8000 fix(playback): detect silent media stalls, surface load errors by johannboehme · Pull Request #149 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions frontend/src/editor/components/MasterAudio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,17 @@ export function MasterAudio({ audioUrl }: Props) {
style={{ display: "none" }}
/>
{!handle.isReady && (
<div className="absolute inset-0 flex items-center justify-center bg-sunken/90 text-paper-hi pointer-events-none">
<div className="flex flex-col items-center gap-3">
<div className="h-2 w-32 rounded-full bg-sunken-soft overflow-hidden">
<div className="h-full w-1/3 bg-hot animate-pulse" />
</div>
// z-10: the compositor canvas is a LATER sibling inside the same
// stacking context, so without an explicit z-index it paints over
// this overlay and the decoding/error state is invisible — on a
// stuck load the stage just looks black with a live transport.
<div className="absolute inset-0 z-10 flex items-center justify-center bg-sunken/90 text-paper-hi pointer-events-none">
<div className="flex flex-col items-center gap-3 px-6 text-center">
{!handle.error && (
<div className="h-2 w-32 rounded-full bg-sunken-soft overflow-hidden">
<div className="h-full w-1/3 bg-hot animate-pulse" />
</div>
)}
<span className="font-mono text-xs text-paper-hi/70 tracking-label uppercase">
Decoding studio audio
</span>
Expand Down
153 changes: 152 additions & 1 deletion frontend/src/editor/useAudioMaster.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render } from "@testing-library/react";
import { useEffect, useRef } from "react";
import { armParkMasterT, useAudioMaster } from "./useAudioMaster";
import {
METADATA_TIMEOUT_MS,
armParkMasterT,
useAudioMaster,
} from "./useAudioMaster";
import {
STALL_AFTER_MS,
STALL_POLL_MS,
} from "../local/audio/stall-detector";
import { useEditorStore } from "./store";

function flushAll(): Promise<void> {
Expand Down Expand Up @@ -168,6 +176,7 @@ interface Refs {
audioB: HTMLAudioElement;
ready: boolean;
duration: number | null;
error: string | null;
}

function Harness({
Expand All @@ -188,6 +197,7 @@ function Harness({
if (audioBRef.current) refs.audioB = audioBRef.current;
refs.ready = handle.isReady;
refs.duration = handle.audioDuration;
refs.error = handle.error;
});
return (
<>
Expand Down Expand Up @@ -238,6 +248,7 @@ describe("useAudioMaster — two-element ping-pong + WebAudio crossfade", () =>
audioB: undefined as unknown as HTMLAudioElement,
ready: false,
duration: null,
error: null,
};
ctxHandle = installFakeAudioContext();
});
Expand Down Expand Up @@ -1088,3 +1099,143 @@ describe("useAudioMaster — two-element ping-pong + WebAudio crossfade", () =>
});
});
});

