hackermusic PLAN-loop-points.md
16 kB · 239 lines
Markdown
at main

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:

  • PlayOptions gains stopAt?: number — an absolute buffer offset, not a context time, so the caller does not have to know startAt. engine.play then calls source.stop(startAt + (stopAt - from)), and endAt becomes min(startAt + duration - from, startAt + stopAt - from). AudioSourceNodeLike.stop already declares the optional when (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 existing onEnded (engine.ts:250's stopped || ended guard is the whole reason this must be a distinct event: stop() also fires onended, and the store advances the queue from there). The engine sets an internal boundary flag when it schedules the stop itself, so the one onended the browser delivers is attributed to onBoundary and never to onEnded — otherwise arming the loop would arm the queue advance with it.
  • Reaching the boundary re-arms at loopStart via engine.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":

  • setLoop validates and clamps against peekBufferDuration() only.
  • The marks' left/width are percentages of bufferDuration(). They therefore sit against a marginally different denominator than the thumb (which uses the rounded duration()) — 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.
  • m does 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 (start updated, end still old) is a region that plays backwards for one frame. Compared by value (start/end both 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, or end <= start + MIN_LOOP (0.25 s — under it there is nothing to hear between two boundaries) are refused with false, 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 changes current.id. Not cleared by playAt on the same id: toggle() resumes an idle player through playAt(cursor, pendingOffset), so clearing on every playAt would 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. armFollowOn arms the next track at now.endAt; with stopAt in play, now.endAt is the loop boundary and the successor would start on top of the second pass. So armFollowOn returns early when peekLoop() is set, setLoop calls clearFollow() on the way in, and setLoop(null) calls clearFollow(); armFollowOn(); on the way out, the way setRepeat does — startTicker never calls armFollowOn, 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.
  • repeat is untouched and not consulted at the boundary. repeat governs 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 reasoning next() uses when "no repeat mode is a licence to ignore" a press.
  • seek(seconds) keeps the region only inside it: a commit between start and end (either edge included) is the user moving the playhead, and the boundary then pulls the clock back to start, 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 its armFollowOn back, and the candidate machine goes with it. Pause/resume re-arms with the same stopAt.
  • Eviction (DECODED_CAP) and the resume-after-eviction path (startLoad(id, pendingOffset)) must carry the region through, so a re-decoded track keeps looping.
  • setLoop writes the session on the way in and out (saveSession(peekPosition())), like seek commits 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-positioned pointer-events: none layer behind the input[type=range], positioned as a percentage of bufferDuration() (see Length — not the denominator the slider's max uses, and say so in a comment so the difference is a decision rather than an oversight).
  • Keys, in the existing onKey handler next to the digits and l, 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 as e.key === "m" — one key, one gesture, three presses:
      1. A at the current position (pending — no region yet),
      2. B → setLoop({start: A, end: B}), looping starts,
      3. clears.
    • Shift+M is not bound and is not swallowed: no second gesture is worth reserving a shifted form for (the l commit's reasoning), and the third m already clears.
    • Position is read from peekLivePosition() — the audio clock through live.position(), falling back to peekPosition() 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 l commit'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–B chip 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-buttons next to the repeat button.
  • m goes past the blown-up cover, alongside space, the digits and l, in the ArtZoom capture handler. Looping is decided while the music plays; swallowing the one key the bar still has is what the l pass-through exists to prevent.
  • qualityNote and 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 recording when. FakeSourceNode.stop() currently fires onended synchronously, which would report the boundary at the moment it was scheduled and, since the engine's stopped guard only knows about the user's stop(), 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 fires onended from advance() once the clock crosses it; a bare stop() keeps firing immediately, because every existing store test depends on that. Natural end-of-buffer stays manual (finish()).
  • engine.test.ts — stopAt schedules source.stop(startAt + stopAt - from) (assert the argument on FakeSourceNode); onBoundary fires at the boundary and onEnded does not; advancing the clock to just short of the boundary fires neither; remaining() respects the boundary; a stopAt past the buffer end behaves like none.
  • store.test.ts — advance past the boundary and assert: a new source armed at start, the queue did not advance, cursor unchanged, 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, and playAt on 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, start past the end, and everything while nothing is decoded — each returning false with the signal untouched.
  • PlayerBar.test.tsx — m sets A then B then clears; Shift+M does nothing; the pending A hairline appears before the chip does; the marks' left/width follow bufferDuration() 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; m reaches the transport from behind the blown-up cover; the four abstentions hold for m (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 junk loop fails the schema rather than restoring NaN.
  • Verify teeth: revert each behaviour and confirm the specific test fails, as with the harvest work.

Order of work #

  1. Engine stopAt + onBoundary, and the fake's timed-stop onended (testable alone, no UI).
  2. Store: bufferDuration, loop signals, validation, per-track-by-id lifetime, armFollowOn stand-down and re-arm on clear.
  3. Session persistence.
  4. Marks, keys, chip, overlay pass-through.
  5. 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 #

  1. Fake: timed stop(when) fires onended from advance(); bare stop() stays immediate; natural end stays finish(). Engine tags its own scheduled stop so it cannot reach onEnded.
  2. Loop survives playAt on the same track id; clears on a track change.
  3. Pending A lives in the bar, drawn as a caret-like hairline; a refused B leaves A pending; cleared on track change, never persisted.
  4. peekLivePosition() added for marking off the audio clock.
  5. setLoop(null) re-arms the follow-on itself.
  6. m only — A, B, clear. Shift+M unbound.
  7. Loop math is buffer.duration only; out-of-range ends are clamped to it, including on restore. No index metadata anywhere near a boundary.
  8. setLoop writes the session immediately.
  9. m passes through the artwork overlay.
  10. setLoop returns boolean.