// `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 | 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, 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 & { onLog?: (line: string) => void; // Test seam: the scan (default: one tolerant ffmpeg decode). scan?: (file: string) => Promise; }; // 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 { 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 { 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 { 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); } }); }