src/ffmpeg.js
// FFmpeg command builder. Nothing in this module spawns a process: commands are built as argv arrays
// from structured operations, every option is checked against an allowlist, filter values use
// FFmpeg's two-level filtergraph escaping, and argv is quoted for a POSIX shell or PowerShell.
// The `render` tool (src/run.js) executes argv built here, after validateArgv, without a shell.
import { ToolError } from "./errors.js";
// ------------------------------------------------------------------------------------------------
// Paths and times
// ------------------------------------------------------------------------------------------------
const CONTROL = /[\u0000-\u001f\u007f\u0085\u2028\u2029]/;
const VIDEO_EXT = /\.(mp4|mov|mkv|webm|m4v)$/i;
const SUB_EXT = /\.(srt|vtt|ass|ssa)$/i;
export function checkPath(p, field, { ext } = {}) {
const s = String(p);
if (!s.trim() || s !== s.trim()) throw new ToolError("invalid_input", `${field}: path must not be empty or start/end with spaces.`);
if (CONTROL.test(s)) throw new ToolError("invalid_input", `${field}: path contains control or line-break characters.`);
if (s.startsWith("-")) throw new ToolError("invalid_input", `${field}: path must not start with "-" (it would be read as an option); prefix it with ./`);
// Protocols (http:, concat:, pipe:, file:, data:, ...) are refused; a Windows drive letter is allowed.
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(s) && !/^[A-Za-z]:[\\/]/.test(s)) throw new ToolError("invalid_input", `${field}: URLs and FFmpeg protocols are not allowed; use a local file path.`);
if (ext && !ext.test(s)) throw new ToolError("invalid_input", `${field}: unexpected file extension (${s.slice(-12)}).`);
return s;
}
export function parseTime(v, field) {
if (typeof v === "number") {
if (!Number.isFinite(v) || v < 0 || v > 86400) throw new ToolError("invalid_input", `${field}: seconds must be between 0 and 86400.`);
return v;
}
const m = /^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/.exec(v) ?? /^(\d+)(?:\.(\d{1,3}))?$/.exec(v);
if (!m) throw new ToolError("invalid_input", `${field}: use seconds or HH:MM:SS(.mmm).`);
if (m.length === 3) return Number(v);
const [, h, mi, s, frac] = m;
if (Number(mi) > 59 && h !== undefined) throw new ToolError("invalid_input", `${field}: minutes must be below 60.`);
if (Number(s) > 59) throw new ToolError("invalid_input", `${field}: seconds must be below 60.`);
return Number(h ?? 0) * 3600 + Number(mi) * 60 + Number(s) + (frac ? Number(`0.${frac}`) : 0);
}
const secs = (x) => String(Math.round(x * 1000) / 1000);
// ------------------------------------------------------------------------------------------------
// Filtergraph escaping (https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping)
// Level 1 escapes an option value (special: \ ' :). Level 2 escapes a filter's argument string
// inside the graph (special: \ ' [ ] , ;). The shell level is handled by the quoting below.
// ------------------------------------------------------------------------------------------------
export const escapeValue = (v) => String(v).replace(/[\\':]/g, (c) => `\\${c}`);
export const escapeArgs = (a) => String(a).replace(/[\\'[\],;]/g, (c) => `\\${c}`);
export const filter = (name, opts) => `${name}=${escapeArgs(opts.map(([k, v]) => `${k}=${escapeValue(v)}`).join(":"))}`;
// ------------------------------------------------------------------------------------------------
// Allowlist validation
// ------------------------------------------------------------------------------------------------
const TIME_RE = /^\d+(\.\d{1,3})?$/;
const FILTERS = new Set(["subtitles", "scale", "pad", "crop", "setsar", "concat", "format", "fps"]);
const enumOf = (...vals) => (v) => vals.includes(v);
const PRESETS = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"];
function filterNamesOk(graph) {
// Drop escaped characters and quoted sections, then read each filter name.
const plain = graph.replace(/\\./g, "").replace(/'[^']*'/g, "");
return plain.split(/[,;]/).every((part) => {
const name = part.replace(/^(\[[^\]]*\])+/, "").split(/[=[]/)[0];
return FILTERS.has(name);
});
}
/** option -> number of values and a validator for each value (path checks are done separately). */
export const OPTIONS = {
"-hide_banner": { n: 0 },
"-nostdin": { n: 0 },
"-nostats": { n: 0 },
"-loglevel": { n: 1, ok: enumOf("error", "warning", "info") },
"-y": { n: 0 },
"-n": { n: 0 },
"-an": { n: 0 },
"-ss": { n: 1, ok: (v) => TIME_RE.test(v) },
"-t": { n: 1, ok: (v) => TIME_RE.test(v) },
"-fs": { n: 1, ok: (v) => /^\d{1,13}$/.test(v) },
// Input option: only the local file protocol (no http, concat:, pipe:, ...) for the next -i.
"-protocol_whitelist": { n: 1, ok: enumOf("file") },
"-i": { n: 1, path: true },
"-f": { n: 1, ok: enumOf("concat") },
"-safe": { n: 1, ok: enumOf("0", "1") },
"-c": { n: 1, ok: enumOf("copy") },
"-c:v": { n: 1, ok: enumOf("copy", "libx264", "libvpx-vp9") },
"-c:a": { n: 1, ok: enumOf("copy", "aac", "libopus") },
"-crf": { n: 1, ok: (v) => /^\d{1,2}$/.test(v) && Number(v) <= 51 },
"-preset": { n: 1, ok: (v) => PRESETS.includes(v) },
"-b:v": { n: 1, ok: enumOf("0") },
"-deadline": { n: 1, ok: enumOf("good", "realtime") },
"-cpu-used": { n: 1, ok: (v) => /^[0-8]$/.test(v) },
"-row-mt": { n: 1, ok: enumOf("1") },
"-pix_fmt": { n: 1, ok: enumOf("yuv420p") },
"-movflags": { n: 1, ok: enumOf("+faststart") },
"-b:a": { n: 1, ok: (v) => /^\d{2,3}k$/.test(v) },
"-map": { n: 1, ok: (v) => /^\[[a-z]{1,8}\]$/.test(v) || /^\d{1,3}:[va]\??$/.test(v) },
"-vf": { n: 1, ok: filterNamesOk },
"-filter_complex": { n: 1, ok: filterNamesOk },
};
/** Throws unless argv is `ffmpeg <allowed options and values...> <output path>`. */
export function validateArgv(argv) {
if (argv.length < 3) throw new ToolError("invalid_command", "Command too short.");
const paths = [];
for (let i = 1; i < argv.length; i++) {
const tok = argv[i];
if (i === argv.length - 1) {
if (OPTIONS[tok]) throw new ToolError("invalid_command", `The command ends with the option ${tok} instead of an output path.`);
checkPath(tok, "output");
paths.push({ role: "output", p: tok });
break;
}
const spec = OPTIONS[tok];
if (!spec) throw new ToolError("invalid_command", `Option not in the allowlist: ${String(tok).slice(0, 40)}`);
for (let k = 1; k <= spec.n; k++) {
const v = argv[i + k];
if (v === undefined || i + k === argv.length - 1) throw new ToolError("invalid_command", `${tok} is missing its value.`);
if (spec.path) {
checkPath(v, `${tok} value`);
paths.push({ role: "input", p: v });
} else if (!spec.ok(v)) throw new ToolError("invalid_command", `Value not allowed for ${tok}: ${String(v).slice(0, 80)}`);
}
i += spec.n;
}
const out = paths.find((x) => x.role === "output").p;
if (paths.some((x) => x.role === "input" && x.p === out)) throw new ToolError("invalid_input", "The output path must differ from every input path.");
return true;
}
// ------------------------------------------------------------------------------------------------
// Shell quoting
// ------------------------------------------------------------------------------------------------
const POSIX_SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/;
// PowerShell re-parses bare native arguments that contain ':' '.' '=' and similar (e.g. -c:v, a.mp4),
// so anything beyond letters, digits, '_' and '-' is single-quoted.
const PS_SAFE = /^[A-Za-z0-9_-]+$/;
export const quotePosix = (s) => (POSIX_SAFE.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`);
// PowerShell treats the typographic single quotes as quote characters too, so they are doubled as well.
export const quotePowerShell = (s) => (PS_SAFE.test(s) ? s : `'${s.replace(/['\u2018\u2019\u201a\u201b]/g, (c) => c + c)}'`);
export function render(argv, shell) {
const q = shell === "powershell" ? quotePowerShell : quotePosix;
const line = argv.map(q).join(" ");
return shell === "powershell" ? `& ${line}` : line;
}
// ------------------------------------------------------------------------------------------------
// Operation builders
// ------------------------------------------------------------------------------------------------
/** Container family of a path: "webm" (VP9/Opus), "mkv" (anything) or "mp4" (.mp4 .m4v .mov: H.264/AAC). */
export function containerOf(p) {
const ext = /\.([A-Za-z0-9]+)$/.exec(String(p))?.[1].toLowerCase();
return ext === "webm" ? "webm" : ext === "mkv" ? "mkv" : "mp4";
}
/** Stream copy works when the output container accepts the input's codecs (same family, or Matroska). */
export const copyCompatible = (input, output) => containerOf(output) === "mkv" || containerOf(input) === containerOf(output);
// libvpx-vp9 speed mapped from x264 presets: [deadline, cpu-used]. realtime/8 is fastest; good/0 is slowest and best.
const VP9_SPEED = { ultrafast: ["realtime", 8], superfast: ["realtime", 7], veryfast: ["good", 5], faster: ["good", 4], fast: ["good", 4], medium: ["good", 3], slow: ["good", 2], slower: ["good", 1], veryslow: ["good", 0] };
function videoArgs(o, out) {
if (containerOf(out) === "webm") {
return ["-c:v", "libvpx-vp9", "-crf", String(o.crf ?? 32), "-b:v", "0", "-deadline", VP9_SPEED[o.preset ?? "medium"][0], "-cpu-used", String(VP9_SPEED[o.preset ?? "medium"][1]), "-row-mt", "1", "-pix_fmt", "yuv420p"];
}
return ["-c:v", "libx264", "-crf", String(o.crf ?? 20), "-preset", o.preset ?? "medium", "-pix_fmt", "yuv420p"];
}
const audioEncode = (out) => (containerOf(out) === "webm" ? ["-c:a", "libopus", "-b:a", "128k"] : ["-c:a", "aac", "-b:a", "192k"]);
const muxArgs = (out) => (/\.(mp4|m4v|mov)$/i.test(out) ? ["-movflags", "+faststart"] : []);
const AUDIO_FITS = { mp4: ["aac", "mp3"], webm: ["opus", "vorbis"] };
/**
* Audio for operations that keep the source audio. Without probe hints (text-only commands): stream
* copy, except into WebM, which needs Opus. With hints from ffprobe (render): copy only when the
* codec fits the container, re-encode otherwise, and -an when the input has no audio stream.
*/
function keepAudio(out, hints) {
if (hints.audioCodec === null) return ["-an"];
const c = containerOf(out);
if (hints.audioCodec === undefined) return c === "webm" ? audioEncode(out) : ["-c:a", "copy"];
return c === "mkv" || AUDIO_FITS[c].includes(hints.audioCodec) ? ["-c:a", "copy"] : audioEncode(out);
}
/** A concat-demuxer "safe" path: relative, portable characters, no component starting with a dot. */
const concatSafe = (p) => !/^([A-Za-z]:)?[\\/]/.test(p) && p.split(/[\\/]/).every((c) => /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(c));
/**
* Builds the arguments (without the ffmpeg binary, global flags and output path) for one structured
* operation. `hints` (optional, from ffprobe in render): { audioCodec: string | null }.
*/
export function buildOperation(o, i, hints = {}) {
const f = `operations[${i}]`;
const notes = [];
const files = [];
let args;
const webm = containerOf(o.output) === "webm";
if (o.op === "trim") {
if (!o.input) throw new ToolError("invalid_input", `${f}: trim needs input.`);
checkPath(o.input, `${f}.input`, { ext: VIDEO_EXT });
checkPath(o.output, `${f}.output`, { ext: VIDEO_EXT });
const start = o.start !== undefined ? parseTime(o.start, `${f}.start`) : 0;
let dur;
if (o.end !== undefined && o.duration !== undefined) throw new ToolError("invalid_input", `${f}: give end or duration, not both.`);
if (o.end !== undefined) dur = parseTime(o.end, `${f}.end`) - start;
else if (o.duration !== undefined) dur = parseTime(o.duration, `${f}.duration`);
else throw new ToolError("invalid_input", `${f}: trim needs end or duration.`);
if (!(dur > 0)) throw new ToolError("invalid_input", `${f}: end must be after start.`);
args = ["-ss", secs(start), "-i", o.input, "-t", secs(dur)];
if (o.reencode) args.push(...videoArgs(o, o.output), ...(hints.audioCodec === null ? ["-an"] : audioEncode(o.output)), ...muxArgs(o.output));
else {
if (!copyCompatible(o.input, o.output)) throw new ToolError("invalid_input", `${f}: stream copy cannot move this input into a .${o.output.split(".").pop()} file; set reencode: true or keep the same container.`);
args.push("-c", "copy");
notes.push("Stream copy is fast and lossless but cuts at keyframes, so the start can shift slightly; set reencode: true for frame-accurate cuts.");
}
} else if (o.op === "concat") {
if (!o.inputs) throw new ToolError("invalid_input", `${f}: concat needs inputs (2 or more).`);
o.inputs.forEach((p, k) => checkPath(p, `${f}.inputs[${k}]`, { ext: VIDEO_EXT }));
checkPath(o.output, `${f}.output`, { ext: VIDEO_EXT });
if ((o.method ?? "demuxer") === "demuxer") {
if (!o.inputs.every((p) => copyCompatible(p, o.output))) throw new ToolError("invalid_input", `${f}: the concat demuxer copies streams, so the output container must match the inputs (or be .mkv); use method: filter to re-encode.`);
const list = o.list_file ?? "concat-list.txt";
checkPath(list, `${f}.list_file`, { ext: /\.txt$/i });
const content = o.inputs.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n";
files.push({ path: list, content });
const safe = o.inputs.every(concatSafe);
args = ["-f", "concat", ...(safe ? [] : ["-safe", "0"]), "-i", list, "-c", "copy"];
notes.push(`Save the files[] content as ${list} first. Paths inside it are resolved relative to the list file's folder.`);
notes.push("The concat demuxer needs every input to share codecs, resolution and frame rate; use method: filter otherwise.");
if (!safe) notes.push("-safe 0 is needed because some paths are absolute or use characters outside FFmpeg's portable set.");
} else {
const audio = o.audio !== false;
const n = o.inputs.length;
const pads = o.inputs.map((_, k) => (audio ? `[${k}:v][${k}:a]` : `[${k}:v]`)).join("");
const graph = `${pads}concat=n=${n}:v=1:a=${audio ? 1 : 0}[v]${audio ? "[a]" : ""}`;
args = [...o.inputs.flatMap((p) => ["-i", p]), "-filter_complex", graph, "-map", "[v]", ...(audio ? ["-map", "[a]"] : ["-an"]), ...videoArgs(o, o.output), ...(audio ? audioEncode(o.output) : []), ...muxArgs(o.output)];
notes.push("The concat filter re-encodes; all inputs need the same resolution and sample aspect ratio (use fit first if they differ)" + (audio ? " and an audio stream." : "."));
}
} else if (o.op === "burn_captions") {
if (!o.input || !o.subtitles) throw new ToolError("invalid_input", `${f}: burn_captions needs input and subtitles.`);
checkPath(o.input, `${f}.input`, { ext: VIDEO_EXT });
checkPath(o.subtitles, `${f}.subtitles`, { ext: SUB_EXT });
checkPath(o.output, `${f}.output`, { ext: VIDEO_EXT });
const subPath = o.subtitles.replace(/\\/g, "/");
if (subPath !== o.subtitles) notes.push("Backslashes in the subtitles path were written as forward slashes (FFmpeg accepts them on Windows).");
const style = [`FontSize=${o.font_size ?? 16}`, `Outline=${o.outline ?? 2}`, `MarginV=${o.margin_v ?? 40}`, "Alignment=2"].join(",");
args = ["-i", o.input, "-vf", filter("subtitles", [["filename", subPath], ["force_style", style]]), ...videoArgs(o, o.output), ...keepAudio(o.output, hints), ...muxArgs(o.output)];
notes.push("Needs an FFmpeg build with libass (the subtitles filter). The subtitles path is resolved from the folder you run FFmpeg in.");
} else if (o.op === "fit") {
if (!o.input || !o.width || !o.height) throw new ToolError("invalid_input", `${f}: fit needs input, width and height.`);
if (o.width % 2 || o.height % 2) throw new ToolError("invalid_input", `${f}: width and height must be even for yuv420p video.`);
checkPath(o.input, `${f}.input`, { ext: VIDEO_EXT });
checkPath(o.output, `${f}.output`, { ext: VIDEO_EXT });
const w = String(o.width);
const h = String(o.height);
const chain =
(o.mode ?? "pad") === "pad"
? [filter("scale", [["w", w], ["h", h], ["force_original_aspect_ratio", "decrease"]]), filter("pad", [["w", w], ["h", h], ["x", "(ow-iw)/2"], ["y", "(oh-ih)/2"]]), "setsar=1"]
: [filter("scale", [["w", w], ["h", h], ["force_original_aspect_ratio", "increase"]]), filter("crop", [["w", w], ["h", h]]), "setsar=1"];
args = ["-i", o.input, "-vf", chain.join(","), ...videoArgs(o, o.output), ...keepAudio(o.output, hints), ...muxArgs(o.output)];
notes.push(o.mode === "crop" ? "crop fills the frame and cuts off the edges; check that nothing important is lost." : "pad keeps the whole picture and adds bars.");
} else if (o.op === "transcode") {
if (!o.input) throw new ToolError("invalid_input", `${f}: transcode needs input.`);
checkPath(o.input, `${f}.input`, { ext: VIDEO_EXT });
checkPath(o.output, `${f}.output`, { ext: VIDEO_EXT });
args = ["-i", o.input, ...videoArgs(o, o.output), ...(hints.audioCodec === null ? ["-an"] : audioEncode(o.output)), ...muxArgs(o.output)];
notes.push(webm ? "Re-encodes to VP9 video and Opus audio (WebM)." : "Re-encodes to H.264 video and AAC audio.");
} else throw new ToolError("invalid_input", `${f}: unknown op.`);
if (webm && (o.op === "burn_captions" || o.op === "fit" || o.reencode || o.method === "filter")) notes.push("WebM output: VP9 video (constant quality, -b:v 0) and Opus audio.");
return { args, notes, files };
}