// DECODING A DAMAGED AUDIO FILE FOR WHAT IT STILL HOLDS (release 30, lane Q). // // A source that served malformed audio mid-stream (Odysee's AAC, CHANNEL.md // `audioCheck`) leaves a container that is mostly decodable: thousands of // "Invalid data found when processing input" lines, and either the whole // runtime or a long prefix of it in between. Two questions are asked of such a // file, with ONE ffmpeg decode each: // // scanDecodable how much of it decodes — the sum of the decoded frames' // durations, and where the decoded timeline jumps (a gap). // The corrupt-source refetch keeps whichever of two copies // decodes LONGER (ytdlp/corruptRefetch.ts). // salvageDecode the same scan, and beside it a 16 kHz mono WAV of the // file ON THE SOURCE'S CLOCK: every undecodable span is // silence of the same length, so a cue at 41:07 in the // transcript is at 41:07 in the recording. A plain decode // drops the bad frames and closes up the gap, and every cue // after the first one lands early by the gap's length. // // THE CLOCK COMES FROM THE CONTAINER. Each packet carries its own timestamp // (an MP4's sample table, not the bytes of the frame), so a frame the decoder // refuses leaves a hole in the decoded frames' timestamps exactly where the // frame was. `aresample=async=1:first_pts=0` fills such holes with silence // (any jump over its `min_hard_comp`, 0.1 s), `apad=whole_dur` pads the tail // out to the container's duration, and `framecrc` on the unpadded output says // where the holes were. Verified with a synthetic corrupted file in // 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 // read anyway (parakeet-stitch slices 16 kHz mono windows). export const SALVAGE_SAMPLE_RATE = 16_000; // The salvage WAV's name in the video dir. Not a real audio file // (`isRealAudioFile` anchors on ONE segment after `audio.`), scratch to the // media tier (lib/mediaTier.ts), and stable — so parakeet's resumable window // cache (`.audio.salvage.wav.parakeet`, scratch too) survives a pause: the // decode is deterministic, the duration the cache is keyed on the same. export const SALVAGE_WAV_FILENAME = "audio.salvage.wav"; // A hole shorter than this is counted (in `decodedSeconds`) but not listed: // one dropped AAC frame is 23 ms, and a file with 6,557 decode errors would // otherwise list thousands of them. export const SALVAGE_GAP_MIN_SECONDS = 0.5; // Two listed holes with less decoded audio than this between them are one gap. export const SALVAGE_GAP_MERGE_SECONDS = 1; export type SalvageGap = [from: number, to: number]; export type DecodeScan = { // Seconds of audio that decoded (the frames' durations, summed). decodedSeconds: number; // The container's duration (ffprobe), or the decoded timeline's end when the // container does not say. totalSeconds: number; // Spans of the source's timeline with no decoded audio, merged and sorted. gaps: SalvageGap[]; // ffmpeg's exit code. A tolerant decode exits 0 on a damaged file; non-zero // means it stopped (an unreadable header, a demuxer that gave up). exitCode: number | null; }; export type SalvageResult = DecodeScan & { // The WAV written (absolute path). wavFile: string; }; export type DecodeDeps = { ffmpegBin: string; 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; // The decoder's tolerance: keep decoding past a refused frame, and let the // demuxer drop packets it flags as corrupt rather than hand them on. const TOLERANT_INPUT_ARGS = ["-err_detect", "ignore_err", "-fflags", "+discardcorrupt"]; // The unpadded scan output: 16 kHz mono PCM, one framecrc line per frame // (`stream, dts, pts, duration, size, crc`), on stdout. function scanOutputArgs(): string[] { return [ "-map", "0:a:0", "-vn", "-ac", "1", "-ar", String(SALVAGE_SAMPLE_RATE), "-c:a", "pcm_s16le", "-f", "framecrc", "pipe:1", ]; } // Parsed framecrc frames, accumulated into decoded seconds and holes. type FrameAccumulator = { feed: (line: string) => void; finish: (totalSeconds: number | null) => { decodedSeconds: number; end: number; gaps: SalvageGap[] }; }; // PURE: framecrc lines in, decoded seconds and gaps out. Exported for tests. export function frameAccumulator(): FrameAccumulator { let tbNum = 1; let tbDen = SALVAGE_SAMPLE_RATE; let decodedTicks = 0; let expectedEnd: number | null = null; const raw: SalvageGap[] = []; const toSec = (ticks: number) => (ticks * tbNum) / tbDen; return { feed(line: string) { const s = line.trim(); if (!s) return; if (s.startsWith("#")) { const tb = /^#tb\s+0:\s*(\d+)\/(\d+)/.exec(s); if (tb) { tbNum = Number(tb[1]) || 1; tbDen = Number(tb[2]) || SALVAGE_SAMPLE_RATE; } return; } const cols = s.split(",").map((c) => c.trim()); if (cols.length < 4 || cols[0] !== "0") return; const pts = Number(cols[2]); const dur = Number(cols[3]); if (!Number.isFinite(pts) || !Number.isFinite(dur)) return; const prevEnd = expectedEnd ?? 0; if (pts > prevEnd) raw.push([toSec(prevEnd), toSec(pts)]); decodedTicks += Math.max(0, dur); expectedEnd = Math.max(prevEnd, pts + dur); }, finish(totalSeconds: number | null) { const end = expectedEnd === null ? 0 : toSec(expectedEnd); const total = totalSeconds !== null && totalSeconds > end ? totalSeconds : end; if (total > end) raw.push([end, total]); return { decodedSeconds: round3(Math.min(toSec(decodedTicks), total)), end: round3(total), gaps: mergeGaps(raw), }; }, }; } // PURE: sort, merge (holes closer than SALVAGE_GAP_MERGE_SECONDS are one), and // drop what is shorter than SALVAGE_GAP_MIN_SECONDS. Exported for tests and for // transcribeOne, which adds the windows an engine could not transcribe. export function mergeGaps(gaps: ReadonlyArray): SalvageGap[] { const sorted = gaps .filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b) && b > a) .map(([a, b]) => [a, b] as SalvageGap) .sort((x, y) => x[0] - y[0]); const merged: SalvageGap[] = []; for (const [a, b] of sorted) { const last = merged.at(-1); if (last && a - last[1] < SALVAGE_GAP_MERGE_SECONDS) { last[1] = Math.max(last[1], b); } else { merged.push([a, b]); } } return merged .filter(([a, b]) => b - a >= SALVAGE_GAP_MIN_SECONDS) .map(([a, b]) => [round3(a), round3(b)] as SalvageGap); } // Seconds covered by a list of (merged, non-overlapping) gaps. export function gapSeconds(gaps: ReadonlyArray): number { return round3(gaps.reduce((sum, [a, b]) => sum + Math.max(0, b - a), 0)); } // The container's duration, or null when ffprobe cannot say. export async function containerDurationSec( ffprobeBin: string, file: string, signal?: AbortSignal, ): Promise { const out = await run( ffprobeBin, ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file], { signal }, ); if (out.exitCode !== 0) return null; const sec = Number.parseFloat(out.stdout.trim()); return Number.isFinite(sec) && sec > 0 ? sec : null; } // HOW MUCH OF A FILE DECODES, with the same tolerance the salvage decode uses. // One decode, no file written. Null when ffmpeg could not be run at all. export async function scanDecodable(file: string, deps: DecodeDeps): Promise { const total = await containerDurationSec(deps.ffprobeBin, file, deps.signal); const acc = frameAccumulator(); const res = await run( deps.ffmpegBin, ["-nostdin", "-hide_banner", "-v", "error", ...TOLERANT_INPUT_ARGS, "-i", file, ...scanOutputArgs()], { 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`); return null; } const done = acc.finish(total); return { decodedSeconds: done.decodedSeconds, totalSeconds: done.end, gaps: done.gaps, exitCode: res.exitCode }; } // DECODE A DAMAGED FILE INTO A WAV ON THE SOURCE'S CLOCK, and say what is // missing from it. One ffmpeg run, two outputs: the unpadded framecrc scan on // stdout, and the padded WAV. Throws when nothing decoded at all. export async function salvageDecode( input: string, wavFile: string, deps: DecodeDeps, ): Promise { const total = await containerDurationSec(deps.ffprobeBin, input, deps.signal); const acc = frameAccumulator(); const pad = total !== null ? `,apad=whole_dur=${total}` : ""; await rm(wavFile, { force: true }); const res = await run( deps.ffmpegBin, [ "-nostdin", "-hide_banner", "-v", "error", ...TOLERANT_INPUT_ARGS, "-i", input, ...scanOutputArgs(), "-map", "0:a:0", "-vn", "-af", `aresample=${SALVAGE_SAMPLE_RATE}:async=1:first_pts=0${pad}`, "-ac", "1", "-c:a", "pcm_s16le", "-f", "wav", "-y", wavFile, ], { signal: deps.signal, onStdoutLine: acc.feed }, ); if (res.spawnError) throw new Error(`ffmpeg could not be run: ${res.spawnError}`); const done = acc.finish(total); if (done.decodedSeconds <= 0) { await rm(wavFile, { force: true }); throw new Error( `nothing in ${path.basename(input)} decodes (ffmpeg exit ${res.exitCode}): ${res.stderrTail.trim().split("\n").slice(-2).join(" | ")}`, ); } return { decodedSeconds: done.decodedSeconds, totalSeconds: done.end, gaps: done.gaps, exitCode: res.exitCode, wavFile, }; } // A one-line summary for a job log. export function describeSalvage(r: Pick): string { const pct = r.totalSeconds > 0 ? Math.round((r.decodedSeconds / r.totalSeconds) * 1000) / 10 : 0; return `${r.decodedSeconds}s of ${r.totalSeconds}s decode (${pct}%), ${r.gaps.length} gap${r.gaps.length === 1 ? "" : "s"} (${gapSeconds(r.gaps)}s)`; } type RunResult = { exitCode: number | null; stdout: string; stderrTail: string; spawnError?: string; }; // 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; lowPriority?: boolean }, ): Promise { return new Promise((resolve) => { let child; try { 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; } let stdout = ""; let carry = ""; let stderrTail = ""; child.stdout.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { if (!opts.onStdoutLine) { stdout += chunk; return; } carry += chunk; let nl = carry.indexOf("\n"); while (nl >= 0) { opts.onStdoutLine(carry.slice(0, nl)); carry = carry.slice(nl + 1); nl = carry.indexOf("\n"); } }); child.stderr.setEncoding("utf8"); child.stderr.on("data", (chunk: string) => { stderrTail = (stderrTail + chunk).slice(-4096); }); let spawnError: string | undefined; let settled = false; const settle = (code: number | null) => { if (settled) return; settled = true; if (carry && opts.onStdoutLine) opts.onStdoutLine(carry); resolve({ exitCode: code, stdout, stderrTail, ...(spawnError ? { spawnError } : {}) }); }; child.on("error", (err) => { spawnError = err.message; // A binary that is not there never emits "close" on some Node versions. if (child.pid === undefined) settle(null); }); child.on("close", (code) => settle(code)); }); }