import { execFile } from "node:child_process"; import path from "node:path"; import { lstat } from "node:fs/promises"; import { localRecordingDuration } from "./localRecordingMetadata"; // Internal process adapter, not an HTTP action. The controller must first resolve // the file through the configured library and apply channel/storage guards. // ffprobeBin comes from Paths (FFPROBE_BIN), never from form input. export async function probeLocalRecording(options: { file: string; ffprobeBin: string; signal?: AbortSignal; timeoutMs?: number; }): Promise<{ format: { duration: number }; streams: Array<{ codec_type: "video" }> }> { if (!path.isAbsolute(options.file) || !/\.mp4$/i.test(options.file)) throw new Error("Expected an absolute local MP4 path"); options.signal?.throwIfAborted(); const before = await lstat(options.file); if (!before.isFile() || before.isSymbolicLink()) throw new Error("Expected a regular MP4 file"); const timeout = options.timeoutMs ?? 15000; if (!Number.isFinite(timeout) || timeout < 1 || timeout > 15000) throw new Error("Invalid inspection timeout"); const stdout = await new Promise((resolve, reject) => { execFile(options.ffprobeBin, ["-v", "error", "-protocol_whitelist", "file", "-f", "mov", "-show_entries", "format=duration:stream=codec_type:stream_disposition=attached_pic", "-of", "json", options.file], { encoding: "utf8", timeout, maxBuffer: 256 * 1024, killSignal: "SIGKILL", windowsHide: true, signal: options.signal, }, (error, output) => { if (!error) { resolve(output); return; } // Never expose ffprobe stderr: it can contain full private source paths. const code = (error as NodeJS.ErrnoException).code; reject(new Error(options.signal?.aborted ? "Media inspection cancelled" : code === "ENOENT" ? "ffprobe is unavailable on the editor server. Install FFmpeg with ffprobe, or configure FFPROBE_BIN." : code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "Media inspection exceeded its output limit" : error.killed ? "Media inspection exceeded its time limit" : "Media inspection failed; check that the file is a readable MP4")); }); }); const after = await lstat(options.file); if (!after.isFile() || after.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) { throw new Error("Recording changed during inspection; preview again"); } options.signal?.throwIfAborted(); let raw: unknown; try { raw = JSON.parse(stdout); } catch { throw new Error("Media inspection returned invalid data"); } const duration = localRecordingDuration(raw); // Only facts needed by preparation cross this boundary. No tags, filenames, // source URLs or embedded timestamps are copied into managed metadata. return { format: { duration }, streams: [{ codec_type: "video" }] }; }