Skip to content

Open source CapCut alternative.

TypeScript

fix(site): keep pass edges exact and tunable [rebuild]

David Le4268b049e813
diff --git a/site/scripts/eval-cut-export-memory.ts b/site/scripts/eval-cut-export-memory.ts
index 951a2f5e..2a66cc17 100644
--- a/site/scripts/eval-cut-export-memory.ts
+++ b/site/scripts/eval-cut-export-memory.ts
@@ -25,6 +25,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { retimeOf } from "@donkeycut/effects-kit";
import { runExport, type ExportSpec, type RenderHandle } from "../src/cut/server/exportPipeline";
+import { SETTINGS } from "../src/lib/config/registry";
const SITE = path.resolve(import.meta.dir, "..");
const REPORT = path.resolve(SITE, "..", "evals", "cut-export-memory.latest-report.json");
@@ -53,7 +54,7 @@ const CUT_COUNTS = [60, 180] as const;
const GROWTH_MAX = 1.5;
/** The most any export may peak at: the pass budget, which a reordered edit
* spends on frames waiting for their turn, plus the process around it. */
-const PEAK_MAX_MB = 2560;
+const PEAK_MAX_MB = SETTINGS.cutExportPasses.default.holdMB + 512;
type Order = "in order" | "reordered";
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 331d6029..87fdb2b4 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -1,6 +1,7 @@
"use client";
import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge, bindCutNotes, bindCutTracking } from "@/cut/lib/chatRuntime";
import { bindCutColor } from "@/cut/lib/colorSettings";
+import { bindCutExportPasses } from "@/cut/lib/exportPassSettings";
import { bindCutSound } from "@/cut/lib/soundSettings";
import { bindCutMotion } from "@/cut/lib/motionSettings";
import { bindCutLoudness } from "@/cut/lib/loudnessSettings";
@@ -55,6 +56,7 @@ export function RequireSession({ children }: { children: ReactNode }) {
bindCutSound(config.data.settings.cutSound);
bindCutMotion(config.data.settings.cutMotion);
bindCutLoudness(config.data.settings.cutLoudness);
+ bindCutExportPasses(config.data.settings.cutExportPasses);
bindCutMediaCache(config.data.settings.cutMediaCache);
reportExposures(config.data);
}, [userId, config.data]);
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index fd27a2b0..9f845732 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -10,6 +10,7 @@ import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
import { engineFeatures } from "./api";
import type { EngineFeature } from "./engineFeatures";
import { cutColor } from "./colorSettings";
+import { cutExportPasses } from "./exportPassSettings";
import { loadLibraryLutFile, lutIdOf } from "./linkedLibrary/luts";
import {
removeBrowserExportJob,
@@ -1514,6 +1515,7 @@ export async function buildExportPayload(
colorSpace: target === "export" ? doc.colorSpace ?? "sdr" : "sdr",
lutSize: cutColor().lutSize,
lutSizeWide: cutColor().lutSizeWide,
+ passes: cutExportPasses(),
duration,
background: projectBackground(doc.background),
clips,
diff --git a/site/src/cut/lib/exportPassSettings.ts b/site/src/cut/lib/exportPassSettings.ts
new file mode 100644
index 00000000..affeac11
--- /dev/null
+++ b/site/src/cut/lib/exportPassSettings.ts
@@ -0,0 +1,16 @@
+import { SETTINGS, type Settings } from "@/lib/config/registry";
+
+// The export pass budget — the memory one ffmpeg pass may hold and the pieces
+// it opens — bound once at session start from account config (the tab) or the
+// global setting (a worker job), and sent with every export spec.
+
+let passes: Settings["cutExportPasses"] = SETTINGS.cutExportPasses.default;
+
+export function bindCutExportPasses(value: unknown): void {
+ const parsed = SETTINGS.cutExportPasses.schema.safeParse(value);
+ if (parsed.success) passes = parsed.data;
+}
+
+export function cutExportPasses(): Settings["cutExportPasses"] {
+ return passes;
+}
diff --git a/site/src/cut/server/exportAudio.test.ts b/site/src/cut/server/exportAudio.test.ts
new file mode 100644
index 00000000..e5fbb393
--- /dev/null
+++ b/site/src/cut/server/exportAudio.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from "bun:test";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { masterRawMix } from "./exportAudio";
+
+describe("masterRawMix", () => {
+ test("pieces laid end to end master as the one mix they make", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "cut-master-"));
+ try {
+ // Three seconds of stereo tone, split at a point that is not a whole
+ // second, so a chunk straddles the two files.
+ const rate = 48_000;
+ const samples = new Float32Array(rate * 3 * 2);
+ for (let i = 0; i < samples.length; i++) {
+ samples[i] = 0.2 * Math.sin((i >> 1) * 0.05);
+ }
+ const bytes = new Uint8Array(samples.buffer);
+ const cut = 2 * 4 * 70_001;
+ const [whole, a, b] = ["whole.f32", "a.f32", "b.f32"].map((f) => path.join(dir, f));
+ await writeFile(whole, bytes);
+ await writeFile(a, bytes.subarray(0, cut));
+ await writeFile(b, bytes.subarray(cut));
+
+ const opts = { sampleRate: rate, channels: 2, targetLufs: -16, ceilingDbtp: -1 };
+ await masterRawMix([whole], path.join(dir, "one.f32"), opts);
+ await masterRawMix([a, b], path.join(dir, "two.f32"), opts);
+ const one = await readFile(path.join(dir, "one.f32"));
+ expect(one.length).toBe(bytes.length);
+ expect((await readFile(path.join(dir, "two.f32"))).equals(one)).toBe(true);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/site/src/cut/server/exportAudio.ts b/site/src/cut/server/exportAudio.ts
index 49abec5b..95ef8fe7 100644
--- a/site/src/cut/server/exportAudio.ts
+++ b/site/src/cut/server/exportAudio.ts
@@ -8,47 +8,52 @@ import { writeStoredZip } from "../lib/stems";
// Both stream through files a second at a time, so an hour of sound costs a
// second of it in memory.
-/** Raw interleaved 32-bit float PCM, read a second at a time as planar
- * chunks. */
-async function* rawChunks(file: string, sampleRate: number, channels: number): AsyncGenerator<Float32Array[]> {
+/** Raw interleaved 32-bit float PCM in files laid end to end, read a second
+ * at a time as planar chunks. */
+async function* rawChunks(files: string[], sampleRate: number, channels: number): AsyncGenerator<Float32Array[]> {
const frameBytes = channels * 4;
const bytes = new Uint8Array(sampleRate * frameBytes);
- const handle = await open(file, "r");
- try {
- let pos = 0;
- let carry = 0;
- for (;;) {
- const { bytesRead } = await handle.read(bytes, carry, bytes.length - carry, pos);
- pos += bytesRead;
- const have = carry + bytesRead;
- const frames = Math.floor(have / frameBytes);
- if (frames > 0) {
- const view = new DataView(bytes.buffer, 0, frames * frameBytes);
- const planar = Array.from({ length: channels }, () => new Float32Array(frames));
- for (let i = 0; i < frames; i++) {
- for (let c = 0; c < channels; c++) planar[c][i] = view.getFloat32((i * channels + c) * 4, true);
+ let carry = 0;
+ for (const file of files) {
+ const handle = await open(file, "r");
+ try {
+ let pos = 0;
+ for (;;) {
+ const { bytesRead } = await handle.read(bytes, carry, bytes.length - carry, pos);
+ if (bytesRead === 0) {
+ break;
+ }
+ pos += bytesRead;
+ const have = carry + bytesRead;
+ const frames = Math.floor(have / frameBytes);
+ if (frames > 0) {
+ const view = new DataView(bytes.buffer, 0, frames * frameBytes);
+ const planar = Array.from({ length: channels }, () => new Float32Array(frames));
+ for (let i = 0; i < frames; i++) {
+ for (let c = 0; c < channels; c++) planar[c][i] = view.getFloat32((i * channels + c) * 4, true);
+ }
+ yield planar;
}
- yield planar;
+ carry = have - frames * frameBytes;
+ if (carry > 0) bytes.copyWithin(0, frames * frameBytes, have);
}
- carry = have - frames * frameBytes;
- if (carry > 0) bytes.copyWithin(0, frames * frameBytes, have);
- if (bytesRead === 0) return;
+ } finally {
+ await handle.close();
}
- } finally {
- await handle.close();
}
}
-/** Master the raw float mix at `input` into `output`, same layout. */
+/** Master the raw float mix in `inputs`, read in order as one stream, into
+ * `output`, same layout. */
export async function masterRawMix(
- input: string,
+ inputs: string[],
output: string,
opts: { sampleRate: number; channels: number; targetLufs: number; ceilingDbtp: number }
): Promise<MasterReport> {
const out = await open(output, "w");
try {
return await masterStream(
- () => rawChunks(input, opts.sampleRate, opts.channels),
+ () => rawChunks(inputs, opts.sampleRate, opts.channels),
async (chunk) => {
const frames = chunk[0].length;
const buf = new Uint8Array(frames * opts.channels * 4);
diff --git a/site/src/cut/server/exportPipeline.e2e.test.ts b/site/src/cut/server/exportPipeline.e2e.test.ts
index a2a3ea56..f33e6279 100644
--- a/site/src/cut/server/exportPipeline.e2e.test.ts
+++ b/site/src/cut/server/exportPipeline.e2e.test.ts
@@ -286,6 +286,11 @@ const sampleGap = (a: Int16Array, b: Int16Array) => {
return a.reduce((gap, v, i) => Math.max(gap, Math.abs(v - b[i])), 0);
};
+/** The spec rendered in passes of `pieces`, at the default memory budget. */
+const inPieces = (spec: ExportSpec, pieces: number): ExportSpec => ({ ...spec, passes: { holdMB: 2048, pieces } });
+/** More pieces than any fixture has: the whole delivery in one pass. */
+const ONE_PASS = 10_000;
+
describe("a delivery rendered in passes", () => {
// The same every-feature project rendered in one pass and in passes of two
// pieces. ProRes is intra-only and the sound is PCM, so the same frames and
@@ -313,7 +318,7 @@ describe("a delivery rendered in passes", () => {
{ name: "Music", lane: 0, file: "2 Music.wav" },
],
};
- expect(passWindows(spec, () => ({ pixels: 0, fps: 30 }), 2).length).toBeGreaterThan(2);
+ expect(passWindows(inPieces(spec, 2), () => ({ pixels: 0, fps: 30 })).length).toBeGreaterThan(2);
// Each render runs in its own copy of the job dir, so the stems it
// packs stay on disk beside its file.
@@ -327,10 +332,10 @@ describe("a delivery rendered in passes", () => {
progress: 0,
log: [],
};
- await runExport(job, spec, (file) => path.join(mediaDir, file), undefined, passPieces);
+ await runExport(job, inPieces(spec, passPieces), (file) => path.join(mediaDir, file));
return { file: job.outPath, stems: spec.stemPlan!.map((_, i) => path.join(dir, `stem_${i}.wav`)) };
};
- const whole = await render("whole", Infinity);
+ const whole = await render("whole", ONE_PASS);
const passes = await render("passes", 2);
expect(framesOf(passes.file)).toEqual(framesOf(whole.file));
@@ -369,7 +374,8 @@ describe("a long recording cut out of order", () => {
const clips: ExportSpec["clips"] = at.map((from, k) => ({
file: "talk.mp4",
in: from,
- out: from + 1.5,
+ // 37 frames: window edges fall between milliseconds.
+ out: from + 37 / 24,
muted: false,
soundBack: 0.4,
soundAhead: 0.4,
@@ -399,16 +405,16 @@ describe("a long recording cut out of order", () => {
container: "mov",
audioCodec: "pcm",
};
- expect(passWindows(spec, () => ({ pixels: 0, fps: 30 }), 3).length).toBeGreaterThan(3);
+ expect(passWindows(inPieces(spec, 3), () => ({ pixels: 0, fps: 30 })).length).toBeGreaterThan(3);
const render = async (name: string, passPieces: number) => {
const dir = path.join(jobsDir, name);
await mkdir(dir);
const job: RenderHandle = { tmpDir: dir, outPath: path.join(dir, "out.mov"), progress: 0, log: [] };
- await runExport(job, spec, (file) => path.join(mediaDir, file), undefined, passPieces);
+ await runExport(job, inPieces(spec, passPieces), (file) => path.join(mediaDir, file));
return job.outPath;
};
- const whole = await render("whole", Infinity);
+ const whole = await render("whole", ONE_PASS);
const passes = await render("passes", 3);
// An AAC decoder fills noise-coded bands from a generator a seek
// restarts, so a pass that reads from its window's first source
diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.ts
index 09bda98e..dbaf92f4 100644
--- a/site/src/cut/server/exportPipeline.test.ts
+++ b/site/src/cut/server/exportPipeline.test.ts
@@ -26,8 +26,10 @@ const stagedFiles = new Map<string, string>();
const probedDims = new Map<string, { width: number; height: number }>();
/** The masters and stem packs the last run asked for. */
-let mastered: { input: string; output: string; opts: Parameters<ExportPipelineIO["masterRawMix"]>[2] }[] = [];
+let mastered: { inputs: string[]; output: string; opts: Parameters<ExportPipelineIO["masterRawMix"]>[2] }[] = [];
let packed: { files: { path: string; name: string }[]; output: string }[] = [];
+/** Each stream probe the last run made, as `kind:file`. */
+let streamProbes: string[] = [];
/** A pass to cancel the job during, the way the dock's cancel lands mid-render. */
let cancelDuring: "master" | "stems" | null = null;
@@ -39,6 +41,7 @@ const runsWithCap = async (over: Partial<ExportSpec>, cap: number | undefined):
written = [];
mastered = [];
packed = [];
+ streamProbes = [];
// Seconds each turned file was asked to produce, summed off the `-t` of the
// chunk runs that wrote its pieces, so the bake reads back a whole file.
const produced = new Map<string, number>();
@@ -52,15 +55,19 @@ const runsWithCap = async (over: Partial<ExportSpec>, cap: number | undefined):
return new TextEncoder().encode(stagedFiles.get(path.basename(file)) ?? "");
}) as unknown as ExportPipelineIO["readFile"],
unlink: (async () => {}) as unknown as ExportPipelineIO["unlink"],
- hasStream: async () => true,
+ hasStream: async (file, kind) => {
+ streamProbes.push(`${kind}:${file}`);
+ return true;
+ },
audioChannels: async (file) => (file.includes("mono") ? 1 : 2),
videoDecodeCost: async () => null,
+ videoPicture: async () => null,
videoDimensions: async (file) => probedDims.get(file) ?? null,
mediaDuration: async (file) => produced.get(file) ?? 0,
videoEncoder: async (codec) =>
codec === "hevc" ? "libx265" : codec.startsWith("prores") ? "prores_ks" : "libx264",
- masterRawMix: async (input, output, opts) => {
- mastered.push({ input, output, opts });
+ masterRawMix: async (inputs, output, opts) => {
+ mastered.push({ inputs, output, opts });
if (cancelDuring === "master") job.error = "Export canceled.";
return {} as Awaited<ReturnType<ExportPipelineIO["masterRawMix"]>>;
},
@@ -96,7 +103,7 @@ const runsWithCap = async (over: Partial<ExportSpec>, cap: number | undefined):
progress: 0,
log: [],
};
- await runExport(job, spec, (f) => `/media/${f}`, io, cap);
+ await runExport(job, cap === undefined ? spec : { ...spec, passes: { holdMB: 2048, pieces: cap } }, (f) => `/media/${f}`, io);
return ffmpegCalls;
};
@@ -483,6 +490,12 @@ describe("passes", () => {
expect(fast.length).toBeGreaterThan(backward.length);
});
+ test("gaps decode nothing, so they hold no frames", () => {
+ // Ten three-second cuts in file order with a three-second gap after each.
+ const clips = Array.from({ length: 10 }, (_, i) => [clip("a.mp4", { in: i * 3, out: i * 3 + 3 }), clip("", { in: 0, out: 3 })]).flat();
+ expect(passWindows(long(20, { clips, duration: 60 }), () => ({ pixels: 1080 * 1920, fps: 30 }))).toEqual([{ start: 0, end: 60 }]);
+ });
+
test("a range is split inside itself", () => {
const windows = passWindows(long(120, { range: { start: 31, end: 200 } }), () => ({ pixels: 1080 * 1920, fps: 30 }));
expect(windows[0].start).toBe(31);
@@ -505,6 +518,8 @@ describe("passes", () => {
expect(a.slice(a.indexOf("-filter_complex") + 2, video)).not.toContain("-c:a");
expect(a.slice(video, mix)).toContain("pcm_f32le");
}
+ // The passes share one look at each file.
+ expect(streamProbes.length).toBe(new Set(streamProbes).size);
const join = passes.at(-1)!;
expect(arg(join, "-display_rotation")).toBe("0");
expect(arg(join, "-f")).toBe("concat");
@@ -1276,17 +1291,53 @@ describe("delivery", () => {
const spec = {
projectId: "p", width: 1080, height: 1920, fps: 30, crf: 24, preset: "veryfast",
duration: 15,
- range: { start: 6, end: 8 },
+ range: { start: 2, end: 3.8 },
clips: [clip("a.mp4", { out: 5, transition: 1 }), clip("b.mp4", { out: 5 }), clip("c.mp4", { out: 5 })],
audio: [],
overlays: [],
} as unknown as ExportSpec;
- // Slots [0,5) [5,10) [10,15): a one-second join reaches 1.5 s past each
- // edge, so the first slot (ending at 5, within 1.5 of 6) stays and the
- // last (starting at 10, beyond 1.5 of 8) is hidden.
+ // Slots [0,5) [5,10) [10,15): the one-second join holds b's first frame
+ // from 4, so b, within the half-second slack of that, stays; c is hidden.
+ expect(narrowSpecToRange(spec).clips.map((c) => !!c.hidden)).toEqual([false, false, true]);
+ });
+
+ test("a clip animating in over its neighbor's held frame keeps the neighbor", () => {
+ const spec = {
+ projectId: "p", width: 1080, height: 1920, fps: 30, crf: 24, preset: "veryfast",
+ duration: 15,
+ range: { start: 6, end: 8 },
+ clips: [
+ clip("a.mp4", { out: 5 }),
+ clip("b.mp4", { out: 5, animIn: { style: "slideleft", seconds: 1.3 } }),
+ clip("c.mp4", { out: 5 }),
+ ],
+ audio: [],
+ overlays: [],
+ } as unknown as ExportSpec;
+ // b slides in over a's last frame until 6.3, inside the range, so a stays.
expect(narrowSpecToRange(spec).clips.map((c) => !!c.hidden)).toEqual([false, false, true]);
});
+ test("a long join reaches only the clips beside it", () => {
+ const spec = {
+ projectId: "p", width: 1080, height: 1920, fps: 30, crf: 24, preset: "veryfast",
+ duration: 25,
+ range: { start: 6, end: 8 },
+ clips: [
+ clip("a.mp4", { out: 5 }),
+ clip("b.mp4", { out: 5 }),
+ clip("c.mp4", { out: 5 }),
+ clip("d.mp4", { out: 5, transition: 3 }),
+ clip("e.mp4", { out: 5 }),
+ ],
+ audio: [],
+ overlays: [],
+ } as unknown as ExportSpec;
+ // The 3 s join between d and e is far from the range: a, ending 1 s
+ // before it, and c, starting 2 s after, are beyond the half-second slack.
+ expect(narrowSpecToRange(spec).clips.map((c) => !!c.hidden)).toEqual([true, false, true, true, true]);
+ });
+
test("a slot the range hides opens none of its inputs", async () => {
const runs = await runsFor({
duration: 15,
@@ -1793,7 +1844,7 @@ describe("a mastered delivery", () => {
expect(enc.slice(videoOut, mixAt)).toContain("pcm_f32le");
expect(mastered).toEqual([
{
- input: "/tmp/graph-test/mix.f32",
+ inputs: ["/tmp/graph-test/mix.f32"],
output: "/tmp/graph-test/master.f32",
opts: { sampleRate: 44100, channels: 2, targetLufs: -14, ceilingDbtp: -1 },
},
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index 7c71f052..b401acd2 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -6,7 +6,8 @@ import { deliveryCodec, deliveryContainer, deliverySpan, KEYFRAME_INTERVAL_S, vi
export type { SpecClipColor };
import { readFile, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
-import { atempoChain, audioChannels, hasStream, mediaDuration, num, videoDecodeCost, videoDimensions } from "./util";
+import { atempoChain, audioChannels, hasStream, mediaDuration, num, videoDecodeCost, videoDimensions, videoPicture } from "./util";
+import { SETTINGS, type Settings } from "@/lib/config/registry";
import { xfadeTransition } from "./transitionExpr";
import { assertGraphSafe, fanOutInputs, fexpr } from "./filterGraph";
import { bakeRetimedAudio, setptsExpr, type BakedAudio } from "./retimeAudio";
@@ -82,6 +83,9 @@ export interface ExportSpec {
* and sRGB sources, `lutSizeWide` for log and HDR. */
lutSize?: number;
lutSizeWide?: number;
+ /** The memory one encode pass may hold and the most pieces it opens;
+ * absent = the setting's default. */
+ passes?: Settings["cutExportPasses"];
/** Where the render lands instead of a stamped file in exports/: "hls" is the
* share's streaming ladder, "preview"
* writes the project's low-res hover proxy, "card" the opening seconds the
@@ -754,34 +758,39 @@ const RANGE_SLACK_S = 0.5;
const READ_MARGIN_S = 1;
const READ_SEEK_MIN_S = 10;
-/** How far past a range's edges a clip still shapes the frames inside it. */
-const rangeReach = (spec: ExportSpec) =>
- Math.max(
- 0,
- ...spec.clips.map((c) => Math.max(c.transition ?? 0, c.soundCross ?? 0, c.soundAhead ?? 0, c.soundBack ?? 0))
- ) + RANGE_SLACK_S;
+/**
+ * How far before and after its slot each track-0 clip shapes the delivery:
+ * its own sound handles, the join and sound crossing at each of its cuts, and
+ * a neighbor's edge animation that plays over its held frame. A 1 s join
+ * into clip j reaches 1 s back from j's start; a 1.3 s entrance on clip j
+ * reaches 1.3 s past clip j-1's end.
+ */
+function clipReach(spec: ExportSpec): { before: number; after: number }[] {
+ return spec.clips.map((c, j) => {
+ const prev = spec.clips[j - 1];
+ const next = spec.clips[j + 1];
+ return {
+ before: Math.max(c.soundBack ?? 0, prev?.transition ?? 0, prev?.soundCross ?? 0, prev?.animOut?.seconds ?? 0),
+ after: Math.max(c.soundAhead ?? 0, c.soundCross ?? 0, next?.animIn?.seconds ?? 0),
+ };
+ });
+}
/**
- * What one encode pass may hold for its pieces — track-0 clips, layered clips
- * and elements. Every piece's input is primed when the graph opens and its
- * chain keeps frames through the encode, about PIECE_FRAMES of its source's
- * size or the delivery's, whichever is larger; cuts played out of file order
- * add the frames their decoder holds until their turn. One pass over a long
- * timeline grows with it, and passes held to this budget stay flat; a larger
- * budget means fewer passes, each decoding the stretch of file its cuts span.
- * PASS_PIECES caps the count whatever the size: each piece brings a decoder
- * and its threads.
+ * Frames each piece of a pass holds: every piece's input is primed when the
+ * graph opens and its chain keeps frames through the encode, about this many
+ * of its source's size or the delivery's, whichever is larger. Cuts played
+ * out of file order add the frames their decoder holds until their turn. The
+ * pass budget (the cutExportPasses setting) caps their sum and the count.
*/
-const PASS_HOLD_BYTES = 2 * 1024 * 1024 * 1024;
const PIECE_FRAMES = 16;
-const PASS_PIECES = 48;
/** A source's decoded picture: its size in pixels and its frame rate. */
export type SourcePicture = { pixels: number; fps: number };
/** A piece of one window: its timeline span and, for footage, the file and
* the source seconds its picture reads. */
-type PassSpan = { start: number; end: number; file: string; lo?: number; hi?: number };
+type PassSpan = { start: number; end: number; before: number; after: number; file: string; lo?: number; hi?: number };
/**
* Seconds of source a file's one decoder holds at most for the window's cuts
@@ -805,52 +814,50 @@ function heldSeconds(cuts: PassSpan[]): number {
/**
* The delivery cut into the windows it renders in, one pass each: every
- * window touches at most `cap` pieces, and their primed frames plus the frames
- * its decoders hold for cuts out of file order stay within PASS_HOLD_BYTES
+ * window touches at most the budget's pieces, and their primed frames plus the
+ * frames its decoders hold for cuts out of file order stay within its memory
* (with the reach a range keeps); each window ends on a frame at a piece's
* start. `sourceOf` is a file's decoded picture. A delivery under the budget
* is one window. Each pass is a range export, so its frames and samples are
* the ones the whole composite has there, and the windows laid end to end
* are the delivery.
*/
-export function passWindows(
- spec: ExportSpec,
- sourceOf: (file: string) => SourcePicture,
- cap: number = PASS_PIECES
-): ExportRange[] {
+export function passWindows(spec: ExportSpec, sourceOf: (file: string) => SourcePicture): ExportRange[] {
+ const budget = spec.passes ?? SETTINGS.cutExportPasses.default;
const from = Math.max(0, spec.range?.start ?? 0);
const to = Math.min(spec.duration, spec.range?.end ?? spec.duration);
- const reach = rangeReach(spec);
const frameBytes = (file: string) => 1.5 * Math.max(sourceOf(file).pixels, spec.width * spec.height);
// Every piece the graph builds a chain for, as a timeline span, with the
// source a footage piece's picture reads.
const spans: PassSpan[] = [];
- const footage = (c: Parameters<typeof retimeOf>[0] & { image?: boolean }): Pick<PassSpan, "lo" | "hi"> => {
- if (c.image) {
+ const footage = (c: Parameters<typeof retimeOf>[0] & { file: string; image?: boolean }): Pick<PassSpan, "lo" | "hi"> => {
+ if (c.image || !c.file) {
return {};
}
const rt = retimeOf(c);
const { lo, hi } = srcSpan(rt, 0, rt.len);
return { lo: Math.max(0, lo - SOURCE_PREROLL), hi };
};
+ const reach = clipReach(spec);
let cursor = 0;
- for (const c of spec.clips) {
- spans.push({ start: cursor, end: cursor + spanLen(c), file: c.file, ...footage(c) });
+ for (const [j, c] of spec.clips.entries()) {
+ spans.push({ start: cursor, end: cursor + spanLen(c), ...reach[j], file: c.file, ...footage(c) });
cursor += spanLen(c);
}
for (const o of spec.overlayVideos ?? []) {
- spans.push({ start: o.start, end: o.start + spanLen(o), file: o.file, ...footage(o) });
+ const handles = { before: o.soundBack ?? 0, after: o.soundAhead ?? 0 };
+ spans.push({ start: o.start, end: o.start + spanLen(o), ...handles, file: o.file, ...footage(o) });
}
for (const o of spec.overlays) {
- spans.push({ start: o.start, end: o.end, file: "" });
+ spans.push({ start: o.start, end: o.end, before: 0, after: 0, file: "" });
}
// A window fits when its pieces' primed frames and its decoders' waiting
// ones come in under the budget.
const fits = (a: number, b: number) => {
- const held = spans.filter((s) => s.end >= a - reach && s.start <= b + reach);
- if (held.length > cap) {
+ const held = spans.filter((s) => s.end + s.after >= a - RANGE_SLACK_S && s.start - s.before <= b + RANGE_SLACK_S);
+ if (held.length > budget.pieces) {
return false;
}
let bytes = held.reduce((sum, s) => sum + PIECE_FRAMES * frameBytes(s.file), 0);
@@ -858,7 +865,7 @@ export function passWindows(
const cuts = held.filter((s) => s.file === file && s.lo !== undefined);
bytes += heldSeconds(cuts) * sourceOf(file).fps * frameBytes(file);
}
- return bytes <= PASS_HOLD_BYTES;
+ return bytes <= budget.holdMB * 1024 * 1024;
};
// Window edges sit on whole frames at piece starts, so each pass's trim
@@ -902,16 +909,16 @@ export function passWindows(
*/
export function narrowSpecToRange(spec: ExportSpec): ExportSpec {
if (!spec.range) return spec;
- const reach = rangeReach(spec);
- const from = Math.max(0, spec.range.start) - reach;
- const to = Math.min(spec.duration, spec.range.end) + reach;
+ const reach = clipReach(spec);
+ const from = Math.max(0, spec.range.start) - RANGE_SLACK_S;
+ const to = Math.min(spec.duration, spec.range.end) + RANGE_SLACK_S;
const inside = (start: number, end: number) => end >= from && start <= to;
let cursor = 0;
- const clips = spec.clips.map((c) => {
+ const clips = spec.clips.map((c, j) => {
const start = cursor;
const end = cursor + spanLen(c);
cursor = end;
- return c.hidden || inside(start, end) ? c : { ...c, hidden: true };
+ return c.hidden || inside(start - reach[j].before, end + reach[j].after) ? c : { ...c, hidden: true };
});
return {
...spec,
@@ -1007,6 +1014,7 @@ export interface ExportPipelineIO {
audioChannels: typeof audioChannels;
videoDecodeCost: typeof videoDecodeCost;
videoDimensions: typeof videoDimensions;
+ videoPicture: typeof videoPicture;
mediaDuration: typeof mediaDuration;
videoEncoder: (codec: ExportVideoCodec) => Promise<string>;
runFfmpeg: typeof runFfmpeg;
@@ -1026,6 +1034,7 @@ const realIO: ExportPipelineIO = {
audioChannels,
videoDecodeCost,
videoDimensions,
+ videoPicture,
mediaDuration,
videoEncoder,
runFfmpeg,
@@ -1034,14 +1043,12 @@ const realIO: ExportPipelineIO = {
/** Render `spec` into `job.outPath`. `mediaPathFor` maps a spec media file
* name to its staged path on disk (the engine reads the project folder; the
* worker reads its download dir); overlay/caption PNGs are read from
- * `job.tmpDir` by base name in both. `passPieces` caps the pieces one encode
- * pass opens (see passWindows). */
+ * `job.tmpDir` by base name in both. */
export async function runExport(
job: RenderHandle,
given: ExportSpec,
mediaPathFor: (file: string) => string,
- io: ExportPipelineIO = realIO,
- passPieces: number = PASS_PIECES
+ io: ExportPipelineIO = realIO
) {
if (given.clips.length === 0) throw new Error("Nothing to export.");
const codec = given.codec ?? "h264";
@@ -1062,23 +1069,62 @@ export async function runExport(
// A long delivery renders in passes held to a memory budget, joined into
// the one file at the end. A piece's cost follows its source's size and
- // frame rate.
+ // frame rate. Every pass reads the same files, so each probe runs once.
+ const probed = probesOnce(io);
const pictures = new Map<string, SourcePicture>();
const footage = [...given.clips, ...(given.overlayVideos ?? [])].filter((c) => c.file && !c.image && !c.removal);
await Promise.all(
[...new Set(footage.map((c) => c.file))].map(async (file) => {
- const at = await resolveMedia(io.stat, mediaPathFor, file);
- const [dims, perSecond] = await Promise.all([io.videoDimensions(at), io.videoDecodeCost(at)]);
- const pixels = dims ? dims.width * dims.height : 0;
- pictures.set(file, { pixels, fps: pixels > 0 && perSecond ? perSecond / (1.5 * pixels) : given.fps });
+ const picture = await probed.videoPicture(await resolveMedia(io.stat, mediaPathFor, file));
+ pictures.set(file, picture ?? { pixels: 0, fps: given.fps });
})
);
- const windows = passWindows(given, (file) => pictures.get(file) ?? { pixels: 0, fps: given.fps }, passPieces);
+ const windows = passWindows(given, (file) => pictures.get(file) ?? { pixels: 0, fps: given.fps });
if (windows.length === 1) {
- await renderPass(job, given, mediaPathFor, io, { kind: "delivery" });
+ await renderPass(job, given, mediaPathFor, probed, { kind: "delivery" });
return;
}
- await renderInPasses(job, given, windows, mediaPathFor, io);
+ await renderInPasses(job, given, windows, mediaPathFor, probed);
+}
+
+/**
+ * `io` with each source probe answered once per file and kind. Durations stay
+ * live: a bake reads back the length of a file it just wrote. A probe that
+ * errors
+ * replays its error to every caller, so each pass decides a stream's
+ * presence the same way.
+ */
+function probesOnce(io: ExportPipelineIO): ExportPipelineIO {
+ const once = <T>(probe: (file: string) => Promise<T>) => {
+ const answers = new Map<string, Promise<T>>();
+ return (file: string) => {
+ if (!answers.has(file)) {
+ answers.set(file, probe(file));
+ }
+ return answers.get(file)!;
+ };
+ };
+ const streams = new Map<string, Promise<{ has: boolean; error?: Error }>>();
+ const hasStream: ExportPipelineIO["hasStream"] = async (file, kind, onProbeError) => {
+ const key = `${kind}:${file}`;
+ if (!streams.has(key)) {
+ let error: Error | undefined;
+ streams.set(key, io.hasStream(file, kind, (e) => (error = e)).then((has) => ({ has, error })));
+ }
+ const { has, error } = await streams.get(key)!;
+ if (error) {
+ onProbeError?.(error);
+ }
+ return has;
+ };
+ return {
+ ...io,
+ hasStream,
+ audioChannels: once(io.audioChannels),
+ videoDecodeCost: once(io.videoDecodeCost),
+ videoDimensions: once(io.videoDimensions),
+ videoPicture: once(io.videoPicture),
+ };
}
/**
@@ -1333,17 +1379,8 @@ async function renderPass(
// each image clip/overlay gets its own looped input below instead. Gap
// spacers (empty file) reference no media at all — they render as black,
// and so do hidden clips outside a range, whose files stay closed.
- const mediaFiles = [
- ...new Set(
- [
- ...spec.clips.filter((c) => !c.image && !c.hidden),
- ...spec.audio,
- ...overlayVideos.filter((o) => !o.image),
- ]
- .map((c) => c.file)
- .filter((f) => f && !turned.has(f) && !twinFiles.has(f))
- ),
- ];
+ const readers = [...spec.clips.filter((c) => !c.image && !c.hidden), ...spec.audio, ...overlayVideos.filter((o) => !o.image)];
+ const mediaFiles = [...new Set(readers.map((c) => c.file).filter((f) => f && !turned.has(f) && !twinFiles.has(f)))];
const audioPresence = new Map<string, boolean>();
const videoPresence = new Map<string, boolean>();
// Files whose audio is one channel. ffmpeg's own mono-to-stereo lays the
@@ -1367,7 +1404,6 @@ async function renderPass(
// Re-stamped by the same amount, the input carries the timestamps an
// unseeked one does, and every trim below reads it unchanged.
const readFrom = new Map<string, number>();
- const readers = [...spec.clips.filter((c) => !c.hidden && !c.image), ...overlayVideos.filter((o) => !o.image), ...spec.audio];
for (const c of readers) {
const back = "soundBack" in c ? (c.soundBack ?? 0) : 0;
const lo = srcSpan(retimeOf(c), -back, 0).lo - SOURCE_PREROLL - READ_MARGIN_S;
@@ -3436,12 +3472,16 @@ async function renderPass(
path: out.kind === "piece" ? out.stems[i] : path.join(job.tmpDir, `stem_${i}.wav`),
name: s.file,
}));
+ // A piece's sound ends where its range trim ends it: the trim cuts on the
+ // millisecond edges the next piece starts from, and a length rounded on
+ // its own would drop the samples between them.
+ const soundLength = out.kind === "piece" ? [] : ["-t", num(span)];
const stemOutputs = stemLabels.flatMap((label, i) => [
"-map", `[${label}]`,
"-c:a", "pcm_s24le",
"-ar", String(STEM_RATE),
"-ac", String(STEM_CHANNELS),
- "-t", num(span),
+ ...soundLength,
stemFiles[i].path,
]);
@@ -3480,7 +3520,7 @@ async function renderPass(
"-t", num(span),
encodePath,
...(rawMix
- ? ["-map", `[${aLabel}]`, "-c:a", "pcm_f32le", "-ar", String(mixRate), "-ac", String(mixChannels), "-f", "f32le", "-t", num(span), mixPath]
+ ? ["-map", `[${aLabel}]`, "-c:a", "pcm_f32le", "-ar", String(mixRate), "-ac", String(mixChannels), "-f", "f32le", ...soundLength, mixPath]
: []),
...stemOutputs,
],
@@ -3498,7 +3538,7 @@ async function renderPass(
// to write its file.
const masteredPath = path.join(job.tmpDir, "master.f32");
if (master) {
- await io.masterRawMix(mixPath, masteredPath, {
+ await io.masterRawMix([mixPath], masteredPath, {
sampleRate: mixRate,
channels: mixChannels,
targetLufs: spec.loudness!,
@@ -3563,6 +3603,8 @@ async function renderInPasses(
mediaPathFor: (file: string) => string,
io: ExportPipelineIO
) {
+ // Colors are read once for every pass to share.
+ given = await withSpecColors(given, mediaPathFor);
const span = deliverySpan(given.range, given.duration);
const ext = containerExtension(given);
const stemPlan = given.stemPlan ?? [];
@@ -3583,8 +3625,8 @@ async function renderInPasses(
done += seconds;
}
- // The mix: the pieces' raw samples read as one stream, mastered when the
- // delivery asks for it.
+ // The mix: the pieces' raw samples read as one stream, mastered straight
+ // off the pieces when the delivery asks for it.
const mixRate = given.audioSampleRate ?? MIX_RATE;
const mixChannels = given.audioChannels ?? 2;
const raw = ["-f", "f32le", "-ar", String(mixRate), "-ac", String(mixChannels)];
@@ -3593,10 +3635,8 @@ async function renderInPasses(
if (given.truePeakCeiling === undefined) {
throw new Error("A mastered export needs its true-peak ceiling.");
}
- const mixPath = path.join(job.tmpDir, "mix.f32");
const masteredPath = path.join(job.tmpDir, "master.f32");
- await io.runFfmpeg(job, ["-y", ...raw, "-i", mix, "-c", "copy", "-f", "f32le", mixPath]);
- await io.masterRawMix(mixPath, masteredPath, {
+ await io.masterRawMix(pieces.map((p) => p.mix), masteredPath, {
sampleRate: mixRate,
channels: mixChannels,
targetLufs: given.loudness,
diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.ts
index 3cc21f70..64001a33 100644
--- a/site/src/cut/server/util.ts
+++ b/site/src/cut/server/util.ts
@@ -154,7 +154,14 @@ export function videoDimensions(
* stretch of decoded frames at once sizes that stretch by this. Null when the
* probe fails or the file carries no picture.
*/
-export function videoDecodeCost(file: string): Promise<number | null> {
+export async function videoDecodeCost(file: string): Promise<number | null> {
+ const picture = await videoPicture(file);
+ return picture ? picture.pixels * 1.5 * picture.fps : null;
+}
+
+/** The first video stream's size in pixels and its frame rate, or null when
+ * the probe fails or the file carries no picture. */
+export function videoPicture(file: string): Promise<{ pixels: number; fps: number } | null> {
return new Promise((resolve) => {
const p = spawn("ffprobe", [
"-v", "error",
@@ -184,7 +191,7 @@ export function videoDecodeCost(file: string): Promise<number | null> {
return Number.isFinite(fps) && fps > 0 && fps < 1000 ? fps : 0;
};
const fps = ratio(s?.avg_frame_rate) || ratio(s?.r_frame_rate) || 30;
- resolve(width * height * 1.5 * fps);
+ resolve({ pixels: width * height, fps });
} catch {
resolve(null);
}
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
index de9b1b3a..ce1c1500 100644
--- a/site/src/cut/worker/exportJob.ts
+++ b/site/src/cut/worker/exportJob.ts
@@ -12,6 +12,7 @@ import { STORAGE_FULL } from "../lib/operationFailure";
import { specMediaFiles, STEMS_MIME, stemsArchiveName } from "../lib/exportDelivery";
import { runnerSession } from "./session";
import { bindCutColor } from "../lib/colorSettings";
+import { bindCutExportPasses } from "../lib/exportPassSettings";
import { bindCutSound } from "../lib/soundSettings";
import { bindCutLoudness } from "../lib/loudnessSettings";
import type { DocExportAudio } from "../lib/exportPresets";
@@ -147,6 +148,7 @@ export async function runExportJob(
bindCutSound(await getGlobalSetting("cutSound"));
// Its loudness target and ceiling come from the setting the tab binds.
bindCutLoudness(await getGlobalSetting("cutLoudness"));
+ bindCutExportPasses(await getGlobalSetting("cutExportPasses"));
}
const body: ExportJobSpec = stored.fromDoc
? {
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 9310f4f5..5dc7c75d 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -391,6 +391,24 @@ export const SETTINGS = defineSettings({
description:
"The color LUT sizes a clip is rendered through (standard, wide-gamut and the draft drawn mid-drag), the preview proxy's size and quality, and the largest LUT file the library takes.",
},
+ cutExportPasses: {
+ schema: z
+ .object({
+ // The frames one ffmpeg pass may hold, MB. A long timeline renders in
+ // passes held under it; a larger budget means fewer passes, each
+ // decoding the stretch of file its cuts span.
+ holdMB: z.number().int().min(256).max(65536),
+ // The most pieces one pass opens, whatever their size: each brings a
+ // decoder and its threads.
+ pieces: z.number().int().min(2).max(512),
+ })
+ .strict(),
+ default: { holdMB: 2048, pieces: 48 },
+ public: true,
+ title: "Export passes",
+ description:
+ "The memory one export pass may hold and the most pieces it opens; a longer timeline renders in more passes.",
+ },
cutSound: {
schema: z
.object({