// `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): 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; // 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, 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; slug: string; config: Pick; scope: AudioAuditScope; force?: boolean; budget?: AuditBudget; ffmpegVersion?: string; jobId?: string; onLog: (line: string) => void; signal: AbortSignal; setProgress?: (p: JobProgress) => void; deps?: AuditDeps; }): Promise { 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> { 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, ctx: { paths: Paths; deps?: AuditDeps }, ): Promise { 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; }