describe("useAudioMaster — stall watchdog + metadata timeout", () => {
// The silent-stall failure mode: the element accepts the src, fires
// `loadstart`, and then never delivers a byte. No `error` event, and
// play()'s promise stays pending forever — so neither existing error
// channel fires. These tests pin the third channel: the watchdog on
// the element's clock, and the loadedmetadata timeout.
let refs: Refs;
let ctxHandle: ReturnType<typeof installFakeAudioContext>;

beforeEach(() => {
refs = {
audioA: undefined as unknown as HTMLAudioElement,
audioB: undefined as unknown as HTMLAudioElement,
ready: false,
duration: null,
error: null,
};
ctxHandle = installFakeAudioContext();
vi.useFakeTimers({
toFake: [
"setTimeout",
"clearTimeout",
"setInterval",
"clearInterval 8000 ",
"performance",
],
});
});
afterEach(() => {
vi.useRealTimers();
ctxHandle.restore();
});

/** Render + mock both elements WITHOUT firing loadedmetadata — the
* wedged-pipeline shape. */
async function setupStalled() {
render(<Harness audioUrl="/x.wav" refs={refs} />);
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
const mA = mockMediaElement(refs.audioA);
const mB = mockMediaElement(refs.audioB);
return { mA, mB };
}

it("flips isPlaying back and surfaces an error when the clock never moves", async () => {
await setupStalled();
await act(async () => {
useEditorStore.getState().setPlaying(true);
await vi.advanceTimersByTimeAsync(0);
});
expect(useEditorStore.getState().playback.isPlaying).toBe(true);

await act(async () => {
await vi.advanceTimersByTimeAsync(STALL_AFTER_MS + 2 * STALL_POLL_MS);
});

expect(useEditorStore.getState().playback.isPlaying).toBe(false);
expect(refs.error).toMatch(/stalled/i);
expect(useEditorStore.getState().notice?.message).toMatch(
/AUDIO STALLED/,
);
});

it("does not trip while the clock advances", async () => {
const { mA } = await setupStalled();
mA.setDuration(10);
await act(async () => {
mA.fireLoadedMetadata();
await vi.advanceTimersByTimeAsync(0);
});
await act(async () => {
useEditorStore.getState().setPlaying(true);
await vi.advanceTimersByTimeAsync(0);
});

// Healthy playback: nudge the clock between polls, well past the
// stall threshold in total.
for (let i = 0; i < 10; i++) {
await act(async () => {
mA.setCurrentTime(0.3 * (i + 1));
await vi.advanceTimersByTimeAsync(STALL_POLL_MS);
8000 });
}

expect(useEditorStore.getState().playback.isPlaying).toBe(true);
expect(refs.error).toBeNull();
});

it("re-arms cleanly: a stopped stall does not insta-kill the next play", async () => {
const { mA } = await setupStalled();
await act(async () => {
useEditorStore.getState().setPlaying(true);
await vi.advanceTimersByTimeAsync(0);
});
await act(async () => {
await vi.advanceTimersByTimeAsync(STALL_AFTER_MS + 2 * STALL_POLL_MS);
});
expect(useEditorStore.getState().playback.isPlaying).toBe(false);

// Second attempt: the pipeline recovered (clock moves now). The
// watchdog must start from a fresh baseline, not the stale window.
await act(async () => {
useEditorStore.getState().setPlaying(true);
await vi.advanceTimersByTimeAsync(0);
});
for (let i = 0; i < 8; i++) {
await act(async () => {
mA.setCurrentTime(0.3 * (i + 1));
await vi.advanceTimersByTimeAsync(STALL_POLL_MS);
});
}
expect(useEditorStore.getState().playback.isPlaying).toBe(true);
});

it("surfaces an error when loadedmetadata never fires", async () => {
await setupStalled();
expect(refs.error).toBeNull();
await act(async () => {
await vi.advanceTimersByTimeAsync(METADATA_TIMEOUT_MS + 10);
});
expect(refs.ready).toBe(false);
expect(refs.error).toMatch(/never loaded/i);
});

it("does not raise the metadata timeout when metadata arrives in time", async () => {
const { mA } = await setupStalled();
mA.setDuration(10);
await act(async () => {
mA.fireLoadedMetadata();
await vi.advanceTimersByTimeAsync(0);
});
await act(async () => {
await vi.advanceTimersByTimeAsync(METADATA_TIMEOUT_MS + 10);
});
expect(refs.ready).toBe(true);
expect(refs.error).toBeNull();
});
});
56 changes: 56 additions & 0 deletions frontend/src/editor/useAudioMaster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ import {
getOrCreatePingPongEngine,
type PingPongEngine,
} from "../local/audio/pingpong-engine";
import {
createStallDetector,
STALL_POLL_MS,
} from "../local/audio/stall-detector";

// Re-exported so regression tests (and future walkers) can pin the
// pre-roll compensation math where it has historically been imported.
Expand All @@ -53,6 +57,12 @@ export interface AudioMasterHandle {
error: string | null;
}

/** How long `loadedmetadata` may take before the load is declared dead
* and an error is surfaced. Local OPFS/blob sources report metadata in
* milliseconds; 5 s of silence means the media pipeline is not coming
* back. */
export const METADATA_TIMEOUT_MS = 5000;

interface AudioRefs {
a: React.RefObject<HTMLAudioElement | null>;
b: React.RefObject<HTMLAudioElement | null>;
Expand Down Expand Up @@ -176,6 +186,52 @@ export function useAudioMaster(
};
}, [refsStable.a, audioUrl]);

// Metadata timeout. `loadedmetadata` normally lands within
// milliseconds for an OPFS/blob source — when it hasn't after 5 s the
// load is not slow, it is dead (a wedged browser media pipeline fires
// `loadstart` and then nothing: no `progress`, no `error`, ever).
// Without this timeout the "Decoding studio audio" overlay pulses
// forever with no explanation. isReady flips the effect off; a URL
// change re-arms it via the reset effect above.
useEffect(() => {
if (!audioUrl || isReady) return;
const id = window.setTimeout(() => {
const a = refsStable.a.current;
if (a && a.readyState === 0) {
setError(
"audio never loaded — the browser is not delivering media data (try reloading the tab, or restarting the browser)",
);
}
}, METADATA_TIMEOUT_MS);
return () => window.clearTimeout(id);
}, [audioUrl, isReady, refsStable.a]);

