Skip to content

Open source CapCut alternative.

TypeScript

fix(cut): show sub-frame clips in every export [rebuild]

David Le500bfd7fbc23
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index d479ebdb..46e8b721 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -33,6 +33,7 @@ import { clipLen, clipSpeed, getClipSpans, MICRO_GAP_S, openedTimeline, overlayL
import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
import { drawStreak, elementLook, isMaskAnimated, isOverlayAnimated, matteLumaToAlpha, normalizeGrade, paintMaskLuma, paintStrokeInk, retimeOf, type FlashFade, type FlashRhythm, type FlashTone, type GlitchKind, type LeakCourse, type Mask, type SpeedNode } from "@donkeycut/effects-kit";
import { renderElementFrames, renderElementPng, renderStillPng, requireStickers } from "./textRender";
+import { holdOverlays } from "./frameGrid";
import { CLIP_MIN_SECONDS, clipCovers, clipFrameAt, clipKeyed, clipPosed, clipPoseAt, clipZoom, contentRect, frameOf, isStickerOverlay, isTextOverlay, laneOf, overlayAnimStyle, projectBackground, rectOf, regionPx, removalActive, shadowInk, subjectMasked, parkedTimeline } from "./types";
import { liveReader } from "./liveReader";
import { soundSourceOf, spanSoundSpec, spanUsesSoundFeature, specSound } from "./soundSource";
@@ -889,6 +890,8 @@ export async function buildExportPayload(
// Every video's color is read before the spec is: footage the lazy fill
// has not reached would otherwise go out as Rec.709.
doc = { ...doc, assets: await withAssetColors(doc.assets, doc) };
+ // Elements shorter than an output frame widen onto the one they hold.
+ doc = { ...doc, overlays: holdOverlays(doc.overlays, settings.fps) };
const spans = getClipSpans(doc.clips, doc.assets);
const duration = projectDuration(doc);
const pngs: ExportPayload["pngs"] = [];
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index 680a1c84..243016bf 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -40,7 +40,8 @@ import { FrameCompositor, MISSING_FRAME, type Frame } from "./composite";
import { ensureClipLuts, sourceLookup } from "./lutBuild";
import { colorRead, type ColorRead, type ReadFile } from "./sourceColor";
import type { OutputSpace } from "@donkeycut/effects-kit";
-import { overlayPlan, trackZeroPlan } from "./framePlan";
+import { heldSpans, overlayPlan, trackZeroAt, trackZeroPlan } from "./framePlan";
+import { heldFrames, holdOverlays, type HeldFrames } from "./frameGrid";
import { frameSink, keyframeTimeAt, openMedia, videoTrackOf, withAssetColors } from "./mediaRead";
import type { InputVideoTrack, WrappedCanvas } from "mediabunny";
import { allowance, canvasBytes, holdMemory } from "./memoryBudget";
@@ -1127,7 +1128,8 @@ export async function renderProjectToMp4(
}
const canvas = createRasterCanvas(settings.width, settings.height);
- const painter = new FramePainter(doc, canvas, resolve);
+ // Elements shorter than an output frame widen onto the one they hold.
+ const painter = new FramePainter({ ...doc, overlays: holdOverlays(doc.overlays, settings.fps) }, canvas, resolve, settings.fps);
const frameDur = 1 / settings.fps;
const frames = Math.max(1, Math.round(span * settings.fps));
@@ -1485,12 +1487,18 @@ export class FramePainter {
private overlayTracks: number[] = [];
private byTrack = new Map<number, ClipSpan[]>();
private spanOfClip = new Map<string, ClipSpan>();
+ /** The frames clips shorter than an output frame hold, on track 0 and
+ * above; empty for a painter drawing loose moments. */
+ private trackZeroHeld: (HeldFrames | null)[] = [];
+ private overlayHeld = new Map<ClipSpan, HeldFrames | null>();
private duration: number;
+ /** `fps` is the output grid of a render, absent for loose moments. */
constructor(
private doc: ExportDoc,
private canvas: RasterSurface,
- private resolve: (asset: MediaAsset) => string
+ private resolve: (asset: MediaAsset) => string,
+ private fps?: number
) {
this.comp = new FrameCompositor(canvas);
this.comp.background = projectBackground(doc.background);
@@ -1562,6 +1570,12 @@ export class FramePainter {
);
for (const list of this.byTrack.values())
for (const sp of list) this.spanOfClip.set(sp.clip.id, sp);
+ if (this.fps) {
+ const fps = this.fps;
+ this.trackZeroHeld = heldFrames(this.spans.map((sp) => ({ start: sp.start, end: sp.start + sp.len })), fps);
+ for (const list of this.byTrack.values())
+ for (const [sp, held] of heldSpans(list, fps)) this.overlayHeld.set(sp, held);
+ }
}
/**
@@ -1689,18 +1703,20 @@ export class FramePainter {
const H = canvas.height;
comp.clear();
- const master = this.spans.find((sp) => t >= sp.start && t < sp.start + sp.len);
- if (master) {
- const plan = trackZeroPlan(master, this.spans, t);
- await this.fetchRemovalMatte(master, t);
- if (plan.incoming) await this.fetchRemovalMatte(plan.incoming, t);
+ // A clip holding a frame past its own end is drawn as at its start.
+ const shown = trackZeroAt(this.spans, this.trackZeroHeld, t);
+ if (shown) {
+ const { span: master, at } = shown;
+ const plan = trackZeroPlan(master, this.spans, at);
+ await this.fetchRemovalMatte(master, at);
+ if (plan.incoming) await this.fetchRemovalMatte(plan.incoming, at);
if (plan.backdrop) {
- await this.fetchRemovalMatte(plan.backdrop.span, t);
+ await this.fetchRemovalMatte(plan.backdrop.span, at);
const frame = await this.readerFor(plan.backdrop.span.asset).frameAt(plan.backdrop.at);
- comp.drawLayer(frame, plan.backdrop.span.clip, false, 1, t);
+ comp.drawLayer(frame, plan.backdrop.span.clip, false, 1, at);
}
- const masterFrame = master.clip.hidden ? MISSING_FRAME : await this.frameOf(master, t);
- const incFrame = plan.incoming ? await this.frameOf(plan.incoming, t) : MISSING_FRAME;
+ const masterFrame = master.clip.hidden ? MISSING_FRAME : await this.frameOf(master, at);
+ const incFrame = plan.incoming ? await this.frameOf(plan.incoming, at) : MISSING_FRAME;
comp.drawCrossJoin(
plan.style,
plan.p,
@@ -1719,23 +1735,23 @@ export class FramePainter {
incAlpha: plan.incAlpha,
incZoom: plan.incZoom,
},
- t
+ at
);
if (plan.veil > 0) comp.fillBlackVeil(plan.veil, rectOf(master.clip));
}
const spansOf = (track: number) => this.byTrack.get(track) ?? [];
- for (const layer of overlayPlan(this.overlayTracks, spansOf, t)) {
+ for (const layer of overlayPlan(this.overlayTracks, spansOf, t, this.overlayHeld)) {
const span = this.spanOfClip.get(layer.clip.id);
if (!span) continue;
- await this.fetchRemovalMatte(span, t);
- const frame = await this.frameOf(span, t);
+ await this.fetchRemovalMatte(span, layer.at);
+ const frame = await this.frameOf(span, layer.at);
comp.drawIntoRect(
frame,
rectOf(layer.clip),
clipCovers(layer.clip),
layer.alpha,
- t,
+ layer.at,
layer.zoom,
layer.clip
);
diff --git a/site/src/cut/lib/exportTail.test.ts b/site/src/cut/lib/exportTail.test.ts
index 407abe38..5f1407e5 100644
--- a/site/src/cut/lib/exportTail.test.ts
+++ b/site/src/cut/lib/exportTail.test.ts
@@ -29,3 +29,13 @@ test("the clip list runs to the end of the cut, black after the last shot", asyn
const length = spec.clips.reduce((sum, c) => sum + (c.out - c.in), 0);
expect(length).toBeCloseTo(5);
});
+
+test("an effect shorter than a frame still holds one frame of the file", async () => {
+ const flash = { id: "fx", kind: "effect", effect: "negative", start: 1.01, end: 1.01 + 1 / 60, x: 0.5, y: 0.5 } as const;
+ const settings = { ...originalSettings(doc.aspect, doc.clips, doc.assets, doc), fps: 30 };
+ const payload = await buildExportPayload("project", { ...doc, overlays: [flash] }, settings, "export");
+ const [effect] = (payload.spec as { effects: { start: number; end: number }[] }).effects;
+ // Frame 31 (1.0333s) is the first at or after the flash: the window has to cover it.
+ expect(effect.start).toBeLessThanOrEqual(31 / 30);
+ expect(effect.end).toBeGreaterThan(31 / 30);
+});
diff --git a/site/src/cut/lib/frameGrid.test.ts b/site/src/cut/lib/frameGrid.test.ts
new file mode 100644
index 00000000..0f3ad1b5
--- /dev/null
+++ b/site/src/cut/lib/frameGrid.test.ts
@@ -0,0 +1,44 @@
+import { expect, test } from "bun:test";
+import { heldFrames, holdOverlays, showsAt } from "./frameGrid";
+import type { Overlay } from "./types";
+
+const FPS = 30;
+/** The output frame times a 30 fps export samples, frames 0..5. */
+const frames = [0, 1, 2, 3, 4, 5].map((k) => k / FPS);
+
+test("a footprint shorter than a frame holds the one at or after its start", () => {
+ const [held] = heldFrames([{ start: 0.01, end: 0.01 + 1 / 60 }], FPS);
+ expect(held).toMatchObject({ first: 1, last: 2 });
+ expect(frames.filter((t) => showsAt(0.01, 0.01 + 1 / 60, held, t))).toEqual([1 / FPS]);
+});
+
+test("a run of flash frames lands one per output frame, and the next clip waits its turn", () => {
+ const items = [0, 1, 2].map((k) => ({ start: k / 60, end: (k + 1) / 60 }));
+ items.push({ start: 3 / 60, end: 4 });
+ const held = heldFrames(items, FPS);
+ expect(held.map((h) => h && [h.first, h.last])).toEqual([null, [1, 2], [2, 3], [3, 120]]);
+ frames.forEach((t, k) => {
+ const live = items.filter((it, i) => showsAt(it.start, it.end, held[i], t));
+ expect(live).toHaveLength(1);
+ expect(items.indexOf(live[0])).toBe(Math.min(k, 3));
+ });
+});
+
+test("footprints that hold their own frames are left as they are", () => {
+ expect(heldFrames([{ start: 0, end: 1 }, { start: 1, end: 1 + 1 / 60 }, { start: 2, end: 3 }], 60)).toEqual([
+ null,
+ null,
+ null,
+ ]);
+});
+
+test("a sub-frame title widens onto its frame and the title after it moves off it", () => {
+ const title = (id: string, start: number, end: number): Overlay =>
+ ({ id, kind: "text", text: id, start, end, x: 0.5, y: 0.5 }) as Overlay;
+ const overlays = [title("a", 0.01, 0.01 + 1 / 60), title("b", 0.01 + 1 / 60, 1), title("c", 0.5, 0.6)];
+ overlays[2].lane = 1;
+ const held = holdOverlays(overlays, FPS);
+ expect(held[0]).toMatchObject({ start: 0.01, end: 1.5 / FPS });
+ expect(held[1]).toMatchObject({ start: 1.5 / FPS, end: 1 });
+ expect(held[2]).toBe(overlays[2]);
+});
diff --git a/site/src/cut/lib/frameGrid.ts b/site/src/cut/lib/frameGrid.ts
new file mode 100644
index 00000000..f07b2059
--- /dev/null
+++ b/site/src/cut/lib/frameGrid.ts
@@ -0,0 +1,99 @@
+import { isAudioEffect } from "@donkeycut/effects-kit";
+import { isEffectOverlay, laneOf, type Overlay } from "./types";
+
+/**
+ * The frames an export lays the timeline on.
+ *
+ * An export samples the cut at k / fps. A footprint shows on the grid frames
+ * from the first at or after its start to the first at or after its end, so a
+ * clip shorter than one output frame can fall between two and show on none: a
+ * 1/60 s flash in a 30 fps file. On a lane, such a clip holds the one frame at
+ * or after its start and the clip after it takes the next, the rule the
+ * ffmpeg join has always kept on track 0. Every renderer reads it from here.
+ */
+
+/** How far past a whole frame a time may sit, in frames, and still count as
+ * on it: rounding in a sum of clip lengths never pushes a cut a frame late. */
+const GRID_SLACK = 1e-3;
+
+/** The first output frame at or after `t` seconds. */
+export const gridFrame = (t: number, fps: number) => Math.ceil(t * fps - GRID_SLACK);
+
+/** The output frames `[first, last)` a footprint holds once the grid moves
+ * it, and the window that shows exactly those: half a frame either side, so
+ * no frame time sits on an edge. */
+export interface HeldFrames {
+ first: number;
+ last: number;
+ from: number;
+ to: number;
+}
+
+/**
+ * For each footprint on one lane, sorted by start and never overlapping, the
+ * frames it holds when the grid moves it, else null: it shows over its own
+ * footprint. A footprint with no frame of its own takes the one at or after
+ * its start, and a neighbor that frame belonged to starts one later.
+ *
+ * Example at 30 fps: [0.01, 0.0267) holds frame 1 (t = 0.0333), and a clip
+ * from 0.0267 that would have opened on frame 1 opens on frame 2.
+ */
+export function heldFrames(
+ items: readonly { start: number; end: number }[],
+ fps: number
+): (HeldFrames | null)[] {
+ let taken = -Infinity;
+ return items.map(({ start, end }) => {
+ const own = gridFrame(start, fps);
+ const ownEnd = gridFrame(end, fps);
+ const first = Math.max(own, taken);
+ const last = Math.max(first + 1, ownEnd);
+ taken = last;
+ if (first === own && last === ownEnd) {
+ return null;
+ }
+ return { first, last, from: (first - 0.5) / fps, to: (last - 0.5) / fps };
+ });
+}
+
+/** Whether a footprint shows at `t`, read through its held frames when the
+ * grid moved it. */
+export const showsAt = (start: number, end: number, held: HeldFrames | null, t: number) =>
+ held ? t >= held.from && t < held.to : t >= start && t < end;
+
+/**
+ * The elements with every footprint the grid moves at `fps` widened onto the
+ * frames it holds, lane by lane. A pushed start moves to its first frame; an
+ * end moves out to the frame after its last. Sound effects carry no picture
+ * and hidden elements show nothing, so neither holds a frame.
+ */
+export function holdOverlays<O extends Overlay>(overlays: O[], fps: number): O[] {
+ const pictured = (o: O) => !o.hidden && !(isEffectOverlay(o) && isAudioEffect(o.effect));
+
+ // Each lane in start order, so a held element pushes the one after it.
+ const lanes = new Map<number, O[]>();
+ for (const o of overlays) {
+ if (!pictured(o)) {
+ continue;
+ }
+ const lane = lanes.get(laneOf(o)) ?? [];
+ lane.push(o);
+ lanes.set(laneOf(o), lane);
+ }
+ const moved = new Map<O, O>();
+ for (const lane of lanes.values()) {
+ lane.sort((a, b) => a.start - b.start);
+ heldFrames(lane, fps).forEach((held, i) => {
+ if (!held) {
+ return;
+ }
+ const o = lane[i];
+ moved.set(o, {
+ ...o,
+ start: held.first > gridFrame(o.start, fps) ? held.from : o.start,
+ end: held.last > gridFrame(o.end, fps) ? held.to : o.end,
+ });
+ });
+ }
+ return moved.size ? overlays.map((o) => moved.get(o) ?? o) : overlays;
+}
diff --git a/site/src/cut/lib/framePlan.test.ts b/site/src/cut/lib/framePlan.test.ts
index b0b4e1dc..a2dc817d 100644
--- a/site/src/cut/lib/framePlan.test.ts
+++ b/site/src/cut/lib/framePlan.test.ts
@@ -3,12 +3,16 @@ import {
clipAnimFx,
crossHandles,
duckGainAt,
+ heldSpans,
+ overlayPlan,
overlayTransitionFx,
prerollLead,
PREROLL_LEAD_S,
soundCrossGain,
+ trackZeroAt,
trackZeroPlan,
} from "./framePlan";
+import { heldFrames } from "./frameGrid";
import { TRANSITION_BLUR, TRANSITION_ZOOM } from "./types";
import type { AudioClip, ClipSpan, MediaAsset, VideoClip } from "./types";
@@ -351,3 +355,30 @@ describe("prerollLead", () => {
}
});
});
+
+describe("one-frame clips on a 30 fps export", () => {
+ /** Spans of the given lengths laid end to end from `from`. */
+ const laid = (from: number, lens: number[], track = 0): ClipSpan[] => {
+ let at = from;
+ return lens.map((len) => {
+ const span = { clip: videoClip({ start: at, out: len, track }), asset, start: at, len, transitionOut: 0, soundOut: 0, soundAhead: 0, soundBack: 0 };
+ at += len;
+ return span;
+ });
+ };
+
+ test("a track-0 flash between two output frames shows its first picture on the next one", () => {
+ const spans = laid(0, [0.01, 1 / 60, 2]);
+ const held = heldFrames(spans.map((sp) => ({ start: sp.start, end: sp.start + sp.len })), 30);
+ expect(trackZeroAt(spans, held, 1 / 30)).toEqual({ span: spans[1], at: spans[1].start });
+ expect(trackZeroAt(spans, held, 2 / 30)?.span).toBe(spans[2]);
+ });
+
+ test("an upper-track flash between two output frames holds the next one", () => {
+ const spans = laid(0.01, [1 / 60, 2], 1);
+ const held = heldSpans(spans, 30);
+ const live = (t: number) => overlayPlan([1], () => spans, t, held);
+ expect(live(1 / 30).map((l) => [l.span, l.at])).toEqual([[spans[0], spans[0].start]]);
+ expect(live(2 / 30).map((l) => l.span)).toEqual([spans[1]]);
+ });
+});
diff --git a/site/src/cut/lib/framePlan.ts b/site/src/cut/lib/framePlan.ts
index 9170ef9b..95fb54c3 100644
--- a/site/src/cut/lib/framePlan.ts
+++ b/site/src/cut/lib/framePlan.ts
@@ -18,6 +18,7 @@ import { headSrc, retimeOf } from "@donkeycut/effects-kit";
* watched the download.
*/
+import { heldFrames, showsAt, type HeldFrames } from "./frameGrid";
import { CLIP_MIN_SECONDS, overlayAnimStyle, TRANSITION_BLUR, TRANSITION_ZOOM } from "./types";
import type { AudioClip, ClipAnim, ClipSpan, MediaAsset, TransitionStyle, VideoClip } from "./types";
@@ -439,6 +440,32 @@ export function trackZeroPlan(master: ClipSpan, spans: ClipSpan[], t: number): T
};
}
+/** The time a span's picture is read at for a frame at `t`: its first
+ * picture while it holds a frame past its own end. */
+const pictureAt = (sp: ClipSpan, t: number) => (t < sp.start + sp.len ? t : sp.start);
+
+/**
+ * The track-0 span a frame at `t` shows, and the time its picture is read at.
+ * `held` is the track's held frames on an export grid (empty off one), so a
+ * clip shorter than a frame still shows on one.
+ */
+export function trackZeroAt(
+ spans: ClipSpan[],
+ held: readonly (HeldFrames | null)[],
+ t: number
+): { span: ClipSpan; at: number } | null {
+ const i = spans.findIndex((sp, k) => showsAt(sp.start, sp.start + sp.len, held[k] ?? null, t));
+ return i < 0 ? null : { span: spans[i], at: pictureAt(spans[i], t) };
+}
+
+/** The held frames of an upper track's shown spans on an `fps` grid, for
+ * `overlayPlan`. A render works them out once, before its first frame. */
+export function heldSpans(spans: ClipSpan[], fps: number): Map<ClipSpan, HeldFrames | null> {
+ const shown = spans.filter((sp) => !sp.clip.hidden);
+ const held = heldFrames(shown.map((sp) => ({ start: sp.start, end: sp.start + sp.len })), fps);
+ return new Map(shown.map((sp, k) => [sp, held[k]]));
+}
+
/** One upper-track clip on screen, with its ramps resolved. */
export interface OverlayPlanItem {
span: ClipSpan;
@@ -447,6 +474,9 @@ export interface OverlayPlanItem {
alpha: number;
zoom: number;
gain: number;
+ /** The time its picture is read at: `t`, or its start while it holds an
+ * output frame past its own end. */
+ at: number;
}
/**
@@ -455,12 +485,15 @@ export interface OverlayPlanItem {
* incoming clip in over the outgoing one.
*
* `spansOf` supplies a track's spans; callers pass the store's own
- * `getClipSpans` so span geometry is computed one way everywhere.
+ * `getClipSpans` so span geometry is computed one way everywhere. An export
+ * passes its tracks' `heldSpans`, so a clip shorter than an output frame
+ * holds one.
*/
export function overlayPlan(
tracks: number[],
spansOf: (track: number) => ClipSpan[],
- t: number
+ t: number,
+ held?: ReadonlyMap<ClipSpan, HeldFrames | null>
): OverlayPlanItem[] {
const live: OverlayPlanItem[] = [];
for (const track of [...tracks].sort((a, b) => a - b)) {
@@ -468,12 +501,13 @@ export function overlayPlan(
for (let i = 0; i < spans.length; i++) {
const sp = spans[i];
if (sp.clip.hidden) continue;
- if (t < sp.start || t >= sp.start + sp.len) continue;
+ if (!showsAt(sp.start, sp.start + sp.len, held?.get(sp) ?? null, t)) continue;
live.push({
span: sp,
clip: sp.clip,
asset: sp.asset,
...overlayTransitionFx(sp, spans[i - 1], spans[i + 1], t),
+ at: pictureAt(sp, t),
});
}
}
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index ecefdede..692ba3ad 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -48,8 +48,9 @@ export const isLinkedAssetType = (type: string): type is LinkedAssetType =>
export const IMAGE_CLIP_SECONDS = 8;
/** The shortest clip, seconds: one frame at 60 fps, a flash frame. Every
- * renderer floors a clip's footprint here, so a one-frame clip plays one
- * frame in the preview and in every export. */
+ * renderer floors a clip's footprint here, and an export at a lower rate
+ * shows a shorter clip on the output frame at or after its start
+ * (`frameGrid.ts`), so a flash frame never drops out of a file. */
export const CLIP_MIN_SECONDS = 1 / 60;
/** Project output frame ratio as "W:H". Presets cover common platforms;
diff --git a/site/src/cut/server/exportPipeline.e2e.test.ts b/site/src/cut/server/exportPipeline.e2e.test.ts
index f33e6279..34dfcfe7 100644
--- a/site/src/cut/server/exportPipeline.e2e.test.ts
+++ b/site/src/cut/server/exportPipeline.e2e.test.ts
@@ -430,3 +430,56 @@ describe("a long recording cut out of order", () => {
240_000
);
});
+
+describe("a flash shorter than an output frame", () => {
+ // A 1/60 s red shot on track 1 at 0.01s sits between frames 0 and 1 of a
+ // 30 fps file; a blue shot follows it. The red holds frame 1 and the blue
+ // opens on frame 2, over black on track 0.
+ test.skipIf(!tools)(
+ "holds the frame after its start, and the shot after it opens one later",
+ async () => {
+ const mediaDir = await mkdtemp(path.join(os.tmpdir(), "cut-e2e-media-"));
+ const tmpDir = await mkdtemp(path.join(os.tmpdir(), "cut-e2e-job-"));
+ try {
+ const solid = (name: string, c: string) =>
+ ff(["-f", "lavfi", "-i", `color=c=${c}:s=64x64:r=60:d=1`, "-pix_fmt", "yuv420p", path.join(mediaDir, name)]);
+ solid("black.mp4", "black");
+ solid("red.mp4", "red");
+ solid("blue.mp4", "blue");
+ const flash = 1 / 60;
+ const spec: ExportSpec = {
+ projectId: "p",
+ width: 64,
+ height: 64,
+ fps: 30,
+ crf: 18,
+ preset: "veryfast",
+ duration: 0.5,
+ clips: [{ file: "black.mp4", in: 0, out: 0.5, muted: true }],
+ overlayVideos: [
+ { file: "red.mp4", in: 0, out: flash, start: 0.01, track: 1, muted: true },
+ { file: "blue.mp4", in: 0, out: 0.4, start: 0.01 + flash, track: 1, muted: true },
+ ],
+ audio: [],
+ overlays: [],
+ };
+ const job: RenderHandle = { tmpDir, outPath: path.join(tmpDir, "out.mp4"), stemsPath: path.join(tmpDir, "stems.zip"), progress: 0, log: [] };
+ await runExport(job, spec, (file) => path.join(mediaDir, file));
+ // A middle pixel of each of the first four frames, as RGB (a 2x2 crop:
+ // 4:2:0 frames crop on even edges).
+ const px = new Uint8Array(
+ ffmpegOut(["-i", job.outPath, "-frames:v", "4", "-vf", "crop=2:2:32:32", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
+ );
+ const hue = (k: number) => {
+ const [r, g, b] = px.slice(k * 12, k * 12 + 3);
+ return r > 150 && b < 100 ? "red" : b > 150 && r < 100 ? "blue" : r < 40 && g < 40 && b < 40 ? "black" : `${r},${g},${b}`;
+ };
+ expect([0, 1, 2, 3].map(hue)).toEqual(["black", "red", "blue", "blue"]);
+ } finally {
+ await rm(mediaDir, { recursive: true, force: true });
+ await rm(tmpDir, { recursive: true, force: true });
+ }
+ },
+ 60_000
+ );
+});
diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.ts
index dbaf92f4..3dd8f4b8 100644
--- a/site/src/cut/server/exportPipeline.test.ts
+++ b/site/src/cut/server/exportPipeline.test.ts
@@ -2018,3 +2018,23 @@ describe("windows on floored times", () => {
}
});
});
+
+describe("clips shorter than an output frame", () => {
+ test("an upper-track flash between two frames holds the next one, and the clip after it waits", async () => {
+ const g = (
+ await graphFor({
+ clips: [clip("a.mp4", { out: 2 })],
+ overlayVideos: [
+ { file: "o.mp4", in: 0, out: 1 / 60, start: 0.01, track: 1, muted: true },
+ { file: "o.mp4", in: 1, out: 2, start: 0.01 + 1 / 60, track: 1, muted: true },
+ ],
+ })
+ ).join(";");
+ // Frame 1 (0.0333s) belongs to the flash alone: one held frame from it,
+ // shown half a frame either side of that frame's time.
+ expect(g).toContain("trim=end_frame=1,setpts=PTS-STARTPTS,fps=30,tpad=start=1");
+ expect(g).toContain(`between(t,${(0.5 / 30).toFixed(6)},${(1.5 / 30).toFixed(6)})`);
+ // The clip after it opens on frame 2.
+ expect(g).toContain(`between(t,${(1.5 / 30).toFixed(6)},`);
+ });
+});
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index be8c9276..ac1d9671 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -18,6 +18,7 @@ import { shiftSpan, type SpecSound } from "../lib/soundSource";
import { masterRawMix, packStems } from "./exportAudio";
import { STEM_CHANNELS, STEM_RATE, type StemDef } from "../lib/stems";
import { CLIP_MAX_ZOOM, CLIP_MIN_SECONDS, clipFrameAt, regionPx, TRANSITION_ZOOM, type ColorGrade } from "../lib/types";
+import { gridFrame, heldFrames, type HeldFrames } from "../lib/frameGrid";
import { audioFxFilters, buildClipLut, elementLook, buildTransferLut, CLARITY_EPS, compositeSpaceFor, detailActive, detailGain, detailRadius, effectFilterLines, effectRecipe, type FlashFade, type FlashRhythm, type FlashTone, type GlitchKind, type LeakCourse, graphicsToHlg, hexToHlgHex, hlgToPq, isAudioEffect, lookFilterLines, lutToCube, mirrorRetimable, parseLutFile, recipeKey, retimeOf, shortestTurn, slowRuns, srcSpan, sortedKeys, soundFilters, type ChainChroma, type ClipColorRecipe, type ClipEffect, type ClipSound, type CodeFormat, type EaseId, type OutputSpace, type OverlayKey, type ParsedLut, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
// The render pipeline itself: spec in, finished mp4 out. Shared by the local
@@ -735,13 +736,6 @@ function concatList(holds: { file: string; to: number }[], fps: number): string
return lines.join("\n") + "\n";
}
-/** How far past a whole frame a time may sit, in frames, and still count as
- * on it: rounding in a sum of clip lengths never pushes a cut a frame late. */
-const GRID_SLACK = 1e-3;
-
-/** The first output frame at or after `t` seconds. */
-const gridFrame = (t: number, fps: number) => Math.ceil(t * fps - GRID_SLACK);
-
/** Filters that hold a stream to exactly `count` frames at `fps`: a short
* one repeats its last frame, a long one is cut. */
const gridHold = (count: number, fps: number) =>
@@ -1326,6 +1320,15 @@ async function renderPass(
const overlayVideos = [...(spec.overlayVideos ?? [])].sort(
(a, b) => a.track - b.track || a.start - b.start
);
+ // The frames each upper-track clip shorter than an output frame holds,
+ // track by track, and the frame its neighbor then opens on.
+ const overlayHeld = new Map<(typeof overlayVideos)[number], HeldFrames>();
+ for (const track of new Set(overlayVideos.map((oc) => oc.track))) {
+ const lane = overlayVideos.filter((oc) => oc.track === track);
+ heldFrames(lane.map((oc) => ({ start: oc.start, end: oc.start + spanLen(oc) })), spec.fps).forEach((held, i) => {
+ if (held) overlayHeld.set(lane[i], held);
+ });
+ }
// Every bare patch of frame in the graph — the letterbox around a fitted
// clip, a gap on track 0, the backdrop behind an edge animation — is the
// project's own background color. ffmpeg takes it as 0xRRGGBB.
@@ -3073,9 +3076,17 @@ async function renderPass(
// The clip's first frame is the first one at or after its start, as on
// track 0. The zoom slices' concat drops the stream's frame-rate
// metadata, so the fps re-stamp keeps tpad's frames on the grid.
- filters.push(`[${masked}]fps=${fps},tpad=start=${gridFrame(oc.start, fps)}[${seg}]`);
+ // A clip the grid moved holds exactly its frames from its first picture.
+ const held = overlayHeld.get(oc);
+ filters.push(
+ held
+ ? `[${masked}]fps=${fps},${gridHold(held.last - held.first, fps)},tpad=start=${held.first}[${seg}]`
+ : `[${masked}]fps=${fps},tpad=start=${gridFrame(oc.start, fps)}[${seg}]`
+ );
const next = `vovv${k}`;
- const enable = `enable='between(t,${edge(oc.start)},${edge(end)})'`;
+ const enable = held
+ ? `enable='between(t,${edge(held.from)},${edge(held.to)})'`
+ : `enable='between(t,${edge(oc.start)},${edge(end)})'`;
// The shadow falls on whatever is already there, then the clip goes down
// over it. Its silhouette is punched out, so the two never fight.
const oshIdx = overlayShadowInput.get(oc);