Community chapters
The community metadata database holds a chapter list for most recordings. Each list gives every chapter's title, start and length, timed on that recording's audio. The server checks each book that has an ASIN or ISBN against the chapter list of its exact matched recording. When the list fits the book's own audio, the server can use it in place of the scan's chapters. It never touches the files on disk.
Three pieces each have one job:
| Piece | Job |
|---|---|
internal/chapteralign | The fit. Pure, with no I/O. Files, the scan's chapters, the community list and a pause Prober go in, and a Result (status, Detail, fitted chapters) comes out. testdata/mythos is a real golden case. |
internal/chaptercheck | The Runner, which runs a background pass and on-demand checks. It fetches the list (meta.Service.RecordingChapters), finds pauses with ffmpeg (media.DetectSilences), fits, and records the outcome (catalog.SaveCommunityChapters). |
catalog/communitychapters.go | The stored check (community_chapters), which books are due, and applyChapterSource, which decides which chapters a book has. |
chaptercheck runs apart from the scan job queue, as bulk matching does,
because it waits on the network and library must not import meta.
Where the chapter list comes from
For a book with an identifier, a recorded match takes precedence. MatchChapters asks for the
selected recording. If it names no usable recording, the lookup’s recording is eligible only on
the same work. If the recorded work itself no longer exists, the lookup can supply the work too. A
book without an ASIN or ISBN is never due for this check.
meta.Service.RecordingChapters(asin, isbn) looks the identifier up (an ASIN,
else an ISBN). It then fetches the chapters of the recording the lookup
names (recording_id), through metaserve's
GET /api/v1/works/{id}/recordings/{rid}/chapters.
The chapter check never substitutes the first recording of a work. A work's chapters belong to one recording, and another recording
may be a different edition altogether. internal/meta caches nothing, because
the community_chapters row is the cache.
| Lookup | Recorded status |
|---|---|
| no match, or a match that names no recording | no_match |
the recording has fewer than two chapters, or the metaserve predates the route (404) | unavailable |
| two or more chapters | the fit's status (see Classifying) |
A service error records nothing, so the book stays due.
When a book is checked
The launcher calls API.StartChapterChecks, which starts Runner.Run for the
server's lifetime. Nothing runs without a metadata service. Every 10
minutes, and at once on a Kick, a pass lists the books due a check
(catalog.DueChapterChecks). A book is due when:
- it has an ASIN or ISBN and a known duration, and
- it has no check yet, or its check's
basisdiffers, or the check is older than 30 days.
The basis
basis is what the check depended on (chapterBasisExpr):
- the identifiers and, when present, the recorded work and recording;
- the duration in ms;
- a hash of the scan's own chapters (
books.chapters_hash); - the book's files in play order, relative to the book (
''for a single-file book).
These make the book due and its check stale: a new match, other audio,
re-tagged chapters, or a file renamed in place. A move does not, because it is
the same audio, and the fit stores its files relative to the book too, so its
chapters follow the book. A re-index of an unchanged book does not either,
which an indexed_at in the basis would.
The pass
- Due books come oldest check first, 50 at a time, with two checked at once
(
internal/pool'sEach, shared with bulk matching). - In mirror mode the first
pass after a start (the first with metadata on, since no copy loads while it
is off) waits for the local copy, at most 10 minutes (
mirrorReady), so a start sends no lookups to the service while the copy loads. - A check gets 5 minutes. Pause searches stop 4 minutes in, counted from the check's start (the community list's fetch included), which leaves time to save the fit on any book. Boundaries not snapped by then keep their placed positions (approximate where their stretch drifts, as below), and the fit is still recorded.
- A book whose check failed records nothing and waits an hour before it is tried again, so failing books can't fill the batch and starve the rest.
- Five failures in a row, or metadata being switched off, end the pass. After such a pass the runner ignores kicks until the next tick.
- A background recheck that finds the same list (
list_hash) for the same audio only renewschecked_at. It looks for no pause again and rewrites nothing. - A check an admin asks for always fits again. For example, a first fit made without ffmpeg then gets its pauses.
Kicks
A Kick follows every committed book change. The API registers it with
Catalog.OnBookChange. These fire it after their transaction:
UpsertBooksandUpsertBook(a scan);EditBookandEditBooks(an edit, an accepted match, or a bulk match run applying);BackfillASIN;- clearing community matches;
- setting or removing a custom cover.
They fire to every listener, so the cover colour pass hears them too. A kick waits 5 s for the kicks behind it, because a scan kicks once per book. A burst is therefore one pass, and the pass only checks what is due.
On-demand checks
POST /admin/libraries/{id}/book/community-chapters is the on-demand check.
Runner.Start checks one book in the background under the server's context and
returns at once. Runner.Checking reports the check from that moment, and that
is the admin book page's community_checking. A book already being checked is
not checked twice: the background pass gets ErrBusy, and Start does
nothing.
Where the identifier comes from
The scanner sets no ASIN from tags. It reads them as match hints only. A book gets its identifier from one of these, and is checked from then on:
- an admin edit;
- an accepted match;
- a bulk match;
- an Audiobookshelf
metadata.json; - an enrichment write.
The fit (chapteralign.Align)
The book's audio can differ from the recording the community timed. An intro or outro may be trimmed, a publisher's preview may be missing at the end, releases may drift a little, or the book may be split into files. So the fit is anchored and piecewise rather than one global shift:
- boundaries both lists agree on are pinned;
- the community boundaries between two pins are placed in proportion;
- each placed boundary is then snapped to the pause it sits in.
The inputs are:
- the book's files in play order (path and duration; one for a single-file book);
- the scan's own chapters (
books.scanned_chapters), so a recheck never fits against community chapters standing in; - the community list, sorted by start, with duplicates of a start dropped;
- an optional
Prober.
The steps:
- Boundaries. Every file start and every chapter start on the whole-book timeline. A file holding two or more chapters has chapters of its own. A file holding one is "one per file", which counts as no chapters.
- Title anchors (
anchorTitles). The book's start is pinned to the community start. In order, each titled boundary pairs with the community boundary withinmax(120 s, 1% of its position)whose title is most similar (the nearest of equals). Similarity (titleSim) is the overlap of the two titles' word sets over the smaller set, and must be at least 0.6.- Leading numbering is stripped (
1.,Chapter 3:,Part 2 -). - Stop words (
the,a,of, ...) are left out unless a title is nothing else. - A word of five letters or more that is one edit away counts as the same word, to allow a typo ("Persophone").
- A title that is only numbering ("Chapter 12") pairs on the number with a bare number or with one that adds a name ("12", "Chapter 12: The Storm"). It never pairs across kinds: "Part 2" is not "Chapter 2".
- Leading numbering is stripped (
- Time anchors (
anchorTimes). Each boundary still unpinned, such as a file boundary or an untitled or renamed chapter, is pinned to a community boundary within 5 s of its time plus the offset of the nearest anchors around it. The search covers only the stretch between those anchors. With no anchor nearby, the offset is the median offset from each boundary to its nearest community boundary within 30 s. - The end (
anchorEnd). The end of the audio pins to the community end when it is withinmax(30 s, 0.15%)of where the last anchor's offset puts it. Otherwise it pins to a community boundary that close, provided what follows that boundary is at mostmin(20 min, 10% of the recording). What follows is not in this copy (a preview, credits), and each such chapter of a minute or more is listed indetail.omitted. If neither applies, the status islength_mismatch. - Stretches (
checkStretches). Each stretch between anchors of at least 120 s on either timeline is measured as local length over community length. The status islength_mismatch(another edition) when any stretch is off by more than 10%, or when the length-weighted median of the stretches 120 s long in the book is off by more than 1%.detail.ratioanddetail.worstreport them. - Coverage (
checkCoverage). Two rules:- Every file boundary must be anchored. Otherwise a community chapter
straddles it, and the status is
crosses_files, withdetail.straddlenaming the chapter, where the boundary falls and the files either side. - At least 80% of the book's own chapters must be anchored, ignoring any
within 30 s of either end (a recording's own intro or credits). Otherwise
the status is
structure_mismatch.
- Every file boundary must be anchored. Otherwise a community chapter
straddles it, and the status is
- Placing (
place). An anchored community boundary takes its anchor's time exactly. Every other one is interpolated linearly between the anchors around it. - Snapping (
snap). Each unpinned boundary gets a search window of4 s + drifteither side, at most 30 s, inside its own file. Drift is how much the stretch's two lengths differ. TheProbergets all of one file's windows at once.media.DetectSilencesruns one ffmpeg per file: the concat demuxer reads each window as an excerpt, andsilencedetectfinds pauses at -40 dB withd=0.4. ffmpeg 5.x and 6.x print six significant digits, so past 10,000 s of excerpts in one file the times are good to 0.1 s.- An ffmpeg older than 5.0, or one built without the concat demuxer, runs once a window instead (30 s each), and the server remembers that for that ffmpeg. A window that fails there leaves the others' answers.
- In playback order, each window's pauses are clipped to stay 0.25 s clear of the neighbouring boundaries, the preceding one where it moved to.
- The boundary moves onto the longest pause of at least 0.4 s, to 0.3 s before the speech resumes, but never before the pause starts.
- A boundary that can't be snapped while its stretch drifts more than 2 s
counts in
detail.approximate. - Without ffmpeg, unpinned boundaries keep their proportional positions.
- Emitting (
emit). The chapters cover the audio with no gap, in the scanner'smetadata.Chaptershape (file_path, in-filestartandend,book_offset).- A chapter under 0.25 s is dropped.
- The first chapter of each file starts at the file's start.
- No chapter runs past its file.
- Classifying (
classify):
| Status | When |
|---|---|
fill | the book has no chapters of its own (none, or one per file) |
same | the book's chapter starts are exactly the fitted ones, and the titles are equal (lowercased, punctuation ignored, numbering kept) |
titles | as same, but some titles differ: detail.title_diffs (index, current, community) |
refine | every chapter of the book (bar the edges) is anchored, and the community has more |
restructure | the community chapters fit, but divide the audio differently |
length_mismatch · structure_mismatch · crosses_files | the reasons a fit fails (no chapters) |
The golden case, testdata/mythos, is Stephen Fry's Mythos as one m4b. It
fits ffprobe's 34 broad chapters against the community recording's 174, with
32 anchors, 140 boundaries snapped and none approximate. The result is 173
chapters with "Preview: Chapter 1 from Odyssey" omitted, a refine.
Storing the check and choosing the chapters
community_chapters (migration 0035) holds each book's last check:
- PK
(library_id, path); basis;status: a fit status,no_matchorunavailable;work_id,recording_id;list_hash, which names the community list;detail: thechapteralign.DetailJSON;chapters: the fitted chapters JSON,[]unless fitted;checked_at.
It is a record of the index, rebuilt by checking again. Like book_enrichment
it is path-keyed with no FK to books, so an index rebuild keeps it, and
moveBookState moves it with the book. See
Data model.
Three books columns from the same migration go with the chapters rows:
chapters_source:''for the scan's own,'community','generated'(see Generated chapters) or'edited'(see Edited chapters).chapters_fit: a hash of the fit in the rows, so an unchanged fit is not written again.scanned_chapters: always the scan's own chapters as JSON, with their scanned titles, written by everyUpsertBook, asbooks.scannedkeeps the scanned metadata. It is''on a row from before 0035, whose rows are the scan's.
The admin's choice is a row of chapter_choices (same migration):
(library_id, path), source (files or community), updated_by and
updated_at. auto in an edit deletes the row. It is durable, path-keyed admin
state like book_overrides, but kept apart from it. It picks chapters, not a
metadata value, so it is no part of edited or edited_fields.
moveBookState moves it with the book's other edits. A disc join does not copy
it, because the joined book is other audio.
The rule
refreshBook runs on every scan upsert, edit, enrichment write and recorded
check (refreshEffective outside a scan). It calls applyChapterSource, the
one statement of the rule. A book gets:
- an admin's edited list, while it applies to the book's files (see Edited chapters);
- otherwise the community's chapters when the check fitted, its
basisis the book's current one, and either the admin chose them or there is no choice and the status isfill; - otherwise the generated ones a Bridge found in the narration, when they apply (see Generated chapters);
- otherwise the scan's own (from
scanned_chapters).
A check whose basis is not the book's current one is stale and never
applied. After a rescan that changed the audio, or a removed match, the book
stays on the scan's chapters until it is checked again, never on chapters
fitted to files that may be gone. The admin book page marks such a check
stale: true.
SaveCommunityChapters records a check and applies the rule in the same
transaction. A scan (UpsertBook, or a length-only update) records the scan's
chapters in scanned_chapters and writes chapter rows only for the source the
rule picks, in the same transaction, so a rescan never shows the scan's chapters
for a moment. A fit that still applies unchanged keeps its rows and their ids;
only titles that changed are written.
Chapter renames (chapter_overrides, keyed by file and start) apply after the
source, except over an edited list. Renaming a community chapter therefore works
like any rename, and switching back restores the files' chapters with their own
renames.
Generated chapters
A book with no chapter markers can get a chapters.json in its .audiosilo/
folder: the chapters a Bridge found in the narration.
The scan stores the checked list in book_attachments.chapters (migration
0051). The format and its checks are in
the .audiosilo folder. The code is
catalog/generatedchapters.go.
Generated chapters are a source between the community's and the files'.
applyChapterSource uses them (applyGenerated) only when all of these hold:
- No source was chosen.
chapter_choiceshas no row for the book. An admin'sfilesorcommunitykeeps the list out. - The community's chapters don't apply. There is no current fitted check
that is chosen or a
fill. - The list's files are the book's (
chaptersOnFiles). There are as many, each with the same path relative to the book's folder (for a single-file book, its file name), and the same size.- In the same order, the chapters are used as listed.
- In another order, they move with their files (
movedChapters). This covers a list the Bridge found while the book played its files in byte order, before 2.4.0's natural order. Each chapter starts at the same place in the same file, by the listed lengths, and runs to the next start in the new order.
chapteralign.Alignanswersfill, run with noProber. There is no snapping, because the list is already timed on this audio.fillis the fit's word for "the book has no chapters of its own" (no file holding two). Any other status leaves the scan's own chapters, so a book tagged with chapters since never shows the list.
When the list applies:
- the rows are the fit;
books.chapters_sourceis'generated'(ChaptersFromGenerated);chapters_fitis a hash of what the list was fitted from (listFitKey): the stored list, the scan's own chapters, and the files' book-relative paths, sizes and lengths. A refresh of an unchanged book therefore neither decodes nor fits the list again.
When the list stops applying (the file is gone, the audio changed, a community
fill, or a files choice), the scan's own chapters come back.
useChapters is the one write of a stand-in list for every source. On a row
from before the snapshot, it records the rows as the snapshot. Then, only when
the book's community check was made of the book as it is now, it re-stamps that
check's basis, so the check stays current.
An admin never chooses generated. PATCH .../book {chapter_source} still
takes files, community or auto. A files choice turns found chapters off,
and auto brings them back. Recording a changed chapters.json re-resolves
the book at once, whether the Bridge's attachments rescan or a scan's backfill
recorded it. The players get the chapters without a re-index.
Edited chapters
An admin can replace a book's chapters with a list of their own, made in the
console's chapter editor (see
Built-in web UI). The code is
catalog/chapteredits.go.
The edit is a row of chapter_edits (migration 0078): PK (library_id, path), list, updated_by (ON DELETE SET NULL) and updated_at. list is a
metadata.ChapterList, the shape of a Bridge's chapters.json, with generator
console. Its chapters are on the whole-book timeline in milliseconds, and its
files are the files the edit was made on, each with its book-relative path,
size and duration_ms. It is durable admin state like chapter_choices:
path-keyed with no FK to books, moved with the book by MoveDurableState,
never copied onto a joined book (other audio), and deleted with its library.
Precedence and dormancy
An edit is the first source (the rule): applyChapterSource
reads it before the choice. applyEdited uses the list while its files are the
book's:
listedOrdermatches them aschaptersOnFilesdoes for achapters.json: as many files, each with the same book-relative path and size. In another play order the chapters move with their files (chaptersInOrder).- A loose single-file book (one audio file in the library, not a folder:
!IsFolder) is compared by its file's size alone. Renamed, the file is the book moved, so the edit has already moved with it. A folder holding one file is matched by path like any folder book: renaming that file leaves the edit dormant until the name comes back. placeOnFiles(pure) puts each chapter in the file its start falls in, at the same place in that file by the lengths the list was made on (duration_msof its basis). Each runs to the next start or the file's end. Itsbook_offsetcomes from the files' lengths now. Another probe that reads a file a little longer or shorter therefore moves no chapter within its audio. A chapter that would start at or past its file's end now leaves the edit dormant.- A start within 50 ms of a file's start (
fileStartSnapMS) is that file's first chapter, each file taking the nearest start no file before it took (snapToFiles, so a file under 100 ms never takes its neighbour's, and a file of no length shares the next file's, as in the console's editor). File starts are the sums of the files' lengths in whole milliseconds (fileStartsMS), as the console sums the basis.
While it applies, the rows are the placed list, books.chapters_source is
'edited' (ChaptersFromEdited) and chapters_fit is listFitKey(list, "", files), so an unchanged book neither decodes nor places the list again.
On other files the edit is dormant. The book gets the next source's
chapters, never the edit applied to other audio. When the files come back, the
edit applies again. The admin book page says which with chapter_edit.state.
No chapter crosses a file. Every file starts a chapter, whose start is fixed and whose title the admin can change.
Renames, choices and Health
- While an edit applies, the renames in
chapter_overridesare dormant: the titles are the edit's.refreshEffectiveskips them, the book page marks no chapteredited, and aPATCH .../bookwithchaptersis400 invalid_overridewithfield: "chapters". Revert brings the renames back. - A
chapter_sourcechoice made while an edit exists is kept. It decides the chapters while the edit is dormant, and after a Revert. - Health's
detailed_chaptersis settled while an edit exists, applied or dormant. An applied edit marks the admin rowedited. - The console offers no Detect chapters for a row whose
chapters_sourceisedited(rowFix), the Community panel offers no source to switch to, and the server refuses such achapters.detectjob (409 chapters_edited,bridge.ErrChaptersEdited, checked from the book'schapters_source; a dormant edit refuses nothing), and Health's Detect dialog passes the book over.
Saving and reverting
PUT .../book/chapters
calls SaveChapterEdit. One transaction checks the request's basis against the
book's files now (basisOf: path, size and duration_ms, in play order), checks
the chapters (checkChapterEdit), writes the row and runs refreshEffective. A
refused list is a 400 chapters_invalid whose detail names the first rule it
breaks (the rules).
The limits are metadata.MaxChapterListEntries (2000 chapters),
metadata.ListChapterTitle (the chapters.json title rule), minChapterGapMS
(1 s between starts) and fileStartSnapMS (a file's start within 50 ms).
The console's chapters-edit-model.ts mirrors these rules, so they change
together. DELETE calls RevertChapterEdit, which deletes the row and runs
refreshEffective, so the next source applies.
On the wire
Every change is additive. An old client reads community chapters as ordinary chapters.
GET /libraries/{id}/chaptersand the book JSON ofGET /libraries/{id}/itemcarrychapters_source. It is"community"for community chapters,"generated"for chapters found in the narration,"edited"for an admin's edited list, and absent otherwise. An old app shows any of them as ordinary chapters with no label. See/chapters.- The admin book page gains:
chapter_source, which can begeneratedoreditedtoo;chapter_choice;community_chapters: the check's status and detail, not the fitted list;community_checking;generated_chapters_fit: a storedchapters.jsonfits the files as they are now, so it stands in with no choice when the community's chapters don't apply;chapter_edit(the edit's state, author and time) andchapter_basis(the files aPUTof an edit sends back).
PUTandDELETE .../book/chapterssave and revert an edit.PATCH .../bookandPOST /admin/books/bulktakechapter_source. The check isPOST .../book/community-chapters.GET /admin/booksrows carrychapters_source,chapters_checkandchapter_choice(omitted when automatic).- Health gains the
detailed_chapterskind: arefinecheck with no choice made and no edited list (see Issues).
The player shows a caption under community chapters, another ("Chapters found in the narration on this server") under generated ones, and a third ("Chapters edited on this server") under edited ones. It refreshes a downloaded book's saved chapters when they change. See The book page and Offline. The console's panel is described under Built-in web UI.