Skip to content

Open source CapCut alternative.

TypeScript

fix(site): scale the preview pre-roll to the source ahead of the in-point

David Leec53ad6abb56
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index af4d223e..2100b7d7 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -5,7 +5,7 @@ import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } fr
import { isFullRect, projectFadeSeconds, rectOf } from "@/cut/lib/types";
import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
import { FrameCompositor, MISSING_FRAME, PENDING_FRAME, type Frame } from "@/cut/lib/composite";
-import { duckGainAt, overlayPlan, PREROLL_LEAD_S, trackZeroPlan } from "@/cut/lib/framePlan";
+import { duckGainAt, overlayPlan, prerollLead, trackZeroPlan } from "@/cut/lib/framePlan";
import { reportMediaElementError } from "@/cut/lib/mediaLinks";
import { registerSourceSampler } from "@/cut/lib/previewCanvas";
@@ -54,11 +54,12 @@ const DECODER_STALL_MS = 10_000;
const DECODER_RETRY_MS = 1_000;
const DECODER_REBUILDS = 3;
-// Inside PREROLL_LEAD_S of a clip's entrance its element is played muted and
-// undrawn, so the decoder is already running across the in-point when the cut
-// lands and the handoff play() resumes hot instead of spinning a cold decoder
-// up. The lead itself is part of the frame plan, which is what decides when a
-// clip is about to be needed.
+// Ahead of a clip's entrance its element is played muted and undrawn, so the
+// decoder is already running across the in-point when the cut lands and the
+// handoff play() resumes hot instead of spinning a cold decoder up. How long
+// that roll gets is `prerollLead`, and when a clip is close enough to be worth
+// keeping alive is the frame plan's `upcoming` — both live there, so the
+// picture and the decoders agree on when a clip is about to be needed.
const pauseEl = (el: MediaEl) => {
if (!isImageEl(el) && !el.paused) el.pause();
@@ -221,18 +222,22 @@ class Engine {
for (const span of spans) {
if (span.start <= t) continue; // current or past — not ours to warm
if (span.start > t + WARM_HORIZON_S) break;
- // The imminent clip inside the pre-roll window is `warmNext`'s to play
- // hot; a parking seek here would fight it, so leave it alone.
- if (span.start - t <= PREROLL_LEAD_S) continue;
+ const speed = clipSpeed(span.clip);
+ const lead = prerollLead(span.clip.in, speed);
+ // The imminent clip inside its own pre-roll window is `warmNext`'s to
+ // play hot; a parking seek here would fight it, so leave it alone. A clip
+ // with no roll to give (an untrimmed one) has no such window, and stays
+ // parked here right up to the cut.
+ if (lead > 0 && span.start - t <= lead) continue;
const el = this.videoFor(span.clip, span.asset); // creating it starts the fetch
// Park a not-yet-imminent clip exactly where the pre-roll will play from
// (`warmNext`'s `from`), not on its entrance frame: parking at `in` and
- // then seeking back `PREROLL_LEAD_S` for the roll-in discards the warmed
- // buffer, and over the network (cloud media) that late re-seek is what
- // used to stall the handoff. Parked here, the pre-roll's seek is a no-op
- // on already-buffered bytes and the cut lands hot.
+ // then seeking back for the roll-in discards the warmed buffer, and over
+ // the network (cloud media) that late re-seek is what used to stall the
+ // handoff. Parked here, the pre-roll's seek is a no-op on already-buffered
+ // bytes and the cut lands hot.
if (!isImageEl(el) && !el.seeking && el.paused) {
- const target = Math.max(0, span.clip.in - PREROLL_LEAD_S * clipSpeed(span.clip));
+ const target = span.clip.in - lead * speed;
if (Math.abs(el.currentTime - target) > 0.1) el.currentTime = target;
}
if (++warmed >= WARM_MAX) break;
@@ -271,18 +276,21 @@ class Engine {
private warmNext(span: ClipSpan, t: number) {
const el = this.videoFor(span.clip, span.asset);
if (isImageEl(el)) return; // a still needs no pipeline
- // Farther out than the lead: leave it parked and buffering (warmAhead's job).
- if (t < span.start - PREROLL_LEAD_S) return;
const speed = clipSpeed(span.clip);
+ // Only as long a roll as there is source ahead of the in-point to cover it
+ // — nothing at all for an untrimmed clip, which stays parked on its already
+ // hot keyframe 0 instead. Farther out than that, it is warmAhead's to park
+ // and buffer.
+ const lead = prerollLead(span.clip.in, speed);
+ if (t < span.start - lead) return;
const rate = safeRate(speed);
if (el.playbackRate !== rate) el.playbackRate = rate;
el.muted = true; // silent until it becomes master and unmutes
// Already rolling: let it run — it crosses `in` on its own as the cut lands.
if (!el.paused) return;
// Seat it `lead` of source before the entrance, then play forward so it
- // reaches `in` right as the playhead reaches the cut. Bounded at 0 for an
- // untrimmed clip, whose keyframe-0 start is already hot.
- const from = Math.max(0, span.clip.in - PREROLL_LEAD_S * speed);
+ // reaches `in` right as the playhead reaches the cut.
+ const from = span.clip.in - lead * speed;
if (!el.seeking && Math.abs(el.currentTime - from) > 0.1) el.currentTime = from;
if (el.readyState >= 2 && !el.seeking) void el.play().catch(() => {});
}
diff --git a/site/src/cut/lib/framePlan.test.ts b/site/src/cut/lib/framePlan.test.ts
index ef9c37f0..5f2a8f95 100644
--- a/site/src/cut/lib/framePlan.test.ts
+++ b/site/src/cut/lib/framePlan.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { clipAnimFx, duckGainAt, trackZeroPlan } from "./framePlan";
+import { clipAnimFx, duckGainAt, prerollLead, PREROLL_LEAD_S, trackZeroPlan } from "./framePlan";
import { TRANSITION_ZOOM } from "./types";
import type { AudioClip, ClipSpan, MediaAsset, VideoClip } from "./types";
@@ -183,3 +183,46 @@ describe("duckGainAt", () => {
expect(duckGainAt([voice({ hidden: true })], 2)).toBe(1);
});
});
+
+describe("prerollLead", () => {
+ // The roll seats the element `lead × speed` of source before the in-point and
+ // plays forward for `lead` of timeline, so it arrives exactly at `in` as the
+ // cut lands. Both halves come from this one number: hold the roll at a fixed
+ // length and the seat has to clamp at 0, which lands the element past `in` and
+ // makes the handoff seek backwards — a decoder restart at every join.
+ const cases: [number, number][] = [
+ [0, 1],
+ [0.2, 1],
+ [3, 1],
+ [0.6, 2],
+ [4, 0.5],
+ ];
+
+ test("gives a trimmed clip the full lead", () => {
+ expect(prerollLead(3, 1)).toBeCloseTo(PREROLL_LEAD_S, 5);
+ });
+
+ test("gives an untrimmed clip none — there is no source to roll through", () => {
+ expect(prerollLead(0, 1)).toBe(0);
+ });
+
+ test("shortens the roll to the source a barely-trimmed clip has", () => {
+ expect(prerollLead(0.2, 1)).toBeCloseTo(0.2, 5);
+ });
+
+ test("scales with the clip's speed", () => {
+ // At 2×, half a second of timeline eats a second of source, so a clip with
+ // 0.6s ahead of its in-point can only roll for 0.3s.
+ expect(prerollLead(0.6, 2)).toBeCloseTo(0.3, 5);
+ expect(prerollLead(4, 2)).toBeCloseTo(PREROLL_LEAD_S, 5);
+ });
+
+ test("seats the roll inside the source and lands it on the in-point", () => {
+ for (const [inPoint, speed] of cases) {
+ const lead = prerollLead(inPoint, speed);
+ const seat = inPoint - lead * speed;
+ expect(seat).toBeGreaterThanOrEqual(0);
+ expect(seat + lead * speed).toBeCloseTo(inPoint, 5);
+ }
+ });
+});
diff --git a/site/src/cut/lib/framePlan.ts b/site/src/cut/lib/framePlan.ts
index 55d43778..7006caf4 100644
--- a/site/src/cut/lib/framePlan.ts
+++ b/site/src/cut/lib/framePlan.ts
@@ -226,6 +226,21 @@ export interface TrackZeroPlan {
/** How long before a clip's entrance its decoder should be spun up. */
export const PREROLL_LEAD_S = 0.5;
+/**
+ * How long the pre-roll for this clip can actually run, in timeline seconds.
+ *
+ * The roll plays the element forward so it arrives at the in-point exactly as
+ * the cut lands, which it can only do where there is source ahead of that point
+ * to play through: a trimmed clip gets the full lead, one that starts at 0 gets
+ * none. Rolling for longer than the source allows leaves the element that far
+ * past its in-point when the cut lands, and the handoff seeks back to reach it —
+ * restarting the decoder at the join, which is the hitch the pre-roll exists to
+ * remove.
+ */
+export function prerollLead(inPoint: number, speed: number): number {
+ return Math.max(0, Math.min(PREROLL_LEAD_S, inPoint / speed));
+}
+
/**
* Work out track 0's state at time `t`: the transition live across the join,
* the master clip's own entrance/exit ramps, and the neighbour frame that