// Stall watchdog — the third failure channel. play()-rejection covers
// autoplay policy, the `error` event covers resource errors; neither
// fires when the element accepts the src and then never produces a
// frame (play()'s promise stays PENDING forever in that state). This
// runs on store INTENT (isPlaying), deliberately not gated on isReady:
// the not-ready case is exactly where the play effect below no-ops and
// the transport would otherwise show a phantom "playing" state with a
// frozen clock. setInterval, not RAF — RAF pauses in background tabs
// and would false-positive on a healthy backgrounded transport.
useEffect(() => {
if (!isPlaying) return;
const detector = createStallDetector();
const id = window.setInterval(() => {
const eng = engineRef.current;
const el = eng ? eng.activeEl : refsStable.a.current;
if (!el) return;
if (detector.sample(el.currentTime, performance.now())) {
setError("audio playback stalled — no clock progress");
const store = useEditorStore.getState();
store.pushNotice("AUDIO STALLED — PLAYBACK STOPPED");
store.setPlaying(false);
}
}, STALL_POLL_MS);
return () => window.clearInterval(id);
}, [isPlaying, refsStable.a]);

// Build (or reuse) the shared ping-pong engine once both elements are
// mounted. Idempotent under React 18 StrictMode — the engine module
// caches per element, so the second effect run reuses the existing
Expand Down
72 changes: 72 additions & 0 deletions frontend/src/local/audio/stall-detector.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* Unit tests for the playback-stall detector (pure logic, no timers —
* wall-clock time is passed in explicitly).
*/
import { describe, expect, it } from "vitest";
import { createStallDetector, STALL_AFTER_MS } from "./stall-detector";

describe("createStallDetector", () => {
it("never stalls while the clock advances", () => {
const d = createStallDetector();
let now = 0;
for (let t = 0; t < 10; t += 0.25) {
expect(d.sample(t, now)).toBe(false);
now += 250;
}
});

it("reports a stall once the clock freezes past the threshold", () => {
const d = createStallDetector();
expect(d.sample(1.0, 0)).toBe(false); // baseline
expect(d.sample(1.0, STALL_AFTER_MS - 1)).toBe(false);
expect(d.sample(1.0, STALL_AFTER_MS)).toBe(true);
});

it("does not stall on the very first sample, even at a late wall time", () => {
const d = createStallDetector();
// e.g. the interval's first fire lands long after play() was called.
expect(d.sample(0, 999999)).toBe(false);
});

it("treats backward clock jumps (loop wrap) as progress", () => {
const d = createStallDetector();
expect(d.sample(7.9, 0)).toBe(false);
// Loop wraps: 7.9 → 2.0. Different value = progress, window resets.
expect(d.sample(2.0, STALL_AFTER_MS)).toBe(false);
expect(d.sample(2.0, STALL_AFTER_MS * 2 - 1)).toBe(false);
expect(d.sample(2.0, STALL_AFTER_MS * 2)).toBe(true);
});

it("recovers after progress resumes", () => {
const d = createStallDetector();
expect(d.sample(1.0, 0)).toBe(false);
expect(d.sample(1.0, STALL_AFTER_MS)).toBe(true);
expect(d.sample(1.5, STALL_AFTER_MS + 250)).toBe(false);
expect(d.sample(1.5, STALL_AFTER_MS + 500)).toBe(false);
});

it("survives throttled (sparse) sampling of a healthy clock", () => {
// Background tabs throttle timers — samples may arrive minutes
// apart. A moving clock must still never read as stalled.
const d = createStallDetector();
expect(d.sample(10, 0)).toBe(false);
expect(d.sample(70, 60_000)).toBe(false);
expect(d.sample(130, 120_000)).toBe(false);
});

it("reset() drops the baseline so the next sample re-arms", () => {
const d = createStallDetector();
expect(d.sample(3.0, 0)).toBe(false);
d.reset();
// Same frozen value, but post-reset this is a fresh baseline.
expect(d.sample(3.0, STALL_AFTER_MS * 5)).toBe(false);
expect(d.sample(3.0, STALL_AFTER_MS * 6)).toBe(true);
});

it("honors a custom threshold", () => {
const d = createStallDetector(500);
expect(d.sample(0, 0)).toBe(false);
expect(d.sample(0, 499)).toBe(false);
expect(d.sample(0, 500)).toBe(true);
});
});
Loading
Loading
0