the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Duet transport review fixes: Play never rewinds, the end is heard, failed resume pauses
Jameson Hodge626a5c5102aa
diff --git a/src/show/transport.ts b/src/show/transport.tsindex 8d16e31..252787d 100644--- a/src/show/transport.ts+++ b/src/show/transport.ts@@ -3,10 +3,12 @@* now, in seconds into the track. Its own AudioContext (the voice engine doesn't run here).** Paused, the playhead is the saved position. Playing, it is that position plus the audible time- * since the source started: the context's output timestamp where the browser has one (it already- * allows for output latency), else currentTime less the reported latency. A seek bumps `epoch`- * (so animation history can be reset) and restarts a fresh source. The context leaving "running"- * (an iOS interruption, the page going to the background) pauses the transport where it was.+ * since the source started (never less than none: the first moments after Play are still in the+ * output buffer): the context's output timestamp where the browser has one (it already allows for+ * output latency), else currentTime less the reported latency. A seek bumps `epoch` (so animation+ * history can be reset) and restarts a fresh source. The track ends when its end is heard, not when+ * the source finishes rendering. The context leaving "running" (an iOS interruption, the page+ * going to the background), or failing to resume after Play, pauses the transport where it was.*/export type TransportState = { playing: boolean; time: number; duration: number; epoch: number };@@ -17,12 +19,16 @@ export class Transport {private offset = 0;private startedAt = 0;private playing = false;+ /** the source has rendered its last sample; the track ends once that is heard */+ private rendered = false;+ /** bumped by every play, pause, seek and dispose: a late resume result for an old one is ignored */+ private generation = 0;private wasRunning = false;epoch = 0;private readonly listeners = new Set<() => void>();- constructor() {- this.ctx = new AudioContext({ latencyHint: "playback" });+ constructor(ctx: AudioContext = new AudioContext({ latencyHint: "playback" })) {+ this.ctx = ctx;this.ctx.onstatechange = () => {const running = this.ctx.state === "running";if (this.wasRunning && !running && this.playing) this.pause();@@ -59,7 +65,11 @@ export class Transport {/** Call from the tap itself: iOS only lets a user gesture start audio. */play(): void {if (!this.buffer || this.playing) return;- void this.ctx.resume();+ const gen = ++this.generation;+ this.ctx.resume().catch(() => {+ // no audio (an interruption, a browser's refusal): back to paused, where it was+ if (gen === this.generation && this.playing) this.pause();+ });if (this.offset >= this.duration - 0.05) this.offset = 0;this.startSource();this.playing = true;@@ -68,6 +78,7 @@ export class Transport {pause(): void {if (!this.playing) return;+ this.generation++;this.offset = this.time();this.stopSource();this.playing = false;@@ -75,6 +86,7 @@ export class Transport {}seek(t: number): void {+ this.generation++;this.offset = Math.min(this.duration, Math.max(0, t));this.epoch++;if (this.playing) {@@ -87,13 +99,21 @@ export class Transport {/** the audible playhead (s) */time(): number {if (!this.playing) return this.offset;- return Math.min(this.duration, Math.max(0, this.offset + this.audibleNow() - this.startedAt));+ const t = Math.min(this.duration, this.offset + Math.max(0, this.audibleNow() - this.startedAt));+ if (this.rendered && t >= this.duration) {+ // the end has been heard: stop here (listeners hear of it after the caller's frame)+ this.playing = false;+ this.offset = this.duration;+ queueMicrotask(() => this.emit());+ }+ return t;}dispose(): void {+ this.generation++;this.stopSource();this.listeners.clear();- void this.ctx.close();+ void this.ctx.close().catch(() => {});}private startSource(): void {@@ -101,13 +121,10 @@ export class Transport {src.buffer = this.buffer;src.connect(this.ctx.destination);src.onended = () => {- if (this.src !== src) return;- this.src = null;- this.offset = this.duration;- this.playing = false;- this.emit();+ if (this.src === src) this.rendered = true;};this.src = src;+ this.rendered = false;this.startedAt = this.ctx.currentTime;src.start(this.startedAt, this.offset);}@@ -115,6 +132,7 @@ export class Transport {private stopSource(): void {const src = this.src;this.src = null;+ this.rendered = false;if (!src) return;src.onended = null;try {diff --git a/tests/transport.test.ts b/tests/transport.test.tsnew file mode 100644index 0000000..768d401--- /dev/null+++ b/tests/transport.test.ts@@ -0,0 +1,137 @@+/**+ * The duet page's transport on a fake AudioContext whose clock and output latency the test sets:+ * the playhead is what the listener hears, Play never moves it back, the end comes when it's heard,+ * and audio that can't resume leaves the transport paused.+ */+import { describe, expect, test } from "bun:test";+import { Transport } from "../src/show/transport.ts";++class FakeSource {+ onended: (() => void) | null = null;+ started: [number, number] | null = null;+ stopped = false;+ buffer: unknown = null;+ connect() {}+ disconnect() {}+ start(when: number, offset: number) {+ this.started = [when, offset];+ }+ stop() {+ this.stopped = true;+ }+}++class FakeContext {+ currentTime = 0;+ outputLatency = 0.2;+ baseLatency = 0;+ state = "suspended";+ onstatechange: (() => void) | null = null;+ destination = {};+ sources: FakeSource[] = [];+ resumeResult: "ok" | "fail" = "ok";+ createBufferSource() {+ const s = new FakeSource();+ this.sources.push(s);+ return s;+ }+ async decodeAudioData() {+ return { duration: 100 };+ }+ async resume() {+ if (this.resumeResult === "fail") throw new Error("interrupted");+ this.setState("running");+ }+ async close() {+ this.setState("closed");+ }+ setState(s: string) {+ this.state = s;+ this.onstatechange?.();+ }+}++async function make() {+ const ctx = new FakeContext();+ const t = new Transport(ctx as unknown as AudioContext);+ await t.load(new ArrayBuffer(0));+ return { ctx, t };+}++describe("Transport", () => {+ test("the playhead is the audible time: still where Play was pressed until the output catches up", async () => {+ const { ctx, t } = await make();+ t.seek(60);+ ctx.currentTime = 5;+ t.play();+ expect(ctx.sources.at(-1)!.started).toEqual([5, 60]);+ expect(t.time()).toBe(60); // not 59.8: the first 0.2 s are still in the output buffer+ ctx.currentTime = 5.7;+ expect(t.time()).toBeCloseTo(60.5, 6);+ });++ test("tapping Play and Pause quickly never moves the playhead back", async () => {+ const { ctx, t } = await make();+ t.seek(60);+ for (let i = 0; i < 5; i++) {+ t.play();+ ctx.currentTime += 0.05;+ t.pause();+ }+ expect(t.time()).toBe(60);+ });++ test("the end comes when it is heard, not when the source finishes rendering", async () => {+ const { ctx, t } = await make();+ t.seek(99);+ t.play();+ ctx.currentTime = 1.0;+ ctx.sources.at(-1)!.onended!(); // rendered; 0.2 s still to come out of the speakers+ expect(t.isPlaying).toBe(true);+ expect(t.time()).toBeCloseTo(99.8, 6);+ ctx.currentTime = 1.25;+ expect(t.time()).toBe(100);+ expect(t.isPlaying).toBe(false);+ // Play at the end starts again from the top+ t.play();+ expect(ctx.sources.at(-1)!.started![1]).toBe(0);+ });++ test("a seek while playing restarts the source there and bumps the epoch", async () => {+ const { ctx, t } = await make();+ t.play();+ const first = ctx.sources.at(-1)!;+ const e = t.epoch;+ ctx.currentTime = 2;+ t.seek(30);+ expect(first.stopped).toBe(true);+ expect(ctx.sources.at(-1)!.started).toEqual([2, 30]);+ expect(t.epoch).toBe(e + 1);+ // the old source's end means nothing now+ first.onended?.();+ ctx.currentTime = 100;+ expect(t.isPlaying).toBe(true);+ });++ test("audio that can't resume leaves the transport paused where it was", async () => {+ const { ctx, t } = await make();+ ctx.resumeResult = "fail";+ t.seek(10);+ t.play();+ await Promise.resolve();+ await Promise.resolve();+ expect(t.isPlaying).toBe(false);+ expect(t.time()).toBe(10);+ });++ test("an interruption while playing pauses it", async () => {+ const { ctx, t } = await make();+ t.play();+ await Promise.resolve();+ expect(ctx.state).toBe("running");+ ctx.currentTime = 3;+ ctx.setState("interrupted");+ expect(t.isPlaying).toBe(false);+ expect(t.time()).toBeCloseTo(2.8, 6);+ });+});