Plan: A–B loop points within a track #
Set a start and end inside the playing track and have that region repeat, exactly as
repeat: single repeats a whole track. Navidrome/Subsonic are irrelevant here — this is
entirely a client-side decision about the decoded buffer.
Read first: src/lib/player/store.ts (the header comment is the store's design rules),
src/lib/player/engine.ts, src/components/PlayerBar.tsx (keys + seek row),
src/lib/player/session.ts, src/test/audio.ts. Skill guides:
node_modules/solid-js/skills/reactivity-diagnostics/SKILL.md,
node_modules/@solidjs/diagnostics/skills/agent-loops/SKILL.md.
The one decision that matters #
The loop boundary must be placed on the audio clock, not in the ticker.
startTicker samples live.position() at TICK_MS = 250. A boundary checked there is
late by up to a quarter second and is exactly the main-thread reaction that armFollowOn
was written to eliminate (store.ts:489, with its measured 80 ms). So:
PlayOptionsgainsstopAt?: number— an absolute buffer offset, not a context time, so the caller does not have to knowstartAt.engine.playthen callssource.stop(startAt + (stopAt - from)), andendAtbecomesmin(startAt + duration - from, startAt + stopAt - from).AudioSourceNodeLike.stopalready declares the optionalwhen(engine.ts:65); only the fake needs changing to match (see Tests).- A scheduled stop is not the user's
stop()and not the buffer running out. It fires a third callback,onBoundary, alongside the existingonEnded(engine.ts:250'sstopped || endedguard is the whole reason this must be a distinct event:stop()also firesonended, and the store advances the queue from there). The engine sets an internalboundaryflag when it schedules the stop itself, so the oneonendedthe browser delivers is attributed toonBoundaryand never toonEnded— otherwise arming the loop would arm the queue advance with it. - Reaching the boundary re-arms at
loopStartviaengine.play({buffer, offset: start, stopAt: end, onBoundary}).
Follow-up (not v1): the seam between two passes is a reactive arm, so it carries
START_LOOKAHEAD of silence. The fix is the same trick as the follow-on — arm the next
pass at when before the boundary arrives. Measure it against FakeAudioContext.advance
the way armFollowOn's comment measures 80 ms, and only then decide it is worth the
second source.
Length: the decoded buffer is the only length #
Every loop number is measured against buffer.duration, never against the store's
rounded duration() signal. duration() is Math.rounded and, before the bytes land, is
only what the index claims (store.ts:605, 705) — and the store already says the index
and the bytes disagree often enough to matter (beginPlayback's clamp comment). A boundary
is a place the audio has to return to on the audio thread, so a half-second of index
metadata is not a length, it is a guess. Half a second late is a boundary you can hear.
That means a new reactive surface on the store — the exact length of the bytes now playing, zero when nothing is decoded:
bufferDuration(): number; // reactive — the decoded buffer's exact duration
peekBufferDuration(): number; // imperative twin, for key handlers
Set from buffer.duration in beginPlayback and at the gapless handover in
naturalEnd; zeroed with the rest of the per-track state (playAt, stop, a load that
changes current.id). It is not derived from duration() — the two signals answer
different questions and duration() is also the slider's max, which stays as it is.
Consequences, all of them "refuse rather than guess":
setLoopvalidates and clamps againstpeekBufferDuration()only.- The marks' left/width are percentages of
bufferDuration(). They therefore sit against a marginally different denominator than the thumb (which uses the roundedduration()) — at most half a second out of a whole track, a couple of pixels at the widest, and the alternative is a boundary that is wrong by more than the gap between the two. mdoes nothing while nothing is decoded. A track with an index length but no bytes has a timeline you can look at and no audio to mark — the marks, the chip and the keys all wait for the same condition, because a region set against metadata is a region that will not match the bytes that arrive.
Store shape (src/lib/player/store.ts) #
export interface LoopRegion { start: number; end: number } // seconds into the buffer, start < end
loop(): LoopRegion | null; // reactive
peekLoop(): LoopRegion | null; // the imperative twin — the store's own paths use peek
setLoop(region: LoopRegion | null): boolean; // false = refused, signal untouched
- One signal holding an object, not two: a half-written region (
startupdated,endstill old) is a region that plays backwards for one frame. Compared by value (start/endboth equal → no write), so re-setting the same region does not wake the chip and the marks. - Name the signal (
createSignal(..., { name: "loop" })) — diagnostics attribution reports scopes by name, and the project convention is that anything reactive is named. - Validate at the setter, and say nothing rather than guessing: non-finite,
start < 0, orend <= start + MIN_LOOP(0.25 s — under it there is nothing to hear between two boundaries) are refused withfalse, leaving the signal untouched. Clamping is for the top edge only:end > bufferDuration→bufferDuration, including for a region restored from a previous visit (a transcode can change the exact length under the stored number). Refuse when nothing is decoded rather than clamping against a claim. - Lifetime: per track, keyed by id rather than by the command that moved there.
Cleared when the track changes — another row,
step/next/previous, album skips,stop, a load that changescurrent.id. Not cleared byplayAton the same id:toggle()resumes an idle player throughplayAt(cursor, pendingOffset), so clearing on everyplayAtwould clear a loop restored from the session the first time the user presses play. A region belonging to the previous track's timeline is a wrong number, not a preference; a region belonging to this track is what they set. - Gapless pre-arming must stand down while a loop is on.
armFollowOnarms the next track atnow.endAt; withstopAtin play,now.endAtis the loop boundary and the successor would start on top of the second pass. SoarmFollowOnreturns early whenpeekLoop()is set,setLoopcallsclearFollow()on the way in, andsetLoop(null)callsclearFollow(); armFollowOn();on the way out, the waysetRepeatdoes —startTickernever callsarmFollowOn, so without it the successor sits un-armed for the rest of the track. This is the interaction most likely to produce an audible bug; treat it as the feature's hard part. repeatis untouched and not consulted at the boundary.repeatgoverns what the clock does when a track ends (step(…, true)); a loop that reaches its end and is told to repeat is the user's own instruction, so it loops regardless of mode — the same reasoningnext()uses when "no repeat mode is a licence to ignore" a press.seek(seconds)keeps the region only inside it: a commit betweenstartandend(either edge included) is the user moving the playhead, and the boundary then pulls the clock back tostart, which is what A–B means. A commit outside the two edges is the user leaving the loop — the marks draw the edges and the slider underneath is the only draggable thing on the row, so carrying the thumb past the far mark is the deliberate way of saying on past here — and the region comes off with the move, the successor gets itsarmFollowOnback, and the candidate machine goes with it. Pause/resume re-arms with the samestopAt.- Eviction (
DECODED_CAP) and the resume-after-eviction path (startLoad(id, pendingOffset)) must carry the region through, so a re-decoded track keeps looping. setLoopwrites the session on the way in and out (saveSession(peekPosition())), likeseekcommits on release. Setting a region and reloading before the next ~5 s tick must not lose it — the cadence exists to spare disk writes during a drag, not to make a deliberate press forgettable.
Session (src/lib/player/session.ts) #
Persist it, or a reload quietly unmakes something the user set deliberately. Add optional
loop to writeSession/sessionSchema (valibot, like atOffset: finite, minValue(0),
end > start checked on read), stored with the track it belongs to and dropped on
read-back unless that id is the restored track — the same guard atOffset gets from being
read alongside at. One blob, one write, same cadence (SESSION_TICKS), plus the immediate
write from setLoop. On restore the region is re-clamped against the buffer once the bytes
land (see Length), not against the stored numbers or the index.
UI (src/components/PlayerBar.tsx) #
- Region marks over the seek row (
:494): an absolutely-positionedpointer-events: nonelayer behind theinput[type=range], positioned as a percentage ofbufferDuration()(see Length — not the denominator the slider'smaxuses, and say so in a comment so the difference is a decision rather than an oversight). - Keys, in the existing
onKeyhandler next to the digits andl, so the bar's four abstentions (caret in the query box, a modifier, a focused button, nothing on the bar) are inherited rather than re-implemented:m, matched ase.key === "m"— one key, one gesture, three presses:- A at the current position (pending — no region yet),
- B →
setLoop({start: A, end: B}), looping starts, - clears.
Shift+Mis not bound and is not swallowed: no second gesture is worth reserving a shifted form for (thelcommit's reasoning), and the thirdmalready clears.- Position is read from
peekLivePosition()— the audio clock throughlive.position(), falling back topeekPosition()when nothing is playing — never from the 250 ms sample. A quarter second of staleness in a boundary that has to repeat is the bug this feature is built to avoid. - Refused (nothing decoded, no length, or
end <= A + MIN_LOOP) → the press does nothing and the bar stays in whatever state it was in: a refused B leaves A pending, not reset.
- A visible state, per the
lcommit's rule that a mode nobody can see is an answer nobody can see:- Pending A draws a single hairline at
start, styled like the slider's own caret (same 2px rule, same colour) — it reads as "the line you set", not as a decoration. - An
A–Bchip beside the repeat button once a region exists, click to clear, showing the two seconds as a tooltip. Out of the tab order (tabindex={-1},onMouseDown={noFocus}), as the bar's other controls are. In.pb-buttonsnext to the repeat button.
- Pending A draws a single hairline at
mgoes past the blown-up cover, alongside space, the digits andl, in theArtZoomcapture handler. Looping is decided while the music plays; swallowing the one key the bar still has is what thelpass-through exists to prevent.qualityNoteand the chips row are unaffected — this is not about what the file is.
Tests #
Every test with a reactive surface goes through captureArtifact + expectNoDiagnostics
(the repo's convention), and the position assertions drive FakeAudioContext.advance
rather than timers — the fake clock only moves when a test says so.
src/test/audio.ts— more than recordingwhen.FakeSourceNode.stop()currently firesonendedsynchronously, which would report the boundary at the moment it was scheduled and, since the engine'sstoppedguard only knows about the user'sstop(), read as the buffer running out: the queue would advance the instant the loop was armed. So:stop(when)with a time records it and firesonendedfromadvance()once the clock crosses it; a barestop()keeps firing immediately, because every existing store test depends on that. Natural end-of-buffer stays manual (finish()).engine.test.ts—stopAtschedulessource.stop(startAt + stopAt - from)(assert the argument onFakeSourceNode);onBoundaryfires at the boundary andonEndeddoes not; advancing the clock to just short of the boundary fires neither;remaining()respects the boundary; astopAtpast the buffer end behaves like none.store.test.ts— advance past the boundary and assert: a new source armed atstart, the queue did not advance,cursorunchanged, no follow-on armed (peekArmedNext()is null), and that clearing the loop lets the successor arm again. Region survives pause/resume, a decoded-entry eviction, andplayAton the same id; it is gone after a row change /next.bufferDuration()is the exact buffer length and 0 with nothing decoded. Refusals:end <= start, non-finite,startpast the end, and everything while nothing is decoded — each returningfalsewith the signal untouched.PlayerBar.test.tsx—msets A then B then clears;Shift+Mdoes nothing; the pending A hairline appears before the chip does; the marks' left/width followbufferDuration()and the keys refuse while the stream is held back (stub fetch pending — a length from the index alone must not be enough to mark against); the chip appears only while a region exists;mreaches the transport from behind the blown-up cover; the four abstentions hold form(query caret, Cmd/Ctrl/Alt, focused button, empty bar).session.test.ts— round-trips, and a stored region belonging to another track is dropped; a junkloopfails the schema rather than restoringNaN.- Verify teeth: revert each behaviour and confirm the specific test fails, as with the harvest work.
Order of work #
- Engine
stopAt+onBoundary, and the fake's timed-stoponended(testable alone, no UI). - Store:
bufferDuration, loop signals, validation, per-track-by-id lifetime,armFollowOnstand-down and re-arm on clear. - Session persistence.
- Marks, keys, chip, overlay pass-through.
- Re-measure the loop seam against the fake clock; decide on the ahead-of-time re-arm.
Non-goals #
Cross-track loops, per-album regions, server-side transcoding to a looped clip, drag-to-
select on the timeline (v2 — it needs a second pointer surface on a row that is also the
scroll target), and any change to REPEAT_ORDER — the button cycles the queue's modes and
this is not one of them.
Decisions taken in review #
- Fake: timed
stop(when)firesonendedfromadvance(); barestop()stays immediate; natural end staysfinish(). Engine tags its own scheduled stop so it cannot reachonEnded. - Loop survives
playAton the same track id; clears on a track change. - Pending A lives in the bar, drawn as a caret-like hairline; a refused B leaves A pending; cleared on track change, never persisted.
peekLivePosition()added for marking off the audio clock.setLoop(null)re-arms the follow-on itself.monly — A, B, clear.Shift+Munbound.- Loop math is
buffer.durationonly; out-of-range ends are clamped to it, including on restore. No index metadata anywhere near a boundary. setLoopwrites the session immediately.mpasses through the artwork overlay.setLoopreturnsboolean.