Open source CapCut alternative.
TypeScript
refactor(cut): extract export pipeline and URL download for worker reuse [rebuild]
David Le5ab96fe6ad63
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsnew file mode 100644index 00000000..abde74d3--- /dev/null+++ b/site/src/cut/server/exportPipeline.ts@@ -0,0 +1,1095 @@+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 { projectFadeSeconds, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";+import { gradeToFfmpegFilter } from "../lib/colorGrade";+import { lookFilterLines } from "../lib/looks";++// The render pipeline itself: spec in, finished mp4 out. Shared by the local+// engine's job registry (jobs.ts) and the cloud render worker, which stage+// media differently but must produce byte-identical renders.++export interface ExportSpec {+ projectId: string;+ /** "preview" renders the low-res hover proxy into the project's preview.mp4+ * instead of a stamped file in exports/. */+ target?: "export" | "preview";+ width: number;+ height: number;+ fps: number;+ crf: number;+ preset: string;+ duration: number;+ /** Whole-video fades, seconds: in from black / out to black, applied to the+ * final composite and mix after all overlays and soundtrack. */+ fadeIn?: number;+ fadeOut?: number;+ clips: {+ file: string;+ in: number;+ out: number;+ muted: boolean;+ /** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */+ volume?: number;+ /** "fit" letterboxes (default); "fill" covers the region and crops. */+ fit?: "fit" | "fill";+ panX?: number; // crop-window pan -1..1 (fill mode, full frame)+ panY?: number;+ /** Region of the frame this clip fills; absent = full frame. */+ frame?: { x: number; y: number; w: number; h: number };+ speed?: number; // playback rate, default 1+ /** Transition into the next clip, in timeline seconds (overlap). */+ transition?: number;+ /** Transition look id, resolved to an xfade name through the+ * TRANSITION_XFADE allowlist (unknown ids render as a plain fade). Cross+ * zoom renders as the fade plus zoom ramps on both segments' overlap+ * windows. */+ transitionStyle?: string;+ /** This clip's own entrance/exit animation, baked into the segment's+ * head/tail window: fade (audio follows), zoom, pop, or a slide+ * against black. Unknown styles render as a fade. */+ animIn?: { style: string; seconds: number };+ animOut?: { style: string; seconds: number };+ /** Preset filter look id + strength 0..1, baked into the segment (the+ * spec carries only the id — the chain is built server-side). */+ look?: string;+ lookAmount?: number;+ /** Hidden clips keep their slot but render black + silent. */+ hidden?: boolean;+ /** A still image: looped for the clip's length instead of trimmed. */+ image?: boolean;+ /** Manual color adjustments, baked into this clip's segment. */+ grade?: ColorGrade;+ }[];+ /** Video tracks composited over the track-0 `clips`, lowest track first. */+ overlayVideos?: {+ file: string;+ in: number;+ out: number;+ start: number; // timeline position, seconds+ track: number;+ /** Region of the frame this overlay fills; absent = full frame. */+ frame?: { x: number; y: number; w: number; h: number };+ fit?: "fit" | "fill";+ muted: boolean;+ /** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */+ volume?: number;+ speed?: number;+ /** Transition ramps, timeline seconds from this overlay's head/tail. On+ * an upper track a fade is an alpha fade (the tracks beneath show+ * through); a cross transition arrives as the incoming clip's headFade+ * while the outgoing clip stays opaque under it, and cross zoom adds a+ * tailZoom/headZoom pair riding that overlap. The audio fades with the+ * picture. */+ headFade?: number;+ tailFade?: number;+ headZoom?: number;+ tailZoom?: number;+ /** A still image: looped for the clip's length instead of trimmed. */+ image?: boolean;+ /** Manual color adjustments, baked into this overlay's segment. */+ grade?: ColorGrade;+ /** Preset filter look id + strength (footage overlays only — image+ * overlays may carry alpha the look chain would flatten). */+ look?: string;+ lookAmount?: number;+ }[];+ audio: {+ file: string;+ in: number;+ out: number;+ start: number;+ volume: number;+ fadeIn?: number;+ fadeOut?: number;+ /** Playback rate (detached-audio clips inherit their video clip's speed). */+ speed?: number;+ /** Voiceover ducking: while this clip plays, every other sound drops to+ * this gain (0..1). Ducking clips never duck each other. */+ duck?: number;+ }[];+ overlays: { file: string; start: number; end: number }[];+ /** Burned-in subtitle stills. Kept apart from `overlays` (titles may+ * overlap each other): each subtitle track (`lane`, absent = 0) is+ * non-overlapping and chronological within itself and renders as one+ * concat-demuxer slideshow, so karaoke word windows don't multiply inputs.+ * Tracks overlap each other in time (one language each). */+ captions?: { file: string; start: number; end: number; lane?: number }[];+}++/** What the pipeline needs from its caller's job record: the staging dir the+ * overlay PNGs were written into, the output path, and the mutable fields the+ * run reports through (progress, the live ffmpeg process for cancellation,+ * the rolling stderr log, and an externally-set error that wins over the+ * generic exit message). The engine's Job and the worker's claimed row both+ * satisfy it structurally. */+export interface RenderHandle {+ tmpDir: string;+ outPath: string;+ progress: number;+ error?: string;+ proc?: ChildProcess;+ log: string[];+}++/** The H.264 encoder to use, probed once against the same `ffmpeg` the exports+ * spawn. Prefer libx264 (CRF + presets) when the build carries it — the dev+ * Homebrew ffmpeg does. The bundled engine ffmpeg is LGPL (`--disable-gpl`), so+ * it has no libx264 and `-preset`/`-crf` don't exist there; fall back to the+ * always-present VideoToolbox hardware H.264 encoder. */+let h264EncoderCache: Promise<"libx264" | "h264_videotoolbox"> | null = null;+function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {+ return (h264EncoderCache ??= new Promise((resolve) => {+ let out = "";+ const proc = spawn("ffmpeg", ["-hide_banner", "-encoders"]);+ proc.stdout?.on("data", (c: Buffer) => (out += c.toString()));+ proc.on("error", () => resolve("h264_videotoolbox"));+ proc.on("close", () => resolve(/\blibx264\b/.test(out) ? "libx264" : "h264_videotoolbox"));+ }));+}++/** VideoToolbox constant quality (1–100, higher = better) from the CRF knob the+ * presets carry (lower CRF = better). Maps the 19/24/30 tiers to ~66/57/46. */+function vtQuality(crf: number) {+ return Math.round(Math.max(35, Math.min(80, 100 - crf * 1.8)));+}++async function resolveMedia(mediaPathFor: (file: string) => string, file: string) {+ const p = mediaPathFor(file);+ const info = await stat(p).catch(() => null);+ if (!info?.isFile()) throw new Error(`Media file missing from project: ${file}`);+ return p;+}++/**+ * Filter prefix converting a wide-gamut/HDR source (phone footage: BT.2020+ * primaries with an HLG or PQ transfer) down to the BT.709 SDR the export is+ * tagged as, or "" for an SDR source. The blind `format=yuv420p` squeeze keeps+ * BT.2020 code values, and players reading them as 709 wash the clip out —+ * visible whenever phone footage sits next to Cut-rendered (already-709)+ * clips. The native `colorspace` filter has no HLG/PQ transfer, so the input+ * is pinned to bt2020-10, a close stand-in over HLG's SDR-compatible range;+ * the 10-bit format hop feeds it a planar format it accepts (decoders hand+ * HDR frames over as p010, which it rejects).+ *+ * The matrix decides, the way players decide. Social-app transcodes (8-bit+ * H.264) keep BT.2020 primaries + HLG transfer tags from the phone original+ * but write an explicit bt709 matrix — players read those as plain 709 SDR,+ * so converting them shifts hue and saturation against what every player+ * shows (verified frame-for-frame against WebKit playback). Convert only+ * when the matrix itself is BT.2020, or when it's untagged and the wide+ * primaries/transfer tags are the only signal there is.+ */+function sdrConvert(c: Awaited<ReturnType<typeof videoColorInfo>>) {+ if (c == null) return "";+ const matrix = c.matrix && c.matrix !== "unknown" ? c.matrix : null;+ const wide =+ matrix?.startsWith("bt2020") === true ||+ (matrix === null &&+ (c.primaries === "bt2020" ||+ c.transfer === "arib-std-b67" ||+ c.transfer === "smpte2084"));+ return wide ? "format=yuv420p10le,colorspace=all=bt709:iall=bt2020:format=yuv420p," : "";+}++/** A clip's effective playback rate (>0, default 1). */+function clipRate(c: ExportSpec["clips"][number]) {+ return c.speed && c.speed > 0 ? c.speed : 1;+}++/** A clip's frame region in even pixels, or null when it fills the whole frame+ * (the common case, which keeps the plain full-frame filter path). */+function regionPx(+ frame: { x: number; y: number; w: number; h: number } | undefined,+ W: number,+ H: number+) {+ if (!frame) return null;+ const even = (n: number) => 2 * Math.round(n / 2);+ const rw = Math.min(W, Math.max(2, even(frame.w * W)));+ const rh = Math.min(H, Math.max(2, even(frame.h * H)));+ // Clamp the origin so rx+rw ≤ W and ry+rh ≤ H — independent even-rounding can+ // otherwise push an edge-touching region a pixel past the frame, which makes+ // the pad filter reject the input ("not within the padded area") and aborts+ // the whole export.+ const rx = Math.max(0, Math.min(even(frame.x * W), W - rw));+ const ry = Math.max(0, Math.min(even(frame.y * H), H - rh));+ if (rx <= 0 && ry <= 0 && rw >= W && rh >= H) return null;+ return { rx, ry, rw, rh };+}++/**+ * Spawn ffmpeg for one pass, tracking `job.proc` so a cancel kills the live+ * process, bounding silence with the stall watchdog, and (when `onProgress` is+ * given) reporting the `time=` cursor from stderr. Rejects with a readable+ * message on a non-zero exit or a missing binary. Shared by the encode pass and+ * the rotation-strip remux.+ */+function runFfmpeg(+ job: RenderHandle,+ args: string[],+ onProgress?: (seconds: number) => void+): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const proc = spawn("ffmpeg", args);+ job.proc = proc;+ // Stall watchdog: legit exports can run long, so bound silence, not total+ // time — kill only if ffmpeg emits nothing for STALL_MS.+ const STALL_MS = 120_000;+ let watchdog: ReturnType<typeof setTimeout> | undefined;+ const bump = () => {+ clearTimeout(watchdog);+ watchdog = setTimeout(() => {+ proc.kill("SIGKILL");+ reject(new Error("Export stalled — no ffmpeg output for 120s."));+ }, STALL_MS);+ watchdog.unref();+ };+ bump();+ proc.stderr.on("data", (chunk: Buffer) => {+ bump();+ const text = chunk.toString();+ job.log.push(text);+ if (job.log.length > 200) job.log.shift();+ if (onProgress) {+ const m = /time=(\d+):(\d+):([\d.]+)/.exec(text);+ if (m) onProgress(Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]));+ }+ });+ proc.on("error", (err) => {+ clearTimeout(watchdog);+ reject(+ err.message.includes("ENOENT")+ ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")+ : err+ );+ });+ proc.on("close", (code) => {+ clearTimeout(watchdog);+ if (code === 0) resolve();+ else if (job.error) reject(new Error(job.error));+ else reject(new Error(`ffmpeg exited with code ${code}.\n${job.log.slice(-8).join("")}`));+ });+ });+}++/** 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. */+export async function runExport(+ job: RenderHandle,+ spec: ExportSpec,+ mediaPathFor: (file: string) => string+) {+ if (spec.clips.length === 0) throw new Error("Nothing to export.");+ const { width: W, height: H, fps } = spec;++ // Tracks number 0..N bottom-up: track 0 folds sequentially into the base+ // picture, the rest overlay it in track order (highest last = frontmost).+ // Within a track, earlier clips composite first, so a dissolving pair+ // blends the incoming clip in over the outgoing one.+ const overlayVideos = [...(spec.overlayVideos ?? [])].sort(+ (a, b) => a.track - b.track || a.start - b.start+ );+ const clipFmt = "yuv420p";+ const padColor = "black";+ // One ffmpeg input per distinct media file (from the project folder),+ // plus one per uploaded overlay PNG.+ // Still images are excluded here: a plain `-i file` decodes one frame, so+ // each image clip/overlay gets its own looped input below instead. Gap+ // spacers (empty file) reference no media at all — they render as black.+ const mediaFiles = [+ ...new Set(+ [+ ...spec.clips.filter((c) => !c.image),+ ...spec.audio,+ ...overlayVideos.filter((o) => !o.image),+ ]+ .map((c) => c.file)+ .filter(Boolean)+ ),+ ];+ const audioPresence = new Map<string, boolean>();+ const videoPresence = new Map<string, boolean>();+ // file → filter prefix folding a wide-gamut/HDR source down to BT.709 (or "").+ const colorFix = new Map<string, string>();+ const inputs: string[] = [];+ const inputIndex = new Map<string, number>();+ // Counted explicitly: the concat input below carries extra flags, so the+ // args array is not a clean ["-i", path] pair per input.+ let nInputs = 0;+ // Resolve paths in order first so ffmpeg input indices stay deterministic,+ // then probe every file's streams concurrently.+ const paths = await Promise.all(mediaFiles.map((f) => resolveMedia(mediaPathFor, f)));+ mediaFiles.forEach((f, i) => {+ inputIndex.set(f, nInputs++);+ inputs.push("-i", paths[i]);+ });+ await Promise.all(+ mediaFiles.map(async (f, i) => {+ // A probe that errors (timeout, non-zero exit) must not be read as+ // "no stream" — that would silently drop real audio to silence or real+ // video to black. Genuine absence returns false with no error, so on a+ // probe error we assume the stream is present and let ffmpeg map it.+ let audioProbeFailed = false;+ const hasAudio = await hasStream(paths[i], "a", () => (audioProbeFailed = true));+ audioPresence.set(f, hasAudio || audioProbeFailed);+ let videoProbeFailed = false;+ const hasVideo = await hasStream(paths[i], "v", () => (videoProbeFailed = true));+ videoPresence.set(f, hasVideo || videoProbeFailed);+ // A failed color probe (null) means no conversion — SDR passthrough.+ colorFix.set(f, sdrConvert(await videoColorInfo(paths[i])));+ })+ );+ for (const o of spec.overlays) {+ inputIndex.set(o.file, nInputs++);+ inputs.push("-i", path.join(job.tmpDir, path.basename(o.file)));+ }++ // Looped input per still image, sized to the clip's timeline length so the+ // segment fills without a source trim. Keyed by clip/overlay identity since+ // two clips of the same image can have different lengths.+ const imageClipInput = new Map<number, number>();+ for (let j = 0; j < spec.clips.length; j++) {+ const c = spec.clips[j];+ if (!c.image || !c.file) continue;+ const dur = Math.max(0.1, (c.out - c.in) / clipRate(c));+ imageClipInput.set(j, nInputs++);+ inputs.push("-loop", "1", "-t", num(dur), "-framerate", String(fps), "-i", await resolveMedia(mediaPathFor, c.file));+ }+ const imageOverlayInput = new Map<(typeof overlayVideos)[number], number>();+ for (const oc of overlayVideos) {+ if (!oc.image) continue;+ const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;+ const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);+ imageOverlayInput.set(oc, nInputs++);+ inputs.push("-loop", "1", "-t", num(olen), "-framerate", String(fps), "-i", await resolveMedia(mediaPathFor, oc.file));+ }++ // One concat-demuxer input per subtitle track: within a track cues never+ // overlap, so each plays as a slideshow with transparent filler+ // ("sub_blank.png", uploaded with the stills) covering the gaps. Tracks+ // (languages) overlap each other, so each gets its own input.+ const captionLanes = new Map<number, NonNullable<ExportSpec["captions"]>>();+ for (const c of spec.captions ?? []) {+ if (c.end <= c.start) continue;+ const lane = c.lane ?? 0;+ if (!captionLanes.has(lane)) captionLanes.set(lane, []);+ captionLanes.get(lane)!.push(c);+ }+ const captionInputs: number[] = [];+ for (const [lane, entries] of [...captionLanes.entries()].sort((a, b) => a[0] - b[0])) {+ entries.sort((a, b) => a.start - b.start);+ const blank = path.join(job.tmpDir, "sub_blank.png");+ const lines = ["ffconcat version 1.0"];+ let cursor = 0;+ for (const c of entries) {+ const from = Math.max(c.start, cursor);+ if (c.end - from < 1e-3) continue;+ if (from - cursor > 1e-3) lines.push(`file '${blank}'`, `duration ${num(from - cursor)}`);+ lines.push(+ `file '${path.join(job.tmpDir, path.basename(c.file))}'`,+ `duration ${num(c.end - from)}`+ );+ cursor = c.end;+ }+ if (spec.duration - cursor > 1e-3) {+ lines.push(`file '${blank}'`, `duration ${num(spec.duration - cursor)}`);+ }+ const list = path.join(job.tmpDir, `captions_${lane}.ffconcat`);+ await writeFile(list, lines.join("\n") + "\n");+ captionInputs.push(nInputs++);+ inputs.push("-f", "concat", "-safe", "0", "-i", list);+ }++ const filters: string[] = [];++ // Per-clip timeline length (source span compressed/expanded by speed). A+ // gap spacer (no file) keeps its exact length: flooring it at 0.1s would+ // land everything after the gap later than the timeline shows, drifting+ // burned-in captions off the picture.+ const clipDur = (c: ExportSpec["clips"][number]) =>+ c.file ? Math.max(0.1, (c.out - c.in) / clipRate(c)) : Math.max(0, c.out - c.in);++ /** One edge effect on a segment's head or tail window. `zoom` ramps scale+ * (settling in on the head, pushing in on the tail); `xfade` runs the named+ * xfade transition against a backdrop — the label in `bg` (a neighbor's+ * held frame), or a black frame when absent; `pop` scales the picture up+ * from / down to 80% with a fade over the same backdrop. */+ type EdgeFx = { kind: "zoom" | "pop" | "xfade"; secs: number; xfade?: string; bg?: string };++ /** Emit `core` into `[out]` with the head/tail edge effects confined to+ * their windows and `fades` appended. Each effected window is sliced out+ * (split → trim → fx → concat) so per-frame effects stay inside the short+ * ramp; plain fades ride `fades` inline instead. `w`×`h` is the segment's+ * constant frame size; `tag` uniquifies intermediate labels. Shared by the+ * track-0 segments and the overlay-track segments. */+ const pushEdgeFx = (+ core: string,+ dur: number,+ head: EdgeFx | null,+ tail: EdgeFx | null,+ w: number,+ h: number,+ fmt: string,+ fades: string,+ out: string,+ tag: string+ ) => {+ const zoomRamp = (side: "head" | "tail", secs: number) => {+ // A head ramp settles TRANSITION_ZOOM→1 (zoom out), a tail ramp pushes+ // 1→TRANSITION_ZOOM (zoom in); zoompan clamps z below 1 itself, so the+ // plain arithmetic needs no guards.+ const frames = Math.max(1, Math.round(secs * fps) - 1);+ const k = num(TRANSITION_ZOOM - 1);+ const z =+ side === "tail"+ ? `1+${k}*in/${frames}`+ : `${num(TRANSITION_ZOOM)}-${k}*in/${frames}`;+ return (+ `zoompan=z=${z}:x=iw/2-(iw/zoom/2):y=ih/2-(ih/zoom/2)` ++ `:d=1:s=${w}x${h}:fps=${fps},setsar=1,format=${fmt}`+ );+ };+ // Emit one sliced window's effect from `[inLab]` to `[outLab]`. The+ // multi-input effects push their own filter lines.+ const applyFx = (fx: EdgeFx, side: "head" | "tail", inLab: string, outLab: string) => {+ const d = num(fx.secs);+ if (fx.kind === "zoom") {+ filters.push(`[${inLab}]${zoomRamp(side, fx.secs)}[${outLab}]`);+ return;+ }+ // The backdrop behind the window: a neighbor's held frame when given+ // (an abutting cut), else black (timeline ends and gaps).+ let bg = fx.bg;+ if (!bg) {+ bg = `xb${tag}_${side}`;+ filters.push(`color=c=black:s=${w}x${h}:r=${fps}:d=${d},format=${fmt}[${bg}]`);+ }+ if (fx.kind === "xfade") {+ // Entering: the backdrop hands off to the picture; exiting: the+ // picture hands off to the backdrop. Anim style ids map straight to+ // xfade names (probed: slideleft moves the frame leftward, so it+ // enters from the right edge and exits off the left; cover/reveal+ // and wipes share the same direction footprints).+ filters.push(+ side === "head"+ ? `[${bg}][${inLab}]xfade=transition=${fx.xfade}:duration=${d}:offset=0[${outLab}]`+ : `[${inLab}][${bg}]xfade=transition=${fx.xfade}:duration=${d}:offset=0[${outLab}]`+ );+ return;+ }+ // Pop: scale 80%↔100% over the window (even dimensions for yuv420p),+ // centered over the backdrop. With a held-frame backdrop the picture+ // alpha-fades so the neighbor stays visible behind it; over black the+ // plain fade is the same thing cheaper.+ const p = side === "head" ? `min(t/${d},1)` : `1-min(t/${d},1)`;+ const sc = `sc${tag}_${side}`;+ const scaleExpr = `scale=w='trunc(iw*(0.8+0.2*(${p}))/2)*2':h=-2:eval=frame`;+ if (fx.bg) {+ filters.push(+ `[${inLab}]format=yuva420p,` ++ `fade=t=${side === "head" ? "in" : "out"}:st=0:d=${d}:alpha=1,${scaleExpr}[${sc}]`+ );+ filters.push(+ `[${bg}][${sc}]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1,format=${fmt}[${outLab}]`+ );+ return;+ }+ filters.push(`[${inLab}]${scaleExpr}[${sc}]`);+ filters.push(+ `[${bg}][${sc}]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1,` ++ `fade=t=${side === "head" ? "in" : "out"}:st=0:d=${d},format=${fmt}[${outLab}]`+ );+ };+ const hs = head && head.secs > 0.01 ? head : null;+ const ts = tail && tail.secs > 0.01 ? tail : null;+ if (!hs && !ts) {+ filters.push(`${core}${fades}[${out}]`);+ return;+ }+ const slices: { from: number; to: number; fx?: EdgeFx; side: "head" | "tail" }[] = [];+ if (hs) slices.push({ from: 0, to: hs.secs, fx: hs, side: "head" });+ const mid0 = hs ? hs.secs : 0;+ const mid1 = ts ? dur - ts.secs : dur;+ if (mid1 - mid0 > 0.01) slices.push({ from: mid0, to: mid1, side: "head" });+ if (ts) slices.push({ from: dur - ts.secs, to: dur, fx: ts, side: "tail" });+ filters.push(`${core},split=${slices.length}${slices.map((_, k) => `[zs${tag}_${k}]`).join("")}`);+ slices.forEach((sl, k) => {+ const cut = `zc${tag}_${k}`;+ // setpts clears the constant-frame-rate metadata the slice xfades+ // demand — re-stamp it on every cut.+ filters.push(+ `[zs${tag}_${k}]trim=${num(sl.from)}:${num(sl.to)},setpts=PTS-STARTPTS,fps=${fps}[${cut}]`+ );+ if (sl.fx) applyFx(sl.fx, sl.side, cut, `zp${tag}_${k}`);+ else filters.push(`[${cut}]null[zp${tag}_${k}]`);+ });+ // concat drops the stream's constant-frame-rate metadata and a downstream+ // xfade join refuses a variable-rate input — re-stamp it.+ filters.push(+ slices.map((_, k) => `[zp${tag}_${k}]`).join("") ++ `concat=n=${slices.length}:v=1:a=0,fps=${fps}${fades}[${out}]`+ );+ };++ /** The edge effect a clip animation asks for, or null when it's a plain+ * fade (fades ride the inline `fade`/`afade` filters instead of a slice).+ * Unknown styles fall back to the fade path. */+ const animEdgeFx = (a: { style: string; seconds: number } | undefined, max: number): EdgeFx | null => {+ if (!a || a.seconds <= 0.01 || max <= 0.01) return null;+ const secs = Math.min(a.seconds, max);+ if (a.style === "zoom") return { kind: "zoom", secs };+ if (a.style === "pop") return { kind: "pop", secs };+ if (/^slide(left|right|up|down)$/.test(a.style)) {+ return { kind: "xfade", secs, xfade: a.style };+ }+ return null;+ };++ /** Whether an animation renders through the inline fade filters. */+ const isFadeAnim = (a: { style: string; seconds: number } | undefined) =>+ !!a && a.seconds > 0.01 && !animEdgeFx(a, Infinity);++ // A clip animation at an abutting hard cut plays over the neighbor's held+ // frame instead of black — an entrance covers the previous clip's last+ // frame, an exit reveals the next clip's first frame. Black remains where+ // there is no neighbor: the timeline's ends, gaps (the adjacent entry is a+ // spacer), and hidden neighbors. Zoom never uncovers the frame, so it needs+ // no backdrop. Precomputed so pass 1 can defer these animations and split+ // off the freeze sources the second pass consumes.+ const freezable = (c?: ExportSpec["clips"][number]) =>+ !!c && !!c.file && !c.hidden && (!!c.image || !!videoPresence.get(c.file));+ const effAnimIn = (j: number) => {+ const p = spec.clips[j - 1];+ return p && (p.transition ?? 0) > 0.01 ? undefined : spec.clips[j].animIn;+ };+ const effAnimOut = (j: number) => {+ const n = spec.clips[j + 1];+ return n && (spec.clips[j].transition ?? 0) > 0.01 ? undefined : spec.clips[j].animOut;+ };+ const backdropAnim = (a?: { style: string; seconds: number }) =>+ a && a.seconds > 0.01 && a.style !== "zoom" ? a : undefined;+ const headBd = spec.clips.map(+ (c, j) => !!(freezable(c) && backdropAnim(effAnimIn(j)) && freezable(spec.clips[j - 1]))+ );+ const tailBd = spec.clips.map(+ (c, j) => !!(freezable(c) && backdropAnim(effAnimOut(j)) && freezable(spec.clips[j + 1]))+ );+ const needFirstFreeze = spec.clips.map((_, j) => j > 0 && tailBd[j - 1]);+ const needLastFreeze = spec.clips.map((_, j) => j < spec.clips.length - 1 && headBd[j + 1]);++ // Per-clip normalized video + audio segments for the join below.+ spec.clips.forEach((c, j) => {+ const idx = c.image ? imageClipInput.get(j)! : inputIndex.get(c.file)!;+ const speed = clipRate(c);+ const dur = clipDur(c);+ const prevC = spec.clips[j - 1];+ const nextC = spec.clips[j + 1];+ // Cross zoom renders as the fade join plus zoom ramps riding the overlap+ // window on both segments (clamped like the join clamps its overlap).+ const czOverlap = (a: (typeof spec.clips)[number], aDur: number, bDur: number) =>+ a.transitionStyle === "crosszoom"+ ? Math.min(a.transition ?? 0, aDur * 0.9, bDur * 0.9)+ : 0;+ const czHead = prevC ? czOverlap(prevC, clipDur(prevC), dur) : 0;+ const czTail = nextC ? czOverlap(c, dur, clipDur(nextC)) : 0;+ // A transitioned joint owns its edges: with a live overlap into or out of+ // this clip, that side's animation is held (running both would fight over+ // the same window) — `transition` in the spec is already the clamped live+ // overlap, so 0 means a hard cut and the animation plays. Matches the+ // preview's suppression exactly.+ const animIn = prevC && (prevC.transition ?? 0) > 0.01 ? undefined : c.animIn;+ const animOut = nextC && (c.transition ?? 0) > 0.01 ? undefined : c.animOut;+ // The clip's own animations own their edge windows (fade animations ride+ // the inline fade filters below); cross zoom fills a side its animation+ // leaves free. Clamped so head+tail never overrun the segment. Backdrop+ // animations are deferred to the second pass, which runs them against the+ // neighbor's held frame — only their audio fade stays here.+ const animInNow = headBd[j] ? undefined : animIn;+ const animOutNow = tailBd[j] ? undefined : animOut;+ let headFx = animEdgeFx(animInNow, dur);+ let tailFx = animEdgeFx(animOutNow, dur - (headFx?.secs ?? 0));+ const hf = isFadeAnim(animInNow) ? Math.min(animInNow!.seconds, dur) : 0;+ const tf = isFadeAnim(animOutNow) ? Math.min(animOutNow!.seconds, dur - hf) : 0;+ // The sound of a fade animation follows the picture whether the fade+ // renders inline (over black) or in the backdrop pass.+ const ahf = animIn?.style === "fade" ? Math.min(animIn.seconds, dur) : 0;+ const atf =+ animOut?.style === "fade" ? Math.min(animOut.seconds, Math.max(0, dur - ahf)) : 0;+ if (!headFx && hf <= 0.01 && czHead > 0.01) {+ headFx = { kind: "zoom", secs: Math.min(czHead, dur) };+ }+ if (!tailFx && tf <= 0.01 && czTail > 0.01) {+ tailFx = { kind: "zoom", secs: Math.min(czTail, dur - (headFx?.secs ?? 0)) };+ }+ // A still's looped input is already the right length at `fps`; it has no+ // source span to trim. Footage trims `in..out` and re-times by speed.+ const timebase = c.image+ ? `[${idx}:v]setpts=PTS-STARTPTS`+ : `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=(PTS-STARTPTS)/${num(speed)}`;+ if ((c.image || videoPresence.get(c.file)) && !c.hidden) {+ const region = regionPx(c.frame, W, H);+ let frame: string;+ if (region) {+ // A regioned track-0 clip (split-screen half) scales into its rect,+ // then pads out to the full frame with black around it.+ const { rx, ry, rw, rh } = region;+ frame =+ c.fit === "fill"+ ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh},` ++ `pad=${W}:${H}:${rx}:${ry}:color=${padColor}`+ : `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2,` ++ `pad=${W}:${H}:${rx}+(${rw}-iw)/2:${ry}+(${rh}-ih)/2:color=${padColor}`;+ } else {+ frame =+ c.fit === "fill"+ ? // Cover the frame, then crop; the pan chooses the visible window.+ `scale=${W}:${H}:force_original_aspect_ratio=increase,` ++ `crop=${W}:${H}:(iw-ow)*${num(0.5 + Math.max(-1, Math.min(1, c.panX ?? 0)) / 2)}` ++ `:(ih-oh)*${num(0.5 + Math.max(-1, Math.min(1, c.panY ?? 0)) / 2)}`+ : `scale=${W}:${H}:force_original_aspect_ratio=decrease,` ++ `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=${padColor}`;+ }+ // setpts/speed rescales the clip's duration on the timeline (footage);+ // a still just replays its looped input.+ // The grade sits after the color conversion (so it acts on the same+ // BT.709 values the preview shows) and before the terminal format.+ let core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeToFfmpegFilter(c.grade)}format=${clipFmt}`;+ // The look bakes in after grade + framing, before the edge effects, so+ // animations move already-graded pixels (matching the preview order).+ if (c.look) {+ const lines = lookFilterLines(`lki${j}`, `lko${j}`, c.look, c.lookAmount, H, clipFmt, `c${j}`);+ if (lines) {+ filters.push(`${core}[lki${j}]`);+ filters.push(...lines);+ core = `[lko${j}]null`;+ }+ }+ const fades =+ (hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}` : "") ++ (tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");+ // A neighbor's backdrop animation freezes a frame of this segment —+ // split the copies it needs off the pre-backdrop picture.+ const nFz = (needFirstFreeze[j] ? 1 : 0) + (needLastFreeze[j] ? 1 : 0);+ const segOut = nFz > 0 ? `vseg${j}` : `v${j}`;+ pushEdgeFx(core, dur, headFx, tailFx, W, H, clipFmt, fades, segOut, `c${j}`);+ if (nFz > 0) {+ filters.push(+ `[vseg${j}]split=${nFz + 1}[v${j}]` ++ (needFirstFreeze[j] ? `[vff${j}]` : "") ++ (needLastFreeze[j] ? `[vfl${j}]` : "")+ );+ }+ } else {+ // No video stream, or a hidden clip: the slot plays black.+ filters.push(+ `color=c=black:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=${clipFmt}[v${j}]`+ );+ }+ if (!c.muted && !c.hidden && audioPresence.get(c.file)) {+ const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";+ const vol = (c.volume ?? 1) !== 1 ? `volume=${num(c.volume ?? 1)},` : "";+ // The picture's fade edges carry the sound with them; zoom edges don't.+ const afades =+ (ahf > 0.01 ? `,afade=t=in:st=0:d=${num(ahf)}` : "") ++ (atf > 0.01 ? `,afade=t=out:st=${num(Math.max(0, dur - atf))}:d=${num(atf)}` : "");+ filters.push(+ `[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` ++ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,${vol}` ++ `apad=whole_dur=${num(dur)},atrim=0:${num(dur)}${afades}[a${j}]`+ );+ } else {+ filters.push(+ `anullsrc=r=44100:cl=stereo,atrim=0:${num(dur)},asetpts=PTS-STARTPTS[a${j}]`+ );+ }+ });++ // Second pass: the backdrop animations. Each slices its edge window and+ // runs the effect against the neighbor's held frame — frozen via tpad+ // clone from the copies split off above, so a slide-in covers the previous+ // clip's last frame and a slide-out reveals the next clip's first frame.+ // Slides become cover/reveal (the backdrop stays put); pop alpha-blends+ // over the frozen frame; fade — and any unknown stored style — crossfades.+ const segLabel = spec.clips.map((_, j) => `v${j}`);+ const backdropFx = (+ a: { style: string; seconds: number },+ side: "head" | "tail",+ secs: number,+ bg: string+ ): EdgeFx => {+ if (a.style === "pop") return { kind: "pop", secs, bg };+ if (/^slide(left|right|up|down)$/.test(a.style)) {+ const dir = a.style.slice(5);+ return { kind: "xfade", secs, xfade: `${side === "head" ? "cover" : "reveal"}${dir}`, bg };+ }+ return { kind: "xfade", secs, xfade: "fade", bg };+ };+ spec.clips.forEach((c, j) => {+ if (!headBd[j] && !tailBd[j]) return;+ const dur = clipDur(c);+ if (headBd[j]) {+ const a = backdropAnim(effAnimIn(j))!;+ const d = Math.min(a.seconds, dur);+ const durPrev = clipDur(spec.clips[j - 1]);+ // fps is re-stamped before tpad — cloning needs a live frame rate, and+ // trim+setpts strip it (without this the freeze collapses to 1 frame).+ filters.push(+ `[vfl${j - 1}]trim=${num(Math.max(0, durPrev - 0.05))}:${num(durPrev)},setpts=PTS-STARTPTS,fps=${fps},` ++ `tpad=stop_mode=clone:stop_duration=${num(d + 0.5)},trim=0:${num(d)},` ++ `setpts=PTS-STARTPTS,fps=${fps}[fzh${j}]`+ );+ pushEdgeFx(+ `[${segLabel[j]}]null`,+ dur,+ backdropFx(a, "head", d, `fzh${j}`),+ null,+ W,+ H,+ clipFmt,+ "",+ `vhb${j}`,+ `hb${j}`+ );+ segLabel[j] = `vhb${j}`;+ }+ if (tailBd[j]) {+ const a = backdropAnim(effAnimOut(j))!;+ const d = Math.min(a.seconds, dur);+ filters.push(+ `[vff${j + 1}]trim=0:0.05,setpts=PTS-STARTPTS,fps=${fps},` ++ `tpad=stop_mode=clone:stop_duration=${num(d + 0.5)},trim=0:${num(d)},` ++ `setpts=PTS-STARTPTS,fps=${fps}[fzt${j}]`+ );+ pushEdgeFx(+ `[${segLabel[j]}]null`,+ dur,+ null,+ backdropFx(a, "tail", d, `fzt${j}`),+ W,+ H,+ clipFmt,+ "",+ `vtb${j}`,+ `tb${j}`+ );+ segLabel[j] = `vtb${j}`;+ }+ });++ // Join the segments. Adjacent clips with a transition cross-dissolve+ // (xfade/acrossfade, overlapping by the transition length); the rest hard-cut+ // (concat). Fold left so mixed sequences chain correctly.+ let vAcc = segLabel[0];+ let aAcc = "a0";+ let acc = clipDur(spec.clips[0]); // running timeline length of the accumulator+ for (let j = 1; j < spec.clips.length; j++) {+ const prev = spec.clips[j - 1];+ const durJ = clipDur(spec.clips[j]);+ // The overlap can't exceed most of either clip, matching the editor clamp.+ const d = Math.min(prev.transition ?? 0, acc * 0.9, durJ * 0.9);+ const vOut = `vj${j}`;+ const aOut = `aj${j}`;+ if (d > 0.01) {+ const offset = Math.max(0, acc - d);+ // The style id resolves through the allowlist map; anything unknown+ // (or an old spec without a style) renders as a plain fade.+ const kind = TRANSITION_XFADE[prev.transitionStyle as TransitionStyle] ?? "fade";+ filters.push(`[${vAcc}][${segLabel[j]}]xfade=transition=${kind}:duration=${num(d)}:offset=${num(offset)}[${vOut}]`);+ filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${aOut}]`);+ acc = acc + durJ - d;+ } else {+ filters.push(`[${vAcc}][${segLabel[j]}]concat=n=2:v=1:a=0[${vOut}]`);+ filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${aOut}]`);+ acc = acc + durJ;+ }+ vAcc = vOut;+ aAcc = aOut;+ }++ // Composite the video stack bottom→top: the overlay tracks draw over the+ // track-0 base in track order. A full-frame layer covers; a regioned one+ // shares the frame (split half) or floats (PiP). Overlay audio (unless+ // muted) mixes in below.+ const overlaySoundLabels: string[] = [];+ let ovk = 0;+ // Overlay one track clip onto `onto`, returning the new label; also queues+ // its audio.+ const addOverlay = (oc: (typeof overlayVideos)[number], onto: string): string => {+ if (!oc.image && !videoPresence.get(oc.file)) return onto;+ const idx = oc.image ? imageOverlayInput.get(oc)! : inputIndex.get(oc.file)!;+ const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;+ const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);+ const end = Math.min(oc.start + olen, spec.duration);+ const region = regionPx(oc.frame, W, H);+ const cover = oc.fit === "fill" || (oc.fit == null && !region);+ // Transition ramps, clamped so head+tail never overrun the segment. On an+ // upper track the fades are alpha fades — the clip dissolves against+ // whatever is beneath it (a cross transition ships as the incoming clip's+ // head fade, blending it in over the still-opaque outgoing clip).+ const hz = Math.max(0, Math.min(oc.headZoom ?? 0, olen));+ const tz = Math.max(0, Math.min(oc.tailZoom ?? 0, olen - hz));+ const hf = Math.max(0, Math.min(oc.headFade ?? 0, olen));+ const tf = Math.max(0, Math.min(oc.tailFade ?? 0, olen - hf));+ const ramped = hz > 0.01 || tz > 0.01;+ const boxW = region ? region.rw : W;+ const boxH = region ? region.rh : H;+ let framing: string;+ let pos: string;+ if (!region) {+ framing = cover+ ? `scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H}`+ : `scale=${W}:${H}:force_original_aspect_ratio=decrease:force_divisible_by=2`;+ pos = cover ? "0:0" : `x=(${W}-w)/2:y=(${H}-h)/2`;+ } else {+ const { rx, ry, rw, rh } = region;+ framing = cover+ ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh}`+ : `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2`;+ pos = cover ? `${rx}:${ry}` : `x=${rx}+(${rw}-w)/2:y=${ry}+(${rh}-h)/2`;+ }+ // zoompan needs a constant frame size: pad a letterboxed segment out to+ // its exact box with transparent margins (the tracks beneath keep showing+ // through) and anchor the overlay at the box origin.+ if (ramped && !cover) {+ framing += `,format=yuva420p,pad=${boxW}:${boxH}:(ow-iw)/2:(oh-ih)/2:[email protected]`;+ pos = region ? `${region.rx}:${region.ry}` : "0:0";+ }+ const fmt = hf > 0.01 || tf > 0.01 || (ramped && !cover) ? "yuva420p" : "yuv420p";+ const fades =+ (hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}:alpha=1` : "") ++ (tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, olen - tf))}:d=${num(tf)}:alpha=1` : "");+ const k = ovk++;+ const seg = `ovv${k}`;+ // A still replays its looped input; footage trims its source span and+ // re-times by speed. tpad then delays the clip to its timeline start.+ const timebase = oc.image+ ? `[${idx}:v]setpts=PTS-STARTPTS`+ : `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)}`;+ let core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${fmt}`;+ // Looks bake into footage overlays only: an image may carry alpha, and a+ // padded letterbox has transparent margins — the look chain's internal+ // filters would flatten either onto black over the tracks beneath. The+ // alpha fades stay safe: they apply after the look.+ if (oc.look && !oc.image && !(ramped && !cover)) {+ const lines = lookFilterLines(`olki${k}`, `olko${k}`, oc.look, oc.lookAmount, H, fmt, `o${k}`);+ if (lines) {+ filters.push(`${core}[olki${k}]`);+ filters.push(...lines);+ core = `[olko${k}]null`;+ }+ }+ const pre = `ovp${k}`;+ pushEdgeFx(+ core,+ olen,+ hz > 0.01 ? { kind: "zoom", secs: hz } : null,+ tz > 0.01 ? { kind: "zoom", secs: tz } : null,+ boxW,+ boxH,+ fmt,+ fades,+ pre,+ `o${k}`+ );+ // The zoom slices' concat drops the stream's frame-rate metadata, and+ // tpad converts start_duration to a frame count through it — without the+ // fps re-stamp it pads zero frames and the overlay lands early.+ filters.push(`[${pre}]fps=${fps},tpad=start_duration=${num(oc.start)}[${seg}]`);+ const next = `vovv${k}`;+ filters.push(+ `[${onto}][${seg}]overlay=${pos}:enable='between(t,${num(oc.start)},${num(end)})':eof_action=pass[${next}]`+ );+ if (!oc.muted && audioPresence.get(oc.file)) {+ const tempo = ospeed !== 1 ? `${atempoChain(ospeed)},` : "";+ const vol = (oc.volume ?? 1) !== 1 ? `volume=${num(oc.volume ?? 1)},` : "";+ // The picture's fade edges carry the sound with them; zoom edges don't.+ const afades =+ (hf > 0.01 ? `afade=t=in:st=0:d=${num(hf)},` : "") ++ (tf > 0.01 ? `afade=t=out:st=${num(Math.max(0, olen - tf))}:d=${num(tf)},` : "");+ const delayMs = Math.max(0, Math.round(oc.start * 1000));+ const lab = `ovs${k}`;+ filters.push(+ `[${idx}:a]atrim=${num(oc.in)}:${num(oc.out)},asetpts=PTS-STARTPTS,${tempo}${vol}${afades}` ++ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,adelay=${delayMs}:all=1[${lab}]`+ );+ overlaySoundLabels.push(lab);+ }+ return next;+ };++ let vLabel = vAcc;+ for (const oc of overlayVideos) vLabel = addOverlay(oc, vLabel);++ // Burn in text overlays, each windowed to its timeline range. Half-open so+ // back-to-back overlays sharing a boundary never composite on the same frame.+ spec.overlays.forEach((o, k) => {+ const idx = inputIndex.get(o.file)!;+ const next = `vov${k}`;+ filters.push(+ `[${vLabel}][${idx}:v]overlay=0:0:enable='gte(t,${num(o.start)})*lt(t,${num(o.end)})'[${next}]`+ );+ vLabel = next;+ });++ // Subtitle stills ride one concat-demuxer slideshow per track (transparent+ // filler in the gaps), so a karaoke cut with hundreds of word windows still+ // costs one ffmpeg input per language instead of one per still.+ captionInputs.forEach((idx, k) => {+ filters.push(`[${idx}:v]fps=${fps},format=yuva420p,setsar=1[caps${k}]`);+ filters.push(`[${vLabel}][caps${k}]overlay=0:0:eof_action=pass[vcaps${k}]`);+ vLabel = `vcaps${k}`;+ });++ // Voiceover ducking: while a ducking clip plays, every other sound drops to+ // its gain. The windows are timeline seconds, so the volume automation must+ // run on timeline-aligned streams — the joined clip audio, and each other+ // sound *after* its adelay.+ const duckWindows = spec.audio+ .filter((a) => a.duck !== undefined && a.duck < 1)+ .map((a) => {+ const speed = a.speed && a.speed > 0 ? a.speed : 1;+ const len = Math.max(0.1, (a.out - a.in) / speed);+ return { from: a.start, to: a.start + len, gain: Math.max(0, a.duck!) };+ });+ // Flatten to non-overlapping segments at the lowest covering gain: chained+ // volume filters multiply, so overlapping voiceovers would otherwise duck+ // deeper than the preview (which takes the minimum).+ const duckSegments = (() => {+ const cuts = [...new Set(duckWindows.flatMap((w) => [w.from, w.to]))].sort((a, b) => a - b);+ const segs: { from: number; to: number; gain: number }[] = [];+ for (let i = 0; i + 1 < cuts.length; i++) {+ const [from, to] = [cuts[i], cuts[i + 1]];+ const covering = duckWindows.filter((w) => w.from < to && w.to > from);+ if (covering.length === 0) continue;+ const gain = Math.min(...covering.map((w) => w.gain));+ const prev = segs[segs.length - 1];+ if (prev && prev.to === from && prev.gain === gain) prev.to = to;+ else segs.push({ from, to, gain });+ }+ return segs;+ })();+ let duckSeq = 0;+ const duckOthers = (label: string): string => {+ if (duckSegments.length === 0) return label;+ // Half-open windows: between() includes both ends, so adjacent segments+ // would both fire (and multiply) on the exact boundary frame.+ const chain = duckSegments+ .map((w) => `volume=enable='gte(t,${num(w.from)})*lt(t,${num(w.to)})':volume=${num(w.gain)}`)+ .join(",");+ const out = `dk${duckSeq++}`;+ filters.push(`[${label}]${chain}[${out}]`);+ return out;+ };++ // Soundtrack clips: trim, gain, shift into place, mix with clip audio.+ const soundLabels: string[] = [];+ spec.audio.forEach((a, k) => {+ const idx = inputIndex.get(a.file)!;+ if (!audioPresence.get(a.file)) return;+ const speed = a.speed && a.speed > 0 ? a.speed : 1;+ const delayMs = Math.max(0, Math.round(a.start * 1000));+ // Timeline length after any speed change; fade offsets are in these+ // (post-tempo) seconds, so atempo runs before the fades.+ const len = Math.max(0.1, (a.out - a.in) / speed);+ const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";+ const fades: string[] = [];+ if (a.fadeIn && a.fadeIn > 0.01) fades.push(`afade=t=in:st=0:d=${num(a.fadeIn)}`);+ if (a.fadeOut && a.fadeOut > 0.01)+ fades.push(`afade=t=out:st=${num(Math.max(0, len - a.fadeOut))}:d=${num(a.fadeOut)}`);+ filters.push(+ `[${idx}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,${tempo}` ++ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` ++ `volume=${num(a.volume)},` ++ (fades.length ? fades.join(",") + "," : "") ++ `adelay=${delayMs}:all=1[snd${k}]`+ );+ // Music and other non-voiceover sound ducks under the voiceovers.+ soundLabels.push(a.duck !== undefined && a.duck < 1 ? `snd${k}` : duckOthers(`snd${k}`));+ });++ // The joined clip audio and overlay-video audio duck too.+ let aLabel = duckOthers(aAcc);+ const extraSound = [...soundLabels, ...overlaySoundLabels.map(duckOthers)];+ if (extraSound.length > 0) {+ const mixIn = [aLabel, ...extraSound].map((l) => `[${l}]`).join("");+ filters.push(+ `${mixIn}amix=inputs=${extraSound.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`+ );+ aLabel = "amix";+ }++ // Whole-video fades on the final composite and mix, so titles, captions,+ // overlays, and soundtrack all fade together.+ const fadeIn = projectFadeSeconds(spec.fadeIn, spec.duration);+ const fadeOut = projectFadeSeconds(spec.fadeOut, spec.duration);+ if (fadeIn > 0.01 || fadeOut > 0.01) {+ const win = (f: string) =>+ [+ ...(fadeIn > 0.01 ? [`${f}=t=in:st=0:d=${num(fadeIn)}`] : []),+ ...(fadeOut > 0.01+ ? [`${f}=t=out:st=${num(Math.max(0, spec.duration - fadeOut))}:d=${num(fadeOut)}`]+ : []),+ ].join(",");+ filters.push(`[${vLabel}]${win("fade")}[vfinal]`);+ vLabel = "vfinal";+ filters.push(`[${aLabel}]${win("afade")}[afinal]`);+ aLabel = "afinal";+ }++ const enc = await h264Encoder();+ const videoCodecArgs =+ enc === "libx264"+ ? ["-c:v", "libx264", "-preset", spec.preset, "-crf", String(spec.crf)]+ : ["-c:v", "h264_videotoolbox", "-q:v", String(vtQuality(spec.crf)), "-allow_sw", "1"];++ // Encode into the tmp dir, then re-emit the container to strip a stray output+ // rotation flag (see the strip pass below). Keeping the encode intermediate+ // lets the second pass own faststart.+ const encodePath = path.join(job.tmpDir, "encode.mp4");+ await runFfmpeg(+ job,+ [+ "-y",+ ...inputs,+ "-filter_complex", filters.join(";"),+ "-map", `[${vLabel}]`,+ "-map", `[${aLabel}]`,+ ...videoCodecArgs,+ "-profile:v", "high",+ "-pix_fmt", "yuv420p",+ "-color_range", "tv",+ "-colorspace", "bt709",+ "-color_primaries", "bt709",+ "-color_trc", "bt709",+ "-c:a", "aac",+ "-b:a", "192k",+ "-t", num(spec.duration),+ encodePath,+ ],+ (t) => (job.progress = Math.min(0.99, t / Math.max(0.1, spec.duration)))+ );++ // ffmpeg's autorotation already baked each source's display matrix into the+ // pixels, so the encode's frames are upright. But for a complex filtergraph it+ // ALSO copies the first input's display-matrix side data onto the output+ // stream — so a phone (portrait) source lands as a correct 1080×1920 file+ // tagged with a stray 90° rotation, and players re-rotate it into a sideways+ // "desktop" frame. `-display_rotation 0` overrides that matrix to identity; a+ // stream copy re-emits the (already correct) pixels and audio unchanged and+ // writes the faststart-optimized final file.+ await runFfmpeg(job, [+ "-y",+ "-display_rotation", "0",+ "-i", encodePath,+ "-map", "0",+ "-c", "copy",+ "-movflags", "+faststart",+ job.outPath,+ ]);++ job.progress = 1;+}diff --git a/site/src/cut/server/http/match.ts b/site/src/cut/server/http/match.tsnew file mode 100644index 00000000..f8554e3c--- /dev/null+++ b/site/src/cut/server/http/match.ts@@ -0,0 +1,70 @@+// Generic route-table matcher shared by the Cut engine router (http/routes.ts)+// and the hosted cloud router (cloud/routes.ts). It lives in its own leaf module+// so the cloud mount can import the matcher without pulling the engine's module+// graph into a hosted bundle.++export interface RouteEntry {+ method: "GET" | "POST" | "PUT" | "DELETE";+ path: string; // ":name" segments bind params+}++export type RouteTableMatch<T extends RouteEntry> =+ | { route: T; params: Record<string, string>; head: boolean }+ | { methodNotAllowed: string[] };++/** Bind a pattern against path segments. Returns the bound params and a+ * specificity score (count of literal segment matches) so more-literal paths+ * win, or null when the shape doesn't match. Params bind RAW (percent-encoded),+ * matching what Next hands its route files — handlers decode themselves. */+function bindPath(+ pattern: string,+ segs: string[]+): { params: Record<string, string>; score: number } | null {+ const pat = pattern.split("/").filter(Boolean);+ if (pat.length !== segs.length) return null;+ const params: Record<string, string> = {};+ let score = 0;+ for (let i = 0; i < pat.length; i++) {+ const p = pat[i];+ if (p.startsWith(":")) params[p.slice(1)] = segs[i];+ else if (p === segs[i]) score++;+ else return null;+ }+ return { params, score };+}++/**+ * Match a request against a route table, mirroring Next's routing so every+ * mount behaves identically: static path segments win over dynamic ones, HEAD+ * is served by the GET handler, and a path that exists for other methods+ * returns 405 (not a dynamic-route false match).+ */+export function matchRouteTable<T extends RouteEntry>(+ routes: readonly T[],+ method: string,+ pathname: string+): RouteTableMatch<T> | null {+ const segs = pathname.split("/").filter(Boolean);+ const wanted = method === "HEAD" ? "GET" : method;++ const matches = routes+ .map((route) => {+ const bound = bindPath(route.path, segs);+ return bound ? { route, params: bound.params, score: bound.score } : null;+ })+ .filter((m) => m !== null);+ if (matches.length === 0) return null;++ // The most-literal path is the single route Next would pick for this URL.+ const top = Math.max(...matches.map((m) => m.score));+ const chosen = matches.filter((m) => m.score === top);++ const hit = chosen.find((m) => m.route.method === wanted);+ if (hit) return { route: hit.route, params: hit.params, head: method === "HEAD" };++ // Path matched but this method has no handler → 405, as Next returns.+ const allow = new Set<string>(chosen.map((m) => m.route.method));+ if (allow.has("GET")) allow.add("HEAD");+ allow.add("OPTIONS");+ return { methodNotAllowed: [...allow] };+}diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 0d795f83..4154688b 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -1,4 +1,5 @@import { adoptLegacyData, isValidCutUser, runWithCutUser } from "../userScope";+import { matchRouteTable } from "./match";import { aiApi } from "./ai";import { engineApi } from "./engine";import { exportApi } from "./export";@@ -119,60 +120,19 @@ export async function runCutRoute(return runWithCutUser(user, () => match.handler(req, match.params));}-/** Bind a pattern against path segments. Returns the bound params and a- * specificity score (count of literal segment matches) so more-literal paths- * win, or null when the shape doesn't match. Params bind RAW (percent-encoded),- * matching what Next hands its route files — handlers decode themselves. */-function bindPath(- pattern: string,- segs: string[]-): { params: Record<string, string>; score: number } | null {- const pat = pattern.split("/").filter(Boolean);- if (pat.length !== segs.length) return null;- const params: Record<string, string> = {};- let score = 0;- for (let i = 0; i < pat.length; i++) {- const p = pat[i];- if (p.startsWith(":")) params[p.slice(1)] = segs[i];- else if (p === segs[i]) score++;- else return null;- }- return { params, score };-}-/**- * Match a request against the table, mirroring Next's routing so the engine and- * dev server behave identically: static path segments win over dynamic ones,- * HEAD is served by the GET handler, and a path that exists for other methods- * returns 405 (not a dynamic-route false match).+ * Match a request against the table via the shared matcher (http/match.ts):+ * static path segments win over dynamic ones, HEAD is served by the GET+ * handler, and a path that exists for other methods returns 405.*/export function matchCutRoute(method: string, pathname: string): RouteMatch | null {- const segs = pathname.split("/").filter(Boolean);- const wanted = method === "HEAD" ? "GET" : method;-- const matches = CUT_ROUTES.map((route) => {- const bound = bindPath(route.path, segs);- return bound ? { route, params: bound.params, score: bound.score } : null;- }).filter((m) => m !== null);- if (matches.length === 0) return null;-- // The most-literal path is the single route Next would pick for this URL.- const top = Math.max(...matches.map((m) => m.score));- const chosen = matches.filter((m) => m.score === top);-- const hit = chosen.find((m) => m.route.method === wanted);- if (hit) {- return {- handler: hit.route.handler,- params: hit.params,- head: method === "HEAD",- scoped: hit.route.scoped !== false,- };- }-- // Path matched but this method has no handler → 405, as Next returns.- const allow = new Set<string>(chosen.map((m) => m.route.method));- if (allow.has("GET")) allow.add("HEAD");- allow.add("OPTIONS");- return { methodNotAllowed: [...allow] };+ const match = matchRouteTable(CUT_ROUTES, method, pathname);+ if (!match) return null;+ if ("methodNotAllowed" in match) return match;+ return {+ handler: match.route.handler,+ params: match.params,+ head: match.head,+ scoped: match.route.scoped !== false,+ };}diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 2ef97284..9b0adaa7 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -1,123 +1,14 @@-import { spawn, type ChildProcess } from "node:child_process";-import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";+import { type ChildProcess } from "node:child_process";+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";import { createJobRegistry } from "./jobRegistry";+import { runExport, type ExportSpec } from "./exportPipeline";import { exportsDir, mediaPath, projectDir, readProject } from "./projects";import { currentCutUser } from "./userScope";-import { atempoChain, hasStream, num, videoColorInfo } from "./util";-import { projectFadeSeconds, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";-import { gradeToFfmpegFilter } from "../lib/colorGrade";-import { lookFilterLines } from "../lib/looks";-export interface ExportSpec {- projectId: string;- /** "preview" renders the low-res hover proxy into the project's preview.mp4- * instead of a stamped file in exports/. */- target?: "export" | "preview";- width: number;- height: number;- fps: number;- crf: number;- preset: string;- duration: number;- /** Whole-video fades, seconds: in from black / out to black, applied to the- * final composite and mix after all overlays and soundtrack. */- fadeIn?: number;- fadeOut?: number;- clips: {- file: string;- in: number;- out: number;- muted: boolean;- /** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */- volume?: number;- /** "fit" letterboxes (default); "fill" covers the region and crops. */- fit?: "fit" | "fill";- panX?: number; // crop-window pan -1..1 (fill mode, full frame)- panY?: number;- /** Region of the frame this clip fills; absent = full frame. */- frame?: { x: number; y: number; w: number; h: number };- speed?: number; // playback rate, default 1- /** Transition into the next clip, in timeline seconds (overlap). */- transition?: number;- /** Transition look id, resolved to an xfade name through the- * TRANSITION_XFADE allowlist (unknown ids render as a plain fade). Cross- * zoom renders as the fade plus zoom ramps on both segments' overlap- * windows. */- transitionStyle?: string;- /** This clip's own entrance/exit animation, baked into the segment's- * head/tail window: fade (audio follows), zoom, pop, or a slide- * against black. Unknown styles render as a fade. */- animIn?: { style: string; seconds: number };- animOut?: { style: string; seconds: number };- /** Preset filter look id + strength 0..1, baked into the segment (the- * spec carries only the id — the chain is built server-side). */- look?: string;- lookAmount?: number;- /** Hidden clips keep their slot but render black + silent. */- hidden?: boolean;- /** A still image: looped for the clip's length instead of trimmed. */- image?: boolean;- /** Manual color adjustments, baked into this clip's segment. */- grade?: ColorGrade;- }[];- /** Video tracks composited over the track-0 `clips`, lowest track first. */- overlayVideos?: {- file: string;- in: number;- out: number;- start: number; // timeline position, seconds- track: number;- /** Region of the frame this overlay fills; absent = full frame. */- frame?: { x: number; y: number; w: number; h: number };- fit?: "fit" | "fill";- muted: boolean;- /** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */- volume?: number;- speed?: number;- /** Transition ramps, timeline seconds from this overlay's head/tail. On- * an upper track a fade is an alpha fade (the tracks beneath show- * through); a cross transition arrives as the incoming clip's headFade- * while the outgoing clip stays opaque under it, and cross zoom adds a- * tailZoom/headZoom pair riding that overlap. The audio fades with the- * picture. */- headFade?: number;- tailFade?: number;- headZoom?: number;- tailZoom?: number;- /** A still image: looped for the clip's length instead of trimmed. */- image?: boolean;- /** Manual color adjustments, baked into this overlay's segment. */- grade?: ColorGrade;- /** Preset filter look id + strength (footage overlays only — image- * overlays may carry alpha the look chain would flatten). */- look?: string;- lookAmount?: number;- }[];- audio: {- file: string;- in: number;- out: number;- start: number;- volume: number;- fadeIn?: number;- fadeOut?: number;- /** Playback rate (detached-audio clips inherit their video clip's speed). */- speed?: number;- /** Voiceover ducking: while this clip plays, every other sound drops to- * this gain (0..1). Ducking clips never duck each other. */- duck?: number;- }[];- overlays: { file: string; start: number; end: number }[];- /** Burned-in subtitle stills. Kept apart from `overlays` (titles may- * overlap each other): each subtitle track (`lane`, absent = 0) is- * non-overlapping and chronological within itself and renders as one- * concat-demuxer slideshow, so karaoke word windows don't multiply inputs.- * Tracks overlap each other in time (one language each). */- captions?: { file: string; start: number; end: number; lane?: number }[];-}+export type { ExportSpec } from "./exportPipeline";export interface Job {id: string;@@ -177,7 +68,10 @@ function pump() {function startRun(job: Job, spec: ExportSpec) {job.status = "running";job.startedAt = Date.now();- void runExport(job, spec)+ void runExport(job, spec, (file) => mediaPath(spec.projectId, file))+ .then(() => {+ job.status = "done";+ }).catch((err: unknown) => {job.status = "error";job.error = err instanceof Error ? err.message : String(err);@@ -356,957 +250,3 @@ export async function createJob(form: FormData): Promise<Job> {}return job;}--/** The H.264 encoder to use, probed once against the same `ffmpeg` the exports- * spawn. Prefer libx264 (CRF + presets) when the build carries it — the dev- * Homebrew ffmpeg does. The bundled engine ffmpeg is LGPL (`--disable-gpl`), so- * it has no libx264 and `-preset`/`-crf` don't exist there; fall back to the- * always-present VideoToolbox hardware H.264 encoder. */-let h264EncoderCache: Promise<"libx264" | "h264_videotoolbox"> | null = null;-function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {- return (h264EncoderCache ??= new Promise((resolve) => {- let out = "";- const proc = spawn("ffmpeg", ["-hide_banner", "-encoders"]);- proc.stdout?.on("data", (c: Buffer) => (out += c.toString()));- proc.on("error", () => resolve("h264_videotoolbox"));- proc.on("close", () => resolve(/\blibx264\b/.test(out) ? "libx264" : "h264_videotoolbox"));- }));-}--/** VideoToolbox constant quality (1–100, higher = better) from the CRF knob the- * presets carry (lower CRF = better). Maps the 19/24/30 tiers to ~66/57/46. */-function vtQuality(crf: number) {- return Math.round(Math.max(35, Math.min(80, 100 - crf * 1.8)));-}--async function resolveMedia(spec: ExportSpec, file: string) {- const p = mediaPath(spec.projectId, file);- const info = await stat(p).catch(() => null);- if (!info?.isFile()) throw new Error(`Media file missing from project: ${file}`);- return p;-}--/**- * Filter prefix converting a wide-gamut/HDR source (phone footage: BT.2020- * primaries with an HLG or PQ transfer) down to the BT.709 SDR the export is- * tagged as, or "" for an SDR source. The blind `format=yuv420p` squeeze keeps- * BT.2020 code values, and players reading them as 709 wash the clip out —- * visible whenever phone footage sits next to Cut-rendered (already-709)- * clips. The native `colorspace` filter has no HLG/PQ transfer, so the input- * is pinned to bt2020-10, a close stand-in over HLG's SDR-compatible range;- * the 10-bit format hop feeds it a planar format it accepts (decoders hand- * HDR frames over as p010, which it rejects).- *- * The matrix decides, the way players decide. Social-app transcodes (8-bit- * H.264) keep BT.2020 primaries + HLG transfer tags from the phone original- * but write an explicit bt709 matrix — players read those as plain 709 SDR,- * so converting them shifts hue and saturation against what every player- * shows (verified frame-for-frame against WebKit playback). Convert only- * when the matrix itself is BT.2020, or when it's untagged and the wide- * primaries/transfer tags are the only signal there is.- */-function sdrConvert(c: Awaited<ReturnType<typeof videoColorInfo>>) {- if (c == null) return "";- const matrix = c.matrix && c.matrix !== "unknown" ? c.matrix : null;- const wide =- matrix?.startsWith("bt2020") === true ||- (matrix === null &&- (c.primaries === "bt2020" ||- c.transfer === "arib-std-b67" ||- c.transfer === "smpte2084"));- return wide ? "format=yuv420p10le,colorspace=all=bt709:iall=bt2020:format=yuv420p," : "";-}--/** A clip's effective playback rate (>0, default 1). */-function clipRate(c: ExportSpec["clips"][number]) {- return c.speed && c.speed > 0 ? c.speed : 1;-}--/** A clip's frame region in even pixels, or null when it fills the whole frame- * (the common case, which keeps the plain full-frame filter path). */-function regionPx(- frame: { x: number; y: number; w: number; h: number } | undefined,- W: number,- H: number-) {- if (!frame) return null;- const even = (n: number) => 2 * Math.round(n / 2);- const rw = Math.min(W, Math.max(2, even(frame.w * W)));- const rh = Math.min(H, Math.max(2, even(frame.h * H)));- // Clamp the origin so rx+rw ≤ W and ry+rh ≤ H — independent even-rounding can- // otherwise push an edge-touching region a pixel past the frame, which makes- // the pad filter reject the input ("not within the padded area") and aborts- // the whole export.- const rx = Math.max(0, Math.min(even(frame.x * W), W - rw));- const ry = Math.max(0, Math.min(even(frame.y * H), H - rh));- if (rx <= 0 && ry <= 0 && rw >= W && rh >= H) return null;- return { rx, ry, rw, rh };-}--/**- * Spawn ffmpeg for one pass, tracking `job.proc` so a cancel kills the live- * process, bounding silence with the stall watchdog, and (when `onProgress` is- * given) reporting the `time=` cursor from stderr. Rejects with a readable- * message on a non-zero exit or a missing binary. Shared by the encode pass and- * the rotation-strip remux.- */-function runFfmpeg(- job: Job,- args: string[],- onProgress?: (seconds: number) => void-): Promise<void> {- return new Promise<void>((resolve, reject) => {- const proc = spawn("ffmpeg", args);- job.proc = proc;- // Stall watchdog: legit exports can run long, so bound silence, not total- // time — kill only if ffmpeg emits nothing for STALL_MS.- const STALL_MS = 120_000;- let watchdog: ReturnType<typeof setTimeout> | undefined;- const bump = () => {- clearTimeout(watchdog);- watchdog = setTimeout(() => {- proc.kill("SIGKILL");- reject(new Error("Export stalled — no ffmpeg output for 120s."));- }, STALL_MS);- watchdog.unref();- };- bump();- proc.stderr.on("data", (chunk: Buffer) => {- bump();- const text = chunk.toString();- job.log.push(text);- if (job.log.length > 200) job.log.shift();- if (onProgress) {- const m = /time=(\d+):(\d+):([\d.]+)/.exec(text);- if (m) onProgress(Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]));- }- });- proc.on("error", (err) => {- clearTimeout(watchdog);- reject(- err.message.includes("ENOENT")- ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")- : err- );- });- proc.on("close", (code) => {- clearTimeout(watchdog);- if (code === 0) resolve();- else if (job.error) reject(new Error(job.error));- else reject(new Error(`ffmpeg exited with code ${code}.\n${job.log.slice(-8).join("")}`));- });- });-}--async function runExport(job: Job, spec: ExportSpec) {- if (spec.clips.length === 0) throw new Error("Nothing to export.");- const { width: W, height: H, fps } = spec;-- // Tracks number 0..N bottom-up: track 0 folds sequentially into the base- // picture, the rest overlay it in track order (highest last = frontmost).- // Within a track, earlier clips composite first, so a dissolving pair- // blends the incoming clip in over the outgoing one.- const overlayVideos = [...(spec.overlayVideos ?? [])].sort(- (a, b) => a.track - b.track || a.start - b.start- );- const clipFmt = "yuv420p";- const padColor = "black";- // One ffmpeg input per distinct media file (from the project folder),- // plus one per uploaded overlay PNG.- // Still images are excluded here: a plain `-i file` decodes one frame, so- // each image clip/overlay gets its own looped input below instead. Gap- // spacers (empty file) reference no media at all — they render as black.- const mediaFiles = [- ...new Set(- [- ...spec.clips.filter((c) => !c.image),- ...spec.audio,- ...overlayVideos.filter((o) => !o.image),- ]- .map((c) => c.file)- .filter(Boolean)- ),- ];- const audioPresence = new Map<string, boolean>();- const videoPresence = new Map<string, boolean>();- // file → filter prefix folding a wide-gamut/HDR source down to BT.709 (or "").- const colorFix = new Map<string, string>();- const inputs: string[] = [];- const inputIndex = new Map<string, number>();- // Counted explicitly: the concat input below carries extra flags, so the- // args array is not a clean ["-i", path] pair per input.- let nInputs = 0;- // Resolve paths in order first so ffmpeg input indices stay deterministic,- // then probe every file's streams concurrently.- const paths = await Promise.all(mediaFiles.map((f) => resolveMedia(spec, f)));- mediaFiles.forEach((f, i) => {- inputIndex.set(f, nInputs++);- inputs.push("-i", paths[i]);- });- await Promise.all(- mediaFiles.map(async (f, i) => {- // A probe that errors (timeout, non-zero exit) must not be read as- // "no stream" — that would silently drop real audio to silence or real- // video to black. Genuine absence returns false with no error, so on a- // probe error we assume the stream is present and let ffmpeg map it.- let audioProbeFailed = false;- const hasAudio = await hasStream(paths[i], "a", () => (audioProbeFailed = true));- audioPresence.set(f, hasAudio || audioProbeFailed);- let videoProbeFailed = false;- const hasVideo = await hasStream(paths[i], "v", () => (videoProbeFailed = true));- videoPresence.set(f, hasVideo || videoProbeFailed);- // A failed color probe (null) means no conversion — SDR passthrough.- colorFix.set(f, sdrConvert(await videoColorInfo(paths[i])));- })- );- for (const o of spec.overlays) {- inputIndex.set(o.file, nInputs++);- inputs.push("-i", path.join(job.tmpDir, path.basename(o.file)));- }-- // Looped input per still image, sized to the clip's timeline length so the- // segment fills without a source trim. Keyed by clip/overlay identity since- // two clips of the same image can have different lengths.- const imageClipInput = new Map<number, number>();- for (let j = 0; j < spec.clips.length; j++) {- const c = spec.clips[j];- if (!c.image || !c.file) continue;- const dur = Math.max(0.1, (c.out - c.in) / clipRate(c));- imageClipInput.set(j, nInputs++);- inputs.push("-loop", "1", "-t", num(dur), "-framerate", String(fps), "-i", await resolveMedia(spec, c.file));- }- const imageOverlayInput = new Map<(typeof overlayVideos)[number], number>();- for (const oc of overlayVideos) {- if (!oc.image) continue;- const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;- const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);- imageOverlayInput.set(oc, nInputs++);- inputs.push("-loop", "1", "-t", num(olen), "-framerate", String(fps), "-i", await resolveMedia(spec, oc.file));- }-- // One concat-demuxer input per subtitle track: within a track cues never- // overlap, so each plays as a slideshow with transparent filler- // ("sub_blank.png", uploaded with the stills) covering the gaps. Tracks- // (languages) overlap each other, so each gets its own input.- const captionLanes = new Map<number, NonNullable<ExportSpec["captions"]>>();- for (const c of spec.captions ?? []) {- if (c.end <= c.start) continue;- const lane = c.lane ?? 0;- if (!captionLanes.has(lane)) captionLanes.set(lane, []);- captionLanes.get(lane)!.push(c);- }- const captionInputs: number[] = [];- for (const [lane, entries] of [...captionLanes.entries()].sort((a, b) => a[0] - b[0])) {- entries.sort((a, b) => a.start - b.start);- const blank = path.join(job.tmpDir, "sub_blank.png");- const lines = ["ffconcat version 1.0"];- let cursor = 0;- for (const c of entries) {- const from = Math.max(c.start, cursor);- if (c.end - from < 1e-3) continue;- if (from - cursor > 1e-3) lines.push(`file '${blank}'`, `duration ${num(from - cursor)}`);- lines.push(- `file '${path.join(job.tmpDir, path.basename(c.file))}'`,- `duration ${num(c.end - from)}`- );- cursor = c.end;- }- if (spec.duration - cursor > 1e-3) {- lines.push(`file '${blank}'`, `duration ${num(spec.duration - cursor)}`);- }- const list = path.join(job.tmpDir, `captions_${lane}.ffconcat`);- await writeFile(list, lines.join("\n") + "\n");- captionInputs.push(nInputs++);- inputs.push("-f", "concat", "-safe", "0", "-i", list);- }-- const filters: string[] = [];-- // Per-clip timeline length (source span compressed/expanded by speed). A- // gap spacer (no file) keeps its exact length: flooring it at 0.1s would- // land everything after the gap later than the timeline shows, drifting- // burned-in captions off the picture.- const clipDur = (c: ExportSpec["clips"][number]) =>- c.file ? Math.max(0.1, (c.out - c.in) / clipRate(c)) : Math.max(0, c.out - c.in);-- /** One edge effect on a segment's head or tail window. `zoom` ramps scale- * (settling in on the head, pushing in on the tail); `xfade` runs the named- * xfade transition against a backdrop — the label in `bg` (a neighbor's- * held frame), or a black frame when absent; `pop` scales the picture up- * from / down to 80% with a fade over the same backdrop. */- type EdgeFx = { kind: "zoom" | "pop" | "xfade"; secs: number; xfade?: string; bg?: string };-- /** Emit `core` into `[out]` with the head/tail edge effects confined to- * their windows and `fades` appended. Each effected window is sliced out- * (split → trim → fx → concat) so per-frame effects stay inside the short- * ramp; plain fades ride `fades` inline instead. `w`×`h` is the segment's- * constant frame size; `tag` uniquifies intermediate labels. Shared by the- * track-0 segments and the overlay-track segments. */- const pushEdgeFx = (- core: string,- dur: number,- head: EdgeFx | null,- tail: EdgeFx | null,- w: number,- h: number,- fmt: string,- fades: string,- out: string,- tag: string- ) => {- const zoomRamp = (side: "head" | "tail", secs: number) => {- // A head ramp settles TRANSITION_ZOOM→1 (zoom out), a tail ramp pushes- // 1→TRANSITION_ZOOM (zoom in); zoompan clamps z below 1 itself, so the- // plain arithmetic needs no guards.- const frames = Math.max(1, Math.round(secs * fps) - 1);- const k = num(TRANSITION_ZOOM - 1);- const z =- side === "tail"- ? `1+${k}*in/${frames}`- : `${num(TRANSITION_ZOOM)}-${k}*in/${frames}`;- return (- `zoompan=z=${z}:x=iw/2-(iw/zoom/2):y=ih/2-(ih/zoom/2)` +- `:d=1:s=${w}x${h}:fps=${fps},setsar=1,format=${fmt}`- );- };- // Emit one sliced window's effect from `[inLab]` to `[outLab]`. The- // multi-input effects push their own filter lines.- const applyFx = (fx: EdgeFx, side: "head" | "tail", inLab: string, outLab: string) => {- const d = num(fx.secs);- if (fx.kind === "zoom") {- filters.push(`[${inLab}]${zoomRamp(side, fx.secs)}[${outLab}]`);- return;- }- // The backdrop behind the window: a neighbor's held frame when given- // (an abutting cut), else black (timeline ends and gaps).- let bg = fx.bg;- if (!bg) {- bg = `xb${tag}_${side}`;- filters.push(`color=c=black:s=${w}x${h}:r=${fps}:d=${d},format=${fmt}[${bg}]`);- }- if (fx.kind === "xfade") {- // Entering: the backdrop hands off to the picture; exiting: the- // picture hands off to the backdrop. Anim style ids map straight to- // xfade names (probed: slideleft moves the frame leftward, so it- // enters from the right edge and exits off the left; cover/reveal- // and wipes share the same direction footprints).- filters.push(- side === "head"- ? `[${bg}][${inLab}]xfade=transition=${fx.xfade}:duration=${d}:offset=0[${outLab}]`- : `[${inLab}][${bg}]xfade=transition=${fx.xfade}:duration=${d}:offset=0[${outLab}]`- );- return;- }- // Pop: scale 80%↔100% over the window (even dimensions for yuv420p),- // centered over the backdrop. With a held-frame backdrop the picture- // alpha-fades so the neighbor stays visible behind it; over black the- // plain fade is the same thing cheaper.- const p = side === "head" ? `min(t/${d},1)` : `1-min(t/${d},1)`;- const sc = `sc${tag}_${side}`;- const scaleExpr = `scale=w='trunc(iw*(0.8+0.2*(${p}))/2)*2':h=-2:eval=frame`;- if (fx.bg) {- filters.push(- `[${inLab}]format=yuva420p,` +- `fade=t=${side === "head" ? "in" : "out"}:st=0:d=${d}:alpha=1,${scaleExpr}[${sc}]`- );- filters.push(- `[${bg}][${sc}]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1,format=${fmt}[${outLab}]`- );- return;- }- filters.push(`[${inLab}]${scaleExpr}[${sc}]`);- filters.push(- `[${bg}][${sc}]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1,` +- `fade=t=${side === "head" ? "in" : "out"}:st=0:d=${d},format=${fmt}[${outLab}]`- );- };- const hs = head && head.secs > 0.01 ? head : null;- const ts = tail && tail.secs > 0.01 ? tail : null;- if (!hs && !ts) {- filters.push(`${core}${fades}[${out}]`);- return;- }- const slices: { from: number; to: number; fx?: EdgeFx; side: "head" | "tail" }[] = [];- if (hs) slices.push({ from: 0, to: hs.secs, fx: hs, side: "head" });- const mid0 = hs ? hs.secs : 0;- const mid1 = ts ? dur - ts.secs : dur;- if (mid1 - mid0 > 0.01) slices.push({ from: mid0, to: mid1, side: "head" });- if (ts) slices.push({ from: dur - ts.secs, to: dur, fx: ts, side: "tail" });- filters.push(`${core},split=${slices.length}${slices.map((_, k) => `[zs${tag}_${k}]`).join("")}`);- slices.forEach((sl, k) => {- const cut = `zc${tag}_${k}`;- // setpts clears the constant-frame-rate metadata the slice xfades- // demand — re-stamp it on every cut.- filters.push(- `[zs${tag}_${k}]trim=${num(sl.from)}:${num(sl.to)},setpts=PTS-STARTPTS,fps=${fps}[${cut}]`- );- if (sl.fx) applyFx(sl.fx, sl.side, cut, `zp${tag}_${k}`);- else filters.push(`[${cut}]null[zp${tag}_${k}]`);- });- // concat drops the stream's constant-frame-rate metadata and a downstream- // xfade join refuses a variable-rate input — re-stamp it.- filters.push(- slices.map((_, k) => `[zp${tag}_${k}]`).join("") +- `concat=n=${slices.length}:v=1:a=0,fps=${fps}${fades}[${out}]`- );- };-- /** The edge effect a clip animation asks for, or null when it's a plain- * fade (fades ride the inline `fade`/`afade` filters instead of a slice).- * Unknown styles fall back to the fade path. */- const animEdgeFx = (a: { style: string; seconds: number } | undefined, max: number): EdgeFx | null => {- if (!a || a.seconds <= 0.01 || max <= 0.01) return null;- const secs = Math.min(a.seconds, max);- if (a.style === "zoom") return { kind: "zoom", secs };- if (a.style === "pop") return { kind: "pop", secs };- if (/^slide(left|right|up|down)$/.test(a.style)) {- return { kind: "xfade", secs, xfade: a.style };- }- return null;- };-- /** Whether an animation renders through the inline fade filters. */- const isFadeAnim = (a: { style: string; seconds: number } | undefined) =>- !!a && a.seconds > 0.01 && !animEdgeFx(a, Infinity);-- // A clip animation at an abutting hard cut plays over the neighbor's held- // frame instead of black — an entrance covers the previous clip's last- // frame, an exit reveals the next clip's first frame. Black remains where- // there is no neighbor: the timeline's ends, gaps (the adjacent entry is a- // spacer), and hidden neighbors. Zoom never uncovers the frame, so it needs- // no backdrop. Precomputed so pass 1 can defer these animations and split- // off the freeze sources the second pass consumes.- const freezable = (c?: ExportSpec["clips"][number]) =>- !!c && !!c.file && !c.hidden && (!!c.image || !!videoPresence.get(c.file));- const effAnimIn = (j: number) => {- const p = spec.clips[j - 1];- return p && (p.transition ?? 0) > 0.01 ? undefined : spec.clips[j].animIn;- };- const effAnimOut = (j: number) => {- const n = spec.clips[j + 1];- return n && (spec.clips[j].transition ?? 0) > 0.01 ? undefined : spec.clips[j].animOut;- };- const backdropAnim = (a?: { style: string; seconds: number }) =>- a && a.seconds > 0.01 && a.style !== "zoom" ? a : undefined;- const headBd = spec.clips.map(- (c, j) => !!(freezable(c) && backdropAnim(effAnimIn(j)) && freezable(spec.clips[j - 1]))- );- const tailBd = spec.clips.map(- (c, j) => !!(freezable(c) && backdropAnim(effAnimOut(j)) && freezable(spec.clips[j + 1]))- );- const needFirstFreeze = spec.clips.map((_, j) => j > 0 && tailBd[j - 1]);- const needLastFreeze = spec.clips.map((_, j) => j < spec.clips.length - 1 && headBd[j + 1]);-- // Per-clip normalized video + audio segments for the join below.- spec.clips.forEach((c, j) => {- const idx = c.image ? imageClipInput.get(j)! : inputIndex.get(c.file)!;- const speed = clipRate(c);- const dur = clipDur(c);- const prevC = spec.clips[j - 1];- const nextC = spec.clips[j + 1];- // Cross zoom renders as the fade join plus zoom ramps riding the overlap- // window on both segments (clamped like the join clamps its overlap).- const czOverlap = (a: (typeof spec.clips)[number], aDur: number, bDur: number) =>- a.transitionStyle === "crosszoom"- ? Math.min(a.transition ?? 0, aDur * 0.9, bDur * 0.9)- : 0;- const czHead = prevC ? czOverlap(prevC, clipDur(prevC), dur) : 0;- const czTail = nextC ? czOverlap(c, dur, clipDur(nextC)) : 0;- // A transitioned joint owns its edges: with a live overlap into or out of- // this clip, that side's animation is held (running both would fight over- // the same window) — `transition` in the spec is already the clamped live- // overlap, so 0 means a hard cut and the animation plays. Matches the- // preview's suppression exactly.- const animIn = prevC && (prevC.transition ?? 0) > 0.01 ? undefined : c.animIn;- const animOut = nextC && (c.transition ?? 0) > 0.01 ? undefined : c.animOut;- // The clip's own animations own their edge windows (fade animations ride- // the inline fade filters below); cross zoom fills a side its animation- // leaves free. Clamped so head+tail never overrun the segment. Backdrop- // animations are deferred to the second pass, which runs them against the- // neighbor's held frame — only their audio fade stays here.- const animInNow = headBd[j] ? undefined : animIn;- const animOutNow = tailBd[j] ? undefined : animOut;- let headFx = animEdgeFx(animInNow, dur);- let tailFx = animEdgeFx(animOutNow, dur - (headFx?.secs ?? 0));- const hf = isFadeAnim(animInNow) ? Math.min(animInNow!.seconds, dur) : 0;- const tf = isFadeAnim(animOutNow) ? Math.min(animOutNow!.seconds, dur - hf) : 0;- // The sound of a fade animation follows the picture whether the fade- // renders inline (over black) or in the backdrop pass.- const ahf = animIn?.style === "fade" ? Math.min(animIn.seconds, dur) : 0;- const atf =- animOut?.style === "fade" ? Math.min(animOut.seconds, Math.max(0, dur - ahf)) : 0;- if (!headFx && hf <= 0.01 && czHead > 0.01) {- headFx = { kind: "zoom", secs: Math.min(czHead, dur) };- }- if (!tailFx && tf <= 0.01 && czTail > 0.01) {- tailFx = { kind: "zoom", secs: Math.min(czTail, dur - (headFx?.secs ?? 0)) };- }- // A still's looped input is already the right length at `fps`; it has no- // source span to trim. Footage trims `in..out` and re-times by speed.- const timebase = c.image- ? `[${idx}:v]setpts=PTS-STARTPTS`- : `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=(PTS-STARTPTS)/${num(speed)}`;- if ((c.image || videoPresence.get(c.file)) && !c.hidden) {- const region = regionPx(c.frame, W, H);- let frame: string;- if (region) {- // A regioned track-0 clip (split-screen half) scales into its rect,- // then pads out to the full frame with black around it.- const { rx, ry, rw, rh } = region;- frame =- c.fit === "fill"- ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh},` +- `pad=${W}:${H}:${rx}:${ry}:color=${padColor}`- : `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2,` +- `pad=${W}:${H}:${rx}+(${rw}-iw)/2:${ry}+(${rh}-ih)/2:color=${padColor}`;- } else {- frame =- c.fit === "fill"- ? // Cover the frame, then crop; the pan chooses the visible window.- `scale=${W}:${H}:force_original_aspect_ratio=increase,` +- `crop=${W}:${H}:(iw-ow)*${num(0.5 + Math.max(-1, Math.min(1, c.panX ?? 0)) / 2)}` +- `:(ih-oh)*${num(0.5 + Math.max(-1, Math.min(1, c.panY ?? 0)) / 2)}`- : `scale=${W}:${H}:force_original_aspect_ratio=decrease,` +- `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=${padColor}`;- }- // setpts/speed rescales the clip's duration on the timeline (footage);- // a still just replays its looped input.- // The grade sits after the color conversion (so it acts on the same- // BT.709 values the preview shows) and before the terminal format.- let core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeToFfmpegFilter(c.grade)}format=${clipFmt}`;- // The look bakes in after grade + framing, before the edge effects, so- // animations move already-graded pixels (matching the preview order).- if (c.look) {- const lines = lookFilterLines(`lki${j}`, `lko${j}`, c.look, c.lookAmount, H, clipFmt, `c${j}`);- if (lines) {- filters.push(`${core}[lki${j}]`);- filters.push(...lines);- core = `[lko${j}]null`;- }- }- const fades =- (hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}` : "") +- (tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");- // A neighbor's backdrop animation freezes a frame of this segment —- // split the copies it needs off the pre-backdrop picture.- const nFz = (needFirstFreeze[j] ? 1 : 0) + (needLastFreeze[j] ? 1 : 0);- const segOut = nFz > 0 ? `vseg${j}` : `v${j}`;- pushEdgeFx(core, dur, headFx, tailFx, W, H, clipFmt, fades, segOut, `c${j}`);- if (nFz > 0) {- filters.push(- `[vseg${j}]split=${nFz + 1}[v${j}]` +- (needFirstFreeze[j] ? `[vff${j}]` : "") +- (needLastFreeze[j] ? `[vfl${j}]` : "")- );- }- } else {- // No video stream, or a hidden clip: the slot plays black.- filters.push(- `color=c=black:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=${clipFmt}[v${j}]`- );- }- if (!c.muted && !c.hidden && audioPresence.get(c.file)) {- const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";- const vol = (c.volume ?? 1) !== 1 ? `volume=${num(c.volume ?? 1)},` : "";- // The picture's fade edges carry the sound with them; zoom edges don't.- const afades =- (ahf > 0.01 ? `,afade=t=in:st=0:d=${num(ahf)}` : "") +- (atf > 0.01 ? `,afade=t=out:st=${num(Math.max(0, dur - atf))}:d=${num(atf)}` : "");- filters.push(- `[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` +- `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,${vol}` +- `apad=whole_dur=${num(dur)},atrim=0:${num(dur)}${afades}[a${j}]`- );- } else {- filters.push(- `anullsrc=r=44100:cl=stereo,atrim=0:${num(dur)},asetpts=PTS-STARTPTS[a${j}]`- );- }- });-- // Second pass: the backdrop animations. Each slices its edge window and- // runs the effect against the neighbor's held frame — frozen via tpad- // clone from the copies split off above, so a slide-in covers the previous- // clip's last frame and a slide-out reveals the next clip's first frame.- // Slides become cover/reveal (the backdrop stays put); pop alpha-blends- // over the frozen frame; fade — and any unknown stored style — crossfades.- const segLabel = spec.clips.map((_, j) => `v${j}`);- const backdropFx = (- a: { style: string; seconds: number },- side: "head" | "tail",- secs: number,- bg: string- ): EdgeFx => {- if (a.style === "pop") return { kind: "pop", secs, bg };- if (/^slide(left|right|up|down)$/.test(a.style)) {- const dir = a.style.slice(5);- return { kind: "xfade", secs, xfade: `${side === "head" ? "cover" : "reveal"}${dir}`, bg };- }- return { kind: "xfade", secs, xfade: "fade", bg };- };- spec.clips.forEach((c, j) => {- if (!headBd[j] && !tailBd[j]) return;- const dur = clipDur(c);- if (headBd[j]) {- const a = backdropAnim(effAnimIn(j))!;- const d = Math.min(a.seconds, dur);- const durPrev = clipDur(spec.clips[j - 1]);- // fps is re-stamped before tpad — cloning needs a live frame rate, and- // trim+setpts strip it (without this the freeze collapses to 1 frame).- filters.push(- `[vfl${j - 1}]trim=${num(Math.max(0, durPrev - 0.05))}:${num(durPrev)},setpts=PTS-STARTPTS,fps=${fps},` +- `tpad=stop_mode=clone:stop_duration=${num(d + 0.5)},trim=0:${num(d)},` +- `setpts=PTS-STARTPTS,fps=${fps}[fzh${j}]`- );- pushEdgeFx(- `[${segLabel[j]}]null`,- dur,- backdropFx(a, "head", d, `fzh${j}`),- null,- W,- H,- clipFmt,- "",- `vhb${j}`,- `hb${j}`- );- segLabel[j] = `vhb${j}`;- }- if (tailBd[j]) {- const a = backdropAnim(effAnimOut(j))!;- const d = Math.min(a.seconds, dur);- filters.push(- `[vff${j + 1}]trim=0:0.05,setpts=PTS-STARTPTS,fps=${fps},` +- `tpad=stop_mode=clone:stop_duration=${num(d + 0.5)},trim=0:${num(d)},` +- `setpts=PTS-STARTPTS,fps=${fps}[fzt${j}]`- );- pushEdgeFx(- `[${segLabel[j]}]null`,- dur,- null,- backdropFx(a, "tail", d, `fzt${j}`),- W,- H,- clipFmt,- "",- `vtb${j}`,- `tb${j}`- );- segLabel[j] = `vtb${j}`;- }- });-- // Join the segments. Adjacent clips with a transition cross-dissolve- // (xfade/acrossfade, overlapping by the transition length); the rest hard-cut- // (concat). Fold left so mixed sequences chain correctly.- let vAcc = segLabel[0];- let aAcc = "a0";- let acc = clipDur(spec.clips[0]); // running timeline length of the accumulator- for (let j = 1; j < spec.clips.length; j++) {- const prev = spec.clips[j - 1];- const durJ = clipDur(spec.clips[j]);- // The overlap can't exceed most of either clip, matching the editor clamp.- const d = Math.min(prev.transition ?? 0, acc * 0.9, durJ * 0.9);- const vOut = `vj${j}`;- const aOut = `aj${j}`;- if (d > 0.01) {- const offset = Math.max(0, acc - d);- // The style id resolves through the allowlist map; anything unknown- // (or an old spec without a style) renders as a plain fade.- const kind = TRANSITION_XFADE[prev.transitionStyle as TransitionStyle] ?? "fade";- filters.push(`[${vAcc}][${segLabel[j]}]xfade=transition=${kind}:duration=${num(d)}:offset=${num(offset)}[${vOut}]`);- filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${aOut}]`);- acc = acc + durJ - d;- } else {- filters.push(`[${vAcc}][${segLabel[j]}]concat=n=2:v=1:a=0[${vOut}]`);- filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${aOut}]`);- acc = acc + durJ;- }- vAcc = vOut;- aAcc = aOut;- }-- // Composite the video stack bottom→top: the overlay tracks draw over the- // track-0 base in track order. A full-frame layer covers; a regioned one- // shares the frame (split half) or floats (PiP). Overlay audio (unless- // muted) mixes in below.- const overlaySoundLabels: string[] = [];- let ovk = 0;- // Overlay one track clip onto `onto`, returning the new label; also queues- // its audio.- const addOverlay = (oc: (typeof overlayVideos)[number], onto: string): string => {- if (!oc.image && !videoPresence.get(oc.file)) return onto;- const idx = oc.image ? imageOverlayInput.get(oc)! : inputIndex.get(oc.file)!;- const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;- const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);- const end = Math.min(oc.start + olen, spec.duration);- const region = regionPx(oc.frame, W, H);- const cover = oc.fit === "fill" || (oc.fit == null && !region);- // Transition ramps, clamped so head+tail never overrun the segment. On an- // upper track the fades are alpha fades — the clip dissolves against- // whatever is beneath it (a cross transition ships as the incoming clip's- // head fade, blending it in over the still-opaque outgoing clip).- const hz = Math.max(0, Math.min(oc.headZoom ?? 0, olen));- const tz = Math.max(0, Math.min(oc.tailZoom ?? 0, olen - hz));- const hf = Math.max(0, Math.min(oc.headFade ?? 0, olen));- const tf = Math.max(0, Math.min(oc.tailFade ?? 0, olen - hf));- const ramped = hz > 0.01 || tz > 0.01;- const boxW = region ? region.rw : W;- const boxH = region ? region.rh : H;- let framing: string;- let pos: string;- if (!region) {- framing = cover- ? `scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H}`- : `scale=${W}:${H}:force_original_aspect_ratio=decrease:force_divisible_by=2`;- pos = cover ? "0:0" : `x=(${W}-w)/2:y=(${H}-h)/2`;- } else {- const { rx, ry, rw, rh } = region;- framing = cover- ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh}`- : `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2`;- pos = cover ? `${rx}:${ry}` : `x=${rx}+(${rw}-w)/2:y=${ry}+(${rh}-h)/2`;- }- // zoompan needs a constant frame size: pad a letterboxed segment out to- // its exact box with transparent margins (the tracks beneath keep showing- // through) and anchor the overlay at the box origin.- if (ramped && !cover) {- framing += `,format=yuva420p,pad=${boxW}:${boxH}:(ow-iw)/2:(oh-ih)/2:[email protected]`;- pos = region ? `${region.rx}:${region.ry}` : "0:0";- }- const fmt = hf > 0.01 || tf > 0.01 || (ramped && !cover) ? "yuva420p" : "yuv420p";- const fades =- (hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}:alpha=1` : "") +- (tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, olen - tf))}:d=${num(tf)}:alpha=1` : "");- const k = ovk++;- const seg = `ovv${k}`;- // A still replays its looped input; footage trims its source span and- // re-times by speed. tpad then delays the clip to its timeline start.- const timebase = oc.image- ? `[${idx}:v]setpts=PTS-STARTPTS`- : `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)}`;- let core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${fmt}`;- // Looks bake into footage overlays only: an image may carry alpha, and a- // padded letterbox has transparent margins — the look chain's internal- // filters would flatten either onto black over the tracks beneath. The- // alpha fades stay safe: they apply after the look.- if (oc.look && !oc.image && !(ramped && !cover)) {- const lines = lookFilterLines(`olki${k}`, `olko${k}`, oc.look, oc.lookAmount, H, fmt, `o${k}`);- if (lines) {- filters.push(`${core}[olki${k}]`);- filters.push(...lines);- core = `[olko${k}]null`;- }- }- const pre = `ovp${k}`;- pushEdgeFx(- core,- olen,- hz > 0.01 ? { kind: "zoom", secs: hz } : null,- tz > 0.01 ? { kind: "zoom", secs: tz } : null,- boxW,- boxH,- fmt,- fades,- pre,- `o${k}`- );- // The zoom slices' concat drops the stream's frame-rate metadata, and- // tpad converts start_duration to a frame count through it — without the- // fps re-stamp it pads zero frames and the overlay lands early.- filters.push(`[${pre}]fps=${fps},tpad=start_duration=${num(oc.start)}[${seg}]`);- const next = `vovv${k}`;- filters.push(- `[${onto}][${seg}]overlay=${pos}:enable='between(t,${num(oc.start)},${num(end)})':eof_action=pass[${next}]`- );- if (!oc.muted && audioPresence.get(oc.file)) {- const tempo = ospeed !== 1 ? `${atempoChain(ospeed)},` : "";- const vol = (oc.volume ?? 1) !== 1 ? `volume=${num(oc.volume ?? 1)},` : "";- // The picture's fade edges carry the sound with them; zoom edges don't.- const afades =- (hf > 0.01 ? `afade=t=in:st=0:d=${num(hf)},` : "") +- (tf > 0.01 ? `afade=t=out:st=${num(Math.max(0, olen - tf))}:d=${num(tf)},` : "");- const delayMs = Math.max(0, Math.round(oc.start * 1000));- const lab = `ovs${k}`;- filters.push(- `[${idx}:a]atrim=${num(oc.in)}:${num(oc.out)},asetpts=PTS-STARTPTS,${tempo}${vol}${afades}` +- `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,adelay=${delayMs}:all=1[${lab}]`- );- overlaySoundLabels.push(lab);- }- return next;- };-- let vLabel = vAcc;- for (const oc of overlayVideos) vLabel = addOverlay(oc, vLabel);-- // Burn in text overlays, each windowed to its timeline range. Half-open so- // back-to-back overlays sharing a boundary never composite on the same frame.- spec.overlays.forEach((o, k) => {- const idx = inputIndex.get(o.file)!;- const next = `vov${k}`;- filters.push(- `[${vLabel}][${idx}:v]overlay=0:0:enable='gte(t,${num(o.start)})*lt(t,${num(o.end)})'[${next}]`- );- vLabel = next;- });-- // Subtitle stills ride one concat-demuxer slideshow per track (transparent- // filler in the gaps), so a karaoke cut with hundreds of word windows still- // costs one ffmpeg input per language instead of one per still.- captionInputs.forEach((idx, k) => {- filters.push(`[${idx}:v]fps=${fps},format=yuva420p,setsar=1[caps${k}]`);- filters.push(`[${vLabel}][caps${k}]overlay=0:0:eof_action=pass[vcaps${k}]`);- vLabel = `vcaps${k}`;- });-- // Voiceover ducking: while a ducking clip plays, every other sound drops to- // its gain. The windows are timeline seconds, so the volume automation must- // run on timeline-aligned streams — the joined clip audio, and each other- // sound *after* its adelay.- const duckWindows = spec.audio- .filter((a) => a.duck !== undefined && a.duck < 1)- .map((a) => {- const speed = a.speed && a.speed > 0 ? a.speed : 1;- const len = Math.max(0.1, (a.out - a.in) / speed);- return { from: a.start, to: a.start + len, gain: Math.max(0, a.duck!) };- });- // Flatten to non-overlapping segments at the lowest covering gain: chained- // volume filters multiply, so overlapping voiceovers would otherwise duck- // deeper than the preview (which takes the minimum).- const duckSegments = (() => {- const cuts = [...new Set(duckWindows.flatMap((w) => [w.from, w.to]))].sort((a, b) => a - b);- const segs: { from: number; to: number; gain: number }[] = [];- for (let i = 0; i + 1 < cuts.length; i++) {- const [from, to] = [cuts[i], cuts[i + 1]];- const covering = duckWindows.filter((w) => w.from < to && w.to > from);- if (covering.length === 0) continue;- const gain = Math.min(...covering.map((w) => w.gain));- const prev = segs[segs.length - 1];- if (prev && prev.to === from && prev.gain === gain) prev.to = to;- else segs.push({ from, to, gain });- }- return segs;- })();- let duckSeq = 0;- const duckOthers = (label: string): string => {- if (duckSegments.length === 0) return label;- // Half-open windows: between() includes both ends, so adjacent segments- // would both fire (and multiply) on the exact boundary frame.- const chain = duckSegments- .map((w) => `volume=enable='gte(t,${num(w.from)})*lt(t,${num(w.to)})':volume=${num(w.gain)}`)- .join(",");- const out = `dk${duckSeq++}`;- filters.push(`[${label}]${chain}[${out}]`);- return out;- };-- // Soundtrack clips: trim, gain, shift into place, mix with clip audio.- const soundLabels: string[] = [];- spec.audio.forEach((a, k) => {- const idx = inputIndex.get(a.file)!;- if (!audioPresence.get(a.file)) return;- const speed = a.speed && a.speed > 0 ? a.speed : 1;- const delayMs = Math.max(0, Math.round(a.start * 1000));- // Timeline length after any speed change; fade offsets are in these- // (post-tempo) seconds, so atempo runs before the fades.- const len = Math.max(0.1, (a.out - a.in) / speed);- const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";- const fades: string[] = [];- if (a.fadeIn && a.fadeIn > 0.01) fades.push(`afade=t=in:st=0:d=${num(a.fadeIn)}`);- if (a.fadeOut && a.fadeOut > 0.01)- fades.push(`afade=t=out:st=${num(Math.max(0, len - a.fadeOut))}:d=${num(a.fadeOut)}`);- filters.push(- `[${idx}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,${tempo}` +- `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` +- `volume=${num(a.volume)},` +- (fades.length ? fades.join(",") + "," : "") +- `adelay=${delayMs}:all=1[snd${k}]`- );- // Music and other non-voiceover sound ducks under the voiceovers.- soundLabels.push(a.duck !== undefined && a.duck < 1 ? `snd${k}` : duckOthers(`snd${k}`));- });-- // The joined clip audio and overlay-video audio duck too.- let aLabel = duckOthers(aAcc);- const extraSound = [...soundLabels, ...overlaySoundLabels.map(duckOthers)];- if (extraSound.length > 0) {- const mixIn = [aLabel, ...extraSound].map((l) => `[${l}]`).join("");- filters.push(- `${mixIn}amix=inputs=${extraSound.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`- );- aLabel = "amix";- }-- // Whole-video fades on the final composite and mix, so titles, captions,- // overlays, and soundtrack all fade together.- const fadeIn = projectFadeSeconds(spec.fadeIn, spec.duration);- const fadeOut = projectFadeSeconds(spec.fadeOut, spec.duration);- if (fadeIn > 0.01 || fadeOut > 0.01) {- const win = (f: string) =>- [- ...(fadeIn > 0.01 ? [`${f}=t=in:st=0:d=${num(fadeIn)}`] : []),- ...(fadeOut > 0.01- ? [`${f}=t=out:st=${num(Math.max(0, spec.duration - fadeOut))}:d=${num(fadeOut)}`]- : []),- ].join(",");- filters.push(`[${vLabel}]${win("fade")}[vfinal]`);- vLabel = "vfinal";- filters.push(`[${aLabel}]${win("afade")}[afinal]`);- aLabel = "afinal";- }-- const enc = await h264Encoder();- const videoCodecArgs =- enc === "libx264"- ? ["-c:v", "libx264", "-preset", spec.preset, "-crf", String(spec.crf)]- : ["-c:v", "h264_videotoolbox", "-q:v", String(vtQuality(spec.crf)), "-allow_sw", "1"];-- // Encode into the tmp dir, then re-emit the container to strip a stray output- // rotation flag (see the strip pass below). Keeping the encode intermediate- // lets the second pass own faststart.- const encodePath = path.join(job.tmpDir, "encode.mp4");- await runFfmpeg(- job,- [- "-y",- ...inputs,- "-filter_complex", filters.join(";"),- "-map", `[${vLabel}]`,- "-map", `[${aLabel}]`,- ...videoCodecArgs,- "-profile:v", "high",- "-pix_fmt", "yuv420p",- "-color_range", "tv",- "-colorspace", "bt709",- "-color_primaries", "bt709",- "-color_trc", "bt709",- "-c:a", "aac",- "-b:a", "192k",- "-t", num(spec.duration),- encodePath,- ],- (t) => (job.progress = Math.min(0.99, t / Math.max(0.1, spec.duration)))- );-- // ffmpeg's autorotation already baked each source's display matrix into the- // pixels, so the encode's frames are upright. But for a complex filtergraph it- // ALSO copies the first input's display-matrix side data onto the output- // stream — so a phone (portrait) source lands as a correct 1080×1920 file- // tagged with a stray 90° rotation, and players re-rotate it into a sideways- // "desktop" frame. `-display_rotation 0` overrides that matrix to identity; a- // stream copy re-emits the (already correct) pixels and audio unchanged and- // writes the faststart-optimized final file.- await runFfmpeg(job, [- "-y",- "-display_rotation", "0",- "-i", encodePath,- "-map", "0",- "-c", "copy",- "-movflags", "+faststart",- job.outPath,- ]);-- job.progress = 1;- job.status = "done";-}diff --git a/site/src/cut/server/urlDownload.ts b/site/src/cut/server/urlDownload.tsnew file mode 100644index 00000000..b8aa857e--- /dev/null+++ b/site/src/cut/server/urlDownload.ts@@ -0,0 +1,198 @@+import { spawn } from "node:child_process";+import { readdir, stat, writeFile } from "node:fs/promises";+import path from "node:path";+import type { LibrarySource } from "./library";++// Download a media URL (TikTok, YouTube, Instagram, …) with yt-dlp, resolved+// from PATH. yt-dlp only extracts video/audio, so a photo tweet falls back to+// fetching the image through X's embed endpoint. Shared by the local engine's+// import routes (urlImport.ts) and the cloud render worker's import_url jobs.++const MEDIA_EXT = /\.(mp4|mov|m4v|webm|mkv|mp3|m4a|aac|wav|ogg|flac)$/i;++interface YtMeta {+ title?: string;+ description?: string;+ uploader?: string;+ upload_date?: string;+ webpage_url?: string;+}++/** What a finished download hands its consumer: the media files (inside a+ * temp dir the wrapper deletes afterwards — one for yt-dlp's merged output,+ * one per photo for a photo tweet) plus what the extractor knew about them.+ * `text` is the source's own words — a tweet's body, or a video's title and+ * description — shown in the chat beside the media it came with. */+export interface Downloaded {+ files: { file: string; title: string }[];+ source: LibrarySource;+ text?: string;+}++// A video's own words for the chat: its title and description joined, capped so+// a long YouTube description (link dumps, chapter lists) can't flood the chat.+// TikTok/Instagram often repeat the caption as both fields, so drop a+// description that just restates the title.+const MAX_SOURCE_TEXT = 2000;+function sourceTextFromMeta(meta: YtMeta): string | undefined {+ const title = (meta.title || "").trim();+ const desc = (meta.description || "").trim();+ const body =+ desc && desc !== title && !desc.startsWith(title)+ ? title+ ? `${title}\n\n${desc}`+ : desc+ : title || desc;+ const text = body.trim();+ if (!text) return undefined;+ return text.length > MAX_SOURCE_TEXT ? `${text.slice(0, MAX_SOURCE_TEXT).trimEnd()}…` : text;+}++/** yt-dlp handles anything with a video/audio stream. A direct image link+ * skips it (yt-dlp rejects plain images), and a tweet it can't pull anything+ * from may still carry photos, so those fall through to the photo fetch; its+ * failure rethrows the yt-dlp error, which names the real cause. */+export async function download(url: string, tmp: string): Promise<Downloaded> {+ if (IMAGE_URL_RE.test(url)) return downloadDirectImage(url, tmp);+ try {+ return await downloadMedia(url, tmp);+ } catch (e) {+ const tweetId = TWEET_RE.exec(url)?.[1];+ if (!tweetId) throw e;+ try {+ return await downloadTweetPhotos(tweetId, url, tmp);+ } catch {+ throw e;+ }+ }+}++async function downloadMedia(url: string, tmp: string): Promise<Downloaded> {+ const meta = await runYtDlp(url, tmp);+ // Pick the largest media file left behind (the merged output).+ const names = (await readdir(tmp)).filter((f) => MEDIA_EXT.test(f));+ if (names.length === 0) throw new Error("Nothing downloadable was found at that URL.");+ const sized = await Promise.all(+ names.map(async (n) => ({ n, size: (await stat(path.join(tmp, n))).size }))+ );+ const file = sized.sort((a, b) => b.size - a.size)[0].n;+ return {+ files: [{ file: path.join(tmp, file), title: (meta.title || "Imported clip").slice(0, 120) }],+ source: {+ url: meta.webpage_url || url,+ title: meta.title,+ uploader: meta.uploader,+ uploadDate: meta.upload_date,+ },+ text: sourceTextFromMeta(meta),+ };+}++const IMAGE_URL_RE = /\.(png|jpe?g|webp|gif|avif|bmp)(?:$|\?)/i;++async function downloadDirectImage(url: string, dir: string): Promise<Downloaded> {+ const res = await fetch(url);+ if (!res.ok) throw new Error("Could not download that image.");+ const name = path.basename(new URL(url).pathname) || "image.jpg";+ const file = path.join(dir, name);+ await writeFile(file, Buffer.from(await res.arrayBuffer()));+ return { files: [{ file, title: name.slice(0, 120) }], source: { url } };+}++const TWEET_RE = /^https?:\/\/(?:www\.)?(?:x|twitter)\.com\/[^/]+\/status\/(\d+)/i;++/** Fetch all of a tweet's photos through X's embed endpoint, plus the post+ * text. The endpoint is auth-free but requires the token its embed script+ * derives from the id — same float math here, precision loss included. */+async function downloadTweetPhotos(id: string, url: string, dir: string): Promise<Downloaded> {+ const token = ((Number(id) / 1e15) * Math.PI).toString(36).replace(/(0+|\.)/g, "");+ const res = await fetch(`https://cdn.syndication.twimg.com/tweet-result?id=${id}&token=${token}`);+ if (!res.ok) throw new Error("Could not read the tweet.");+ const tweet = (await res.json()) as {+ text?: string;+ user?: { name?: string; screen_name?: string };+ photos?: { url?: string }[];+ };+ const photoUrls = (tweet.photos ?? []).map((p) => p.url).filter((u): u is string => !!u);+ if (photoUrls.length === 0) throw new Error("No photo was found in this tweet.");+ const handle = tweet.user?.screen_name;+ // The endpoint HTML-escapes the post text; it becomes titles and chat text.+ const text = (tweet.text || "")+ .replace(/&(amp|lt|gt|quot|#39);/g, (_, e) =>+ ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[e as string] ?? ""+ )+ .replace(/\s+/g, " ")+ .trim();+ const baseTitle = (text || `Photo from ${handle ? `@${handle}` : "X"}`).slice(0, 120);+ const files: Downloaded["files"] = [];+ for (const [i, photoUrl] of photoUrls.entries()) {+ // pbs.twimg.com serves the original resolution behind name=orig.+ let img = await fetch(`${photoUrl}${photoUrl.includes("?") ? "&" : "?"}name=orig`);+ if (!img.ok) img = await fetch(photoUrl);+ if (!img.ok) throw new Error("Could not download the tweet's photos.");+ const ext = (+ /\.(png|jpe?g|webp|gif)(?:$|\?)/i.exec(photoUrl)?.[1] ||+ (img.headers.get("content-type")?.includes("png") ? "png" : "jpg")+ ).toLowerCase();+ const file = path.join(dir, `${id}-${i + 1}.${ext}`);+ await writeFile(file, Buffer.from(await img.arrayBuffer()));+ files.push({+ file,+ title: photoUrls.length > 1 ? `${baseTitle} (${i + 1}/${photoUrls.length})` : baseTitle,+ });+ }+ return {+ files,+ source: {+ url,+ title: text || undefined,+ uploader: handle ? `@${handle}` : tweet.user?.name,+ },+ text: text || undefined,+ };+}++function runYtDlp(url: string, dir: string): Promise<YtMeta> {+ return new Promise((resolve, reject) => {+ const p = spawn("yt-dlp", [+ "--no-playlist",+ "--no-progress",+ "-f", "mp4/bestvideo*+bestaudio/best",+ "--merge-output-format", "mp4",+ "-o", path.join(dir, "%(id)s.%(ext)s"),+ "--print-json",+ url,+ ]);+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ reject(new Error("Download timed out."));+ }, 300_000);+ timer.unref();+ let out = "";+ let err = "";+ p.stdout.on("data", (d) => (out += d.toString()));+ p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-2000)));+ p.on("error", (e) => {+ clearTimeout(timer);+ reject(+ e.message.includes("ENOENT")+ ? new Error("yt-dlp is not available in this build.")+ : e+ );+ });+ p.on("close", (code) => {+ clearTimeout(timer);+ if (code !== 0) {+ reject(new Error(err.split("\n").filter(Boolean).slice(-1)[0] || "Download failed."));+ return;+ }+ // --print-json emits the info dict as JSON; take the last JSON line.+ const line = out.trim().split("\n").reverse().find((l) => l.trimStart().startsWith("{"));+ try {+ resolve(line ? (JSON.parse(line) as YtMeta) : {});+ } catch {+ resolve({});+ }+ });+ });+}diff --git a/site/src/cut/server/urlImport.ts b/site/src/cut/server/urlImport.tsindex 5de78d79..d1400da7 100644--- a/site/src/cut/server/urlImport.ts+++ b/site/src/cut/server/urlImport.ts@@ -1,61 +1,21 @@-import { spawn } from "node:child_process";-import { copyFile, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";+import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";import os from "node:os";import path from "node:path";import { addDownloaded, type LibraryAsset, type LibrarySource } from "./library";import { assertLocalRuntime } from "./local-only";import { mediaDir, mediaPath as projectMediaPath, readProject } from "./projects";+import { download, type Downloaded } from "./urlDownload";import { uniqueName } from "./util";-// Download a media URL (TikTok, YouTube, Instagram, …) with the bundled-// yt-dlp, resolved from the widened PATH (tool-path.ts) exactly like ffmpeg.-// yt-dlp only extracts video/audio, so a photo tweet falls back to fetching-// the image through X's embed endpoint.--const MEDIA_EXT = /\.(mp4|mov|m4v|webm|mkv|mp3|m4a|aac|wav|ogg|flac)$/i;+// Import a media URL (TikTok, YouTube, Instagram, …) into the library or a+// project. The fetch itself lives in urlDownload.ts (the bundled yt-dlp,+// resolved from the widened PATH — tool-path.ts — exactly like ffmpeg); this+// module owns the local landing spots and the concurrency guard.// A small ceiling so a burst of pastes can't spawn unbounded downloads.const MAX_ACTIVE = 2;let active = 0;-interface YtMeta {- title?: string;- description?: string;- uploader?: string;- upload_date?: string;- webpage_url?: string;-}--/** What a finished download hands its consumer: the media files (inside a- * temp dir the wrapper deletes afterwards — one for yt-dlp's merged output,- * one per photo for a photo tweet) plus what the extractor knew about them.- * `text` is the source's own words — a tweet's body, or a video's title and- * description — shown in the chat beside the media it came with. */-interface Downloaded {- files: { file: string; title: string }[];- source: LibrarySource;- text?: string;-}--// A video's own words for the chat: its title and description joined, capped so-// a long YouTube description (link dumps, chapter lists) can't flood the chat.-// TikTok/Instagram often repeat the caption as both fields, so drop a-// description that just restates the title.-const MAX_SOURCE_TEXT = 2000;-function sourceTextFromMeta(meta: YtMeta): string | undefined {- const title = (meta.title || "").trim();- const desc = (meta.description || "").trim();- const body =- desc && desc !== title && !desc.startsWith(title)- ? title- ? `${title}\n\n${desc}`- : desc- : title || desc;- const text = body.trim();- if (!text) return undefined;- return text.length > MAX_SOURCE_TEXT ? `${text.slice(0, MAX_SOURCE_TEXT).trimEnd()}…` : text;-}-/** Run one guarded download and hand the files to `consume` before the temp* dir is deleted. The active slot spans the whole operation; mkdtemp runs* inside the try so a failure there still releases the slot (else a rejection@@ -109,152 +69,3 @@ export async function importUrlToProject(return { files, source: dl.source, text: dl.text };});}--/** yt-dlp handles anything with a video/audio stream. A direct image link- * skips it (yt-dlp rejects plain images), and a tweet it can't pull anything- * from may still carry photos, so those fall through to the photo fetch; its- * failure rethrows the yt-dlp error, which names the real cause. */-async function download(url: string, tmp: string): Promise<Downloaded> {- if (IMAGE_URL_RE.test(url)) return downloadDirectImage(url, tmp);- try {- return await downloadMedia(url, tmp);- } catch (e) {- const tweetId = TWEET_RE.exec(url)?.[1];- if (!tweetId) throw e;- try {- return await downloadTweetPhotos(tweetId, url, tmp);- } catch {- throw e;- }- }-}--async function downloadMedia(url: string, tmp: string): Promise<Downloaded> {- const meta = await runYtDlp(url, tmp);- // Pick the largest media file left behind (the merged output).- const names = (await readdir(tmp)).filter((f) => MEDIA_EXT.test(f));- if (names.length === 0) throw new Error("Nothing downloadable was found at that URL.");- const sized = await Promise.all(- names.map(async (n) => ({ n, size: (await stat(path.join(tmp, n))).size }))- );- const file = sized.sort((a, b) => b.size - a.size)[0].n;- return {- files: [{ file: path.join(tmp, file), title: (meta.title || "Imported clip").slice(0, 120) }],- source: {- url: meta.webpage_url || url,- title: meta.title,- uploader: meta.uploader,- uploadDate: meta.upload_date,- },- text: sourceTextFromMeta(meta),- };-}--const IMAGE_URL_RE = /\.(png|jpe?g|webp|gif|avif|bmp)(?:$|\?)/i;--async function downloadDirectImage(url: string, dir: string): Promise<Downloaded> {- const res = await fetch(url);- if (!res.ok) throw new Error("Could not download that image.");- const name = path.basename(new URL(url).pathname) || "image.jpg";- const file = path.join(dir, name);- await writeFile(file, Buffer.from(await res.arrayBuffer()));- return { files: [{ file, title: name.slice(0, 120) }], source: { url } };-}--const TWEET_RE = /^https?:\/\/(?:www\.)?(?:x|twitter)\.com\/[^/]+\/status\/(\d+)/i;--/** Fetch all of a tweet's photos through X's embed endpoint, plus the post- * text. The endpoint is auth-free but requires the token its embed script- * derives from the id — same float math here, precision loss included. */-async function downloadTweetPhotos(id: string, url: string, dir: string): Promise<Downloaded> {- const token = ((Number(id) / 1e15) * Math.PI).toString(36).replace(/(0+|\.)/g, "");- const res = await fetch(`https://cdn.syndication.twimg.com/tweet-result?id=${id}&token=${token}`);- if (!res.ok) throw new Error("Could not read the tweet.");- const tweet = (await res.json()) as {- text?: string;- user?: { name?: string; screen_name?: string };- photos?: { url?: string }[];- };- const photoUrls = (tweet.photos ?? []).map((p) => p.url).filter((u): u is string => !!u);- if (photoUrls.length === 0) throw new Error("No photo was found in this tweet.");- const handle = tweet.user?.screen_name;- // The endpoint HTML-escapes the post text; it becomes titles and chat text.- const text = (tweet.text || "")- .replace(/&(amp|lt|gt|quot|#39);/g, (_, e) =>- ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[e as string] ?? ""- )- .replace(/\s+/g, " ")- .trim();- const baseTitle = (text || `Photo from ${handle ? `@${handle}` : "X"}`).slice(0, 120);- const files: Downloaded["files"] = [];- for (const [i, photoUrl] of photoUrls.entries()) {- // pbs.twimg.com serves the original resolution behind name=orig.- let img = await fetch(`${photoUrl}${photoUrl.includes("?") ? "&" : "?"}name=orig`);- if (!img.ok) img = await fetch(photoUrl);- if (!img.ok) throw new Error("Could not download the tweet's photos.");- const ext = (- /\.(png|jpe?g|webp|gif)(?:$|\?)/i.exec(photoUrl)?.[1] ||- (img.headers.get("content-type")?.includes("png") ? "png" : "jpg")- ).toLowerCase();- const file = path.join(dir, `${id}-${i + 1}.${ext}`);- await writeFile(file, Buffer.from(await img.arrayBuffer()));- files.push({- file,- title: photoUrls.length > 1 ? `${baseTitle} (${i + 1}/${photoUrls.length})` : baseTitle,- });- }- return {- files,- source: {- url,- title: text || undefined,- uploader: handle ? `@${handle}` : tweet.user?.name,- },- text: text || undefined,- };-}--function runYtDlp(url: string, dir: string): Promise<YtMeta> {- return new Promise((resolve, reject) => {- const p = spawn("yt-dlp", [- "--no-playlist",- "--no-progress",- "-f", "mp4/bestvideo*+bestaudio/best",- "--merge-output-format", "mp4",- "-o", path.join(dir, "%(id)s.%(ext)s"),- "--print-json",- url,- ]);- const timer = setTimeout(() => {- p.kill("SIGKILL");- reject(new Error("Download timed out."));- }, 300_000);- timer.unref();- let out = "";- let err = "";- p.stdout.on("data", (d) => (out += d.toString()));- p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-2000)));- p.on("error", (e) => {- clearTimeout(timer);- reject(- e.message.includes("ENOENT")- ? new Error("yt-dlp is not available in this build.")- : e- );- });- p.on("close", (code) => {- clearTimeout(timer);- if (code !== 0) {- reject(new Error(err.split("\n").filter(Boolean).slice(-1)[0] || "Download failed."));- return;- }- // --print-json emits the info dict as JSON; take the last JSON line.- const line = out.trim().split("\n").reverse().find((l) => l.trimStart().startsWith("{"));- try {- resolve(line ? (JSON.parse(line) as YtMeta) : {});- } catch {- resolve({});- }- });- });-}