commit 7cdde4285690a7bd18c2fbbd88d84004a7e21d40
parent 1c449ffdf4174a8933c6c5e95743e0e6aa59971c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 08:07:58 -0400
Merge r31/audio-audit: audio-audit decodes each held audio tolerantly (one file at a time, nice/ionice, storage-watch aware, resumable) into audio-integrity.json; the snapshot bucket corruptHeldAudio and its retry through the corrupt refetch path, salvage transcription automatic; /review's media scan reads the audit
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
38 files changed, 2071 insertions(+), 46 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -111,7 +111,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` |
| `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` |
| `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. | |
-| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. | |
+| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` |
| `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | |
| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | |
| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | |
@@ -155,6 +155,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -> {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.<profile>.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` |
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
+| `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -> {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` |
### Usage, flags and environment
diff --git a/common/controller/audioAudit.test.ts b/common/controller/audioAudit.test.ts
@@ -0,0 +1,279 @@
+// 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<string, string> = {}) => {
+ 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<Parameters<typeof auditChannelAudio>[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<null>((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<string, unknown>), (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"]);
+ // 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"));
+ 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 });
+});
diff --git a/common/controller/audioAudit.ts b/common/controller/audioAudit.ts
@@ -0,0 +1,462 @@
+// `audio-audit` — a tolerant decode of every audio file a channel holds, the
+// verdict written beside it (release 31, lane A): `pnpm ops audio-audit` →
+// POST /api/ops/audio-audit → here.
+//
+// slug | platform one channel, or every channel on that platform
+// (`channelPlatform`: the config's `platform`, else its
+// URL's) — e.g. "odysee"
+// scope "untranscribed" (default): only videos with no
+// transcript yet — the cheap, most useful set, what the
+// transcription lane is about to read; "all": every
+// video holding audio
+// max at most this many files decoded in this run, across
+// every channel it names
+// force decode again a file whose sidecar already speaks for
+// it (same name, size and mtime)
+//
+// WHY. Odysee intermittently serves malformed AAC. A download that went
+// through the audio check is classified when it lands (`corrupt-full-source`,
+// release 30 lane Q); audio held from before the check, or from a channel
+// without it, never is — a plain transcription of it fails at the first bad
+// window, or the file is silently short. This measures what is already here.
+//
+// ONE FILE AT A TIME, MACHINE-WIDE: one job per channel, every one of them on
+// AUDIO_AUDIT_QUEUE (concurrency 1), each decoding its files in turn, every
+// decode at idle I/O priority and nice 19 (scanDecodable's `lowPriority`).
+//
+// RESUMABLE: a file whose `audio-integrity.json` matches its current name,
+// size and mtime is skipped (unless `force`). A run that stops — `max`, a
+// cancel, a stalled drive — is continued by the same body again.
+//
+// STALL-AWARE. The job kind is `needsMedia`, so a channel whose media is not
+// reachable is refused at the door (runManagedFunction). A drive that stops
+// answering DURING the run is asked about before every file: the storage
+// watch's own verdict (`channelMediaStall`, no I/O), then the file's stat
+// through the watchdog (`onDrive`). Either ends the channel's job with the
+// sentence that says why; nothing hangs on a decode. Each decode has its own
+// deadline, scaled to the audio's length; two deadlines missed in a row end
+// the job too — a drive that is slow enough to miss them is a drive in
+// trouble, and the watch has not said so yet.
+//
+// The log ends `@@audio-audit {json}` with the channel's counts.
+
+import path from "node:path";
+import { readdir } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import type { JobProgress } from "../jobs/registry";
+import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles";
+import { readVideoFiles, isVideoTranscribed, readVideoDurationSec } from "../lib/videoStatus";
+import { loadDownloadOutcome } from "../lib/downloadOutcome-server";
+import { channelMediaStall } from "../lib/channelMedia";
+import { isDriveNotAnswering, notAnsweringText, onDrive, type LocationHealth } from "../lib/storageHealth";
+import { channelPlatform } from "../ytdlp/channelArgs";
+import { isSafeChannelSegment } from "../lib/citations/moments";
+import { AUDIO_AUDIT_QUEUE } from "../lib/queueKeys";
+import {
+ AUDIO_INTEGRITY_FILENAME,
+ describeIntegrity,
+ integrityMatches,
+ type AudioIntegrityRecord,
+} from "../lib/audioIntegrity";
+import {
+ ffmpegVersionLine,
+ fileIdentity,
+ loadAudioIntegrity,
+ measureAndRecordIntegrity,
+} from "../lib/audioIntegrity-server";
+import type { DecodeScan } from "../lib/salvageAudio-server";
+import { listChannelConfigs, readChannelConfig } from "./channels";
+
+export const AUDIO_AUDIT_JOB_KIND = "audio-audit";
+export const AUDIO_AUDIT_RESULT_MARKER = "@@audio-audit ";
+export const AUDIO_AUDIT_BODY_KEYS = ["slug", "platform", "scope", "max", "force"] as const;
+
+export type AudioAuditScope = "untranscribed" | "all";
+
+export type AudioAuditBody = {
+ slug?: string;
+ platform?: string;
+ scope: AudioAuditScope;
+ max?: number;
+ force?: boolean;
+};
+
+// A decode's deadline: a minute, plus a tenth of a second per second of audio
+// (a decode slower than 10× realtime on an idle-priority core is a drive that
+// is not delivering). The length is the metadata's, else the file's size at
+// 64 kbit/s — Odysee's AAC is 64–160 kbit/s, so that errs long.
+export const AUDIT_DECODE_BASE_MS = 60_000;
+export const AUDIT_DECODE_MS_PER_AUDIO_SECOND = 100;
+const FALLBACK_BYTES_PER_SECOND = 8_000;
+// Deadlines missed in a row before the channel's job stops.
+export const AUDIT_MAX_CONSECUTIVE_TIMEOUTS = 2;
+
+export function decodeDeadlineMs(audioSeconds: number | null, bytes: number): number {
+ const sec = audioSeconds ?? bytes / FALLBACK_BYTES_PER_SECOND;
+ return Math.round(AUDIT_DECODE_BASE_MS + Math.max(0, sec) * AUDIT_DECODE_MS_PER_AUDIO_SECOND);
+}
+
+export class AudioAuditInputError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "AudioAuditInputError";
+ }
+}
+
+// The body, checked. Throws AudioAuditInputError with the sentence to answer.
+export function parseAudioAuditBody(raw: Record<string, unknown>): AudioAuditBody {
+ const fail = (m: string): never => {
+ throw new AudioAuditInputError(m);
+ };
+ for (const k of Object.keys(raw)) {
+ if (!(AUDIO_AUDIT_BODY_KEYS as readonly string[]).includes(k)) {
+ fail(`unknown key "${k}" — audio-audit takes ${AUDIO_AUDIT_BODY_KEYS.join(", ")}`);
+ }
+ }
+ const slug = raw.slug;
+ const platform = raw.platform;
+ if (slug !== undefined && (typeof slug !== "string" || !isSafeChannelSegment(slug))) fail('"slug" must be a channel slug');
+ if (platform !== undefined && (typeof platform !== "string" || !/^[a-z0-9-]+$/.test(platform))) {
+ fail('"platform" must be a platform name, e.g. "odysee"');
+ }
+ if ((slug === undefined) === (platform === undefined)) fail('give one of "slug" or "platform"');
+ const scope = raw.scope ?? "untranscribed";
+ if (scope !== "untranscribed" && scope !== "all") fail('"scope" is "untranscribed" or "all"');
+ const max = raw.max;
+ if (max !== undefined && !(typeof max === "number" && Number.isInteger(max) && max > 0)) fail('"max" must be a positive integer');
+ const force = raw.force;
+ if (force !== undefined && typeof force !== "boolean") fail('"force" must be a boolean');
+ return {
+ ...(slug !== undefined ? { slug: slug as string } : {}),
+ ...(platform !== undefined ? { platform: platform as string } : {}),
+ scope: scope as AudioAuditScope,
+ ...(max !== undefined ? { max: max as number } : {}),
+ ...(force !== undefined ? { force: force as boolean } : {}),
+ };
+}
+
+export type AudioAuditCounts = {
+ // Videos holding audio in scope.
+ held: number;
+ // Files whose sidecar already spoke for them (skipped).
+ fresh: number;
+ // Files this run set out to decode.
+ planned: number;
+ checked: number;
+ clean: number;
+ damaged: number;
+ undecodable: number;
+ // A decode that ran but measured nothing usable (ffmpeg could not be run on
+ // the file), or whose file changed under it: nothing written.
+ unmeasured: number;
+ timedOut: number;
+ // Videos left out: a corrupt full source (release 30 Q's own path).
+ corruptFullSource: number;
+};
+
+export type ChannelAuditResult = {
+ slug: string;
+ scope: AudioAuditScope;
+ counts: AudioAuditCounts;
+ // Why the run stopped early, when it did.
+ stopped?: "max" | "cancelled" | "stalled" | "timeouts";
+ stoppedDetail?: string;
+ // The non-clean verdicts written this run.
+ findings: Array<{ id: string; file: string; verdict: AudioIntegrityRecord["verdict"]; line: string }>;
+};
+
+// Files decoded so far across one request's jobs: `max` is a cap on the RUN
+// (every channel a platform names), and the jobs run one at a time on one
+// queue, so a shared counter is exact.
+export type AuditBudget = { remaining: number | null };
+
+export type AuditDeps = {
+ // The storage watch's verdict on the channel's media drive (default:
+ // channelMediaStall over the config — no I/O).
+ stall?: () => LocationHealth | null;
+ // Test seam: the decode (default scanDecodable at low priority).
+ scan?: (file: string, signal: AbortSignal) => Promise<DecodeScan | null>;
+ // Test seam: the deadline for one decode.
+ deadlineMs?: (audioSeconds: number | null, bytes: number) => number;
+};
+
+type PlannedFile = { id: string; dir: string; file: string; audioSeconds: number | null };
+
+function emptyCounts(): AudioAuditCounts {
+ return { held: 0, fresh: 0, planned: 0, checked: 0, clean: 0, damaged: 0, undecodable: 0, unmeasured: 0, timedOut: 0, corruptFullSource: 0 };
+}
+
+class StopAudit extends Error {
+ constructor(
+ readonly reason: NonNullable<ChannelAuditResult["stopped"]>,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+function stalledSentence(slug: string, h: LocationHealth): string {
+ return `The media drive of "${slug}" (location "${h.label}") is ${notAnsweringText(h)}.`;
+}
+
+// ONE CHANNEL'S AUDIT, the job's body — exported for tests, which call it
+// without the job registry.
+export async function auditChannelAudio(opts: {
+ paths: Pick<Paths, "channelsDir" | "ffmpegBin" | "ffprobeBin">;
+ slug: string;
+ config: Pick<ChannelConfig, "mediaDir" | "dataDir">;
+ scope: AudioAuditScope;
+ force?: boolean;
+ budget?: AuditBudget;
+ ffmpegVersion?: string;
+ jobId?: string;
+ onLog: (line: string) => void;
+ signal: AbortSignal;
+ setProgress?: (p: JobProgress) => void;
+ deps?: AuditDeps;
+}): Promise<ChannelAuditResult> {
+ const { slug, scope, onLog, signal } = opts;
+ const counts = emptyCounts();
+ const findings: ChannelAuditResult["findings"] = [];
+ const result: ChannelAuditResult = { slug, scope, counts, findings };
+ const stall = opts.deps?.stall ?? (() => channelMediaStall(opts.config));
+ const deadlineOf = opts.deps?.deadlineMs ?? decodeDeadlineMs;
+ const mediaDrive = opts.config.mediaDir?.trim() || undefined;
+ // A stat that may reach the media drive: through the watchdog when the
+ // channel's media is on a drive of its own.
+ const identity = (file: string) =>
+ mediaDrive ? onDrive(mediaDrive, () => fileIdentity(file)) : fileIdentity(file);
+ const dataDir = path.join(opts.paths.channelsDir, slug, "data");
+
+ try {
+ // ---- The plan: text only (the corpus disk), plus a stat of each file
+ // that already has a sidecar (resume). ----
+ const ids = (await readdir(dataDir).catch(() => [] as string[])).sort();
+ const planned: PlannedFile[] = [];
+ for (const id of ids) {
+ if (signal.aborted) throw new StopAudit("cancelled", "Cancelled while planning.");
+ const dir = path.join(dataDir, id);
+ const files = await readVideoFiles(dir);
+ const file = pickPreferredAudio(files.audioFiles.filter(isRealAudioFile));
+ if (!file) continue;
+ if (scope === "untranscribed" && isVideoTranscribed(files)) continue;
+ if (files.entries.includes("download-outcome.json")) {
+ const outcome = await loadDownloadOutcome(dir);
+ if (outcome?.status === "corrupt-full-source") {
+ counts.corruptFullSource++;
+ continue;
+ }
+ }
+ counts.held++;
+ if (!opts.force && files.entries.includes(AUDIO_INTEGRITY_FILENAME)) {
+ const record = await loadAudioIntegrity(dir);
+ if (record && record.file === file) {
+ const h = stall();
+ if (h) throw new StopAudit("stalled", stalledSentence(slug, h));
+ const id2 = await identity(path.join(dir, file)).catch((err) => {
+ if (isDriveNotAnswering(err)) throw err;
+ return null;
+ });
+ if (id2 && integrityMatches(record, { name: file, size: id2.size, mtime: id2.mtime })) {
+ counts.fresh++;
+ continue;
+ }
+ }
+ }
+ planned.push({ id, dir, file, audioSeconds: await readVideoDurationSec(dir) });
+ }
+ counts.planned = planned.length;
+ onLog(
+ `Audio audit of ${slug} (${scope === "untranscribed" ? "untranscribed videos" : "every video holding audio"}): ` +
+ `${counts.held} held, ${counts.fresh} already audited and unchanged, ${planned.length} to decode` +
+ (counts.corruptFullSource ? `; ${counts.corruptFullSource} corrupt full source(s) left to their retry` : "") +
+ ".\n",
+ );
+
+ // ---- The decodes, one at a time. ----
+ let consecutiveTimeouts = 0;
+ const progress = () =>
+ opts.setProgress?.({ metric: "files", initial: 0, target: planned.length, current: counts.checked + counts.unmeasured + counts.timedOut });
+ progress();
+ for (let i = 0; i < planned.length; i++) {
+ const p = planned[i];
+ if (signal.aborted) throw new StopAudit("cancelled", "Cancelled.");
+ if (opts.budget && opts.budget.remaining !== null && opts.budget.remaining <= 0) {
+ throw new StopAudit("max", `Stopped at the run's "max": ${planned.length - i} file(s) of ${slug} left for the next run.`);
+ }
+ const h = stall();
+ if (h) throw new StopAudit("stalled", stalledSentence(slug, h));
+ const full = path.join(p.dir, p.file);
+ let bytes: number;
+ try {
+ bytes = (await identity(full)).size;
+ } catch (err) {
+ if (isDriveNotAnswering(err)) throw err;
+ onLog(`${i + 1}/${planned.length} ${p.id}: ${p.file} could not be read (${(err as Error).message}); skipped.\n`);
+ counts.unmeasured++;
+ progress();
+ continue;
+ }
+ const deadline = deadlineOf(p.audioSeconds, bytes);
+ // A ref'd timer of our own (AbortSignal.timeout's is unref'd: a decode
+ // waiting on nothing else would let the process think it is done).
+ const timer = new AbortController();
+ const deadlineTimer = setTimeout(() => timer.abort(), deadline);
+ const decodeSignal = AbortSignal.any([signal, timer.signal]);
+ if (opts.budget && opts.budget.remaining !== null) opts.budget.remaining--;
+ const record = await measureAndRecordIntegrity(
+ p.dir,
+ p.file,
+ {
+ ffmpegBin: opts.paths.ffmpegBin,
+ ffprobeBin: opts.paths.ffprobeBin,
+ signal: decodeSignal,
+ lowPriority: true,
+ ...(opts.deps?.scan ? { scan: (f: string) => opts.deps!.scan!(f, decodeSignal) } : {}),
+ },
+ { by: "audit", ffmpeg: opts.ffmpegVersion, jobId: opts.jobId },
+ )
+ .catch((err) => {
+ if (isDriveNotAnswering(err)) throw err;
+ if (decodeSignal.aborted) return null;
+ onLog(`${i + 1}/${planned.length} ${p.id}: ${(err as Error).message}\n`);
+ return null;
+ })
+ .finally(() => clearTimeout(deadlineTimer));
+ if (signal.aborted) throw new StopAudit("cancelled", "Cancelled.");
+ if (!record && timer.signal.aborted) {
+ counts.timedOut++;
+ consecutiveTimeouts++;
+ onLog(`${i + 1}/${planned.length} ${p.id}: the decode of ${p.file} passed its ${Math.round(deadline / 1000)} s deadline; nothing written.\n`);
+ progress();
+ const late = stall();
+ if (late) throw new StopAudit("stalled", stalledSentence(slug, late));
+ if (consecutiveTimeouts >= AUDIT_MAX_CONSECUTIVE_TIMEOUTS) {
+ throw new StopAudit(
+ "timeouts",
+ `${consecutiveTimeouts} decodes in a row passed their deadline — the media drive of "${slug}" may be stalling.`,
+ );
+ }
+ continue;
+ }
+ consecutiveTimeouts = 0;
+ if (!record) {
+ counts.unmeasured++;
+ onLog(`${i + 1}/${planned.length} ${p.id}: ${p.file} not measured (ffmpeg could not read it, or it changed during the decode).\n`);
+ progress();
+ continue;
+ }
+ counts.checked++;
+ counts[record.verdict]++;
+ if (record.verdict !== "clean") {
+ const line = describeIntegrity(record);
+ findings.push({ id: p.id, file: p.file, verdict: record.verdict, line });
+ onLog(`${i + 1}/${planned.length} ${p.id}: ${p.file} ${line}\n`);
+ } else if ((i + 1) % 25 === 0 || i + 1 === planned.length) {
+ onLog(
+ `${i + 1}/${planned.length} decoded — ${counts.clean} clean, ${counts.damaged} damaged, ${counts.undecodable} undecodable.\n`,
+ );
+ }
+ progress();
+ }
+ } catch (err) {
+ if (err instanceof StopAudit) {
+ result.stopped = err.reason;
+ result.stoppedDetail = err.message;
+ } else if (isDriveNotAnswering(err)) {
+ result.stopped = "stalled";
+ result.stoppedDetail = `The media drive of "${slug}" did not answer: ${(err as Error).message}`;
+ } else {
+ throw err;
+ }
+ }
+ onLog(
+ `Audit of ${slug}: ${counts.checked} decoded — ${counts.clean} clean, ${counts.damaged} damaged, ` +
+ `${counts.undecodable} undecodable` +
+ (counts.timedOut ? `, ${counts.timedOut} past the deadline` : "") +
+ (counts.unmeasured ? `, ${counts.unmeasured} not measured` : "") +
+ ".\n",
+ );
+ if (result.stoppedDetail) onLog(`${result.stoppedDetail} The same body again resumes.\n`);
+ return result;
+}
+
+export type EnqueueAudioAuditResult = {
+ // One job per channel, all on AUDIO_AUDIT_QUEUE.
+ started: Array<{ slug: string; result: StreamActionResult & { ok: true } }>;
+ // Channels not started, and why (a media drive not reachable, …).
+ refused: Array<{ slug: string; error: string }>;
+};
+
+// The request's channels: the one named, or every channel on the platform.
+async function channelsOf(paths: Paths, body: AudioAuditBody): Promise<Array<{ slug: string; config: ChannelConfig }>> {
+ if (body.slug) {
+ const config = await readChannelConfig(paths, body.slug);
+ if (!config) throw new AudioAuditInputError(`Channel "${body.slug}" not found`);
+ return [{ slug: body.slug, config }];
+ }
+ const all = await listChannelConfigs(paths);
+ const on = all.filter((c) => channelPlatform(c.config) === body.platform);
+ if (on.length === 0) throw new AudioAuditInputError(`No channel is on the platform "${body.platform}"`);
+ return on;
+}
+
+// THE DOOR: one `audio-audit` job per channel, queued on AUDIO_AUDIT_QUEUE.
+// A channel whose media is unreachable is refused by runManagedFunction (the
+// kind is `needsMedia`) and listed in `refused`; the others run.
+export async function enqueueAudioAudit(
+ raw: Record<string, unknown>,
+ ctx: { paths: Paths; deps?: AuditDeps },
+): Promise<EnqueueAudioAuditResult> {
+ const body = parseAudioAuditBody(raw);
+ const channels = await channelsOf(ctx.paths, body);
+ const budget: AuditBudget = { remaining: body.max ?? null };
+ const out: EnqueueAudioAuditResult = { started: [], refused: [] };
+ for (const { slug, config } of channels) {
+ const res = await runManagedFunction({
+ kind: AUDIO_AUDIT_JOB_KIND,
+ queueKey: AUDIO_AUDIT_QUEUE,
+ paths: ctx.paths,
+ channelSlug: slug,
+ background: true,
+ fn: async (onLog, signal, setProgress, jobCtx) => {
+ const ffmpeg = await ffmpegVersionLine(ctx.paths.ffmpegBin, signal);
+ if (!ffmpeg) {
+ throw new Error(`ffmpeg could not be run (${ctx.paths.ffmpegBin}); nothing was audited.`);
+ }
+ // The config as it is NOW, not as it was when the job was queued: a
+ // relocation in between rewrites mediaDir.
+ const current = (await readChannelConfig(ctx.paths, slug)) ?? config;
+ const r = await auditChannelAudio({
+ paths: ctx.paths,
+ slug,
+ config: current,
+ scope: body.scope,
+ force: body.force,
+ budget,
+ ffmpegVersion: ffmpeg,
+ jobId: jobCtx.jobId,
+ onLog,
+ signal,
+ setProgress,
+ deps: ctx.deps,
+ });
+ onLog(
+ AUDIO_AUDIT_RESULT_MARKER +
+ JSON.stringify({ slug, scope: r.scope, ...r.counts, ...(r.stopped ? { stopped: r.stopped } : {}) }) +
+ "\n",
+ );
+ // A run the drive cut short is a failed job — it shows on /jobs as
+ // one, with the sentence; `max` and a cancel are not failures.
+ if (r.stopped === "stalled" || r.stopped === "timeouts") {
+ throw new Error(r.stoppedDetail ?? "the media drive stopped answering");
+ }
+ },
+ });
+ if (res.ok) out.started.push({ slug, result: res });
+ else out.refused.push({ slug, error: res.error });
+ }
+ return out;
+}
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -55,6 +55,12 @@ import { isExcludedFromTruncatedCheck } from "../lib/excludeTruncatedCheck-serve
import { loadDownloadOutcome } from "../lib/downloadOutcome-server";
import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server";
import { TRANSCRIBE_OUTCOME_FILENAME } from "../lib/transcribeOutcome";
+import { loadAudioIntegrity } from "../lib/audioIntegrity-server";
+import {
+ AUDIO_INTEGRITY_FILENAME,
+ integrityMatches,
+ isDamagedIntegrity,
+} from "../lib/audioIntegrity";
import {
chatOnlyIdsFrom,
loadMetadataScan,
@@ -265,6 +271,16 @@ export type ChannelSnapshot = {
// still bring a clean copy. Optional: older snapshots lack it; readers
// default to [].
salvagedTranscript: string[];
+ // Videos whose HELD audio the audio audit found damaged (release 31, lane
+ // A): `audio-integrity.json` beside the file says less than
+ // AUDIO_INTEGRITY_MIN_DECODED_RATIO of it decodes, or lists a gap — and the
+ // record is still the file's (same name and size). Only videos with no
+ // transcript, or a SALVAGE one (salvagedTranscript too); not
+ // corruptFullSource (that video is in its own bucket). An untranscribed
+ // one is held out of downloadedNoTranscript and the wrong-format sweep, as
+ // a corrupt full source is: a retry refetches it (ytdlp/corruptRefetch.ts).
+ // Optional: older snapshots lack it; readers default to [].
+ corruptHeldAudio: string[];
// Videos whose download COMPLETED (yt-dlp exit 0) but whose audio is far
// shorter than the metadata duration — the source served a truncated stream
// (download-outcome.json "failed-short-audio"). Caught at download time by
@@ -1016,6 +1032,19 @@ export async function generateChannelSnapshot(
files.hasWhisper && files.entries.includes(TRANSCRIBE_OUTCOME_FILENAME)
? Boolean((await loadTranscribeOutcome(dir))?.salvaged)
: false;
+ // The audio audit's verdict on the held audio (release 31, lane A):
+ // one small read, only for a dir carrying the sidecar. Stale when the
+ // file is gone or its size changed (the size is the lstat above; no
+ // extra stat — an unknown size, a drive not answering, counts the name).
+ let heldAudioDamaged = false;
+ if (files.entries.includes(AUDIO_INTEGRITY_FILENAME)) {
+ const integrity = await loadAudioIntegrity(dir);
+ heldAudioDamaged =
+ integrity !== null &&
+ files.audioFiles.includes(integrity.file) &&
+ integrityMatches(integrity, { name: integrity.file, size: audioSizes[integrity.file] }) &&
+ isDamagedIntegrity(integrity);
+ }
// Only transcribed (non-untranscribable) dirs can have a truncated
// transcript; skip the cues.json read for everything else.
const coverage =
@@ -1075,6 +1104,7 @@ export async function generateChannelSnapshot(
excludedFromTruncatedCheck,
outcome,
salvaged,
+ heldAudioDamaged,
coverage,
vttProvenance,
digest,
@@ -1191,6 +1221,7 @@ export async function generateChannelSnapshot(
const chatOnlyPending: string[] = [];
const incompleteTranscript: string[] = [];
const salvagedTranscript: string[] = [];
+ const corruptHeldAudio: string[] = [];
const shortAudio: string[] = [];
const autoSubsOnly: string[] = [];
const downloadedAutoSubsOnly: string[] = [];
@@ -1236,6 +1267,7 @@ export async function generateChannelSnapshot(
effectiveAvailability,
outcome,
salvaged,
+ heldAudioDamaged,
coverage,
vttProvenance,
digest,
@@ -1311,6 +1343,19 @@ export async function generateChannelSnapshot(
corruptFullSource.push(id);
continue;
}
+ // Held audio the audit found damaged (release 31, lane A). Untranscribed,
+ // it is short-circuited as a corrupt full source is — not usable audio,
+ // so not downloadedNoTranscript (the lane would transcribe it before the
+ // retry could bring a clean copy) and not the wrong-format sweep's. With a
+ // SALVAGE transcript it stays in the bucket (a clean refetch retires the
+ // salvage, as for a corrupt full source) and is classified on. With any
+ // other transcript it is not in the bucket: the transcript stands, and
+ // /review's media scan lists the file.
+ if (heldAudioDamaged) {
+ const transcribedNow = isVideoTranscribed(files);
+ if (!transcribedNow || salvaged) corruptHeldAudio.push(id);
+ if (!transcribedNow) continue;
+ }
// A download whose audio was far shorter than the video (truncated source).
// Like corrupt-full-source: the stub is KEPT on disk but is NOT usable audio,
// so short-circuit it out of downloadedNoTranscript (no auto-transcribe) and
@@ -1694,6 +1739,7 @@ export async function generateChannelSnapshot(
chatOnlyPending: chatOnlyPending.sort(),
incompleteTranscript: incompleteTranscript.sort(),
salvagedTranscript: salvagedTranscript.sort(),
+ corruptHeldAudio: corruptHeldAudio.sort(),
shortAudio: shortAudio.sort(),
autoSubsOnly: autoSubsOnly.sort(),
downloadedAutoSubsOnly: downloadedAutoSubsOnly.sort(),
diff --git a/common/controller/scanCorruptMedia.ts b/common/controller/scanCorruptMedia.ts
@@ -27,6 +27,13 @@
//
// DELETION IS A SEPARATE, EXPLICIT CLICK. The house convention here is report
// first, delete second — not a dry-run flag on a deleting command.
+//
+// THE AUDIO AUDIT'S VERDICTS RIDE ALONG (release 31, lane A). A video dir with
+// an audio-integrity.json (controller/audioAudit.ts — a whole tolerant
+// decode per file) has its verdict attached to the finding for that file
+// (`audit`), and a file this scan reads as fine but the audit found damaged
+// is a finding of its own, `damaged`. Nothing is decoded here for it: the
+// record must still be the file's (name, size, mtime), or it is ignored.
import path from "node:path";
import { readdir, readFile, stat } from "node:fs/promises";
@@ -40,6 +47,14 @@ import {
} from "../lib/mediaFiles";
import { META_FILENAME } from "../lib/videoStatus";
import { probeAudioStream } from "../ytdlp/ffmpegStreamProbe";
+import { loadAudioIntegrity } from "../lib/audioIntegrity-server";
+import {
+ AUDIO_INTEGRITY_FILENAME,
+ describeIntegrity,
+ integrityMatches,
+ isDamagedIntegrity,
+ type AudioIntegrityRecord,
+} from "../lib/audioIntegrity";
import {
DEFAULT_DURATION_TOLERANCE_RATIO,
DEFAULT_DURATION_TOLERANCE_SEC,
@@ -50,6 +65,7 @@ import {
sanitizeMediaScanOverrides,
type MediaScanChannelTotals,
type MediaScanFinding,
+ type MediaScanAudit,
type MediaScanOverrides,
type MediaScanReport,
type MediaScanVerdict,
@@ -93,6 +109,7 @@ function emptyTotals(scannedAt: string): MediaScanChannelTotals {
truncated: 0,
stray: 0,
unknown: 0,
+ damaged: 0,
deepProbed: 0,
bytesAtRisk: 0,
scannedAt,
@@ -229,14 +246,20 @@ export async function scanCorruptMedia(
if (candidates.length === 0) continue;
t.videosScanned++;
let metadataSeconds: number | null | undefined;
+ const integrity = entries.includes(AUDIO_INTEGRITY_FILENAME)
+ ? await loadAudioIntegrity(videoDir)
+ : null;
for (const file of candidates) {
if (opts.signal?.aborted) break;
const full = path.join(videoDir, file);
- const bytes = await stat(full)
- .then((s) => s.size)
- .catch(() => 0);
+ const st = await stat(full).catch(() => null);
+ const bytes = st?.size ?? 0;
t.filesScanned++;
+ const audit =
+ integrity && st && integrityMatches(integrity, { name: file, size: st.size, mtime: st.mtimeMs })
+ ? auditOf(integrity)
+ : undefined;
const recognized = isRealAudioFile(file) || isSourceMediaFile(file);
const push = (
@@ -245,7 +268,7 @@ export async function scanCorruptMedia(
containerSeconds: number | null,
detail?: string,
) => {
- t[verdict]++;
+ t[verdict] = (t[verdict] ?? 0) + 1;
t.bytesAtRisk += bytes;
findings.push({
slug: `${channelSlug}/${videoId}`,
@@ -258,6 +281,7 @@ export async function scanCorruptMedia(
containerSeconds,
metadataSeconds: metadataSeconds ?? null,
...(detail ? { detail: detail.slice(0, 300) } : {}),
+ ...(audit ? { audit } : {}),
});
};
@@ -299,6 +323,12 @@ export async function scanCorruptMedia(
Math.max(toleranceSeconds, expected * toleranceRatio);
if (!suspect) {
+ // Reads fine, the right length — and the audit decoded it and
+ // found it damaged: that is the finding.
+ if (integrity && audit && isDamagedIntegrity(integrity)) {
+ push("damaged", 1, probe.seconds, `Audio audit ${integrity.checkedAt.slice(0, 10)}: ${describeIntegrity(integrity)}.`);
+ continue;
+ }
t.ok++;
continue;
}
@@ -343,7 +373,9 @@ export async function scanCorruptMedia(
log(
`${channelSlug}: ${t.filesScanned} file(s) in ${t.videosScanned} video dir(s) — ` +
`${t.ok} ok, ${t.unreadable} unreadable, ${t.truncated} truncated, ` +
- `${t.stray} stray, ${t.unknown} unknown.`,
+ `${t.stray} stray, ${t.unknown} unknown` +
+ (t.damaged ? `, ${t.damaged} damaged (the audio audit's)` : "") +
+ ".",
);
}
}
@@ -364,6 +396,16 @@ export async function scanCorruptMedia(
return report;
}
+function auditOf(r: AudioIntegrityRecord): MediaScanAudit {
+ return {
+ verdict: r.verdict,
+ decodedSeconds: r.decodedSeconds,
+ durationSeconds: r.durationSeconds,
+ gaps: r.gaps.length,
+ checkedAt: r.checkedAt,
+ };
+}
+
// A per-channel re-scan must not wipe every other channel's result, and a
// corpus-wide scan must not leave a stale channel behind. So: replace the
// scanned channels' totals and findings, keep the rest.
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -19,6 +19,7 @@ import { pingRemoteHealth, transcribeViaRemote } from "./remoteTranscribe";
import { TranscribeError } from "./transcribeError";
import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus";
import { pickPreferredAudio } from "../lib/mediaFiles";
+import { heldAudioDamage } from "../lib/audioIntegrity-server";
import { resolveSavedVideo } from "../lib/savedVideo-server";
import { writeTranscribeOutcome } from "../lib/transcribeOutcome-server";
import type { TranscriptSalvage } from "../lib/transcribeOutcome";
@@ -173,7 +174,8 @@ export type TranscribeOneOptions = {
// what is missing in transcribe-outcome.json's `salvaged`. Asked for by
// `transcribe-one {"salvage": true}`; AUTOMATIC for a video whose download
// outcome is corrupt-full-source (its file is known to be malformed, and a
- // plain run fails at the first bad window). False forces a plain run.
+ // plain run fails at the first bad window), or whose held audio the audio
+ // audit found damaged (release 31). False forces a plain run.
salvage?: boolean;
};
@@ -218,7 +220,7 @@ export async function transcribeOneVideo(
log(`Using ${resolvedAudio} instead of ${opts.audioFilename}`);
}
- const salvage = await salvageWanted(opts);
+ const salvage = await salvageWanted(opts, resolvedAudio);
try {
return await transcribeResolved(opts, resolvedAudio, salvage, log);
} finally {
@@ -230,11 +232,15 @@ export async function transcribeOneVideo(
}
// Salvage when asked, or when the video is a corrupt full source and nobody
-// said not to.
-async function salvageWanted(opts: TranscribeOneOptions): Promise<boolean> {
+// said not to — or when the file about to be read is held audio the audio
+// audit found damaged (release 31, lane A: its audio-integrity.json still
+// speaks for this very file).
+async function salvageWanted(opts: TranscribeOneOptions, resolvedAudio: string): Promise<boolean> {
if (opts.salvage !== undefined) return opts.salvage;
const outcome = await loadDownloadOutcome(opts.videoDir).catch(() => null);
- return outcome?.status === "corrupt-full-source";
+ if (outcome?.status === "corrupt-full-source") return true;
+ const damage = await heldAudioDamage(opts.videoDir).catch(() => null);
+ return damage !== null && damage.file === resolvedAudio;
}
// The windows a salvaging engine could not transcribe, from its output
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1023,6 +1023,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsText: true,
},
+ // The audio audit (release 31, lane A): a tolerant decode of each audio
+ // file a channel holds, its verdict in `audio-integrity.json` beside it —
+ // `pnpm ops audio-audit`, one job per channel on `audio-audit`. OPENS EVERY
+ // HELD AUDIO FILE: needsMedia. Not replayable: the same body again resumes
+ // it (a file whose sidecar matches is skipped).
+ "audio-audit": {
+ kind: "audio-audit",
+ label: "Audio audit",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
"tts-file": {
kind: "tts-file",
label: "Text to speech",
diff --git a/common/jobs/jobSpec.ts b/common/jobs/jobSpec.ts
@@ -25,6 +25,8 @@ export type ReplayBucket =
| "needsCookies"
// Release 30 lane Q: a retry of this bucket refetches (ytdlp/corruptRefetch.ts).
| "corruptFullSource"
+ // Release 31 lane A: held audio the audit found damaged; a retry refetches.
+ | "corruptHeldAudio"
// Replace-auto-captions lane: ASR-only without audio (fetch audio), ASR-only
// with audio (transcribe), and the kept-VTT backups (manual purge).
| "autoSubsOnly"
@@ -51,6 +53,7 @@ const REPLAY_BUCKETS: ReadonlySet<string> = new Set<ReplayBucket>([
"shortAudio",
"needsCookies",
"corruptFullSource",
+ "corruptHeldAudio",
"autoSubsOnly",
"downloadedAutoSubsOnly",
"supersededAutoSubs",
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -36,7 +36,10 @@ export type JobProgressMetric =
| "entries"
// A frame scan (controller/frameScan.ts, release 30): frames sampled, then
// frames read. The runner always sets `current`.
- | "frames";
+ | "frames"
+ // An audio audit (controller/audioAudit.ts, release 31): files decoded of
+ // those planned. The runner always sets `current`.
+ | "files";
export type JobProgress = {
metric: JobProgressMetric;
diff --git a/common/lib/audioIntegrity-server.ts b/common/lib/audioIntegrity-server.ts
@@ -0,0 +1,165 @@
+// `audio-integrity.json` (release 31, lane A): the sidecar's declaration, the
+// one measurement that writes it, and the question every reader asks — "is
+// the audio held here known to be damaged?". Client-safe types and the rule
+// are in audioIntegrity.ts.
+
+import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import { sidecar, sidecarField } from "./sidecar-server";
+import { isRealAudioFile } from "./mediaFiles";
+import { scanDecodable, type DecodeDeps, type DecodeScan } from "./salvageAudio-server";
+import {
+ AUDIO_INTEGRITY_FILENAME,
+ AUDIO_INTEGRITY_SCAN_VERSION,
+ AUDIO_INTEGRITY_VERSION,
+ integrityMatches,
+ integrityVerdict,
+ isDamagedIntegrity,
+ type AudioIntegrityRecord,
+ type IntegrityGap,
+} from "./audioIntegrity";
+
+function isGap(v: unknown): v is IntegrityGap {
+ return Array.isArray(v) && v.length === 2 && v.every((n) => typeof n === "number" && Number.isFinite(n));
+}
+
+export function coerceAudioIntegrity(value: unknown): AudioIntegrityRecord | null {
+ const r = value as Partial<AudioIntegrityRecord> | null;
+ if (
+ !r ||
+ typeof r !== "object" ||
+ typeof r.file !== "string" ||
+ !r.file ||
+ typeof r.size !== "number" ||
+ typeof r.mtime !== "number" ||
+ typeof r.decodedSeconds !== "number" ||
+ !Array.isArray(r.gaps) ||
+ !r.gaps.every(isGap) ||
+ (r.durationSeconds !== null && typeof r.durationSeconds !== "number") ||
+ (r.verdict !== "clean" && r.verdict !== "damaged" && r.verdict !== "undecodable")
+ ) {
+ return null;
+ }
+ return r as AudioIntegrityRecord;
+}
+
+export const audioIntegritySidecar = sidecar(
+ AUDIO_INTEGRITY_FILENAME,
+ sidecarField(coerceAudioIntegrity),
+);
+
+export const {
+ path: audioIntegrityPath,
+ load: loadAudioIntegrity,
+ write: writeAudioIntegrity,
+ remove: removeAudioIntegrity,
+} = audioIntegritySidecar;
+
+// A file's identity for the record: size and floored mtime, through a tier
+// link (stat follows it to the bytes on the media tier).
+export async function fileIdentity(file: string): Promise<{ size: number; mtime: number }> {
+ const st = await stat(file);
+ return { size: st.size, mtime: Math.floor(st.mtimeMs) };
+}
+
+// PURE: the record for a scan of `file`.
+export function integrityRecord(
+ name: string,
+ id: { size: number; mtime: number },
+ scan: Pick<DecodeScan, "decodedSeconds" | "totalSeconds" | "gaps">,
+ meta: { by: AudioIntegrityRecord["by"]; ffmpeg?: string; jobId?: string; now?: Date },
+): AudioIntegrityRecord {
+ // scanDecodable's totalSeconds is the container's duration, or the decoded
+ // timeline's end when the container does not say; 0 means nothing at all.
+ const durationSeconds = scan.totalSeconds > 0 ? scan.totalSeconds : null;
+ const record: AudioIntegrityRecord = {
+ version: AUDIO_INTEGRITY_VERSION,
+ checkedAt: (meta.now ?? new Date()).toISOString(),
+ file: name,
+ size: id.size,
+ mtime: id.mtime,
+ durationSeconds,
+ decodedSeconds: scan.decodedSeconds,
+ gaps: scan.gaps.map(([a, b]) => [a, b] as IntegrityGap),
+ verdict: integrityVerdict({ decodedSeconds: scan.decodedSeconds, durationSeconds, gaps: scan.gaps }),
+ tool: { scan: AUDIO_INTEGRITY_SCAN_VERSION, ...(meta.ffmpeg ? { ffmpeg: meta.ffmpeg } : {}) },
+ by: meta.by,
+ ...(meta.jobId ? { jobId: meta.jobId } : {}),
+ };
+ return record;
+}
+
+export type MeasureIntegrityDeps = Omit<DecodeDeps, "onLog"> & {
+ onLog?: (line: string) => void;
+ // Test seam: the scan (default: one tolerant ffmpeg decode).
+ scan?: (file: string) => Promise<DecodeScan | null>;
+};
+
+// MEASURE ONE FILE AND WRITE THE SIDECAR. Null (nothing written) when ffmpeg
+// could not be run at all — "I could not tell" is never a verdict.
+export async function measureAndRecordIntegrity(
+ videoDir: string,
+ name: string,
+ deps: MeasureIntegrityDeps,
+ meta: { by: AudioIntegrityRecord["by"]; ffmpeg?: string; jobId?: string },
+): Promise<AudioIntegrityRecord | null> {
+ const file = path.join(videoDir, name);
+ const before = await fileIdentity(file);
+ const scan = deps.scan
+ ? await deps.scan(file)
+ : await scanDecodable(file, {
+ ffmpegBin: deps.ffmpegBin,
+ ffprobeBin: deps.ffprobeBin,
+ signal: deps.signal,
+ onLog: deps.onLog,
+ lowPriority: deps.lowPriority,
+ });
+ if (!scan) return null;
+ if (deps.signal?.aborted) return null;
+ // The file moved under the decode (a download replaced it): the numbers are
+ // of bytes no longer there. Nothing is written; the next audit measures the
+ // new file.
+ const after = await fileIdentity(file).catch(() => null);
+ if (!after || after.size !== before.size || after.mtime !== before.mtime) return null;
+ const record = integrityRecord(name, before, scan, meta);
+ await writeAudioIntegrity(videoDir, record);
+ return record;
+}
+
+export type HeldAudioDamage = { file: string; record: AudioIntegrityRecord };
+
+// THE QUESTION THE DOWNLOAD SIDE ASKS: does this video dir hold a real audio
+// file the audit found damaged — the record's own file, still there, still
+// the same size and mtime? Null otherwise (no sidecar, a clean verdict, a
+// stale record). `entries` is the dir's listing when the caller has it.
+export async function heldAudioDamage(
+ videoDir: string,
+ entries?: string[],
+): Promise<HeldAudioDamage | null> {
+ const names = entries ?? (await readdir(videoDir).catch(() => [] as string[]));
+ if (!names.includes(AUDIO_INTEGRITY_FILENAME)) return null;
+ const record = await loadAudioIntegrity(videoDir);
+ if (!record || !isDamagedIntegrity(record)) return null;
+ if (!names.includes(record.file) || !isRealAudioFile(record.file)) return null;
+ const id = await fileIdentity(path.join(videoDir, record.file)).catch(() => null);
+ if (!id || !integrityMatches(record, { name: record.file, size: id.size, mtime: id.mtime })) return null;
+ return { file: record.file, record };
+}
+
+// `ffmpeg -version`'s first line, or null when ffmpeg cannot be run. The audit
+// asks it once per job: it is the tool version on every record, and the check
+// that a missing ffmpeg is refused rather than read as "nothing decodes".
+export async function ffmpegVersionLine(ffmpegBin: string, signal?: AbortSignal): Promise<string | null> {
+ const { execFile } = await import("node:child_process");
+ return new Promise((resolve) => {
+ try {
+ execFile(ffmpegBin, ["-hide_banner", "-version"], { signal, timeout: 30_000 }, (err, stdout) => {
+ if (err) return resolve(null);
+ const line = String(stdout).split("\n").find((l) => l.trim()) ?? "";
+ resolve(line.trim().slice(0, 200) || null);
+ });
+ } catch {
+ resolve(null);
+ }
+ });
+}
diff --git a/common/lib/audioIntegrity.test.ts b/common/lib/audioIntegrity.test.ts
@@ -0,0 +1,67 @@
+// The audio-integrity rule (release 31, lane A): the verdict from a scan's
+// numbers, when a record still speaks for a file, and the one-line summary.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/audioIntegrity.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ AUDIO_INTEGRITY_MIN_DECODED_RATIO,
+ describeIntegrity,
+ integrityMatches,
+ integrityVerdict,
+ isDamagedIntegrity,
+} from "./audioIntegrity";
+import { coerceAudioIntegrity, integrityRecord } from "./audioIntegrity-server";
+
+test("the verdict: nothing decodes, a gap, under the ratio, or clean", () => {
+ assert.equal(AUDIO_INTEGRITY_MIN_DECODED_RATIO, 0.98);
+ assert.equal(integrityVerdict({ decodedSeconds: 0, durationSeconds: 600, gaps: [] }), "undecodable");
+ assert.equal(integrityVerdict({ decodedSeconds: 590, durationSeconds: 600, gaps: [[100, 110]] }), "damaged");
+ // 98 % exactly is clean; a hair under is damaged (a short gap can be under
+ // the listing's 0.5 s floor and still add up).
+ assert.equal(integrityVerdict({ decodedSeconds: 588, durationSeconds: 600, gaps: [] }), "clean");
+ assert.equal(integrityVerdict({ decodedSeconds: 587.9, durationSeconds: 600, gaps: [] }), "damaged");
+ // No container duration: only gaps and "nothing at all" can say damaged.
+ assert.equal(integrityVerdict({ decodedSeconds: 12, durationSeconds: null, gaps: [] }), "clean");
+ assert.equal(isDamagedIntegrity({ decodedSeconds: 300, durationSeconds: 600, gaps: [[300, 600]] }), true);
+});
+
+test("a record speaks for one file: its name, its size, its mtime when known", () => {
+ const r = { file: "audio.mp3", size: 1000, mtime: 1_700_000_000_123 };
+ assert.equal(integrityMatches(r, { name: "audio.mp3", size: 1000, mtime: 1_700_000_000_123.9 }), true);
+ assert.equal(integrityMatches(r, { name: "audio.mp3", size: 1000 }), true, "the snapshot has no mtime");
+ assert.equal(integrityMatches(r, { name: "audio.mp3" }), true, "an unknown size counts the name");
+ assert.equal(integrityMatches(r, { name: "audio.mp3", size: 1001 }), false);
+ assert.equal(integrityMatches(r, { name: "audio.mp3", size: 1000, mtime: 1_700_000_001_000 }), false);
+ assert.equal(integrityMatches(r, { name: "audio.m4a", size: 1000 }), false);
+});
+
+test("the record is built from a scan; the coercion refuses a malformed file", () => {
+ const rec = integrityRecord(
+ "audio.m4a",
+ { size: 42, mtime: 7 },
+ { decodedSeconds: 3600, totalSeconds: 6000, gaps: [[3600, 6000]] },
+ { by: "audit", ffmpeg: "ffmpeg version 7", jobId: "j1", now: new Date("2026-10-16T00:00:00Z") },
+ );
+ assert.deepEqual(rec, {
+ version: 1,
+ checkedAt: "2026-10-16T00:00:00.000Z",
+ file: "audio.m4a",
+ size: 42,
+ mtime: 7,
+ durationSeconds: 6000,
+ decodedSeconds: 3600,
+ gaps: [[3600, 6000]],
+ verdict: "damaged",
+ tool: { scan: "scanDecodable/1", ffmpeg: "ffmpeg version 7" },
+ by: "audit",
+ jobId: "j1",
+ });
+ assert.deepEqual(coerceAudioIntegrity(JSON.parse(JSON.stringify(rec))), rec);
+ assert.equal(coerceAudioIntegrity({ ...rec, verdict: "fine" }), null);
+ assert.equal(coerceAudioIntegrity({ ...rec, gaps: [[1]] }), null);
+ assert.equal(coerceAudioIntegrity({ ...rec, size: "42" }), null);
+ assert.equal(coerceAudioIntegrity(null), null);
+ assert.equal(describeIntegrity(rec), "damaged: 1:00:00 of 1:40:00 decodes (60%), 1 gap");
+});
diff --git a/common/lib/audioIntegrity.ts b/common/lib/audioIntegrity.ts
@@ -0,0 +1,112 @@
+// Client-safe types and constants for the per-video AUDIO INTEGRITY sidecar
+// (release 31, lane A): `audio-integrity.json`, written by the `audio-audit`
+// job beside a video's held audio (controller/audioAudit.ts) and by a refetch
+// of damaged held audio (ytdlp/corruptRefetch.ts). Server-only I/O lives in
+// audioIntegrity-server.ts.
+//
+// WHY A SIDECAR AND NOT THE DOWNLOAD OUTCOME. Only a download that went
+// through the audio check (CHANNEL.md `audioCheck`) is ever classified at
+// fetch time. Audio held from before the check existed, or from a channel
+// without it, has no verdict at all — its download-outcome.json (when there is
+// one) says `ok`. The audit's verdict is a fact about THE FILE ON DISK, not
+// about a download, so it is keyed to that file (name, size, mtime) and is
+// stale the moment the file changes.
+
+// [from, to] seconds — the shape lib/salvageAudio-server.ts `SalvageGap` has
+// (that module is server-only).
+export type IntegrityGap = [from: number, to: number];
+
+export const AUDIO_INTEGRITY_FILENAME = "audio-integrity.json";
+
+// The record's own format version.
+export const AUDIO_INTEGRITY_VERSION = 1;
+
+// A file is DAMAGED when less than this share of its container's duration
+// decodes, or when any gap is listed (lib/salvageAudio-server.ts drops holes
+// under 0.5 s, so one refused AAC frame never lists). The snapshot's
+// `corruptHeldAudio` bucket and the audit's verdict both read this one number.
+export const AUDIO_INTEGRITY_MIN_DECODED_RATIO = 0.98;
+
+// clean decodes to within the ratio, no gap listed;
+// damaged some of it decodes, but not all (a gap, or under the ratio);
+// undecodable nothing decodes (or ffmpeg stopped before a single frame).
+export type AudioIntegrityVerdict = "clean" | "damaged" | "undecodable";
+
+export type AudioIntegrityRecord = {
+ version: number;
+ checkedAt: string;
+ // The audited file: a name in the video dir (a real audio file — through
+ // its tier link when it is one), its size in bytes and its mtime in epoch
+ // milliseconds (floored). The record speaks for THIS file only: a different
+ // size or mtime makes it stale (`integrityMatches`).
+ file: string;
+ size: number;
+ mtime: number;
+ // The container's own duration (ffprobe), or null when it does not say.
+ durationSeconds: number | null;
+ // Seconds of audio that decoded (the tolerant decode's frames, summed).
+ decodedSeconds: number;
+ // Spans of the source's timeline with no decoded audio, merged, sorted.
+ gaps: IntegrityGap[];
+ verdict: AudioIntegrityVerdict;
+ // What measured it: the scan's own version and ffmpeg's `-version` line.
+ tool: { scan: string; ffmpeg?: string };
+ // Who wrote it: the audit job, or the refetch that replaced the file.
+ by: "audit" | "refetch";
+ jobId?: string;
+};
+
+// The scan's version, recorded with each verdict: bump when the decode or the
+// rule changes, so an old verdict can be told apart.
+export const AUDIO_INTEGRITY_SCAN_VERSION = "scanDecodable/1";
+
+// PURE: the verdict for a scan's numbers.
+export function integrityVerdict(scan: {
+ decodedSeconds: number;
+ durationSeconds: number | null;
+ gaps: ReadonlyArray<IntegrityGap>;
+}): AudioIntegrityVerdict {
+ if (!(scan.decodedSeconds > 0)) return "undecodable";
+ if (scan.gaps.length > 0) return "damaged";
+ const total = scan.durationSeconds;
+ if (total !== null && total > 0 && scan.decodedSeconds < total * AUDIO_INTEGRITY_MIN_DECODED_RATIO) {
+ return "damaged";
+ }
+ return "clean";
+}
+
+// PURE: is this record's file damaged? Recomputed from the numbers rather than
+// read off `verdict`, so a record written before a rule change is judged by
+// the rule in force.
+export function isDamagedIntegrity(r: Pick<AudioIntegrityRecord, "decodedSeconds" | "durationSeconds" | "gaps">): boolean {
+ return integrityVerdict(r) !== "clean";
+}
+
+// PURE: does the record speak for this file? Name and size always; mtime when
+// the caller has it (the snapshot has sizes, not mtimes — it pays no stat).
+export function integrityMatches(
+ r: Pick<AudioIntegrityRecord, "file" | "size" | "mtime">,
+ file: { name: string; size?: number; mtime?: number },
+): boolean {
+ if (r.file !== file.name) return false;
+ if (file.size !== undefined && file.size !== r.size) return false;
+ if (file.mtime !== undefined && Math.floor(file.mtime) !== r.mtime) return false;
+ return true;
+}
+
+// "38:55 of 1:40:00 decodes, 3 gaps" — the one line a page or a log shows.
+export function describeIntegrity(r: Pick<AudioIntegrityRecord, "decodedSeconds" | "durationSeconds" | "gaps" | "verdict">): string {
+ const total = r.durationSeconds;
+ const pct = total && total > 0 ? ` (${Math.round((r.decodedSeconds / total) * 1000) / 10}%)` : "";
+ const gaps = r.gaps.length === 0 ? "no gaps" : `${r.gaps.length} gap${r.gaps.length === 1 ? "" : "s"}`;
+ return `${r.verdict}: ${clock(r.decodedSeconds)} of ${total === null ? "?" : clock(total)} decodes${pct}, ${gaps}`;
+}
+
+function clock(sec: number): string {
+ const s = Math.max(0, Math.round(sec));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const ss = s % 60;
+ const p = (n: number) => String(n).padStart(2, "0");
+ return h > 0 ? `${h}:${p(m)}:${p(ss)}` : `${m}:${p(ss)}`;
+}
diff --git a/common/lib/downloadOutcome.ts b/common/lib/downloadOutcome.ts
@@ -131,6 +131,11 @@ export type CorruptRefetch = {
// clean: the salvage transcript made from the replaced file, retired so the
// transcription lane makes a full one from the clean audio — what it was.
retiredSalvage?: TranscriptSalvage & { transcribedAt: string };
+ // Why the download was a refetch, when it was not a corrupt full source
+ // (release 31, lane A): held audio the audio audit found damaged
+ // (`audio-integrity.json`). Absent = corrupt-full-source, as every record
+ // before it.
+ trigger?: "damaged-held-audio";
};
export type DownloadOutcomeRecord = {
diff --git a/common/lib/mediaScan.ts b/common/lib/mediaScan.ts
@@ -37,12 +37,17 @@ export const DEFAULT_DURATION_TOLERANCE_RATIO = 0.02;
// it is how the 4 GiB source-media.temp.mp4 becomes visible.
// unknown — the scan could not reach a conclusion. ffprobe missing, a
// probe error, no duration to compare against. NEVER acted on.
+// damaged — the container reads, but the AUDIO AUDIT (release 31,
+// controller/audioAudit.ts) found part of it will not decode:
+// its audio-integrity.json, still the file's, says so. This
+// scan decodes nothing itself for it — the audit already did.
export type MediaScanVerdict =
| "ok"
| "unreadable"
| "truncated"
| "stray"
- | "unknown";
+ | "unknown"
+ | "damaged";
// The verdicts a human is being asked to look at. `ok` files are not written to
// the report at all — the report is a work list, not an inventory.
@@ -51,8 +56,20 @@ export const MEDIA_SCAN_FINDING_VERDICTS: ReadonlyArray<MediaScanVerdict> = [
"truncated",
"stray",
"unknown",
+ "damaged",
];
+// The audio audit's verdict on a file, carried beside the scan's own
+// (release 31): from the file's audio-integrity.json when that record is
+// still the file's (same name, size and mtime).
+export type MediaScanAudit = {
+ verdict: "clean" | "damaged" | "undecodable";
+ decodedSeconds: number;
+ durationSeconds: number | null;
+ gaps: number;
+ checkedAt: string;
+};
+
export type MediaScanFinding = {
// `${channelSlug}/${videoId}`, the slug the rest of the app uses.
slug: string;
@@ -72,6 +89,8 @@ export type MediaScanFinding = {
// First meaningful line of probe output. The evidence, so a verdict can be
// argued with rather than merely trusted.
detail?: string;
+ // The audio audit's verdict on the same file, when it has one.
+ audit?: MediaScanAudit;
};
export type MediaScanChannelTotals = {
@@ -82,6 +101,9 @@ export type MediaScanChannelTotals = {
truncated: number;
stray: number;
unknown: number;
+ // Readable files the audio audit found damaged (release 31). Optional:
+ // reports written before it lack the key.
+ damaged?: number;
// Files that got the tier-2 full decode.
deepProbed: number;
bytesAtRisk: number;
@@ -114,6 +136,7 @@ export function mediaScanTotals(report: MediaScanReport): MediaScanChannelTotals
truncated: 0,
stray: 0,
unknown: 0,
+ damaged: 0,
deepProbed: 0,
bytesAtRisk: 0,
scannedAt: "",
@@ -126,6 +149,7 @@ export function mediaScanTotals(report: MediaScanReport): MediaScanChannelTotals
out.truncated += t.truncated;
out.stray += t.stray;
out.unknown += t.unknown;
+ out.damaged = (out.damaged ?? 0) + (t.damaged ?? 0);
out.deepProbed += t.deepProbed;
out.bytesAtRisk += t.bytesAtRisk;
if (t.scannedAt > out.scannedAt) out.scannedAt = t.scannedAt;
diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts
@@ -65,6 +65,12 @@ export const REPORT_TICK_QUEUE = "report-tick";
// on a LOCAL vision model goes on `draft:local` instead (the GPU's lane).
export const FRAME_SCAN_QUEUE = "frames";
+// The audio audit (release 31, controller/audioAudit.ts): one job per channel,
+// every one on this key, so ONE file is decoded at a time machine-wide — the
+// audit reads whole libraries off drives that also serve downloads and
+// transcription, and it is background work.
+export const AUDIO_AUDIT_QUEUE = "audio-audit";
+
// Per-channel queue for channel-local bookkeeping jobs (clean/clear/verify).
export function channelQueueKey(slug: string): string {
return `channel:${slug}`;
diff --git a/common/lib/salvageAudio-server.ts b/common/lib/salvageAudio-server.ts
@@ -27,7 +27,9 @@
// salvageAudio-server.test.ts: tone bursts after the damage keep their times.
import { spawn } from "node:child_process";
+import { accessSync, constants as fsConstants } from "node:fs";
import { rm } from "node:fs/promises";
+import os from "node:os";
import path from "node:path";
// The sample rate both outputs are decoded at: what parakeet and whisper.cpp
@@ -73,6 +75,12 @@ export type DecodeDeps = {
ffprobeBin: string;
signal?: AbortSignal;
onLog?: (line: string) => void;
+ // Run the DECODE (not the ffprobe) at the lowest CPU and I/O priority:
+ // `ionice -c3` (idle class) when util-linux's ionice is on PATH, and nice
+ // 19 on the process either way. Asked for by the audio audit (release 31,
+ // lane A — controller/audioAudit.ts), which decodes whole libraries in the
+ // background; every other caller decodes one file somebody is waiting on.
+ lowPriority?: boolean;
};
const round3 = (n: number) => Math.round(n * 1000) / 1000;
@@ -200,7 +208,7 @@ export async function scanDecodable(file: string, deps: DecodeDeps): Promise<Dec
const res = await run(
deps.ffmpegBin,
["-nostdin", "-hide_banner", "-v", "error", ...TOLERANT_INPUT_ARGS, "-i", file, ...scanOutputArgs()],
- { signal: deps.signal, onStdoutLine: acc.feed },
+ { signal: deps.signal, onStdoutLine: acc.feed, lowPriority: deps.lowPriority },
);
if (res.spawnError) {
deps.onLog?.(`ffmpeg could not be run on ${path.basename(file)}: ${res.spawnError}\n`);
@@ -281,15 +289,55 @@ type RunResult = {
// spawn, line-streamed stdout (a framecrc scan of a long file is ~15 MB),
// stderr kept to its tail (a damaged file prints a line per refused frame).
+// The lowest priority a decode can ask for (DecodeDeps.lowPriority): the
+// command to spawn, through `ionice -c3` when it is on PATH. `ionice` execs
+// the program, so the child's pid is the decoder's and a signal reaches it.
+export function lowPriorityCommand(bin: string, args: string[]): { bin: string; args: string[] } {
+ const ionice = ioniceBin();
+ return ionice ? { bin: ionice, args: ["-c3", bin, ...args] } : { bin, args };
+}
+
+let ioniceCache: string | null | undefined;
+function ioniceBin(): string | null {
+ if (ioniceCache !== undefined) return ioniceCache;
+ ioniceCache = null;
+ if (process.platform !== "linux") return ioniceCache;
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
+ if (!dir) continue;
+ const candidate = path.join(dir, "ionice");
+ try {
+ accessSync(candidate, fsConstants.X_OK);
+ ioniceCache = candidate;
+ break;
+ } catch {
+ // not here
+ }
+ }
+ return ioniceCache;
+}
+
+// The CPU half: nice 19 on the spawned process (it keeps it across exec).
+// Best-effort — a platform that refuses leaves the decode at normal priority.
+function deprioritize(pid: number | undefined): void {
+ if (pid === undefined) return;
+ try {
+ os.setPriority(pid, 19);
+ } catch {
+ // not permitted here; the decode still runs
+ }
+}
+
function run(
bin: string,
args: string[],
- opts: { signal?: AbortSignal; onStdoutLine?: (line: string) => void },
+ opts: { signal?: AbortSignal; onStdoutLine?: (line: string) => void; lowPriority?: boolean },
): Promise<RunResult> {
return new Promise((resolve) => {
let child;
try {
- child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"], signal: opts.signal });
+ const cmd = opts.lowPriority ? lowPriorityCommand(bin, args) : { bin, args };
+ child = spawn(cmd.bin, cmd.args, { stdio: ["ignore", "pipe", "pipe"], signal: opts.signal });
+ if (opts.lowPriority) deprioritize(child.pid);
} catch (err) {
resolve({ exitCode: null, stdout: "", stderrTail: "", spawnError: (err as Error).message });
return;
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -7,6 +7,7 @@ import { SIDECAR_FILENAMES, sidecar, sidecarField } from "./sidecar-server";
import { SUB_FILE_RE } from "./videoStatus";
// Every sidecar module, so the enumeration below sees every declaration.
import "./archiveOrg-server";
+import "./audioIntegrity-server";
import "./attribution-server";
import "./diarization-server";
import "./digest-server";
@@ -45,12 +46,13 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all fourteen are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
"archiveorg.json",
"attribution.json",
+ "audio-integrity.json",
"availability.json",
"diarization.json",
"do-not-clean.json",
diff --git a/common/views/pipeline/channelFlow.ts b/common/views/pipeline/channelFlow.ts
@@ -444,6 +444,12 @@ export function computeChannelFlow(
"download",
"Download completed but the audio stayed malformed; the file is kept. A retry downloads again — a source that is only sometimes malformed can come back clean.",
),
+ ...siding(
+ "damaged held audio",
+ buckets.corruptHeldAudio.length,
+ "download",
+ "The audio audit found part of the held file will not decode; it is kept. A retry downloads again with the audio check.",
+ ),
],
transcribe: [
...siding("failed", failedVideoIds.length, "transcribe"),
diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts
@@ -43,6 +43,7 @@ export function normalizeBuckets(
chatOnlyPending: raw?.chatOnlyPending ?? [],
incompleteTranscript: raw?.incompleteTranscript ?? [],
salvagedTranscript: raw?.salvagedTranscript ?? [],
+ corruptHeldAudio: raw?.corruptHeldAudio ?? [],
shortAudio: raw?.shortAudio ?? [],
autoSubsOnly: raw?.autoSubsOnly ?? [],
downloadedAutoSubsOnly: raw?.downloadedAutoSubsOnly ?? [],
@@ -318,6 +319,15 @@ export function computeStageStatuses(
),
);
}
+ if (buckets.corruptHeldAudio.length > 0) {
+ downloadParts.push(
+ pluralize(
+ buckets.corruptHeldAudio.length,
+ "damaged held audio file",
+ "damaged held audio files",
+ ),
+ );
+ }
const download: StageStatus = {
id: "download",
title: "Download",
diff --git a/common/ytdlp/corruptRefetch.test.ts b/common/ytdlp/corruptRefetch.test.ts
@@ -35,6 +35,12 @@ import {
import { downloadOneManaged } from "./downloadOneManaged";
import { destinationExists } from "./runYtdlp";
import { generateChannelSnapshot } from "../controller/channelSnapshot";
+import {
+ fileIdentity,
+ heldAudioDamage,
+ integrityRecord,
+ writeAudioIntegrity,
+} from "../lib/audioIntegrity-server";
const ID = "H64QQZuw-aA";
const PATHS = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" };
@@ -361,3 +367,164 @@ test("a clean refetch leaves a transcript that is not a salvage alone", async ()
assert.equal((await readOutcome(f.videoDir)).corruptRefetches?.[0].retiredSalvage, undefined);
await rm(f.root, { recursive: true, force: true });
});
+
+// ---------------------------------------------------------------------------
+// Release 31, lane A: held audio the audio audit found damaged is the second
+// trigger. Its outcome is an old `ok` (or nothing); a failed refetch restores
+// THAT, never a corrupt-full-source status it never had.
+// ---------------------------------------------------------------------------
+
+async function heldFixture(opts: { status?: DownloadOutcomeRecord | null; verdict?: "damaged" | "clean"; tiered?: boolean } = {}) {
+ const f = await fixture({ tiered: opts.tiered, status: opts.status ?? undefined });
+ if (opts.status === null) await rm(path.join(f.videoDir, "download-outcome.json"));
+ else if (opts.status === undefined) {
+ await writeFile(
+ path.join(f.videoDir, "download-outcome.json"),
+ JSON.stringify(outcome({ status: "ok", startedAt: "2026-01-01T00:00:00.000Z", finishedAt: "2026-01-01T00:10:00.000Z" })),
+ );
+ }
+ const id = await fileIdentity(path.join(f.videoDir, "audio.mp4"));
+ await writeAudioIntegrity(
+ f.videoDir,
+ integrityRecord(
+ "audio.mp4",
+ id,
+ opts.verdict === "clean"
+ ? { decodedSeconds: 600, totalSeconds: 600, gaps: [] }
+ : { decodedSeconds: 300, totalSeconds: 600, gaps: [[300, 600]] },
+ { by: "audit" },
+ ),
+ );
+ return f;
+}
+
+function heldCtx(audits: string[]) {
+ const c = ctx();
+ return {
+ ...c,
+ ctx: {
+ ...c.ctx,
+ deps: {
+ ...c.ctx.deps,
+ audit: async (videoDir: string, file: string) => {
+ audits.push(`${path.basename(videoDir)}/${file}=${await readFile(path.join(videoDir, file), "utf8")}`);
+ return null;
+ },
+ },
+ },
+ };
+}
+
+test("damaged held audio is a refetch; a clean one is not; a stale record is not", async () => {
+ const f = await heldFixture();
+ const { ctx: c, log } = heldCtx([]);
+ const plan = await prepareCorruptRefetch(f.videoDir, c);
+ assert.ok(plan);
+ assert.equal(plan.trigger, "damaged-held-audio");
+ assert.equal(plan.previous?.status, "ok");
+ assert.deepEqual(plan.asides, ["audio.mp4"]);
+ assert.match(log.join(""), /Damaged held audio: refetching \(the audit: damaged: 5:00 of 10:00 decodes \(50%\), 1 gap\)/);
+ await rm(f.root, { recursive: true, force: true });
+
+ const clean = await heldFixture({ verdict: "clean" });
+ assert.equal(await prepareCorruptRefetch(clean.videoDir, heldCtx([]).ctx), null);
+ await rm(clean.root, { recursive: true, force: true });
+
+ const stale = await heldFixture();
+ await writeFile(path.join(stale.videoDir, "audio.mp4"), "OLD-MALFORMED-BUT-LONGER");
+ assert.equal(await prepareCorruptRefetch(stale.videoDir, heldCtx([]).ctx), null);
+ await rm(stale.root, { recursive: true, force: true });
+});
+
+test("damaged held audio, clean refetch: the kept file goes, the new one is audited, the history says why", async () => {
+ const f = await heldFixture({ tiered: true });
+ const audits: string[] = [];
+ const { ctx: c, log } = heldCtx(audits);
+ const plan = await prepareCorruptRefetch(f.videoDir, c);
+ assert.ok(plan);
+ await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN");
+ const rec = await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c);
+ assert.equal(rec.status, "ok-audio-checked");
+ assert.deepEqual(rec.corruptRefetches?.map((r) => [r.result, r.trigger]), [["clean", "damaged-held-audio"]]);
+ assert.deepEqual((await readdir(f.videoDir)).filter((n) => n.endsWith(CORRUPT_KEPT_SUFFIX)), []);
+ assert.equal(existsSync(path.join(f.channelsDir, "c", "media", ID, "audio.mp4" + CORRUPT_KEPT_SUFFIX)), false);
+ assert.deepEqual(audits, [`${ID}/audio.mp4=NEW-CLEAN`]);
+ assert.match(log.join(""), /Damaged held audio: the refetch is clean; removed the kept audio\.mp4/);
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("damaged held audio, failed refetch: the file and its OLD ok record come back; the audit record speaks for it again", async () => {
+ const f = await heldFixture({ tiered: true });
+ const before = await fileIdentity(path.join(f.videoDir, "audio.mp4"));
+ const audits: string[] = [];
+ const { ctx: c, log } = heldCtx(audits);
+ const plan = await prepareCorruptRefetch(f.videoDir, c);
+ assert.ok(plan);
+ const rec = await settleCorruptRefetch(plan, outcome({ status: "failed", failureClass: "rate_limit" }), c);
+ assert.equal(rec.status, "failed", "the caller sees the failure");
+ const disk = await readOutcome(f.videoDir);
+ assert.equal(disk.status, "ok", "never a corrupt-full-source status it never had");
+ assert.equal(disk.corruptRefetches?.[0].trigger, "damaged-held-audio");
+ assert.equal(disk.corruptRefetches?.[0].result, "failed");
+ assert.deepEqual(await fileIdentity(path.join(f.videoDir, "audio.mp4")), before, "size and mtime kept");
+ assert.ok(await heldAudioDamage(f.videoDir), "still damaged held audio, so still in the bucket");
+ assert.deepEqual(audits, [], "nothing new to audit");
+ assert.match(log.join(""), /the held audio stays as it was/);
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("damaged held audio with no outcome record: a failed refetch keeps the download's own, with the retry", async () => {
+ const f = await heldFixture({ status: null });
+ const { ctx: c } = heldCtx([]);
+ const plan = await prepareCorruptRefetch(f.videoDir, c);
+ assert.ok(plan);
+ assert.equal(plan.previous, null);
+ await settleCorruptRefetch(plan, outcome({ status: "failed", failureClass: "network" }), c);
+ const disk = await readOutcome(f.videoDir);
+ assert.equal(disk.status, "failed");
+ assert.equal(disk.corruptRefetches?.length, 1);
+ assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "OLD-MALFORMED");
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("damaged held audio, malformed again: the longer decode stays, the video is a corrupt full source, re-audited", async () => {
+ const f = await heldFixture();
+ const audits: string[] = [];
+ const { ctx: c } = heldCtx(audits);
+ c.deps.measure = async (file: string) => ((await readFile(file, "utf8")).startsWith("NEW") ? 500 : 300);
+ const plan = await prepareCorruptRefetch(f.videoDir, c);
+ assert.ok(plan);
+ await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-MALFORMED");
+ const rec = await settleCorruptRefetch(plan, outcome({ status: "corrupt-full-source" }), c);
+ assert.equal(rec.status, "corrupt-full-source");
+ assert.equal(rec.corruptRefetches?.[0].kept, "new");
+ assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "NEW-MALFORMED");
+ assert.deepEqual(audits, [`${ID}/audio.mp4=NEW-MALFORMED`]);
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("a refetch of damaged held audio cut mid-download: the old ok record does not make the kept copy disposable", async () => {
+ const f = await heldFixture();
+ const { ctx: c } = heldCtx([]);
+ const plan = await prepareCorruptRefetch(f.videoDir, c);
+ assert.ok(plan);
+ // …killed before the download wrote anything. The next refetch starts:
+ const { ctx: c2, log } = heldCtx([]);
+ const again = await prepareCorruptRefetch(f.videoDir, c2);
+ assert.ok(again, "the restored file is still damaged held audio");
+ assert.match(log.join(""), /back to audio\.mp4/);
+ assert.equal(
+ await readFile(path.join(f.videoDir, "audio.mp4" + CORRUPT_KEPT_SUFFIX), "utf8"),
+ "OLD-MALFORMED",
+ );
+ assert.equal((await readOutcome(f.videoDir)).status, "ok", "and never rewritten corrupt-full-source");
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("the retry's prefilter asks again for damaged held audio; a sweep still counts it as there", async () => {
+ const f = await heldFixture();
+ const dataDir = path.dirname(f.videoDir);
+ assert.equal(await destinationExists(dataDir, ID, "transcribe"), true);
+ assert.equal(await destinationExists(dataDir, ID, "transcribe", { refetchDamagedAudio: true }), false);
+ await rm(f.root, { recursive: true, force: true });
+});
diff --git a/common/ytdlp/corruptRefetch.ts b/common/ytdlp/corruptRefetch.ts
@@ -33,9 +33,27 @@
//
// A RUN CUT SHORT (killed between moving the file aside and settling) leaves
// an `.corrupt-kept` file behind; the next prepare resolves it first.
+//
+// HELD AUDIO THE AUDIT FOUND DAMAGED IS REFETCHED THE SAME WAY (release 31,
+// lane A). A video whose `audio-integrity.json` (controller/audioAudit.ts)
+// still speaks for a real audio file it holds — same name, size and mtime —
+// and judges it damaged is the second trigger: the same aside, the same
+// settle, with three differences.
+// - Its outcome may be anything (`ok` from before the audio check, or no
+// sidecar at all); a failed refetch restores THAT record (or, with none,
+// keeps the download's own), never a corrupt-full-source status it never
+// had. The file is renamed back with its mtime, so the audit's record
+// speaks for it again and the video stays in corruptHeldAudio.
+// - downloadOneManaged turns the audio check ON for the refetch on a
+// transcribe-handling channel that has it off: a refetch that cannot tell
+// clean from malformed would be a coin toss.
+// - After a clean or still-malformed refetch the kept file is decoded again
+// and `audio-integrity.json` rewritten (`by: "refetch"`) — also for a
+// corrupt full source that carries one.
+// Its CorruptRefetch entries carry `trigger: "damaged-held-audio"`.
import path from "node:path";
-import { readdir } from "node:fs/promises";
+import { readdir, stat } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type {
CorruptRefetch,
@@ -58,6 +76,16 @@ import {
type TranscriptSalvage,
} from "../lib/transcribeOutcome";
import { CUES_JSON_FILENAME, WHISPER_FILENAME } from "../lib/videoStatus";
+import {
+ AUDIO_INTEGRITY_FILENAME,
+ describeIntegrity,
+ type AudioIntegrityRecord,
+} from "../lib/audioIntegrity";
+import {
+ heldAudioDamage,
+ loadAudioIntegrity,
+ measureAndRecordIntegrity,
+} from "../lib/audioIntegrity-server";
export const CORRUPT_KEPT_SUFFIX = ".corrupt-kept";
@@ -73,13 +101,23 @@ export type CorruptRefetchDeps = {
// Seconds of a file that decode (null: not measurable). Default: one
// tolerant ffmpeg decode (scanDecodable).
measure?: (file: string) => Promise<number | null>;
+ // The re-audit after a clean or still-malformed refetch (release 31, lane
+ // A). Default: one tolerant decode, written to audio-integrity.json.
+ audit?: (videoDir: string, file: string) => Promise<AudioIntegrityRecord | null>;
now?: () => Date;
};
+// Why a download is a refetch.
+export type CorruptRefetchTrigger = "corrupt-full-source" | "damaged-held-audio";
+
export type CorruptRefetchPlan = {
videoDir: string;
- // The corrupt-full-source record the retry started from.
- previous: DownloadOutcomeRecord;
+ trigger: CorruptRefetchTrigger;
+ // The record the retry started from: corrupt-full-source for that trigger;
+ // for damaged held audio whatever was there, or null.
+ previous: DownloadOutcomeRecord | null;
+ // damaged-held-audio: the audit's record that made it one.
+ damage?: AudioIntegrityRecord;
// The original names moved aside (each now `<name>.corrupt-kept`).
asides: string[];
startedAt: string;
@@ -140,9 +178,21 @@ async function resolveLeftovers(videoDir: string, entries: string[], ctx: Ctx):
const leftovers = entries.filter(isCorruptKeptName);
if (leftovers.length === 0) return;
const record = await loadDownloadOutcome(videoDir);
- const clean = record?.status.startsWith("ok") === true;
+ const finished = record ? Date.parse(record.finishedAt) : Number.NaN;
for (const aside of leftovers) {
const name = originalName(aside);
+ // "The download since was clean" needs a clean record written AFTER the
+ // file was set aside (its ctime is the rename's). Damaged held audio's
+ // own record is often an old `ok` (release 31, lane A) — removing the
+ // aside on that would lose the only copy of a run cut mid-download.
+ const asideAt = await stat(path.join(videoDir, aside))
+ .then((st) => st.ctimeMs)
+ .catch(() => Number.NaN);
+ const clean =
+ record?.status.startsWith("ok") === true &&
+ Number.isFinite(finished) &&
+ Number.isFinite(asideAt) &&
+ finished >= asideAt;
if (clean) {
ctx.onLog(`Removing ${aside} left by an earlier refetch: the download since was clean.\n`);
await removeMediaFile(videoDir, aside);
@@ -158,8 +208,20 @@ async function resolveLeftovers(videoDir: string, entries: string[], ctx: Ctx):
}
}
// A failure written but never settled: the video is still the corrupt
- // source it was, and its bucket says so.
- if (record && !clean && record.status !== "corrupt-full-source") {
+ // source it was, and its bucket says so. Not when the aside was damaged
+ // held audio (release 31, lane A) — the audit's record names it: that
+ // video never was a corrupt full source, and its bucket is the audit
+ // record, which the restored file matches again.
+ const audited = entries.includes(AUDIO_INTEGRITY_FILENAME)
+ ? (await loadAudioIntegrity(videoDir))?.file
+ : undefined;
+ const heldTrigger = audited !== undefined && leftovers.some((a) => originalName(a) === audited);
+ if (
+ record &&
+ !heldTrigger &&
+ !record.status.startsWith("ok") &&
+ record.status !== "corrupt-full-source"
+ ) {
await writeDownloadOutcome(videoDir, { ...record, status: "corrupt-full-source" });
}
}
@@ -204,8 +266,17 @@ export async function prepareCorruptRefetch(
const first = await readdir(videoDir).catch(() => [] as string[]);
await resolveLeftovers(videoDir, first, ctx);
const previous = await loadDownloadOutcome(videoDir);
- if (previous?.status !== "corrupt-full-source") return null;
const entries = await readdir(videoDir).catch(() => [] as string[]);
+ let trigger: CorruptRefetchTrigger;
+ let damage: AudioIntegrityRecord | undefined;
+ if (previous?.status === "corrupt-full-source") {
+ trigger = "corrupt-full-source";
+ } else {
+ const held = await heldAudioDamage(videoDir, entries);
+ if (!held) return null;
+ trigger = "damaged-held-audio";
+ damage = held.record;
+ }
const kept = entries.filter(isRealAudioFile);
const asides: string[] = [];
try {
@@ -222,13 +293,17 @@ export async function prepareCorruptRefetch(
);
}
ctx.onLog(
- kept.length > 0
- ? `Corrupt full source: refetching. The kept ${kept.join(", ")} is set aside until the download ends.\n`
- : `Corrupt full source: refetching (no kept file on disk).\n`,
+ trigger === "damaged-held-audio"
+ ? `Damaged held audio: refetching (the audit: ${describeIntegrity(damage!)}). The kept ${kept.join(", ")} is set aside until the download ends.\n`
+ : kept.length > 0
+ ? `Corrupt full source: refetching. The kept ${kept.join(", ")} is set aside until the download ends.\n`
+ : `Corrupt full source: refetching (no kept file on disk).\n`,
);
return {
videoDir,
+ trigger,
previous,
+ ...(damage ? { damage } : {}),
asides,
startedAt: (ctx.deps?.now?.() ?? new Date()).toISOString(),
};
@@ -242,6 +317,8 @@ export async function settleCorruptRefetch(
ctx: Ctx,
): Promise<DownloadOutcomeRecord> {
const { videoDir, previous, asides } = plan;
+ const held = plan.trigger === "damaged-held-audio";
+ const who = held ? "Damaged held audio" : "Corrupt full source";
const entries = await readdir(videoDir).catch(() => [] as string[]);
const fresh = entries.filter(isRealAudioFile);
const lastError = outcome.attempts.at(-1)?.error;
@@ -251,8 +328,33 @@ export async function settleCorruptRefetch(
result: "failed",
status: outcome.status,
...(outcome.failureClass ? { failureClass: outcome.failureClass } : {}),
+ ...(held ? { trigger: "damaged-held-audio" as const } : {}),
+ };
+ const history = previous?.corruptRefetches ?? [];
+ // The kept file decoded again, its audit record rewritten: always for
+ // damaged held audio, and for a corrupt full source that carries a record
+ // (a stale one would otherwise linger beside a new file).
+ const reaudit = async () => {
+ const now = await readdir(videoDir).catch(() => [] as string[]);
+ if (!held && !now.includes(AUDIO_INTEGRITY_FILENAME)) return;
+ const file = pickPreferredAudio(now.filter(isRealAudioFile));
+ if (!file) return;
+ const audit =
+ ctx.deps?.audit ??
+ ((dir: string, name: string) =>
+ measureAndRecordIntegrity(
+ dir,
+ name,
+ { ffmpegBin: ctx.paths.ffmpegBin, ffprobeBin: ctx.paths.ffprobeBin, signal: ctx.signal, onLog: ctx.onLog },
+ { by: "refetch" },
+ ));
+ try {
+ const r = await audit(videoDir, file);
+ ctx.onLog(r ? `Audio audit of ${file}: ${describeIntegrity(r)}.\n` : `Audio audit of ${file}: not measured.\n`);
+ } catch (err) {
+ ctx.onLog(`Audio audit of ${file} failed: ${(err as Error).message}\n`);
+ }
};
- const history = previous.corruptRefetches ?? [];
const removeAsides = async () => {
for (const name of asides) await removeMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX);
};
@@ -271,8 +373,9 @@ export async function settleCorruptRefetch(
};
await writeDownloadOutcome(videoDir, record);
ctx.onLog(
- `Corrupt full source: the refetch is clean${asides.length ? `; removed the kept ${asides.join(", ")}` : ""}.\n`,
+ `${who}: the refetch is clean${asides.length ? `; removed the kept ${asides.join(", ")}` : ""}.\n`,
);
+ await reaudit();
return record;
}
@@ -295,7 +398,7 @@ export async function settleCorruptRefetch(
}
const record: DownloadOutcomeRecord = {
...outcome,
- attempts: [...previous.attempts, ...outcome.attempts],
+ attempts: [...(previous?.attempts ?? []), ...outcome.attempts],
corruptRefetches: [
...history,
{ ...base, result: "still-malformed", kept, ...(decoded ? { decodedSeconds: decoded } : {}) },
@@ -304,10 +407,12 @@ export async function settleCorruptRefetch(
await writeDownloadOutcome(videoDir, record);
await tierVideoDir(videoDir, { onLog: ctx.onLog });
ctx.onLog(
- `Corrupt full source: the refetch is malformed too; kept the ${kept === "new" ? "new" : "earlier"} copy` +
+ `${who}: the refetch is malformed too; kept the ${kept === "new" ? "new" : "earlier"} copy` +
(decoded ? ` (${decoded.new ?? "?"}s vs ${decoded.previous ?? "?"}s decode)` : "") +
+ (held ? "; the video is a corrupt full source now" : "") +
".\n",
);
+ await reaudit();
return record;
}
@@ -316,21 +421,23 @@ export async function settleCorruptRefetch(
for (const name of fresh) await removeMediaFile(videoDir, name);
for (const name of asides) await renameMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX, name);
}
- const record: DownloadOutcomeRecord = {
- ...previous,
- finishedAt: outcome.finishedAt,
- attempts: [...previous.attempts, ...outcome.attempts],
- corruptRefetches: [
- ...history,
- { ...base, ...(lastError ? { error: lastError } : {}) },
- ],
- };
+ // The record the retry started from, with this retry appended — or, for
+ // damaged held audio that had none, the download's own.
+ const failed: CorruptRefetch = { ...base, ...(lastError ? { error: lastError } : {}) };
+ const record: DownloadOutcomeRecord = previous
+ ? {
+ ...previous,
+ finishedAt: outcome.finishedAt,
+ attempts: [...previous.attempts, ...outcome.attempts],
+ corruptRefetches: [...history, failed],
+ }
+ : { ...outcome, corruptRefetches: [failed] };
await writeDownloadOutcome(videoDir, record);
await tierVideoDir(videoDir, { onLog: ctx.onLog });
ctx.onLog(
- `Corrupt full source: the refetch ended ${outcome.status}${outcome.failureClass ? ` (${outcome.failureClass})` : ""}; ` +
+ `${who}: the refetch ended ${outcome.status}${outcome.failureClass ? ` (${outcome.failureClass})` : ""}; ` +
(asides.length ? `moved the kept ${asides.join(", ")} back; ` : "") +
- `the video stays corrupt-full-source.\n`,
+ (held ? `the held audio stays as it was.\n` : `the video stays corrupt-full-source.\n`),
);
return { ...outcome, corruptRefetches: record.corruptRefetches };
}
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -678,6 +678,23 @@ export async function downloadOneManaged(
const refetch = canonicalId
? await prepareCorruptRefetch(path.join(channelDir, "data", canonicalId), refetchCtx)
: null;
+ // Damaged held audio (release 31, lane A) is refetched WITH the audio
+ // check on a transcribe-handling channel that has it off: the settle
+ // decides by clean / malformed, and only the check can say which.
+ if (
+ refetch?.trigger === "damaged-held-audio" &&
+ opts.channelConfig.handling === "transcribe" &&
+ opts.channelConfig.audioCheck?.enabled !== true
+ ) {
+ opts.onLog("This channel has no audio check; the refetch of damaged held audio runs with it on.\n");
+ opts = {
+ ...opts,
+ channelConfig: {
+ ...opts.channelConfig,
+ audioCheck: { ...(opts.channelConfig.audioCheck ?? {}), enabled: true },
+ },
+ };
+ }
let outcome = await runManagedDownload(opts, channelDir, startedAt, canonicalId);
if (refetch) outcome = await settleCorruptRefetch(refetch, outcome, refetchCtx);
await recordWaybackProvenance(opts, channelDir, canonicalId);
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -89,6 +89,7 @@ import {
} from "./downloadFormat";
import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
+import { heldAudioDamage } from "../lib/audioIntegrity-server";
export type YtdlpMode =
| "store-playlist"
@@ -306,6 +307,10 @@ async function retryBucket(opts: RunYtdlpOpts): Promise<void> {
// corruptFullSource bucket's retry would prefilter every id away
// ("Nothing to fetch"). downloadOneManaged moves the file aside and back.
refetchCorruptFullSource: true,
+ // AND HELD AUDIO THE AUDIT FOUND DAMAGED (release 31, lane A): the same
+ // reason — the file on disk is not a destination that makes the video
+ // complete, or the corruptHeldAudio bucket's retry would fetch nothing.
+ refetchDamagedAudio: true,
});
}
@@ -736,6 +741,7 @@ async function downloadPlaylistManaged(
idAllowList?: ReadonlyArray<string>;
handlingOverride?: ChannelHandling;
refetchCorruptFullSource?: boolean;
+ refetchDamagedAudio?: boolean;
},
): Promise<void> {
const { prefilter, idAllowList, handlingOverride } = cfg;
@@ -833,6 +839,7 @@ async function downloadPlaylistManaged(
await destinationExists(dataDir, dirId, effectiveHandling, {
replaceAutoSubs: opts.replaceAutoSubs,
refetchCorruptFullSource: cfg.refetchCorruptFullSource,
+ refetchDamagedAudio: cfg.refetchDamagedAudio,
})
) {
alreadyComplete++;
@@ -1612,7 +1619,11 @@ export async function destinationExists(
dataDir: string,
id: string,
handling: ChannelHandling,
- opts: { replaceAutoSubs?: boolean; refetchCorruptFullSource?: boolean } = {},
+ opts: {
+ replaceAutoSubs?: boolean;
+ refetchCorruptFullSource?: boolean;
+ refetchDamagedAudio?: boolean;
+ } = {},
): Promise<boolean> {
const dir = path.join(dataDir, id);
const entries = await readdir(dir).catch(() => [] as string[]);
@@ -1626,6 +1637,11 @@ export async function destinationExists(
) {
return false;
}
+ // The same for held audio the audio audit found damaged (release 31, lane
+ // A): its record must still be the file's (name, size, mtime).
+ if (opts.refetchDamagedAudio === true && (await heldAudioDamage(dir, entries))) {
+ return false;
+ }
// Our own transcript always counts as "already done".
if (entries.includes("transcript.json")) return true;
// A VTT normally counts too — channels can be hybrid. The replace-auto-captions
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **`pnpm ops audio-audit` checks the audio already on disk, file by file.** `pnpm ops audio-audit --json '{"platform":"odysee"}'` (or `{"slug":"<channel>"}`; `"scope":"all"` for transcribed videos too, `"max"` to cap the files) decodes each audio file a channel holds with error tolerance — one file at a time, at the lowest CPU and disk priority — and writes what it found beside the file in `audio-integrity.json`: clean, damaged (part of it will not decode) or undecodable, with how much decodes and where the gaps are. Audio downloaded before the audio check existed, or on a channel without it, was never checked. The same command again skips the files already checked. A drive that stops answering ends that channel's run with a sentence that says so instead of hanging.
+- **Damaged held audio has its own bucket, and its Retry downloads again.** The channel's Download stage has a **Damaged held audio** card (and the report a `corruptHeldAudio` bucket) for files the audit found damaged; they are no longer handed to the transcription lane. **Retry** (or `pnpm ops retry-bucket --json '{"slug":"<channel>","bucket":"corruptHeldAudio"}'`) sets the file aside and downloads again with the audio check on: a clean copy replaces it, a copy that is malformed too keeps whichever decodes longer, and a failed download puts the file back. Transcribing such a file decodes what it can and keeps the gaps as silence. **/review**'s media scan shows the audit's verdict beside its own, and lists a file it reads as fine but the audit found damaged.
- **A poker frame scan finds the moments a highlight reel is made of.** Besides the double-ups, busts and big pots, the derivation now marks: every pot the streamer's player takes (a pot of 25 big blinds or more is a big pot; the same log line read twice with a digit off is one pot), the player's all-ins with how they ended (doubled, won, lost, busted, or not read), each blind level going up (from the client's "Blinds are now" line; a misread line that a later one contradicts is ignored, in the big blind too), and the field falling under 100, 50, 27 and 18 players and to the final table (from the client's "position N of M" only, once each). Each of these says which rule made it, what it read, and whether a second reading backs it (`confirmed`) or not; a reading flagged against a spoken number still makes nothing. An all-in banner the model reads is the player's only when the player's chips are all in the middle. The new moments appear on an existing scan by re-deriving it, with no model call: `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>","rederive":true}'`. Needs a restart of the editor.
- **A frame-scan supercut has substance, and shows the numbers on screen.** `umtool new <slug> --from <channel>/<video> --seed frames` now ranks the scan's moments — big pots and won all-ins first, then the final table, players-left marks and the bust, then the other swings, the smaller pots, and level-ups last — and takes them until the clips fill `--target <seconds>` (240 by default). The draft turns on the on-screen deck with a new **stats** panel: the stack, the stack in big blinds, players left and the level, in a corner of the picture over each clip, each number changing when the scan read it change (`render.chrome.stats`; a clip's `"stats": false` leaves it out, `"stats": true` draws it on one clip only). A build checks the panel's frames, and fails when a clip that asks for it was drawn without it. The project is new: re-seeding an existing one needs a new slug.
- **A channel that copies another creator's streams can be paired with the creator, both ways.** Name the creator's channels on the mirror's Configure form ("Mirror of (channel slugs)", or `pnpm ops channel-config --json '{"slug":"<mirror>","patch":{"mirrorOf":"<creator>, <creator-rumble>"}}'`). The channel page then has a **Mirror** stage: **Scan** (or `pnpm ops mirror-scan --json '{"slug":"<mirror>"}'`, `"dryRun": true` to count without writing) matches each of the mirror's videos, by the day it was recorded (the title's date when the channel has a recorded-date pattern) and its title and length, with the creator's videos uploaded a day before to two days after. Each video is then the **only copy** (no creator channel has it public), **creator deleted** (removed on one platform, public on another), **never uploaded** (missing from one platform) or **creator public**, with a filter for each and links to the creator's copies; and the other way, the creator's deleted or private videos in the mirror's span and how many of them the mirror holds. The result stays on this machine (`transcripts/mirrors/<slug>.json`) and is never published. With the MCP on a local archive, `get_video_metadata` says what copies a video has, and `enumerate_matches` takes `"copies": "only-here"` for the videos that survive only on a mirror; a published site says this is not available.
diff --git a/editor/app/api/ops/audio-audit/route.ts b/editor/app/api/ops/audio-audit/route.ts
@@ -0,0 +1,51 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ AUDIO_AUDIT_BODY_KEYS,
+ AudioAuditInputError,
+ enqueueAudioAudit,
+} from "yt-dlp-transcript-common/controller/audioAudit";
+import { OpsInputError, opsFail, ops } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug | platform, scope?: "untranscribed" | "all", max?, force? }
+// -> { ok: true, jobIds, channels, refused: [{slug, error}] }
+//
+// The audio audit (release 31, lane A): every audio file the channel holds
+// (or every channel on the platform holds) decoded with error tolerance, one
+// at a time machine-wide at idle priority, its verdict written beside it in
+// `audio-integrity.json` — clean, damaged or undecodable. One `audio-audit`
+// job per channel on the `audio-audit` queue. `scope` "untranscribed" (the
+// default) audits only videos with no transcript yet; "all" every video
+// holding audio. `max` caps the files decoded across the run; `force`
+// decodes again a file whose record is still its own. The same body again
+// resumes. A channel whose media is unreachable is refused (in `refused`);
+// none started at all is a 409. Each job's log ends `@@audio-audit {json}`.
+//
+// AN ADAPTER: the rules are the controller's (controller/audioAudit.ts).
+export async function POST(request: Request) {
+ return ops(request, AUDIO_AUDIT_BODY_KEYS, async (body) => {
+ let out;
+ try {
+ out = await enqueueAudioAudit(body, { paths: getPaths() });
+ } catch (e) {
+ if (e instanceof AudioAuditInputError) throw new OpsInputError(e.message);
+ throw e;
+ }
+ // The jobs run to completion on disk; nobody reads these streams.
+ for (const s of out.started) void s.result.stream.cancel();
+ if (out.started.length === 0) {
+ return opsFail(
+ `No audit started: ${out.refused.map((r) => `${r.slug}: ${r.error}`).join("; ")}`,
+ 409,
+ );
+ }
+ return NextResponse.json({
+ ok: true,
+ jobIds: out.started.map((s) => s.result.jobId),
+ channels: out.started.map((s) => s.slug),
+ refused: out.refused,
+ });
+ });
+}
diff --git a/editor/app/channels/[slug]/components/VideoListPane.tsx b/editor/app/channels/[slug]/components/VideoListPane.tsx
@@ -856,7 +856,7 @@ export function VideoListPane({
function StatusGlyphs({ row }: { row: VideoRow }) {
const dlColor =
- row.partial || row.corruptSource || row.corruptFullSource
+ row.partial || row.corruptSource || row.corruptFullSource || row.corruptHeldAudio
? "bg-warning"
: row.downloaded
? "bg-success"
@@ -880,7 +880,9 @@ function StatusGlyphs({ row }: { row: VideoRow }) {
? "corrupt source (needs re-download)"
: row.corruptFullSource
? "corrupt full source (download completed but audio is malformed; file kept — a retry downloads again)"
- : "downloaded"
+ : row.corruptHeldAudio
+ ? "damaged held audio (the audio audit found part of it will not decode; file kept — a retry downloads again)"
+ : "downloaded"
}
className={`w-2 h-2 rounded-full ${dlColor}`}
/>
diff --git a/editor/app/channels/[slug]/components/flow/AttentionStrip.tsx b/editor/app/channels/[slug]/components/flow/AttentionStrip.tsx
@@ -67,6 +67,7 @@ export function collectAttention(input: AttentionInput): Chip[] {
"download",
"destructive",
);
+ add("damaged held audio", buckets.corruptHeldAudio.length, "download");
add(
"incomplete transcripts",
buckets.incompleteTranscript.length,
diff --git a/editor/app/channels/[slug]/components/stages/DownloadStage.tsx b/editor/app/channels/[slug]/components/stages/DownloadStage.tsx
@@ -31,6 +31,8 @@ type Props = {
needsCookiesIds: string[];
// Release 30 lane Q: complete downloads whose audio stayed malformed.
corruptFullSourceIds: string[];
+ // Release 31 lane A: held audio the audio audit found damaged.
+ corruptHeldAudioIds: string[];
missingShard: ShardConfigSummary | null;
};
@@ -45,6 +47,7 @@ export function DownloadStage({
partialDownloadIds,
needsCookiesIds,
corruptFullSourceIds,
+ corruptHeldAudioIds,
missingShard,
}: Props) {
const [downloadQueue, setDownloadQueue] = useState(defaultQueueKey);
@@ -238,6 +241,12 @@ export function DownloadStage({
defaultQueueKey={defaultQueueKey}
existingQueues={existingQueues}
/>
+ <CorruptHeldAudioList
+ slug={slug}
+ ids={corruptHeldAudioIds}
+ defaultQueueKey={defaultQueueKey}
+ existingQueues={existingQueues}
+ />
</div>
);
}
@@ -547,6 +556,56 @@ function CorruptFullSourceList({
);
}
+// HELD AUDIO THE AUDIT FOUND DAMAGED (release 31, lane A): `pnpm ops
+// audio-audit` decoded the file on disk and part of it would not. A retry
+// downloads again with the audio check, exactly as for a corrupt full source.
+function CorruptHeldAudioList({
+ slug,
+ ids,
+ defaultQueueKey,
+ existingQueues,
+}: {
+ slug: string;
+ ids: string[];
+ defaultQueueKey: string;
+ existingQueues: string[];
+}) {
+ const [ranHere, setRanHere] = useState(false);
+ if (ids.length === 0 && !ranHere) return null;
+ return (
+ <div className="flex flex-col gap-2 rounded border border-border p-3">
+ <div>
+ <h4 className="text-sm font-semibold">
+ Damaged held audio ({ids.length})
+ </h4>
+ <p className="text-xs text-muted-foreground">
+ The audio audit found part of each file will not decode; the file is
+ kept. A retry downloads again with the audio check. If the new copy
+ is malformed too, the one that decodes longer stays; if the download
+ fails, the held file stays.
+ </p>
+ </div>
+ <VideoIdList
+ slug={slug}
+ ids={ids}
+ ariaLabel="damaged held audio list"
+ emptyAriaLabel="damaged held audio empty"
+ emptyMessage="None"
+ itemAriaLabel={(id) => `damaged held audio ${id}`}
+ />
+ <RetryBucketControl
+ slug={slug}
+ ids={ids}
+ actionLabel="damaged held audio"
+ defaultQueueKey={defaultQueueKey}
+ existingQueues={existingQueues}
+ bucketKey="corruptHeldAudio"
+ onRun={() => setRanHere(true)}
+ />
+ </div>
+ );
+}
+
function Heading({ title, desc }: { title: string; desc: string }) {
return (
<div>
diff --git a/editor/app/channels/[slug]/lib/videoRows.ts b/editor/app/channels/[slug]/lib/videoRows.ts
@@ -29,6 +29,10 @@ export type VideoRow = {
// kept on disk; a retry refetches it (release 30, lane Q). Distinct from
// corruptSource (which never finished) and from a failed transcription.
corruptFullSource: boolean;
+ // Held audio the audio audit found damaged, with no transcript yet
+ // (snapshot `corruptHeldAudio` minus its salvage transcripts — release 31,
+ // lane A). Kept on disk; a retry refetches it.
+ corruptHeldAudio?: boolean;
failedTranscription: boolean;
// Has at least one finalized audio file not in the channel's target format —
// the failed-extract orphans (audio.m4a with no audio.mp3) plus dirs with the
diff --git a/editor/app/channels/[slug]/lib/videoRowsServer.ts b/editor/app/channels/[slug]/lib/videoRowsServer.ts
@@ -46,6 +46,9 @@ export function computeVideoRows(input: ComputeRowsInput): VideoRow[] {
const digestWarningsSet = new Set(buckets.digestWarnings ?? []);
const corruptSourceSet = new Set(buckets.corruptSource);
const corruptFullSourceSet = new Set(buckets.corruptFullSource);
+ const salvagedSet = new Set(buckets.salvagedTranscript);
+ // Damaged held audio with no transcript: the bucket minus its salvages.
+ const heldDamagedSet = new Set(buckets.corruptHeldAudio.filter((id) => !salvagedSet.has(id)));
const failedTranscription = new Set(input.failedTranscriptionIds);
const runningIds = new Set<string>();
@@ -64,6 +67,7 @@ export function computeVideoRows(input: ComputeRowsInput): VideoRow[] {
const isPartial = partial.has(id);
const isCorruptSource = corruptSourceSet.has(id);
const isCorruptFullSource = corruptFullSourceSet.has(id);
+ const isCorruptHeldAudio = heldDamagedSet.has(id);
// A corrupt-source video is a download/source problem, not a failed
// transcription — don't let a stale failed-transcriptions entry (pruned on
// the next transcribe pass) mark it failed here. Same for a kept
@@ -81,13 +85,15 @@ export function computeVideoRows(input: ComputeRowsInput): VideoRow[] {
isOnDisk &&
!inNoTranscript &&
!inDownloadedNoTranscript &&
- !isCorruptFullSource;
+ !isCorruptFullSource &&
+ !isCorruptHeldAudio;
const excluded = input.excludedIds.has(id);
let status: VideoRowStatus;
if (isFailedT) status = "failed";
else if (isCorruptSource) status = "corrupt_source";
else if (isCorruptFullSource) status = "corrupt_full_source";
+ else if (isCorruptHeldAudio) status = "downloaded_no_transcript";
else if (isPartial) status = "partial_download";
else if (isUndownloaded) status = "not_downloaded";
else if (isUntranscribable) status = "untranscribable";
@@ -105,6 +111,7 @@ export function computeVideoRows(input: ComputeRowsInput): VideoRow[] {
partial: isPartial,
corruptSource: isCorruptSource,
corruptFullSource: isCorruptFullSource,
+ ...(isCorruptHeldAudio ? { corruptHeldAudio: true } : {}),
failedTranscription: isFailedT,
wrongFormatAudio:
wrongFormatAudio.has(id) || multipleAudioFormats.has(id),
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -513,6 +513,7 @@ export default async function ChannelDetailPage({
partialDownloadIds={buckets.partialDownloads}
needsCookiesIds={buckets.needsCookies}
corruptFullSourceIds={buckets.corruptFullSource}
+ corruptHeldAudioIds={buckets.corruptHeldAudio}
missingShard={await shard("download-missing")}
/>
);
diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx
@@ -163,6 +163,7 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = {
cards: "Cards",
entries: "Entries",
frames: "Frames",
+ files: "Files",
};
// Per-metric glyph for the compact line ("↓ 5/10").
@@ -177,6 +178,7 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = {
cards: "\u25a4 ",
entries: "\u2261 ",
frames: "\u25a3 ",
+ files: "\u266a ",
};
const METRIC_FILL: Record<JobProgressMetric, string> = {
@@ -190,6 +192,7 @@ const METRIC_FILL: Record<JobProgressMetric, string> = {
cards: "bg-success/60",
entries: "bg-success/60",
frames: "bg-info/60",
+ files: "bg-info/60",
};
// One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left"
diff --git a/editor/app/review/components/MediaScanFindingRow.tsx b/editor/app/review/components/MediaScanFindingRow.tsx
@@ -15,6 +15,7 @@ const VERDICT_LABEL: Record<MediaScanFinding["verdict"], string> = {
truncated: "truncated",
stray: "stray file",
unknown: "could not tell",
+ damaged: "damaged",
};
const VERDICT_HELP: Record<MediaScanFinding["verdict"], string> = {
@@ -27,8 +28,18 @@ const VERDICT_HELP: Record<MediaScanFinding["verdict"], string> = {
"Readable media that is not one of the app's own outputs: a leftover scratch or temp file taking up disk.",
unknown:
"The scan could not reach a conclusion. Nothing is claimed about this file.",
+ damaged:
+ "The container reads, but the audio audit decoded it and part of it would not decode. The channel's Download stage can retry it.",
};
+function clock(sec: number): string {
+ const s = Math.max(0, Math.round(sec));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const p = (n: number) => String(n).padStart(2, "0");
+ return h > 0 ? `${h}:${p(m)}:${p(s % 60)}` : `${m}:${p(s % 60)}`;
+}
+
export function MediaScanFindingRow({
finding,
reviewed,
@@ -90,6 +101,25 @@ export function MediaScanFindingRow({
: `${Math.round(finding.metadataSeconds)}s`}
</p>
)}
+ {finding.audit && (
+ <p
+ aria-label={`audio audit ${key}`}
+ className="text-xs text-muted-foreground"
+ >
+ audio audit{" "}
+ <time dateTime={finding.audit.checkedAt}>
+ {finding.audit.checkedAt.slice(0, 10)}
+ </time>
+ : {finding.audit.verdict} — {clock(finding.audit.decodedSeconds)} of{" "}
+ {finding.audit.durationSeconds === null
+ ? "?"
+ : clock(finding.audit.durationSeconds)}{" "}
+ decodes
+ {finding.audit.gaps > 0
+ ? `, ${finding.audit.gaps} gap${finding.audit.gaps === 1 ? "" : "s"}`
+ : ""}
+ </p>
+ )}
{finding.detail && (
<p className="text-xs text-muted-foreground font-mono break-all">
{finding.detail}
diff --git a/editor/e2e/audio-check-scenarios.spec.ts b/editor/e2e/audio-check-scenarios.spec.ts
@@ -385,6 +385,85 @@ test.describe("audio-checked download scenarios", () => {
).toBe(false);
});
+ test("the audio audit finds damaged held audio; its bucket's retry downloads again and the new file audits clean", async ({
+ page,
+ }) => {
+ // Release 31 lane A. Audio held from before the audio check (here: a clean
+ // download whose file is then damaged on disk) is classified by nothing at
+ // fetch time; the audit decodes it, the report lists it, the retry
+ // refetches it as it would a corrupt full source.
+ await resetData("audio-check-channel");
+ await writeFile(
+ resolvePath(`${CHANNEL_ROOT}/playlist`),
+ `https://odysee.com/@example/clip:${VIDEO_ID}\n`,
+ );
+ await writeFakeConfig({ mode: "happy", totalChunks: 4, chunkDelayMs: 100 });
+ await triggerDownload(page);
+ await waitForOutcome((o) => o.status === "ok-audio-checked", "clean first download");
+ const audio = `${CHANNEL_ROOT}/data/${VIDEO_ID}/audio.mp3`;
+ expect(await pathExists(audio)).toBe(true);
+ // The held file goes bad on disk (fake-ffmpeg's tolerant decode reads half
+ // of a file carrying the corrupt marker; fake-ffprobe its __DUR__).
+ await writeFile(resolvePath(audio), "__CORRUPT__ __DUR=600__ held audio\n");
+
+ const res = await page.request.post(`${baseUrl}/api/ops/audio-audit`, {
+ headers: { authorization: "Bearer test-worker-token" },
+ data: { slug: CHANNEL, scope: "all" },
+ });
+ expect(res.ok()).toBeTruthy();
+ const body = (await res.json()) as { jobIds: string[]; channels: string[] };
+ expect(body.channels).toEqual([CHANNEL]);
+ expect(body.jobIds).toHaveLength(1);
+ const sidecar = `${CHANNEL_ROOT}/data/${VIDEO_ID}/audio-integrity.json`;
+ await expect
+ .poll(
+ async () =>
+ (await readJson<{ verdict?: string }>(sidecar).catch(() => null))?.verdict ?? "",
+ { timeout: 30_000, message: "the audit's verdict beside the file" },
+ )
+ .toBe("damaged");
+ // The report lists it (the job's end asks for a regen).
+ await expect
+ .poll(
+ async () =>
+ (
+ await readJson<{ buckets?: { corruptHeldAudio?: string[] } }>(
+ `${CHANNEL_ROOT}/snapshot.json`,
+ ).catch(() => null)
+ )?.buckets?.corruptHeldAudio ?? [],
+ { timeout: 30_000, message: "the video in the corruptHeldAudio bucket" },
+ )
+ .toEqual([VIDEO_ID]);
+
+ await page.goto(channelStage(CHANNEL, "download"));
+ await expect(page.getByLabel(`damaged held audio ${VIDEO_ID}`)).toBeVisible();
+ const bucket = page.getByLabel("retry damaged held audio bucket");
+ await bucket.getByRole("button", { name: /^Retry \(1\)$/ }).click();
+ const retryLog = page.getByLabel("Retry damaged held audio output");
+ await expect(retryLog).toContainText("Damaged held audio: refetching", {
+ timeout: 30_000,
+ });
+ await expect(retryLog).toContainText("the refetch is clean", {
+ timeout: 60_000,
+ });
+ const outcome = await waitForOutcome(
+ (o) => o.corruptRefetches?.[0]?.result === "clean",
+ "clean refetch outcome",
+ );
+ expect(outcome.corruptRefetches?.[0]?.trigger).toBe("damaged-held-audio");
+ await expect
+ .poll(
+ async () =>
+ (await readJson<{ verdict?: string; by?: string }>(sidecar).catch(() => null))?.by ?? "",
+ { timeout: 15_000, message: "the new file audited by the refetch" },
+ )
+ .toBe("refetch");
+ expect((await readJson<{ verdict: string }>(sidecar)).verdict).toBe("clean");
+ expect(
+ await pathExists(`${CHANNEL_ROOT}/data/${VIDEO_ID}/audio.mp3.corrupt-kept`),
+ ).toBe(false);
+ });
+
test("deterministic corruption exhausts retry cap and surfaces failed-corrupt-source", async ({
page,
}) => {
diff --git a/editor/e2e/fixtures/bin/fake-ffmpeg.mjs b/editor/e2e/fixtures/bin/fake-ffmpeg.mjs
@@ -42,6 +42,12 @@ async function readSrc(file) {
}
}
+// `ffmpeg -version` (the audio audit asks it once per job for the tool line).
+if (argv.includes("-version")) {
+ process.stdout.write("ffmpeg version fake-e2e Copyright (c) the fixture\n");
+ process.exit(0);
+}
+
const src = arg("-i") ?? "<unknown>";
const out = argv[argv.length - 1];
if (!out || out.startsWith("-")) {
@@ -54,6 +60,25 @@ if (srcBuf?.includes(SLOW_PROBE_MARKER)) {
await sleep(SLOW_PROBE_MS);
}
+// THE TOLERANT DECODE'S SCAN (lib/salvageAudio-server.ts scanDecodable):
+// `-f framecrc pipe:1`. Frames covering the file's duration (fake-ffprobe's
+// rule: `__DUR=<s>__`, else 100000 s); a file carrying CORRUPT_MARKER decodes
+// only its first half — a gap to the end, which the audio audit reads as
+// damaged. Checked BEFORE the corrupt exit below: a tolerant decode never
+// stops at a bad frame.
+if (out === "pipe:1" && arg("-f") === "framecrc") {
+ const text = srcBuf ? srcBuf.toString("utf8") : "";
+ const m = text.match(/__DUR=([0-9]+(?:\.[0-9]+)?)__/);
+ const total = m ? Number(m[1]) : 100000;
+ const decoded = text.includes(CORRUPT_MARKER) ? total / 2 : total;
+ const frames = 100;
+ const step = Math.round((decoded / frames) * 16000);
+ const lines = ["#tb 0: 1/16000"];
+ for (let i = 0; i < frames; i++) lines.push(`0, ${i * step}, ${i * step}, ${step}, ${step * 2}, 0x00000000`);
+ process.stdout.write(lines.join("\n") + "\n");
+ process.exit(0);
+}
+
if (srcBuf?.includes(CORRUPT_MARKER)) {
process.stderr.write(
`[aac @ 0x1234] Sample rate index in program config element does not match the sample rate index configured by the container.\n`,
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9824,3 +9824,57 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
`get_video_metadata` adds a `- copies:` line (`copiesIndex`: a mirror video's status and the creator's strong
matches; a creator video held by a mirror, and whether it is gone); `enumerate_matches` `copies: "only-here"`
restricts the scan to the only-copy mirror videos by id (to the mirror channels unless the call scopes itself).
+
+## Release 31 lane A: the audio-integrity audit (verified 2026-10-16, branch `r31/audio-audit`)
+
+- **`channels/<slug>/data/<id>/audio-integrity.json`** (declared with `sidecar()` in `lib/audioIntegrity-server.ts`;
+ types and the rule in `lib/audioIntegrity.ts`) — TEXT, never published: `{version: 1, checkedAt, file, size, mtime
+ (epoch ms, floored), durationSeconds (container, or null), decodedSeconds, gaps: [[from, to], …], verdict: clean |
+ damaged | undecodable, tool: {scan: "scanDecodable/1", ffmpeg?}, by: audit | refetch, jobId?}`. It speaks for ONE
+ file: the record is stale when the named file is gone or its size (or, where the reader has it, mtime) differs.
+ Written only by `measureAndRecordIntegrity` (the audit and the refetch's re-audit); nothing is written when ffmpeg
+ could not run or the file changed during the decode.
+- **The rule** (`integrityVerdict`, `AUDIO_INTEGRITY_MIN_DECODED_RATIO` = 0.98): nothing decodes → undecodable; any
+ listed gap (holes ≥ 0.5 s after merging, the tail to the container's duration included) or under 98 % of the
+ container's duration decoded → damaged; else clean. Readers recompute it from the numbers (`isDamagedIntegrity`),
+ not from `verdict`.
+- **The job**: kind `audio-audit` (`needsMedia`, not replayable), ONE PER CHANNEL, every one on queue `audio-audit`
+ (`AUDIO_AUDIT_QUEUE`) — one file decoded at a time machine-wide; `pnpm ops audio-audit {slug | platform, scope?:
+ untranscribed (default: no transcript, `isVideoTranscribed`) | all, max? (files across the whole request — a shared
+ counter, exact because the jobs run in turn), force?}` → `{jobIds, channels, refused}` (409 when none started).
+ `platform` = `channelPlatform(config)`. The file audited is `pickPreferredAudio` of the real audio files; a video
+ whose outcome is corrupt-full-source is left out (counted `corruptFullSource`). The decode is `scanDecodable` with
+ `lowPriority` (`ionice -c3` when on PATH + `os.setPriority(pid, 19)`; only this caller asks). Resume: a file whose
+ record matches name+size+mtime is `fresh` (skipped) unless `force`. Before each file the storage watch's verdict
+ (`channelMediaStall`, no I/O) and the file's stat through `onDrive` (when the channel has a `mediaDir`); a stall
+ ends the channel's job FAILED with "The media drive of "<slug>" (location "<label>") is not answering since …".
+ Each decode has a deadline of 60 s + 0.1 s per audio second (metadata duration, else size at 8 kB/s); two in a row
+ missed end the job failed too. The job asks `ffmpeg -version` first and fails without it (a missing ffmpeg under
+ ionice would otherwise read as "nothing decodes"). Progress metric `files`. Log ends `@@audio-audit {slug, scope,
+ held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}`.
+- **Snapshot bucket `corruptHeldAudio`** (`controller/channelSnapshot.ts`, after the corrupt-full-source
+ short-circuit): a dir with the sidecar whose record names one of its real audio files, matches that file's lstat'd
+ size (`audioSizes`; an unknown size counts the name) and is damaged — and the video has NO transcript, or a SALVAGE
+ one. Untranscribed members are short-circuited out of downloadedNoTranscript and wrongFormatAudio (the lane does not
+ transcribe them; a retry first). A damaged file under any other transcript is in no bucket (/review lists it).
+ `ReplayBucket`; channel flow siding "damaged held audio" (download); Download stage card **Damaged held audio**
+ (`retry damaged held audio bucket`, items `damaged held audio <id>`); attention chip; the video list's download dot
+ (row `corruptHeldAudio`, status `downloaded_no_transcript`).
+- **The refetch's second trigger** (`ytdlp/corruptRefetch.ts`): `prepareCorruptRefetch` → `trigger:
+ "damaged-held-audio"` when the outcome is not corrupt-full-source and `heldAudioDamage(videoDir)` (record matches
+ name+size+mtime, damaged) — same aside/settle. `previous` may be null. Failed → the previous record (status kept,
+ e.g. `ok`) with the attempts and the retry appended, or with none the download's own record + `corruptRefetches`;
+ the file renamed back keeps size+mtime, so the record matches again. Clean / still-malformed → the kept file is
+ re-audited (`by: "refetch"`; also for a corrupt full source that carries a record). `CorruptRefetch.trigger:
+ "damaged-held-audio"`. `downloadOneManaged` turns `audioCheck` on for that refetch on a transcribe-handling channel
+ without it. Retry prefilter: `destinationExists(…, {refetchDamagedAudio: true})` (retry-bucket passes it for every
+ bucket, beside `refetchCorruptFullSource`). Log prefix "Damaged held audio:".
+- **Leftovers rule changed for both triggers**: an `.corrupt-kept` is removed as "the download since was clean" only
+ when the record is ok* AND its `finishedAt` is at or after the aside's ctime (the rename's); an older ok record
+ restores it. The unsettled-failure rewrite to corrupt-full-source is skipped when the audit record names the aside.
+- **Salvage**: `transcribeOne`'s automatic salvage also fires when `heldAudioDamage` names the very file being read.
+- **/review's media scan** (`scanCorruptMedia`) reads the sidecar per dir: a matching record rides on the finding as
+ `audit: {verdict, decodedSeconds, durationSeconds, gaps (count), checkedAt}`; a file tier 1 reads as fine (and the
+ right length) whose record is damaged is a finding of verdict `damaged` (totals `damaged?`). No decode for it.
+- **e2e fixtures**: `fake-ffmpeg.mjs` answers `-version`, and `-f framecrc pipe:1` with 100 frames over fake-ffprobe's
+ duration (`__DUR=<s>__`, else 100000) — half of it for a file carrying `__CORRUPT__`.
diff --git a/plans/release-31/audio-audit.md b/plans/release-31/audio-audit.md
@@ -0,0 +1,67 @@
+# Release 31, lane A — the audio-integrity audit (as shipped)
+
+Branch `r31/audio-audit` from `main` `3ef1b558` (`main` `c9ec3bc8` and then `1ed16ffc` — lanes C, P3, D — merged in
+before the final gates). Brief: `r31a-brief.md` (the plan of record for this lane). FACTS: "Release 31 lane A: the
+audio-integrity audit".
+
+## What and why
+
+Only a download that went through the audio check is ever classified (release 30 Q's `corrupt-full-source`). Audio
+held from before the check, or from a channel without it, was never checked; the media scan on /review read
+containers, fed no bucket and no refetch. This lane measures what is on disk and routes the damage into Q's refetch.
+
+- **`audio-integrity.json`** (`lib/audioIntegrity.ts`, `lib/audioIntegrity-server.ts`, declared with `sidecar()`):
+ one record per video dir, for one file (name, size, mtime); verdict clean | damaged | undecodable by
+ `integrityVerdict` (`AUDIO_INTEGRITY_MIN_DECODED_RATIO` 0.98, or any listed gap).
+- **The job** (`controller/audioAudit.ts`): `pnpm ops audio-audit {slug | platform, scope?, max?, force?}` → one
+ `audio-audit` job per channel (`needsMedia`) on the `audio-audit` queue, so one file is decoded at a time
+ machine-wide; the decode is `scanDecodable` with the new `lowPriority` (`ionice -c3` when on PATH, nice 19 by
+ `os.setPriority`; only this caller asks). Resumable by name+size+mtime; `max` a counter shared by the run's jobs;
+ corrupt full sources left to Q. Stall-aware: `channelMediaStall` before each file, the stat through `onDrive`, a
+ deadline per decode (60 s + 0.1 s per audio second), two missed in a row stop the job; a stop by the drive fails
+ the job with the sentence. `ffmpeg -version` first (refused without it). Log ends `@@audio-audit {…}`.
+- **Bucket `corruptHeldAudio`** in the one classifier (`channelSnapshot.ts`, after the corrupt-full-source
+ short-circuit): damaged held audio with no transcript (short-circuited out of downloadedNoTranscript and the
+ wrong-format sweep) or a salvage transcript. Normalized in `stageStatus`, a download siding in `channelFlow`, the
+ Download stage's **Damaged held audio** card with the bucket's Retry, an attention chip, the video list's dot.
+- **The retry** (`ytdlp/corruptRefetch.ts`): a second trigger, `damaged-held-audio`; the audio check is forced on
+ for it (`downloadOneManaged`); a failed refetch restores the previous record (or keeps the download's own); the
+ kept file is re-audited after clean / still-malformed. `destinationExists` `refetchDamagedAudio` (retry-bucket).
+ Salvage transcription is automatic for such a file (`transcribeOne`).
+- **/review**: `scanCorruptMedia` attaches the audit's verdict (`audit`) to a finding and lists a readable file the
+ audit found damaged as `damaged`; the finding row shows the audit line.
+
+| Commit | What |
+| --- | --- |
+| `68e87ea5` | the audit, the sidecar, the bucket and its surfaces, the refetch trigger, salvage, /review, ops route/help, COMMANDS.md, the e2e fake ffmpeg, the e2e scenario, CHANGELOG |
+| (this commit) | this record, FACTS |
+
+## Gates (from the worktree root, every one behind the shared heavy lock)
+
+- tsc: `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` clean on the merged tree.
+- common: 4362 at the branch's start → 4427 after merging main (lanes C, P3, D) and this lane, all pass. This lane's
+ own: `controller/audioAudit.test.ts` 11 (real ffmpeg over the synthetic damaged recording), `lib/audioIntegrity
+ .test.ts` 3, `ytdlp/corruptRefetch.test.ts` +7, `lib/sidecar-server.test.ts` (fifteen declared).
+- editor unit: 319 → 322 (with the merged lanes), all pass.
+- test:scripts: 1030 (+3 skipped) → 1041 (+3 skipped), all pass.
+- `docs cli --check`, `docs files --check`, `docs env --check`, `settings example --check`: clean (COMMANDS.md
+ regenerated).
+- e2e `audio-check-scenarios.spec.ts` (with the new scenario: audit → corruptHeldAudio → Retry → clean, re-audited):
+ run 1 — **17/17 passed** (1.2 min, foreground, behind the lock; the build through the heavy slot first).
+- Decode speed measured on a synthetic 30-minute AAC file: 1168× realtime at normal priority, 1039× at the audit's
+ low priority (≈ 3.5 s per hour of audio on an idle machine; a slow drive dominates).
+
+## Rulings and calls
+
+- Corrupt full sources are not audited (Q's path covers them); counted in the log.
+- The bucket holds untranscribed damaged files and salvage-transcribed ones; a damaged file under any other transcript
+ stands, in no bucket (/review lists it). Untranscribed members are held out of the transcription lane until a
+ retry, as a corrupt full source is.
+- The snapshot matches the record by name and size only (no extra stat); the audit and the refetch by name, size and
+ mtime.
+- Q's leftover rule tightened: an aside is removed as "since clean" only with a clean record newer than the aside.
+
+## Not done
+
+No live run (the orchestrator's). CHANNEL.md needs nothing (per-video sidecars are not in it). The video page does
+not show the audit record (the bucket, the row dot and /review do).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -126,6 +126,9 @@
// pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'
// pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait
// pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait
+// pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait
+// pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'
+// pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait
// pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait
// pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'
// pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'
@@ -475,6 +478,12 @@ const ACTIONS = [
// R6.3: learn (the proposal pass), unlearn and promote-alias (a learned
// spelling as a search alias, plan then confirm).
"report-schedule",
+ // THE AUDIO AUDIT (release 31): every audio file a channel (or a platform's
+ // channels) holds decoded with error tolerance, one at a time at idle
+ // priority, the verdict in audio-integrity.json beside it ({slug | platform,
+ // scope?, max?, force?}); one audio-audit job per channel. The damaged ones
+ // are the report's corruptHeldAudio bucket, which retry-bucket refetches.
+ "audio-audit",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -1114,6 +1123,8 @@ export function usage() {
" with ids is not replayable, as a checkbox selection in the UI is not.",
' "corruptFullSource" downloads again: the kept file is set aside, and comes',
" back if the download fails; malformed again, the longer decode stays.",
+ ' "corruptHeldAudio" (held audio the audio audit found damaged) is refetched',
+ " the same way, with the audio check on; the new file is audited again.",
"",
'transcribe-bucket transcribes a channel\'s "downloaded, not transcribed"',
' bucket on the transcription queue, as the channel page\'s Transcribe button',
@@ -1459,6 +1470,28 @@ export function usage() {
" (umtool's /tools/bench). The log ends with",
" @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.",
"",
+ 'audio-audit decodes every audio file a channel holds, with error tolerance,',
+ ' and writes the verdict beside it in audio-integrity.json: {"slug" |',
+ ' "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed",',
+ ' the default: videos with no transcript yet; "all": every video holding',
+ ' audio), "max"? (files decoded across the run), "force"? (decode again a',
+ ' file whose record is still its own)} -> {jobIds, channels, refused}. One',
+ " audio-audit job per channel on the audio-audit queue: one file at a time",
+ " machine-wide, at idle I/O priority and nice 19. The verdict is clean,",
+ " damaged (a gap, or under 98% of the container's duration decodes) or",
+ " undecodable, with the decoded seconds, the gaps, the file's size and mtime",
+ " and ffmpeg's version. The same body again resumes (a file whose record",
+ " matches is skipped). A channel whose media is unreachable is refused; a",
+ " drive that stops answering mid-run ends that channel's job with the",
+ " sentence (failed), as do two decodes in a row past their deadline (a",
+ " minute plus a tenth of the audio's length). Corrupt full sources are left",
+ " to their retry. Damaged untranscribed files (and their salvage",
+ " transcripts) are the report's corruptHeldAudio bucket, held out of the",
+ ' transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches',
+ " them; a transcription of one salvages automatically. Each log ends with",
+ " @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged,",
+ " undecodable, unmeasured, timedOut, corruptFullSource, stopped?}.",
+ "",
'frame-scan reads a saved stream\'s frames for a profile\'s progress: {"slug",',
' "id", "profile"? ("poker", the default), "everySeconds"? (default',
" settings.generation.frames.everySeconds, 10), \"from\"?, \"to\"? (source seconds),",