Skip to content

Open source CapCut alternative.

TypeScript

perf(site): the tab holds a file once, under one memory ceiling

David Le7417aa7fed6a
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index db28df15..ca53a3b0 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -44,6 +44,8 @@ The client probes the engine's health endpoint (dedicated port first, dev server
**A handover is on the picture or on the sound.** A transition is a blend at the cut rather than an overlap: the clips still abut, the layout never moves, and the incoming clip starts exactly at the cut. Most styles blend the picture across the outgoing clip's last seconds. The cross dissolve hands over on the sound instead — the picture cuts while the two clips ramp past each other, half the handover either side of it. Its bar sits across the cut for that reason, where every other bar ends on the boundary it plays. The two windows sit on separate fields, so everything that draws the picture reads a plain cut and only the mix ramps: the preview, the in-tab export, and the ffmpeg graph the engine and the worker build all follow from that one split. A sound handover needs a second clip's sound to cross into, so a bar of it parked on a clip's open head or tail plays nothing.
+**A clip's rate is a curve over its footage.** A clip plays at one speed, or at a speed that changes through it: nodes pinned to moments in the source, each with a rate, joined by a smooth curve that holds its shape through trims and splits because the nodes belong to the footage. One map sits under it — timeline seconds to source seconds and back — and everything that reads a clip reads that map: the preview's decoder and its pitch-held sound, the in-tab export, the filmstrip on the bar, the beat dots, the assistant's cue arithmetic, and the ffmpeg graph the engine and the cloud worker build. The picture side of that graph is the map itself written as a timestamp expression; the sound side is baked first, since ffmpeg's tempo filter only takes a constant, so all three renderers stretch the sound with the same code. The curve is edited in a strip over the timeline — the footage behind the graph, the beats as ticks a node snaps to, presets for the usual ramps — and the assistant lays one from a description with the same tool.
+
**A crossing needs handle, and holds its loudness.** Clips never overlap, so for the length of a cross dissolve each one plays into the other's time out of its handle — the media its trim left behind, the outgoing clip past its out point and the incoming clip before its in point. That is what makes both sides really audible over a cut their pictures hard-join, and it is why the ramps are equal-power (sine and cosine) rather than straight lines: two signals meeting at half level sum to the loudness they each had, so the mix never dips through the join. A clip trimmed to the end of its source has no handle to reach into; its side of the crossing stops at the cut, and the handover reads as a dip instead of a crossing. Every renderer works from the same two numbers on a span — how far the crossing runs, and how far each side reaches — so the preview, the browser fold and the ffmpeg graph land on one sound. It opens at 0.3 seconds, shorter than a picture blend's half second: that covers the jump in room tone at a cut while staying under the length where the ear starts hearing two voices, and it asks less of the trim each clip has left. It is picked where the other work on the sound is picked — the Effects tab's Sound family — while the styles that blend the picture are picked from the Transitions tab. A bar can also be hidden, like anything else on the timeline: it grays out and plays nothing while keeping the cut it sits on, so the joint runs hard and the blend is one click away again.
## The preview
@@ -60,7 +62,7 @@ Some machines cannot decode the footage as fast as it plays, and no reader can i
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.
+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 an eighth 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.
The ceiling is a model. The memory that runs a machine out is memory a page cannot see — decoded frames sit inside the platform's decoder, canvas backing sits in the GPU process, and the browser reports the size of neither — so the counting happens at the allocation sites, where the sizes are known exactly. What the browser does report is roughly how much memory the machine has, which is enough to tell a laptop from a workstation.
diff --git a/site/src/cut/lib/behindPass.ts b/site/src/cut/lib/behindPass.ts
index d5867d1d..56d4d12f 100644
--- a/site/src/cut/lib/behindPass.ts
+++ b/site/src/cut/lib/behindPass.ts
@@ -19,7 +19,7 @@ import {
wordSampleWindows,
} from "@donkeycut/effects-kit";
import { personSegmenter, segmentSubjectAlpha } from "./cutout";
-import { holdMemory } from "./memoryBudget";
+import { allowance, holdMemory } from "./memoryBudget";
import { createRasterCanvas } from "./raster";
import { renderElementPng } from "./textRender";
import {
@@ -115,6 +115,19 @@ export function subjectMatteSnapshot(): { canvas: HTMLCanvasElement | null; at:
* headless they are server canvases with the same 2D interface. */
const scratchCanvas = () => createRasterCanvas(1, 1) as HTMLCanvasElement;
+/** Element pictures the pass may hold: the elements live on one frame are a
+ * handful of full-size pictures, and a play through the cut reaches every
+ * element in it. */
+const RASTER_TUNED = 48 * 2 ** 20;
+
+/** What one element's pictures cost: one per word it lights, four bytes a
+ * pixel, at the size of the frame they are drawn on. */
+const entryBytes = (e: { byWord: Map<number, ImageBitmap> }): number => {
+ let n = 0;
+ for (const b of e.byWord.values()) n += b.width * b.height * 4;
+ return n;
+};
+
export class SubjectMaskCompositor {
/** `publishes` marks the live preview's instance, the one whose matte the
* DOM layer reads. */
@@ -140,12 +153,15 @@ export class SubjectMaskCompositor {
*/
private rasters = new Map<
string,
- { of: Overlay; byWord: Map<number, ImageBitmap>; pending: Set<number> }
+ { of: Overlay; byWord: Map<number, ImageBitmap>; pending: Set<number>; usedAt: number }
>();
- private readonly releaseMemory = holdMemory("pictures", () => {
+ /** Frames this pass has drawn, which is the clock the pictures are given
+ * back on: an element drawn on the frame being composited is the one the
+ * next frame will ask for again. */
+ private pass = 0;
+ private readonly releaseMemory = holdMemory("overlayRasters", () => {
let n = 0;
- for (const e of this.rasters.values())
- for (const b of e.byWord.values()) n += b.width * b.height * 4;
+ for (const e of this.rasters.values()) n += entryBytes(e);
return n;
});
private person: HTMLCanvasElement | null = null;
@@ -176,12 +192,37 @@ export class SubjectMaskCompositor {
entry.of = o;
}
if (!entry) {
- entry = { of: o, byWord: new Map(), pending: new Set() };
+ entry = { of: o, byWord: new Map(), pending: new Set(), usedAt: this.pass };
this.rasters.set(o.id, entry);
}
+ entry.usedAt = this.pass;
return entry;
}
+ /**
+ * Give back the pictures of the elements this pass has gone longest without
+ * drawing, once what it holds is past its share.
+ *
+ * A picture is one full-size frame per element, so a play through a cut
+ * whose elements come and go leaves the pass holding every one it has ever
+ * drawn. What a frame is drawing was drawn on the frame before it, so the
+ * live ones are the youngest and stay; an element the playhead has left
+ * draws again from scratch when it is next reached.
+ */
+ private sweepRasters(): void {
+ const cap = allowance("overlayRasters", RASTER_TUNED);
+ let held = 0;
+ for (const e of this.rasters.values()) held += entryBytes(e);
+ if (held <= cap) return;
+ for (const [id, e] of [...this.rasters].sort((a, b) => a[1].usedAt - b[1].usedAt)) {
+ if (held <= cap) break;
+ if (e.usedAt >= this.pass) continue;
+ held -= entryBytes(e);
+ for (const b of e.byWord.values()) b.close();
+ this.rasters.delete(id);
+ }
+ }
+
private rasterFor(
o: Overlay,
w: number,
@@ -404,6 +445,7 @@ export class SubjectMaskCompositor {
// means the entry outlives the element, so the document's own list is what
// says which entries are still owed — checked only when there are more of
// them than elements, which is the only way one can be stale.
+ this.pass++;
if (this.rasters.size > overlays.length) {
const ids = new Set(overlays.map((o) => o.id));
for (const [id, e] of this.rasters) {
@@ -412,6 +454,7 @@ export class SubjectMaskCompositor {
this.rasters.delete(id);
}
}
+ this.sweepRasters();
const active = behindOverlaysAt(overlays, t);
const wantsMatte = overlays.some(
(o) => frontSubjectOverlay(o) && drawable(o) && t >= o.start && t <= o.end
diff --git a/site/src/cut/lib/chunkCache.test.ts b/site/src/cut/lib/chunkCache.test.ts
index dd9281e6..399d1153 100644
--- a/site/src/cut/lib/chunkCache.test.ts
+++ b/site/src/cut/lib/chunkCache.test.ts
@@ -1,11 +1,13 @@
import { describe, expect, test } from "bun:test";
import {
CHUNK_SIZE,
+ ChunkMemory,
chunkIdentity,
chunkRuns,
collect,
decodeResident,
encodeResident,
+ routeMediaUrl,
streamRun,
} from "./chunkCache";
@@ -55,6 +57,80 @@ describe("chunkIdentity", () => {
});
});
+describe("routeMediaUrl", () => {
+ const page = "https://donkeycut.com";
+
+ test("takes the page's own media routes, relative or absolute", () => {
+ expect(routeMediaUrl("/api/cut-cloud/projects/p1/media/a%20b.mp4", page)).toBe(
+ "https://donkeycut.com/api/cut-cloud/projects/p1/media/a%20b.mp4"
+ );
+ expect(routeMediaUrl(`${page}/api/cut-cloud/library/media/a.mp4`, page)).toBe(
+ `${page}/api/cut-cloud/library/media/a.mp4`
+ );
+ });
+
+ test("takes a shared view's media route, so a viewer holds the file once", () => {
+ // A share reads the owner's bytes through its token, and the route
+ // redirects to the same media origin the owner's own route lands on.
+ expect(routeMediaUrl("/api/cut-shared/tok3n/projects/p1/media/a.mp4", page)).toBe(
+ `${page}/api/cut-shared/tok3n/projects/p1/media/a.mp4`
+ );
+ });
+
+ test("answers null for anything that is not a route to media", () => {
+ expect(routeMediaUrl("https://example.com/api/cut-cloud/projects/p1/media/a.mp4", page)).toBe(null);
+ expect(routeMediaUrl("http://localhost:41417/api/cut/projects/p/media/a.mp4", page)).toBe(null);
+ expect(routeMediaUrl(`${page}/api/cut-cloud/projects/p1`, page)).toBe(null);
+ expect(routeMediaUrl(`${page}/api/cut-shared/tok3n/projects/p1`, page)).toBe(null);
+ expect(routeMediaUrl("https://media.donkeycut.com/cut/u1/library/a.mp4?e=1&s=x", page)).toBe(null);
+ expect(routeMediaUrl("/api/cut-cloud/projects/p1/media/a.mp4", "")).toBe(null);
+ });
+});
+
+describe("ChunkMemory", () => {
+ const bytes = (n: number, fill = 1) => new Uint8Array(n).fill(fill);
+
+ test("holds a chunk once for every reader and counts what it holds", () => {
+ const m = new ChunkMemory(() => 10);
+ m.remember("a", 0, bytes(4));
+ m.remember("a", 0, bytes(4, 2));
+ expect(m.held).toBe(4);
+ expect(m.recall("a", 0)?.[0]).toBe(2);
+ expect(m.recall("a", 1)).toBe(null);
+ expect(m.recall("b", 0)).toBe(null);
+ });
+
+ test("lets the least recently touched chunk go at the cap", () => {
+ const m = new ChunkMemory(() => 10);
+ m.remember("a", 0, bytes(4));
+ m.remember("a", 1, bytes(4));
+ m.recall("a", 0);
+ m.remember("a", 2, bytes(4));
+ expect(m.held).toBe(8);
+ expect(m.recall("a", 1)).toBe(null);
+ expect(m.recall("a", 0)).not.toBe(null);
+ expect(m.recall("a", 2)).not.toBe(null);
+ });
+
+ test("refuses a chunk larger than the whole cap", () => {
+ const m = new ChunkMemory(() => 3);
+ m.remember("a", 0, bytes(4));
+ expect(m.held).toBe(0);
+ expect(m.recall("a", 0)).toBe(null);
+ });
+
+ test("forgets a version whole and leaves the others", () => {
+ const m = new ChunkMemory(() => 100);
+ m.remember("k/v1", 0, bytes(4));
+ m.remember("k/v1", 1, bytes(4));
+ m.remember("k/v2", 0, bytes(4));
+ m.forget("k/v1");
+ expect(m.held).toBe(4);
+ expect(m.recall("k/v1", 0)).toBe(null);
+ expect(m.recall("k/v2", 0)).not.toBe(null);
+ });
+});
+
describe("chunkRuns", () => {
test("groups consecutive indices into runs", () => {
expect(chunkRuns([0, 1, 2, 5, 6, 9], 8)).toEqual([
diff --git a/site/src/cut/lib/chunkCache.ts b/site/src/cut/lib/chunkCache.ts
index 17328993..94c564c6 100644
--- a/site/src/cut/lib/chunkCache.ts
+++ b/site/src/cut/lib/chunkCache.ts
@@ -26,6 +26,18 @@
* closing the editor stops the downloads while one decoder disposing mid-run
* leaves another's bytes coming.
*
+ * The bytes are held in this tab once. Every reader on a file — the
+ * picture's walk, the sound's, the peaks, the filmstrip — reads through the
+ * same chunk memory here, sized from the tab's reads share, so a chunk one
+ * of them just pulled off disk or the network serves the rest from memory
+ * and none of them keeps a copy of its own past the few megabytes its walk
+ * is standing on.
+ *
+ * A route URL — the page's own `/api/cut-cloud/.../media/...` address, which
+ * an asset carries while it has no signed link — opens here too: the route
+ * answers with a redirect to the signed object, and the object is what the
+ * store keys on, so a reader on either address finds the same chunks.
+ *
* Everything here is a cache. A quota refusal, a torn write, or a browser
* with no OPFS costs the network read it always cost; a read that cannot
* reach the network at all is the one failure that propagates, and the
@@ -40,6 +52,7 @@ import {
writeFileAt,
} from "./backend/browser/opfs";
import { CUT_MEDIA_ORIGIN } from "./hosts";
+import { allowance, holdMemory } from "./memoryBudget";
export const CHUNK_SIZE = 2 * 1024 * 1024;
/** Longest single ranged request, in chunks, when a read needs a missing run. */
@@ -188,6 +201,105 @@ export function decodeResident(b64: string, total: number): Set<number> {
const chunkCount = (size: number) => Math.ceil(size / CHUNK_SIZE);
const chunkLen = (idx: number, size: number) => Math.min(CHUNK_SIZE, size - idx * CHUNK_SIZE);
+/**
+ * The page's own media routes: a project's file or a library file on the
+ * cloud surface, and a shared view's project file, which reaches the owner's
+ * bytes through a share token.
+ *
+ * Both redirect to the media origin, which is the address the store holds an
+ * object under, so someone reading a cut shared with them holds the file once
+ * for every reader on it, the way its owner does.
+ */
+const ROUTE_MEDIA_PATH =
+ /^\/api\/cut-(?:cloud|shared\/[^/]+)\/(?:projects\/[^/]+|library)\/media\/[^/]+$/;
+
+/** A route URL as this page would fetch it, or null for any other address.
+ * Relative routes resolve against the page; an absolute one has to be the
+ * page's own origin, since that is the only server that answers them. */
+export function routeMediaUrl(
+ url: string,
+ origin = typeof location === "undefined" ? "" : location.origin
+): string | null {
+ if (!origin) return null;
+ let u: URL;
+ try {
+ u = new URL(url, origin);
+ } catch {
+ return null;
+ }
+ if (u.origin !== origin || !ROUTE_MEDIA_PATH.test(u.pathname)) return null;
+ return u.href;
+}
+
+// --- memory ---
+
+/**
+ * Chunks held in memory, once each, for every reader on the object.
+ *
+ * Least recently touched goes first when the cap is reached. A chunk is keyed
+ * by the object version it belongs to, so two versions of one object never
+ * answer for each other, and forgetting a version drops everything it held.
+ */
+export class ChunkMemory {
+ private chunks = new Map<string, Uint8Array>();
+ private bytes = 0;
+
+ constructor(private readonly cap: () => number) {}
+
+ /** Bytes held right now. */
+ get held(): number {
+ return this.bytes;
+ }
+
+ recall(scope: string, idx: number): Uint8Array | null {
+ const k = `${scope}/${idx}`;
+ const hit = this.chunks.get(k);
+ if (!hit) return null;
+ this.chunks.delete(k);
+ this.chunks.set(k, hit);
+ return hit;
+ }
+
+ remember(scope: string, idx: number, bytes: Uint8Array): void {
+ const k = `${scope}/${idx}`;
+ const prior = this.chunks.get(k);
+ if (prior) {
+ this.bytes -= prior.length;
+ this.chunks.delete(k);
+ }
+ const cap = this.cap();
+ if (bytes.length > cap) return;
+ this.chunks.set(k, bytes);
+ this.bytes += bytes.length;
+ while (this.bytes > cap) {
+ const oldest = this.chunks.keys().next().value!;
+ this.bytes -= this.chunks.get(oldest)!.length;
+ this.chunks.delete(oldest);
+ }
+ }
+
+ forget(scope: string): void {
+ for (const [k, bytes] of this.chunks) {
+ if (k.startsWith(`${scope}/`)) {
+ this.bytes -= bytes.length;
+ this.chunks.delete(k);
+ }
+ }
+ }
+}
+
+/** What the chunk memory was tuned to hold: a minute of a phone recording,
+ * which is the stretch the picture, the sound and the peaks are all reading
+ * from at once. */
+const MEMORY_TUNED = 128 * 2 ** 20;
+/** Decided once: the ceiling does not move, and every ask re-records the
+ * same pressure. */
+let memoryCap = 0;
+const memory = new ChunkMemory(
+ () => (memoryCap ||= allowance("chunkMemory", MEMORY_TUNED))
+);
+holdMemory("chunkMemory", () => memory.held);
+
// --- open ---
const states = new Map<string, Promise<ObjState>>();
@@ -568,30 +680,45 @@ async function readRange(state: ObjState, start: number, end: number): Promise<U
const to = Math.min(end, base + bytes.length);
if (to > from) out.set(bytes.subarray(from - base, to - base), from - start);
};
- // Plan first: pin the fetches already in the air, then open one run per
- // consecutive stretch that has to touch the network.
+ // Plan first: serve what memory holds, pin the fetches already in the air,
+ // then open one run per consecutive stretch that has to touch the network.
+ const scope = stateKey(state.id);
const have = new Map<number, Promise<Uint8Array>>();
+ const served = new Set<number>();
const need: number[] = [];
for (let i = c0; i <= c1; i++) {
- const flying = state.inflight.get(i);
- if (flying) have.set(i, flying);
- else if (!state.resident.has(i) && !(i === 0 && state.probe0)) need.push(i);
+ const mem = memory.recall(scope, i);
+ if (mem) {
+ // Already in memory: copied out here, so nothing holds the chunk open
+ // while the rest of the read waits on the network.
+ place(i, mem);
+ served.add(i);
+ } else {
+ const flying = state.inflight.get(i);
+ if (flying) have.set(i, flying);
+ else if (!state.resident.has(i) && !(i === 0 && state.probe0)) need.push(i);
+ }
}
for (const [a, b] of chunkRuns(need, MAX_RUN)) {
const runPromises = startRun(state, a, b);
for (let i = a; i <= b; i++) have.set(i, runPromises[i - a]);
}
+ const keep = (idx: number, bytes: Uint8Array) => {
+ memory.remember(scope, idx, bytes);
+ return bytes;
+ };
await Promise.all(
Array.from({ length: c1 - c0 + 1 }, async (_, k) => {
const idx = c0 + k;
+ if (served.has(idx)) return;
const planned = have.get(idx);
- if (planned) return place(idx, await planned);
+ if (planned) return place(idx, keep(idx, await planned));
if (idx === 0 && state.probe0 && !state.resident.has(0)) return place(0, state.probe0);
const disk = await residentBytes(state, idx);
- if (disk) return place(idx, disk);
+ if (disk) return place(idx, keep(idx, disk));
// The disk copy vanished under us (evicted mid-read); fetch it alone.
const [refetch] = startRun(state, idx, idx);
- place(idx, await refetch);
+ place(idx, keep(idx, await refetch));
})
);
return out;
@@ -730,6 +857,7 @@ async function removeVersion(keyHash: string, versionTag: string, bytes: number)
return 0;
}
const k = `${keyHash}/${versionTag}`;
+ memory.forget(k);
const live = states.get(k);
if (live) {
states.delete(k);
@@ -774,10 +902,50 @@ export async function dropChunksMatching(part: string): Promise<void> {
// --- the seams ---
-/** CustomSource callbacks over the chunk store for a signed cloud media URL,
- * or null when the URL is not cloud media or this browser holds no store —
- * the caller falls back to a plain URL source. `dispose` releases the object,
- * which cancels its requests once nothing else is reading it. */
+/**
+ * Open the object a route URL redirects to.
+ *
+ * The route answers a ranged read with a redirect to the signed object, and
+ * the URL the bytes came from is the one the store keys on. One byte is
+ * enough to learn it; the body is let go before the object opens, so the
+ * open reads chunk 0 the way every open does.
+ */
+/**
+ * Route probes in the air, by route URL.
+ *
+ * Every reader on a file opens at once — the picture, the sound, the peaks,
+ * the filmstrip — and each learns the object's address only from its own
+ * probe, so without this each would spend a round trip through the route
+ * (which signs a URL, and for a share resolves the share) before `states`
+ * could hold them together. The memo is dropped the moment the probe settles,
+ * so a reader opening later still asks the route for a freshly signed URL.
+ */
+const probes = new Map<string, Promise<ObjState>>();
+
+function openThroughRoute(route: string): Promise<ObjState> {
+ const flying = probes.get(route);
+ if (flying) return flying;
+ const probe = probeRoute(route).finally(() => {
+ if (probes.get(route) === probe) probes.delete(route);
+ });
+ probes.set(route, probe);
+ return probe;
+}
+
+async function probeRoute(route: string): Promise<ObjState> {
+ const res = await fetchRange(route, 0, 0);
+ if (!res.ok) throw new Error(`Cloud media read failed (${res.status}).`);
+ await res.body?.cancel().catch(() => {});
+ const id = chunkIdentity(res.url);
+ if (!id) throw new Error("Cloud media route did not land on the media origin.");
+ return openObject(id, res.url);
+}
+
+/** CustomSource callbacks over the chunk store for a signed cloud media URL
+ * or the page's own route to one, or null when the URL is neither or this
+ * browser holds no store — the caller falls back to a plain URL source.
+ * `dispose` releases the object, which cancels its requests once nothing else
+ * is reading it. */
export function chunkSourceOptions(url: string): {
getSize: () => Promise<number>;
read: (start: number, end: number) => Promise<Uint8Array>;
@@ -785,11 +953,12 @@ export function chunkSourceOptions(url: string): {
} | null {
if (!supportsBrowserStore()) return null;
const id = chunkIdentity(url);
- if (!id) return null;
+ const route = id ? null : routeMediaUrl(url);
+ if (!id && !route) return null;
let opened: Promise<ObjState> | null = null;
let disposed = false;
const open = () =>
- (opened ??= openObject(id, url).then((s) => {
+ (opened ??= (id ? openObject(id, url) : openThroughRoute(route!)).then((s) => {
if (disposed) throw new DOMException("Aborted", "AbortError");
acquire(s);
return s;
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index 40751f2d..5cbc16c7 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -32,7 +32,7 @@ import { renderMix, type MixClip, type MixItem, type MixSpec } from "./audioMix"
import { FrameCompositor, MISSING_FRAME, type Frame } from "./composite";
import { overlayPlan, trackZeroPlan } from "./framePlan";
import { frameSink, openMedia, videoTrackOf } from "./mediaRead";
-import { allowance, canvasBytes } from "./memoryBudget";
+import { allowance, canvasBytes, holdMemory } from "./memoryBudget";
import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
import { applyEffectToCanvas, evalOverlayFrame, grainTile, isAudioEffect, isMaskAnimated, isOverlayAnimated, maskFrameAt, MATTE_FPS, matteLumaToAlpha, planAnimatedLayers, type LottieHandle, type OverlayAnim, type PaintPhase } from "@donkeycut/effects-kit";
@@ -853,6 +853,13 @@ export class FramePainter {
private comp: FrameCompositor;
private stamps: StampCache;
private readers = new Map<string, ClipReader>();
+ /** What the open readers are standing on, so a render in the tab shows up
+ * beside the preview's own pictures in the memory report. */
+ private readonly releaseMemory = holdMemory("exportReaders", () => {
+ let n = 0;
+ for (const r of this.readers.values()) n += canvasBytes(READER_POOL * r.sourcePixels);
+ return n;
+ });
/** Frames drawn, which is the clock the readers' eviction order runs on. */
private frameNo = 0;
private behind: SubjectMaskCompositor | null = null;
@@ -973,7 +980,10 @@ export class FramePainter {
*/
private evictReaders(): void {
const cost = (r: ClipReader) => canvasBytes(READER_POOL * r.sourcePixels);
- const cap = allowance("canvases", READERS_TUNED * canvasBytes(READER_POOL * 1920 * 1080));
+ const cap = allowance(
+ "exportReaders",
+ READERS_TUNED * canvasBytes(READER_POOL * 1920 * 1080)
+ );
let held = 0;
for (const r of this.readers.values()) held += cost(r);
if (held <= cap) return;
@@ -1127,6 +1137,7 @@ export class FramePainter {
this.behind?.dispose();
for (const r of this.readers.values()) r.dispose();
this.readers.clear();
+ this.releaseMemory();
}
}
diff --git a/site/src/cut/lib/frameSource.test.ts b/site/src/cut/lib/frameSource.test.ts
index 207f947a..e0e264ad 100644
--- a/site/src/cut/lib/frameSource.test.ts
+++ b/site/src/cut/lib/frameSource.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import type { Timed } from "./frameSource";
import type { MediaAsset } from "./types";
@@ -82,7 +82,37 @@ const frameSink = ((track: FakeTrack, size?: { height?: number }) => ({
const keyframeTimeAt = (async (_track: unknown, t: number) => Math.max(0, Math.floor(t))) as never;
const media = await import("./mediaRead");
-mock.module("./mediaRead", () => ({ ...media, openMedia, videoTrackOf, frameSink, keyframeTimeAt }));
+// The shared open, over the fake files: one input per URL, closed by the
+// last holder to let go, the way the real one is.
+const shared = new Map<string, { input: FakeInput; refs: number }>();
+const openMediaShared = (src: string) => {
+ let entry = shared.get(src);
+ if (!entry) {
+ entry = { input: (openMedia as unknown as (s: string) => FakeInput)(src), refs: 0 };
+ shared.set(src, entry);
+ }
+ const held = entry;
+ held.refs++;
+ let released = false;
+ return {
+ input: held.input,
+ release() {
+ if (released) return;
+ released = true;
+ if (--held.refs > 0) return;
+ if (shared.get(src) === held) shared.delete(src);
+ held.input.dispose();
+ },
+ };
+};
+mock.module("./mediaRead", () => ({
+ ...media,
+ openMedia,
+ openMediaShared,
+ videoTrackOf,
+ frameSink,
+ keyframeTimeAt,
+}));
const { BACK_WINDOW, ClipFrameSource, FrameRing, FrameSourcePool, mappingKey, walkClaim } =
await import("./frameSource");
@@ -320,6 +350,17 @@ describe("walkClaim", () => {
});
describe("FrameSourcePool", () => {
+ // The pool's budgets are the smaller of what it was tuned to want and this
+ // machine's share, and these tests are about the tuning: they put the pool
+ // on a machine with room, which is what a sixteen-gigabyte report is, and
+ // hand the machine back after.
+ beforeEach(() => {
+ Object.defineProperty(navigator, "deviceMemory", { value: 16, configurable: true });
+ });
+ afterEach(() => {
+ delete (navigator as { deviceMemory?: number }).deviceMemory;
+ });
+
test("one source per mapping and size, reused across frames", () => {
const pool = new FrameSourcePool(4);
pool.beginFrame();
diff --git a/site/src/cut/lib/frameSource.ts b/site/src/cut/lib/frameSource.ts
index ebd7db89..14e499de 100644
--- a/site/src/cut/lib/frameSource.ts
+++ b/site/src/cut/lib/frameSource.ts
@@ -23,8 +23,15 @@
* capacity and the pool size move together, and that is the whole memory story.
*/
-import type { Input, InputVideoTrack, WrappedCanvas } from "mediabunny";
-import { frameSink, keyframeTimeAt, openMedia, videoTrackOf, type FrameCanvasSink } from "./mediaRead";
+import type { InputVideoTrack, WrappedCanvas } from "mediabunny";
+import {
+ frameSink,
+ keyframeTimeAt,
+ openMediaShared,
+ videoTrackOf,
+ type FrameCanvasSink,
+ type MediaHandle,
+} from "./mediaRead";
import { allowance, canvasBytes, decodedFrameBytes, holdMemory } from "./memoryBudget";
import { meterPull, meterSource, meterWalk } from "./perfTrace";
import type { MediaAsset } from "./types";
@@ -512,7 +519,8 @@ interface BackWalk {
* show two distinct frames.
*/
export class ClipFrameSource {
- private input: Input | null = null;
+ /** The file, shared with every other source and voice reading it. */
+ private reader: MediaHandle | null = null;
private track: InputVideoTrack | null = null;
private sink: FrameCanvasSink | null = null;
private ring = new FrameRing<WrappedCanvas>(RING);
@@ -968,8 +976,8 @@ export class ClipFrameSource {
// A still's bitmap holds real memory the GC can't see the size of.
if (this.still && this.still.image instanceof ImageBitmap) this.still.image.close();
this.still = null;
- this.input?.dispose();
- this.input = null;
+ this.reader?.release();
+ this.reader = null;
this.track = null;
this.sink = null;
}
@@ -994,7 +1002,7 @@ export class ClipFrameSource {
if (this.closed || asset.type === "image") return;
const aim = ++this.aim;
// Nothing open and nothing opening: the next ask opens the new address.
- if (!this.input && !this.opening) return;
+ if (!this.reader && !this.opening) return;
void (async () => {
// An open in flight built its stack for the old address; it settles
// first, so the swap below replaces a stack that has stopped moving.
@@ -1002,12 +1010,12 @@ export class ClipFrameSource {
await this.opening;
} catch {}
if (this.closed || this.aim !== aim) return;
- const input = openMedia(this.asset.url);
+ const reader = openMediaShared(this.asset.url);
try {
- const track = await videoTrackOf(input);
- if (this.closed || this.aim !== aim) return input.dispose();
+ const track = await videoTrackOf(reader.input);
+ if (this.closed || this.aim !== aim) return reader.release();
if (!track) {
- input.dispose();
+ reader.release();
this.fail();
return;
}
@@ -1018,15 +1026,15 @@ export class ClipFrameSource {
// canvases, so they hold still, and they are what answers until the
// first walk on the new stack lands. The old file is let go once the
// old walk's drain has let go of it.
- const oldInput = this.input;
- this.input = input;
+ const oldReader = this.reader;
+ this.reader = reader;
this.track = track;
this.sink = sink;
this.opening = Promise.resolve();
this.dropBack(true);
this.stopStream();
await this.drainRun;
- oldInput?.dispose();
+ oldReader?.release();
if (this.closed || this.aim !== aim) return;
// Walk bookkeeping belongs to the stack that is gone; the new one
// starts clean, quick retries and all.
@@ -1039,7 +1047,7 @@ export class ClipFrameSource {
// sends its ask to the new stack.
this.onFrame();
} catch {
- input.dispose();
+ reader.release();
// The old stack stays installed and keeps serving its ring; the
// failure books the usual retries, and the retry's open reads the
// current address.
@@ -1078,20 +1086,20 @@ export class ClipFrameSource {
private open(): Promise<void> {
if (this.opening) return this.opening;
this.opening = (async () => {
- const input = openMedia(this.asset.url);
+ const reader = openMediaShared(this.asset.url);
try {
- const track = await videoTrackOf(input);
+ const track = await videoTrackOf(reader.input);
if (!track) {
- input.dispose();
+ reader.release();
this.unreadable = true;
return;
}
if (this.closed) {
- input.dispose();
+ reader.release();
return;
}
- this.input?.dispose();
- this.input = input;
+ this.reader?.release();
+ this.reader = reader;
this.track = track;
// Not awaited: it reads metadata the sink is about to read anyway, and
// the first frame should not wait behind it. Until it answers, the
@@ -1110,7 +1118,7 @@ export class ClipFrameSource {
// the quick retries again.
this.attempts = 0;
} catch {
- input.dispose();
+ reader.release();
this.fail();
}
})();
@@ -1687,8 +1695,8 @@ export class FrameSourcePool {
private budget = 10,
private readonly onFrame: () => void = () => {}
) {
- const stopDecoders = holdMemory("decoders", () => this.decoderBytes);
- const stopCanvases = holdMemory("canvases", () => this.canvasBytes);
+ const stopDecoders = holdMemory("previewDecoders", () => this.decoderBytes);
+ const stopCanvases = holdMemory("previewCanvases", () => this.canvasBytes);
this.release = () => {
stopDecoders();
stopCanvases();
@@ -1828,7 +1836,7 @@ export class FrameSourcePool {
// read first until the budget runs out, and the idle ones past it stand
// down. The budget is the smaller of what the preview was tuned to want
// and this machine's share, so a laptop sheds decoders a desktop keeps.
- const decoderCap = allowance("decoders", decodedFrameBytes(LIVE_PIXELS) * DECODER_FRAMES);
+ const decoderCap = allowance("previewDecoders", decodedFrameBytes(LIVE_PIXELS) * DECODER_FRAMES);
let liveBytes = 0;
for (const [id, src] of [...this.sources.entries()].sort((a, b) => b[1].touched - a[1].touched)) {
if (src.suspended) continue;
@@ -1842,7 +1850,7 @@ export class FrameSourcePool {
// the canvas budget runs out, and what does not fit closes for real. Only
// stood-down sources are on the shelf, so nothing holding a decoder — and
// nothing the picture is being drawn from — is ever closed here.
- const warmCap = allowance("canvases", canvasBytes(WARM_PIXELS));
+ const warmCap = allowance("previewCanvases", canvasBytes(WARM_PIXELS));
let held = 0;
let warm = 0;
for (const [id, src] of [...this.sources.entries()].sort((a, b) => b[1].touched - a[1].touched)) {
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 2fb3acf2..a18646af 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -20,9 +20,11 @@ import {
framesAt,
frameSink,
openMedia,
+ openMediaShared,
probeMediaFile,
UnreadableMediaError,
videoTrackOf,
+ type MediaHandle,
} from "./mediaRead";
import {
clearPendingUpload,
@@ -2181,7 +2183,7 @@ function sweepDerived(): void {
const now = Date.now();
if (now - derivedSweptAt < DERIVED_SWEEP_MS) return;
derivedSweptAt = now;
- const cap = allowance("pictures", DERIVED_MAX);
+ const cap = allowance("libraryPictures", DERIVED_MAX);
if (derivedBytes() > cap && unusedDerivedBytes() > 0) releaseUnusedDerived();
}
const EDGE_POOL_CAP = 4;
@@ -2198,7 +2200,7 @@ type EdgeRequest = {
* height — trim edges and tile previews read different sizes from the same
* warm reader. */
type EdgeReader = {
- input: ReturnType<typeof openMedia>;
+ reader: MediaHandle;
sinkFor: (height: number) => ReturnType<typeof frameSink>;
sinks: Map<number, ReturnType<typeof frameSink>>;
};
@@ -2210,8 +2212,8 @@ const edgeQueue = new Map<string, EdgeRequest>();
const edgeBackQueue = new Map<string, EdgeRequest>();
const edgePool = new Map<string, Promise<EdgeReader>>();
-holdMemory("pictures", stripBytes);
-holdMemory("pictures", derivedBytes);
+holdMemory("edgeFrames", stripBytes);
+holdMemory("libraryPictures", derivedBytes);
let edgePumping = false;
function edgeKey(url: string, time: number, height: number) {
@@ -2265,10 +2267,10 @@ function edgeReader(url: string): Promise<EdgeReader> {
return hit;
}
const opening = (async () => {
- const input = openMedia(url);
- const track = await videoTrackOf(input);
+ const handle = openMediaShared(url);
+ const track = await videoTrackOf(handle.input);
if (!track) {
- input.dispose();
+ handle.release();
throw new UnreadableMediaError("This file has no readable video.");
}
// A pool of canvases each sink cycles through, so a drag that reads
@@ -2290,7 +2292,7 @@ function edgeReader(url: string): Promise<EdgeReader> {
while (sinks.size > EDGE_SINK_HEIGHTS) sinks.delete(sinks.keys().next().value!);
return sink;
};
- const reader = { input, sinkFor, sinks };
+ const reader = { reader: handle, sinkFor, sinks };
openEdgeReaders.add(reader);
return reader;
})();
@@ -2301,7 +2303,7 @@ function edgeReader(url: string): Promise<EdgeReader> {
old
.then((r) => {
openEdgeReaders.delete(r);
- r.input.dispose();
+ r.reader.release();
})
.catch(() => {});
}
@@ -2330,7 +2332,10 @@ async function pumpEdgeFrames() {
// says nothing about the size of what is counted: three hundred
// frames of a phone video are a different number of megabytes from
// three hundred of a screen recording.
- const cap = allowance("pictures", canvasBytes(EDGE_CACHE_CAP * THUMB_H * THUMB_H * 2));
+ const cap = allowance(
+ "edgeFrames",
+ canvasBytes(EDGE_CACHE_CAP * THUMB_H * THUMB_H * 2)
+ );
let bytes = stripBytes();
while (edgeCache.size > EDGE_CACHE_CAP || (edgeCache.size > 1 && bytes > cap)) {
const oldest = edgeCache.keys().next().value!;
diff --git a/site/src/cut/lib/mediaRead.ts b/site/src/cut/lib/mediaRead.ts
index 98d14ab7..27ea2c53 100644
--- a/site/src/cut/lib/mediaRead.ts
+++ b/site/src/cut/lib/mediaRead.ts
@@ -87,16 +87,26 @@ export class UnreadableMediaError extends Error {
* looking at. So the local engine and any other plain-HTTP origin keep the
* library's pair, and so does a link that says it is slow or metered. The
* width is for multiplexed cloud media over a real network. */
-function urlParallelism(url: string): number {
+function urlParallelism(url: string, cache: number): number {
+ // Room decides first. A ranged reader grows each worker's region ahead of
+ // itself up to PREFETCH_REGION, so a source running more workers than its
+ // cache has room for spends the width refetching what the other workers
+ // just evicted. The pair is the floor: below that a walk stops overlapping
+ // its own reads at all.
+ const afforded = Math.max(2, Math.floor(cache / PREFETCH_REGION));
if (!/^https:/i.test(url)) return 2;
const conn =
typeof navigator === "undefined"
? undefined
: (navigator as { connection?: { saveData?: boolean; effectiveType?: string } }).connection;
if (conn?.saveData || /(^|-)2g$|^3g$/.test(conn?.effectiveType ?? "")) return 2;
- return 8;
+ return Math.min(8, afforded);
}
+/** How far ahead of itself one ranged worker reads before it stops growing
+ * its region (mediabunny's network prefetch profile). */
+const PREFETCH_REGION = 8 * 2 ** 20;
+
/** Backoff, in seconds, for a URL read whose request failed outright. The
* list ends, so a URL that is genuinely gone still fails — the preview's
* outage recovery (frameSource.ts) re-opens on its own cadence, and a read
@@ -187,12 +197,17 @@ function trackedFetch(url: string): typeof fetch {
* becomes a gigabyte.
*/
const READERS = 16;
-/** Bytes of the file one reader keeps in memory. Enough that a walk reading
- * forward never re-fetches what it just read, and small enough that the
- * readers together stay inside the tab's ceiling. */
-const READ_CACHE = 32 * 2 ** 20;
+/**
+ * Bytes of the file one reader keeps for itself: the reads its own walk just
+ * made, so a demuxer stepping back over a header it read a moment ago has it
+ * in hand. The bytes every reader on a file shares are held once, in the
+ * chunk cache's memory (chunkCache.ts), so this is only what a walk needs
+ * ahead of and behind its own position. Sixteen of these and the chunk memory
+ * together fill the reads share.
+ */
+const READ_CACHE = 8 * 2 ** 20;
-/** Chunked readers open right now, for the memory report. */
+/** Readers open right now, for the memory report. */
let openReaders = 0;
/** Decided on the first open and held: the ceiling does not move, so asking
@@ -200,51 +215,95 @@ let openReaders = 0;
* what the readers hold must not itself count as a request for room. */
let readCache = 0;
const readCacheSize = (): number =>
- (readCache ||= Math.round(allowance("reads", READ_CACHE * READERS) / READERS));
+ (readCache ||= Math.round(
+ allowance("readerCaches", READ_CACHE * READERS) / READERS
+ ));
-holdMemory("reads", () => openReaders * readCacheSize());
+holdMemory("readerCaches", () => openReaders * readCacheSize());
export function openMedia(src: string | Blob): Input {
const blob = typeof src === "string" ? resolveRegisteredBlob(src) ?? src : src;
let source;
- let chunkedRead = false;
+ // Every source keeps a cache of what it read, and every one of them is
+ // given the same size: a reader on this Mac's engine or on a store-minted
+ // blob holds file bytes in this tab the same as one on the cloud does. A
+ // cache this small is safe on a URL source because every server the page
+ // reads a file from answers a range with 206 — the engine's own file route
+ // and the media origin both do — so a chunk dropped is a chunk refetched;
+ // it is a server that ignores ranges that puts the source into the
+ // sequential mode where a read behind the cache throws.
+ const maxCacheSize = readCacheSize();
if (typeof blob === "string") {
const chunked = chunkSourceOptions(blob);
source = chunked
? new CustomSource({
...chunked,
prefetchProfile: "network",
- maxCacheSize: readCacheSize(),
+ maxCacheSize,
})
: new UrlSource(blob, {
- parallelism: urlParallelism(blob),
+ parallelism: urlParallelism(blob, maxCacheSize),
getRetryDelay: urlRetryDelay,
fetchFn: trackedFetch(blob),
+ maxCacheSize,
});
- chunkedRead = !!chunked;
} else {
- source = new BlobSource(blob);
+ source = new BlobSource(blob, { maxCacheSize });
}
const input = new Input({ formats: ALL_FORMATS, source });
// The cache lives inside the source, where nothing can ask it how big it has
// grown. Counting the readers that own one is what makes the total
// reportable, and the count is only right if it is taken where the reader is
// let go — so the dispose every caller already makes is where it is taken.
- if (chunkedRead) {
- openReaders++;
- const dispose = input.dispose.bind(input);
- let closed = false;
- input.dispose = () => {
- if (!closed) {
- closed = true;
- openReaders--;
- }
- return dispose();
- };
- }
+ openReaders++;
+ const dispose = input.dispose.bind(input);
+ let closed = false;
+ input.dispose = () => {
+ if (!closed) {
+ closed = true;
+ openReaders--;
+ }
+ return dispose();
+ };
return input;
}
+/**
+ * One reader per file, shared by everything reading it.
+ *
+ * A cut of forty segments from one recording asks for forty sources, and
+ * each would otherwise parse the same file and keep its own cache of the
+ * same bytes. Holders on a URL share one input — the parse, the reader's
+ * cache, the open file — and the last to let go closes it. The sinks and
+ * decoders stay per holder: a track serves any number of them. A store
+ * blob URL is a URL here too, since it names one file for as long as it is
+ * registered. A holder releases exactly once; a second release is nothing.
+ */
+export type MediaHandle = { input: Input; release: () => void };
+
+const sharedInputs = new Map<string, { input: Input; refs: number }>();
+
+export function openMediaShared(src: string): MediaHandle {
+ let entry = sharedInputs.get(src);
+ if (!entry) {
+ entry = { input: openMedia(src), refs: 0 };
+ sharedInputs.set(src, entry);
+ }
+ const held = entry;
+ held.refs++;
+ let released = false;
+ return {
+ input: held.input,
+ release: () => {
+ if (released) return;
+ released = true;
+ if (--held.refs > 0) return;
+ if (sharedInputs.get(src) === held) sharedInputs.delete(src);
+ held.input.dispose();
+ },
+ };
+}
+
/** Run `fn` against an open input and dispose it however that ends. */
export async function withMedia<T>(src: string | Blob, fn: (input: Input) => Promise<T>): Promise<T> {
const input = openMedia(src);
@@ -577,7 +636,13 @@ export interface AudioWalk {
* container parse and one decoder serve a whole clip.
*/
export function openAudioWalk(src: string | Blob, from = 0, to?: number): AudioWalk {
- const input = openMedia(src);
+ // A voice on a URL reads the file its picture's source already holds open.
+ const handle =
+ typeof src === "string"
+ ? openMediaShared(src)
+ : { input: openMedia(src), release: () => void 0 };
+ const input = handle.input;
+ const close = typeof src === "string" ? handle.release : () => input.dispose();
let closed = false;
let finding: Promise<InputAudioTrack | null> | null = null;
let reader: AsyncGenerator<WrappedAudioBuffer, void, unknown> | null = null;
@@ -624,7 +689,7 @@ export function openAudioWalk(src: string | Blob, from = 0, to?: number): AudioW
// answering is waiting on exactly one of those.
stop(reader);
reader = null;
- input.dispose();
+ close();
},
};
}
diff --git a/site/src/cut/lib/mediaShared.test.ts b/site/src/cut/lib/mediaShared.test.ts
new file mode 100644
index 00000000..0d3fda41
--- /dev/null
+++ b/site/src/cut/lib/mediaShared.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from "bun:test";
+import { openMediaShared } from "./mediaRead";
+
+const URL_A = "https://media.donkeycut.com/cut/u1/projects/p1/media/a.mp4?e=1&s=x";
+const URL_B = "https://media.donkeycut.com/cut/u1/projects/p1/media/b.mp4?e=1&s=x";
+
+describe("openMediaShared", () => {
+ test("holders on one URL share one input; another URL gets its own", () => {
+ const a = openMediaShared(URL_A);
+ const b = openMediaShared(URL_A);
+ const c = openMediaShared(URL_B);
+ expect(a.input).toBe(b.input);
+ expect(c.input).not.toBe(a.input);
+ a.release();
+ b.release();
+ c.release();
+ });
+
+ test("the file stays open until the last holder lets go", () => {
+ const a = openMediaShared(URL_A);
+ const b = openMediaShared(URL_A);
+ a.release();
+ // One holder still has it: a new holder joins the same input.
+ const c = openMediaShared(URL_A);
+ expect(c.input).toBe(b.input);
+ b.release();
+ c.release();
+ });
+
+ test("once every holder is gone, the next open is a fresh file", () => {
+ const a = openMediaShared(URL_A);
+ const input = a.input;
+ a.release();
+ const b = openMediaShared(URL_A);
+ expect(b.input).not.toBe(input);
+ b.release();
+ });
+
+ test("a holder releasing twice is nothing", () => {
+ const a = openMediaShared(URL_A);
+ const b = openMediaShared(URL_A);
+ a.release();
+ a.release();
+ // b still holds the file: a third holder joins it.
+ const c = openMediaShared(URL_A);
+ expect(c.input).toBe(b.input);
+ b.release();
+ c.release();
+ });
+});
diff --git a/site/src/cut/lib/memoryBudget.test.ts b/site/src/cut/lib/memoryBudget.test.ts
index dac69b8a..259e87ce 100644
--- a/site/src/cut/lib/memoryBudget.test.ts
+++ b/site/src/cut/lib/memoryBudget.test.ts
@@ -7,6 +7,7 @@ import {
holdMemory,
mb,
memoryCeiling,
+ memoryHolders,
memoryUsage,
takeMemoryPressure,
} from "./memoryBudget";
@@ -14,36 +15,73 @@ import {
const MB = 2 ** 20;
const drops: (() => void)[] = [];
-const hold = (bucket: Parameters<typeof holdMemory>[0], bytes: number) => {
- drops.push(holdMemory(bucket, () => bytes));
+const hold = (holder: Parameters<typeof holdMemory>[0], bytes: number) => {
+ drops.push(holdMemory(holder, () => bytes));
};
+const holderNames = Object.keys(memoryHolders) as (keyof typeof memoryHolders)[];
+
afterEach(() => {
for (const drop of drops.splice(0)) drop();
takeMemoryPressure();
});
describe("the ceiling", () => {
- test("is a share of the machine, decided once", () => {
+ test("is a share of the machine", () => {
// The environment the tests run in reports no `deviceMemory`, which is the
// same silence Safari and Firefox give a real page: the assumed size
- // stands in, and a quarter of it is the tab's.
- expect(memoryCeiling()).toBe(2 * 2 ** 30);
+ // stands in, and an eighth of it is the tab's.
+ expect(memoryCeiling()).toBe(2 ** 30);
expect(memoryCeiling()).toBe(memoryCeiling());
});
+ test("splits a bucket between the holders that share it", () => {
+ const huge = 99 * 2 ** 30;
+ // The reads share is the chunk memory's and the readers' own caches',
+ // half each, so the two of them together stand on the bucket and not
+ // twice it.
+ const half = Math.round(memoryCeiling() * 0.25 * 0.5);
+ expect(allowance("chunkMemory", huge)).toBe(half);
+ expect(allowance("readerCaches", huge)).toBe(half);
+ expect(allowance("chunkMemory", huge) + allowance("readerCaches", huge)).toBe(
+ Math.round(memoryCeiling() * 0.25)
+ );
+ // A tuning under the portion is still left alone.
+ expect(allowance("readerCaches", 4 * MB)).toBe(4 * MB);
+ });
+
+ test("every holder of a bucket together ask for the whole of it, once", () => {
+ // Nothing outside this table can hand a cache room, so a bucket whose
+ // portions sum past one has promised memory twice, and a bucket that sums
+ // under it is leaving room no one may use.
+ const sums = new Map<string, number>();
+ for (const name of holderNames) {
+ const { bucket, portion } = memoryHolders[name];
+ sums.set(bucket, (sums.get(bucket) ?? 0) + portion);
+ }
+ // Every bucket is stood in by someone, and the fractions come to one.
+ expect([...sums.keys()].sort()).toEqual([
+ "audio",
+ "canvases",
+ "decoders",
+ "pictures",
+ "reads",
+ ]);
+ for (const [, sum] of sums) expect(Math.abs(sum - 1)).toBeLessThan(1e-9);
+ });
+
test("hands a bucket the smaller of its tuning and its share", () => {
// A size the machine can afford is left alone, so a preview tuned on a
// machine with room behaves there exactly as it was tuned to.
const small = 4 * MB;
- expect(allowance("decoders", small)).toBe(small);
+ expect(allowance("previewDecoders", small)).toBe(small);
expect(takeMemoryPressure()).toEqual([]);
// A size it cannot is cut to the share, and the cut is recorded: the
// machine is deciding, not the tuning.
const huge = 99 * 2 ** 30;
- expect(allowance("decoders", huge)).toBeLessThan(huge);
- expect(allowance("decoders", huge)).toBe(Math.round(memoryCeiling() * 0.4));
+ expect(allowance("previewDecoders", huge)).toBeLessThan(huge);
+ expect(allowance("previewDecoders", huge)).toBe(Math.round(memoryCeiling() * 0.4));
expect(takeMemoryPressure()).toEqual(["decoders"]);
// Reading the pressure clears it, so a later window reports its own.
expect(takeMemoryPressure()).toEqual([]);
@@ -51,12 +89,7 @@ describe("the ceiling", () => {
test("splits the whole ceiling between the buckets and no more", () => {
const huge = 99 * 2 ** 30;
- const shares =
- allowance("decoders", huge) +
- allowance("canvases", huge) +
- allowance("reads", huge) +
- allowance("audio", huge) +
- allowance("pictures", huge);
+ const shares = holderNames.reduce((n, name) => n + allowance(name, huge), 0);
expect(shares).toBeLessThanOrEqual(memoryCeiling());
expect(shares).toBeGreaterThan(memoryCeiling() * 0.99);
});
@@ -64,21 +97,25 @@ describe("the ceiling", () => {
describe("what is being held", () => {
test("adds up what every cache reports, by bucket", () => {
- hold("decoders", 10 * MB);
- hold("decoders", 5 * MB);
- hold("reads", 3 * MB);
+ // Against what the modules loaded beside this one are already reporting:
+ // every cache in the editor registers itself the moment it is imported.
+ const before = memoryUsage();
+ hold("previewDecoders", 10 * MB);
+ hold("previewDecoders", 5 * MB);
+ hold("chunkMemory", 3 * MB);
const usage = memoryUsage();
- expect(mb(usage.decoders)).toBe(15);
- expect(mb(usage.reads)).toBe(3);
- expect(mb(usage.canvases)).toBe(0);
- expect(mb(usage.total)).toBe(18);
+ expect(mb(usage.decoders - before.decoders)).toBe(15);
+ expect(mb(usage.reads - before.reads)).toBe(3);
+ expect(mb(usage.canvases - before.canvases)).toBe(0);
+ expect(mb(usage.total - before.total)).toBe(18);
});
test("forgets a cache that has been let go", () => {
- hold("audio", 8 * MB);
- expect(mb(memoryUsage().audio)).toBe(8);
+ const before = memoryUsage().audio;
+ hold("mixerAudio", 8 * MB);
+ expect(mb(memoryUsage().audio - before)).toBe(8);
drops.pop()!();
- expect(memoryUsage().audio).toBe(0);
+ expect(memoryUsage().audio).toBe(before);
});
test("reports nothing rather than guessing when the browser is silent", () => {
diff --git a/site/src/cut/lib/memoryBudget.ts b/site/src/cut/lib/memoryBudget.ts
index 5fa4696e..de61dcab 100644
--- a/site/src/cut/lib/memoryBudget.ts
+++ b/site/src/cut/lib/memoryBudget.ts
@@ -64,21 +64,23 @@ const SHARES: Record<MemoryBucket, number> = {
/**
* The tab's share of the machine.
*
- * A quarter of what the browser reports leaves the operating system, the
- * browser's own processes and the person's other tabs the rest. Past that the
+ * The ceiling covers the tab and the decoder process working for it, which
+ * between them are one of several things the machine is running: the
+ * operating system, the browser's other processes, the person's other tabs.
+ * An eighth of what the browser reports leaves those the rest. Past that the
* machine starts swapping, and a swapping machine previews worse than one
* decoding at half the size — the picture stops for a page fault, which no
- * amount of decode headroom recovers.
+ * amount of decode headroom recovers. An 18GB laptop reports sixteen and
+ * gets two gigabytes, which is where the tuned sizes below start to bind.
*/
-const CEILING_SHARE = 0.25;
+const CEILING_SHARE = 0.125;
/**
* What to assume when the browser does not say.
*
* `deviceMemory` is Chrome and Edge only; Safari and Firefox report nothing.
- * Eight is also the largest number Chrome will report, so it already means
- * "eight or more" — assuming it for the browsers that stay silent puts them
- * on the same footing as the machines we can see, which are overwhelmingly
- * the same machines.
+ * Chrome rounds to a power of two and reports sixteen on the machines that
+ * have it, so eight is the figure for a machine of ordinary size — assuming
+ * it for the browsers that stay silent puts them on that footing.
*/
const ASSUMED_GB = 8;
/** The smallest ceiling worth honouring: below this the editor cannot hold a
@@ -88,30 +90,76 @@ const CEILING_MIN = 384 * 2 ** 20;
const GB = 2 ** 30;
-let ceiling = 0;
-
/**
- * Bytes the editor may hold, decided once.
+ * Bytes the editor may hold.
*
- * `deviceMemory` is coarse by design — it rounds to a power of two and caps at
- * eight — which is enough to tell the machines that need protecting from the
- * machines that do not, and it is the only figure a page is given.
+ * `deviceMemory` is coarse by design — it rounds to a power of two — which is
+ * enough to tell the machines that need protecting from the machines that do
+ * not, and it is the only figure a page is given. It is read each time it is
+ * asked for: the figure never moves, and the read is a property lookup.
*/
export function memoryCeiling(): number {
- if (ceiling) return ceiling;
const reported =
typeof navigator === "undefined"
? 0
: ((navigator as unknown as { deviceMemory?: number }).deviceMemory ?? 0);
const gb = reported > 0 ? reported : ASSUMED_GB;
- ceiling = Math.max(CEILING_MIN, Math.round(gb * GB * CEILING_SHARE));
- return ceiling;
+ return Math.max(CEILING_MIN, Math.round(gb * GB * CEILING_SHARE));
}
-/** Bytes a holder in `bucket` may stand on: the smaller of the size it was
- * tuned to want and its share of the ceiling. */
-export function allowance(bucket: MemoryBucket, tuned: number): number {
- const share = Math.round(memoryCeiling() * SHARES[bucket]);
+/**
+ * Everything that stands in a bucket, and how much of the bucket each may
+ * stand on.
+ *
+ * The split lives here, in one table. A fraction typed into one file cannot
+ * see the fractions typed into the others, and the sum is the whole point: two
+ * caches that each ask for their bucket's share stand on twice it. Every holder is named here, the ones that only report what they
+ * hold included — room reserved for a cache that never asks is room the asking
+ * caches must not be handed. The fractions in a bucket sum to one, and a test
+ * says so.
+ */
+const HOLDERS = {
+ /** Frames the live decoders behind the preview are holding. */
+ previewDecoders: { bucket: "decoders", portion: 1 },
+ /** The preview pool: the ring each live source lands frames on, and the
+ * shelf of canvases kept for the sources that have stood down. */
+ previewCanvases: { bucket: "canvases", portion: 0.75 },
+ /** Readers a render keeps open between frames, each with its own pool of
+ * canvases at the source's size. */
+ exportReaders: { bucket: "canvases", portion: 0.25 },
+ /** File bytes held once for every reader on a cloud file. */
+ chunkMemory: { bucket: "reads", portion: 0.5 },
+ /** What each open reader keeps of its own walk through a file. */
+ readerCaches: { bucket: "reads", portion: 0.5 },
+ /** Decoded sound waiting for the mixer to schedule it. */
+ mixerAudio: { bucket: "audio", portion: 1 },
+ /** Filmstrips and waveforms drawn for shelf entries. */
+ libraryPictures: { bucket: "pictures", portion: 0.45 },
+ /** Captured frames behind trim edges and filmstrip tiles. */
+ edgeFrames: { bucket: "pictures", portion: 0.3 },
+ /** Decoded sticker images, shared across the page's renders. */
+ stickers: { bucket: "pictures", portion: 0.15 },
+ /** Element pictures the behind-the-person pass draws from. */
+ overlayRasters: { bucket: "pictures", portion: 0.1 },
+} as const satisfies Record<string, { bucket: MemoryBucket; portion: number }>;
+
+/** A named cache in the budget. */
+export type MemoryHolder = keyof typeof HOLDERS;
+
+/** The table itself, for the report that names what each cache holds and for
+ * the test that adds each bucket's portions up. */
+export const memoryHolders = HOLDERS as Record<
+ MemoryHolder,
+ { bucket: MemoryBucket; portion: number }
+>;
+
+/**
+ * Bytes a holder may stand on: the smaller of the size it was tuned to want
+ * and its portion of its bucket's share of the ceiling.
+ */
+export function allowance(holder: MemoryHolder, tuned: number): number {
+ const { bucket, portion } = HOLDERS[holder];
+ const share = Math.round(memoryCeiling() * SHARES[bucket] * portion);
if (share < tuned) bound[bucket] = true;
return Math.min(tuned, share);
}
@@ -146,7 +194,8 @@ const holders = new Map<MemoryBucket, Set<Reporter>>();
* allocation eventually forgets one, and the number it forgot is the number a
* report needs. Returns the way to stop reporting.
*/
-export function holdMemory(bucket: MemoryBucket, bytes: Reporter): () => void {
+export function holdMemory(holder: MemoryHolder, bytes: Reporter): () => void {
+ const { bucket } = HOLDERS[holder];
let set = holders.get(bucket);
if (!set) holders.set(bucket, (set = new Set()));
set.add(bytes);
diff --git a/site/src/cut/lib/previewMixer.ts b/site/src/cut/lib/previewMixer.ts
index b7014a39..306f2fc7 100644
--- a/site/src/cut/lib/previewMixer.ts
+++ b/site/src/cut/lib/previewMixer.ts
@@ -235,7 +235,7 @@ export class PreviewMixer {
* scheduled is placed against this. */
private anchor: { timeline: number; ctx: number; wall: number } | null = null;
private decoded = new Map<string, AudioBuffer>();
- private readonly releaseMemory = holdMemory("audio", () => decodedBytes(this.decoded));
+ private readonly releaseMemory = holdMemory("mixerAudio", () => decodedBytes(this.decoded));
/** Whether the clock is running. */
get running(): boolean {
@@ -984,7 +984,7 @@ export class PreviewMixer {
// with the ones it has finished, and the next frame would pay a full decode
// for sound it was already holding.
this.decoded.set(key, buffer);
- const cap = allowance("audio", STRETCH_CACHE_BYTES);
+ const cap = allowance("mixerAudio", STRETCH_CACHE_BYTES);
let cached = decodedBytes(this.decoded);
for (const [oldest, buf] of this.decoded) {
if (cached <= cap || this.decoded.size <= 1) break;
diff --git a/site/src/cut/lib/stickerCache.test.ts b/site/src/cut/lib/stickerCache.test.ts
new file mode 100644
index 00000000..0e97a9ce
--- /dev/null
+++ b/site/src/cut/lib/stickerCache.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from "bun:test";
+import { setRasterFactory } from "./raster";
+import { cutRenderEnv } from "./textRender";
+import type { MediaAsset } from "./types";
+
+// A sticker this big costs four megabytes decoded, so two of them fill the
+// share the stickers hold at the test ceiling and a third pushes one out.
+const SIDE = 1000;
+
+let decodes = 0;
+setRasterFactory({
+ createCanvas: () => {
+ throw new Error("The sticker cache draws nothing.");
+ },
+ decodeImage: async () => {
+ decodes++;
+ return { source: {} as CanvasImageSource, width: SIDE, height: SIDE };
+ },
+ canvasToBlob: async () => new Blob(),
+});
+
+globalThis.fetch = (async () => new Response(new Blob())) as typeof fetch;
+
+const assets = ["a1", "a2", "a3"].map(
+ (id) => ({ id, url: `https://media.donkeycut.com/cut/u1/library/${id}.png` }) as MediaAsset
+);
+const resolve = (id: string) => cutRenderEnv(assets).resolveAsset!(id);
+
+describe("the sticker cache", () => {
+ test("holds what it has room for and drops what nothing has asked for", async () => {
+ await resolve("a1");
+ await resolve("a2");
+ expect(decodes).toBe(2);
+
+ // A sticker already decoded is handed back without decoding it again,
+ // which is what a render asking every frame depends on.
+ await resolve("a2");
+ expect(decodes).toBe(2);
+
+ // The third is past the share: the one nothing has asked for since goes.
+ await resolve("a3");
+ expect(decodes).toBe(3);
+ await resolve("a3");
+ await resolve("a2");
+ expect(decodes).toBe(3);
+
+ // The dropped one decodes again the moment something reaches for it.
+ await resolve("a1");
+ expect(decodes).toBe(4);
+ });
+});
diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.ts
index b80e0c82..b90ef7b9 100644
--- a/site/src/cut/lib/textRender.ts
+++ b/site/src/cut/lib/textRender.ts
@@ -13,7 +13,7 @@ import {
type WordDraw,
} from "@donkeycut/effects-kit";
import type { CSSProperties } from "react";
-import { holdMemory } from "./memoryBudget";
+import { allowance, holdMemory } from "./memoryBudget";
import { createRasterCanvas, decodeRasterImage, rasterCanvasToPng } from "./raster";
import { fontStack, type MediaAsset, type Overlay } from "./types";
@@ -76,19 +76,50 @@ export function wordDrawCss(d: WordDraw, lineHeight = LINE_HEIGHT): CSSPropertie
return css;
}
-/** Decoded sticker images by asset id, shared across one page's renders. An
- * <img> decode handles SVG too (createImageBitmap on an SVG blob does not). */
+/** Decoded sticker images by asset id, shared across one page's renders, in
+ * the order they were last asked for. An <img> decode handles SVG too
+ * (createImageBitmap on an SVG blob does not). */
const stickerCache = new Map<string, Promise<StickerImage | null>>();
/** What each decoded sticker costs, filled in as they land. The cache above
* holds promises, which cannot be asked their size; this is what makes the
* pictures the page is holding countable. */
const stickerBytes = new Map<string, number>();
-holdMemory("pictures", () => {
+/** What the decoded stickers may stand on: a cut whose clips carry different
+ * stickers holds every one it has drawn, and a sticker is a full-size picture
+ * however small it is placed. */
+const STICKER_TUNED = 24 * 2 ** 20;
+
+const stickersHeld = (): number => {
let n = 0;
for (const bytes of stickerBytes.values()) n += bytes;
return n;
-});
+};
+
+holdMemory("stickers", stickersHeld);
+
+/**
+ * Drop the stickers a render has gone longest without asking for, once the
+ * decoded ones are past their share.
+ *
+ * The one just asked for is never dropped, and neither is a decode still in
+ * the air — a sticker on screen is asked for again on the next frame, and
+ * dropping it would decode it once a frame. What is dropped is a picture no
+ * frame has reached for since, and it decodes again the moment one does.
+ */
+function sweepStickers(asked: string): void {
+ const cap = allowance("stickers", STICKER_TUNED);
+ let held = stickersHeld();
+ if (held <= cap) return;
+ for (const id of [...stickerCache.keys()]) {
+ if (held <= cap) break;
+ const bytes = stickerBytes.get(id);
+ if (id === asked || bytes === undefined) continue;
+ stickerCache.delete(id);
+ stickerBytes.delete(id);
+ held -= bytes;
+ }
+}
function decodeSticker(url: string): Promise<StickerImage | null> {
return fetch(url)
@@ -112,15 +143,21 @@ export function cutRenderEnv(assets: MediaAsset[]): RenderEnv {
const asset = assets.find((a) => a.id === assetId);
if (!asset) return Promise.resolve(null);
let hit = stickerCache.get(asset.id);
- if (!hit) {
+ if (hit) {
+ // Asked for again: move it to the young end of the cache.
+ stickerCache.delete(asset.id);
+ } else {
hit = decodeSticker(asset.url).then((img) => {
// A failed decode is not worth pinning; the next render retries.
if (!img) stickerCache.delete(asset.id);
- else stickerBytes.set(asset.id, img.width * img.height * 4);
+ else {
+ stickerBytes.set(asset.id, img.width * img.height * 4);
+ sweepStickers(asset.id);
+ }
return img;
});
- stickerCache.set(asset.id, hit);
}
+ stickerCache.set(asset.id, hit);
return hit;
},
};