Open source CapCut alternative.
TypeScript
perf(site): a big 4K file dropped from the library plays at once [rebuild]
David Lee5164d3843f6
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex a72556be..35047c34 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -60,6 +60,8 @@ A play whose clip has decoded nothing at all has nothing to play, and carrying tSome machines cannot decode the footage as fast as it plays, and no reader can invent frames that the decoder has not produced. Left alone that play never recovers: the sound goes on, the picture falls further behind with every second, and a minute in it is half a minute stale. So a preview that has stayed behind its sound for a few seconds decodes smaller from then on, and the picture catches up at a lower resolution. It is a trade taken once per play and never taken back — every open decoder is abandoned when the size changes and each source pays a fresh keyframe seek, so undoing it would cost more than the pixels are worth. Two things are excluded from it. The opening seconds of a play, where every machine trails while nothing is decoded yet and files are being opened, and a reader whose walk is waiting on bytes: decoding smaller does nothing for a picture that is late because the link has not delivered it, and the preview would end up softer for the rest of the session having gained nothing. The floor is 360, below which there is no picture worth keeping in sync.+A play is the urgent read. The reads behind the editor — a waveform, a filmstrip, a scene probe, the strip's tile captures — open the same file the preview is playing from, and on a big file they take what the picture needs: decoder slots, the link's width, the thread the frames are drawn on. A 4K recording dropped and played at once used to move the playhead over a picture that stood still, because four readers were decoding its keyframes beside the one walk that mattered. So that work waits for the play to stop and picks up where it was, publishing what it had reached; a clip-edge capture, which a trim is waiting on, still goes straight through. The Mac's shelf lands a clip without moving it, too: the engine clones the file into the project before the asset exists, so the first read opens the project's own copy and no reader ever holds the file at two addresses.+Decoders live in a bounded pool, and leaving the pool is suspension before it is closure: an idle source gives up its decoder but keeps the parsed file and the canvases its frames land on, so the next visit wakes it for the cost of one keyframe seek. The canvases are the part that must not churn — a montage of short clips replayed for a few minutes, allocating a fresh set on every reopen, floods the GPU process until frames stop arriving at all. They also must not pile up, so the warm shelf of stood-down sources is capped by the memory it holds rather than by a count of them: a small stage keeps a montage's whole cast, a large one keeps a few, and what does not fit closes for real. A file that moves to a new address mid-play — an import landing in project storage, a signed link re-minted ahead of expiry — keeps its source: the frames already decoded carry the picture while a fresh reader opens on the new address behind them, and the walk goes on from wherever the playhead stands. Closing there instead would put a cold open in front of the very next frame, and the picture would freeze for exactly as long as the open takes.Those caps are shares of one number. A cut is built out of expensive pictures — frames held inside the platform's decoder, canvases behind every source the pool keeps warm, the bytes of the files they were decoded from — and each of those was capped in whatever currency its own subsystem thought in: a count of decoders, a number of pixels, a number of open files. The tab's real ceiling was whatever those happened to add up to on the machine the tuning was done on. Now every cache says what it holds in bytes and asks what it may hold, and the answer is the smaller of the size it was tuned to want and its share of a quarter of the machine's memory. Where there is room the tuned size is the smaller one and the preview behaves as it was tuned to. Where there is not, the share binds first and every cache sheds together. Which caches stand in a share, and how much of it each may stand on, is written in that one place as well, so two caches cannot be handed the same room and a cache that only reports what it holds still has room set aside for it. File bytes are the share the tab itself stands on, and they are held once. A file is opened once for the tab: a cut of forty segments from one recording has forty sources, and they share the one parsed file and its reader cache, each holding only its own decoder and canvases; the voices and the filmstrip's readers join the same open file. Under that, every read of a cloud file goes through one chunk memory, and a reader keeps for itself only the few megabytes its own walk is standing on. A file addressed by the page's own route, while it has no signed link, reads through the same store, since the route redirects to the object the store keys on; a cut shared with someone reads through the share's route the same way, so a viewer holds the file once the way its owner does.@@ -106,7 +108,7 @@ Cloud projects follow the account: the same project opens in any browser on anyEvery client call goes through a backend seam (`site/src/cut/lib/backend/`): the local driver is the engine transport unchanged, the cloud driver rewrites the same paths to `/api/cut-cloud/*` with the session cookie, and the browser driver answers storage routes in the page from origin-private storage, falling through to the cloud twin for AI. Residency is per project and fixed when the project is created, so creating one is where the user chooses. One picker makes that choice, standing beside New project in the sidebar: it names a shelf — Local or Cloud — and everything the browser creates lands there, new projects and anything added to the library alike. Local is this Mac's engine when the app has connected and this browser's own storage otherwise, so a machine without the app still has a real local shelf. The choice sticks on that browser until they change it, and every other New project button follows it. Inside a folder the folder decides, since a project files only into a folder beside it. Folders file into folders on every shelf: a tile drags onto another tile or up onto a crumb, every level shows the shelf, the grid and New folder the top does, a folder nests only beside itself on its own shelf, and deleting one brings what it held up a level. The home lists every shelf as one listing — the Mac's from its stored listing when the app is closed — each project badged with where it lives, and opening one binds the editor to that project's backend. Capability flags on the driver hide what a backend can't do, so components never feature-detect.-The library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Library folders nest the way project folders do, on the Library page and in the editor's library panel alike. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up. Filing an item into a folder on another shelf crosses the same way — the bytes come down and go back up, a file with its cover and a template with its own media, and the copy left behind comes off.+The library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Library folders nest the way project folders do, on the Library page and in the editor's library panel alike. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it — on the Mac as a clone, landed before the clip is placed — and off it the browser carries them down and back up. Filing an item into a folder on another shelf crosses the same way — the bytes come down and go back up, a file with its cover and a template with its own media, and the copy left behind comes off.The phone feeds the cloud shelf. Clips recorded in the iOS app upload themselves to it, marked as camera footage; that marker gives the desktop its Camera Roll — a tab of phone clips kept out of the main Library grid, and a locked Camera Roll folder in the editor's library panel so the footage drops into any project. A recording arrives named after the clock it was shot on, which says nothing about which clip it is, so each one is titled from itself: the page reads the opening of the clip and one frame, a light model names it in a few words, and the shelf keeps that answer, so the work happens once and the card, the viewer and the assistant all read the same title. The tile shows the title with the date under it, and hands over the whole line when the tile is too narrow to hold it. The file's own name stays what a prompt's reference resolves against. Inspiration saved on the phone lands in an Inspiration folder on the same shelf, links riding the same worker import every shelf uses. What the phone put on the shelf it also mirrors: deleting a clip from the Camera Roll or the Library tombstones it, and the phone deletes its own copy on the next pass, so the roll on the phone and the roll at the desk stay one set. Notes are edited on both sides: the phone and the desktop's Notes tab work the same set, the newer edit winning, deletes carrying across. Notes file into folders of their own, on the shelf's folder table, and folders file into folders: the desktop files them by dragging onto the same folder tiles the Library uses — a folder tile drags too, onto another tile or back out to a crumb — the phone by dragging a card or a row onto a folder row, and every level shows the same shelf, grid and New folder the top does, and nothing above it. A folder made on either side is on the other by the next pass, and deleting one brings what it held up a level. Every request from the app carries a client marker, the server remembers accounts it has seen it from, and only those accounts get the phone tabs — a desktop-only account's sidebar never changes. The app's own guide covers the phone side: [The iOS App](../ios-app.md).diff --git a/evals/cut-keys.latest-report.json b/evals/cut-keys.latest-report.jsonindex 8f92b19e..dc862613 100644--- a/evals/cut-keys.latest-report.json+++ b/evals/cut-keys.latest-report.json@@ -1,5 +1,5 @@{- "at": "2026-09-03T10:17:17.872Z",+ "at": "2026-09-04T11:49:57.661Z","results": [{"name": "drop/selected",@@ -10,8 +10,8 @@{"name": "drop/split","what": "⌘B with the mouse still where it dropped cuts the new clip",- "ok": false,- "detail": "1 clips after ⌘B"+ "ok": true,+ "detail": ""},{"name": "drop/delete",@@ -22,8 +22,8 @@{"name": "drop/typing","what": "a chat composer focused before the drag lets go of the keys at the drop",- "ok": false,- "detail": "1 clips after ⌘B with DIV focused"+ "ok": true,+ "detail": ""}]}\ No newline at end of filediff --git a/site/scripts/eval-cut-perf.ts b/site/scripts/eval-cut-perf.tsindex 93da5dec..0efc7742 100644--- a/site/scripts/eval-cut-perf.ts+++ b/site/scripts/eval-cut-perf.ts@@ -29,6 +29,11 @@* and for late frames rising from the first pass to the* last. This is the session-decay case: a preview that is* smooth for a minute and choppy after five fails here.+ * a big file, dropped — a 4K clip goes from the library shelf onto the+ * timeline by the real drag, play is pressed as it lands,+ * and the trace is checked for the picture arriving with+ * the sound and for what held the thread in between. The+ * one case that takes its media the way a person does.** Fixtures build deterministically into dist/cut-perf/ (gitignored) from the* bundled stock clips, so the montage's cut times are known exactly.@@ -39,7 +44,7 @@* npm run eval:cut-perf [--only <case>] [--runs N] [--out path]* [--enforce-budgets] [--headed] [--dump-trace]* [--machine desktop|laptop|ryzen-5500u|potato] [--cpu N]- * [--net <kbps>] [--rtt <ms>]+ * [--net <kbps>] [--rtt <ms>] [--big-file <path>]*/import { chromium, type Browser, type Page } from "playwright";@@ -307,6 +312,16 @@ interface Trace {presents: PresentRecord[];seeks: SeekRecord[];longTasks: { at: number; ms: number }[];+ /** The same stretches as frames, naming the script that held each one. */+ longFrames: {+ at: number;+ ms: number;+ blockedMs: number;+ fn: string;+ src: string;+ invoker: string;+ scriptMs: number;+ }[];ticks: number;liveSamples: number[];liveSources: number[];@@ -958,6 +973,9 @@ interface EvalCase {minKbps?: number;/** The project this case measures; the montage of stock clips when unset. */seed?: (page: Page) => Promise<Fixture>;+ /** A file put on the library shelf before the editor opens, for a case+ * that takes its media the way a person does. Removed after the run. */+ shelf?: { file: () => Promise<string>; name: string };run: (page: Page, fx: Fixture) => Promise<CaseResult>;}@@ -1188,7 +1206,9 @@ async function judgePlay(// the link's arithmetic, so counting them judges the fixture rather than the// preview. What such a case is for is whether the picture stayed with the// sound while it went short, which the lag and clock notes below still ask.- starved = false+ starved = false,+ // What a case asks of the trace beyond the questions every play shares.+ extra?: (trace: Trace, notes: string[]) => void): Promise<CaseResult> {const trace = await stopTrace(page);const notes: string[] = [];@@ -1266,6 +1286,19 @@ async function judgePlay(.map(([id, r]) => `${id}:${Math.round((100 * r.stale) / r.n)}%/${Math.round(r.worst)}ms`);if (dark.length) console.log(`[detail] dark ${dark.join(" ")}`);}+ // What held the thread, worst first, with the script the browser blames.+ // The frame's length and the blocking inside it are both here: a frame is+ // long the moment its paint is, and only the blocking is time no one else+ // could have used.+ const held = [...(trace.longFrames ?? [])].sort((a, b) => b.blockedMs - a.blockedMs).slice(0, 6);+ for (const l of held) {+ const who = l.fn || l.src ? ` ${l.fn || "?"}@${l.src || "?"} (${l.invoker}, ${l.scriptMs}ms script)` : "";+ console.log(+ `[detail] blocked ${l.blockedMs}ms of a ${Math.round(l.ms)}ms frame at +${Math.round(+ l.at - trace.presents[0].at+ )}ms${who}`+ );+ }}// The plainest question this case asks, and the one a viewer would ask:@@ -1307,6 +1340,7 @@ async function judgePlay(// Long tasks are reported, not gated: this case judges sync, decay and// memory, and the stray dev-build hiccup that leaves every frame exact is// not a fail.+ extra?.(trace, notes);return {name,bucket: "playback",@@ -1915,6 +1949,172 @@ const filmstripCutsCase: EvalCase = {},};+// ── A big file dropped from the library ─────────────────────────────────────+//+// The complaint this case is written for: a long 4K file dragged from the+// library shelf onto the timeline plays its sound and moves the playhead+// while the picture sits on one frame. Every other playback case seeds the+// store, which measures the engine on its own. This one takes the file the+// way a person does — an upload to the shelf, the card dragged onto track 0,+// play pressed the moment it lands — so everything the drop sets off in the+// page (strip captures, waveform peaks, the poster) is on the clock beside+// the engine, and the first seconds are the seconds judged.++/** The big file: 4K at thirty frames, keyframes a second apart, at a phone+ * recording's rate. H.264, which every machine the suite runs on decodes. */+const BIG_S = 90;+const BIG_KBPS = 40_000;+/** The name the file carries on the shelf, which is how the card is found+ * and how a crashed run's copy is swept. */+const BIG_NAME = "cut-perf-4k.mp4";+/** How much of the file is played. The report lives in the first stretch. */+const BIG_PLAY_S = 20;+/** How long the picture may take to arrive after play is pressed on a fresh+ * drop, on the reference machine: the file opens, the first keyframe decodes,+ * and the strip's own captures are competing for the same decoder. */+const FIRST_PICTURE_S = 1.5;++/** A file of one's own in the big file's place — the recording a report+ * came with, or a shape the fixture is not (HEVC off a phone) — with+ * `--big-file <path>`. The fixture is what the nightly measures. */+async function buildBigClip(): Promise<string> {+ const own = arg("--big-file");+ if (own) return path.resolve(own);+ const dst = path.join(OUT, "library-4k.mp4");+ if (existsSync(dst)) return dst;+ const src = path.join(STOCK, "animal-dog-sprint.mp4");+ await run("ffmpeg", [+ "-y", "-loglevel", "error",+ "-stream_loop", "-1", "-i", src,+ "-f", "lavfi", "-i", "sine=frequency=330:sample_rate=48000",+ "-t", String(BIG_S),+ "-map", "0:v:0", "-map", "1:a:0",+ "-c:v", "libx264", "-preset", "ultrafast",+ "-g", "30", "-keyint_min", "30",+ "-b:v", `${BIG_KBPS}k`, "-maxrate", `${BIG_KBPS}k`, "-bufsize", `${BIG_KBPS * 2}k`,+ "-r", "30", "-vf", "scale=3840:2160", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-b:a", "128k",+ "-shortest",+ dst,+ ]);+ return dst;+}++/** Put a file on the dev account's library shelf, and hand back its id. */+async function shelve(file: string, name: string): Promise<string> {+ const form = new FormData();+ form.set("file", new File([await readFile(file)], name, { type: "video/mp4" }));+ const res = await fetch(`${BASE}/api/cut/library?u=${DEV_USER}`, { method: "POST", body: form });+ if (!res.ok) throw new Error(`library upload failed: ${res.status}`);+ return ((await res.json()) as { id: string }).id;+}++async function unshelve(id: string): Promise<void> {+ const res = await fetch(`${BASE}/api/cut/library/${id}?u=${DEV_USER}`, { method: "DELETE" });+ if (!res.ok && res.status !== 404) console.log(`[cleanup] delete library ${id} failed: ${res.status}`);+}++/** Remove the shelf copies a crashed run left behind. */+async function sweepShelf(): Promise<void> {+ const res = await fetch(`${BASE}/api/cut/library?u=${DEV_USER}`);+ if (!res.ok) return;+ const { assets = [] } = (await res.json()) as { assets?: { id: string; name: string }[] };+ const stale = assets.filter((a) => a.name === BIG_NAME);+ for (const a of stale) await unshelve(a.id);+ if (stale.length) console.log(`[cleanup] removed ${stale.length} leftover shelf cop${stale.length === 1 ? "y" : "ies"}`);+}++/** Bring the Library sub-tab of the Media panel up and hand back the card. */+async function libraryCard(page: Page, name: string) {+ const tab = page.getByText("Library", { exact: true }).first();+ if (!(await tab.isVisible().catch(() => false))) {+ await page.getByText("Media", { exact: true }).first().click();+ await tab.waitFor({ state: "visible", timeout: 10_000 });+ }+ await tab.click();+ const card = page.locator("[data-sel-id]").filter({ hasText: name.replace(/\.mp4$/, "") }).first();+ await card.waitFor({ state: "visible", timeout: 30_000 });+ return card;+}++/** The real gesture: drag the card onto track 0 and wait for the clip to land. */+async function dropOnTrack(page: Page, card: Awaited<ReturnType<typeof libraryCard>>): Promise<void> {+ const surface = page.locator("[data-segment-drop]").first();+ const box = await surface.boundingBox();+ if (!box) throw new Error("no timeline drop surface");+ await card.dragTo(surface, { targetPosition: { x: 160, y: box.height - 60 } });+ await page.waitForFunction(+ () => {+ const w = window as unknown as { __cutDev: { useEditor: { getState(): { clips: unknown[] } } } };+ return w.__cutDev.useEditor.getState().clips.length > 0;+ },+ undefined,+ { timeout: 30_000 }+ );+}++const libraryDropCase: EvalCase = {+ name: "play-4k-from-library",+ bucket: "playback",+ transitions: false,+ shelf: { file: buildBigClip, name: BIG_NAME },+ // The project stays empty: the file arrives by the gesture below.+ seed: async () => ({ cuts: [], duration: BIG_S }),+ run: async (page) => {+ const card = await libraryCard(page, BIG_NAME);+ // The trace opens before the drop, so the drop's own work is in it.+ await startTrace(page);+ await dropOnTrack(page, card);+ const pressed = await page.evaluate(() => performance.now());+ await setPlaying(page, true);+ await page.waitForFunction(+ (end: number) => {+ const dev = (window as unknown as {+ __cutDev: { playheadAt(): number; useEditor: { getState(): { playing: boolean } } };+ }).__cutDev;+ return dev.playheadAt() >= end || !dev.useEditor.getState().playing;+ },+ BIG_PLAY_S,+ { timeout: BIG_PLAY_S * 6000, polling: 100 }+ );+ await setPlaying(page, false);+ return judgePlay(+ page,+ "play-4k-from-library",+ 1,+ (p) => p.t > FIRST_PICTURE_S * MACHINE.cpu && p.t < BIG_PLAY_S - 0.3,+ false,+ (trace, notes) => {+ const first = trace.presents.find((p) => p.at >= pressed && p.exact && !p.stale && p.clipId);+ const wait = first ? (first.at - pressed) / 1000 : Infinity;+ if (wait > FIRST_PICTURE_S * MACHINE.cpu)+ notes.push(`first picture ${Number.isFinite(wait) ? `${wait.toFixed(2)}s` : "never"} after play`);+ // The play runs on the thread the picture is drawn from, and this is+ // what that thread was doing once the picture was there. What comes+ // before belongs to the drop's own render and to the open — the first+ // 4K frame handed from the decoder to a canvas is a beat of GPU work+ // on its own — and both are in the trace to be read.+ //+ // Blocked time rather than the task's own length, because a task is+ // only reported at all once it passes fifty milliseconds: measured by+ // length against a frame's budget, every long task there is fails,+ // and the dev build's own overlay fails it as surely as the preview+ // would. What is blocked is what nothing else could run in.+ const from = first?.at ?? pressed;+ const held = (trace.longFrames ?? [])+ .filter((f) => f.at >= from)+ .sort((a, b) => b.blockedMs - a.blockedMs)[0];+ if (held && held.blockedMs > GATE.longTaskMs) {+ notes.push(+ `${held.blockedMs}ms of a ${Math.round(held.ms)}ms frame blocked the main thread` ++ (held.fn || held.src ? ` (${held.fn || "?"}@${held.src || "?"})` : "")+ );+ }+ }+ );+ },+};+const CASES: EvalCase[] = [// The gesture the complaint was about: the pointer slides along the timeline// and the picture has to keep up with it, frame by frame.@@ -2019,6 +2219,7 @@ const CASES: EvalCase[] = [idleCase,filmstripCase,filmstripCutsCase,+ libraryDropCase,];// ── Run ─────────────────────────────────────────────────────────────────────@@ -2580,6 +2781,7 @@ async function main(): Promise<void> {// child per case and merges what they report.if (!ONLY) {await sweepProjects();+ await sweepShelf();const results = await fanOut(cases.map((c) => c.name));await writeReport(results);return;@@ -2603,6 +2805,7 @@ async function main(): Promise<void> {c.minKbps && MACHINE.netKbps > 0? Math.max(MACHINE.netKbps, c.minKbps): MACHINE.netKbps;+ const shelfId = c.shelf ? await shelve(await c.shelf.file(), c.shelf.name) : null;const projectId = await newProject();let r: CaseResult;try {@@ -2615,6 +2818,7 @@ async function main(): Promise<void> {// project would keep writing to a doc the engine has just removed.await page.goto("about:blank").catch(() => {});await deleteProject(projectId);+ if (shelfId) await unshelve(shelfId);}results.push(r);const mark = r.pass ? "ok " : "FAIL";diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex 72f1b62b..bbe98562 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -15,7 +15,7 @@ import { clipLen, projectDuration, useEditor } from "@/cut/lib/store";import { copyStageFrame, primeStageFrame, stageHasFrame } from "@/cut/lib/stageFrame";import {capturePoster,- capturePosterWhenReady,+ capturePosterOnPicture,paintPoster,readPoster,} from "@/cut/lib/posterCache";@@ -69,7 +69,7 @@ function useCachedFirstFrame(canvasRef: RefObject<HTMLCanvasElement | null>) {void paintPoster(canvas, data);}});- const stop = capturePosterWhenReady("frame", projectId, () => canvasRef.current);+ const stop = capturePosterOnPicture("frame", projectId, () => canvasRef.current);return () => {alive = false;stop();diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 7818d77a..5cb4ec70 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -48,7 +48,8 @@ import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";import { keyboardToEditor, shortcutDecline } from "@/cut/lib/shortcutGate";import { additiveClick } from "@/cut/lib/hostKeys";import { CLIP_GAP, laneDragFor, laneDragParts, startLaneMove, startLaneTrim, type LaneDrag, type LaneKind } from "@/cut/lib/laneTracks";-import { downloadMedia, ensurePeaks, importImage, importStockMusic, importStockVideo, peekEdgeFrame, requestEdgeFrame, revealMedia, stripFailedFor, subscribeStripStatus } from "@/cut/lib/media";+import { reportSwallowed } from "@/cut/lib/report";+import { downloadMedia, dropEdgeFrames, ensurePeaks, importImage, importStockMusic, importStockVideo, peekEdgeFrame, requestEdgeFrame, revealMedia, stripFailedFor, subscribeStripStatus } from "@/cut/lib/media";import { planFilmstrip, type FilmTile } from "@/cut/lib/filmstrip";import { waveGain } from "@/cut/lib/waveform";import { track0Clips, laneGapAt, sameLane, type LaneRef, clipLen, clipSpeed, getClipSpans, maxClipFade, overlayLaneOrder, overlayLayers, projectDuration, resolveTransitions, rippleInsert, useEditor } from "@/cut/lib/store";@@ -1664,8 +1665,9 @@ export function Timeline() {if (only && !only(asset)) continue;const sticker = !!stickerOf(asset);placeAssetAt(asset.id, asset.type, next(asset, sticker), audioRow, place);- } catch {+ } catch (err) {// A copy that fails leaves the rest of the run alone.+ reportSwallowed(`[cut] library drop failed for ${item.fileName}`, err);}}};@@ -4374,12 +4376,19 @@ function DropGhostFilm({for (let k = 0; k < count; k++) {const t = (k * imgW + imgW / 2) / pps;if (peekEdgeFrame(ghost.url, t)) continue;- void requestEdgeFrame(`drop-ghost:${k}`, ghost.url, t).then((src) => {+ // Behind a play, like the strip's own tiles: a drag across the timeline+ // while the cut plays would otherwise put a hundred keyframe decodes of+ // a 4K file in front of the walk drawing the picture. The ghost shows+ // its poster until the play stops.+ void requestEdgeFrame(`drop-ghost:${k}`, ghost.url, t, undefined, {+ background: true,+ }).then((src) => {if (live && src) bump();});}return () => {live = false;+ dropEdgeFrames("drop-ghost:");};}, [needsReads, ghost.url, count, imgW, pps]);if (ghost.kind === "image") {diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex 37d7df5b..e633f214 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -2,6 +2,7 @@import { useEffect, type RefObject } from "react";+import { noteStagePicture } from "@/cut/lib/posterCache";import {getClipSpans,overlayLayers,@@ -200,6 +201,15 @@ class Engine {private lastRead: number | null = null;private readBackward = false;private lastWalkCost = 0;+ /** Dev only: where a slow tick spent its time, phase by phase. */+ private phases: string[] = [];+ private phaseAt = 0;+ private phase(label: string) {+ if (process.env.NODE_ENV === "production") return;+ const now = performance.now();+ this.phases.push(`${label} ${Math.round(now - this.phaseAt)}`);+ this.phaseAt = now;+ }/** Whether the tick being drawn is a playing one — read by the matte* provider, which the compositor calls mid-frame. */private renderPlaying = false;@@ -732,7 +742,16 @@ class Engine {// paint. Either way the loop stops as soon as there is nothing to do.if (playing || this.dirty) {this.dirty = false;+ const at = performance.now();+ this.phases.length = 0;+ this.phaseAt = at;this.render(playing);+ // A tick that held the thread past a few frames, with the phase that+ // held it. The playhead write is where the timeline and the inspector+ // re-render; the rest is the engine's own.+ const ms = performance.now() - at;+ if (process.env.NODE_ENV !== "production" && ms > 50)+ engineLog(`engine ${this.serial} tick ${Math.round(ms)}ms: ${this.phases.join(", ")}`);}if (playing || this.dirty) this.schedule();}@@ -741,6 +760,7 @@ class Engine {const s = useEditor.getState();const spans = getClipSpans(s.clips, s.assets);const total = projectDuration(s);+ this.phase("spans");// The frame's color is the project's, read fresh each frame: every clear// and every letterbox below paints it, so a cut with no footage at all// still plays a picture.@@ -817,6 +837,7 @@ class Engine {}const master = spans.find((sp) => t >= sp.start && t < sp.start + sp.len);+ this.phase("clock");// Ask for the master's picture before clearing. A clip nothing has decoded// yet answers `pending`, and clearing on the strength of that would black@@ -826,6 +847,7 @@ class Engine {// open can't freeze the playhead or carry playback past a stop mark.const masterFrame = master ? this.frameFor(master, t, playing, true) : MISSING_FRAME;const pendingMaster = masterFrame.kind === "pending";+ this.phase("master");// A play whose master clip has decoded nothing has nothing to play: the// clock would carry the playhead across a stretch of the cut nobody saw or// heard, and land somewhere further on when the file finally opened. So it@@ -859,11 +881,17 @@ class Engine {this.comp.subjectMatteProvider = (at) => this.behind.clipMatteOf(this.canvas, at);this.behind.draw(this.canvas, s.overlays, s.assets, t);this.comp.drawProjectFade(fadeGain);+ // A paused draw is the picture standing still, which is when a+ // readback of it costs nothing anyone is watching; a play's first+ // frame is read back once the play stops and the frame is redrawn.+ if (!playing && masterFrame.kind === "ready") noteStagePicture();}+ this.phase("draw");// Decoders for what is about to arrive, and the ones nothing needs closed.this.warm(t, playing);this.pool.evict();+ this.phase("warm");if (playing) {this.mixer.setMasterGain(fadeGain);@@ -878,6 +906,7 @@ class Engine {})));this.mixer.update(t, this.voicesAt(t, spans, master));+ this.phase("audio");// A scoped effect preview auto-pauses at its stop mark; the end of the// cut stops playback outright.const stop = s.previewStopAt;@@ -890,11 +919,13 @@ class Engine {} else {this.writeHead(t);}+ this.phase("head");} else {// The sound's readers on the same footing as the picture's: the clip// under a parked playhead has its file open before the play begins,// rather than opening it once the clock is already running.this.mixer.warm(t, this.voicesAt(t, spans, master));+ this.phase("audio");}if (tracing()) {diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex c4e4dde8..3d04b245 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -16,6 +16,7 @@ import {MAX_FONT_BYTES,presignedUpload,probeFileMeta,+ registerLandedAsset,uploadProjectMediaTo,} from "./media";import {@@ -716,13 +717,37 @@ export async function importLibraryAsset(): Promise<MediaAsset> {if (lib.type === "font")throw new Error("Fonts are used from the font menu, not the timeline.");+ // The project's media takes the name the shelf shows, so a phone+ // recording lands on the timeline under its title.+ const name = lib.title || lib.name;+ // On this Mac the engine lands the file with a clone, and it is landed+ // before this returns: the asset registers at the project's own address+ // and plays from there. Registered on the shelf's address first, the+ // preview would open the file there, then open it again at the project's+ // once the copy reported — two readers and a walk restarted on a file+ // whose every keyframe is a 4K decode — while the strip and the waveform+ // went on reading the shelf's copy.+ if (lib.residency === "local" && sameShelf(lib.residency)) {+ const fileName = await copyLibraryFileToProject(+ projectId,+ lib.residency,+ lib.fileName,+ lib.id,+ );+ return registerLandedAsset(projectId, {+ fileName,+ name,+ type: lib.type,+ duration: lib.duration,+ width: lib.width,+ height: lib.height,+ });+ }return importRemote(projectId,{url: libraryMediaUrl(lib.fileName, lib.residency),- // The project's media takes the name the shelf shows, so a phone- // recording lands on the timeline under its title.- name: lib.title || lib.name,+ name,fileName: lib.fileName,type: lib.type,duration: lib.duration,diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex a18646af..2de4fe7e 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -24,8 +24,10 @@ import {probeMediaFile,UnreadableMediaError,videoTrackOf,+ type IdleGate,type MediaHandle,} from "./mediaRead";+import type { WrappedCanvas } from "mediabunny";import {clearPendingUpload,dropLocalMedia,@@ -777,6 +779,53 @@ export function importRemote(return asset;}+/**+ * Register media that has already landed in the project's storage as an+ * asset, at the address it will always play from.+ *+ * The other way in, `importRemote`, plays from a source address while the+ * bytes copy behind the editor and moves every reader once they land. A copy+ * that was over before the asset existed has nothing to move: the first read+ * opens the stored file, and no reader ever holds the file at two addresses.+ */+export async function registerLandedAsset(+ projectId: string,+ init: {+ fileName: string;+ name: string;+ type: AssetType;+ duration: number;+ width?: number;+ height?: number;+ }+): Promise<MediaAsset> {+ const asset: MediaAsset = {+ id: uid(),+ fileName: init.fileName,+ name: init.name,+ type: init.type,+ duration: init.duration,+ ...(init.width !== undefined ? { width: init.width } : {}),+ ...(init.height !== undefined ? { height: init.height } : {}),+ url: await storedMediaUrl(projectId, init.fileName),+ };+ useEditor.getState().addAsset(asset);+ void enrichAsset(asset);+ // A shelf's dimensions are what it was told; the file's are what it has.+ // Everything sized off the asset — the fit, the reader's budget, an export's+ // source size — reads this, so the truth lands behind the placement.+ if (init.type === "video") {+ void probeMediaFile(asset.url)+ .then((m) => {+ if (m.hasVideo) {+ useEditor.getState().updateAsset(asset.id, { width: m.width, height: m.height });+ }+ })+ .catch(() => {});+ }+ return asset;+}+/** Store a fetchable image (a stock tile) in the project's media as a* first-class image asset at its native resolution — no video baking — and* register it, without placing it on the timeline. Callers choose where it@@ -1526,6 +1575,91 @@ export function keepImportedBytes(assetId: string, bytes: Blob): void {}}+/**+ * Resolves once nothing is playing.+ *+ * The reads behind the editor — a waveform, a strip, a scene probe, a tile+ * capture — open the same file the preview is playing from, and on a big+ * file they take what the picture needs: decoder slots, the link's width, and+ * the thread the frames are drawn on. A play is the urgent thing; this work+ * waits for it to stop and picks up where it was. Cheap when nothing is+ * playing, which is when it is awaited most.+ */+/** What a long read consults to know the preview wants the file back. */+export const IDLE_GATE: IdleGate = {+ busy: () => useEditor.getState().playing,+ idle: () => idlePlayback(),+};++const idleWaiters = new Set<() => void>();+let idleWatch: (() => void) | null = null;++/** Wake `resolve` when the cut stops playing; the handle stops the wait. One+ * store subscription serves every waiter, since it runs on every write the+ * editor makes and a play is when the writes are busiest. */+function waitForIdle(resolve: () => void): () => void {+ idleWaiters.add(resolve);+ idleWatch ??= useEditor.subscribe((s) => {+ if (s.playing) return;+ const woken = [...idleWaiters];+ idleWaiters.clear();+ idleWatch?.();+ idleWatch = null;+ for (const fn of woken) fn();+ });+ return () => {+ idleWaiters.delete(resolve);+ if (idleWaiters.size) return;+ idleWatch?.();+ idleWatch = null;+ };+}++export function idlePlayback(): Promise<void> {+ if (!useEditor.getState().playing) return Promise.resolve();+ return new Promise((resolve) => void waitForIdle(resolve));+}++/** The same wait, with a handle for a caller that may stop wanting it — a+ * wait left running holds its place in the set until the play ends. */+export function idleWait(): { done: Promise<void>; cancel: () => void } {+ if (!useEditor.getState().playing) return { done: Promise.resolve(), cancel: () => {} };+ let cancel = () => {};+ const done = new Promise<void>((resolve) => {+ cancel = waitForIdle(resolve);+ });+ return { done, cancel };+}++/**+ * `framesAt`, given back while the cut is playing.+ *+ * A sweep that merely stops pulling still holds everything it opened: the+ * file, the decoder, and the frames the decode pump counts in flight — the+ * slot the preview was short of. So a play ends the walk outright, which+ * disposes the reader with it, and the times still owed are read by a fresh+ * walk once the play stops.+ */+async function* idleFramesAt(+ url: string,+ times: number[],+ size?: { height: number }+): AsyncGenerator<WrappedCanvas | null> {+ let from = 0;+ while (from < times.length) {+ await idlePlayback();+ const before = from;+ for await (const frame of framesAt(url, times.slice(from), size)) {+ yield frame;+ from++;+ if (useEditor.getState().playing) break;+ }+ // A pass that answered nothing has nothing more to give — an unreadable+ // file, a walk that died — and another would open it forever.+ if (from === before) return;+ }+}+/** Generate filmstrip thumbnails / waveform peaks and merge them into the* store. Safe to call repeatedly; skips assets that are already enriched.* `src` overrides where the frames are read from — an import still uploading@@ -1542,6 +1676,13 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {useEditor.getState().updateAsset(asset.id, { thumbs: [src], thumbStep: IMAGE_CLIP_SECONDS });}} else if (asset.type === "video") {+ // A clip dropped and played at once is played first; the strip and the+ // sound band fill in when the play stops.+ const openProject = useEditor.getState().projectId;+ await idlePlayback();+ // A play is long enough to leave the project in it. Nothing this sweep+ // writes belongs to whatever is open now.+ if (useEditor.getState().projectId !== openProject) return;// The clip box draws the sound under the picture, so a video enriches// waveform peaks alongside its filmstrip. The two are separate reads of// the file, so the peaks decode starts here and runs beside the strip's@@ -1601,6 +1742,9 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {await peaksRun;enrichRetries.delete(asset.id);} else if (asset.type === "audio" && !asset.peaks?.length) {+ const openProject = useEditor.getState().projectId;+ await idlePlayback();+ if (useEditor.getState().projectId !== openProject) return;const publish = (peaks: number[]) => useEditor.getState().updateAsset(asset.id, { peaks });try {const peaks = await loadPeaks(asset, held ?? src, publish);@@ -1792,7 +1936,7 @@ async function loadPeaks(const key = peaksCacheKey(useEditor.getState().projectId, asset.id);const cached = await readCachedPeaks(key, asset.duration);if (cached) return cached;- const peaks = await makePeaks(src, asset.duration, onPartial);+ const peaks = await makePeaks(src, asset.duration, onPartial, IDLE_GATE);writeCache(key, { peaks, duration: asset.duration, at: Date.now() });return peaks;}@@ -1845,7 +1989,7 @@ async function g16Sweep(url: string, times: number[]): Promise<(Float32Array | n}) as CanvasRenderingContext2D | null;if (!ctx) return times.map(() => null);const out: (Float32Array | null)[] = [];- for await (const frame of framesAt(url, times, { height: SIGNATURE_SIZE })) {+ for await (const frame of idleFramesAt(url, times, { height: SIGNATURE_SIZE })) {if (!frame) {out.push(null);continue;@@ -1979,7 +2123,7 @@ async function makeThumbs(return thumbs;};let published = 0;- for await (const frame of framesAt(url, times, { height: THUMB_H })) {+ for await (const frame of idleFramesAt(url, times, { height: THUMB_H })) {captured.push(frame ? await rasterCanvasToDataUrl(frame.canvas, "image/jpeg", 0.92) : null);if (!onTiles || captured.length >= times.length) continue;const now = Date.now();@@ -2053,7 +2197,7 @@ async function refineSceneCuts(assetId: string, url: string, duration: number) {}const regrabbed = new Map<number, string>();let k = 0;- for await (const frame of framesAt(+ for await (const frame of idleFramesAt(url,moved.map((m) => m.t),{ height: THUMB_H }@@ -2215,6 +2359,9 @@ const edgePool = new Map<string, Promise<EdgeReader>>();holdMemory("edgeFrames", stripBytes);holdMemory("libraryPictures", derivedBytes);let edgePumping = false;+/** Wakes a pump holding the strip's captures for a play, when a clip-edge+ * capture arrives that should not wait for it. */+let edgeWake: (() => void) | null = null;function edgeKey(url: string, time: number, height: number) {return `${url}#${time.toFixed(2)}@${height}`;@@ -2248,10 +2395,25 @@ export function requestEdgeFrame(prev?.resolvers.forEach((r) => r(null));queue.set(slot, { url, time, height, key, resolvers: [resolve] });}+ if (!opts?.background) edgeWake?.();void pumpEdgeFrames();});}+/** Let go of every queued capture whose slot starts with `prefix`: the+ * surface that asked is gone, and a 4K keyframe decoded for a ghost that has+ * already landed is a decoder taken from the clip it became. A capture+ * mid-read finishes; only the queue empties. */+export function dropEdgeFrames(prefix: string): void {+ for (const queue of [edgeQueue, edgeBackQueue]) {+ for (const [slot, req] of queue) {+ if (!slot.startsWith(prefix)) continue;+ queue.delete(slot);+ req.resolvers.forEach((r) => r(null));+ }+ }+}+/** Captures still queued or mid-read. The filmstrip eval waits on zero to* know a zoomed strip has finished filling in. */export function edgeFramesPending(): number {@@ -2315,6 +2477,25 @@ async function pumpEdgeFrames() {edgePumping = true;try {for (;;) {+ // Strip tiles read behind everything: behind every clip-edge capture,+ // and behind a play. The timeline follows the playhead while it plays,+ // and every scroll asks for the tiles that came into view — captures+ // that would open a second decoder on the file being played and read+ // its keyframes beside the walk. They land once the play stops. An+ // edge capture arriving meanwhile wakes the pump for itself.+ if (edgeQueue.size === 0 && edgeBackQueue.size > 0) {+ const idle = idleWait();+ await Promise.race([+ idle.done,+ new Promise<void>((resolve) => {+ edgeWake = resolve;+ }),+ ]);+ // Whichever won, the other is no longer wanted: a wait left in the+ // set outlives every wake of a long play.+ idle.cancel();+ edgeWake = null;+ }const queue = edgeQueue.size ? edgeQueue : edgeBackQueue;const next = queue.entries().next();if (next.done) break;@@ -2370,11 +2551,12 @@ const PEAKS_MAX = 60_000;function makePeaks(src: string | Blob,duration: number,- onPartial?: (peaks: number[]) => void+ onPartial?: (peaks: number[]) => void,+ gate?: IdleGate): Promise<number[]> {const buckets =duration > 0? Math.min(PEAKS_MAX, Math.max(400, Math.round(duration * PEAKS_PER_SECOND))): 1600;- return audioPeaks(src, buckets, onPartial);+ return audioPeaks(src, buckets, onPartial, gate);}diff --git a/site/src/cut/lib/mediaRead.ts b/site/src/cut/lib/mediaRead.tsindex c3acef80..d6b014bf 100644--- a/site/src/cut/lib/mediaRead.ts+++ b/site/src/cut/lib/mediaRead.ts@@ -733,44 +733,70 @@ const PEAKS_PUBLISH_MS = 250;* chunk — the moments the walk has not reached yet sit flat — and fills in* left to right until the returned array is the whole read.*/+/** What a long read consults to know something more urgent — a play of this+ * same file — wants the decoder and the link back. */+export interface IdleGate {+ busy: () => boolean;+ idle: () => Promise<void>;+}+export async function audioPeaks(src: string | Blob,buckets: number,- onPartial?: (peaks: number[]) => void+ onPartial?: (peaks: number[]) => void,+ gate?: IdleGate): Promise<number[]> {// Peaks are a real decode; a headless runtime skips them and the waveform// enriches the next time a browser holds the asset.if (typeof AudioDecoder === "undefined") return [];- const input = openMedia(src);- try {- const track = await audioTrackOf(input);- if (!track) return [];- // Read the length first so each chunk can be folded into its bucket and- // dropped; without it the buckets aren't known until the last sample, and- // the whole file has to be held to place any of it.- const duration = await input.computeDuration();- if (!(duration > 0)) return [];-- const peaks = new Array<number>(buckets).fill(0);- let published = 0;- for await (const { buffer, timestamp } of new AudioBufferSink(track).buffers()) {- const data = buffer.getChannelData(0);- const rate = buffer.sampleRate;- // Every 8th sample, matching what the whole-file pass measured.- for (let i = 0; i < data.length; i += 8) {- const v = Math.abs(data[i]);- const at = (timestamp + i / rate) / duration;- const bucket = Math.min(buckets - 1, Math.max(0, Math.floor(at * buckets)));- if (v > peaks[bucket]) peaks[bucket] = v;+ const peaks = new Array<number>(buckets).fill(0);+ let published = 0;+ // Where the next pass picks up. A play ends the walk rather than suspending+ // it — a suspended walk keeps the file, the decoder and the buffers it had+ // in flight, which is what the preview was short of — so the read resumes+ // from the second it had reached.+ let from = 0;+ for (;;) {+ await gate?.idle();+ const input = openMedia(src);+ let read = 0;+ let done = true;+ try {+ const track = await audioTrackOf(input);+ if (!track) return [];+ // Read the length first so each chunk can be folded into its bucket and+ // dropped; without it the buckets aren't known until the last sample, and+ // the whole file has to be held to place any of it.+ const duration = await input.computeDuration();+ if (!(duration > 0)) return [];++ for await (const { buffer, timestamp } of new AudioBufferSink(track).buffers(from)) {+ const data = buffer.getChannelData(0);+ const rate = buffer.sampleRate;+ // Every 8th sample, matching what the whole-file pass measured.+ for (let i = 0; i < data.length; i += 8) {+ const v = Math.abs(data[i]);+ const at = (timestamp + i / rate) / duration;+ const bucket = Math.min(buckets - 1, Math.max(0, Math.floor(at * buckets)));+ if (v > peaks[bucket]) peaks[bucket] = v;+ }+ read++;+ from = timestamp + buffer.duration;+ if (gate?.busy()) {+ done = false;+ break;+ }+ if (!onPartial) continue;+ const now = Date.now();+ if (now - published < PEAKS_PUBLISH_MS) continue;+ published = now;+ onPartial(peaks.slice());}- if (!onPartial) continue;- const now = Date.now();- if (now - published < PEAKS_PUBLISH_MS) continue;- published = now;- onPartial(peaks.slice());+ } finally {+ input.dispose();}- return peaks;- } finally {- input.dispose();+ // Read to the end, or a pass that got nothing — an unreadable file, a walk+ // that died — which another pass would only repeat.+ if (done || read === 0) return peaks;}}diff --git a/site/src/cut/lib/perfTrace.ts b/site/src/cut/lib/perfTrace.tsindex bc59c8ed..a046477a 100644--- a/site/src/cut/lib/perfTrace.ts+++ b/site/src/cut/lib/perfTrace.ts@@ -91,10 +91,26 @@ export interface LongTaskRecord {ms: number;}+/** A frame the browser reported as long, with the script it blames. */+export interface LongFrameRecord {+ at: number;+ ms: number;+ /** Of that, the part no other work could run in. */+ blockedMs: number;+ fn: string;+ src: string;+ invoker: string;+ scriptMs: number;+}+export interface Trace {presents: PresentRecord[];seeks: SeekRecord[];longTasks: LongTaskRecord[];+ /** The same stretches seen as frames, naming what held them. A long frame+ * spans the task, the style pass, the layout and the paint, so its length+ * is a different number from the task's and is read beside it. */+ longFrames: LongFrameRecord[];/** rAF callbacks the engine ran, for checking that an idle editor is idle. */ticks: number;/** Decoded frames the sources are holding open, sampled per present. */@@ -151,6 +167,7 @@ const SAME_TIME = 0.004;let trace: Trace | null = null;let observer: PerformanceObserver | null = null;+let frameObserver: PerformanceObserver | null = null;/** The seek still waiting for its picture. A later seek replaces it, which is* what makes a fast drag measure the position it settled on. */let pendingSeek: SeekRecord | null = null;@@ -163,6 +180,7 @@ export function startTrace(): void {presents: [],seeks: [],longTasks: [],+ longFrames: [],ticks: 0,liveSamples: [],liveSources: [],@@ -187,12 +205,40 @@ export function startTrace(): void {// run.observer = null;}+ // Beside it, the same stretches as frames. A long task says a frame was+ // held; a long animation frame says which script held it, which is the+ // question a report leads to. They are kept apart because their lengths+ // mean different things and the budgets are set against the task's.+ try {+ frameObserver = new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ if (!trace) continue;+ const lead = leadScript(entry as LongFrameEntry);+ keep(trace.longFrames, {+ at: entry.startTime,+ ms: entry.duration,+ blockedMs: Math.round((entry as LongFrameEntry).blockingDuration ?? 0),+ fn: lead?.sourceFunctionName ?? "",+ src: chunkName(lead?.sourceURL),+ invoker: lead?.invoker ?? "",+ scriptMs: Math.round(lead?.duration ?? 0),+ });+ }+ });+ frameObserver.observe({ type: "long-animation-frame", buffered: false });+ } catch {+ // Long animation frames are newer than long tasks; a browser without them+ // still reports the task.+ frameObserver = null;+ }}export function stopTrace(): Trace | null {const out = trace;observer?.disconnect();observer = null;+ frameObserver?.disconnect();+ frameObserver = null;trace = null;pendingSeek = null;return out;@@ -997,6 +1043,13 @@ function watchInputs(): () => void {};}+/** The script that held a frame the longest, of those the browser named. */+function leadScript(entry: LongFrameEntry): LongFrameScript | null {+ let lead: LongFrameScript | null = null;+ for (const s of entry.scripts ?? []) if (!lead || s.duration > lead.duration) lead = s;+ return lead;+}+function noteLongFrame(entry: LongFrameEntry): void {const m = threadMeter;if (!m) return;@@ -1010,10 +1063,9 @@ function noteLongFrame(entry: LongFrameEntry): void {}const scripts = entry.scripts ?? [];let scriptMs = 0;- let lead: LongFrameScript | null = null;+ const lead = leadScript(entry);for (const s of scripts) {scriptMs += s.duration;- if (!lead || s.duration > lead.duration) lead = s;const fn = s.sourceFunctionName || chunkName(s.sourceURL);const key = `${s.invoker ?? ""}>${fn}`;m.byScript.set(key, (m.byScript.get(key) ?? 0) + s.duration);diff --git a/site/src/cut/lib/posterCache.ts b/site/src/cut/lib/posterCache.tsindex ea5446b7..eb6d98f4 100644--- a/site/src/cut/lib/posterCache.ts+++ b/site/src/cut/lib/posterCache.ts@@ -33,7 +33,7 @@ type PosterKind = "card" | "frame";const WIDTH: Record<PosterKind, number> = { card: 480, frame: 640 };const QUALITY = 0.72;-// How long to keep asking a surface for its picture, and how often. A card+// How long to keep asking a card for its picture, and how often. A card// element renders its poster frame without ever firing a reliable event — a// preload="metadata" video may never reach `loadeddata` — so the picture is// taken by asking rather than by listening.@@ -97,8 +97,61 @@ export function capturePoster(}}+// The stage says when it has drawn a real picture, so the preview's poster+// is taken from a frame known to be there. Asking on a timer instead meant a+// pixel readback of the stage every few hundred milliseconds for the first+// twenty seconds of every open — each one a flush of the GPU work behind the+// canvas, landing on the drop and the first play — for a picture the stage+// could simply have announced.+const pictureListeners = new Set<() => void>();++/** The stage drew a paused frame with a picture in it. */+export function noteStagePicture(): void {+ for (const fn of pictureListeners) fn();+}++/** How long after a black picture the next one is read. A cut that opens on+ * a fade from black draws pictures for a while before one has anything in it. */+const RETRY_MS = 1_000;++/** Keep the stage's picture once it has drawn one, reading the pixels off the+ * draw the stage announces. A picture that reads back black is tried again a+ * second later, for as long as the stage stays open. Returns a canceller for+ * the caller's cleanup. */+export function capturePosterOnPicture(+ kind: PosterKind,+ projectId: string,+ source: () => HTMLCanvasElement | null,+ scope?: CutMode+): () => void {+ let last = -Infinity;+ let pending = 0;+ const onPicture = () => {+ if (pending || performance.now() - last < RETRY_MS) return;+ // Off the stage's own tick: the readback waits for the frame to be+ // handed over, so the draw that announced it is not held for it.+ pending = window.setTimeout(() => {+ pending = 0;+ const el = source();+ // No canvas this instant is a render between the draw and this read,+ // which says nothing about the picture: wait for the next draw. Only a+ // picture actually kept ends the listening.+ if (!el) return;+ last = performance.now();+ if (capturePoster(kind, projectId, el, scope)) pictureListeners.delete(onPicture);+ }, 0);+ };+ pictureListeners.add(onPicture);+ return () => {+ pictureListeners.delete(onPicture);+ window.clearTimeout(pending);+ };+}+/** Keep asking `source` for its picture until one is there to keep, then stop.- * Returns a canceller for the caller's cleanup. */+ * A card's video element renders its poster frame without ever firing a+ * reliable event, so the picture is taken by asking. Returns a canceller for+ * the caller's cleanup. */export function capturePosterWhenReady(kind: PosterKind,projectId: string,diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex da33e519..e0af3739 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -1,5 +1,5 @@import { spawn } from "node:child_process";-import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { copyFile, constants, mkdir, readFile, rm, writeFile } from "node:fs/promises";import path from "node:path";import type { ClipSound } from "@donkeycut/effects-kit";import { resolveParent, settleParents } from "@/cut/lib/folderTree";@@ -84,6 +84,7 @@ export interface TemplateLayer {muted: boolean;speed?: number;speedCurve?: [number, number][];+ reverse?: boolean;sound?: ClipSound;track: number;asClip?: boolean; // re-materializes as a track-0 timeline clip rather than an overlay@@ -98,6 +99,7 @@ export interface TemplateAudio {fadeOut?: number;speed?: number;speedCurve?: [number, number][];+ reverse?: boolean;sound?: ClipSound;}export interface LibraryTemplate {@@ -361,7 +363,11 @@ export async function useInProject(const base = asset.fileName;const dest = await uniqueName(base, (n) => projectMediaPath(projectId, n));- await copyFile(libMediaPath(base), projectMediaPath(projectId, dest));+ // A clone where the disk offers one: the project's file shares the+ // shelf's blocks until either is written, so landing a multi-gigabyte+ // recording is a metadata write, and the page reading the project's copy+ // a moment later is not waiting behind the bytes.+ await copyFile(libMediaPath(base), projectMediaPath(projectId, dest), constants.COPYFILE_FICLONE);return dest;}