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: abortable, deduplicated OPFS copies; harden waveform and caption paths

my_mac654375b27d97
diff --git a/src/hooks/streamingAudioPeaks.ts b/src/hooks/streamingAudioPeaks.ts
index a0560089b..8e906ad21 100644
--- a/src/hooks/streamingAudioPeaks.ts
+++ b/src/hooks/streamingAudioPeaks.ts
@@ -23,6 +23,36 @@ const READ_END_PADDING_SEC = 0.5;
// Keep in sync with audioPeaksWorker.ts so both paths render identically.
const MAX_PEAK_BLOCKS = 24_000;
const PEAK_BLOCKS_PER_SEC = 200;
+// Upper bound for the duration fallback scan when container metadata is
+// unreliable (MediaRecorder WebM often reports 0/Infinity — see
+// streamingDecoder's validateDuration). Same ceiling as the export scan.
+const SCAN_UNBOUNDED_FALLBACK_SEC = 24 * 60 * 60;
+
+/**
+ * Ground-truth duration from audio packet timestamps, for containers whose
+ * metadata duration is missing or bogus. Demux-only (no decode), so it is a
+ * fast forward pass even for multi-GB files.
+ */
+async function scanAudioDurationSec(demuxer: WebDemuxer, signal?: AbortSignal): Promise<number> {
+ const reader = demuxer.read("audio", 0, SCAN_UNBOUNDED_FALLBACK_SEC).getReader();
+ let maxEndUs = 0;
+ try {
+ while (!signal?.aborted) {
+ const { done, value: chunk } = await reader.read();
+ if (done || !chunk) break;
+ const endUs = chunk.timestamp + (chunk.duration ?? 0);
+ if (endUs > maxEndUs) maxEndUs = endUs;
+ }
+ } finally {
+ try {
+ await reader.cancel();
+ } catch {
+ /* already closed */
+ }
+ }
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
+ return maxEndUs / 1e6;
+}
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
@@ -63,11 +93,6 @@ export async function computePeaksFromFileStreaming(
LOAD_TIMEOUT_MS,
"Timed out while reading media info for the waveform.",
);
- const durationSec =
- Number.isFinite(mediaInfo.duration) && mediaInfo.duration > 0 ? mediaInfo.duration : 0;
- if (durationSec <= 0) {
- throw new Error("Unknown duration; cannot bucket waveform peaks.");
- }
let audioConfig: AudioDecoderConfig;
try {
@@ -81,6 +106,18 @@ export async function computePeaksFromFileStreaming(
}
const sampleRate = audioConfig.sampleRate || 48_000;
+ // MediaRecorder WebM often reports a missing/bogus container duration
+ // (see streamingDecoder's validateDuration); fall back to a demux-only
+ // packet-timestamp scan so those recordings still get a waveform.
+ let durationSec =
+ Number.isFinite(mediaInfo.duration) && mediaInfo.duration > 0 ? mediaInfo.duration : 0;
+ if (durationSec <= 0) {
+ durationSec = await scanAudioDurationSec(demuxer, signal);
+ }
+ if (durationSec <= 0) {
+ throw new Error("Unknown duration; cannot bucket waveform peaks.");
+ }
+
const blocks = Math.min(MAX_PEAK_BLOCKS, Math.ceil(durationSec * PEAK_BLOCKS_PER_SEC));
const totalSamples = Math.max(1, Math.ceil(durationSec * sampleRate));
const peaks = new Float32Array(blocks * 2); // [min0, max0, min1, max1, ...]
@@ -113,28 +150,41 @@ export async function computePeaksFromFileStreaming(
});
decoder.configure(audioConfig);
- const reader = demuxer.read("audio", 0, durationSec + READ_END_PADDING_SEC).getReader();
try {
- while (!signal?.aborted && !decodeError) {
- const { done, value: chunk } = await reader.read();
- if (done || !chunk) break;
- decoder.decode(chunk);
- while (decoder.decodeQueueSize > DECODE_QUEUE_BACKPRESSURE && !signal?.aborted) {
- await new Promise((r) => setTimeout(r, 1));
+ const reader = demuxer.read("audio", 0, durationSec + READ_END_PADDING_SEC).getReader();
+ try {
+ while (!signal?.aborted && !decodeError) {
+ const { done, value: chunk } = await reader.read();
+ if (done || !chunk) break;
+ decoder.decode(chunk);
+ while (decoder.decodeQueueSize > DECODE_QUEUE_BACKPRESSURE && !signal?.aborted) {
+ await new Promise((r) => setTimeout(r, 1));
+ }
}
+ } finally {
+ try {
+ await reader.cancel();
+ } catch {
+ /* already closed */
+ }
+ }
+
+ // Flush only on the clean path; an aborted or errored decode should
+ // not wait for the full pipeline to drain.
+ if (!signal?.aborted && !decodeError && decoder.state === "configured") {
+ await decoder.flush();
}
} finally {
- try {
- await reader.cancel();
- } catch {
- /* already closed */
+ // Always release the decoder — a throw in the demux loop must not
+ // leak a configured AudioDecoder (they hold codec-native memory).
+ if (decoder.state !== "closed") {
+ try {
+ decoder.close();
+ } catch {
+ /* already closed */
+ }
}
}
-
- if (decoder.state === "configured") {
- await decoder.flush();
- decoder.close();
- }
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
if (decodeError) throw decodeError;
if (decodedFrames === 0) {
diff --git a/src/hooks/useAudioPeaks.ts b/src/hooks/useAudioPeaks.ts
index d6eb687a5..daa0abf09 100644
--- a/src/hooks/useAudioPeaks.ts
+++ b/src/hooks/useAudioPeaks.ts
@@ -74,7 +74,8 @@ async function computePeaksForUrl(videoUrl: string, signal?: AbortSignal): Promi
const info = await window.electronAPI.getReadableFileInfo(videoUrl);
if (info.success && typeof info.size === "number" && info.size > MAX_IN_MEMORY_SOURCE_BYTES) {
const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
- const file = await materializeLocalSourceFile(videoUrl, filename);
+ // signal also aborts the OPFS copy (unless the export shares it).
+ const file = await materializeLocalSourceFile(videoUrl, filename, { signal });
try {
return await computePeaksFromFileStreaming(file, signal);
} finally {
diff --git a/src/lib/captioning/extractMono16k.ts b/src/lib/captioning/extractMono16k.ts
index 999113e9d..bf2c7320f 100644
--- a/src/lib/captioning/extractMono16k.ts
+++ b/src/lib/captioning/extractMono16k.ts
@@ -6,6 +6,12 @@ import { extractMonoPcmViaWebDemuxer } from "./extractMono16kWebDemuxer";
export { MAX_CAPTION_AUDIO_SEC };
const FETCH_TIMEOUT_MS = 120_000;
+// The demuxer caption path holds every decoded AudioData frame plus full-rate
+// merge buffers in memory (~50 MB per minute of 48 kHz audio all-in), so very
+// long recordings would exhaust the renderer heap well before the 4 h caption
+// ceiling. For sources too large to load in memory anyway, cap the decoded
+// audio; captions come back truncated instead of crashing the renderer.
+const LARGE_FILE_CAPTION_SEC = 30 * 60;
async function fetchWithTimeout(url: string, signal?: AbortSignal): Promise<Response> {
const ctrl = new AbortController();
@@ -33,9 +39,10 @@ async function loadSourceVideoFile(videoUrl: string, signal?: AbortSignal): Prom
if (!isRemoteUrl && window.electronAPI) {
// Streams large recordings through OPFS instead of reading them whole, so
- // captions work for multi-GB files just like export does.
+ // captions work for multi-GB files just like export does. The signal also
+ // aborts the copy itself when the caption pass is cancelled.
const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
- return materializeLocalSourceFile(videoUrl, filename);
+ return materializeLocalSourceFile(videoUrl, filename, { signal });
}
const response = await fetchWithTimeout(videoUrl, signal);
@@ -152,13 +159,26 @@ export async function extractMono16kFromVideoUrl(
try {
// Large recordings skip the in-memory decodeAudioData path (it would load
// the whole file) and go straight to the streaming web-demuxer path below.
- const primary = file.size > MAX_IN_MEMORY_SOURCE_BYTES ? null : await tryDecodeAudioDataPath();
+ const isLargeFile = file.size > MAX_IN_MEMORY_SOURCE_BYTES;
+ const primary = isLargeFile ? null : await tryDecodeAudioDataPath();
if (primary) {
return primary;
}
- const pcm = await extractMonoPcmViaWebDemuxer(file, options?.signal);
- return truncateAndResampleTo16k(pcm.mono, pcm.sampleRate, pcm.durationSec, options?.signal);
+ // For oversized sources, also cap how much audio the demuxer path decodes
+ // — its frame/merge buffers are in-memory and scale with duration.
+ const pcm = await extractMonoPcmViaWebDemuxer(
+ file,
+ options?.signal,
+ isLargeFile ? LARGE_FILE_CAPTION_SEC : undefined,
+ );
+ const out = await truncateAndResampleTo16k(
+ pcm.mono,
+ pcm.sampleRate,
+ pcm.durationSec,
+ options?.signal,
+ );
+ return { ...out, truncated: out.truncated || pcm.capped };
} finally {
// Release the OPFS cache reference taken when streaming a large source.
// The File name is the cache-entry key (no-op for small/remote sources).
diff --git a/src/lib/captioning/extractMono16kWebDemuxer.ts b/src/lib/captioning/extractMono16kWebDemuxer.ts
index 3a00aa0bf..641f26351 100644
--- a/src/lib/captioning/extractMono16kWebDemuxer.ts
+++ b/src/lib/captioning/extractMono16kWebDemuxer.ts
@@ -92,11 +92,17 @@ function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promi
/**
* Demux + WebCodecs audio decode (same stack as export). Use when `decodeAudioData`
* can't handle the container (e.g. WebM with video).
+ *
+ * @param maxReadSec Optional cap on how much audio to demux/decode. The decoded
+ * frames and merge buffers are held in memory, so very long recordings must be
+ * capped below MAX_CAPTION_AUDIO_SEC to avoid exhausting the renderer heap.
+ * `capped` reports whether the cap actually cut the track short.
*/
export async function extractMonoPcmViaWebDemuxer(
file: File,
signal?: AbortSignal,
-): Promise<{ mono: Float32Array; sampleRate: number; durationSec: number }> {
+ maxReadSec?: number,
+): Promise<{ mono: Float32Array; sampleRate: number; durationSec: number; capped: boolean }> {
const demuxer = new WebDemuxer({ wasmFilePath: webDemuxerWasmUrl() });
await withTimeout(
demuxer.load(file),
@@ -132,7 +138,8 @@ export async function extractMonoPcmViaWebDemuxer(
// Many WebM/Matroska files report a too-short duration, so capping read at reported time stops
// demux early and clips everything past that. Read to the caption-decode ceiling instead; the
// demuxer stops when the track ends.
- const readEndSec = MAX_CAPTION_AUDIO_SEC + READ_END_PADDING_SEC;
+ const readCapSec = Math.min(maxReadSec ?? MAX_CAPTION_AUDIO_SEC, MAX_CAPTION_AUDIO_SEC);
+ const readEndSec = readCapSec + READ_END_PADDING_SEC;
const decodedFrames: AudioData[] = [];
const decoder = new AudioDecoder({
@@ -183,6 +190,9 @@ export async function extractMonoPcmViaWebDemuxer(
// metadata when frames lack duration.
const durationSec = inferredDurationSec > 0.02 ? inferredDurationSec : reportedDurationSec;
+ // The cap cut the track short when the reported extent exceeds what we read.
+ const capped = reportedDurationSec > readCapSec + READ_END_PADDING_SEC;
+
const mono = mergeAndConsumeDecodedAudioToMonoLinear(decodedFrames, sampleRate, durationSec);
- return { mono, sampleRate, durationSec };
+ return { mono, sampleRate, durationSec, capped };
}
diff --git a/src/lib/exporter/localSourceFile.test.ts b/src/lib/exporter/localSourceFile.test.ts
index 705bd11d3..7d4b14163 100644
--- a/src/lib/exporter/localSourceFile.test.ts
+++ b/src/lib/exporter/localSourceFile.test.ts
@@ -324,6 +324,118 @@ describe("materializeLocalSourceFile (large file OPFS path)", () => {
});
});
+describe("materializeLocalSourceFile (in-flight dedup & abort)", () => {
+ const OPTS = { thresholdBytes: 4, chunkBytes: 3 };
+
+ it("deduplicates concurrent copies of the same entry into one stream", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+ const source = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
+ const api = largeSourceApi("/rec/dup.mp4", source);
+ stubElectronAPI(api);
+
+ const [a, b] = await Promise.all([
+ materializeLocalSourceFile("/rec/dup.mp4", "dup.mp4", OPTS),
+ materializeLocalSourceFile("/rec/dup.mp4", "dup.mp4", OPTS),
+ ]);
+
+ // One shared copy: 7 bytes / 3-byte chunks => exactly 3 reads, not 6.
+ expect(api.readFileChunk).toHaveBeenCalledTimes(3);
+ expect(new Uint8Array(await a.arrayBuffer())).toEqual(source);
+ expect(new Uint8Array(await b.arrayBuffer())).toEqual(source);
+ expect(a.name).toBe(b.name);
+
+ // Each caller took one reference; after both release, a later
+ // materialization of another entry prunes it.
+ releaseLocalSourceFile(a.name);
+ releaseLocalSourceFile(b.name);
+ stubElectronAPI(largeSourceApi("/rec/other.mp4", new Uint8Array([9, 9, 9, 9, 9])));
+ const other = await materializeLocalSourceFile("/rec/other.mp4", "other.mp4", OPTS);
+ expect(cacheDir(root)?.files.size).toBe(1);
+ releaseLocalSourceFile(other.name);
+ });
+
+ it("aborts the copy via the AbortSignal and cleans up the partial entry", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+ const source = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
+ const api = largeSourceApi("/rec/ab.mp4", source);
+ let releaseFirstChunk!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ releaseFirstChunk = resolve;
+ });
+ api.readFileChunk = vi.fn(async (_url: string, offset: number, length: number) => {
+ if (offset === 0) await gate;
+ return {
+ success: true,
+ data: source.slice(offset, offset + length).buffer,
+ bytesRead: Math.min(length, source.byteLength - offset),
+ };
+ });
+ stubElectronAPI(api);
+
+ const controller = new AbortController();
+ const promise = materializeLocalSourceFile("/rec/ab.mp4", "ab.mp4", {
+ ...OPTS,
+ signal: controller.signal,
+ });
+ // Let the copy enter its gated first chunk, then abort mid-copy.
+ while (api.readFileChunk.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ controller.abort();
+ releaseFirstChunk();
+
+ await expect(promise).rejects.toThrow(/abort/i);
+ // Give the shared flight's cleanup a tick to settle.
+ await new Promise((r) => setTimeout(r, 0));
+ expect(cacheDir(root)?.files.size ?? 0).toBe(0);
+
+ // A retry after abort works from scratch.
+ const retry = await materializeLocalSourceFile("/rec/ab.mp4", "ab.mp4", OPTS);
+ expect(new Uint8Array(await retry.arrayBuffer())).toEqual(source);
+ releaseLocalSourceFile(retry.name);
+ });
+
+ it("keeps the shared copy alive while another joined caller is still interested", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+ const source = new Uint8Array([1, 2, 3, 4, 5, 6]);
+ const api = largeSourceApi("/rec/share.mp4", source);
+ let releaseFirstChunk!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ releaseFirstChunk = resolve;
+ });
+ api.readFileChunk = vi.fn(async (_url: string, offset: number, length: number) => {
+ if (offset === 0) await gate;
+ return {
+ success: true,
+ data: source.slice(offset, offset + length).buffer,
+ bytesRead: Math.min(length, source.byteLength - offset),
+ };
+ });
+ stubElectronAPI(api);
+
+ const controller = new AbortController();
+ const abortable = materializeLocalSourceFile("/rec/share.mp4", "share.mp4", {
+ ...OPTS,
+ signal: controller.signal,
+ });
+ const steady = materializeLocalSourceFile("/rec/share.mp4", "share.mp4", OPTS);
+ while (api.readFileChunk.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ // One of two joined callers aborts: the shared copy must keep going.
+ controller.abort();
+ releaseFirstChunk();
+
+ await expect(abortable).rejects.toThrow(/abort/i);
+ const file = await steady;
+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(source);
+ releaseLocalSourceFile(file.name);
+ });
+});
+
describe("materializeLocalSourceFile (MIME inference)", () => {
it.each([
["/tmp/clip.webm", "video/webm"],
diff --git a/src/lib/exporter/localSourceFile.ts b/src/lib/exporter/localSourceFile.ts
index 62b1b6237..8f4fbb8c3 100644
--- a/src/lib/exporter/localSourceFile.ts
+++ b/src/lib/exporter/localSourceFile.ts
@@ -17,6 +17,13 @@ import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";
* we stream the file into an OPFS-backed file in fixed-size chunks and hand back
* the disk-backed `File` from `getFile()`. Memory stays flat regardless of size.
*
+ * Concurrency: copies are deduplicated per cache entry — concurrent callers of
+ * the same recording (e.g. the trim waveform and an export) share one in-flight
+ * copy instead of racing two writables on the same OPFS handle. Each caller can
+ * pass an `AbortSignal`; the underlying copy is aborted only once every joined
+ * caller has aborted. Successful callers take one cache reference each and must
+ * call {@link releaseLocalSourceFile} with the returned File's `.name`.
+ *
* Small recordings keep the original in-memory path — it is simpler and avoids
* an extra on-disk copy for the common case.
*/
@@ -34,6 +41,8 @@ export interface MaterializeProgress {
export interface MaterializeOptions {
onProgress?: (progress: MaterializeProgress) => void;
+ /** Aborts the wait; the shared copy stops once every joined caller aborts. */
+ signal?: AbortSignal;
/** Override the in-memory threshold (testing only). */
thresholdBytes?: number;
/** Override the OPFS copy chunk size (testing only). */
@@ -50,6 +59,17 @@ export interface MaterializeOptions {
*/
const activeCacheRefs = new Map<string, number>();
+/** One shared in-flight copy per cache entry; concurrent callers join it. */
+interface InflightCopy {
+ promise: Promise<void>;
+ controller: AbortController;
+ consumers: number;
+ progressListeners: Set<(progress: MaterializeProgress) => void>;
+ lastProgress?: MaterializeProgress;
+}
+
+const inflightCopies = new Map<string, InflightCopy>();
+
function retainCache(cacheName: string): void {
activeCacheRefs.set(cacheName, (activeCacheRefs.get(cacheName) ?? 0) + 1);
}
@@ -66,8 +86,28 @@ export function releaseLocalSourceFile(cacheName: string): void {
else activeCacheRefs.set(cacheName, refs - 1);
}
-function activeCacheNames(): Set<string> {
- return new Set(activeCacheRefs.keys());
+/** Names that must survive pruning: referenced by a demuxer or mid-copy. */
+function keepSet(): Set<string> {
+ const keep = new Set(activeCacheRefs.keys());
+ for (const name of inflightCopies.keys()) keep.add(name);
+ return keep;
+}
+
+/**
+ * Removes cache entries left behind by a previous session (or by exports whose
+ * source was never materialized again). Call once at app startup: nothing is
+ * referenced or mid-copy at that point, so everything stale is reclaimed.
+ */
+export async function clearStaleSourceCache(): Promise<void> {
+ const getDirectory = navigator.storage?.getDirectory?.bind(navigator.storage);
+ if (!getDirectory) return;
+ try {
+ const root = await getDirectory();
+ const dir = await root.getDirectoryHandle(OPFS_CACHE_DIR);
+ await pruneStaleEntries(dir, keepSet());
+ } catch {
+ // No cache directory yet — nothing to clean.
+ }
}
const MIME_BY_EXTENSION: Record<string, string> = {
@@ -96,13 +136,17 @@ function hashString(input: string): string {
return (hash >>> 0).toString(36);
}
+function throwIfAborted(signal?: AbortSignal): void {
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
+}
+
/**
* Returns a `File` for a local recording path/URL, streaming large files through
* OPFS so nothing multi-GB is ever held in memory.
*
* @param videoUrl Local file path or `file://` URL of the recording.
* @param filename Preferred file name for the returned `File`.
- * @param options Progress callback and (testing) threshold/chunk overrides.
+ * @param options Progress callback, abort signal, (testing) size overrides.
*/
export async function materializeLocalSourceFile(
videoUrl: string,
@@ -114,12 +158,14 @@ export async function materializeLocalSourceFile(
throw new Error("Local source loading is only available in the desktop app.");
}
+ throwIfAborted(options?.signal);
const threshold = options?.thresholdBytes ?? MAX_IN_MEMORY_SOURCE_BYTES;
const info = await api.getReadableFileInfo(videoUrl);
if (!info.success || typeof info.size !== "number") {
throw new Error(info.message || info.error || "Failed to read source video");
}
+ throwIfAborted(options?.signal);
// Common case: small enough to read in one shot.
if (info.size <= threshold) {
@@ -127,6 +173,7 @@ export async function materializeLocalSourceFile(
if (!result.success || !result.data) {
throw new Error(result.message || result.error || "Failed to read source video");
}
+ throwIfAborted(options?.signal);
const name = (result.path || filename).split(/[\\/]/).pop() || filename;
return new File([result.data], name, { type: mimeTypeForPath(name) });
}
@@ -157,29 +204,102 @@ async function copyToOpfsFile(
// Cache key ties the copy to this exact file revision so repeated exports of
// the same recording reuse the cached copy instead of re-streaming gigabytes.
const cacheName = `${hashString(videoUrl)}-${size}-${Math.round(mtimeMs)}.bin`;
+ const signal = options?.signal;
- // Retain BEFORE pruning/writing: a concurrent materialization builds its keep
- // set from the refcounts, so retaining only after the copy finished would let
- // it prune this entry mid-write and fail the copy. Released in the catch
- // below on failure; on success the caller releases once the demuxer is done.
- retainCache(cacheName);
+ // Join (or start) the shared in-flight copy for this entry. Loop so a caller
+ // that races a flight aborted by its last consumer can start a fresh one.
+ for (;;) {
+ throwIfAborted(signal);
+
+ let flight = inflightCopies.get(cacheName);
+ if (flight?.controller.signal.aborted) {
+ await flight.promise.catch(() => undefined);
+ continue;
+ }
+ if (!flight) {
+ const controller = new AbortController();
+ const fresh: InflightCopy = {
+ controller,
+ consumers: 0,
+ progressListeners: new Set(),
+ promise: Promise.resolve(),
+ };
+ // Register BEFORE starting the copy so its own name is in keepSet()
+ // when the copy prunes, and so concurrent prunes keep mid-write entries.
+ inflightCopies.set(cacheName, fresh);
+ fresh.promise = runCopy(
+ dir,
+ cacheName,
+ videoUrl,
+ size,
+ controller.signal,
+ options?.chunkBytes ?? COPY_CHUNK_BYTES,
+ (p) => {
+ fresh.lastProgress = p;
+ for (const listener of fresh.progressListeners) listener(p);
+ },
+ ).finally(() => {
+ if (inflightCopies.get(cacheName) === fresh) inflightCopies.delete(cacheName);
+ });
+ // A flight abandoned by every consumer would otherwise be an unhandled rejection.
+ fresh.promise.catch(() => undefined);
+ flight = fresh;
+ }
+
+ flight.consumers += 1;
+ if (options?.onProgress) {
+ flight.progressListeners.add(options.onProgress);
+ if (flight.lastProgress) options.onProgress(flight.lastProgress);
+ }
+ const joined = flight;
+ const onAbort = () => {
+ joined.consumers -= 1;
+ // Last interested caller gone: stop the underlying copy.
+ if (joined.consumers <= 0) joined.controller.abort();
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ try {
+ await joined.promise;
+ throwIfAborted(signal);
+ const handle = await dir.getFileHandle(cacheName);
+ const file = await handle.getFile();
+ retainCache(cacheName);
+ return file;
+ } finally {
+ signal?.removeEventListener("abort", onAbort);
+ if (options?.onProgress) joined.progressListeners.delete(options.onProgress);
+ if (!signal?.aborted) joined.consumers -= 1;
+ }
+ }
+}
+
+/** Streams the source into the cache entry; resolves once it is complete on disk. */
+async function runCopy(
+ dir: FileSystemDirectoryHandle,
+ cacheName: string,
+ videoUrl: string,
+ size: number,
+ signal: AbortSignal,
+ chunkBytes: number,
+ emitProgress: (progress: MaterializeProgress) => void,
+): Promise<void> {
try {
- await pruneStaleEntries(dir, activeCacheNames());
+ await pruneStaleEntries(dir, keepSet());
const handle = await dir.getFileHandle(cacheName, { create: true });
// Reuse a complete prior copy.
const existing = await handle.getFile();
if (existing.size === size) {
- options?.onProgress?.({ copiedBytes: size, totalBytes: size });
- return existing;
+ emitProgress({ copiedBytes: size, totalBytes: size });
+ return;
}
- const chunkBytes = options?.chunkBytes ?? COPY_CHUNK_BYTES;
const writable = await handle.createWritable();
try {
let offset = 0;
while (offset < size) {
+ throwIfAborted(signal);
const length = Math.min(chunkBytes, size - offset);
const chunk = await window.electronAPI.readFileChunk(videoUrl, offset, length);
if (!chunk.success || !chunk.data) {
@@ -191,7 +311,7 @@ async function copyToOpfsFile(
}
await writable.write(chunk.data);
offset += chunk.data.byteLength;
- options?.onProgress?.({ copiedBytes: offset, totalBytes: size });
+ emitProgress({ copiedBytes: offset, totalBytes: size });
}
await writable.close();
} catch (error) {
@@ -209,12 +329,11 @@ async function copyToOpfsFile(
`Streamed copy is incomplete (${file.size} of ${size} bytes); the source video may still be in use.`,
);
}
- return file;
} catch (error) {
- // Drop this operation's reference, then drop the (possibly partial) copy
- // so a retry does not resume from a corrupt file — unless another
- // in-flight operation still references the same entry.
- releaseLocalSourceFile(cacheName);
+ // Drop the partial copy so a retry does not resume from a corrupt file.
+ // (No caller has retained this entry — retains happen only after success —
+ // but keep the guard in case a prior complete copy of the same name is
+ // still being read.)
if (!activeCacheRefs.has(cacheName)) {
try {
await dir.removeEntry(cacheName);
diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.ts
index 79af8bf99..34cfcd568 100644
--- a/src/lib/exporter/streamingDecoder.ts
+++ b/src/lib/exporter/streamingDecoder.ts
@@ -195,6 +195,10 @@ export class StreamingVideoDecoder {
// 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;
+ // Aborts an in-flight OPFS materialization when the decoder is cancelled,
+ // destroyed, or the load times out — otherwise a cancelled export would keep
+ // streaming gigabytes in the background and leak the cache reference.
+ private readonly loadAbort = new AbortController();
/** Routes to the appropriate loader based on whether the source is local or remote. */
private async loadSourceFile(
@@ -204,9 +208,11 @@ export class StreamingVideoDecoder {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI) {
return this.withTimeout(
- StreamingVideoDecoder.loadLocalSourceFile(videoUrl, onProgress),
+ StreamingVideoDecoder.loadLocalSourceFile(videoUrl, onProgress, this.loadAbort.signal),
LOCAL_SOURCE_LOAD_TIMEOUT_MS,
"Timed out while loading the source video.",
+ // Stop the underlying copy too; a bare reject would leave it running.
+ () => this.loadAbort.abort(),
);
}
return this.withTimeout(
@@ -224,9 +230,10 @@ export class StreamingVideoDecoder {
static async loadLocalSourceFile(
videoUrl: string,
onProgress?: (progress: MaterializeProgress) => void,
+ signal?: AbortSignal,
): Promise<File> {
const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
- return materializeLocalSourceFile(videoUrl, filename, { onProgress });
+ return materializeLocalSourceFile(videoUrl, filename, { onProgress, signal });
}
/** Loads a remote or blob video URL via fetch. */
@@ -764,11 +771,13 @@ export class StreamingVideoDecoder {
/** Signals the decoder to stop processing at the next cancellation checkpoint. */
cancel(): void {
this.cancelled = true;
+ this.loadAbort.abort();
}
/** Cancels decoding and releases the VideoDecoder and WebDemuxer resources. */
destroy(): void {
this.cancelled = true;
+ this.loadAbort.abort();
if (this.decoder) {
try {
@@ -795,9 +804,17 @@ export class StreamingVideoDecoder {
}
/** Wraps a promise with a hard timeout, rejecting with `message` if it exceeds `timeoutMs`. */
- private withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
+ private withTimeout<T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ message: string,
+ onTimeout?: () => void,
+ ): Promise<T> {
return new Promise<T>((resolve, reject) => {
- const timer = window.setTimeout(() => reject(new Error(message)), timeoutMs);
+ const timer = window.setTimeout(() => {
+ onTimeout?.();
+ reject(new Error(message));
+ }, timeoutMs);
promise.then(
(value) => {
window.clearTimeout(timer);
diff --git a/src/main.tsx b/src/main.tsx
index ef7497386..28d128507 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -2,9 +2,19 @@ import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import { I18nProvider } from "./contexts/I18nContext";
+import { clearStaleSourceCache } from "./lib/exporter/localSourceFile";
import "./index.css";
const windowType = new URLSearchParams(window.location.search).get("windowType") || "";
+
+// Reclaim multi-GB OPFS source copies left behind by a previous session (they
+// are only pruned opportunistically during the next large-file load otherwise).
+// Nothing is referenced at startup, so everything stale is safe to remove.
+if (!windowType) {
+ window.setTimeout(() => {
+ clearStaleSourceCache().catch(() => undefined);
+ }, 5_000);
+}
const showNotes = new URLSearchParams(window.location.search).get("showNotes") === "true";
if (
showNotes ||