Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776/** * The Web Audio half of the player: one AudioContext, one graph, and a clock * worth trusting. * * Shape of the graph (docs/research/navidrome-api-and-audio-engine.md §4.1, * the buffer-queue engine): * * AudioBufferSourceNode ─▶ trackGain ─▶ masterGain ─▶ destination * * Per-play source and trackGain nodes are cheap, disposable plumbing; the * AudioBuffer is the expensive thing and lives outside this module (the store * caches and evicts). Two consequences of that split drive the API: * * - a source node is one-shot — `start()` may be called once, ever. Pause is * therefore "stop, remember the offset" and resume is "new node, * `start(when, offset)`", not a flag on the old node; * - position is never a wall-clock estimate. It is derived from * `AudioContext.currentTime` — the audio clock, which is what the listener * actually hears — so it cannot drift away from the sound the way a * `Date.now()` bookkeeping would. * * Scheduling always uses a small lookahead (`START_LOOKAHEAD`), never * `start(currentTime)`: `currentTime` names the *next render quantum*, and a * source armed inside the quantum the audio thread is already assembling can * land late. ~80ms absorbs main-thread jitter (this app has a lot of it: a * virtualized list, a harvest) without becoming audible latency. * * Everything the module touches on the browser is reached through * `AudioContextLike`, so a test can hand it a fake and assert what was * scheduled and when, with no audio hardware involved. */
import { beginLoadClock, elapsed, tracePlayback } from "./trace";import type { ShiftQuality } from "./shift";import { SHIFT_QUALITIES } from "./shift";
/** * Seconds of buffer we hand the audio thread. See the note above. * * Exported because a caller scheduling a *handover* between two live sources — * the store's loop-clear restart — has to arm the follower on the same clock * and the same margin this module puts behind a reactive start, and two * constants in two files is a relation, not a guarantee. */export const START_LOOKAHEAD = 0.08;
/** Master gain ramp time constant, s. Direct `.value` writes click. */const GAIN_RAMP = 0.01;
/** Structural subset of the DOM's AudioBuffer — everything we ask of it. */export interface AudioBufferLike { readonly duration: number; readonly numberOfChannels: number; readonly sampleRate: number; /** * The decoded samples of one channel, read-only view, length `sampleRate * duration`. * * Added for the loop detector (player/detect.ts), which is the first thing in the app * that wants the *samples* rather than the length of them: detection runs on bytes the * store already decoded, which is what makes it as format-agnostic as the player is and * costs no second decode. The real AudioBuffer throws for a channel index at or past * `numberOfChannels`; callers loop over the channels rather than guessing a count, so * the fake can hand out what it holds without modelling that. */ getChannelData(channel: number): Float32Array;}
export interface AudioParamLike { value: number; setTargetAtTime?(target: number, startTime: number, timeConstant: number): void;}
export interface AudioNodeLike { connect(destination: AudioNodeLike): unknown; disconnect(): void;}
export interface GainNodeLike extends AudioNodeLike { gain: AudioParamLike;}
export interface AudioSourceNodeLike extends AudioNodeLike { buffer: AudioBufferLike | null; /** * The deck's speed. The browser's own `AudioParam`, of which the engine sets only * `value` — and sets it once, at arm time, never on a node that is already running. * * Worth naming the absence beside it: `AudioBufferSourceNode` has **no** * `preservesPitch`. That property belongs to `HTMLMediaElement` alone, and the W3C * thread refusing to add it here dates from 2012 and still describes the state of the * art. On this node rate *is* pitch, with nothing to turn off — which is the whole * feature rather than a limitation of it: see `PlayOptions.rate`. */ playbackRate: AudioParamLike; onended: (() => void) | null; start(when?: number, offset?: number): void; stop(when?: number): void;}
/** Structural subset of an `AudioWorkletNode` — the parts the shifter handle uses. */export interface AudioWorkletNodeLike extends AudioNodeLike { readonly port: { postMessage(message: unknown): void; onmessage: ((event: { data: unknown }) => void) | null; }; readonly parameters: { get(name: string): AudioParamLike | undefined };}
/** * Structural subset of AudioContext — the parts the engine uses. * * `audioWorklet` is optional because it is the part a browser may not have said yes to yet — and * because the test fake is allowed to omit it and see the engine carry on without a pitch control, * which is the honest shape of "this feature needs a worklet". Note what is *not* here: no * `createWorkletNode`. No such method exists on `AudioContext` — an `AudioWorkletNode` is * constructed with the context as its first argument — and an interface that asked for one is how * this feature managed to look entirely working, in every test, while returning no shifter in every * browser. The node is built where it is actually built, in `shift-node.ts`, against the real global. */export interface AudioContextLike extends AudioNodeLike { readonly state: "suspended" | "running" | "closed"; readonly currentTime: number; readonly sampleRate: number; readonly destination: AudioNodeLike; readonly audioWorklet?: { addModule(url: string): Promise<void> } | undefined; resume(): Promise<void>; suspend?(): Promise<void>; close?(): Promise<void>; createBufferSource(): AudioSourceNodeLike; createGain(): GainNodeLike; decodeAudioData(data: ArrayBuffer): Promise<AudioBufferLike>;}
/** * What the engine needs from a pitch shifter: a node in the graph, one number to change, and a * report of what the delay turned out to be. * * Built by `shift-node.ts` around a real `AudioWorkletNode`. Injectable, because the alternative is * asking jsdom for an audio thread it does not have. */export interface ShifterHandle { /** * The node itself. This is the thing that goes into the graph — `master.connect(the handle)` is a * type error in the DOM and a `TypeError` at runtime, because a wrapper around a node is not one, * and the engine used to do exactly that: the graph was torn down, the connect threw, the throw was * caught, and the pitch control vanished with the master left unplugged. Every fake in the test * suite accepted it, because a fake that will connect anything connects anything. */ readonly node: AudioNodeLike; /** the shifter's own output → the given node (the context destination, in every real use) */ connect(destination: AudioNodeLike): void; /** take the node out of the graph at both ends */ disconnect(): void; /** the frequency ratio to shift by; 1 leaves the signal alone and the engine wires it out */ setRatio(ratio: number): void; /** the tuning of the algorithm — window length, in the end, and with it the latency */ setQuality(quality: ShiftQuality): void; /** output delay in samples, as the node itself last reported it */ latency(): number; /** take the node out of the graph and let it go */ dispose(): void;}
export interface PlayOptions { buffer: AudioBufferLike; /** seconds into the buffer to start from (seek, resume after pause) */ offset?: number; /** per-track gain; ReplayGain lands here later */ gain?: number; /** * Arm at this absolute `currentTime` instead of at "now plus lookahead". * * This is what makes a boundary gapless: the follow-on source is armed while * the current one is still playing, at the exact instant its predecessor's last * sample is scheduled to be heard, so the audio thread decides when the next * track begins and the main thread is not in the loop. Passing `when` opts out * of `START_LOOKAHEAD`, correctly: that lookahead exists to survive a *reactive* * arm — one issued after the event that wanted sound — and an arm made seconds * ahead of its own start time is long past any quantum being assembled. * * A `when` in the past starts immediately, which is the browser's behaviour and * the right one here: it means we armed too late, not that the track should be * silent. */ when?: number; /** * Stop at this absolute buffer offset, rather than where the bytes run out. * * An offset into the buffer and not a context time, so the caller does not have * to know `startAt` — which it cannot observe anyway once a source has been armed * ahead of time. `endAt` and `remaining()` follow the boundary, and the browser * is told to cut the source off with `source.stop(startAt + stopAt - from)`, so * the boundary lands on the audio clock rather than whenever a ticker next * samples the position. * * Anything that is not a place the source could stop at — absent, non-finite, * past the end of the bytes, at or before the offset it is starting from — is * treated as no boundary at all, which is the same thing as asking for a loop that * has nothing between its two ends. * * A boundary at exactly the end of the buffer does count, and has to: that is the * region whose B is the end of the track, and the audio is over at that moment * either way. What the boundary is *for* is which of the two events the browser's * single `onended` becomes — the end of a track hands the queue to the next song, * and a boundary that is the end of a track puts the clock back at A instead. */ stopAt?: number; /** * The buffer ran out. Deliberately NOT called for our own `stop()` — the * queue advances on this, and every pause/skip/seek would otherwise rewind * the user two tracks instead of one. */ onEnded?: () => void; /** * Sample-rate multiplier — the deck's speed. 1 plays the bytes as they are. * * Because a BufferSource has no pitch preservation to speak of, this is a *varispeed* * control and not a pitch control: at 2 the track is an octave up and takes half as * long, at 0.5 an octave down and twice as long. That coupling is the feature (see * `player/pitch.ts`), and it is why everything this module reports stays in *buffer* * seconds while only the wall clock moves: position, `remaining()` and a `stopAt` * boundary all name the same second of the file whatever the rate, so a loop marked * at concert pitch still bounds the same bars at ×2. * * Anything unusable — absent, NaN, zero, negative — is 1: bytes that will not play at * all is a worse answer than bytes that play at their own speed. Beyond a couple of * octaves either way the number stops being a musical request and starts being a * mistake, and a source at 0.01× is a four-minute track that ends in eleven hours with * every follow-on seam armed against it, so the range is clamped rather than trusted. */ rate?: number; /** * A scheduled `stopAt` was reached. * * Its own callback rather than a flag on `onEnded`, because the one `onended` * the browser delivers here is delivered by the same mechanism as the one a * buffer running out fires — and the store advances the queue from that. Without * a distinct event, arming a loop would arm the queue advance with it. */ onBoundary?: () => void;}
export interface Playback { readonly buffer: AudioBufferLike; /** context-clock time the source was armed for */ readonly startAt: number; /** * The rate this source was armed at, as it was handed to the audio thread. * * A number about *this* node, not about the player's current setting: a source armed * ahead of a seam keeps the rate it was armed with, so this is the only honest way to * ask what a node that is already in the air is doing. `rearmLive` needs exactly that, * because the offset a follower has to start at is where this source *will be* at the * handover second — and that distance is travelled at this rate, not the new one. */ readonly rate: number; /** buffer offset it was armed at */ readonly from: number; /** * context-clock time of the last sample this playback will produce. The * follow-on is armed here: one number, on one clock, decided once — which is * the only way two plays can meet without a hole between them. * * With a `stopAt` this is the boundary, not the end of the bytes, which is what * makes an A–B region work with the gapless path rather than against it: the * follower is armed at the last sample the listener is actually going to hear. */ readonly endAt: number; /** seconds into the buffer, per the audio clock (never past the end) */ position(): number; /** seconds of buffer left to hear */ remaining(): number; /** * End this playback. A bare stop is immediate: the node goes silent now, and * the graph wiring comes down now. * * A `when` in the future is a different thing — a handover, not a death. The * node keeps playing (and stays connected) until that second, so a follower * armed for the same instant takes over with no hole and no waveform step; * the wiring comes down when the browser says the node ended. This is how a * boundary already scheduled on the node is taken out of the air: the earlier * of two stops wins, so stopping a bounded source *before* its boundary * cancels the boundary. */ stop(when?: number): void;}
export interface AudioEngine { /** the shared context, or null before it is first needed */ context(): AudioContextLike | null; /** sample rate of the shared context (0 before it exists) */ sampleRate(): number; /** * Shift the pitch by this frequency ratio, leaving the clock where it was. * * Not semitones, and not a key: the engine is told one number and does not know that a key, a * locked tempo and a varispeed went into it — see `player/pitch.ts`, which is where that sum is * kept. 1 means "do not touch what I heard", and at 1 the node is wired *out* rather than fed * unity: a bypass that still runs the DSP is a bypass that can add distortion, latency and a * dropout of its own. * * The first request that is not 1 builds the node, which takes a trip to the audio thread to fetch * the worklet module; the shift then arrives a few milliseconds late, once. Every later change is * synchronous with the audio clock, because a param write is. */ setShift(ratio: number): void; /** the ratio currently in force, whether or not anything exists to apply it */ shift(): number; /** re-tune the algorithm. Restarts the shifter's stream, so expect the delay to move. */ setShiftQuality(quality: ShiftQuality): void; shiftQuality(): ShiftQuality; /** whether the browser gave us an audio thread to shift on at all */ shifterReady(): boolean; /** * Seconds the shifter is putting between the graph and the speakers right now — 0 while it is * bypassed, tens of milliseconds while it is not. * * The pulse in the bar subtracts this from the playhead. Nothing else should: the position a seek * bar shows is the position the *file* is at, and a seek that landed a frame early would be a seek * that does the wrong thing to the audio, not merely to the picture of it. */ shiftLatency(): number; /** * Create the context and take it out of `suspended`. MUST be called * synchronously from a user gesture the first time: a context created (or * resumed) outside a gesture is blocked by the autoplay policy and its * `resume()` promise never settles. */ unlock(): Promise<void>; /** whole-file decode — `decodeAudioData` cannot ingest a fragment */ decode(bytes: ArrayBuffer): Promise<AudioBufferLike>; play(options: PlayOptions): Playback; setMasterGain(value: number): void; close(): void;}
export interface AudioEngineOverrides { /** inject a context factory (tests; AudioContext-less environments) */ createContext?: () => AudioContextLike; /** * Build the pitch shifter on a context. Absent means no pitch control: the varispeed still works, * and every time-math in the app is unchanged by whether the shifter exists. */ createShifter?: ( context: AudioContextLike, quality: ShiftQuality, ) => Promise<ShifterHandle | null>; /** * Whether this listener is one who moves the pitch. Asked once, when a context is built, and * answered true means the shifter is wired into the chain *before the first sample* rather than at * the first shift. * * The reason it is worth a callback is that joining the chain is the one transition that cannot be * made quietly: the shifter delays its output by its window, so a graph that grows one halfway * through a word loses that much audio while its rings fill. Paid at the top of a track it is * inaudible; paid in the middle of one it is not. A returning pitch listener therefore never sees a * transition at all, and a listener who has never touched `[` still pays nothing — not the delay, * not the CPU, not the module fetch. */ keepShifter?: () => boolean;}
function defaultCreateContext(): AudioContextLike { const g = globalThis as unknown as Record<string, (new () => AudioContextLike) | undefined>; const Ctor = g.AudioContext ?? g.webkitAudioContext; if (!Ctor) throw new Error("Web Audio is unavailable in this browser"); // "interactive": the only hint that asks the UA for the lowest-latency // output path, which is what a keyboard-driven player is trading for. return new Ctor();}
function clampOffset(offset: number, duration: number): number { if (!Number.isFinite(offset) || offset <= 0) return 0; return Math.min(offset, duration);}
/** * Two octaves either way, which is as far as a request in semitones gets and no further. * * The clamp is not a safety net for a hostile caller — the only caller is this app, and it * offers one octave. It is there because a rate is a *divisor* everywhere downstream (a * duration, a seam, an arm margin) and the failure of a rate near zero is not a track that * plays slowly but a player whose every future boundary is armed hours ahead. */export const RATE_MIN = 0.25;export const RATE_MAX = 4;
function normalizeRate(rate: number | undefined): number { if (rate === undefined || !Number.isFinite(rate) || rate <= 0) return 1; return Math.min(RATE_MAX, Math.max(RATE_MIN, rate));}
/** * The pitch ratio the shifter will accept, which is a wider range than the rate: a key is ±2 * semitone-octaves at most, and the shifter's own guard against a ratio that would make the signal * meaningless sits in the DSP. What this clamp is for is the same thing the rate clamp is for — a * ratio near zero is not a low note, it is a stream that never comes out the other end. */function normalizeRatio(ratio: number | undefined): number { if (ratio === undefined || !Number.isFinite(ratio) || ratio <= 0) return 1; return Math.min(4, Math.max(0.25, ratio));}
export function createAudioEngine(overrides: AudioEngineOverrides = {}): AudioEngine { const make = overrides.createContext ?? defaultCreateContext;
// One context for the whole app. Multiple contexts means multiple clocks, // which throws away the only reason to use Web Audio for playback; it is // also a per-origin resource cap waiting to be hit. let ctx: AudioContextLike | null = null; let master: GainNodeLike | null = null; // Volume the user asked for, kept even before there is a graph to apply it // to: the app can be opened, volume set, and only then played. let masterGain = 1;
// ─── the pitch shifter ──────────────────────────────────────────────────────────────── // // One node for the whole graph, on the master rather than per source, for the same reason the // volume is on the master: a shifter that belongs to a *playback* has a delay line that is rebuilt // at every seam, and a rebuilt delay line is a hole in the audio exactly where this app is most // careful not to make one. On the master, the gapless handover happens upstream of it and the // shifter never notices. let shifter: ShifterHandle | null = null; /** in flight, so a second press does not fetch the worklet twice */ let loading: Promise<void> | null = null; let shiftRatio = 1; let quality: ShiftQuality = "balanced"; /** the browser said no, once: no point asking every time a key is pressed */ let shifterRefused = false;
/** * Reconnect the master, which is the whole of engaging and disengaging the shifter. * * At a ratio of 1 the node is wired *out* rather than fed unity: pass-through in this algorithm is * transparent to within float rounding and still costs a window's worth of delay, an allocation- * free but real amount of arithmetic per quantum, and one more thing in the chain that can glitch. * Unasking is cheaper and safer than asking for nothing. */ function wireMaster(): void { if (!ctx || !master) return; // One shape, once the chain exists: master → shifter → destination, at every ratio including 1. // // There used to be a second shape — straight to the destination at unison, on the argument that a // shifter doing nothing should not be in the way — and moving between the two was what clicked. // The node holds its output back by its window (78 ms on the default tuning), so unplugging it // snaps the audio forward by that much in a single sample and plugging it back in drops the same // amount out: `]` down to zero skipped the middle of a word. The listener heard a discontinuity on // exactly the transition they were most likely to make, and called it hideous, correctly. // // Ratio 1 through the shifter is the same *signal* as the bypass, 78 ms later — and a delay is not // a glitch. It is a delay the bar already knows about: `shiftLatency` below stops pretending a // bypassed graph has no delay, and the pulse is painted against the audio that is actually coming // out of the speaker either way. master.disconnect(); if (shifter) { // The node into the master, and the node's output to the destination: two ends of one node, and // neither of them the handle. See `ShifterHandle.node`. master.connect(shifter.node); shifter.connect(ctx.destination); } else { master.connect(ctx.destination); } }
/** Build the node on the audio thread. Called once, on the first shift that is not unity. */ function loadShifter(): Promise<void> { const makeShifter = overrides.createShifter; const c = needContext(); if (!makeShifter || shifterRefused) return Promise.resolve(); if (loading) return loading; loading = makeShifter(c, quality) .then((handle) => { if (!handle) { shifterRefused = true; return; } shifter = handle; // Whatever was asked for while the module was being fetched, and whatever the re-tune cost, // both land here rather than in the callbacks that asked for them. handle.setRatio(shiftRatio); handle.setQuality(quality); wireMaster(); tracePlayback("shifter engaged", undefined, undefined, () => ({ ratio: shiftRatio, quality, latency: handle.latency(), })); }) .catch((error: unknown) => { // No audio thread to shift on — an old Safari, a page with no user gesture yet, a worklet // that failed to compile. The deck still plays and still varies speed; what stops working is // the pitch control, which is the smallest thing in this module to lose. shifterRefused = true; shifter = null; // And said out loud, once, because every other part of this path is silent on purpose: the // record plays, the readout above the title still moves, and the only thing missing is the // sound of the pitch changing. A feature that fails without a trace is a bug report nobody // can file, and the error the browser gave is the whole difference between "this browser has // no audio worklet" and "the module threw on its way in". console.warn("pitch control unavailable — the deck still plays", error); tracePlayback("shifter refused", undefined, undefined, () => ({ error: String(error) })); }); return loading; }
function needContext(): AudioContextLike { if (ctx && ctx.state !== "closed") return ctx; ctx = make(); // The master gain is the graph's single volume control and the place a // limiter/compressor will hang later; built once, next to its context. master = ctx.createGain(); master.gain.value = masterGain; master.connect(ctx.destination); // The pitch the deck was left in, if any. Asked for here rather than when it was set, because a // context is not something this app creates until the page has asked for sound: a listener who // left the key at +3 would otherwise be opening a page that builds an audio graph — suspended, // harmless, and muttering a warning about autoplay policies into every console on earth — before // they have pressed anything. if (!shifter && !shifterRefused && (shiftRatio !== 1 || overrides.keepShifter?.())) void loadShifter(); return ctx; }
async function resume(): Promise<void> { const c = needContext(); if (c.state !== "suspended") return; // Swallowed on purpose: when the page has no activation the promise simply // never settles, and if it does reject there is nothing to do but wait for // the next gesture and try again. Awaiting it forever would leave the // player stuck in "loading" with a source node already armed. // // Which is exactly the case the trace has to speak for, because the swallow makes it // invisible: the source is armed, the clock never moves, and the bar says the track is // playing. A context that is still suspended after a second of being asked is not waiting // for a promise — it is waiting for a gesture, which is a sentence about the page rather // than about the code, and the one thing the console cannot otherwise tell you. const asked = beginLoadClock(); await c.resume().catch(() => undefined); if (c.state === "suspended") { tracePlayback( "the AudioContext is still suspended — it is waiting for a gesture, not for this code", undefined, elapsed(asked), ); } }
return { context: () => ctx, sampleRate: () => ctx?.sampleRate ?? 0,
// Best effort, and never a rejection: this runs synchronously from the // click or keypress that asked for music, and an unhandled rejection from // the AudioContext constructor (no Web Audio, too many contexts, a hostile // environment) would land on the page instead of on the player. The failure // still surfaces — the decode that follows reaches the same constructor and // reports it through the store's error state. unlock: () => resume().catch(() => undefined),
async decode(bytes) { const c = needContext(); // NB: decodeAudioData detaches `bytes`; callers must not reuse it. It // also resamples to the context rate, so "bit-perfect" output has to // bypass this graph entirely (see the research doc, §3.3). return await c.decodeAudioData(bytes); },
play(options) { const c = needContext(); const buffer = options.buffer; const from = clampOffset(options.offset ?? 0, buffer.duration); const rate = normalizeRate(options.rate);
const source = c.createBufferSource(); const trackGain = c.createGain(); trackGain.gain.value = options.gain ?? 1; source.buffer = buffer; // Set before `start`, and never again: the rate is a fact about this arm of this // source. Changing it on a node that is already running would leave `position()` // describing a speed the source has left behind, and a boundary already scheduled // on the node could not be moved with it — only outranked by an earlier stop. A // rate change is therefore a new source, which is what the store's `rearmLive` // makes it, on the same argument `seek` has always used. source.playbackRate.value = rate; source.connect(trackGain); trackGain.connect(master ?? c.destination);
// An explicit `when` is the follow-on's whole point: the seam is placed on // the audio clock rather than left to whenever the main thread gets round // to arming. Without one, this is a start behind a gesture and it wants the // lookahead (see the module header). const startAt = options.when !== undefined && Number.isFinite(options.when) ? options.when : c.currentTime + START_LOOKAHEAD;
// Where the bytes stop being the thing the listener is hearing: the end of // the buffer, or the boundary if one was asked for and is a place it can // actually sit. Every read out of this playback is measured against that. // // Divided by the rate, because a duration in the file and a second on the audio // clock are only the same thing at ×1: two minutes of bytes at ×2 are over in a // minute of wall time. This is the one place the two units meet, and `endAt` is what // the follow-on is armed at, so getting the direction wrong here is not a wrong // number in a readout — it is the next track arriving in the middle of this one. const requested = options.stopAt; const bounded = requested !== undefined && Number.isFinite(requested) && requested > from && requested <= buffer.duration; const limit = bounded ? (requested as number) : buffer.duration;
let ended = false; let stopped = false; // True as soon as *we* are the reason the source is going to end: a stop // scheduled for the boundary is the browser's own `onended`, and it must not // be read as the buffer having run out. let boundary = false; const position = () => { if (ended) return limit; const elapsed = c.currentTime - startAt; // Buffer seconds, so the rate multiplies: a wall-clock second of a ×2 source is // two seconds of the file. Everything the bar reads off this number — the fill, the // A–B marks, the pulse's phase — is measured in buffer seconds too, which is what // keeps them all true without knowing a rate exists. return Math.min(limit, from + Math.max(0, elapsed) * rate); };
source.onended = () => { // `onended` also fires after stop(), which is exactly the trap: the // store advances the queue from here, and a skip would be heard as // "track ended" on top of the track the user just chose. if (stopped || ended) return; ended = true; if (boundary) options.onBoundary?.(); else options.onEnded?.(); }; source.start(startAt, from);
// The offset matters: resuming at 90s of a 200s buffer ends at // startAt + 110, not startAt + 200 — and at ×2, startAt + 55. A boundary can only be // earlier than that, since it has to sit inside the bytes to count as one. const naturalEndAt = startAt + Math.max(0, buffer.duration - from) / rate; const endAt = bounded ? startAt + ((requested as number) - from) / rate : naturalEndAt; // Arming a source and *then* telling it when to stop: `stop()` before // `start()` is an InvalidStateError in the browser, and the fake's // once-only `start` is the small version of that rule. if (bounded) { boundary = true; source.stop(endAt); } // The numbers the audio thread was handed. Everything about a track that is "playing" // and silent comes down to these: a `startAt` the clock has already passed, a `from` // past the end of the bytes, a boundary at or behind the offset, a context still // suspended. The store cannot print them — it does not own the lookahead, the clamp or // the clock — and by the time the symptom is visible the numbers are gone. tracePlayback("source armed on the audio clock", undefined, undefined, () => ({ from: from.toFixed(2), at: startAt.toFixed(2), clock: c.currentTime.toFixed(2), // Only worth a column when it is not the boring one: a line that always says ×1.00 // teaches nobody to look at it. ...(rate === 1 ? {} : { rate: `×${rate}` }), // How far in the future the start was when it was asked for; negative means the // browser was asked to start something in the past, which it does immediately and // which is what a late follow-on seam sounds like. lead: (startAt - c.currentTime).toFixed(2), stopAt: bounded ? (requested as number).toFixed(2) : "the end of the bytes", endAt: endAt.toFixed(2), state: c.state, }));
return { buffer, startAt, from, rate, endAt, position, remaining: () => Math.max(0, limit - position()), stop: (when?: number) => { if (stopped || ended) return; stopped = true; // A stop scheduled for a moment the clock has not reached is a handover: // the node has to keep producing samples until then, so the graph wiring // comes down at its `ended` rather than here. A bare stop (or one already // past) is a death, and it is silent from this line. const scheduled = when !== undefined && Number.isFinite(when) && when > c.currentTime; try { source.stop(when); } finally { if (scheduled) { const dispatch = source.onended; source.onended = () => { dispatch?.(); source.disconnect(); trackGain.disconnect(); }; } else { // Unhook the graph now rather than waiting for collection: the // nodes are cheap, but holding them keeps the buffer reachable. source.disconnect(); trackGain.disconnect(); } } }, }; },
setMasterGain(value) { const v = Math.min(1, Math.max(0, value)); masterGain = v; if (!ctx || !master) return; const g = master.gain; // setTargetAtTime rather than `g.value = v`: assigning the value directly // changes it at a render-quantum boundary and is audible as a click. if (g.setTargetAtTime) g.setTargetAtTime(v, ctx.currentTime, GAIN_RAMP); else g.value = v; },
setShift(ratio) { const next = normalizeRatio(ratio); if (next === shiftRatio) return; shiftRatio = next; // Asked for before the graph exists is normal — the key is a setting of the deck, and a // listener can move it with nothing loaded at all. It waits in `shiftRatio` and is applied when // a context is finally built, exactly as the volume waits in `masterGain`. if (next !== 1 && ctx && !shifter && !shifterRefused) void loadShifter(); if (shifter) shifter.setRatio(next); wireMaster(); },
shift: () => shiftRatio,
setShiftQuality(next) { if (SHIFT_QUALITIES.includes(next)) quality = next; // The re-tune rebuilds the shifter's rings, and with them the delay. Nothing is read back here: // `shiftLatency` below asks the node every time, which is the only way to get a number that // moves on its own — see there. shifter?.setQuality(quality); },
shiftQuality: () => quality,
shifterReady: () => shifter !== null,
shiftLatency() { // No condition on the ratio: the chain is either there or it is not, and a chain that is in the // graph delays the audio at unison exactly as it does at +3. Reporting 0 for a wired shifter // would paint the pulse against a position the listener stopped hearing at. if (!shifter || !ctx) return 0; // Asked of the node each time, rather than cached when it was built. The delay is something the // audio thread *tells* us — a report on a port, arriving some time after the node exists, and // again after every re-tune — and a copy made at load time is a copy that reads 0 until the // first tuning change, which is a pulse painted exactly where the old bug painted it. return shifter.latency() / ctx.sampleRate; },
close() { const c = ctx; ctx = null; master = null; // The node belongs to the context it was built on; dropping both together is the only way not // to leave a worklet holding two rings of floats for a graph that no longer exists. shifter?.dispose(); shifter = null; loading = null; if (!c || c.state === "closed") return; // An open AudioContext keeps an output device claimed; the page may live // a long time, so closing it is worth the (untyped, older) API dance. void c.close?.().catch?.(() => undefined); }, };}