import { beforeEach, expect, it } from "vitest"; import { createAudioEngine, RATE_MAX, RATE_MIN } from "./engine"; import { FakeAudioContext, FakeShifter, silence, type FakeAudioOptions } from "../../test/audio"; import type { ShifterHandle } from "./engine"; /** * The engine on its own: what got armed, when, and what the clock says. These * are the invariants the store depends on and that no UI test could see. * * The fake context is created lazily through the engine's own factory — every * assertion is about the context the engine is actually using, and a test that * expects none gets one made for it by `context()` only when it asks. */ let options: FakeAudioOptions; let ctx: FakeAudioContext | undefined; function context(): FakeAudioContext { return (ctx ??= new FakeAudioContext(options)); } function engine() { ctx = undefined; return createAudioEngine({ createContext: () => (ctx ??= new FakeAudioContext(options)) }); } /** * The engine asks a buffer when to start, never what to play — but the interface says a * buffer has samples, because the detector needs them, so the literal carries them. Shared * zeros rather than one per buffer, for the same reason the fake keeps them: nothing here * reads a sample, and a hundred seconds of stereo is 17 MB of nothing. */ const buffer = (duration = 100) => ({ duration, numberOfChannels: 2, sampleRate: 44100, getChannelData: () => silence(Math.round(44100 * duration)), }); beforeEach(() => { options = {}; ctx = undefined; FakeAudioContext.reset(); }); it("arms the source ahead of the clock, never at currentTime", () => { const e = engine(); context().currentTime = 5; const p = e.play({ buffer: buffer() }); expect(p.startAt).toBeCloseTo(5.08, 6); expect(context().lastSource!.started[0]).toEqual({ when: 5.08, offset: 0 }); }); it("a source is started exactly once — pause/resume must build a new one", () => { const e = engine(); const p = e.play({ buffer: buffer() }); const source = context().lastSource!; expect(() => source.start(1, 0)).toThrow(/only be started once/); p.stop(); }); it("position starts at the offset, follows the audio clock, and stops at the end", () => { const e = engine(); const c = context(); const p = e.play({ buffer: buffer(10), offset: 4 }); // nothing has been heard yet: the source is armed, not started expect(p.position()).toBe(4); c.advance(2); // 4 + (2 - 0.08): the buffer does not begin until its armed start passes, so // the first 80ms of clock are not part of the track's position expect(p.position()).toBeCloseTo(4 + (2 - 0.08), 5); c.advance(20); // clamped: a source whose buffer ran out must not report minute 3 expect(p.position()).toBe(10); expect(p.remaining()).toBe(0); }); it("stop() is ours and does not masquerade as the end of the track", () => { const e = engine(); const c = context(); let ended = 0; const p = e.play({ buffer: buffer(), onEnded: () => ended++ }); // the fake fires `ended` on stop, like a browser does p.stop(); expect(ended).toBe(0); // both nodes of the playback come out of the graph expect(c.lastSource!.disconnects).toBe(1); expect(c.gains[1]!.disconnects).toBe(1); // and a late or duplicate end still says nothing c.lastSource!.finish(); c.lastSource!.stop(); expect(ended).toBe(0); }); it("the buffer running out reports itself once", () => { const e = engine(); const c = context(); let ended = 0; e.play({ buffer: buffer(), onEnded: () => ended++ }); c.lastSource!.finish(); c.lastSource!.finish(); expect(ended).toBe(1); }); /** * A–B, at the only layer where it can be tested honestly: the boundary has to be a * number handed to the audio thread, so these assert what was scheduled and when — * against a fake clock that only moves when the test says so — rather than that the * sound stopped somewhere plausible. */ it("a boundary is scheduled on the audio clock, from a buffer offset", () => { const e = engine(); const c = context(); c.currentTime = 5; const p = e.play({ buffer: buffer(100), offset: 10, stopAt: 30 }); const source = c.lastSource!; // startAt + (stopAt - from): an offset into the buffer goes in, an absolute // context time comes out. The caller could not have done this arithmetic itself — // `startAt` is the engine's, and for a pre-armed follow-on it is seconds in the // future, which is exactly why stopAt is not a context time. expect(source.stopAt).toBeCloseTo(p.startAt + (30 - 10), 6); expect(p.endAt).toBeCloseTo(source.stopAt!, 6); // The follow-on is armed at the boundary, not at the end of the bytes: one number, // on one clock, and the only reason a loop and a gapless seam can share a store. expect(p.endAt).toBeLessThan(p.startAt + 100 - 10); }); it("the boundary is its own event, and the queue-advancing one keeps silent", () => { const e = engine(); const c = context(); let ended = 0; let boundary = 0; e.play({ buffer: buffer(100), stopAt: 30, onEnded: () => ended++, onBoundary: () => boundary++ }); // Just short of it: neither. This is the assertion that the fake's bare `stop()` // would have flattered — a fake that fired `ended` at the moment the stop was // *scheduled* reports the boundary 30 seconds early here, and the store reading it // would hand the queue to the next track the instant a loop was armed. c.advance(20); expect(boundary).toBe(0); expect(ended).toBe(0); c.advance(20); expect(boundary).toBe(1); expect(ended).toBe(0); // the queue would have advanced on this one c.advance(60); expect(boundary).toBe(1); // once, like the buffer's own end }); it("remaining() and position() are measured to the boundary", () => { const e = engine(); const c = context(); const p = e.play({ buffer: buffer(100), stopAt: 30 }); expect(p.remaining()).toBeCloseTo(30, 5); c.advance(10); expect(p.remaining()).toBeCloseTo(20 + 0.08, 5); // the source has not heard its first 80ms yet c.advance(100); // The readout cannot run on past the second the audio thread is going to send the // listener back to: a clock that did would sweep the thumb across the tail of the // track between two passes, which is the bug the boundary exists to stop. expect(p.position()).toBe(30); expect(p.remaining()).toBe(0); }); it("a boundary that is not a place the source could stop is no boundary", () => { const e = engine(); const c = context(); let ended = 0; let boundary = 0; const over = e.play({ buffer: buffer(100), stopAt: 240, onEnded: () => ended++, onBoundary: () => boundary++, }); // Past the end of the bytes: asking for a boundary you cannot hear is the same // request as asking for none, and taking it literally would mean a source that // plays to the end and then reports a boundary the listener never heard. expect(c.lastSource!.stopAt).toBeUndefined(); expect(over.endAt).toBeCloseTo(0.08 + 100, 6); c.advance(200); expect(boundary).toBe(0); expect(ended).toBe(0); c.lastSource!.finish(); // the natural end is still the browser's own news expect(ended).toBe(1); // At or before where it starts, and the same refusal: a region with nothing in it // is a stutter, not a loop. const back = e.play({ buffer: buffer(100), offset: 40, stopAt: 30, onBoundary: () => boundary++, }); expect(c.lastSource!.stopAt).toBeUndefined(); expect(back.endAt).toBeCloseTo(c.currentTime + 0.08 + 60, 6); c.advance(200); expect(boundary).toBe(0); }); it("stopping a bounded playback is still ours — not the boundary, not the end", () => { const e = engine(); const c = context(); let ended = 0; let boundary = 0; const p = e.play({ buffer: buffer(100), stopAt: 30, onEnded: () => ended++, onBoundary: () => boundary++, }); p.stop(); // the pause, mid-loop c.advance(60); // ...and the boundary arrives on the clock anyway, as it must expect(ended).toBe(0); expect(boundary).toBe(0); expect(c.lastSource!.stopped).toBe(true); }); /** * The deck's speed. These are the assertions the *feature* rests on, and they are all about * one relation: a rate moves the wall clock, never the file. Every number the engine hands the * audio thread that names a place in the bytes — an offset, a boundary — stays put; every * number that names a second on the clock is divided. Get that relation wrong in either * direction and the failure is not a wrong readout: it is the next track arriving in the middle * of this one, or a loop cutting a phrase short. * * The pitch itself is not testable here and is not pretended to be: `AudioBufferSourceNode` has * no `preservesPitch` to assert the absence of, so the node being handed 2 *is* the octave. */ it("the rate goes to the node, which is where the octave actually happens", () => { const e = engine(); const c = context(); const p = e.play({ buffer: buffer(), rate: 2 }); expect(c.lastSource!.playbackRate.value).toBe(2); // ...and comes back off the playback, because the store has to know what a node already in the // air was armed with: a successor's start offset is measured at the *outgoing* rate. expect(p.rate).toBe(2); // The boring case is still the default, and worth pinning: a rate that leaked into the next // `play()` would be a track played at the wrong speed two keypresses later. expect(e.play({ buffer: buffer() }).rate).toBe(1); expect(c.sources.at(-1)!.playbackRate.value).toBe(1); }); it("at ×2 the clock crosses the bytes twice as fast, and position still names the file", () => { const e = engine(); const c = context(); const p = e.play({ buffer: buffer(10), offset: 4, rate: 2 }); expect(p.position()).toBe(4); // armed, not started: nothing of the track has been heard c.advance(2); // 4 + (2 - 0.08) × 2: the source has run 1.92 wall seconds and covered twice that much of the // record. Note which side of the multiplication the offset sits on — the four seconds it starts // at are a place in the file, and a place in the file is never scaled. expect(p.position()).toBeCloseTo(4 + (2 - 0.08) * 2, 5); c.advance(20); // Clamped at the end of the bytes and not at a wall-clock second: the thumb, the A–B marks and // the pulse are all read against this number, and they all mean seconds of the file. expect(p.position()).toBe(10); expect(p.remaining()).toBe(0); }); it("the end of the buffer is a duration divided, so the seam is armed for the end that will happen", () => { const e = engine(); const c = context(); c.currentTime = 5; const p = e.play({ buffer: buffer(100), rate: 2 }); // 50 wall seconds, not 100. This is the number the successor is armed at, so getting the half // wrong here is not a display error — it is track two landing on top of track one. expect(p.endAt).toBeCloseTo(5.08 + 50, 6); expect(p.endAt).toBeLessThan(p.startAt + 100); const slow = e.play({ buffer: buffer(100), rate: 0.5 }); expect(slow.endAt).toBeCloseTo(c.currentTime + 0.08 + 200, 6); }); it("a boundary is a place in the file, so it does not move; the second it arrives on does", () => { const e = engine(); const c = context(); c.currentTime = 5; let boundary = 0; const p = e.play({ buffer: buffer(100), offset: 10, stopAt: 30, rate: 2, onBoundary: () => boundary++, }); const source = c.lastSource!; // startAt + (stopAt - from) / rate. The loop keeps its edges — the same two seconds of the // record at any speed — and loses half the wall time between them. expect(source.stopAt).toBeCloseTo(p.startAt + (30 - 10) / 2, 6); expect(p.endAt).toBeCloseTo(source.stopAt!, 6); // Nine wall seconds in, the boundary has not been reached (it needs ten)... c.advance(9.9); expect(boundary).toBe(0); expect(p.position()).toBeLessThan(30); // ...and sixteen in it has been, at the second the clock was told. c.advance(6.2); expect(boundary).toBe(1); expect(p.position()).toBe(30); // and the clock is at B, not past it }); it("an unusable rate is no rate, and a wild one is clamped before the audio thread sees it", () => { const e = engine(); const c = context(); // Zero and its neighbours are not slow speeds: a rate is a divisor everywhere downstream, and // 0.001 is a four-minute track whose every follow-on is armed hours ahead. The answer to a // number that cannot mean a speed is the bytes at their own speed. for (const junk of [0, -1, Number.NaN, Number.POSITIVE_INFINITY, undefined]) { expect(e.play({ buffer: buffer(10), rate: junk }).rate, String(junk)).toBe(1); } expect(e.play({ buffer: buffer(10), rate: 1000 }).rate).toBe(RATE_MAX); expect(e.play({ buffer: buffer(10), rate: 0.001 }).rate).toBe(RATE_MIN); expect(c.lastSource!.playbackRate.value).toBe(RATE_MIN); }); it("one lazily-created context serves the whole engine", async () => { const e = engine(); // no output device before anyone asks for sound expect(FakeAudioContext.instances).toHaveLength(0); e.play({ buffer: buffer() }); e.play({ buffer: buffer(), offset: 3 }); await e.decode(new ArrayBuffer(8)); expect(FakeAudioContext.instances).toHaveLength(1); expect(context().sources).toHaveLength(2); // master → destination once; each playback brings its own track gain expect(context().gains).toHaveLength(3); expect(context().gains[0]!.connects).toBe(1); }); it("volume is remembered until there is a graph to apply it to", () => { const e = engine(); e.setMasterGain(2); // clamped: this is a gain, not a loudness knob e.setMasterGain(0.25); expect(FakeAudioContext.instances).toHaveLength(0); e.play({ buffer: buffer() }); // setTargetAtTime, not `value =`: a step change at a quantum boundary clicks expect(context().gains[0]!.gain.value).toBeCloseTo(0.25, 5); }); /** * The pitch shifter, as far as the engine owns it: which node is in the chain, when it gets there, * and what the engine says about the delay it costs. * * The DSP is not tested here — it is pure, it runs on either side of a thread boundary, and * `shift.test.ts` measures it. What is under test is the wiring, which is where a feature like this * actually fails in the wild: a node left in the chain at unity, a second module fetched per press, * a delay reported to the bar that the audio does not charge. */ const settled = () => new Promise((r) => setTimeout(r, 0)); function shifterEngine( handle: ShifterHandle | null = new FakeShifter(), keepShifter?: () => boolean, ) { ctx = undefined; let asks = 0; const e = createAudioEngine({ // Always a fresh context, and not the `??=` the shared helper above uses: this file closes a // graph and opens another, and a factory that hands back the closed one would have the engine // ask for a live context forever. The real `AudioContext` constructor cannot answer twice with // the same dead object; the fake was being too helpful. createContext: () => (ctx = new FakeAudioContext(options)), createShifter: async () => { asks++; return handle; }, keepShifter, }); return { e, handle, asked: () => asks }; } it("the shifter arrives on the first shift that is not unity, and not one time more", async () => { const handle = new FakeShifter(); const { e, asked } = shifterEngine(handle); // Asked for and not given, because nothing has been shifted: the node costs two rings of floats // and a thread to run on, and a page where nobody touches the pitch should not pay either. expect(e.shift()).toBe(1); expect(asked()).toBe(0); expect(e.shifterReady()).toBe(false); e.setShift(2); await settled(); // A key with nothing on the deck is a setting and not a graph. Building an audio context because a // persisted preference said +3 would open a suspended graph, and mutter an autoplay warning into // every console on the page's first paint, before anybody has asked for sound. expect(e.context()).toBeNull(); expect(asked()).toBe(0); expect(e.shift()).toBe(2); // The graph arrives with the first play, and the shift arrives with the graph. e.play({ buffer: buffer(10) }); await settled(); expect(asked()).toBe(1); expect(e.shifterReady()).toBe(true); expect(handle.ratio).toBe(2); // A dozen presses later there is still one node and one module: the shifter belongs to the graph, // and a fresh one per press would be a fresh delay line in the middle of the seam. for (const r of [1.5, 1.122, 0.79, 1]) e.setShift(r); await settled(); expect(asked()).toBe(1); }); it("the chain stays wired at unison, because leaving it is what clicked", async () => { const handle = new FakeShifter(); const { e, asked } = shifterEngine(handle); e.play({ buffer: buffer(10) }); const master = context().gains[0]!; e.setShift(2); await settled(); expect(master.connects).toBeGreaterThan(0); expect(handle.connects).toBeGreaterThan(0); const disconnects = handle.disconnects; // Back to unison, and nothing moves. The node holds its output back by its window, so unplugging it // snaps the audio forward by that much in one sample — the listener pressing `]` down to zero heard // the middle of a word skipped, on the transition they were most likely to make. Running the same // signal through the node at ratio 1 is the same signal a window later, and a delay is not a glitch. e.setShift(1); await settled(); expect(handle.disconnects).toBe(disconnects); expect(e.shifterReady()).toBe(true); expect(asked()).toBe(1); // And the shape is the same one, in that order: master into the shifter, the shifter's own output on // the destination. The graph has exactly one shape once it exists, and the ratio is the only thing in // it that moves. expect(master.connections.at(-1)).toBe("shifter"); }); it("a listener who has moved the pitch gets the chain before the first sample", async () => { // No `setShift` in this test at all: the point is that the graph is built the way the listener // already listens, so their first press of `]` is a ratio and not a rewiring. Joining the chain // mid-track loses a window of audio while the rings fill; joining it at the top of a track loses // something nobody can hear. const handle = new FakeShifter(); const { e, asked } = shifterEngine(handle, () => true); e.play({ buffer: buffer(10) }); await settled(); expect(asked()).toBe(1); expect(e.shifterReady()).toBe(true); expect(e.shift()).toBe(1); expect(e.shiftLatency()).toBeCloseTo(4096 / 44100, 6); }); it("a listener who never has pays for none of it", async () => { const handle = new FakeShifter(); const { e, asked } = shifterEngine(handle, () => false); e.play({ buffer: buffer(10) }); await settled(); // Not the module, not the node, not the delay, and not the half percent of a core: `keepShifter` is // the only thing standing between a plain deck and this one, so the answer false has to mean no work // at all rather than work quietly thrown away. expect(asked()).toBe(0); expect(e.shifterReady()).toBe(false); expect(e.shiftLatency()).toBe(0); }); it("the delay the node reports is the delay the bar is told, at unison included", async () => { const handle = new FakeShifter(); const { e } = shifterEngine(handle); e.play({ buffer: buffer(10) }); context(); // the context exists before the shift, so its sample rate is the one being divided expect(e.shiftLatency()).toBe(0); // nothing built, so nothing delayed e.setShift(2); await settled(); // 4 096 samples at the fake's 44 100: the number the pulse is moved by, in the seconds the bar // works in rather than the samples the DSP counts in. expect(e.shiftLatency()).toBeCloseTo(4096 / 44100, 6); handle.delay = 8192; e.setShiftQuality("smooth"); expect(e.shiftLatency()).toBeCloseTo(8192 / 44100, 6); expect(handle.quality).toBe("smooth"); // Unison is not "the last number I was given" and it is not zero either: the chain is in the graph, // the audio is behind the playhead by its window at ratio 1 exactly as it is at +3, and a bar that // stopped compensating the moment the key came home would flash a tenth of a second early on every // beat of the record the listener put back. e.setShift(1); expect(e.shiftLatency()).toBeCloseTo(8192 / 44100, 6); }); it("a browser with no audio thread for it still plays the record", async () => { const { e } = shifterEngine(null); e.play({ buffer: buffer(10) }); e.setShift(2); await settled(); expect(e.shifterReady()).toBe(false); expect(e.shiftLatency()).toBe(0); // The request is remembered rather than dropped: the deck's key is a setting, and a setting that // evaporates because one part of the browser is missing is a setting nobody can see. expect(e.shift()).toBe(2); // ...and none of it touched the transport, which is the only claim here that a listener can make. expect(context().lastSource!.started.length).toBe(1); }); it("a key set with nothing loaded is in force when something finally is", async () => { const handle = new FakeShifter(); const { e, asked } = shifterEngine(handle); e.setShift(1.334805); await settled(); expect(asked()).toBe(0); // remembered, not fetched — see the test above for why e.play({ buffer: buffer(10) }); await settled(); expect(handle.ratio).toBeCloseTo(1.334805, 6); expect(e.shiftLatency()).toBeGreaterThan(0); }); it("closing the graph takes the shifter with it", async () => { const handle = new FakeShifter(); const { e, asked } = shifterEngine(handle); e.play({ buffer: buffer(10) }); e.setShift(2); await settled(); expect(e.shifterReady()).toBe(true); e.close(); expect(handle.disposed).toBe(true); expect(e.shifterReady()).toBe(false); // A new graph gets its own node rather than a handle to a context that no longer exists. e.play({ buffer: buffer(10) }); e.setShift(3); await settled(); expect(asked()).toBe(2); }); it("an unusable ratio is no ratio, and a wild one is clamped before the thread sees it", async () => { const handle = new FakeShifter(); const { e } = shifterEngine(handle); e.play({ buffer: buffer(10) }); for (const junk of [ 0, -1, Number.NaN, Number.POSITIVE_INFINITY, undefined as unknown as number, ]) { e.setShift(junk); await settled(); expect(e.shift(), String(junk)).toBe(1); } e.setShift(1e6); expect(e.shift()).toBe(4); e.setShift(1e-6); expect(e.shift()).toBe(0.25); // Never handed to a node: a ratio that small is not a low note, it is a stream that stops coming // out of the delay line at all. await settled(); expect(handle.ratio).toBe(0.25); });