// IS THE MERGED FILE WHOLE (DESIGN-4 4)? yt-dlp's merge (and the editor's own) // is a stream copy: every packet of each stream file is in the merged file. // A torn or skipped fragment does not change a file's probed LENGTH (the // timestamps carry it), so the length proves nothing; the packets do. Per // track, one ffprobe pass over each file: // - the merged file's packet count equals its stream file's; // - their spans agree within max(0.5 s, 2 frames); // - in every file, consecutive packet times (sorted) never step more than // 1.5× the track's median step for video, 2× for audio, nor 0.1 s (a hole), and the // decode times, where the file has them, only go forward. // ffprobe runs at `-v error`: a raw WebM stream file's "unknown-length // element" warning, one per fragment (Matroska clusters of a live stream), is // a warning, never an error here; only the exit and the packets count. // Cost, measured: about 115 k packets a second (a 3 h file, 830 k packets, // 7.2 s cached) plus the read of the file — for a 6 h 19 min stream (683 k // video + 980 k audio packets) about 15 s of CPU per file, the merged file and // its two streams about 30 s plus reading them twice over (minutes on a // spinning disk). It runs AFTER the landing and the transcription hand-off; // the stream files go only after it passes. import { spawn } from "node:child_process"; import { setPriority } from "node:os"; import { createInterface } from "node:readline"; export type TrackScan = { kind: "video" | "audio" | "other"; packets: number; span: number; medianStep: number; maxStep: number; backward: number }; export type FileScan = { file: string; tracks: TrackScan[] } | { file: string; error: string }; export async function scanMediaFile(ffprobeBin: string, file: string, signal?: AbortSignal): Promise { const kinds = await new Promise((resolve) => { const c = spawn(ffprobeBin, ["-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", file], { stdio: ["ignore", "pipe", "pipe"], signal }); let out = ""; let err = ""; c.stdout.on("data", (d: Buffer) => (out += d.toString())); c.stderr.on("data", (d: Buffer) => (err += d.toString())); c.on("error", (e) => resolve(e.message)); c.on("close", (code) => resolve(code === 0 ? out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) : `ffprobe exit ${code}: ${err.trim().slice(0, 300)}`)); }); if (typeof kinds === "string") return { file, error: kinds }; const pts: number[][] = kinds.map(() => []); const dur: number[] = kinds.map(() => 0); const lastDts: number[] = kinds.map(() => -Infinity); const backward: number[] = kinds.map(() => 0); const code = await new Promise((resolve) => { const c = spawn(ffprobeBin, ["-v", "error", "-show_entries", "packet=stream_index,pts_time,dts_time,duration_time", "-of", "csv=p=0", file], { stdio: ["ignore", "pipe", "pipe"], signal, }); try { if (c.pid) setPriority(c.pid, 10); } catch { // (Best effort: a lower priority.) } let err = ""; c.stderr.on("data", (d: Buffer) => (err = (err + d.toString()).slice(-2000))); const rl = createInterface({ input: c.stdout }); rl.on("line", (line) => { const [si, p, d, du] = line.split(","); const i = Number(si); if (!Number.isInteger(i) || i < 0 || i >= kinds.length) return; const pt = Number(p); if (!Number.isFinite(pt)) return; pts[i]!.push(pt); const dd = Number(d); if (Number.isFinite(dd)) { if (dd <= lastDts[i]!) backward[i]!++; lastDts[i] = dd; } const dn = Number(du); if (Number.isFinite(dn)) dur[i] = dn; }); c.on("error", (e) => resolve(e.message)); c.on("close", (code) => resolve(code === 0 ? 0 : `ffprobe exit ${code}: ${err.trim().slice(0, 300)}`)); }); if (code !== 0) return { file, error: String(code) }; const tracks: TrackScan[] = kinds.map((k, i) => { const t = Float64Array.from(pts[i]!).sort(); const steps = new Float64Array(Math.max(0, t.length - 1)); for (let j = 1; j < t.length; j++) steps[j - 1] = t[j]! - t[j - 1]!; const sorted = Float64Array.from(steps).sort(); const median = sorted.length ? sorted[Math.floor(sorted.length / 2)]! : 0; return { kind: k === "video" ? "video" : k === "audio" ? "audio" : "other", packets: t.length, span: t.length ? t[t.length - 1]! + dur[i]! - t[0]! : 0, medianStep: median, maxStep: sorted.length ? sorted[sorted.length - 1]! : 0, backward: backward[i]!, }; }); return { file, tracks }; } export const HOLE_FLOOR_SECONDS = 0.1; export type Verdict = { ok: true; tracks: TrackScan[] } | { ok: false; why: string }; const holeOf = (t: TrackScan): string | null => { if (t.kind === "other" || t.packets < 3) return null; // A floor of 0.1 s: an encoder's dropped frame (0.067 s at 30 fps) is not a // hole; a lost fragment (1-5 s of a YouTube stream) always is. const limit = Math.max(HOLE_FLOOR_SECONDS, (t.kind === "video" ? 1.5 : 2) * t.medianStep); if (t.maxStep > limit + 1e-6) return `a ${t.maxStep.toFixed(3)} s step in its ${t.kind} (median ${t.medianStep.toFixed(3)} s): a hole`; if (t.backward > 0) return `${t.backward} ${t.kind} packet(s) decode backwards`; return null; }; // REVIEW-6 3: the picture and the sound of one recording end together. A // track torn or stopped early reads, raw and merged alike, only up to where // it stopped (ffprobe stops where the merge did), so the packets agree; the // OTHER track does not. Apart by more than max(2 s, 2 fragments): not whole. export const TRACK_SPAN_MIN_TOLERANCE_SECONDS = 2; const tracksApart = (tracks: TrackScan[], fragmentSeconds: number): string | null => { const v = tracks.find((t) => t.kind === "video"); const a = tracks.find((t) => t.kind === "audio"); if (!v || !a) return null; const tol = Math.max(TRACK_SPAN_MIN_TOLERANCE_SECONDS, 2 * fragmentSeconds); return Math.abs(v.span - a.span) > tol ? `its video holds ${v.span.toFixed(1)} s and its audio ${a.span.toFixed(1)} s (more than ${tol} s apart): one track stopped short` : null; }; // One file alone (a muxed recording): the scan. export async function verifyScan(ffprobeBin: string, file: string, signal?: AbortSignal, o: { fragmentSeconds?: number } = {}): Promise { const s = await scanMediaFile(ffprobeBin, file, signal); if ("error" in s) return { ok: false, why: `it does not read (${s.error})` }; for (const t of s.tracks) { const h = holeOf(t); if (h) return { ok: false, why: h }; } const apart = tracksApart(s.tracks, o.fragmentSeconds ?? 0); if (apart) return { ok: false, why: apart }; return { ok: true, tracks: s.tracks }; } // A merged file against the stream files it was made from. export async function verifyMerged(ffprobeBin: string, merged: string, streams: readonly string[], signal?: AbortSignal, o: { fragmentSeconds?: number } = {}): Promise { const m = await scanMediaFile(ffprobeBin, merged, signal); if ("error" in m) return { ok: false, why: `the merged file does not read (${m.error})` }; for (const t of m.tracks) { const h = holeOf(t); if (h) return { ok: false, why: `the merged file has ${h}` }; } const apart = tracksApart(m.tracks, o.fragmentSeconds ?? 0); if (apart) return { ok: false, why: `the merged file: ${apart}` }; for (const f of streams) { const s = await scanMediaFile(ffprobeBin, f, signal); if ("error" in s) return { ok: false, why: `${f.split("/").pop()} does not read (${s.error})` }; for (const t of s.tracks) { if (t.kind === "other") continue; const h = holeOf(t); if (h) return { ok: false, why: `${f.split("/").pop()} has ${h}` }; const mt = m.tracks.find((x) => x.kind === t.kind); if (!mt) return { ok: false, why: `the merged file has no ${t.kind} track` }; if (mt.packets !== t.packets) return { ok: false, why: `its ${t.kind}: ${mt.packets} packets merged, ${t.packets} in ${f.split("/").pop()}` }; const tol = Math.max(0.5, 2 * t.medianStep); if (Math.abs(mt.span - t.span) > tol) return { ok: false, why: `its ${t.kind}: ${mt.span.toFixed(2)} s merged, ${t.span.toFixed(2)} s in ${f.split("/").pop()}` }; } } return { ok: true, tracks: m.tracks }; }