src/run.js
// The `render` tool: EXECUTES allowlisted FFmpeg operations on local files. This is the only module
// of this agent that starts processes or writes files. Safety measures:
// - structured operations only, built by ffmpeg.js and re-checked with validateArgv (option, value
// and filter allowlists) before anything runs;
// - spawn() with an argv array and shell: false, a scrubbed environment and a timeout;
// - ffmpeg/ffprobe located only via FFMPEG_PATH / FFPROBE_PATH (absolute paths) or absolute PATH
// entries; a clear "ffmpeg_not_found" error otherwise;
// - every path must resolve (after symlinks) inside the media root: AGENTROVE_MEDIA_ROOT, or the
// folder the CLI / MCP server was started in;
// - inputs are probed with ffprobe (protocol_whitelist=file, container and subtitle format
// allowlists, a video stream is required) before FFmpeg runs, with -protocol_whitelist file on
// every FFmpeg input too;
// - limits: output duration (checked before running and enforced with -t), output size (-fs),
// per-operation timeout;
// - an output may never replace an input; an existing output is kept unless overwrite is true;
// - a failed operation's partial output is removed only if this run created it.
import { spawn } from "node:child_process";
import { statSync, lstatSync, realpathSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve, dirname, basename, relative, sep, delimiter, isAbsolute } from "node:path";
import { ToolError } from "./errors.js";
import { buildOperation, validateArgv, checkPath, containerOf, parseTime } from "./ffmpeg.js";
const IS_WIN = process.platform === "win32";
const EXE = IS_WIN ? ".exe" : "";
const INSTALL_HINT = "Install FFmpeg (official downloads: ffmpeg.org/download.html) and set FFMPEG_PATH to the full path of the ffmpeg executable, or add its folder to PATH.";
export const LIMITS = {
defaultTimeoutSeconds: 600,
defaultMaxOutputSeconds: 900,
defaultMaxOutputMegabytes: 1024,
maxSubtitleBytes: 512 * 1024,
};
// Input containers FFmpeg may open (ffprobe format_name), and subtitle formats for burn_captions.
const VIDEO_FORMATS = new Set(["mov", "mp4", "matroska", "webm"]);
const SUB_FORMATS = new Set(["srt", "webvtt", "ass"]);
// ------------------------------------------------------------------------------------------------
// Locating FFmpeg
// ------------------------------------------------------------------------------------------------
const isFile = (p) => {
try {
return statSync(p).isFile();
} catch {
return false;
}
};
function fromEnv(env, key, name) {
const p = env[key];
if (!isAbsolute(p) || !new RegExp(`^${name}(\\.exe)?$`, "i").test(basename(p))) {
throw new ToolError("ffmpeg_not_found", `${key} must be the absolute path of the ${name}${EXE} executable (got "${String(p).slice(0, 200)}"). ${INSTALL_HINT}`);
}
if (!isFile(p)) throw new ToolError("ffmpeg_not_found", `FFmpeg not found: ${key} points to ${p}, which does not exist. ${INSTALL_HINT}`);
return p;
}
function onPath(env, name) {
// Only absolute PATH entries, so a binary planted in the current folder is never picked up.
const dirs = String(env.PATH ?? env.Path ?? "").split(delimiter).filter((d) => d && isAbsolute(d));
return dirs.map((d) => join(d, `${name}${EXE}`)).find(isFile) ?? null;
}
/** Finds ffmpeg and ffprobe: FFMPEG_PATH / FFPROBE_PATH, then ffprobe next to ffmpeg, then PATH. */
export function locateBinaries(env = process.env) {
const ffmpeg = env.FFMPEG_PATH ? fromEnv(env, "FFMPEG_PATH", "ffmpeg") : onPath(env, "ffmpeg");
if (!ffmpeg) throw new ToolError("ffmpeg_not_found", `FFmpeg not found: FFMPEG_PATH is not set and no ffmpeg${EXE} is on PATH. ${INSTALL_HINT}`);
let ffprobe;
if (env.FFPROBE_PATH) ffprobe = fromEnv(env, "FFPROBE_PATH", "ffprobe");
else {
const sibling = join(dirname(ffmpeg), `ffprobe${EXE}`);
ffprobe = isFile(sibling) ? sibling : onPath(env, "ffprobe");
}
if (!ffprobe) throw new ToolError("ffmpeg_not_found", `ffprobe not found next to ${ffmpeg} or on PATH (set FFPROBE_PATH). ffprobe ships with FFmpeg. ${INSTALL_HINT}`);
return { ffmpeg, ffprobe };
}
// ------------------------------------------------------------------------------------------------
// Running processes (no shell)
// ------------------------------------------------------------------------------------------------
const ENV_KEEP = new Set(["PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "LANG", "LC_ALL", "FONTCONFIG_FILE", "FONTCONFIG_PATH"]);
/** The child gets only the variables it needs (no API keys or tokens from the parent environment). */
function childEnv() {
const out = {};
for (const [k, v] of Object.entries(process.env)) if (ENV_KEEP.has(k.toUpperCase()) && v !== undefined) out[k] = v;
return out;
}
export function runProcess(bin, args, { cwd, timeoutMs, maxStdout = 4 * 1024 * 1024, maxStderr = 64 * 1024 }) {
return new Promise((done) => {
let stdout = "";
let stderr = "";
let timedOut = false;
let child;
try {
child = spawn(bin, args, { cwd, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: childEnv() });
} catch (error) {
done({ code: null, error, stdout, stderr, timedOut });
return;
}
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, timeoutMs);
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (d) => {
if (stdout.length < maxStdout) stdout += d;
});
child.stderr.on("data", (d) => {
stderr = (stderr + d).slice(-maxStderr);
});
child.on("error", (error) => {
clearTimeout(timer);
done({ code: null, error, stdout, stderr, timedOut });
});
child.on("close", (code, signal) => {
clearTimeout(timer);
done({ code, signal, stdout, stderr, timedOut });
});
});
}
export const tail = (s, lines = 20) => String(s).trim().split(/\r?\n/).filter(Boolean).slice(-lines).join("\n").slice(-2000);
const capsCache = new Map();
async function capabilities(bins, cwd) {
if (capsCache.has(bins.ffmpeg)) return capsCache.get(bins.ffmpeg);
const run = (a) => runProcess(bins.ffmpeg, ["-hide_banner", ...a], { cwd, timeoutMs: 20000 });
const [ver, enc, fil] = await Promise.all([run(["-version"]), run(["-encoders"]), run(["-filters"])]);
if (ver.error || ver.code !== 0) throw new ToolError("ffmpeg_not_found", `Could not run ${bins.ffmpeg} (${ver.error?.code ?? `exit ${ver.code}`}). ${INSTALL_HINT}`);
const caps = {
version: ver.stdout.split(/\r?\n/)[0].trim().slice(0, 200),
encoders: new Set([...enc.stdout.matchAll(/^\s*[VAS][A-Z.]{5}\s+(\S+)/gm)].map((m) => m[1])),
filters: new Set([...fil.stdout.matchAll(/^\s*[A-Z.]{2,3}\s+(\S+)\s+\S+->\S+/gm)].map((m) => m[1])),
};
capsCache.set(bins.ffmpeg, caps);
return caps;
}
// ------------------------------------------------------------------------------------------------
// ffprobe
// ------------------------------------------------------------------------------------------------
const rate = (r) => {
const m = /^(\d+)\/(\d+)$/.exec(r ?? "");
return m && Number(m[2]) ? Math.round((Number(m[1]) / Number(m[2])) * 1000) / 1000 : undefined;
};
const num = (v) => (v === undefined || v === "N/A" || Number.isNaN(Number(v)) ? undefined : Number(v));
/** Probes a local file; returns normalized metadata or { error } (never throws for unreadable media). */
export async function probe(bins, file, { cwd, timeoutMs = 30000 } = {}) {
const r = await runProcess(
bins.ffprobe,
["-v", "error", "-protocol_whitelist", "file", "-show_entries", "format=format_name,duration,size,bit_rate:stream=index,codec_type,codec_name,profile,width,height,pix_fmt,avg_frame_rate,sample_aspect_ratio,display_aspect_ratio,sample_rate,channels", "-of", "json", file],
{ cwd, timeoutMs },
);
if (r.error) throw new ToolError("ffmpeg_not_found", `Could not run ffprobe at ${bins.ffprobe} (${r.error.code ?? r.error.message}). ${INSTALL_HINT}`);
if (r.timedOut) return { error: "ffprobe timed out" };
if (r.code !== 0) return { error: tail(r.stderr, 3) || `ffprobe exited with code ${r.code}` };
let j;
try {
j = JSON.parse(r.stdout);
} catch {
return { error: "ffprobe returned unreadable output" };
}
const streams = (j.streams ?? []).map((s) => {
const o = { index: s.index, codec_type: s.codec_type, codec_name: s.codec_name ?? "unknown" };
if (s.profile) o.profile = String(s.profile);
if (s.width) o.width = s.width;
if (s.height) o.height = s.height;
if (s.pix_fmt) o.pix_fmt = s.pix_fmt;
const fr = rate(s.avg_frame_rate);
if (s.codec_type === "video" && fr) o.frame_rate = fr;
if (s.display_aspect_ratio && s.display_aspect_ratio !== "0:1") o.display_aspect_ratio = s.display_aspect_ratio;
if (s.sample_aspect_ratio && s.sample_aspect_ratio !== "0:1") o.sample_aspect_ratio = s.sample_aspect_ratio;
if (num(s.sample_rate)) o.sample_rate = num(s.sample_rate);
if (s.channels) o.channels = s.channels;
return o;
});
const fmt = j.format ?? {};
return {
format_name: String(fmt.format_name ?? ""),
duration_seconds: num(fmt.duration) !== undefined ? Math.round(num(fmt.duration) * 1000) / 1000 : undefined,
size_bytes: num(fmt.size),
bit_rate: num(fmt.bit_rate),
streams,
};
}
const video = (m) => m.streams.find((s) => s.codec_type === "video");
const audio = (m) => m.streams.find((s) => s.codec_type === "audio");
// ------------------------------------------------------------------------------------------------
// Paths
// ------------------------------------------------------------------------------------------------
const key = (p) => (IS_WIN ? p.toLowerCase() : p);
const within = (root, p) => key(p) === key(root) || key(p).startsWith(key(root.endsWith(sep) ? root : root + sep));
export function mediaRoot(dir) {
let real;
try {
real = realpathSync(resolve(dir));
} catch {
throw new ToolError("invalid_input", `The media folder ${dir} does not exist.`);
}
if (!statSync(real).isDirectory()) throw new ToolError("invalid_input", `The media folder ${dir} is not a folder.`);
return real;
}
function lexical(root, p, field) {
checkPath(p, field);
// Besides a leading drive letter, no ':' at all (FFmpeg protocol syntax, NTFS alternate data streams).
if (p.replace(/^[A-Za-z]:[\\/]/, "").includes(":")) throw new ToolError("invalid_input", `${field}: ":" is not allowed in render paths (except after a drive letter).`);
const abs = resolve(root, p);
if (!within(root, abs)) throw new ToolError("path_outside_root", `${field}: ${p} is outside the media folder (${root}). render only reads and writes files inside it; set AGENTROVE_MEDIA_ROOT or start the CLI/MCP server in the folder that holds your media.`);
return abs;
}
function existingInput(root, p, field) {
const abs = lexical(root, p, field);
let real;
try {
real = realpathSync(abs);
} catch {
throw new ToolError("invalid_input", `${field}: ${p} was not found in the media folder.`);
}
if (!within(root, real)) throw new ToolError("path_outside_root", `${field}: ${p} resolves (through a link) to a file outside the media folder.`);
if (!statSync(real).isFile()) throw new ToolError("invalid_input", `${field}: ${p} is not a regular file.`);
return real;
}
/** Folder resolved through links + file name: how an output path (or a not-yet-produced input) is compared. */
function canonical(abs) {
try {
return join(realpathSync(dirname(abs)), basename(abs));
} catch {
return abs;
}
}
function outputTarget(root, p, field) {
const abs = lexical(root, p, field);
let parent;
try {
parent = realpathSync(dirname(abs));
} catch {
throw new ToolError("invalid_input", `${field}: the folder for ${p} does not exist (render does not create folders).`);
}
if (!within(root, parent)) throw new ToolError("path_outside_root", `${field}: the folder for ${p} resolves outside the media folder.`);
const target = join(parent, basename(abs));
let st = null;
try {
st = lstatSync(target);
} catch {
/* does not exist yet */
}
if (st?.isSymbolicLink()) throw new ToolError("invalid_input", `${field}: ${p} is a symbolic link; render does not write through links.`);
if (st && !st.isFile()) throw new ToolError("invalid_input", `${field}: ${p} exists and is not a regular file.`);
return { abs: target, existed: !!st };
}
const rel = (root, p) => relative(root, p).split(sep).join("/");
// ------------------------------------------------------------------------------------------------
// render
// ------------------------------------------------------------------------------------------------
const SUB_TEXT_RE = /^(?:\uFEFF)?(?:WEBVTT|\s*\d+\s*\r?\n\s*\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}\s*-->)/;
/** Static checks for every operation: no process is started and nothing is written. */
function planOperations(ops, root, overwrite) {
const produced = new Map(); // key(abs output) -> operation index
const originals = new Map(); // key(real input) -> description
const plan = ops.map((o, i) => {
const f = `operations[${i}]`;
if (o.subtitles_text !== undefined && o.op !== "burn_captions") throw new ToolError("invalid_input", `${f}: subtitles_text is only used by burn_captions.`);
if (o.op === "burn_captions" && o.subtitles !== undefined && o.subtitles_text !== undefined) throw new ToolError("invalid_input", `${f}: give subtitles (a file) or subtitles_text, not both.`);
if (o.op === "burn_captions" && o.subtitles_text !== undefined) {
if (!SUB_TEXT_RE.test(o.subtitles_text) || !o.subtitles_text.includes("-->")) throw new ToolError("invalid_input", `${f}.subtitles_text: expected SubRip (SRT) or WebVTT caption text, e.g. the captions_srt output of export_captions.`);
if (Buffer.byteLength(o.subtitles_text) > LIMITS.maxSubtitleBytes) throw new ToolError("invalid_input", `${f}.subtitles_text is larger than ${LIMITS.maxSubtitleBytes} bytes.`);
}
// Same structural validation as ffmpeg_commands (paths, extensions, times, sizes).
buildOperation({ ...o, subtitles: o.subtitles ?? (o.subtitles_text !== undefined ? (o.subtitles_text.trimStart().replace(/^\uFEFF/, "").startsWith("WEBVTT") ? "captions.vtt" : "captions.srt") : undefined) }, i);
const resolveIn = (p, field) => {
const abs = canonical(lexical(root, p, field));
if (produced.has(key(abs))) return { given: p, abs, produced: true };
const real = existingInput(root, p, field);
originals.set(key(real), `${field} (${p})`);
return { given: p, abs: real, produced: false };
};
const inputs = o.op === "concat" ? o.inputs.map((p, k) => resolveIn(p, `${f}.inputs[${k}]`)) : [resolveIn(o.input, `${f}.input`)];
const subtitles = o.op === "burn_captions" && o.subtitles !== undefined ? resolveIn(o.subtitles, `${f}.subtitles`) : null;
const out = outputTarget(root, o.output, `${f}.output`);
if (produced.has(key(out.abs))) throw new ToolError("invalid_input", `${f}.output: ${o.output} is also written by operations[${produced.get(key(out.abs))}].`);
produced.set(key(out.abs), i);
return { o, i, f, inputs, subtitles, out };
});
// Checked after every input is known, so an output can never replace an input of any operation.
for (const p of plan) {
const hit = originals.get(key(p.out.abs));
if (hit) throw new ToolError("would_overwrite_input", `${p.f}.output: ${p.o.output} is an input (${hit}); render never overwrites an input.`);
}
for (const p of plan) {
if (p.out.existed && !overwrite) throw new ToolError("output_exists", `${p.f}.output: ${p.o.output} already exists. Choose a new name, or set overwrite: true to replace it (inputs are never replaced).`);
}
return plan;
}
function expectedDuration(p, metas) {
const d = metas.map((m) => m.duration_seconds ?? 0);
if (p.o.op === "concat") return d.reduce((a, b) => a + b, 0);
if (p.o.op === "trim") {
const start = p.o.start !== undefined ? parseTime(p.o.start, `${p.f}.start`) : 0;
const len = p.o.end !== undefined ? parseTime(p.o.end, `${p.f}.end`) - start : parseTime(p.o.duration, `${p.f}.duration`);
if (metas[0].duration_seconds !== undefined && start >= metas[0].duration_seconds) throw new ToolError("invalid_input", `${p.f}: start (${start} s) is at or after the end of ${p.o.input} (${metas[0].duration_seconds} s).`);
return metas[0].duration_seconds !== undefined ? Math.min(len, metas[0].duration_seconds - start) : len;
}
return d[0];
}
function checkCompat(p, metas) {
if (p.o.op !== "concat") return;
const vs = metas.map(video);
const sameSize = vs.every((v) => v.width === vs[0].width && v.height === vs[0].height);
if ((p.o.method ?? "demuxer") === "demuxer") {
const as = metas.map(audio);
const same = sameSize && vs.every((v) => v.codec_name === vs[0].codec_name) && as.every((a) => (a?.codec_name ?? null) === (as[0]?.codec_name ?? null));
if (!same) throw new ToolError("incompatible_inputs", `${p.f}: the concat demuxer needs inputs with the same codecs and resolution (${metas.map((m, k) => `${p.o.inputs[k]}: ${video(m).codec_name} ${video(m).width}x${video(m).height}${audio(m) ? `/${audio(m).codec_name}` : "/no audio"}`).join("; ")}). Use method: filter, and fit first if sizes differ.`);
} else {
if (!sameSize) throw new ToolError("incompatible_inputs", `${p.f}: the concat filter needs inputs with the same resolution (${metas.map((m, k) => `${p.o.inputs[k]}: ${video(m).width}x${video(m).height}`).join("; ")}). Run fit on them first.`);
if (p.o.audio !== false && metas.some((m) => !audio(m))) throw new ToolError("incompatible_inputs", `${p.f}: ${p.o.inputs.filter((_, k) => !audio(metas[k])).join(", ")} has no audio stream; set audio: false or add audio.`);
}
}
function withInputWhitelist(args) {
const out = [];
for (const a of args) {
if (a === "-i") out.push("-protocol_whitelist", "file");
out.push(a);
}
return out;
}
/**
* Executes the operations in order (a later operation may use an earlier one's output).
* opts: { root, env, bins, timeoutMs, maxOutputBytes } - overrides for tests and embedding.
*/
export async function runRender(input, opts = {}) {
const env = opts.env ?? process.env;
const root = mediaRoot(opts.root ?? env.AGENTROVE_MEDIA_ROOT ?? process.cwd());
const overwrite = input.overwrite === true;
const timeoutMs = opts.timeoutMs ?? Math.round((input.timeout_seconds ?? LIMITS.defaultTimeoutSeconds) * 1000);
const maxSeconds = input.max_output_seconds ?? LIMITS.defaultMaxOutputSeconds;
const maxBytes = opts.maxOutputBytes ?? Math.round((input.max_output_megabytes ?? LIMITS.defaultMaxOutputMegabytes) * 1024 * 1024);
const plan = planOperations(input.operations, root, overwrite); // 1. static checks, before FFmpeg is even looked up
const bins = opts.bins ?? locateBinaries(env); // 2. find FFmpeg
const caps = await capabilities(bins, root);
const tmp = mkdtempSync(join(tmpdir(), "agentrove-render-"));
const results = [];
const warnings = [];
const fail = (code, message) => {
const doneMsg = results.length ? ` Completed before the failure: ${results.map((r) => r.output).join(", ")}.` : " No operation completed.";
return new ToolError(code, `${message}${doneMsg}`, { completed: results });
};
try {
for (const p of plan) {
const { o, i, f } = p;
// 3. Probe inputs (produced intermediates exist now).
const metas = [];
for (const [k, inp] of p.inputs.entries()) {
const field = o.op === "concat" ? `${f}.inputs[${k}]` : `${f}.input`;
const m = await probe(bins, inp.abs, { cwd: root });
if (m.error) throw fail("invalid_media", `${field}: ${inp.given} is not a readable video file (ffprobe: ${m.error}).`);
if (!m.format_name.split(",").some((n) => VIDEO_FORMATS.has(n))) throw fail("invalid_media", `${field}: ${inp.given} is a "${m.format_name}" file; render accepts MP4/MOV, Matroska and WebM containers only.`);
if (!video(m)) throw fail("invalid_media", `${field}: ${inp.given} has no video stream.`);
metas.push(m);
}
let subtitlesPath;
if (o.op === "burn_captions") {
if (p.subtitles) subtitlesPath = p.subtitles.abs;
else {
const vtt = o.subtitles_text.trimStart().replace(/^\uFEFF/, "").startsWith("WEBVTT");
subtitlesPath = join(tmp, `captions-${i}.${vtt ? "vtt" : "srt"}`);
writeFileSync(subtitlesPath, o.subtitles_text, "utf8");
}
const sm = await probe(bins, subtitlesPath, { cwd: root });
if (sm.error || !sm.format_name.split(",").some((n) => SUB_FORMATS.has(n))) throw fail("invalid_media", `${f}: the subtitles are not a readable SRT, WebVTT or ASS file (${sm.error ?? sm.format_name}).`);
if (!caps.filters.has("subtitles")) throw fail("ffmpeg_missing_feature", `${f}: this FFmpeg build has no subtitles filter (it needs libass). Install a build with libass.`);
}
// 4. Limits and compatibility.
let expected;
try {
checkCompat(p, metas);
expected = expectedDuration(p, metas);
} catch (e) {
throw fail(e.code ?? "invalid_input", e.message);
}
if (expected > maxSeconds) throw fail("limit_exceeded", `${f}: the output would be about ${Math.round(expected)} s long, above max_output_seconds (${maxSeconds}).`);
// 5. Build, validate and run the exact argv.
const real = { ...o, output: p.out.abs };
if (o.op === "concat") real.inputs = p.inputs.map((x) => x.abs);
else real.input = p.inputs[0].abs;
if (o.op === "burn_captions") real.subtitles = subtitlesPath;
if (o.op === "concat" && (o.method ?? "demuxer") === "demuxer") real.list_file = join(tmp, `concat-${i}.txt`);
delete real.subtitles_text;
const a0 = audio(metas[0]);
const built = buildOperation(real, i, { audioCodec: a0 ? a0.codec_name : null });
for (const file of built.files) writeFileSync(file.path, file.content, "utf8"); // concat list, in the private temp folder
const args = withInputWhitelist(built.args);
const cap = o.op === "trim" ? [] : ["-t", String(Math.ceil(maxSeconds))];
const argv = [bins.ffmpeg, "-hide_banner", "-nostdin", "-nostats", "-loglevel", "warning", p.out.existed ? "-y" : "-n", ...args, ...cap, "-fs", String(maxBytes), p.out.abs];
validateArgv(argv);
for (let k = 1; k < argv.length - 1; k++) {
if ((argv[k] === "-c:v" || argv[k] === "-c:a") && argv[k + 1] !== "copy" && !caps.encoders.has(argv[k + 1])) throw fail("ffmpeg_missing_feature", `${f}: this FFmpeg build has no ${argv[k + 1]} encoder.`);
}
const started = Date.now();
const r = await runProcess(bins.ffmpeg, argv.slice(1), { cwd: root, timeoutMs });
const elapsed = Date.now() - started;
const cleanup = () => {
if (!p.out.existed) rmSync(p.out.abs, { force: true });
};
if (r.error) {
cleanup();
throw fail("ffmpeg_not_found", `${f}: could not start FFmpeg (${r.error.code ?? r.error.message}). ${INSTALL_HINT}`);
}
if (r.timedOut) {
cleanup();
throw fail("timeout", `${f} (${o.op}) was stopped after ${Math.round(timeoutMs / 100) / 10} s (timeout_seconds); its partial output was removed.`);
}
if (r.code !== 0) {
cleanup();
throw fail("ffmpeg_failed", `${f} (${o.op}) failed: FFmpeg exited with code ${r.code}${p.out.existed ? "" : "; its partial output was removed"}. Last FFmpeg messages:\n${tail(r.stderr) || "(none)"}`);
}
const size = isFile(p.out.abs) ? statSync(p.out.abs).size : 0;
if (!size) {
cleanup();
throw fail("ffmpeg_failed", `${f} (${o.op}): FFmpeg exited normally but wrote no output. Last FFmpeg messages:\n${tail(r.stderr) || "(none)"}`);
}
if (size >= maxBytes) {
cleanup();
throw fail("limit_exceeded", `${f}: the output reached max_output_megabytes (${Math.round((maxBytes / 1048576) * 100) / 100} MB) and was cut off, so it was removed.`);
}
// 6. Verify the output with ffprobe.
const m = await probe(bins, p.out.abs, { cwd: root });
if (m.error || !video(m)) throw fail("ffmpeg_failed", `${f}: the output ${o.output} could not be verified with ffprobe (${m.error ?? "no video stream"}).`);
if (m.duration_seconds !== undefined && expected && Math.abs(m.duration_seconds - expected) > Math.max(0.5, expected * 0.05)) {
warnings.push(`${f}: output is ${m.duration_seconds} s, expected about ${Math.round(expected * 100) / 100} s.`);
}
const messages = tail(r.stderr, 6);
results.push({
index: i,
op: o.op,
output: rel(root, p.out.abs),
argv,
exit_code: 0,
elapsed_ms: elapsed,
output_metadata: { path: rel(root, p.out.abs), container: containerOf(p.out.abs), ...m },
notes: [...built.notes.filter((n) => !/^Save the files\[\]|resolved from the folder you run/.test(n)), ...(p.out.existed ? ["Replaced the existing output file (overwrite: true)."] : [])],
...(messages ? { ffmpeg_messages: messages } : {}),
});
}
} finally {
rmSync(tmp, { recursive: true, force: true });
}
return {
executed: true,
media_root: root,
ffmpeg: { path: bins.ffmpeg, ffprobe_path: bins.ffprobe, version: caps.version },
results,
warnings,
};
}