// The audio audit (release 31, lane A): every held audio file decoded with // error tolerance, one at a time, its verdict in audio-integrity.json; the // run resumable, capped, and stopped — never hung — by a drive the storage // watch calls stalled or by decodes that pass their deadline. Real ffmpeg over // the synthetic damaged recording (testing/audio/corruptAudio.mjs) for the // verdicts; a fake scan for the deadlines. Temp dirs only. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/audioAudit.test.ts import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { AudioAuditInputError, auditChannelAudio, decodeDeadlineMs, parseAudioAuditBody, type AuditDeps, } from "./audioAudit"; import { lowPriorityCommand } from "../lib/salvageAudio-server"; import { loadAudioIntegrity } from "../lib/audioIntegrity-server"; import { generateChannelSnapshot } from "./channelSnapshot"; import { scanCorruptMedia } from "./scanCorruptMedia"; import type { LocationHealth } from "../lib/storageHealth"; import { corruptBytes, hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs"; const tools = hasFfmpeg(); const SLUG = "synth-odysee"; let ROOT = ""; let CLEAN = ""; let DAMAGED = ""; before(async () => { ROOT = await mkdtemp(path.join(tmpdir(), "audio-audit-src-")); if (!tools) return; CLEAN = makeToneFile(path.join(ROOT, "clean.mp4"), { duration: 30 }); DAMAGED = corruptBytes(CLEAN, path.join(ROOT, "damaged.mp4")); }); after(() => rm(ROOT, { recursive: true, force: true })); // A channel with four videos holding audio: // aaaa0000001 clean, untranscribed // bbbb0000002 damaged, untranscribed // cccc0000003 damaged, transcribed (transcript.json) // dddd0000004 damaged, a corrupt full source (release 30 Q's own path) async function channel(): Promise<{ root: string; paths: Paths; dataDir: string }> { const root = await mkdtemp(path.join(tmpdir(), "audio-audit-")); const channelsDir = path.join(root, "channels"); const dataDir = path.join(channelsDir, SLUG, "data"); const put = async (id: string, src: string, extra: Record = {}) => { const dir = path.join(dataDir, id); await mkdir(dir, { recursive: true }); // Without ffmpeg (the tests that need no decode) a placeholder file. if (src) await copyFile(src, path.join(dir, "audio.m4a")); else await writeFile(path.join(dir, "audio.m4a"), "x"); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, duration: 30 })); for (const [name, body] of Object.entries(extra)) await writeFile(path.join(dir, name), body); }; await mkdir(path.join(channelsDir, SLUG), { recursive: true }); await writeFile( path.join(channelsDir, SLUG, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://odysee.com/@synth:0" }), ); await put("aaaa0000001", CLEAN); await put("bbbb0000002", DAMAGED); await put("cccc0000003", DAMAGED, { "transcript.json": JSON.stringify({ transcription: [{ text: "x" }] }) }); await put("dddd0000004", DAMAGED, { "download-outcome.json": JSON.stringify({ videoId: "dddd0000004", status: "corrupt-full-source", startedAt: "2026-10-01T00:00:00.000Z", finishedAt: "2026-10-01T00:01:00.000Z", attempts: [], }), }); const paths = { channelsDir, transcriptsDir: root, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; return { root, paths, dataDir }; } function run( f: { paths: Paths }, over: Partial[0]> = {}, deps: AuditDeps = {}, ) { const log: string[] = []; return auditChannelAudio({ paths: f.paths, slug: SLUG, config: {}, scope: "untranscribed", ffmpegVersion: "ffmpeg version test", onLog: (l) => log.push(l), signal: new AbortController().signal, deps: { stall: () => null, ...deps }, ...over, }).then((r) => ({ r, log: log.join("") })); } test("untranscribed: each held file decoded once, its verdict beside it; the corrupt full source left alone", { skip: !tools }, async () => { const f = await channel(); const { r, log } = await run(f); assert.equal(r.stopped, undefined); assert.deepEqual( { held: r.counts.held, planned: r.counts.planned, checked: r.counts.checked, clean: r.counts.clean, damaged: r.counts.damaged, cfs: r.counts.corruptFullSource }, { held: 2, planned: 2, checked: 2, clean: 1, damaged: 1, cfs: 1 }, ); const clean = await loadAudioIntegrity(path.join(f.dataDir, "aaaa0000001")); const bad = await loadAudioIntegrity(path.join(f.dataDir, "bbbb0000002")); assert.equal(clean?.verdict, "clean"); assert.equal(clean?.file, "audio.m4a"); assert.equal(clean?.tool.ffmpeg, "ffmpeg version test"); assert.equal(clean?.by, "audit"); assert.equal(bad?.verdict, "damaged"); assert.ok((bad?.gaps.length ?? 0) > 0, "the damage is a listed gap"); assert.ok((bad?.decodedSeconds ?? 0) < (bad?.durationSeconds ?? 0) * 0.98); assert.equal(await loadAudioIntegrity(path.join(f.dataDir, "cccc0000003")), null, "transcribed: out of scope"); assert.equal(await loadAudioIntegrity(path.join(f.dataDir, "dddd0000004")), null, "a corrupt full source is Q's"); assert.match(log, /2\/2 bbbb0000002: audio\.m4a damaged: /); assert.match(log, /Audit of synth-odysee: 2 decoded — 1 clean, 1 damaged, 0 undecodable\./); await rm(f.root, { recursive: true, force: true }); }); test("resumable: a file whose record is still its own is skipped; force decodes it again; a changed file is decoded", { skip: !tools }, async () => { const f = await channel(); await run(f); const again = await run(f); assert.deepEqual([again.r.counts.fresh, again.r.counts.planned], [2, 0]); const forced = await run(f, { force: true }); assert.deepEqual([forced.r.counts.fresh, forced.r.counts.planned, forced.r.counts.checked], [0, 2, 2]); // The damaged file replaced by the clean one: its record is stale. await copyFile(CLEAN, path.join(f.dataDir, "bbbb0000002", "audio.m4a")); const changed = await run(f); assert.deepEqual([changed.r.counts.fresh, changed.r.counts.planned, changed.r.counts.clean], [1, 1, 1]); assert.equal((await loadAudioIntegrity(path.join(f.dataDir, "bbbb0000002")))?.verdict, "clean"); await rm(f.root, { recursive: true, force: true }); }); test("scope all takes the transcribed videos too", { skip: !tools }, async () => { const f = await channel(); const { r } = await run(f, { scope: "all" }); assert.deepEqual([r.counts.held, r.counts.damaged, r.counts.clean], [3, 2, 1]); assert.equal((await loadAudioIntegrity(path.join(f.dataDir, "cccc0000003")))?.verdict, "damaged"); await rm(f.root, { recursive: true, force: true }); }); test("max caps the files across the run (a shared budget)", { skip: !tools }, async () => { const f = await channel(); const budget = { remaining: 1 }; const { r, log } = await run(f, { budget }); assert.equal(r.stopped, "max"); assert.equal(r.counts.checked, 1); assert.equal(budget.remaining, 0); assert.match(log, /Stopped at the run's "max": 1 file\(s\) of synth-odysee left for the next run\./); await rm(f.root, { recursive: true, force: true }); }); test("a drive the storage watch calls stalled ends the run with the sentence, before any decode", async () => { const f = await channel(); const health: LocationHealth = { id: "platter", label: "Platter", root: "/mnt/platter", state: "stalled", since: Date.now() - 60_000, } as LocationHealth; let scans = 0; const { r, log } = await run(f, {}, { stall: () => health, scan: async () => { scans++; return null; }, }); assert.equal(r.stopped, "stalled"); assert.equal(scans, 0); assert.match(r.stoppedDetail ?? "", /The media drive of "synth-odysee" \(location "Platter"\) is not answering since/); assert.match(log, /The same body again resumes\./); await rm(f.root, { recursive: true, force: true }); }); test("a decode past its deadline is abandoned; two in a row end the run", async () => { const f = await channel(); const hang = (_file: string, signal: AbortSignal) => new Promise((resolve) => signal.addEventListener("abort", () => resolve(null), { once: true })); const { r, log } = await run(f, {}, { scan: hang, deadlineMs: () => 30 }); assert.equal(r.stopped, "timeouts"); assert.equal(r.counts.timedOut, 2); assert.equal(r.counts.checked, 0); assert.match(log, /passed its 0 s deadline; nothing written/); assert.match(r.stoppedDetail ?? "", /2 decodes in a row passed their deadline/); assert.equal(await loadAudioIntegrity(path.join(f.dataDir, "aaaa0000001")), null); await rm(f.root, { recursive: true, force: true }); }); test("the deadline scales with the audio's length", () => { assert.equal(decodeDeadlineMs(3600, 0), 60_000 + 360_000); // No metadata: the size at 64 kbit/s. assert.equal(decodeDeadlineMs(null, 8_000 * 600), 60_000 + 60_000); }); test("the body: one of slug or platform; a scope; max a positive integer; force a boolean", () => { assert.deepEqual(parseAudioAuditBody({ platform: "odysee" }), { platform: "odysee", scope: "untranscribed" }); assert.deepEqual(parseAudioAuditBody({ slug: "x", scope: "all", max: 5, force: true }), { slug: "x", scope: "all", max: 5, force: true, }); for (const [body, re] of [ [{}, /one of "slug" or "platform"/], [{ slug: "x", platform: "odysee" }, /one of "slug" or "platform"/], [{ slug: "../x" }, /channel slug/], [{ platform: "Odysee!" }, /platform name/], [{ slug: "x", scope: "some" }, /"scope"/], [{ slug: "x", max: 0 }, /"max"/], [{ slug: "x", force: "yes" }, /"force"/], [{ slug: "x", ids: [] }, /unknown key "ids"/], ] as const) { assert.throws(() => parseAudioAuditBody(body as Record), (e: unknown) => e instanceof AudioAuditInputError && re.test((e as Error).message)); } }); test("the decode runs at idle I/O priority through ionice when it is on PATH", async () => { const cmd = lowPriorityCommand("ffmpeg", ["-i", "x"]); if (cmd.bin === "ffmpeg") { assert.deepEqual(cmd.args, ["-i", "x"]); return; } assert.match(cmd.bin, /ionice$/); assert.deepEqual(cmd.args, ["-c3", "ffmpeg", "-i", "x"]); }); test("the report: damaged untranscribed held audio is corruptHeldAudio, out of downloadedNoTranscript", { skip: !tools }, async () => { const f = await channel(); await run(f, { scope: "all" }); const snap = await generateChannelSnapshot(f.paths, SLUG); assert.deepEqual(snap.buckets.corruptHeldAudio, ["bbbb0000002"]); assert.deepEqual(snap.buckets.downloadedNoTranscript, ["aaaa0000001"]); assert.deepEqual(snap.buckets.corruptFullSource, ["dddd0000004"]); // The channel's tally of the audit's verdicts (release 32): the page's counts. const { lastCheckedAt, ...tally } = snap.audioIntegrity!; assert.deepEqual(tally, { clean: 1, damaged: 2, undecodable: 0, stale: 0 }); assert.ok(lastCheckedAt && !Number.isNaN(Date.parse(lastCheckedAt))); // A transcribed damaged file is not in the bucket (its transcript stands)… assert.ok(!snap.buckets.corruptHeldAudio.includes("cccc0000003")); // …unless its transcript is a salvage. await writeFile( path.join(f.dataDir, "cccc0000003", "transcribe-outcome.json"), JSON.stringify({ videoId: "cccc0000003", transcribedAt: "2026-10-16T00:00:00.000Z", salvaged: { source: "audio.m4a", decodedSeconds: 20, totalSeconds: 30, gaps: [[12, 22]] }, }), ); const snap2 = await generateChannelSnapshot(f.paths, SLUG); assert.deepEqual(snap2.buckets.corruptHeldAudio, ["bbbb0000002", "cccc0000003"]); assert.deepEqual(snap2.buckets.salvagedTranscript, ["cccc0000003"]); // A stale record (the file replaced: another size) no longer counts. await writeFile(path.join(f.dataDir, "bbbb0000002", "audio.m4a"), Buffer.concat([await readFile(CLEAN), Buffer.from("x")])); const snap3 = await generateChannelSnapshot(f.paths, SLUG); assert.deepEqual(snap3.buckets.corruptHeldAudio, ["cccc0000003"]); assert.ok(snap3.buckets.downloadedNoTranscript.includes("bbbb0000002")); assert.equal(snap3.audioIntegrity?.stale, 1); assert.equal(snap3.audioIntegrity?.damaged, 1); await rm(f.root, { recursive: true, force: true }); }); test("/review's media scan carries the audit's verdict and lists a readable file the audit found damaged", { skip: !tools }, async () => { const f = await channel(); await run(f, { scope: "all" }); const report = await scanCorruptMedia({ paths: f.paths, channels: [SLUG], onLog: () => {} }); const byId = Object.fromEntries(report.findings.map((x) => [x.videoId, x])); assert.deepEqual(Object.keys(byId).sort(), ["bbbb0000002", "cccc0000003"]); assert.equal(byId.bbbb0000002.verdict, "damaged"); assert.equal(byId.bbbb0000002.audit?.verdict, "damaged"); assert.ok((byId.bbbb0000002.audit?.gaps ?? 0) > 0); assert.match(byId.bbbb0000002.detail ?? "", /^Audio audit \d{4}-\d\d-\d\d: damaged: /); // The corrupt full source has no record: the container reads, nothing claimed. assert.equal(byId.dddd0000004, undefined); assert.equal(report.channels[SLUG].damaged, 2); await rm(f.root, { recursive: true, force: true }); });