Open source CapCut alternative.
TypeScript
feat(site): masks, person matte, and clip keyframes in the export paths [rebuild]
David Le7a316eb5d102
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 9dc4045e..1bdc6cde 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -6,9 +6,9 @@ import { renderProjectToMp4 } from "./exportRender";import { putSigned } from "./media";import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";import { captionStyle, cueOverlay, cueWordWindows, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";-import { isOverlayAnimated, normalizeGrade } from "@donkeycut/effects-kit";+import { isMaskAnimated, isOverlayAnimated, normalizeGrade, paintMaskLuma } from "@donkeycut/effects-kit";import { renderElementFrames, renderElementPng } from "./textRender";-import { frameOf, isStickerOverlay, isTextOverlay, laneOf, overlayAnimStyle } from "./types";+import { clipPoseAt, frameOf, isStickerOverlay, isTextOverlay, laneOf, overlayAnimStyle, rectOf, regionPx, subjectMasked } from "./types";import type {Aspect,AudioClip,@@ -188,6 +188,81 @@ interface ExportPayload {pngs: { name: string; blob: Blob }[];}+/** A masked video clip's coverage in the spec: one grayscale still, a+ * sampled sequence when the mask is keyframed, or the shared person matte+ * (`subject`) with its knobs. */+interface SpecMask {+ file?: string;+ frames?: { file: string; duration: number }[];+ subject?: { invert?: boolean; feather?: number };+}++/** How often a keyframed clip mask samples — the person-matte cadence; the+ * server re-stamps the output fps over it. */+const MASK_SAMPLE_FPS = 15;++/** Paint a clip's mask coverage for its export segment: one luma PNG for a+ * resting mask, a 15fps sampled sequence for a keyframed one. Keyframed+ * opacity folds into the luma — a clip fading under its pose track exports+ * an opacity-scaled coverage (flat white when it has no shape mask), so the+ * graph never needs an animatable alpha filter. The pictures land in `pngs`+ * and the returned entry references them by name. */+async function renderClipMaskPictures(+ clip: VideoClip,+ box: { x: number; y: number; w: number; h: number },+ W: number,+ H: number,+ dur: number,+ tag: string,+ pngs: ExportPayload["pngs"]+): Promise<SpecMask | undefined> {+ const m = clip.mask && clip.mask.kind !== "subject" ? clip.mask : undefined;+ const opacityVaries = (clip.kf ?? []).some((k) => Math.abs(k.opacity - 1) > 1e-3);+ if (!m && !opacityVaries) return undefined;+ const rect = rectOf(clip);+ const anchor = { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 };+ const frame = { width: W, height: H, scale: Math.min(W, H) / 1080 };+ const canvas = document.createElement("canvas");+ canvas.width = box.w;+ canvas.height = box.h;+ const blobAt = (tLocal: number) => {+ const ctx = canvas.getContext("2d")!;+ if (m) {+ paintMaskLuma(canvas, m, tLocal, frame, anchor, box.x, box.y);+ } else {+ ctx.globalCompositeOperation = "source-over";+ ctx.fillStyle = "#ffffff";+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ }+ if (opacityVaries) {+ const v = Math.round(+ 255 * Math.max(0, Math.min(1, clipPoseAt(clip, tLocal).opacity))+ );+ ctx.globalCompositeOperation = "multiply";+ ctx.fillStyle = `rgb(${v},${v},${v})`;+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.globalCompositeOperation = "source-over";+ }+ return new Promise<Blob>((resolve, reject) =>+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not render the mask."))), "image/png")+ );+ };+ if (!(m && isMaskAnimated(m)) && !opacityVaries) {+ const name = `${tag}.png`;+ pngs.push({ name, blob: await blobAt(0) });+ return { file: name };+ }+ const step = 1 / MASK_SAMPLE_FPS;+ const n = Math.max(1, Math.round(dur * MASK_SAMPLE_FPS));+ const frames: { file: string; duration: number }[] = [];+ for (let i = 0; i < n; i++) {+ const name = `${tag}_f${i}.png`;+ pngs.push({ name, blob: await blobAt(i * step) });+ frames.push({ file: name, duration: i === n - 1 ? Math.max(step, dur - (n - 1) * step) : step });+ }+ return { frames };+}+/** Build the export spec + overlay PNGs from the cut. Media already lives in* the project folder — the spec references it by file name; only overlay PNGs* travel with the request. Shared by full exports and the low-res hover proxy. */@@ -215,6 +290,33 @@ async function buildExportPayload(throw new Error("Add a video to the timeline first.");}+ // The person matte renders first, so the loops below attach subject fields+ // only when the effect will actually composite (no person segmenter, or no+ // person → everything renders plain, matching the preview's degrade). The+ // spec field keeps its `behindMask` name so older engines keep rendering+ // behind-tagged text.+ let behindMask: { file: string; from: number } | undefined;+ const wantsSubject =+ doc.overlays.some((o) => subjectMasked(o) && !o.hidden) ||+ doc.clips.some((c) => c.mask?.kind === "subject" && !c.hidden);+ if (wantsSubject) {+ const mask = await import("./maskVideo")+ .then((m) => m.renderSubjectMask(doc, duration))+ .catch(() => null);+ if (mask) {+ pngs.push({ name: "behind_mask.mp4", blob: mask.blob });+ behindMask = { file: "behind_mask.mp4", from: mask.from };+ }+ }+ /** The subject entry a masked item ships, or undefined without a matte. */+ const subjectOf = (m: { invert?: boolean; feather?: number } | undefined) =>+ behindMask && m+ ? {+ ...(m.invert ? { invert: true } : {}),+ ...(m.feather ? { feather: m.feather } : {}),+ }+ : undefined;+const clipEntries = spans.map((sp) => ({file: sp.asset.fileName,in: sp.clip.in,@@ -240,7 +342,30 @@ async function buildExportPayload(// trimming a source span.image: sp.asset.type === "image",grade: normalizeGrade(sp.clip.grade),+ mask: undefined as SpecMask | undefined,+ kf: sp.clip.kf,}));+ // Track-0 segments render at the full output frame (regioned clips pad out+ // to it), so their masks paint full-frame. A subject mask rides the shared+ // matte; painted pictures still travel beside it when the pose track keys+ // opacity, since opacity ships as coverage luma.+ for (let i = 0; i < spans.length; i++) {+ const c = spans[i].clip;+ const dur = Math.max(0.1, (c.out - c.in) / clipSpeed(c));+ const pictures = await renderClipMaskPictures(+ c,+ { x: 0, y: 0, w: settings.width, h: settings.height },+ settings.width,+ settings.height,+ dur,+ `mask_c${i}`,+ pngs+ );+ const subject = c.mask?.kind === "subject" ? subjectOf(c.mask) : undefined;+ if (pictures || subject) {+ clipEntries[i].mask = { ...(pictures ?? {}), ...(subject ? { subject } : {}) };+ }+ }// The server's video graph is a sequential fold, so gaps between the// free-placed clips ship as explicit spacer segments: no file, hidden and@@ -278,6 +403,9 @@ async function buildExportPayload(// ramps). Animations map fade/zoom natively; the styles that need frame// motion degrade to a fade up here.const overlayTracks = [...new Set(overlayLayers(doc.clips).map((c) => c.track))];+ // Entry → its source clip, so the mask loop below can paint per clip after+ // the entries assemble.+ const overlayClipOf = new Map<object, VideoClip>();const overlayVideos = overlayTracks.flatMap((track) => {const trackSpans = getClipSpans(doc.clips, doc.assets, track);const ramps = trackSpans.map(() => ({ headFade: 0, tailFade: 0, headZoom: 0, tailZoom: 0 }));@@ -308,26 +436,59 @@ async function buildExportPayload(return trackSpans.map((sp, i) => ({ c: sp.clip, ramp: ramps[i] })).filter(({ c }) => !c.hidden && c.start < duration)- .map(({ c, ramp }) => ({- file: assetById.get(c.assetId)!.fileName,- in: c.in,- out: c.out,- start: c.start,- track: c.track,- frame: c.frame,- // Pass `fit` through unset so the server's "default full-frame overlay- // covers what's below" branch fires — normalizing to "fit" defeated it.- fit: c.fit,- muted: c.muted,- volume: c.volume,- speed: c.speed,- image: assetById.get(c.assetId)!.type === "image",- grade: normalizeGrade(c.grade),- look: c.look,- lookAmount: c.lookAmount,- ...ramp,- }));+ .map(({ c, ramp }) => {+ const entry = {+ file: assetById.get(c.assetId)!.fileName,+ in: c.in,+ out: c.out,+ start: c.start,+ track: c.track,+ frame: c.frame,+ // Pass `fit` through unset so the server's "default full-frame overlay+ // covers what's below" branch fires — normalizing to "fit" defeated it.+ fit: c.fit,+ muted: c.muted,+ volume: c.volume,+ speed: c.speed,+ image: assetById.get(c.assetId)!.type === "image",+ grade: normalizeGrade(c.grade),+ look: c.look,+ lookAmount: c.lookAmount,+ mask: undefined as SpecMask | undefined,+ kf: c.kf,+ ...ramp,+ };+ overlayClipOf.set(entry, c);+ return entry;+ });});+ // Upper-track segments render at their region box (letterboxed ones pad out+ // to it when masked), so their masks paint box-sized. Subject masks ride+ // the shared matte, with opacity-key luma pictures beside them.+ for (let i = 0; i < overlayVideos.length; i++) {+ const entry = overlayVideos[i];+ const c = overlayClipOf.get(entry);+ if (!c) continue;+ const region = regionPx(c.frame, settings.width, settings.height);+ const box = region+ ? { x: region.rx, y: region.ry, w: region.rw, h: region.rh }+ : { x: 0, y: 0, w: settings.width, h: settings.height };+ const ospeed = c.speed && c.speed > 0 ? c.speed : 1;+ const olen = Math.max(0.1, (c.out - c.in) / ospeed);+ const pictures = await renderClipMaskPictures(+ c,+ box,+ settings.width,+ settings.height,+ olen,+ `mask_ov${i}`,+ pngs+ );+ const subject = c.mask?.kind === "subject" ? subjectOf(c.mask) : undefined;+ if (pictures || subject) {+ entry.mask = { ...(pictures ?? {}), ...(subject ? { subject } : {}) };+ }+ }const audio = doc.audioClips.filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId))@@ -343,20 +504,6 @@ async function buildExportPayload(duck: a.duck,}));- // Text-behind-speaker: the mask video renders first so the loop below tags- // behind elements only when the effect will actually composite (no person- // segmenter, or no person → the text stays a normal front title).- let behindMask: { file: string; from: number } | undefined;- if (doc.overlays.some((o) => isTextOverlay(o) && !!o.behindSubject && !o.hidden)) {- const mask = await import("./maskVideo")- .then((m) => m.renderBehindMask(doc, duration))- .catch(() => null);- if (mask) {- pngs.push({ name: "behind_mask.mp4", blob: mask.blob });- behindMask = { file: "behind_mask.mp4", from: mask.from };- }- }-const overlays: {file?: string;start: number;@@ -365,7 +512,9 @@ async function buildExportPayload(y?: number;blank?: string;frames?: { file: string; duration: number }[];- behind?: boolean;+ /** The element trims by the shared person matte (invert = behind the+ * speaker). */+ subject?: { invert?: boolean; feather?: number };/** Its row: lane 0 is the top of the stack, and the effects interleave* with these by lane. */lane?: number;@@ -390,9 +539,14 @@ async function buildExportPayload(if (o.kind === "effect") continue;// A blank title has no pixels to burn; shapes and stickers always render.if (isTextOverlay(o) && !o.text.trim()) continue;+ // A subject-masked element's stream must run its whole window so the+ // server can multiply the matte in per frame — the frames mechanism+ // covers that (a static element costs one frame plus the blank).+ const subject = subjectMasked(o) && o.mask ? subjectOf(o.mask) : undefined;+ const subjectFields = subject ? { subject } : {};// A Lottie sticker's pixels move on their own, so it exports as frames// even with no transform animation set.- if (isOverlayAnimated(o) || (isStickerOverlay(o) && o.lottie)) {+ if (isOverlayAnimated(o) || (isStickerOverlay(o) && o.lottie) || subject) {// Animated: a region-cropped 30fps frame sequence that the server plays// as a concat-demuxer slideshow overlaid at the region. Presets sample// their heads and tails and reuse the middle; a keyframed pose changes@@ -413,7 +567,7 @@ async function buildExportPayload(blank,frames: set.entries.map((e) => ({ file: names[e.image], duration: e.duration })),lane: laneOf(o),- ...(behindMask && isTextOverlay(o) && o.behindSubject ? { behind: true } : {}),+ ...subjectFields,});continue;}@@ -425,7 +579,7 @@ async function buildExportPayload(start: o.start,end: Math.min(o.end, duration),lane: laneOf(o),- ...(behindMask && isTextOverlay(o) && o.behindSubject ? { behind: true } : {}),+ ...subjectFields,});}diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.tsindex 41ae72fe..febf85bd 100644--- a/site/src/cut/lib/exportRender.ts+++ b/site/src/cut/lib/exportRender.ts@@ -32,10 +32,10 @@ import { overlayPlan, trackZeroPlan } from "./framePlan";import { frameSink, openMedia, videoTrackOf } from "./mediaRead";import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";import { captionStyle, cueOverlay, cueWordWindows, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";-import { applyEffectToCanvas, evalOverlayFrame, grainTile, isOverlayAnimated, planAnimatedLayers, type LottieHandle, type OverlayAnim } from "@donkeycut/effects-kit";-import { BehindCompositor, hasBehindOverlays } from "./behindPass";+import { applyEffectToCanvas, evalOverlayFrame, grainTile, isMaskAnimated, isOverlayAnimated, maskFrameAt, planAnimatedLayers, type LottieHandle, type OverlayAnim } from "@donkeycut/effects-kit";+import { hasSubjectOverlays, SubjectMaskCompositor } from "./behindPass";import { renderElementPng } from "./textRender";-import { frameOf, isEffectOverlay, isFullRect, isTextOverlay, laneOf, overlayAnimStyle, projectFadeSeconds, rectOf } from "./types";+import { behindSubjectOverlay, frameOf, frontSubjectOverlay, isEffectOverlay, isFullRect, isTextOverlay, laneOf, overlayAnimStyle, projectFadeSeconds, rectOf } from "./types";import type { ClipSpan, EffectOverlay, MediaAsset, Overlay, StickerOverlay } from "./types";import type { ExportDoc, ExportSettings } from "./exportClient";@@ -281,8 +281,10 @@ async function stampText(doc: ExportDoc): Promise<StampedLayer[]> {if (o.hidden || o.start >= duration) continue;// A blank title has no pixels to draw; shapes and stickers always render.if (isTextOverlay(o) && !o.text.trim()) continue;- // Behind-speaker titles composite in the behind pass, under the person.- if (isTextOverlay(o) && o.behindSubject) continue;+ // Behind-the-speaker elements composite in the subject pass, under the+ // person; front subject-masked elements stamp normally and the draw+ // trims them to the matte.+ if (behindSubjectOverlay(o)) continue;// Effect elements filter the video per frame; nothing to stamp.if (o.kind === "effect") continue;// A Lottie sticker seeks per frame; its handle rides the layer.@@ -357,6 +359,7 @@ async function stampText(doc: ExportDoc): Promise<StampedLayer[]> {*/class StampCache {private drawn = new Map<StampedLayer, ImageBitmap>();+ private maskFrames = new Map<StampedLayer, { t: number; bitmap: ImageBitmap }>();constructor(private width: number,@@ -374,6 +377,22 @@ class StampCache {return bitmap;}+ /** The layer's picture with a keyframed mask evaluated at this moment. The+ * mask changes the pixels themselves, so there is one live bitmap per layer,+ * replaced as the render walks forward — the mask-side twin of the Lottie+ * per-frame path. */+ async bitmapForMaskAt(layer: StampedLayer, tLocal: number): Promise<ImageBitmap> {+ const hit = this.maskFrames.get(layer);+ if (hit && Math.abs(hit.t - tLocal) < 1e-6) return hit.bitmap;+ const m = layer.overlay.mask!;+ const flat = { ...layer.overlay, mask: { ...m, ...maskFrameAt(m, tLocal), kf: undefined } };+ const png = await renderElementPng(flat, this.width, this.height, this.assets);+ const bitmap = await createImageBitmap(png);+ hit?.bitmap.close();+ this.maskFrames.set(layer, { t: tLocal, bitmap });+ return bitmap;+ }+/** Release the pictures of layers that have finished by `t`. */retire(t: number) {for (const [layer, bitmap] of this.drawn) {@@ -382,11 +401,19 @@ class StampCache {this.drawn.delete(layer);}}+ for (const [layer, hit] of this.maskFrames) {+ if (layer.end <= t) {+ hit.bitmap.close();+ this.maskFrames.delete(layer);+ }+ }}dispose() {for (const bitmap of this.drawn.values()) bitmap.close();this.drawn.clear();+ for (const hit of this.maskFrames.values()) hit.bitmap.close();+ this.maskFrames.clear();}}@@ -610,13 +637,17 @@ export async function renderProjectToMp4(const layers = await stampText(doc);// Deepest lane first, so a walk of it is a walk up the stack.const stacked = [...layers].sort((a, b) => b.stackLane - a.stackLane);- // The behind pass is created only when something is tagged; prepare()- // makes rasters and the segmenter resident before the first frame.+ // The subject pass is created only when something reads the person matte;+ // prepare() makes rasters and the segmenter resident before the first+ // frame. Subject-masked clips pull their matte mid-stack through the+ // compositor's provider, per frame (no throttling in an export).let fxScratch: OffscreenCanvas | null = null;- let behind: BehindCompositor | null = null;- if (hasBehindOverlays(doc.overlays)) {- behind = new BehindCompositor();+ let behind: SubjectMaskCompositor | null = null;+ if (hasSubjectOverlays(doc.overlays) || doc.clips.some((c) => c.mask?.kind === "subject")) {+ behind = new SubjectMaskCompositor();await behind.prepare(doc.overlays, settings.width, settings.height, doc.assets);+ const pass = behind;+ comp.subjectMatteProvider = (at) => pass.clipMatteOf(canvas, at, { minMaskInterval: 0 });}stop();@@ -678,8 +709,9 @@ export async function renderProjectToMp4(comp.drawIntoRect(frame, rect, cover, layer.alpha, t, layer.zoom, layer.clip);}- // Behind-speaker titles: video → text → segmented person, exactly the- // preview's pass, sampled per exported frame (no mask throttling).+ // The subject pass: video → behind elements → segmented person, exactly+ // the preview's pass, sampled per exported frame (no mask throttling).+ // It also refreshes the matte the front subject-masked stamps read.behind?.draw(canvas, doc.overlays, doc.assets, t, { minMaskInterval: 0 });// The stack, bottom up: an effect grades what plays under it, so the@@ -690,7 +722,7 @@ export async function renderProjectToMp4(for (const o of liveEffectsAt(doc.overlays, t)) {const upto = stacked.findIndex((l) => l.stackLane <= laneOf(o));const end = upto < 0 ? stacked.length : upto;- if (end > drawn) await drawStamps(canvas, stacked.slice(drawn, end), stamps, t);+ if (end > drawn) await drawStamps(canvas, stacked.slice(drawn, end), stamps, t, behind);drawn = Math.max(drawn, end);if (!fxScratch) {fxScratch = new OffscreenCanvas(canvas.width, canvas.height);@@ -707,7 +739,7 @@ export async function renderProjectToMp4(o.end - o.start);}- await drawStamps(canvas, stacked.slice(drawn), stamps, t);+ await drawStamps(canvas, stacked.slice(drawn), stamps, t, behind);stamps.retire(t);comp.drawProjectFade(projectFadeGain(doc, t, duration));@@ -754,7 +786,8 @@ async function drawStamps(canvas: HTMLCanvasElement | OffscreenCanvas,layers: StampedLayer[],stamps: StampCache,- t: number+ t: number,+ subject?: SubjectMaskCompositor | null) {const ctx = canvas.getContext("2d") as| CanvasRenderingContext2D@@ -785,9 +818,20 @@ async function drawStamps(ctx.restore();continue;}- const bitmap = await stamps.bitmapFor(layer);+ const bitmap = isMaskAnimated(layer.overlay.mask)+ ? await stamps.bitmapForMaskAt(layer, t - (layer.animStart ?? layer.start))+ : await stamps.bitmapFor(layer);+ // A front subject-masked stamp trims to the pass's current matte — its+ // pixels change with the video, so the trim happens at draw time, never+ // in the cached raster.+ const subjectFront = !!subject && frontSubjectOverlay(layer.overlay);if (!layer.anim) {- ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);+ const picture = subjectFront+ ? subject!.mattedStamp(layer.overlay, canvas.width, canvas.height, (c) =>+ c.drawImage(bitmap, 0, 0, canvas.width, canvas.height)+ )+ : bitmap;+ ctx.drawImage(picture, 0, 0, canvas.width, canvas.height);continue;}// Unkeyed, the bitmap bakes the element's own rotation/opacity and only@@ -802,13 +846,26 @@ async function drawStamps(const scale = Math.min(canvas.width, canvas.height) / 1080;const cx = layer.overlay.x * canvas.width;const cy = layer.overlay.y * canvas.height;+ const posed = (c: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D) => {+ c.translate(ev.x * canvas.width + ev.dx * scale, ev.y * canvas.height + ev.dy * scale);+ c.rotate((ev.rotation * Math.PI) / 180);+ c.scale(ev.scale, ev.scale);+ c.translate(-cx, -cy);+ c.drawImage(bitmap, 0, 0, canvas.width, canvas.height);+ };ctx.save();ctx.globalAlpha = ev.opacity;- ctx.translate(ev.x * canvas.width + ev.dx * scale, ev.y * canvas.height + ev.dy * scale);- ctx.rotate((ev.rotation * Math.PI) / 180);- ctx.scale(ev.scale, ev.scale);- ctx.translate(-cx, -cy);- ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);+ if (subjectFront) {+ // Pose the stamp inside the matte surface, so the matte stays put in+ // frame space while the element travels beneath it.+ ctx.drawImage(+ subject!.mattedStamp(layer.overlay, canvas.width, canvas.height, posed),+ 0,+ 0+ );+ } else {+ posed(ctx);+ }ctx.restore();}}diff --git a/site/src/cut/lib/maskVideo.ts b/site/src/cut/lib/maskVideo.tsindex 6e9b195c..e63801cd 100644--- a/site/src/cut/lib/maskVideo.ts+++ b/site/src/cut/lib/maskVideo.ts@@ -1,12 +1,15 @@"use client";/**- * The behind-speaker mask video for the ffmpeg export path. The page — the- * only place that can run segmentation — composes the video layers over the- * behind window at a small size, segments each frame, and encodes the person- * mask as a plain grayscale H.264 clip (white = person; no alpha encoding,- * which browsers can't do reliably). The server scales it up, pads it to the- * timeline, and `alphamerge`s the person back over the behind-tagged text.+ * The person-matte video for the ffmpeg export path. The page — the only+ * place that can run segmentation — composes the video layers over the+ * subject window at a small size, segments each frame, and encodes the+ * person mask as a plain grayscale H.264 clip (white = person; no alpha+ * encoding, which browsers can't do reliably). The server scales it up, pads+ * it to the timeline, and every subject-masked consumer — behind elements,+ * front subject elements, subject-masked clips — trims by it. The matte+ * source leaves subject-masked clips out of its composite, so a trimmed clip+ * never reads its own pixels back.*/import {@@ -22,7 +25,7 @@ import { overlayPlan, trackZeroPlan } from "./framePlan";import { ClipReader, VIDEO_CODECS } from "./exportRender";import type { ExportDoc } from "./exportClient";import { getClipSpans } from "./store";-import { frameOf, isFullRect, isTextOverlay, rectOf, type ClipSpan, type MediaAsset } from "./types";+import { frameOf, isEffectOverlay, isFullRect, isTextOverlay, rectOf, subjectMasked, type ClipSpan, type MediaAsset } from "./types";/** Encoded mask rate — the server's fps filter duplicates frames up to the* output rate, and a person moves little in 1/15s. */@@ -36,22 +39,39 @@ const sourceTimeAt = (sp: ClipSpan, t: number) => {return Math.min(sp.clip.out, sp.clip.in + Math.max(0, t - sp.start) * speed);};+/** A clip whose picture trims by the person matte (either direction). */+const subjectClip = (c: { mask?: { kind: string } }) => c.mask?.kind === "subject";+/**- * Render the person-mask video covering every behind-tagged title's window- * (one union range). Null when nothing is tagged, no person segmenter is- * available, or the range is empty — the export simply proceeds without the- * effect, matching the preview's front-title degrade.+ * Render the person-mask video covering every subject-masked consumer's+ * window (one union range): behind and front subject elements, and+ * subject-masked video clips. Null when nothing reads the matte, no person+ * segmenter is available, or the range is empty — the export simply proceeds+ * without the effect, matching the preview's degrade.*/-export async function renderBehindMask(+export async function renderSubjectMask(doc: ExportDoc,duration: number): Promise<{ blob: Blob; from: number } | null> {- const behind = doc.overlays.filter(- (o) => isTextOverlay(o) && !!o.behindSubject && !o.hidden && !!o.text.trim() && o.start < duration- );- if (behind.length === 0) return null;- const from = Math.max(0, Math.min(...behind.map((o) => o.start)));- const to = Math.min(duration, Math.max(...behind.map((o) => o.end)));+ const windows: { start: number; end: number }[] = doc.overlays+ .filter(+ (o) =>+ subjectMasked(o) &&+ !o.hidden &&+ !isEffectOverlay(o) &&+ (!isTextOverlay(o) || !!o.text.trim()) &&+ o.start < duration+ )+ .map((o) => ({ start: o.start, end: o.end }));+ for (const track of [...new Set(doc.clips.map((c) => c.track))]) {+ for (const sp of getClipSpans(doc.clips, doc.assets, track)) {+ if (!subjectClip(sp.clip) || sp.clip.hidden || sp.start >= duration) continue;+ windows.push({ start: sp.start, end: sp.start + sp.len });+ }+ }+ if (windows.length === 0) return null;+ const from = Math.max(0, Math.min(...windows.map((w) => w.start)));+ const to = Math.min(duration, Math.max(...windows.map((w) => w.end)));if (to - from < 0.05) return null;const segmenter = await personSegmenter();if (!segmenter) return null;@@ -96,10 +116,13 @@ export async function renderBehindMask(for (let i = 0; i < frames; i++) {const t = Math.min(to, from + i / MASK_FPS);comp.clear();+ // Subject-masked clips stay out of the matte's composite (their shape+ // masks still apply through the compositor): the matte drives their+ // trim, so reading their own pixels back would feed the mask itself.const master = spans.find((sp) => t >= sp.start && t < sp.start + sp.len);- if (master && !master.clip.hidden) {+ if (master && !master.clip.hidden && !subjectClip(master.clip)) {const plan = trackZeroPlan(master, spans, t);- if (plan.backdrop) {+ if (plan.backdrop && !subjectClip(plan.backdrop.span.clip)) {const f = await readerFor(plan.backdrop.span.asset).frameAt(plan.backdrop.at);comp.drawLayer(f, plan.backdrop.span.clip, false, 1, t);}@@ -107,6 +130,7 @@ export async function renderBehindMask(comp.drawLayer(f ?? MISSING_FRAME, master.clip, false, 1, t);}for (const layer of overlayPlan(overlayTracks, (track) => byTrack.get(track) ?? [], t)) {+ if (subjectClip(layer.clip)) continue;const span = spanOfClip.get(layer.clip.id);if (!span) continue;const f = await readerFor(layer.asset).frameAt(sourceTimeAt(span, t));diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.tsindex 133ce2f5..aae1e2d1 100644--- a/site/src/cut/server/exportPipeline.test.ts+++ b/site/src/cut/server/exportPipeline.test.ts@@ -245,3 +245,218 @@ describe("export filtergraph timebases", () => {expect(xfadeMismatches(g)).toEqual([]);});});++describe("clip masks in the filtergraph", () => {+ test("a masked track-0 clip trims onto a black base and keeps the join sound", async () => {+ const g = await graphFor({+ clips: [+ clip("a.mp4", { mask: { file: "mask_c0.png" }, transition: 0.5, transitionStyle: "crossfade" }),+ clip("b.mp4"),+ ],+ });+ const joined = g.join(";");+ // The multiply chain: painted coverage into the segment's alpha, then the+ // black base restores the opaque constant-size label.+ expect(joined).toContain("alphaextract");+ expect(joined).toContain("blend=all_mode=multiply");+ expect(joined).toContain("alphamerge");+ expect(joined).toContain("format=gray");+ expect(xfadeMismatches(g)).toEqual([]);+ });++ test("a keyframed mask on an upper track plays as a concat slideshow at the box", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { out: 6 })],+ overlayVideos: [+ {+ file: "ov.mp4",+ in: 0,+ out: 2,+ start: 1,+ track: 1,+ muted: true,+ frame: { x: 0.5, y: 0.5, w: 0.5, h: 0.5 },+ mask: {+ frames: [+ { file: "mask_ov0_f0.png", duration: 1 },+ { file: "mask_ov0_f1.png", duration: 1 },+ ],+ },+ },+ ],+ });+ const joined = g.join(";");+ expect(joined).toContain("blend=all_mode=multiply");+ // A letterboxed masked overlay pads out to its region box so the painted+ // mask and the segment share exact pixel geometry.+ expect(joined).toContain("pad=540:960");+ expect(joined).toContain("alphamerge,format=yuva420p");+ expect(xfadeMismatches(g)).toEqual([]);+ });++ test("a masked letterboxed overlay keeps its look, graded before the pad", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { out: 6 })],+ overlayVideos: [+ {+ file: "ov.mp4",+ in: 0,+ out: 2,+ start: 1,+ track: 1,+ muted: true,+ look: "vhs",+ frame: { x: 0.5, y: 0.5, w: 0.5, h: 0.5 },+ mask: { file: "mask_ov0.png" },+ },+ ],+ });+ const joined = g.join(";");+ // The look chain runs on the opaque scaled picture; the transparent box+ // pad joins the chain after it, so the margins stay clear.+ expect(joined).toContain("[olki0]");+ const lookAt = g.findIndex((c) => c.includes("[olki0]"));+ const padAt = g.findIndex((c) => c.includes("pad=540:960") && c.includes("[email protected]"));+ expect(lookAt).toBeGreaterThanOrEqual(0);+ expect(padAt).toBeGreaterThanOrEqual(lookAt);+ expect(xfadeMismatches(g)).toEqual([]);+ });++ test("a mask under head/tail alpha fades keeps both", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { out: 6 })],+ overlayVideos: [+ {+ file: "ov.mp4",+ in: 0,+ out: 3,+ start: 0.5,+ track: 1,+ muted: true,+ headFade: 0.3,+ tailFade: 0.3,+ mask: { file: "mask_ov0.png" },+ },+ ],+ });+ const joined = g.join(";");+ // Fades apply on the segment before the mask multiplies, so both survive+ // (fade alpha=1 multiplies; alphamerge would have replaced it).+ const fadeChain = g.find((c) => c.includes("fade=t=in") && c.includes("alpha=1"));+ const maskChain = g.findIndex((c) => c.includes("blend=all_mode=multiply"));+ expect(fadeChain === undefined).toBe(false);+ expect(maskChain).toBeGreaterThan(g.indexOf(fadeChain!));+ expect(joined).toContain("format=gray");+ expect(xfadeMismatches(g)).toEqual([]);+ });+});++describe("subject masks in the filtergraph", () => {+ test("subject-tagged elements and clips take matte splits, negated when inverted", async () => {+ const g = await graphFor({+ clips: [+ clip("a.mp4", { out: 6, mask: { subject: { invert: true, feather: 20 } } }),+ ],+ overlayVideos: [+ {+ file: "ov.mp4",+ in: 0,+ out: 2,+ start: 1,+ track: 1,+ muted: true,+ mask: { subject: {} },+ },+ ],+ overlays: [+ {+ start: 1,+ end: 3,+ x: 100,+ y: 200,+ blank: "b.png",+ frames: [{ file: "el_f0.png", duration: 2 }],+ subject: { invert: true },+ },+ ],+ behindMask: { file: "behind_mask.mp4", from: 0.5 },+ });+ const joined = g.join(";");+ // Three consumers, one split each, every one through the same multiply+ // chain in lane order.+ expect(joined).toContain("split=3[bhs0][bhs1][bhs2]");+ expect(g.filter((c) => c.includes("negate")).length).toBe(2);+ expect(joined).toContain("gblur=sigma=");+ expect(g.filter((c) => c.includes("blend=all_mode=multiply")).length).toBe(3);+ expect(xfadeMismatches(g)).toEqual([]);+ });+});++describe("clip keyframes in the filtergraph", () => {+ const KF = [+ { t: 0, x: 0.3, y: 0.5, scale: 1, rotation: 0, opacity: 1 },+ { t: 2, x: 0.7, y: 0.4, scale: 1.6, rotation: 45, opacity: 1 },+ ];++ test("a keyed track-0 clip transforms over a transparent base, opaque out", async () => {+ const g = await graphFor({+ clips: [+ clip("a.mp4", { out: 4, kf: KF, transition: 0.5, transitionStyle: "crossfade" }),+ clip("b.mp4"),+ ],+ });+ const joined = g.join(";");+ expect(joined).toContain("rotate=a=");+ expect(joined).toContain("eval=frame");+ expect(joined).toContain("clip((t-0.000)/2.000,0,1)");+ // The transparent base carries the positioned picture; the black base+ // restores the opaque constant-size label the join expects.+ expect(joined).toContain("[email protected]");+ expect(xfadeMismatches(g)).toEqual([]);+ });++ test("a keyed overlay clip positions by expression with its start folded in", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { out: 8 })],+ overlayVideos: [+ {+ file: "ov.mp4",+ in: 0,+ out: 3,+ start: 1.5,+ track: 1,+ muted: true,+ kf: KF,+ },+ ],+ });+ const joined = g.join(";");+ expect(joined).toContain("(t-1.500)");+ expect(joined).toContain("rotate=a=");+ expect(joined).toContain("-w/2");+ expect(xfadeMismatches(g)).toEqual([]);+ });++ test("a keyed subject-masked overlay rides the transparent base before the matte", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { out: 8 })],+ overlayVideos: [+ {+ file: "ov.mp4",+ in: 0,+ out: 3,+ start: 1,+ track: 1,+ muted: true,+ kf: KF,+ mask: { subject: {} },+ },+ ],+ behindMask: { file: "behind_mask.mp4", from: 0.5 },+ });+ const joined = g.join(";");+ expect(joined).toContain("[email protected]");+ expect(joined).toContain("blend=all_mode=multiply");+ expect(xfadeMismatches(g)).toEqual([]);+ });+});diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex c5342e51..28f15098 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -2,8 +2,8 @@ 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 { effectFilterLines, gradeToFfmpegFilter, lookFilterLines } from "@donkeycut/effects-kit";+import { projectFadeSeconds, regionPx, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";+import { effectFilterLines, gradeToFfmpegFilter, lookFilterLines, shortestTurn, sortedKeys, type OverlayKey } from "@donkeycut/effects-kit";// 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@@ -62,6 +62,22 @@ export interface ExportSpec {image?: boolean;/** Manual color adjustments, baked into this clip's segment. */grade?: ColorGrade;+ /** Client-painted grayscale coverage trimming this clip's picture (white+ * keeps the pixel; feather and invert are baked into the pictures): one+ * full-frame still, or a sampled `frames` sequence for a keyframed mask+ * covering the segment's own [0, dur]. `subject` trims by the shared+ * person matte (`behindMask`) instead — inverted keeps the picture off+ * the person, feather softens the matte edge (design px). */+ mask?: {+ file?: string;+ frames?: { file: string; duration: number }[];+ subject?: { invert?: boolean; feather?: number };+ };+ /** Keyframed pose track, seconds from the segment's own start: x/y move+ * the picture's center (frame fractions), scale multiplies it, rotation+ * turns it. Opacity keys ride the painted mask's luma, so the graph+ * never needs an animatable alpha filter. */+ kf?: { t: number; x: number; y: number; scale: number; rotation: number; opacity: number }[];}[];/** Video tracks composited over the track-0 `clips`, lowest track first. */overlayVideos?: {@@ -95,6 +111,16 @@ export interface ExportSpec {* overlays may carry alpha the look chain would flatten). */look?: string;lookAmount?: number;+ /** Client-painted grayscale coverage trimming this overlay's picture,+ * box-sized (a letterboxed segment pads out to its box when masked);+ * `subject` trims by the shared person matte instead. */+ mask?: {+ file?: string;+ frames?: { file: string; duration: number }[];+ subject?: { invert?: boolean; feather?: number };+ };+ /** Keyframed pose track, seconds from this overlay's start. */+ kf?: { t: number; x: number; y: number; scale: number; rotation: number; opacity: number }[];}[];audio: {file: string;@@ -123,9 +149,10 @@ export interface ExportSpec {y?: number;blank?: string;frames?: { file: string; duration: number }[];- /** Text-behind-speaker: composite this element beneath the alphamerged- * person cutout (needs `behindMask`). */- behind?: boolean;+ /** The element trims by the shared person matte (needs `behindMask` and+ * a `frames` stream): inverted keeps it off the person — behind the+ * speaker, in its own lane order — and feather softens the matte edge. */+ subject?: { invert?: boolean; feather?: number };/** Its row: lane 0 is the top of the stack. Elements composite deepest* lane first, and effects interleave with them by the same number. */lane?: number;@@ -243,24 +270,6 @@ function clipRate(c: ExportSpec["clips"][number]) {/** 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@@ -459,6 +468,52 @@ export async function runExport(inputs.push("-loop", "1", "-t", num(olen), "-framerate", String(fps), "-i", await resolveMedia(io.stat, mediaPathFor, oc.file));}+ // Client-painted clip masks: a resting mask is one looped still the length+ // of its segment; a keyframed one plays as its own concat slideshow, both+ // on the segment's local clock (the mask multiplies in before tpad).+ const maskInput = async (+ mk: NonNullable<ExportSpec["clips"][number]["mask"]>,+ dur: number,+ tag: string+ ): Promise<number | undefined> => {+ if (mk.frames?.length) {+ const lines = ["ffconcat version 1.0"];+ for (const f of mk.frames) {+ if (f.duration < 1e-4) continue;+ lines.push(+ `file '${path.join(job.tmpDir, path.basename(f.file))}'`,+ `duration ${num(f.duration)}`+ );+ }+ const list = path.join(job.tmpDir, `${tag}.ffconcat`);+ await io.writeFile(list, lines.join("\n") + "\n");+ const idx = nInputs++;+ inputs.push("-f", "concat", "-safe", "0", "-i", list);+ return idx;+ }+ if (!mk.file) return undefined;+ const idx = nInputs++;+ inputs.push("-loop", "1", "-t", num(dur), "-framerate", String(fps), "-i", path.join(job.tmpDir, path.basename(mk.file)));+ return idx;+ };+ const clipMaskInput = new Map<number, number>();+ for (let j = 0; j < spec.clips.length; j++) {+ const c = spec.clips[j];+ if (!c.mask) continue;+ const dur = c.file ? Math.max(0.1, (c.out - c.in) / clipRate(c)) : Math.max(0, c.out - c.in);+ const idx = await maskInput(c.mask, dur, `mask_clip_${j}`);+ if (idx !== undefined) clipMaskInput.set(j, idx);+ }+ const overlayMaskInput = new Map<(typeof overlayVideos)[number], number>();+ for (let k = 0; k < overlayVideos.length; k++) {+ const oc = overlayVideos[k];+ if (!oc.mask) continue;+ const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;+ const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);+ const idx = await maskInput(oc.mask, olen, `mask_ovl_${k}`);+ if (idx !== undefined) overlayMaskInput.set(oc, idx);+ }+// 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@@ -503,6 +558,123 @@ export async function runExport(// 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);+ // Where each track-0 segment lands on the joined timeline: transitions+ // pad their overlap, so the layout is the plain running sum of durations.+ const clipStarts: number[] = [];+ {+ let accStart = 0;+ for (const c of spec.clips) {+ clipStarts.push(accStart);+ accStart += clipDur(c);+ }+ }++ // The shared person matte, split once per subject-mask consumer: elements+ // trimmed to (or off) the person, and subject-masked clips on any track.+ // Each consumer takes one split, negates it when inverted, and blurs it by+ // its feather.+ const outScale = Math.min(W, H) / 1080;+ const clipDrawable = (c: ExportSpec["clips"][number]) =>+ (c.image || videoPresence.get(c.file)) && !c.hidden;+ const subjectActive = !!spec.behindMask && behindMaskInput !== undefined;+ const matteConsumers = !subjectActive+ ? 0+ : spec.overlays.filter((o) => o.subject && o.frames?.length && o.blank).length ++ overlayVideos.filter((oc) => oc.mask?.subject && (oc.image || videoPresence.get(oc.file)))+ .length ++ spec.clips.filter((c) => c.mask?.subject && clipDrawable(c)).length;+ let matteN = 0;+ if (subjectActive && matteConsumers > 0) {+ filters.push(+ `[${behindMaskInput}:v]fps=${fps},scale=${W}:${H},setsar=1,format=gray,` ++ `tpad=start_duration=${num(Math.max(0, spec.behindMask!.from))}:color=black[bh_src]`+ );+ filters.push(+ matteConsumers > 1+ ? `[bh_src]split=${matteConsumers}` ++ Array.from({ length: matteConsumers }, (_, i) => `[bhs${i}]`).join("")+ : `[bh_src]null[bhs0]`+ );+ }+ // ---- Keyframed clip poses as filter expressions -------------------------+ // The pose track is piecewise-linear with the ends held flat, exactly the+ // kit evaluator: v0 + Σ Δi·clip((V−ti)/(ti+1−ti),0,1) builds that shape as+ // one monotone expression, safe inside overlay/scale/rotate.+ const piecewiseExpr = (keys: { t: number; v: number }[], varExpr: string): string => {+ const ks = [...keys].sort((a, b) => a.t - b.t);+ let e = `${num(ks[0].v)}`;+ for (let i = 0; i < ks.length - 1; i++) {+ const dt = Math.max(1e-6, ks[i + 1].t - ks[i].t);+ const dv = ks[i + 1].v - ks[i].v;+ if (Math.abs(dv) < 1e-9) continue;+ e += `+${num(dv)}*clip((${varExpr}-${num(ks[i].t)})/${num(dt)},0,1)`;+ }+ return `(${e})`;+ };+ /** The pose track's rotation values unwrapped into cumulative degrees, so+ * the expression lerps the short way around like the kit evaluator. */+ const unwrappedRotation = (kf: OverlayKey[]): { t: number; v: number }[] => {+ const ks = sortedKeys(kf);+ const out: { t: number; v: number }[] = [{ t: ks[0].t, v: ks[0].rotation }];+ for (let i = 1; i < ks.length; i++) {+ out.push({+ t: ks[i].t,+ v: out[i - 1].v + shortestTurn(ks[i - 1].rotation, ks[i].rotation),+ });+ }+ return out;+ };+ const varies = (kf: OverlayKey[], field: "x" | "y" | "scale" | "rotation") =>+ kf.some((k) => Math.abs(k[field] - kf[0][field]) > 1e-6);+ /** The rotate/scale filters a keyed segment runs before positioning, on+ * its own local clock. `boxW`/`boxH` give the constant rotate canvas. */+ const poseTransformFilters = (+ kf: OverlayKey[],+ boxW: number,+ boxH: number+ ): string => {+ const ks = sortedKeys(kf);+ let chain = "";+ if (varies(ks, "rotation") || Math.abs(ks[0].rotation) > 1e-6) {+ const diag = 2 * Math.ceil(Math.hypot(boxW, boxH) / 2);+ const rot = piecewiseExpr(unwrappedRotation(ks), "t");+ chain += `,rotate=a='${rot}*PI/180':ow=${diag}:oh=${diag}:[email protected]`;+ }+ if (varies(ks, "scale") || Math.abs(ks[0].scale - 1) > 1e-6) {+ const sc = piecewiseExpr(ks.map((k) => ({ t: k.t, v: k.scale })), "t");+ chain += `,scale=w='trunc(iw*${sc}/2)*2':h=-2:eval=frame`;+ }+ return chain;+ };+ /** The overlay x/y expressions placing a keyed segment's center at its+ * pose, with the key clock offset to `startAt` on the consuming stream's+ * timeline (0 for a local-clock base). */+ const posePositionExprs = (kf: OverlayKey[], startAt: number): { x: string; y: string } => {+ const ks = sortedKeys(kf);+ const v = startAt > 1e-9 ? `(t-${num(startAt)})` : "t";+ return {+ x: `'${piecewiseExpr(ks.map((k) => ({ t: k.t, v: k.x })), v)}*${W}-w/2'`,+ y: `'${piecewiseExpr(ks.map((k) => ({ t: k.t, v: k.y })), v)}*${H}-h/2'`,+ };+ };++ /** One matte split, shaped for a consumer. Every counted consumer takes+ * exactly one, so the split's outputs all connect. */+ const nextMatte = (+ tag: string,+ subject: { invert?: boolean; feather?: number }+ ): string => {+ let cur = `bhs${matteN++}`;+ if (subject.invert) {+ filters.push(`[${cur}]negate[${tag}n]`);+ cur = `${tag}n`;+ }+ if (subject.feather && subject.feather > 0) {+ filters.push(`[${cur}]gblur=sigma=${num((subject.feather * outScale) / 4)}[${tag}b]`);+ cur = `${tag}b`;+ }+ return cur;+ };/** 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@@ -766,7 +938,67 @@ export async function runExport(// 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}`);+ const mkIdx = clipMaskInput.get(j);+ const subjMask = subjectActive && matteConsumers > 0 ? c.mask?.subject : undefined;+ const keyed = !!c.kf?.length;+ if (mkIdx !== undefined || subjMask || keyed) {+ // Masked or keyframed track-0 clip, composed in the preview's order:+ // the painted coverage multiplies first (it rides the clip), the+ // pose transforms and positions the result over a transparent base,+ // the person matte — frame-anchored — trims last, and a black base+ // restores the constant-size opaque frame the join expects. The+ // multiply chains (alphaextract → blend → alphamerge) compose with+ // any alpha the segment carries.+ pushEdgeFx(core, dur, headFx, tailFx, W, H, clipFmt, fades, `vmr${j}`, `c${j}`);+ let cur = `vmr${j}`;+ if (mkIdx !== undefined) {+ filters.push(`[${mkIdx}:v]fps=${fps},scale=${W}:${H},setsar=1,format=gray[cmk${j}]`);+ filters.push(`[${cur}]format=rgba,split[cm0_${j}][cm1_${j}]`);+ filters.push(`[cm1_${j}]alphaextract[cma${j}]`);+ filters.push(`[cma${j}][cmk${j}]blend=all_mode=multiply[cmm${j}]`);+ filters.push(`[cm0_${j}][cmm${j}]alphamerge[cmc${j}]`);+ cur = `cmc${j}`;+ } else {+ filters.push(`[${cur}]format=rgba[cmc${j}]`);+ cur = `cmc${j}`;+ }+ if (keyed) {+ const tf = poseTransformFilters(c.kf!, W, H);+ if (tf) {+ filters.push(`[${cur}]null${tf}[ckt${j}]`);+ cur = `ckt${j}`;+ }+ const pos = posePositionExprs(c.kf!, 0);+ filters.push(+ `[email protected]:s=${W}x${H}:r=${fps}:d=${num(dur)},format=yuva420p[ckb${j}]`+ );+ filters.push(+ `[ckb${j}][${cur}]overlay=x=${pos.x}:y=${pos.y}:eof_action=pass[ckp${j}]`+ );+ cur = `ckp${j}`;+ }+ if (subjMask) {+ const matte = nextMatte(`bsc${j}`, subjMask);+ // Clone-pad past the matte's own end so a segment running longer+ // than the matte window never shortens the join.+ filters.push(+ `[${matte}]trim=${num(clipStarts[j])}:${num(clipStarts[j] + dur)},` ++ `setpts=PTS-STARTPTS,fps=${fps},tpad=stop_mode=clone:stop_duration=${num(dur)},` ++ `trim=0:${num(dur)},setpts=PTS-STARTPTS,fps=${fps}[cms${j}]`+ );+ filters.push(`[${cur}]format=rgba,split[cs0_${j}][cs1_${j}]`);+ filters.push(`[cs1_${j}]alphaextract[csa${j}]`);+ filters.push(`[csa${j}][cms${j}]blend=all_mode=multiply[csm${j}]`);+ filters.push(`[cs0_${j}][csm${j}]alphamerge[csc${j}]`);+ cur = `csc${j}`;+ }+ filters.push(`color=c=black:s=${W}x${H}:r=${fps}:d=${num(dur)}[cmb${j}]`);+ filters.push(+ `[cmb${j}][${cur}]overlay=0:0:shortest=1,format=${clipFmt},fps=${fps}[${segOut}]`+ );+ } else {+ pushEdgeFx(core, dur, headFx, tailFx, W, H, clipFmt, fades, segOut, `c${j}`);+ }if (nFz > 0) {filters.push(`[vseg${j}]split=${nFz + 1}[v${j}]` +@@ -936,6 +1168,9 @@ export async function runExport(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 maskIdx = overlayMaskInput.get(oc);+ const subjMask = subjectActive && matteConsumers > 0 ? oc.mask?.subject : undefined;+ const keyed = !!oc.kf?.length;const boxW = region ? region.rw : W;const boxH = region ? region.rh : H;let framing: string;@@ -952,14 +1187,20 @@ export async function runExport(: `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";+ // zoompan needs a constant frame size — and a mask trims at the box, so+ // both 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. The pad joins the chain after the look+ // bakes in, so the look grades the opaque scaled picture and never+ // flattens the transparent margins.+ const boxed = (ramped || maskIdx !== undefined || !!subjMask || keyed) && !cover;+ const boxPad = boxed+ ? `,format=yuva420p,pad=${boxW}:${boxH}:(ow-iw)/2:(oh-ih)/2:[email protected]`+ : "";+ if (boxed) pos = region ? `${region.rx}:${region.ry}` : "0:0";+ const fmt = hf > 0.01 || tf > 0.01 || boxed ? "yuva420p" : "yuv420p";+ // The look chain reads the pre-pad picture, which is opaque.+ const lookFmt = boxed ? "yuv420p" : fmt;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` : "");@@ -970,19 +1211,19 @@ export async function runExport(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}`);+ let core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${lookFmt}`;+ // Looks bake into footage overlays only: an image may carry alpha, which+ // the look chain's internal filters would flatten onto black over the+ // tracks beneath. The alpha fades stay safe: they apply after the look.+ if (oc.look && !oc.image) {+ const lines = lookFilterLines(`olki${k}`, `olko${k}`, oc.look, oc.lookAmount, H, lookFmt, `o${k}`);if (lines) {filters.push(`${core}[olki${k}]`);filters.push(...lines);core = `[olko${k}]null`;}}+ if (boxPad) core += boxPad;const pre = `ovp${k}`;pushEdgeFx(core,@@ -996,14 +1237,66 @@ export async function runExport(pre,`o${k}`);+ // A masked overlay multiplies the painted coverage into whatever alpha+ // the segment already carries (transparent pad, alpha fades), then keeps+ // its alpha through the tpad/overlay below. A keyed pose rotates and+ // scales on the segment's local clock before the delay.+ let masked = pre;+ if (maskIdx !== undefined) {+ filters.push(`[${maskIdx}:v]fps=${fps},scale=${boxW}:${boxH},setsar=1,format=gray[omk${k}]`);+ filters.push(`[${pre}]format=rgba,split[om0${k}][om1${k}]`);+ filters.push(`[om1${k}]alphaextract[oma${k}]`);+ filters.push(`[oma${k}][omk${k}]blend=all_mode=multiply[omm${k}]`);+ filters.push(`[om0${k}][omm${k}]alphamerge,format=yuva420p[omc${k}]`);+ masked = `omc${k}`;+ }+ if (keyed) {+ const tf = poseTransformFilters(oc.kf!, boxW, boxH);+ if (tf) {+ filters.push(`[${masked}]format=rgba${tf},format=yuva420p[okt${k}]`);+ masked = `okt${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}]`);+ filters.push(`[${masked}]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}]`- );+ const enable = `enable='between(t,${num(oc.start)},${num(end)})'`;+ if (subjMask) {+ // Subject-masked overlay clip: the delayed segment lands on the full+ // frame at its spot — a static pad, or an expression overlay onto a+ // transparent base when keyed — its alpha multiplies by the timeline-+ // aligned matte, and the trimmed layer composites at the origin.+ const matte = nextMatte(`bso${k}`, subjMask);+ if (keyed) {+ const kpos = posePositionExprs(oc.kf!, oc.start);+ filters.push(+ `[email protected]:s=${W}x${H}:r=${fps}:d=${num(spec.duration)},format=yuva420p[osb${k}]`+ );+ filters.push(+ `[osb${k}][${seg}]overlay=x=${kpos.x}:y=${kpos.y}:eof_action=pass[osp${k}]`+ );+ } else {+ const padX = region ? region.rx : 0;+ const padY = region ? region.ry : 0;+ filters.push(+ `[${seg}]format=rgba,pad=${W}:${H}:${padX}:${padY}:[email protected][osp${k}]`+ );+ }+ filters.push(`[osp${k}]format=rgba,split[os0${k}][os1${k}]`);+ filters.push(`[os1${k}]alphaextract[osa${k}]`);+ filters.push(`[osa${k}][${matte}]blend=all_mode=multiply[osm${k}]`);+ filters.push(`[os0${k}][osm${k}]alphamerge,format=yuva420p[osc${k}]`);+ filters.push(`[${onto}][osc${k}]overlay=0:0:${enable}:eof_action=pass[${next}]`);+ } else if (keyed) {+ const kpos = posePositionExprs(oc.kf!, oc.start);+ filters.push(+ `[${onto}][${seg}]overlay=x=${kpos.x}:y=${kpos.y}:${enable}:eof_action=pass[${next}]`+ );+ } else {+ filters.push(`[${onto}][${seg}]overlay=${pos}:${enable}: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)},` : "";@@ -1035,6 +1328,23 @@ export async function runExport(const next = `vov${k}`;const animIdx = animOverlayInput.get(k);if (animIdx !== undefined) {+ if (o.subject && subjectActive && matteConsumers > 0) {+ // Subject-trimmed element: its slideshow pads out to the full frame+ // at its region, the matte multiplies into its alpha, and the+ // trimmed element composites at the origin — in its own lane order,+ // behind (inverted) or on the person alike.+ const matte = nextMatte(`bse${k}`, o.subject);+ filters.push(+ `[${animIdx}:v]fps=${fps},setsar=1,format=rgba,` ++ `pad=${W}:${H}:${num(o.x ?? 0)}:${num(o.y ?? 0)}:[email protected][oep${k}]`+ );+ filters.push(`[oep${k}]split[oe0${k}][oe1${k}]`);+ filters.push(`[oe1${k}]alphaextract[oea${k}]`);+ filters.push(`[oea${k}][${matte}]blend=all_mode=multiply[oem${k}]`);+ filters.push(`[oe0${k}][oem${k}]alphamerge,format=yuva420p[oes${k}]`);+ filters.push(`[${onto}][oes${k}]overlay=0:0:eof_action=pass[${next}]`);+ return next;+ }filters.push(`[${animIdx}:v]fps=${fps},format=yuva420p,setsar=1[oanim${k}]`);filters.push(`[${onto}][oanim${k}]overlay=${num(o.x ?? 0)}:${num(o.y ?? 0)}:eof_action=pass[${next}]`@@ -1050,36 +1360,16 @@ export async function runExport(return next;};- // Text-behind-speaker: the composite splits, the behind-tagged elements- // burn onto one branch, and the other branch — alphamerged with the- // page-rendered person mask (standard LGPL filters) — lays the subject- // back over them. Front overlays then continue on the merged stream.- const behindKs = spec.behindMask- ? spec.overlays.flatMap((o, k) => (o.behind ? [k] : []))- : [];- if (spec.behindMask && behindMaskInput !== undefined && behindKs.length > 0) {- filters.push(`[${vLabel}]split[bh_text][bh_person]`);- let textLab = "bh_text";- for (const k of behindKs) textLab = compositeOverlayEntry(k, textLab);- filters.push(- `[${behindMaskInput}:v]fps=${fps},scale=${spec.width}:${spec.height},format=gray,` +- `tpad=start_duration=${num(Math.max(0, spec.behindMask.from))}:color=black[bh_mask]`- );- filters.push(`[bh_person]format=rgba[bh_rgba]`);- filters.push(`[bh_rgba][bh_mask]alphamerge[bh_cut]`);- filters.push(`[${textLab}][bh_cut]overlay=0:0:eof_action=pass[bh_done]`);- vLabel = "bh_done";- }// The element stack, deepest lane first, with the effects standing in it:// an effect grades what plays under it, so everything below its lane is// composited before its chain runs, and the elements above it land on the// graded picture untouched. Each chain is gated to its own window (the shake// recipe swaps in a jittered branch through an overlay instead, so nothing- // else rescales).+ // else rescales). Subject-tagged elements trim by their matte split inside+ // this walk, in their own lane order.const laneOfEntry = (k: number) => spec.overlays[k].lane ?? 0;const stacked = spec.overlays.map((o, k) => k)- .filter((k) => !(spec.overlays[k].behind && behindKs.includes(k))).sort((a, b) => laneOfEntry(b) - laneOfEntry(a));const effects = (spec.effects ?? []).map((e, i) => ({ e, i }))