Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions docs-developers/frontend/apple-watch.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ these changes both sides, with tests on both:

| The player | The watch |
|---|---|
| `book-queue.ts` | `Core/Timeline.swift`; whole-book chapter moves in `Core/PlayerRules.swift` |
| `book-queue.ts`, `transport.ts` | `Core/Timeline.swift` (file places); `ChapterNav` in `Core/PlayerRules.swift` (finding and stepping chapters) |
| `listening-sync.ts`, `listening-outbox.ts` | `Core/SpanRecorder.swift`, `Core/Outbox.swift` |
| `progress-sync.ts`, `place-reconcile.ts` | `Core/AckAndOffer.swift` |
| `server-address.ts`, `pairingFallback` | `Core/AddressPicker.swift` |
Expand Down Expand Up @@ -98,6 +98,16 @@ seek bar). Away from 1x, one more line gives the wall-clock time left in the pho

## Playing and syncing

`WatchAudioEngine` passes the playing file to `NowPlayingTimes.of`, which finds
its chapter with `ChapterNav.index`.
When files share a start, `ChapterNav.step` steps Previous and Next in file order,
from the playing file and the seconds into it, as the
[phone's transport](player-ui.md#rings-the-transport-and-titles) does. When no two
files share a start, it uses whole-book seconds. A chapter tap or a step between
tied files gives `WatchAudioEngine.seek` the chapter's file path and in-file start.
`Timeline.resumePlace` resolves those to a queue index and seconds. For a skip
or scrub given only book seconds, it prefers the playing file among tied files.

**Starting to play** (`Playback/WatchAudioEngine.swift`):

- **A refused start.** A start the player refused before its audio moved is often the system
Expand Down Expand Up @@ -158,9 +168,14 @@ npm run test:watch # swift test on watch-core/; skips, and passes, without sw
```

`.github/workflows/watch.yml` runs it on a macOS runner when `targets/watch/**`, `watch-core/**`
or the script change, since the Linux `ci` job has no Swift toolchain. The Swift tests carry the
TS test vectors. They cover the timeline, spans, the outbox, acks and offers, addresses, message
decoding and encoding, the rendition plan, held books, the `remove` decision, `StatePublication`,
or the script change, since the Linux `ci` job has no Swift toolchain.
`TimelineTests`, the phone's Jest tests and Wear's JUnit tests all read
`watch-core/Tests/WatchCoreTests/Fixtures/timeline-ties.json`. Its cases check
which file and chapter a place selects, ties with a zero-length marker, and the
file and seconds reached by Previous and Next.

The other Swift tests carry the TS test vectors too. They cover the rest of the
timeline, spans, the outbox, acks and offers, addresses, message decoding and encoding, the rendition plan, held books, the `remove` decision, `StatePublication`,
the download percent (`DownloadProgress`), a refused start (`StartRefusal`), `AccountRules` and
`JSONFile.load`.

Expand Down
38 changes: 24 additions & 14 deletions docs-developers/frontend/book-page.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,15 @@ Both ways to play go through the app's one play path, `usePlayBook`

- The primary calls it with `{ toggle: true }`. A loaded book pauses or plays in place
on every layout; it never restarts.
- A chapter row, a timeline tap or a step key calls it with `{ at: jump }`. A `Jump` is
a `BookPlace`, `{ position?, track? }`, with a track for a file of unknown length.
- A chapter row calls it with `{ at: jump }`. A `Jump` is a `BookPlace`. For a
chapter it carries the corrected whole-book `position` and, when known,
`file: { path, pos }` with the library-relative path and the chapter's start in
that file. A file row carries `track`. A timeline tap supplies whole-book seconds.
- On a phone it opens the full player there, unless the player is already on top.
The route applies the jump once, also to the loaded book.
- On a tablet or desktop it jumps the loaded book there (`seekBook`, or
`goToTrack`) and plays on, or starts this book there in place
(`startBookInPlace`).
- On a tablet or desktop it jumps the loaded book there or starts it in place
(`startBookInPlace`). Both look the chapter's file up in the queue that plays,
as [the player does](playback.md#building-the-queue-book-queuets).

`usePlayBook` rejects when the book can't start. The error is a `PlaybackStartError`
when the engine couldn't start it (see
Expand Down Expand Up @@ -348,16 +350,24 @@ chapters have the same shape either way.
`useBookAnnotations` (`pinsOf`):

- While the book is loaded, its place follows the player
(`timelinePosition(selectBookPosition)`), and a tap or drag `seekBook`s.
(`timelinePosition(selectBookPosition)`), and a tap or drag calls `seekBook`.
- Otherwise it draws the saved place, and a tap jumps through `usePlayBook`.
- A step key goes to the next chapter start or back to the start of the current one
(`nextSegmentStart`, `previousSegmentStart`, the transport's own rules).

`scrubTarget` keeps a tap from landing in the last 30 s. The current row is
`rowAt(rows, position)`; the page passes it in, and every row counts as heard once the
book is finished. A row is memoised on its few values: its state and the bookmark
glyph. A bookmark inside the book marks the row `rowAt` puts it in. So a moving place
redraws only the rows that change.
- `scrubTarget` keeps both kinds of tap short of the book's end.
- A step key on a loaded book uses the player's `stepSegment`
([the transport](player-ui.md#rings-the-transport-and-titles)). Before the book loads, the keys use whole-book
seconds from the saved place (`nextSegmentStart` and `previousSegmentStart`).

`rowAt(rows, position, file)` matches the playing chapter by file path and in-file
start, so it finds the right row even when a partial queue orders the files
differently. Before playback, it uses the saved file and seconds when available.
With only book seconds it follows the player's tie rule
([Chapter names](playback.md#building-the-queue-book-queuets)).

The timeline uses the current row at the playhead and `rowAt(rows, seconds)` for
other hover positions. It uses a row as the current timeline segment only when
every row has a known start. A bookmark marks the row `rowAt` finds for its book
position. Each row is memoised on its state and bookmark glyph, and all rows
count as heard once the book is finished.

### The Details tab

Expand Down
80 changes: 42 additions & 38 deletions docs-developers/frontend/playback.md
Original file line number Diff line number Diff line change
Expand Up @@ -538,15 +538,18 @@ track is exactly what it always was. A local file is never transcoded.

Other queue math that lives here:

- **`chapterBookOffset`** recomputes every chapter's whole-book offset from the
client's own file durations plus the in-file `start`. It locates the file **by
`file_path` first**, with a bounds-checked `file_index` fallback. It deliberately
ignores the server's `book_offset`, which comes back 0 for every chapter on some
on-demand-indexed books. That made chapter detection resolve to the last chapter.
- **`buildBookQueue`** resolves each chapter's file by `file_path`, falling back
to a valid `file_index`. It records the resolved path and index and adds the
file's offset to the chapter's in-file start. The screens use the same sum
(`chapterBookOffset`). Neither reads the server's `book_offset`, which comes
back as 0 for every chapter on some books indexed on demand.
- **`buildChapterClips(specs, chapters)`** produces the native clip list. Android
plays the clips as items; iOS uses them for its chapter lock screen.
- Each chapter becomes one clip mapped to `(fileIndex, [startInFile,
endInFile])`.
- The clips run in file order. A stable sort by file keeps tied markers that
arrive out of file order in the right place, and keeps the chapter order
within each file.
- The last chapter in each file clips "to end" (`endInFile = 0`), so an
inaccurate final `end` can't cut off the file's tail.
- It returns `[]` for **0 or 1 chapters**, and the engine then plays one item per
Expand All @@ -565,36 +568,35 @@ Other queue math that lives here:
- **`locate(offsets, bookPosition, prefer?)`** and **`toBookPosition(offsets, index,
positionInTrack)`** convert between the whole-book timeline and per-track
coordinates.
- **`chapterAt(chapters, bookPosition, playing?)`** finds the active chapter by
`book_offset`.
- **Files that share an offset.** A file of unknown length (a server with no
prober, or a VBR MP3 with no header, reports 0) gives the next file the same
offset. `locate` resolves such a tie to the **first** of the tied files, since the
length is unknown rather than zero, so a book starts in its first file. A caller
that knows the file the place is in (the playing one, a chapter's) passes it as
`prefer`, and among the tied files that one wins. `chapterAt` does the same for
chapters that share a start in different files: the first file's wins, unless
`playing` names another tied file, so the player names the chapter of the file
it is in. Within one file, a tie is a chapter of no length before another, and the
later one is the chapter playing. The companion's chapter list seeks to a chapter
in its own file (`seekBook(offset, trackIndexById(...))`).
- **Files that share an offset.** A file of unknown length contributes zero seconds
to the next file's offset. Given only whole-book seconds, `locate` picks the
first file at the latest offset reached. For a skip, scrub or seek, `seekBook`
passes the playing file as `prefer`. For a book with file offsets of 0, 60 and
60 s, a skip back to 65 s stays in file three while file three plays. A skip back to
55 s lands in file one.
- **Chapter names.** `chapterAt(chapters, bookPosition, playing?)` looks for the
latest chapter start reached in the playing file. If none qualifies, it checks
all files. At equal starts, `tiedMarkerWins` prefers the first file
in play order. Within one file, a chapter with length takes precedence over a
zero-length marker. Otherwise the first in chapter list order wins. A lone
zero-length marker still names its chapter.
- **Chapter taps and saved places.** A chapter tap carries the file's path and the
seconds into it, as can a saved place. `filePlaceIn` looks up the path in the
queue that will play, which can have a different file order after a partial
download. If the named file is missing, `locateBookPlace` uses the whole-book
position. The companion's chapter list calls
`seekBook(c.book_offset, { path: c.file_path, pos: c.start })`.
- **A file's length** as the player reads it is `fileDurationOf(queue, index,
engine)`: the engine's, unless the server measured the file and the engine's is
unknown or more than `FINISHED_TOLERANCE` (5 s) shorter, then the server's. The
snapshot's `duration`, the seek clamp and the time left in the file use it.
`shortOfFileEnd` and `endsShortOfBook` feed the engine fault check
([An engine that runs off a short file](#an-engine-that-runs-off-a-short-file)).
- **`chapterCountdowns`** feeds the sleep sheet's "Or stop after" rows, with
wall-clock times scaled by the playback rate (`rate.ts` `wallClockSeconds`).
**`nextChapterEnd`** answers the sleep timer's question "where does the next
worthwhile chapter end?". Both use the same `chapterEndPosition`, so the list the
listener picks from and the boundary a shake retargets cannot disagree.

Neither assumes the chapters ascend by position. `chapterBookOffset`'s fallback
for an out-of-range `file_index` degrades to 0 preceding files, so stale or
duplicated metadata yields ends that are not monotonic. `chapterCountdowns`
therefore locates the current chapter with `chapterAt`, and `nextChapterEnd` takes
the **nearest** qualifying end rather than the first qualifying array element.
- **`chapterCountdowns`** starts the sleep sheet's list at the chapter found by
`chapterAt` for the playing file. It scales the time until each end by the
playback rate. The End of chapter tile and a shake use `nextChapterEnd`, which
scans for the nearest qualifying end in whole-book seconds. Both functions
calculate chapter ends with `chapterEndPosition`.

`total` is the largest of the book's reported duration, the summed file durations
and the furthest chapter end. Metadata with `duration: 0` then degrades instead of
Expand All @@ -607,8 +609,8 @@ per-track, and the selectors map it to the whole-book timeline:

- `selectBookPosition` is `toBookPosition(queue.offsets, snapshot.trackIndex,
snapshot.position)`.
- `selectCurrentChapter` overlays `queue.chapters` on that position by
`book_offset`. The full player's seek bar is **chapter-relative**.
- `selectCurrentChapter` passes that position and the playing file's path to
`chapterAt`. The full player's seek bar is **chapter-relative**.

The actions are `playBook`, `toggle`, `pause`, `retry`, `seekBook`, `seekInTrack`,
`goToTrack`, `skipSeconds`, `setRate` and `stop`. `seekInTrack` and `goToTrack`
Expand Down Expand Up @@ -819,19 +821,21 @@ It keeps the newest record by `updated_at`. Unlike the replay queue, it is **nev
pruned on sync**. It exists so a flaky resume fetch can't lose the position, after
a beta report of a book that "restarted from the beginning".

**On the way out: the `resumeFloor` save guard (`store.ts`).** The store keeps the
whole-book position it actually resumed from as a running high-water mark.
**On the way out: the `resumeFloor` save guard (`store.ts`).** The floor starts at
the resume position and advances as the player saves progress. The store keeps
both the whole-book seconds and the track that set the floor.
`persist` refuses to save a position more than `SLIP_TOLERANCE` (60 s) *below* that
floor.

- Only a deliberate seek or jump by the listener lowers the floor: `lowerFloorTo`
in `seekBook`, `seekInTrack` and `goToTrack`, and a native `onRemoteMove`, which
is the listener's own move made outside the app.
- A deliberate seek or jump can lower the floor through `lowerFloorTo`, including
a native `onRemoteMove`. A natural advance to a later file at the same offset
can also lower it. The next file can report fewer whole-book seconds even though
the listener has moved forward.
- The server is last-write-wins. Without the guard, a restart at 0 that slipped
through with a fresh timestamp would overwrite real progress for good. The guard
makes that write impossible.
- `retry()` also reloads at `max(resumeFloor, currentPosition)`, so a transient 0
in the snapshot can't be loaded again.
- When Retry needs the floor, `reloadPlace` uses the file that set it. This keeps
a low engine reading from restarting a different file at the same book second.

### An engine that runs off a short file

Expand Down
36 changes: 27 additions & 9 deletions docs-developers/frontend/player-ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,17 +274,17 @@ have carried the listener in the wall-clock time between them.
- a move forward beyond that by more than the threshold, or backward by more than
the threshold, is a jump.

One rule covers every source, which is why the store isn't touched. A recording site
in `seekBook` would miss every jump the engine makes on the OS's behalf.

What must **not** read as a jump, and why it doesn't:

- **Loading or resuming a book**, and a book change: the baseline drops when
`selectBookKey` changes, and the snapshot current at that moment (the old engine
state) is skipped. For a short settle window after the first fresh sample, the
samples only move the baseline.
- **Retry, reloads and buffering**: only `playing` and `paused` are sampled.
- **The downloads hot-swap**: same book, same position.
- **A download swap or Retry** that changes the file order or the offsets drops
the previous sample and clears any undo chip (`startJumpUndo`), since old
whole-book seconds no longer line up. A queue with the same files, order and
offsets keeps the chip.
- **The app coming back after iOS suspended JS**: a heartbeat runs only while the
app is not active and a book is loaded. A stalled heartbeat marks the return
`unobserved`. Forward movement up to the allowance is then accepted even from a
Expand Down Expand Up @@ -587,9 +587,12 @@ content with its own scroller. Children mount only while the sheet is open.
- **Speed** is `speed-model.ts`: the grid, the presets, stepping and the sheet's own
range (`SPEED_MIN`/`SPEED_MAX`). The range is the same 0.5-2 that `clampRate` in
`rate.ts` enforces in the store.
- **Sleep** is `sleep-sheet-model.ts`: the presets, the "Or stop after" rows and the
notice. The End of chapter tile's target comes from `chapterTimerTarget`
(`src/playback/sleep-timer.ts`), the rule the timer itself arms.
- **Sleep** is `sleep-sheet-model.ts`: the presets (`SLEEP_MINUTES`), the notice
(`sleepNotice`) and the "Or stop after" rows (`stopAfterRows`). The playing file
identifies the current chapter when starts tie. If that chapter
has no known length, the sheet hides the whole list, since a later chapter's end
could still fall inside the playing file. The End of chapter tile gets its own
target from `chapterTimerTarget` in `src/playback/sleep-timer.ts`.

Picking a timer records a touch (`noteInteraction`) and closes the sheet. The sleep
readouts (`useSleepPill`, `useSleepCountdown`) read the phase, the countdown and the
Expand Down Expand Up @@ -645,6 +648,11 @@ The whole-book timeline is `book-timeline.tsx` with the pure
- **Runs.** Chapters are merged into runs like the Now card's `scaleRuns`. Each run
is placed by time with `runBox`, the one mapping that the playhead, taps and pins
use.
- **Chapter names.** At the playhead, `BookTimeline` uses the current chapter or
row supplied by its caller for the hover tip and slider value text. Elsewhere it
calls `chapterAtSecond`. The player uses `chapterAt` and keeps the playing
chapter's name when the hovered chapter shares its start. The book page uses
`rowAt`. Both follow the [tie rule](playback.md#building-the-queue-book-queuets).
- **Pins.** Bookmark and note pins come from `usePlayingPins`, the playing book's
case of `useBookAnnotations`. That hook reads ANY book's bookmarks and notes, and
their `pins`, through its own connection. It never throws when the connection is
Expand All @@ -659,14 +667,24 @@ The whole-book timeline is `book-timeline.tsx` with the pure
The book page draws the same `BookTimeline` for any book
([The book page](book-page.md#the-chapters-tab)).

Home's Now card uses `tiedChapterIndexAt` for both the chapter label and the
highlight on its scale. It uses the playing file and seconds into it for a live
place, or the saved file and seconds when showing saved progress.

### Rings, the transport and titles

- **Rings** (`src/components/ui/progress-ring.tsx`): `ProgressRing` (a fraction the
caller ticks) and `CountdownRing` (empties by itself, on the UI thread). Both are
transform-only.
- **The transport cluster** (`transport-controls.tsx`) comes in three sizes.
Previous and next read the live position at press time through `stepSegment`
(`transport.ts`), which steps by chapters, else by files.
Previous and Next read the live file and position through `stepSegment` in
`transport.ts`. When files share a start, `stepInFileOrder` orders chapters by
file and then by seconds into that file. It seeks by file path and in-file
start, so Next reaches the next file's chapter even at the same book time.
Previous restarts the chapter, or goes to the one before within its first three
seconds.
With distinct file starts the controls use whole-book seconds. They step by
file if the queue has no chapters or no usable book duration.
- **`prettify-title.ts` cleans filename-shaped labels for display.** Audiobook
"chapter" labels are often just the audio *filename* (`01_the_hobbit_ch1.mp3`).
`prettifyChapterTitle` strips a recognised extension, turns underscores into
Expand Down
4 changes: 3 additions & 1 deletion docs-developers/frontend/sleep-timer.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ The sleep sheet arms and reads the store in two places:
list real chapters only, never the synthetic `virtualChapterInterval` ones. They
arm through `startUntilPosition(endPosition, stopAfterLabel(row))`. The first row
("This chapter") uses the chapter's own label (`chapterSleepLabel`), and the
others use `afterChapters`.
others use `afterChapters`. The playing file picks the first row among chapters
that share a start, and the list is empty when that chapter has no length
([Speed and sleep sheets](player-ui.md#speed-and-sleep-sheets)).
- The "End of chapter" tile shows the countdown of `chapterTimerTarget`. The store
exports it so the tile and the timer it starts compute one target.

Expand Down
Loading