Open source CapCut alternative.
TypeScript
fix(site): hold the whole-video walk while the cut plays
David Le68db5bd193fd
diff --git a/site/src/cut/lib/chunkCache.ts b/site/src/cut/lib/chunkCache.tsindex c3a22461..30b30c33 100644--- a/site/src/cut/lib/chunkCache.ts+++ b/site/src/cut/lib/chunkCache.ts@@ -1091,8 +1091,14 @@ export async function adoptChunks(fromUrl: string, toUrl: string): Promise<void>/** Walk a file's chunks into the store front to back, skipping what is* already resident or in the air. Stops on abort, on a store that has run out- * of room, and on a network failure — every chunk that landed stays. */-export async function prefetchChunks(url: string, signal: AbortSignal): Promise<void> {+ * of room, and on a network failure — every chunk that landed stays. `gate`+ * holds the walk before each request, for as long as something with a better+ * claim on the link needs it. */+export async function prefetchChunks(+ url: string,+ signal: AbortSignal,+ gate?: () => Promise<void>+): Promise<void> {if (!supportsBrowserStore() || signal.aborted) return;const id = chunkIdentity(url);if (!id) return;@@ -1104,6 +1110,11 @@ export async function prefetchChunks(url: string, signal: AbortSignal): Promise<for (let i = 0; i < total; i++) {if (signal.aborted || !canPersist(state)) return;if (state.resident.has(i) || state.inflight.has(i)) continue;+ if (gate) {+ await gate();+ if (signal.aborted) return;+ if (state.resident.has(i) || state.inflight.has(i)) continue;+ }let last = i;while (last - i + 1 < PREFETCH_RUN &&diff --git a/site/src/cut/lib/mediaSync.ts b/site/src/cut/lib/mediaSync.tsindex 5e3a9a40..934650b3 100644--- a/site/src/cut/lib/mediaSync.ts+++ b/site/src/cut/lib/mediaSync.ts@@ -247,16 +247,17 @@ let prefetch: PrefetchRun | null = null;* and swap onto blob URLs, so an <img> paints local bytes offline. Every file* reports back through `onDone` exactly once — its blob URL when whole bytes* landed, null otherwise — so the caller can swap playing assets mid-session- * and retire per-file loading state either way. Videos wait for `videosAfter`- * (the clip spans the cut plays, read first) while the other files go ahead. Starting a prefetch cancels- * any earlier one — the queue follows the open project — and records the open+ * and retire per-file loading state either way. Videos hold at `videoGate`+ * before each file and each ranged request — the caller's wait for the clip+ * spans the cut plays and for a play to stop — while the other files go+ * ahead. Starting a prefetch cancels any earlier one — the queue follows the open project — and records the open* for eviction recency. Fire-and-forget; a failed or refused write costs* nothing but the cache. */export function prefetchCloudMedia(projectId: string,files: { fileName: string; url: string; type?: AssetType }[],onDone?: (fileName: string, blobUrl: string | null) => void,- videosAfter?: () => Promise<void>+ videoGate?: () => Promise<void>): void {if (!supportsBrowserStore()) {for (const f of files) onDone?.(f.fileName, null);@@ -274,18 +275,12 @@ export function prefetchCloudMedia(// The small files a still or a sticker paints go first; the videos follow// the spans the cut plays.files = [...files.filter((f) => f.type !== "video"), ...files.filter((f) => f.type === "video")];- let waited = false;for (let i = 0; i < files.length; i++) {if (run.ctrl.signal.aborted) return;const f = files[i];- if (f.type === "video" && !waited) {- waited = true;- await videosAfter?.().catch(() => {});- if (run.ctrl.signal.aborted) return;- }const r =f.type === "video"- ? await cacheVideoChunks(f.url, run.ctrl.signal)+ ? await cacheVideoChunks(f.url, run.ctrl.signal, videoGate): await cacheOne(projectId, f.fileName, f.url, run.ctrl.signal).catch(// Offline mid-stream: the abort discarded the partial write.() => ({ go: true, url: null as string | null })@@ -306,9 +301,10 @@ export function prefetchCloudMedia(* on-demand reads finish it — and the queue always goes on. */async function cacheVideoChunks(url: string,- signal: AbortSignal+ signal: AbortSignal,+ gate?: () => Promise<void>): Promise<{ go: boolean; url: string | null }> {- await prefetchChunks(url, signal).catch(() => {});+ await prefetchChunks(url, signal, gate).catch(() => {});return { go: !signal.aborted, url: null };}diff --git a/site/src/cut/lib/spanWarm.ts b/site/src/cut/lib/spanWarm.tsindex db511b29..e0b31a6e 100644--- a/site/src/cut/lib/spanWarm.ts+++ b/site/src/cut/lib/spanWarm.ts@@ -101,6 +101,9 @@ export function warmClipSpans(spans: WarmSpan[]): Promise<void> {return done;}+/** Whether a walk is reading now. */+export const clipWarmBusy = (): boolean => walk !== null;+/** Resolves once no walk is reading: the one running now, and any a play* started in its place. What waits on this — the whole-file prefetch — never* shares the link with a walk the playhead depends on. */diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 18c43639..1a23b97e 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -73,7 +73,7 @@ import { fetchSignedMediaUrls, pinDocBase } from "./backend/cloud";import { cancelRevoke, resolveRegisteredBlob, revokeRegistered } from "./backend/browser/registry";import { markSignedBatch } from "./mediaLinks";import { dropLocalMedia, localMediaUrl, prefetchCloudMedia } from "./mediaSync";-import { clipWarmSettled, stopClipWarm, warmClipSpans, warmOrder } from "./spanWarm";+import { clipWarmBusy, clipWarmSettled, stopClipWarm, warmClipSpans, warmOrder } from "./spanWarm";import {dropCachedDoc,readCachedDoc,@@ -2217,9 +2217,12 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {Math.min(firstUse.get(asset.fileName) ?? Infinity, c.start));}+ // A video the preview plays through its proxy is walked as the+ // proxy: the preview never reads that master, and a render reads+ // it on the worker or on demand.const queue = missing.flatMap((a) => {- const url = signed.urls.get(a.fileName);+ const url = (a.type === "video" ? a.proxyUrl : undefined) ?? signed.urls.get(a.fileName);return url ? [{ fileName: a.fileName, url, type: a.type }] : [];}).sort(@@ -2250,7 +2253,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {next.delete(fileName);return { loadingMedia: next };});- }, clipWarmSettled);+ }, videoWalkGate);}} else {markSignedBatch(id, null);@@ -5372,6 +5375,27 @@ useEditor.subscribe((s, prev) => {docSeq++;});+/** Resolves once the cut is not playing. */+function untilStopped(): Promise<void> {+ if (!useEditor.getState().playing) return Promise.resolve();+ return new Promise((resolve) => {+ const off = useEditor.subscribe((s) => {+ if (s.playing) return;+ off();+ resolve();+ });+ });+}++/** The whole-video walk's hold: it reads only while no clip spans are being+ * read and the cut is not playing, so the link is the play's. */+export async function videoWalkGate(): Promise<void> {+ while (clipWarmBusy() || useEditor.getState().playing) {+ await clipWarmSettled();+ await untilStopped();+ }+}+// A play from a new spot reads ahead from there: the walk the open started// may still be reading the far end of the cut, or have finished long before// an edit put new clips under the playhead.diff --git a/site/src/cut/lib/videoWalkGate.test.ts b/site/src/cut/lib/videoWalkGate.test.tsnew file mode 100644index 00000000..0c5562d2--- /dev/null+++ b/site/src/cut/lib/videoWalkGate.test.ts@@ -0,0 +1,39 @@+import { expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";++// The whole-video walk downloaded masters beside a play and took the link+// from the clips the play was opening. It now reads only while the cut is+// stopped and no clip spans are being read.+let releaseRead!: () => void;+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, {+ openMediaShared: (() => ({ input: {} as never, release: () => {} })) as never,+ videoTrackOf: (() => new Promise((resolve) => (releaseRead = () => resolve(null)))) as never,+});+const { useEditor, videoWalkGate } = await import("./store");+const { warmClipSpans } = await import("./spanWarm");++const tick = () => new Promise((r) => setTimeout(r, 10));++test("the walk holds while the cut plays and goes once it stops", async () => {+ useEditor.setState({ playing: true });+ let open = false;+ void videoWalkGate().then(() => (open = true));+ await tick();+ expect(open).toBe(false);+ useEditor.setState({ playing: false });+ await tick();+ expect(open).toBe(true);+});++test("the walk holds while clip spans are read and goes once they land", async () => {+ useEditor.setState({ playing: false });+ const reading = warmClipSpans([{ url: "https://m/a.mp4.light.mp4", from: 0, to: 0.5 }]);+ let open = false;+ void videoWalkGate().then(() => (open = true));+ await tick();+ expect(open).toBe(false);+ releaseRead();+ await reading;+ await tick();+ expect(open).toBe(true);+});