Skip to content

Open source CapCut alternative.

TypeScript

fix(site): crop expressions ride quoted through ffmpeg's graph parser [rebuild]

David Lec973f6cc8180
diff --git a/site/src/cut/server/convert.ts b/site/src/cut/server/convert.ts
index f4968b4d..d9042c76 100644
--- a/site/src/cut/server/convert.ts
+++ b/site/src/cut/server/convert.ts
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
import { h264Encoder, runFfmpeg, sdrConvert, vtQuality, type RenderHandle } from "./exportPipeline";
+import { assertGraphSafe } from "./filterGraph";
import { videoColorInfo, videoDimensions } from "./util";
/**
@@ -132,7 +133,7 @@ export async function convertToMp4(
// is where an odd source height would otherwise land.
const scale = shrink ? `scale=-2:${cap - (cap % 2)},` : "";
const chain = `${sdr}${scale}`.replace(/,$/, "");
- if (chain) video.push("-vf", chain);
+ if (chain) video.push("-vf", assertGraphSafe(chain));
const enc = await h264Encoder();
video.push(
...(enc === "libx264"
diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.ts
index de729ef8..5c781bae 100644
--- a/site/src/cut/server/exportPipeline.test.ts
+++ b/site/src/cut/server/exportPipeline.test.ts
@@ -481,6 +481,11 @@ describe("the project background in the filtergraph", () => {
expect(g.join(";")).toContain("color=0xFFFFFF");
});
+ test("a covering clip's crop quotes its min() so the graph parser keeps it whole", async () => {
+ const g = await graphFor({ clips: [clip("a.mp4", { fit: "fill", zoom: 1.5 })] });
+ expect(g.join(";")).toContain("crop='min(iw,1080)':'min(ih,1920)'");
+ });
+
test("no background named keeps the black frame every cut had before", async () => {
const g = await graphFor({ clips: [clip("", { out: 4, hidden: true, muted: true })] });
expect(g.join(";")).toContain("color=c=black:");
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index 9c95ce17..592421c2 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "node:child_process";
import { stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { atempoChain, hasStream, num, videoColorInfo } from "./util";
+import { assertGraphSafe, fexpr } from "./filterGraph";
import { CLIP_MAX_ZOOM, projectFadeSeconds, regionPx, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";
import { effectFilterLines, gradeToFfmpegFilter, lookFilterLines, shortestTurn, sortedKeys, type OverlayKey } from "@donkeycut/effects-kit";
@@ -433,7 +434,7 @@ export async function runExport(
if (!cover && z <= 1.0001) return scale;
const kx = num(0.5 + Math.max(-1, Math.min(1, panX ?? 0)) / 2);
const ky = num(0.5 + Math.max(-1, Math.min(1, panY ?? 0)) / 2);
- return `${scale},crop=min(iw\,${bw}):min(ih\,${bh}):(iw-ow)*${kx}:(ih-oh)*${ky}`;
+ return `${scale},crop=${fexpr(`min(iw,${bw})`)}:${fexpr(`min(ih,${bh})`)}:(iw-ow)*${kx}:(ih-oh)*${ky}`;
};
// One ffmpeg input per distinct media file (from the project folder),
// plus one per uploaded overlay PNG.
@@ -1688,7 +1689,7 @@ export async function runExport(
[
"-y",
...inputs,
- "-filter_complex", filters.join(";"),
+ "-filter_complex", assertGraphSafe(filters.join(";")),
"-map", `[${vLabel}]`,
"-map", `[${aLabel}]`,
...videoCodecArgs,
diff --git a/site/src/cut/server/filterGraph.test.ts b/site/src/cut/server/filterGraph.test.ts
new file mode 100644
index 00000000..f9b5ae8e
--- /dev/null
+++ b/site/src/cut/server/filterGraph.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "bun:test";
+import { assertGraphSafe, fexpr } from "./filterGraph";
+
+const thrown = (fn: () => unknown): string => {
+ try {
+ fn();
+ return "";
+ } catch (e) {
+ return (e as Error).message;
+ }
+};
+
+describe("filter graph safety", () => {
+ test("fexpr quotes an expression so its commas ride through the graph parser", () => {
+ expect(fexpr("min(iw,330)")).toBe("'min(iw,330)'");
+ });
+
+ test("fexpr refuses an expression carrying a single quote", () => {
+ expect(thrown(() => fexpr("min(iw,'330')"))).toContain("single quote");
+ });
+
+ test("a bare comma inside a call is caught before ffmpeg sees it", () => {
+ expect(
+ thrown(() =>
+ assertGraphSafe("[1:v]scale=330:716,crop=min(iw,330):min(ih,716):(iw-ow)*0.5[o]")
+ )
+ ).toContain("fexpr()");
+ });
+
+ test("quoted and escaped commas pass, as do the chain and graph separators", () => {
+ const g =
+ "[0:v]crop='min(iw,330)':'min(ih,716)',fps=30[v0];" +
+ "[1:v]crop=min(iw\\,64):min(ih\\,64),overlay=enable='between(t,1,2)'[v1]";
+ expect(assertGraphSafe(g)).toBe(g);
+ });
+});
diff --git a/site/src/cut/server/filterGraph.ts b/site/src/cut/server/filterGraph.ts
new file mode 100644
index 00000000..2c974560
--- /dev/null
+++ b/site/src/cut/server/filterGraph.ts
@@ -0,0 +1,51 @@
+/**
+ * ffmpeg's graph parser splits chains on `,` and graphs on `;` wherever they
+ * appear — it ignores parentheses. An expression like `min(iw,330)` written
+ * bare into a filter option therefore cuts the graph mid-call, and the run
+ * dies with `No such filter: '330):min(ih'`. Two rules keep that impossible:
+ * every expression that can carry a comma goes through `fexpr`, and every
+ * assembled graph goes through `assertGraphSafe` on its way to ffmpeg.
+ */
+
+/** A filter option value single-quoted so the graph parser carries it whole. */
+export function fexpr(expr: string): string {
+ if (expr.includes("'")) {
+ throw new Error(`filter expression carries a single quote: ${expr}`);
+ }
+ return `'${expr}'`;
+}
+
+/**
+ * The assembled graph, checked: a bare `,` or `;` inside parentheses would
+ * split a filter mid-expression, so it throws here — at build, with the
+ * offending stretch named — before ffmpeg turns it into a cryptic parse error.
+ */
+export function assertGraphSafe(graph: string): string {
+ let depth = 0;
+ let quoted = false;
+ for (let i = 0; i < graph.length; i++) {
+ const ch = graph[i];
+ if (quoted) {
+ if (ch === "'") quoted = false;
+ continue;
+ }
+ if (ch === "\\") {
+ i++;
+ continue;
+ }
+ if (ch === "'") {
+ quoted = true;
+ } else if (ch === "(") {
+ depth++;
+ } else if (ch === ")") {
+ depth = Math.max(0, depth - 1);
+ } else if ((ch === "," || ch === ";") && depth > 0) {
+ const from = Math.max(0, i - 40);
+ throw new Error(
+ `filter graph splits inside an expression near "…${graph.slice(from, i + 20)}…" — ` +
+ `quote the expression with fexpr()`
+ );
+ }
+ }
+ return graph;
+}
diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.ts
index 5b4c565d..139abd82 100644
--- a/site/src/cut/server/frames.ts
+++ b/site/src/cut/server/frames.ts
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { mediaPath } from "./projects";
+import { assertGraphSafe, fexpr } from "./filterGraph";
import { num, round } from "./util";
function run(cmd: string, args: string[]): Promise<void> {
@@ -105,7 +106,7 @@ export async function makeFreezeFrame(
const even = (n: number) => 2 * Math.round(n / 2);
const kx = (0.5 + (framing?.panX ?? 0) / 2).toFixed(4);
const ky = (0.5 + (framing?.panY ?? 0) / 2).toFixed(4);
- const crop = `,crop=min(iw\,${w}):min(ih\,${h}):(iw-ow)*${kx}:(ih-oh)*${ky}`;
+ const crop = `,crop=${fexpr(`min(iw,${w})`)}:${fexpr(`min(ih,${h})`)}:(iw-ow)*${kx}:(ih-oh)*${ky}`;
vf = cover
? `scale=${even(w * z)}:${even(h * z)}:force_original_aspect_ratio=increase${crop}`
: `scale=${even(w * z)}:${even(h * z)}:force_original_aspect_ratio=decrease` +
@@ -119,7 +120,7 @@ export async function makeFreezeFrame(
"-i", png,
"-t", dur.toFixed(3),
"-r", "30",
- ...(vf ? ["-vf", vf] : []),
+ ...(vf ? ["-vf", assertGraphSafe(vf)] : []),
"-c:v", "libx264",
"-preset", "veryfast",
"-pix_fmt", "yuv420p",
diff --git a/site/src/cut/server/hlsLadder.ts b/site/src/cut/server/hlsLadder.ts
index 510c66fb..39587cd1 100644
--- a/site/src/cut/server/hlsLadder.ts
+++ b/site/src/cut/server/hlsLadder.ts
@@ -15,6 +15,7 @@ import { spawn } from "node:child_process";
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { runFfmpeg, type RenderHandle } from "./exportPipeline";
+import { assertGraphSafe } from "./filterGraph";
import { hasStream, videoDimensions } from "./util";
/** Segment length. Six seconds is the common VOD choice: long enough that
@@ -171,7 +172,7 @@ export async function encodeRungs(
[
"-y",
"-i", source,
- "-filter_complex", [split, ...scales].join(";"),
+ "-filter_complex", assertGraphSafe([split, ...scales].join(";")),
...maps,
...codecArgs,
...(withAudio ? ["-c:a", "aac", "-b:a", `${AUDIO_KBPS}k`, "-ac", "2"] : []),
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 832be513..8bc031e2 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -3,6 +3,7 @@ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"
import os from "node:os";
import path from "node:path";
import { alignCues } from "../lib/cueAlign";
+import { assertGraphSafe } from "./filterGraph";
import { assertLocalRuntime } from "./local-only";
import { createJobRegistry } from "./jobRegistry";
import { mediaPath, readProject } from "./projects";
@@ -422,7 +423,7 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
[
"-y",
...inputs,
- "-filter_complex", filters.join(";"),
+ "-filter_complex", assertGraphSafe(filters.join(";")),
"-map", `[${aLabel}]`,
"-ac", "1",
"-ar", "16000",
diff --git a/site/src/cut/worker/cardJob.ts b/site/src/cut/worker/cardJob.ts
index 806f11f3..84201297 100644
--- a/site/src/cut/worker/cardJob.ts
+++ b/site/src/cut/worker/cardJob.ts
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
import { stat } from "node:fs/promises";
import path from "node:path";
import type { RenderHandle } from "../server/exportPipeline";
+import { assertGraphSafe } from "../server/filterGraph";
import { prisma, registerObject, type ClaimedJob } from "./db";
import { cardKey, uploadFile } from "./r2";
@@ -68,9 +69,11 @@ async function renderAnimation(source: string, dest: string): Promise<number> {
"-i",
source,
"-vf",
- `fps=${recipe.fps},scale=w=${recipe.box}:h=${recipe.box}:` +
- `force_original_aspect_ratio=decrease:flags=lanczos,split[s0][s1];` +
- `[s0]palettegen=max_colors=${recipe.colors}[p];[s1][p]paletteuse=dither=bayer:bayer_scale=3`,
+ assertGraphSafe(
+ `fps=${recipe.fps},scale=w=${recipe.box}:h=${recipe.box}:` +
+ `force_original_aspect_ratio=decrease:flags=lanczos,split[s0][s1];` +
+ `[s0]palettegen=max_colors=${recipe.colors}[p];[s1][p]paletteuse=dither=bayer:bayer_scale=3`
+ ),
"-loop",
"0",
dest,