Skip to content

Open source CapCut alternative.

TypeScript

fix(site): the preview holds the picture to the clock its sound leaves on

David Lef2d25240a4d9
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index 519bba84..3545c46d 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -14,9 +14,10 @@ import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
import { SubjectMaskCompositor } from "@/cut/lib/behindPass";
import { FrameCompositor, MISSING_FRAME, PENDING_FRAME, type Frame } from "@/cut/lib/composite";
import { duckGainAt, overlayPlan, trackZeroPlan } from "@/cut/lib/framePlan";
-import { type ClipFrameSource, FrameSourcePool, mappingKey } from "@/cut/lib/frameSource";
+import { type ClipFrameSource, FrameSourcePool, mappingKey, walkCostMs } from "@/cut/lib/frameSource";
import { PreviewMixer, type Voice } from "@/cut/lib/previewMixer";
import {
+ markAudioClock,
markLiveSamples,
markLiveSources,
markPresent,
@@ -45,10 +46,20 @@ import { registerSourceSampler } from "@/cut/lib/previewCanvas";
/** How far ahead of the playhead a clip's decoder is opened and started. */
const WARM_HORIZON_S = 2.5;
-/** Inside this, an upcoming clip is walked rather than merely opened. */
+/** Inside this, an upcoming clip is walked as well as opened. */
const WARM_STREAM_S = 0.75;
-/** Decoders alive at once. Past the tab's hardware decode slots the rest fall
- * back to software, and frames start arriving late. */
+/**
+ * Decoders alive at once.
+ *
+ * Past the tab's hardware decode slots the rest fall back to software, where
+ * they are the same processor split further, so it reads as a number that
+ * should shrink on a machine with few slots. It does not. Shrinking it makes
+ * a fast cut suspend and reopen sources it is about to need again, and a
+ * reopen on such a machine costs a fresh decoder and a full walk from the
+ * keyframe — the expensive thing, paid repeatedly. Measured on the eval's
+ * few-slot profiles, cutting this to six moved late frames from 42% to 52%
+ * and turned a flat play into one that decayed across its length.
+ */
const DECODER_BUDGET = 12;
/** Source time of a clip at timeline time `t`. */
@@ -91,6 +102,7 @@ class Engine {
/** The playhead value the engine itself wrote last, so its own echo is
* tellable from an outside move — a seek while playing. */
private written: number | null = null;
+ private lastWalkCost = 0;
private unsubscribe: () => void;
private unwatch: () => void;
@@ -132,6 +144,11 @@ class Engine {
* decode slots in a second. Rounding up keeps the identity still while the
* box moves and never decodes below display size, and the step is small
* enough that the extra rows decoded above it stay cheap.
+ *
+ * It holds still for the life of the engine for a second reason: the pool
+ * keys on it, so moving it mid-play abandons every open decoder at once and
+ * pays a fresh keyframe walk for each — on the machines this would be meant
+ * to help, that storm costs far more than the pixels it saves.
*/
private decodeHeight(): number {
return Math.ceil(this.canvas.height / 180) * 180 || 180;
@@ -213,6 +230,13 @@ class Engine {
* the overlay tracks alike — so a cut or an overlay's entrance lands on a
* ring that is already full. */
private warm(t: number, playing: boolean) {
+ if (process.env.NODE_ENV !== "production") {
+ const cost = walkCostMs();
+ if (cost && cost !== this.lastWalkCost) {
+ this.lastWalkCost = cost;
+ engineLog(`walk cost ${cost}ms`);
+ }
+ }
const s = useEditor.getState();
const lists = [getClipSpans(s.clips, s.assets)];
for (const track of new Set(overlayLayers(s.clips).map((c) => c.track))) {
@@ -548,6 +572,8 @@ class Engine {
stale: masterFrame.kind !== "ready",
});
markLiveSamples(this.pool.held);
+ const clock = this.mixer.clockLead();
+ markAudioClock(clock.lead, clock.reported);
markLiveSources(this.pool.active, this.pool.size, this.pool.warmPixels);
}
}
diff --git a/site/src/cut/lib/devHooks.ts b/site/src/cut/lib/devHooks.ts
index dcb6afe6..f16adeb6 100644
--- a/site/src/cut/lib/devHooks.ts
+++ b/site/src/cut/lib/devHooks.ts
@@ -11,7 +11,7 @@ import { renderProjectToMp4 } from "./exportRender";
import { useGenerate } from "./generate";
import { useGenScene } from "./genScene";
import { edgeFramesPending, enrichAsset, importFileToProject } from "./media";
-import { awaitingFrame, startTrace, stopTrace } from "./perfTrace";
+import { awaitingFrame, startTrace, stopTrace, traceReport } from "./perfTrace";
import { playheadAt } from "./playhead";
import { projectDuration, useEditor } from "./store";
@@ -38,5 +38,10 @@ export function installDevHooks(): void {
start: startTrace,
stop: stopTrace,
awaiting: awaitingFrame,
+ /** Stop recording and answer with the summary. */
+ report: () => {
+ const trace = stopTrace();
+ return trace ? traceReport(trace) : null;
+ },
};
}
diff --git a/site/src/cut/lib/frameSource.ts b/site/src/cut/lib/frameSource.ts
index fc73d1f7..4d86096e 100644
--- a/site/src/cut/lib/frameSource.ts
+++ b/site/src/cut/lib/frameSource.ts
@@ -60,17 +60,58 @@ const POOL = RING + 2;
* playhead and the decoder would burn through the file to put it there.
*/
export const DECODE_AHEAD_S = 0.3;
-/** How far past a walk's last landed frame the playhead may read before the
- * walk is re-anchored there. A walk running behind still lands frames — the
- * picture advances, a beat late — so it keeps walking while the lag stays
- * watchable, and hops forward to the playhead once the frames it lands are
- * history. */
+/**
+ * How far past a walk's last landed frame the playhead may read before the
+ * walk is re-anchored ahead of it.
+ *
+ * A walk running behind still lands frames — the picture advances, a beat
+ * late — so it keeps walking while the lag stays watchable, and hops forward
+ * once the frames it lands are history. The tolerance is wide because ending
+ * the lag costs a keyframe seek that lands nothing at all until it finishes:
+ * on the machine that trails in the first place, that seek is longer than the
+ * lag it would cure, and a walk restarted every time it slips runs that seek
+ * over and over while the picture sits frozen. Measured on the eval's few-slot
+ * profiles, tightening this to a fifth of a second took late frames from 8% to
+ * 52% and the worst lag from a tenth of a second to four tenths.
+ */
const LAG_HOP_S = 2;
+
/** How far the playhead may travel past a walk's start while its first frame
* is still decoding. That first step is a keyframe seek — every frame from the
* keyframe to the start decodes before one lands — and a restart pays the
* whole seek again from scratch, so a slow decoder gets room to finish it. */
const FIRST_FRAME_S = 4;
+/**
+ * How long recent walks took to land their first frame, newest last.
+ *
+ * A walk begins at the keyframe before the time asked for and decodes forward
+ * to it, so this is the real price of reaching a clip that is not already
+ * open — and it is the number that separates one machine from another far
+ * better than any count of cores. With hardware decode behind it a walk lands
+ * in a fraction of the time it takes to play the clip. With every stream on
+ * the CPU, and a keyframe a couple of seconds back, the same walk can take
+ * longer than the clip is on screen. The median over a dozen of them is what
+ * the engine's log reports, and it is the first thing to read when a preview
+ * is stuttering on a machine that is not this one.
+ */
+const WALK_COSTS: number[] = [];
+const WALK_SAMPLES = 12;
+/** Walks timed before the median is worth reading. */
+const WALK_MIN = 4;
+
+function noteWalkCost(ms: number): void {
+ WALK_COSTS.push(ms);
+ if (WALK_COSTS.length > WALK_SAMPLES) WALK_COSTS.shift();
+}
+
+/** The median time a recent walk took to land its first frame, in
+ * milliseconds; zero until enough of them have been timed to mean anything. */
+export function walkCostMs(): number {
+ if (WALK_COSTS.length < WALK_MIN) return 0;
+ const xs = [...WALK_COSTS].sort((a, b) => a - b);
+ return Math.round(xs[xs.length >> 1]);
+}
+
/** Two source times closer than this are the same frame. */
const SAME = 1e-4;
/** Frames the backward-skim cache keeps of one span: the span is decoded once
@@ -299,6 +340,10 @@ export class ClipFrameSource {
private stream: AsyncGenerator<WrappedCanvas, void, unknown> | null = null;
private streamFrom = 0;
private streamTail = 0;
+ /** When the current walk was started, and whether it has landed anything
+ * yet, for timing what reaching a clip costs on this machine. */
+ private walkAt = 0;
+ private walkFirst = false;
/** The walk ran off the end of the file. Its span is still the truth — there
* are no frames past its tail to decode — so a reader inside it must not
* keep restarting a walk that can only end again. */
@@ -636,14 +681,11 @@ export class ClipFrameSource {
// Whether the walk serves `t` is a question about the walk — where it
// started and the last frame it has landed. On a machine whose decoder
// trails real time the tail falls behind the playhead while frames keep
- // landing: the picture advances, a beat late. A restart there pays a
- // keyframe seek that lands nothing for even longer, and a walk held to a
- // tight deadline gets restarted before any such seek can finish — the
- // picture freezes solid while the playhead runs on the audio clock. So a
- // lagging walk keeps its claim until the frames it lands are history
- // (`LAG_HOP_S`), and a walk still decoding toward its first frame — mid
- // keyframe-seek, with nothing landed yet to show for it — gets the longer
- // `FIRST_FRAME_S`, since a restart would begin that same seek again.
+ // landing: the picture advances, a beat late. It keeps its claim until the
+ // frames it lands are history (`LAG_HOP_S`), and then re-anchors at the
+ // playhead. A walk still decoding toward its first frame — mid keyframe
+ // seek, nothing landed yet — gets the longer `FIRST_FRAME_S`, since a
+ // restart would begin that same seek again.
if (this.stream) {
// The walk serves `t` if the frame is already held, or if `t` reads at
// or past the walk's edge — the tail once frames have landed, its start
@@ -680,6 +722,8 @@ export class ClipFrameSource {
if (this.closed || !this.sink || this.stream) return;
// The read may have been overtaken while the file was opening.
if (Math.abs(this.streamFrom - from) > SAME) return;
+ this.walkAt = performance.now();
+ this.walkFirst = true;
this.stream = this.sink.canvases(Math.max(0, from));
void this.drain(from);
}
@@ -808,6 +852,10 @@ export class ClipFrameSource {
break;
}
this.streamTail = value.timestamp;
+ if (this.walkFirst) {
+ this.walkFirst = false;
+ noteWalkCost(performance.now() - this.walkAt);
+ }
this.ring.push(value);
this.onFrame();
}
diff --git a/site/src/cut/lib/perfTrace.ts b/site/src/cut/lib/perfTrace.ts
index ff4f5cb6..5e6fdab4 100644
--- a/site/src/cut/lib/perfTrace.ts
+++ b/site/src/cut/lib/perfTrace.ts
@@ -10,8 +10,10 @@
* frame" become numbers a script can hold to a budget.
*
* The trace is off until something arms it, and while it is off every call here
- * is a null check. The eval arms it through `window.__cutPerf`; nothing in the
- * product turns it on.
+ * is a null check. The perf eval arms it through `window.__cutPerf`, and so can
+ * a person on a machine we cannot reproduce: `__cutPerf.start()`, play the part
+ * that stutters, then `__cutPerf.report()` for a summary small enough to paste
+ * into a bug report. Nothing turns it on by itself.
*/
/** One composited frame that reached the canvas. */
@@ -26,9 +28,10 @@ export interface PresentRecord {
/**
* The source time the master layer was asked for.
*
- * With `srcTs` this is the whole sync story: sound is scheduled against the
- * same clock `t` comes from, so `wantSrc - srcTs` is how far the picture sits
- * behind the sound at that instant.
+ * With `srcTs` this is how far the picture sits behind the clock it is drawn
+ * against. That clock is the audible one — see `audioLead` for the separate
+ * question of whether the preview is reading it, which this cannot see: a
+ * picture drawn against the wrong clock is exactly on time against it.
*/
wantSrc: number | null;
/** The clip the master picture came from, so a boundary is findable. */
@@ -78,9 +81,40 @@ export interface Trace {
/** Megabytes of canvas backing on the warm shelf — the stood-down sources,
* which is the part the pool's memory budget governs. */
warmMb: number[];
+ /**
+ * Seconds the picture is held behind the graph's clock, and seconds the
+ * output device says it holds, sampled per present.
+ *
+ * A rendered sample has not been heard yet — it is in the buffer the device
+ * reads next — so the moment the picture belongs at is the rendered moment
+ * less that buffer. These two are read independently, one from the clock the
+ * preview actually uses and one from the device, and they should agree. A
+ * lead of zero against a device reporting otherwise is the picture running
+ * ahead of its own sound by however much the device holds, which is tens of
+ * milliseconds on CoreAudio and can be a fifth of a second on shared-mode
+ * WASAPI or a Bluetooth output.
+ */
+ audioLead: number[];
+ audioLatency: number[];
startedAt: number;
}
+/**
+ * Records one trace keeps of each kind.
+ *
+ * The eval's runs are a fraction of this. What it bounds is a recording left
+ * armed on a real machine: at sixty frames a second this is around twenty
+ * minutes, after which the oldest records fall off and the trace describes the
+ * most recent stretch — which is the stretch someone recording a stutter cares
+ * about.
+ */
+const CAP = 72_000;
+
+function keep<T>(xs: T[], x: T): void {
+ xs.push(x);
+ if (xs.length > CAP) xs.shift();
+}
+
/** Times equal within this are the same instant. Half a frame at 120fps —
* tight enough that a real lag never passes, loose enough that float drift on
* the timeline never fails. */
@@ -105,6 +139,8 @@ export function startTrace(): void {
liveSources: [],
keptSources: [],
warmMb: [],
+ audioLead: [],
+ audioLatency: [],
startedAt: performance.now(),
};
pendingSeek = null;
@@ -112,7 +148,7 @@ export function startTrace(): void {
try {
observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
- trace?.longTasks.push({ at: entry.startTime, ms: entry.duration });
+ if (trace) keep(trace.longTasks, { at: entry.startTime, ms: entry.duration });
}
});
observer.observe({ entryTypes: ["longtask"] });
@@ -136,7 +172,7 @@ export function stopTrace(): Trace | null {
export function markSeek(t: number): void {
if (!trace) return;
const rec: SeekRecord = { t, at: performance.now(), latencyMs: null };
- trace.seeks.push(rec);
+ keep(trace.seeks, rec);
pendingSeek = rec;
}
@@ -144,7 +180,7 @@ export function markSeek(t: number): void {
export function markPresent(rec: Omit<PresentRecord, "at">): void {
if (!trace) return;
const at = performance.now();
- trace.presents.push({ ...rec, at });
+ keep(trace.presents, { ...rec, at });
// A held or black frame is not an answer to the question the scrub asked —
// neither is the neighbouring frame drawn while the real one decodes. The
// clock keeps running until the frame that belongs at that time is on screen.
@@ -164,17 +200,91 @@ export function markTick(): void {
trace.ticks++;
}
+/** What the preview's clock is doing about the output device: how far the
+ * picture is being held back, and how far the device says it should be. */
+export function markAudioClock(lead: number, reported: number): void {
+ if (!trace) return;
+ keep(trace.audioLead, lead);
+ keep(trace.audioLatency, reported);
+}
+
/** How many decoded frames are being held open right now. */
export function markLiveSamples(n: number): void {
if (!trace) return;
- trace.liveSamples.push(n);
+ keep(trace.liveSamples, n);
}
/** What the decoder pool is holding right now: sources with a decoder, sources
* kept at all, and the canvas backing behind them. */
export function markLiveSources(active: number, kept: number, warmPixels: number): void {
if (!trace) return;
- trace.liveSources.push(active);
- trace.keptSources.push(kept);
- trace.warmMb.push(Math.round(warmPixels * 4e-6));
+ keep(trace.liveSources, active);
+ keep(trace.keptSources, kept);
+ keep(trace.warmMb, Math.round(warmPixels * 4e-6));
+}
+
+/** A trace boiled down to the numbers that name a stutter. */
+export interface TraceReport {
+ /** Seconds the recording covers, and frames painted in them. */
+ seconds: number;
+ presented: number;
+ /** Frames a second the preview actually held. */
+ fps: number;
+ /** Share of frames that were not the one belonging at that moment: the
+ * stutter, as the viewer sees it. */
+ late: number;
+ /** The same share over the first and last third, so a preview that decays
+ * across a session is tellable from one that was always this way. */
+ decay: { first: number; last: number };
+ /** Seconds the picture sat behind the moment asked for. */
+ lagP50: number;
+ lagP95: number;
+ lagMax: number;
+ /** Seconds the picture is held back for the output device, and what the
+ * device says it holds. These agree when the preview is reading the clock
+ * its sound leaves on; a lead of zero against a device holding a fifth of a
+ * second is a picture running that far ahead of its own audio. */
+ audioLeadS: number;
+ audioLatencyS: number;
+ /** Decoders open, frames held, and the canvas backing behind them. */
+ sources: number;
+ held: number;
+ warmMb: number;
+ /** The longest the main thread was blocked, in milliseconds. */
+ longTaskMs: number;
+}
+
+const pct = (xs: PresentRecord[]): number =>
+ xs.length ? +(xs.filter((p) => !p.exact || p.stale).length / xs.length).toFixed(3) : 0;
+
+const at = (xs: number[], q: number): number => {
+ if (!xs.length) return 0;
+ const sorted = [...xs].sort((a, b) => a - b);
+ return +sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))].toFixed(3);
+};
+
+/** Boil a trace down to something a person can paste into a bug report. */
+export function traceReport(t: Trace): TraceReport {
+ const presents = t.presents;
+ const span = presents.length ? (presents[presents.length - 1].at - presents[0].at) / 1000 : 0;
+ const lags = presents
+ .filter((p) => p.srcTs !== null && p.wantSrc !== null)
+ .map((p) => Math.max(0, p.wantSrc! - p.srcTs!));
+ const third = Math.floor(presents.length / 3);
+ return {
+ seconds: +span.toFixed(1),
+ presented: presents.length,
+ fps: span > 0 ? +(presents.length / span).toFixed(1) : 0,
+ late: pct(presents),
+ decay: { first: pct(presents.slice(0, third)), last: pct(presents.slice(-third)) },
+ lagP50: at(lags, 0.5),
+ lagP95: at(lags, 0.95),
+ lagMax: +Math.max(0, ...lags).toFixed(3),
+ audioLeadS: at(t.audioLead, 0.5),
+ audioLatencyS: at(t.audioLatency, 0.5),
+ sources: Math.max(0, ...t.liveSources),
+ held: Math.max(0, ...t.liveSamples),
+ warmMb: Math.max(0, ...t.warmMb),
+ longTaskMs: Math.round(Math.max(0, ...t.longTasks.map((l) => l.ms))),
+ };
}
diff --git a/site/src/cut/lib/previewMixer.ts b/site/src/cut/lib/previewMixer.ts
index 652723c0..1a679b08 100644
--- a/site/src/cut/lib/previewMixer.ts
+++ b/site/src/cut/lib/previewMixer.ts
@@ -33,6 +33,10 @@ const WINDOW_S = 20;
const WINDOW_STRETCHED_S = 4;
/** Schedule the next window once the playhead is this close to running out. */
const AHEAD_S = 2;
+/** Most the picture will be held back for the output device, whatever the
+ * device claims. Well past a Bluetooth headset, and short of anything that
+ * would read as the playhead refusing to move. */
+const MAX_LATENCY_S = 0.4;
/** One audible thing on the timeline: a clip's own sound, or a soundtrack item. */
export interface Voice {
@@ -103,12 +107,50 @@ export class PreviewMixer {
return this.ctx;
}
+ /**
+ * How far behind the graph's clock the sound is actually heard.
+ *
+ * `ctx.currentTime` is the moment the graph has *rendered* to, and a rendered
+ * sample has not left the machine yet: it is sitting in the output buffer the
+ * device will read next. `baseLatency` is what the graph itself holds and
+ * `outputLatency` is what the device does, and their sum is the gap between
+ * a sample being written and a person hearing it.
+ *
+ * The size of that gap is the platform's to decide, and platforms disagree by
+ * an order of magnitude. CoreAudio hands back something in the tens of
+ * milliseconds. WASAPI in shared mode — every Windows browser, by default —
+ * routinely holds several times that, and a Bluetooth output holds more
+ * again. A picture drawn against the unadjusted clock therefore runs ahead of
+ * its own sound by an amount that is invisible where this is developed and
+ * plainly wrong on the machines most people edit on.
+ *
+ * Capped, because the number comes from a driver: a device reporting
+ * something absurd would otherwise hold the picture at the play position for
+ * as long as it claimed.
+ */
+ private latency(): number {
+ const ctx = this.ctx;
+ if (!ctx) return 0;
+ const reported = (ctx.baseLatency || 0) + (ctx.outputLatency || 0);
+ return Math.min(MAX_LATENCY_S, Math.max(0, reported));
+ }
+
+ /** The moment leaving the speakers, given the moment the graph has rendered
+ * to. Held at the play position over the first buffer: the sound starts at
+ * once and the picture waits out the device rather than stepping backwards
+ * into what has already been heard. */
+ private heard(graph: number): number {
+ return Math.max(this.anchor?.timeline ?? 0, graph - this.latency());
+ }
+
/**
* Where the playhead is, from the sound's own clock.
*
* This is the whole point of the arrangement: the number the picture is drawn
* against comes from the same clock the samples leave on, so they cannot
- * drift apart no matter what the main thread is doing.
+ * drift apart no matter what the main thread is doing. Leaving is the word —
+ * what the graph has rendered is a buffer ahead of what is audible, and the
+ * picture is drawn against the audible one.
*/
now(): number {
if (!this.anchor) return 0;
@@ -121,8 +163,13 @@ export class PreviewMixer {
// until the audio clock agrees with it, and a clock that disagrees is
// re-anchored rather than believed.
if (!this.ctx || this.ctx.state !== "running") return wall;
- const audio = this.anchor.timeline + (this.ctx.currentTime - this.anchor.ctx);
- if (Math.abs(audio - wall) > 0.25) {
+ const graph = this.anchor.timeline + (this.ctx.currentTime - this.anchor.ctx);
+ // Measured on the graph's clock, which is the one the anchor was taken on.
+ // Comparing the heard clock against the wall would read the device's own
+ // buffer as drift and tear down every scheduled window to correct for it,
+ // which on the machines with the largest buffers is the loudest thing this
+ // class could do.
+ if (Math.abs(graph - wall) > 0.25) {
this.anchor.ctx = this.ctx.currentTime - (wall - this.anchor.timeline);
// Everything already scheduled was placed against the old anchor and is
// now wrong by the size of the jump — a context that sat suspended until
@@ -131,9 +178,27 @@ export class PreviewMixer {
// their full length, so they stop here and the next update refills from
// where the clock now stands.
this.restart(wall);
- return wall;
+ return this.heard(wall);
}
- return audio;
+ return this.heard(graph);
+ }
+
+ /**
+ * How far the picture is being held behind the graph's clock right now, and
+ * what the output device says it holds. Zero when nothing is playing.
+ *
+ * These are two independent readings of the same thing — one taken from what
+ * the clock actually returns, one from the device — and the perf eval holds
+ * them against each other. A preview that went back to drawing against the
+ * rendered clock reports a lead of zero on a device claiming a fifth of a
+ * second, which is the picture running that far ahead of its own sound.
+ */
+ clockLead(): { lead: number; reported: number } {
+ const ctx = this.ctx;
+ const reported = ctx ? (ctx.baseLatency || 0) + (ctx.outputLatency || 0) : 0;
+ if (!this.anchor || !ctx || ctx.state !== "running") return { lead: 0, reported };
+ const graph = this.anchor.timeline + (ctx.currentTime - this.anchor.ctx);
+ return { lead: Math.max(0, graph - this.heard(graph)), reported };
}
/** Stop every scheduled window and mark each voice to refill at `timeline`. */