/** * The real loudspeaker code against a FAKE sound engine whose resume() and decodeAudioData() * finish only when the test says so. This shows that stopped or replaced speech never starts; * it says nothing about MP3 decoding or playback in a real browser, the Even app or a phone. */ import { beforeEach, describe, expect, it } from 'vitest'; import { createSpeaker } from '../src/ui/speaker.ts'; interface Deferred { promise: Promise; resolve: (value: T) => void; reject: (err: Error) => void; } function deferred(): Deferred { let resolve!: (value: T) => void; let reject!: (err: Error) => void; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; } class FakeSource { buffer: unknown = null; onended: (() => void) | null = null; started = 0; stopped = 0; connect(): void {} start(): void { this.started += 1; } stop(): void { this.stopped += 1; } } class FakeAudioContext { static last: FakeAudioContext; state: 'suspended' | 'running' = 'suspended'; destination = {}; resumes: Array> = []; decodes: Array & { label: string }> = []; sources: FakeSource[] = []; /** When true, resume() succeeds at once (an engine that is already running). */ ready = false; constructor() { FakeAudioContext.last = this; } resume(): Promise { if (this.ready) { this.state = 'running'; return Promise.resolve(); } const d = deferred(); this.resumes.push(d); return d.promise.then(() => { this.state = 'running'; }); } decodeAudioData(data: ArrayBuffer): Promise<{ label: string }> { const label = new TextDecoder().decode(data); const d = Object.assign(deferred<{ label: string }>(), { label }); this.decodes.push(d); return d.promise; } createBufferSource(): FakeSource { const source = new FakeSource(); this.sources.push(source); return source; } } const bytes = (label: string) => new TextEncoder().encode(label); const tick = () => new Promise((r) => setTimeout(r, 0)); const win = () => ({ AudioContext: FakeAudioContext, setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms) }) as unknown as Window; const ctx = () => FakeAudioContext.last; /** A promise's state without waiting for it. */ async function settled(p: Promise): Promise<'pending' | 'resolved' | 'rejected'> { const marker = {}; return Promise.race([p.then(() => 'resolved' as const, () => 'rejected' as const), tick().then(() => marker)]).then((v) => (v === marker ? 'pending' : (v as 'resolved' | 'rejected'))); } const starts = () => ctx().sources.reduce((n, s) => n + s.started, 0); describe('loudspeaker (fake sound engine)', () => { let speaker: NonNullable>; beforeEach(() => { speaker = createSpeaker(win())!; }); it('there is no loudspeaker in a page without a sound engine', () => { expect(createSpeaker({ setTimeout } as unknown as Window)).toBeNull(); }); it('plays to the end: resolves when the audio finishes by itself', async () => { const playing = speaker.play(bytes('one')); ctx().resumes[0]!.resolve(); await tick(); expect(ctx().decodes.map((d) => d.label)).toEqual(['one']); ctx().decodes[0]!.resolve({ label: 'one' }); await tick(); expect(ctx().sources).toHaveLength(1); expect(ctx().sources[0]!.started).toBe(1); expect(ctx().sources[0]!.buffer).toEqual({ label: 'one' }); expect(await settled(playing)).toBe('pending'); ctx().sources[0]!.onended!(); expect(await settled(playing)).toBe('resolved'); expect(ctx().sources[0]!.stopped).toBe(0); // Stopping afterwards touches nothing. speaker.stop(); expect(ctx().sources[0]!.stopped).toBe(0); }); it('stop while it is sounding stops that source once and ends the play', async () => { const playing = speaker.play(bytes('one')); ctx().resumes[0]!.resolve(); await tick(); ctx().decodes[0]!.resolve({ label: 'one' }); await tick(); speaker.stop(); expect(ctx().sources[0]!.stopped).toBe(1); expect(await settled(playing)).toBe('resolved'); speaker.stop(); expect(ctx().sources[0]!.stopped).toBe(1); expect(starts()).toBe(1); }); it('stop while the engine is still starting: nothing is decoded or started later', async () => { const playing = speaker.play(bytes('one')); speaker.stop(); ctx().resumes[0]!.resolve(); await tick(); expect(await settled(playing)).toBe('resolved'); expect(ctx().decodes).toHaveLength(0); expect(ctx().sources).toHaveLength(0); }); it('stop while decoding: the decoded audio is never started', async () => { const playing = speaker.play(bytes('one')); ctx().resumes[0]!.resolve(); await tick(); expect(ctx().decodes).toHaveLength(1); speaker.stop(); ctx().decodes[0]!.resolve({ label: 'one' }); await tick(); expect(await settled(playing)).toBe('resolved'); expect(ctx().sources).toHaveLength(0); expect(starts()).toBe(0); }); it('two answers decoding at once, the older finishing last: only the newer one is heard', async () => { const older = speaker.play(bytes('older')); ctx().resumes[0]!.resolve(); await tick(); ctx().ready = true; const newer = speaker.play(bytes('newer')); await tick(); expect(ctx().decodes.map((d) => d.label)).toEqual(['older', 'newer']); // The newer one is ready first and starts. ctx().decodes[1]!.resolve({ label: 'newer' }); await tick(); expect(ctx().sources).toHaveLength(1); expect(ctx().sources[0]!.buffer).toEqual({ label: 'newer' }); // Then the older one arrives: it starts nothing and does not stop the newer one. ctx().decodes[0]!.resolve({ label: 'older' }); await tick(); expect(await settled(older)).toBe('resolved'); expect(ctx().sources).toHaveLength(1); expect(ctx().sources[0]!.stopped).toBe(0); expect(await settled(newer)).toBe('pending'); ctx().sources[0]!.onended!(); expect(await settled(newer)).toBe('resolved'); expect(starts()).toBe(1); }); it('two answers decoding at once, the older finishing first: it is not heard either', async () => { const older = speaker.play(bytes('older')); ctx().resumes[0]!.resolve(); await tick(); ctx().ready = true; const newer = speaker.play(bytes('newer')); await tick(); ctx().decodes[0]!.resolve({ label: 'older' }); await tick(); expect(await settled(older)).toBe('resolved'); expect(ctx().sources).toHaveLength(0); ctx().decodes[1]!.resolve({ label: 'newer' }); await tick(); expect(ctx().sources.map((s) => s.buffer)).toEqual([{ label: 'newer' }]); speaker.stop(); expect(await settled(newer)).toBe('resolved'); }); it('a new answer while one is sounding stops the old source and plays the new', async () => { const first = speaker.play(bytes('first')); ctx().resumes[0]!.resolve(); await tick(); ctx().decodes[0]!.resolve({ label: 'first' }); await tick(); ctx().ready = true; const second = speaker.play(bytes('second')); expect(ctx().sources[0]!.stopped).toBe(1); expect(await settled(first)).toBe('resolved'); await tick(); ctx().decodes[1]!.resolve({ label: 'second' }); await tick(); expect(ctx().sources).toHaveLength(2); expect(ctx().sources[1]!.started).toBe(1); // The old source's late "ended" changes nothing. ctx().sources[0]!.onended?.(); expect(await settled(second)).toBe('pending'); expect(ctx().sources[1]!.stopped).toBe(0); }); it('a blocked engine and undecodable audio are failures, and leave nothing playing', async () => { const blocked = speaker.play(bytes('one')); // resume never settles; the 800 ms race ends it blocked.catch(() => undefined); // looked at below, after the wait await new Promise((r) => setTimeout(r, 850)); expect(await settled(blocked)).toBe('rejected'); ctx().ready = true; const bad = speaker.play(bytes('two')); await tick(); ctx().decodes[0]!.reject(new Error('EncodingError')); expect(await settled(bad)).toBe('rejected'); expect(ctx().sources).toHaveLength(0); }); });