Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix: key OPFS cache refcount by cache entry, not source URL

my_mac53589d0d9d84
diff --git a/src/lib/captioning/extractMono16k.ts b/src/lib/captioning/extractMono16k.ts
index 8763c0aed..999113e9d 100644
--- a/src/lib/captioning/extractMono16k.ts
+++ b/src/lib/captioning/extractMono16k.ts
@@ -161,6 +161,7 @@ export async function extractMono16kFromVideoUrl(
return truncateAndResampleTo16k(pcm.mono, pcm.sampleRate, pcm.durationSec, options?.signal);
} finally {
// Release the OPFS cache reference taken when streaming a large source.
- releaseLocalSourceFile(videoUrl);
+ // The File name is the cache-entry key (no-op for small/remote sources).
+ releaseLocalSourceFile(file.name);
}
}
diff --git a/src/lib/exporter/localSourceFile.test.ts b/src/lib/exporter/localSourceFile.test.ts
index 2d83f1ed9..16b7c0007 100644
--- a/src/lib/exporter/localSourceFile.test.ts
+++ b/src/lib/exporter/localSourceFile.test.ts
@@ -184,7 +184,7 @@ describe("materializeLocalSourceFile (large file OPFS path)", () => {
expect(api.readFileChunk).toHaveBeenCalledTimes(3);
expect(api.readBinaryFile).not.toHaveBeenCalled();
- releaseLocalSourceFile("/rec/a.mp4");
+ releaseLocalSourceFile(file.name);
});
it("reuses the cached copy on a second call without re-streaming", async () => {
@@ -193,14 +193,15 @@ describe("materializeLocalSourceFile (large file OPFS path)", () => {
stubElectronAPI(api);
stubOpfs(new FakeDir());
- await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
+ const first = await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
const firstReads = api.readFileChunk.mock.calls.length;
- await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
+ const second = await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
expect(api.readFileChunk.mock.calls.length).toBe(firstReads); // no new reads
+ expect(second.name).toBe(first.name);
- releaseLocalSourceFile("/rec/b.mp4");
- releaseLocalSourceFile("/rec/b.mp4");
+ releaseLocalSourceFile(first.name);
+ releaseLocalSourceFile(second.name);
});
it("keeps a cache entry that is still referenced by another active source", async () => {
@@ -208,16 +209,16 @@ describe("materializeLocalSourceFile (large file OPFS path)", () => {
stubOpfs(root);
stubElectronAPI(largeSourceApi("/rec/a.mp4", new Uint8Array([1, 2, 3, 4, 5])));
- await materializeLocalSourceFile("/rec/a.mp4", "a.mp4", OPTS); // A retained
+ const a = await materializeLocalSourceFile("/rec/a.mp4", "a.mp4", OPTS); // A retained
stubElectronAPI(largeSourceApi("/rec/b.mp4", new Uint8Array([6, 7, 8, 9, 10])));
- await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS); // prunes, but A is active
+ const b = await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS); // prunes, A active
// A must NOT have been pruned while still in use.
expect(cacheDir(root)?.files.size).toBe(2);
- releaseLocalSourceFile("/rec/a.mp4");
- releaseLocalSourceFile("/rec/b.mp4");
+ releaseLocalSourceFile(a.name);
+ releaseLocalSourceFile(b.name);
});
it("prunes a cache entry once it has been released", async () => {
@@ -225,20 +226,46 @@ describe("materializeLocalSourceFile (large file OPFS path)", () => {
stubOpfs(root);
stubElectronAPI(largeSourceApi("/rec/a.mp4", new Uint8Array([1, 2, 3, 4, 5])));
- await materializeLocalSourceFile("/rec/a.mp4", "a.mp4", OPTS); // A retained
+ const a = await materializeLocalSourceFile("/rec/a.mp4", "a.mp4", OPTS); // A retained
stubElectronAPI(largeSourceApi("/rec/b.mp4", new Uint8Array([6, 7, 8, 9, 10])));
- await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS); // B retained
+ const b = await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS); // B retained
- releaseLocalSourceFile("/rec/a.mp4"); // A no longer in use
+ releaseLocalSourceFile(a.name); // A no longer in use
stubElectronAPI(largeSourceApi("/rec/c.mp4", new Uint8Array([11, 12, 13, 14, 15])));
- await materializeLocalSourceFile("/rec/c.mp4", "c.mp4", OPTS); // prunes A, keeps B, adds C
+ const c = await materializeLocalSourceFile("/rec/c.mp4", "c.mp4", OPTS); // prunes A, keeps B+C
// A pruned; B (still active) and C remain.
expect(cacheDir(root)?.files.size).toBe(2);
- releaseLocalSourceFile("/rec/b.mp4");
- releaseLocalSourceFile("/rec/c.mp4");
+ releaseLocalSourceFile(b.name);
+ releaseLocalSourceFile(c.name);
+ });
+
+ it("removes the partial cache entry when a chunk read fails mid-copy", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+
+ const source = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
+ const api = largeSourceApi("/rec/err.mp4", source);
+ let reads = 0;
+ api.readFileChunk = vi.fn(async (_url: string, offset: number, length: number) => {
+ reads += 1;
+ if (reads === 2) return { success: false, message: "disk read failed" };
+ return {
+ success: true,
+ data: source.slice(offset, offset + length).buffer,
+ bytesRead: Math.min(length, source.byteLength - offset),
+ };
+ });
+ stubElectronAPI(api);
+
+ await expect(materializeLocalSourceFile("/rec/err.mp4", "err.mp4", OPTS)).rejects.toThrow(
+ /disk read failed/,
+ );
+
+ // The partial copy is cleaned up and holds no live reference.
+ expect(cacheDir(root)?.files.size ?? 0).toBe(0);
});
});
diff --git a/src/lib/exporter/localSourceFile.ts b/src/lib/exporter/localSourceFile.ts
index 0c478872b..f247d45d5 100644
--- a/src/lib/exporter/localSourceFile.ts
+++ b/src/lib/exporter/localSourceFile.ts
@@ -41,38 +41,33 @@ export interface MaterializeOptions {
}
/**
- * Cache entries currently referenced by a live demuxer, keyed by source URL.
- * Pruning never removes a name that is still in use, so a concurrent export or
- * caption pass reading a different recording cannot have its copy deleted.
- * Callers must {@link releaseLocalSourceFile} when the demuxer is destroyed.
+ * Reference counts of OPFS cache entries currently read by a live demuxer, keyed
+ * by cache-entry name (which equals the returned File's `.name`). Pruning never
+ * removes a name with a live reference, so a concurrent export or caption pass
+ * reading a different recording — or a different revision of the same one —
+ * cannot have its copy deleted. Keying by cache name (not source URL) keeps
+ * revisions independent: releasing one never touches another's count.
*/
-const activeSources = new Map<string, { cacheName: string; refs: number }>();
-
-function retainSource(videoUrl: string, cacheName: string): void {
- const entry = activeSources.get(videoUrl);
- if (entry && entry.cacheName === cacheName) {
- entry.refs += 1;
- } else {
- // A new file revision (size/mtime change) supersedes any prior entry.
- activeSources.set(videoUrl, { cacheName, refs: 1 });
- }
+const activeCacheRefs = new Map<string, number>();
+
+function retainCache(cacheName: string): void {
+ activeCacheRefs.set(cacheName, (activeCacheRefs.get(cacheName) ?? 0) + 1);
}
/**
- * Releases a reference taken by {@link materializeLocalSourceFile} for a large
- * (OPFS-streamed) source. No-op for small sources and for URLs never streamed.
+ * Releases a reference taken by {@link materializeLocalSourceFile}. Pass the
+ * returned File's `.name`. No-op for small/remote sources, whose names were
+ * never retained.
*/
-export function releaseLocalSourceFile(videoUrl: string): void {
- const entry = activeSources.get(videoUrl);
- if (!entry) return;
- entry.refs -= 1;
- if (entry.refs <= 0) activeSources.delete(videoUrl);
+export function releaseLocalSourceFile(cacheName: string): void {
+ const refs = activeCacheRefs.get(cacheName);
+ if (refs === undefined) return;
+ if (refs <= 1) activeCacheRefs.delete(cacheName);
+ else activeCacheRefs.set(cacheName, refs - 1);
}
function activeCacheNames(): Set<string> {
- const names = new Set<string>();
- for (const entry of activeSources.values()) names.add(entry.cacheName);
- return names;
+ return new Set(activeCacheRefs.keys());
}
/** Stable non-cryptographic hash for building a cache key from a path. */
@@ -157,7 +152,7 @@ async function copyToOpfsFile(
const existing = await handle.getFile();
if (existing.size === size) {
options?.onProgress?.({ copiedBytes: size, totalBytes: size });
- retainSource(videoUrl, cacheName);
+ retainCache(cacheName);
return existing;
}
@@ -201,7 +196,7 @@ async function copyToOpfsFile(
`Streamed copy is incomplete (${file.size} of ${size} bytes); the source video may still be in use.`,
);
}
- retainSource(videoUrl, cacheName);
+ retainCache(cacheName);
return file;
}
diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.ts
index 706ef056a..1c26c51a2 100644
--- a/src/lib/exporter/streamingDecoder.ts
+++ b/src/lib/exporter/streamingDecoder.ts
@@ -185,9 +185,10 @@ export class StreamingVideoDecoder {
private decoder: VideoDecoder | null = null;
private cancelled = false;
private metadata: DecodedVideoInfo | null = null;
- // Local source URL streamed into OPFS, released on destroy() so its cache
- // copy can be pruned once no demuxer is reading it.
- private localSourceUrl: string | null = null;
+ // Name of the OPFS cache entry backing a large local source (equals the
+ // File's .name), released on destroy() so the copy can be pruned once no
+ // demuxer is reading it. Null for small/remote sources (never retained).
+ private sourceCacheName: string | null = null;
/** Routes to the appropriate loader based on whether the source is local or remote. */
private async loadSourceFile(
@@ -196,7 +197,6 @@ export class StreamingVideoDecoder {
): Promise<File> {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI) {
- this.localSourceUrl = videoUrl;
return this.withTimeout(
StreamingVideoDecoder.loadLocalSourceFile(videoUrl, onProgress),
LOCAL_SOURCE_LOAD_TIMEOUT_MS,
@@ -239,6 +239,9 @@ export class StreamingVideoDecoder {
onSourceProgress?: (progress: MaterializeProgress) => void,
): Promise<DecodedVideoInfo> {
const file = await this.loadSourceFile(videoUrl, onSourceProgress);
+ // For OPFS-streamed sources the File name is the cache-entry key; retained
+ // by materialize and released in destroy(). No-op key for small/remote.
+ this.sourceCacheName = file.name;
// Relative URL so it resolves in both dev (http) and packaged (file://) builds
const wasmUrl = new URL("./wasm/web-demuxer.wasm", window.location.href).href;
@@ -779,9 +782,9 @@ export class StreamingVideoDecoder {
this.demuxer = null;
}
- if (this.localSourceUrl) {
- releaseLocalSourceFile(this.localSourceUrl);
- this.localSourceUrl = null;
+ if (this.sourceCacheName) {
+ releaseLocalSourceFile(this.sourceCacheName);
+ this.sourceCacheName = null;
}
}