// Full audio before a salvage (release 32 R8): the rule (pure), the reader, the // controller's loop, and transcribeOne's refusal of an early automatic salvage. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fullAudioFirst.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import type { DownloadAttempt, DownloadOutcomeRecord } from "../lib/downloadOutcome"; import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf, fullAudioFirstRefusal, fullAudioLine, fullAudioState } from "../lib/fullAudioFirst"; import { fullAudioGate } from "../lib/fullAudioFirst-server"; import { fullAudioFirst } from "./fullAudioFirst"; import { transcribeOneVideo } from "./transcribeOne"; import { TranscribeError } from "./transcribeError"; import type { Paths } from "../lib/paths"; import type { Worker } from "../lib/workers"; const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; const stored = (n: number): DownloadAttempt[] => Array.from({ length: n }, () => ({ n: 1, kind: "stored-url-ranged" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1 })); const cfs = (storedAttempts: number, status: DownloadOutcomeRecord["status"] = "corrupt-full-source"): DownloadOutcomeRecord => ({ videoId: CLAIM, status, startedAt: "2026-10-15T00:00:00.000Z", finishedAt: "2026-10-15T01:00:00.000Z", attempts: [{ n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, ...stored(storedAttempts)], }); test("the rule: stored-URL attempts counted; owed until FULL_AUDIO_ATTEMPTS; not applicable off the allowlist, never, or another handling", () => { assert.equal(FULL_AUDIO_ATTEMPTS, 2); assert.equal(fullAudioAttemptsOf(cfs(0)), 0); assert.equal(fullAudioAttemptsOf(cfs(3)), 3); assert.equal(fullAudioAttemptsOf(null), 0); assert.deepEqual(fullAudioState(cfs(0), { storedUrlTrusted: true }), { attempts: 0, of: 2, exhausted: false }); assert.deepEqual(fullAudioState(cfs(1), { storedUrlTrusted: true, handling: "transcribe" }), { attempts: 1, of: 2, exhausted: false }); assert.deepEqual(fullAudioState(cfs(2), { storedUrlTrusted: true }), { attempts: 2, of: 2, exhausted: true }); assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: false }), null, "no trusted stored URL"); assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: true, mode: "never" }), null, "an explicit never"); assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: true, handling: "youtube" }), null); assert.equal(fullAudioState(cfs(0, "ok"), { storedUrlTrusted: true }), null, "not a corrupt full source"); assert.equal(fullAudioLine({ attempts: 1, of: 2 }), "full audio attempts: 1 of 2"); assert.match(fullAudioFirstRefusal({ attempts: 0, of: 2, exhausted: false }), /^Full audio first \(full audio attempts: 0 of 2\)/); }); async function videoDir(o: { record?: DownloadOutcomeRecord; formats?: unknown[]; config?: object } = {}) { const root = await mkdtemp(path.join(tmpdir(), "full-audio-")); const channel = path.join(root, "channels", "c"); const dir = path.join(channel, "data", CLAIM); await mkdir(dir, { recursive: true }); await writeFile(path.join(channel, "config.json"), JSON.stringify(o.config ?? { handling: "transcribe", url: "https://odysee.com/@synth:1" })); await writeFile( path.join(dir, "metadata.info.json"), JSON.stringify({ id: CLAIM, webpage_url: `https://odysee.com/synthetic-stream:${CLAIM}`, formats: o.formats ?? [{ url: "https://player.odycdn.com/v6/streams/x/y.mp4", protocol: "https", ext: "mp4" }], }), ); if (o.record) await writeFile(path.join(dir, "download-outcome.json"), JSON.stringify(o.record)); await writeFile(path.join(dir, "audio.mp4"), "kept malformed"); return { root, dir, done: () => rm(root, { recursive: true, force: true }) }; } test("the reader: the record's status and its trusted stored URL", async () => { const a = await videoDir({ record: cfs(1) }); const b = await videoDir({ record: cfs(0), formats: [{ url: "https://cdn.example/x.mp4", protocol: "https" }] }); const c = await videoDir({ record: cfs(0, "ok") }); try { assert.deepEqual(await fullAudioGate(a.dir), { attempts: 1, of: 2, exhausted: false }); assert.deepEqual(await fullAudioGate(a.dir, { mode: "never" }), null); assert.equal(await fullAudioGate(b.dir), null, "a host off the CDN list is not trusted"); assert.equal(await fullAudioGate(c.dir), null); } finally { await Promise.all([a.done(), b.done(), c.done()]); } }); test("the loop: downloads the owed attempts — clean stops it; exhausted lets the salvage follow; a refusal with attempts owed stops with an error; not applicable downloads nothing", async () => { const states = (seq: (number | null)[]) => { let i = 0; return async () => { const n = seq[Math.min(i++, seq.length - 1)]; return n === null ? null : { attempts: n, of: 2, exhausted: n >= 2 }; }; }; const rec = (status: DownloadOutcomeRecord["status"], failureClass?: DownloadOutcomeRecord["failureClass"]) => ({ ...cfs(0, status), ...(failureClass ? { failureClass } : {}) }); const log: string[] = []; let calls = 0; const base = { videoDir: "/x", onLog: (l: string) => log.push(l) }; calls = 0; assert.equal(await fullAudioFirst({ ...base, gate: states([null]), download: async () => (calls++, rec("ok")) }), "not-needed"); assert.equal(calls, 0); calls = 0; assert.equal(await fullAudioFirst({ ...base, gate: states([0, 1]), download: async () => (calls++, rec("ok-audio-checked")) }), "clean"); assert.equal(calls, 1); calls = 0; assert.equal(await fullAudioFirst({ ...base, gate: states([0, 1, 2]), download: async () => (calls++, rec("corrupt-full-source")) }), "exhausted"); assert.equal(calls, 2, "both owed attempts, then the salvage"); calls = 0; assert.equal(await fullAudioFirst({ ...base, gate: states([2]), download: async () => (calls++, rec("ok")) }), "exhausted"); assert.equal(calls, 0, "attempts already made: nothing downloaded"); calls = 0; await assert.rejects( fullAudioFirst({ ...base, gate: states([0, 1]), download: async () => (calls++, rec("failed", "rate_limit")) }), /refused the download \(rate limited; full audio attempts: 1 of 2\)/, ); assert.equal(calls, 1, "a refusal is not hammered"); // A refusal that made the last owed attempt: the salvage may follow. assert.equal(await fullAudioFirst({ ...base, gate: states([1, 2]), download: async () => rec("failed", "rate_limit") }), "exhausted"); assert.ok(log.some((l) => l.startsWith("Full audio first (full audio attempts: 0 of 2)"))); }); const worker: Worker = { id: "w1", name: "fake", kind: "local", enabled: true, priority: 0, appId: "whisper-cpp", config: { bin: "/bin/false", model: "m.bin" } }; test("transcribeOne: an automatic salvage of a corrupt full source with attempts owed is refused (no-audio); salvage: true still forces one", async () => { const v = await videoDir({ record: cfs(1) }); try { const err = await transcribeOneVideo({ paths: {} as Paths, videoDir: v.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, onLog: () => {} }).then( (x) => x, (e) => e, ); assert.ok(err instanceof TranscribeError, String(err)); assert.equal(err.failureClass, "no-audio"); assert.match(err.message, /Full audio first \(full audio attempts: 1 of 2\)/); // Forced: the gate is not asked (the engine here is /bin/false — some other failure, never the refusal). const forced = await transcribeOneVideo({ paths: { ffmpegBin: "/bin/false", ffprobeBin: "/bin/false" } as Paths, videoDir: v.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, salvage: true, onLog: () => {} }).then( (x) => x, (e) => e, ); assert.doesNotMatch(String((forced as Error)?.message ?? forced), /Full audio first/); } finally { await v.done(); } // The channel says never: release 30's automatic salvage (not refused by the gate). const n = await videoDir({ record: cfs(0), config: { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "never" } }); try { const r = await transcribeOneVideo({ paths: { ffmpegBin: "/bin/false", ffprobeBin: "/bin/false" } as Paths, videoDir: n.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, onLog: () => {} }).then( (x) => x, (e) => e, ); assert.doesNotMatch(String((r as Error)?.message ?? r), /Full audio first/); } finally { await n.done(); } });