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: guard OPFS source cache and surface copy progress

my_maca0c0875f5fa0
diff --git a/src/components/video-editor/ExportDialog.tsx b/src/components/video-editor/ExportDialog.tsx
index 44eae5d2e..b012617c1 100644
--- a/src/components/video-editor/ExportDialog.tsx
+++ b/src/components/video-editor/ExportDialog.tsx
@@ -62,6 +62,8 @@ export function ExportDialog({
const isCompiling =
isExporting && progress && progress.percentage >= 100 && exportFormat === "gif";
const isFinalizing = progress?.phase === "finalizing";
+ // Streaming a large recording into OPFS before frames start rendering.
+ const isPreparing = progress?.phase === "preparing";
const renderProgress = progress?.renderProgress;
const getStatusMessage = () => {
@@ -172,7 +174,9 @@ export function ExportDialog({
<span>
{isCompiling || isFinalizing
? t("export.compiling")
- : t("export.renderingFrames")}
+ : isPreparing
+ ? t("export.processing")
+ : t("export.renderingFrames")}
</span>
<span className="font-mono text-slate-200">
{isCompiling || isFinalizing ? (
@@ -240,7 +244,14 @@ export function ExportDialog({
{t("export.frames")}
</div>
<div className="text-slate-200 font-medium text-sm">
- {progress.currentFrame} / {progress.totalFrames}
+ {isPreparing ? (
+ <span className="flex items-center gap-2">
+ <Loader2 className="w-3 h-3 animate-spin" />
+ {t("export.processing")}
+ </span>
+ ) : (
+ `${progress.currentFrame} / ${progress.totalFrames}`
+ )}
</div>
</div>
</div>
diff --git a/src/lib/captioning/extractMono16k.ts b/src/lib/captioning/extractMono16k.ts
index 09988fac3..8763c0aed 100644
--- a/src/lib/captioning/extractMono16k.ts
+++ b/src/lib/captioning/extractMono16k.ts
@@ -1,14 +1,11 @@
-import { materializeLocalSourceFile } from "@/lib/exporter/localSourceFile";
+import { materializeLocalSourceFile, releaseLocalSourceFile } from "@/lib/exporter/localSourceFile";
+import { MAX_IN_MEMORY_SOURCE_BYTES } from "@/lib/exporter/sourceFileLimits";
import { MAX_CAPTION_AUDIO_SEC } from "./captionConstants";
import { extractMonoPcmViaWebDemuxer } from "./extractMono16kWebDemuxer";
export { MAX_CAPTION_AUDIO_SEC };
const FETCH_TIMEOUT_MS = 120_000;
-// Above this size, `file.arrayBuffer()` for the decodeAudioData path would try to
-// hold the whole recording in memory. Skip straight to the streaming web-demuxer
-// path instead (it reads audio packets on demand).
-const MAX_DECODE_AUDIO_DATA_BYTES = 1.5 * 1024 * 1024 * 1024;
async function fetchWithTimeout(url: string, signal?: AbortSignal): Promise<Response> {
const ctrl = new AbortController();
@@ -152,13 +149,18 @@ export async function extractMono16kFromVideoUrl(
}
};
- // 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_DECODE_AUDIO_DATA_BYTES ? null : await tryDecodeAudioDataPath();
- if (primary) {
- return primary;
- }
+ 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();
+ if (primary) {
+ return primary;
+ }
- const pcm = await extractMonoPcmViaWebDemuxer(file, options?.signal);
- return truncateAndResampleTo16k(pcm.mono, pcm.sampleRate, pcm.durationSec, options?.signal);
+ const pcm = await extractMonoPcmViaWebDemuxer(file, options?.signal);
+ return truncateAndResampleTo16k(pcm.mono, pcm.sampleRate, pcm.durationSec, options?.signal);
+ } finally {
+ // Release the OPFS cache reference taken when streaming a large source.
+ releaseLocalSourceFile(videoUrl);
+ }
}
diff --git a/src/lib/exporter/localSourceFile.test.ts b/src/lib/exporter/localSourceFile.test.ts
index 3c60f1056..2d83f1ed9 100644
--- a/src/lib/exporter/localSourceFile.test.ts
+++ b/src/lib/exporter/localSourceFile.test.ts
@@ -1,11 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { materializeLocalSourceFile } from "./localSourceFile";
-
-/**
- * The large-file (OPFS streaming) path is verified end-to-end against a real
- * multi-GB recording; these unit tests cover the small-file branch and the
- * error handling that does not depend on OPFS.
- */
+import { materializeLocalSourceFile, releaseLocalSourceFile } from "./localSourceFile";
function stubElectronAPI(api: Record<string, unknown>) {
vi.stubGlobal("window", { ...globalThis.window, electronAPI: api } as unknown);
@@ -15,7 +9,7 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-describe("materializeLocalSourceFile", () => {
+describe("materializeLocalSourceFile (small file path)", () => {
it("reads a small file in one shot and returns a File with its bytes", async () => {
const bytes = new Uint8Array([1, 2, 3, 4, 5]);
stubElectronAPI({
@@ -84,3 +78,167 @@ describe("materializeLocalSourceFile", () => {
);
});
});
+
+// ---- Minimal in-memory OPFS fake for the large-file streaming path ----
+
+class FakeWritable {
+ private parts: Uint8Array[] = [];
+ constructor(private readonly onClose: (bytes: Uint8Array) => void) {}
+ async write(data: ArrayBuffer | Uint8Array) {
+ this.parts.push(data instanceof Uint8Array ? new Uint8Array(data) : new Uint8Array(data));
+ }
+ async close() {
+ const total = this.parts.reduce((n, p) => n + p.byteLength, 0);
+ const merged = new Uint8Array(total);
+ let offset = 0;
+ for (const p of this.parts) {
+ merged.set(p, offset);
+ offset += p.byteLength;
+ }
+ this.onClose(merged);
+ }
+ async abort() {
+ this.parts = [];
+ }
+}
+
+class FakeFileHandle {
+ bytes = new Uint8Array(0);
+ constructor(readonly name: string) {}
+ async getFile() {
+ return new File([this.bytes], this.name);
+ }
+ async createWritable() {
+ return new FakeWritable((b) => {
+ this.bytes = b;
+ });
+ }
+}
+
+class FakeDir {
+ files = new Map<string, FakeFileHandle>();
+ subdirs = new Map<string, FakeDir>();
+ async getDirectoryHandle(name: string, opts?: { create?: boolean }) {
+ let dir = this.subdirs.get(name);
+ if (!dir && opts?.create) {
+ dir = new FakeDir();
+ this.subdirs.set(name, dir);
+ }
+ if (!dir) throw new DOMException("NotFound", "NotFoundError");
+ return dir as unknown as FileSystemDirectoryHandle;
+ }
+ async getFileHandle(name: string, opts?: { create?: boolean }) {
+ let file = this.files.get(name);
+ if (!file && opts?.create) {
+ file = new FakeFileHandle(name);
+ this.files.set(name, file);
+ }
+ if (!file) throw new DOMException("NotFound", "NotFoundError");
+ return file as unknown as FileSystemFileHandle;
+ }
+ async *keys() {
+ yield* this.files.keys();
+ }
+ async removeEntry(name: string) {
+ this.files.delete(name);
+ }
+}
+
+function stubOpfs(root: FakeDir) {
+ vi.stubGlobal("navigator", { storage: { getDirectory: async () => root } } as unknown);
+}
+
+function cacheDir(root: FakeDir): FakeDir | undefined {
+ return root.subdirs.get("openscreen-source-cache");
+}
+
+/** electronAPI whose readFileChunk serves slices of `source`. */
+function largeSourceApi(url: string, source: Uint8Array, mtimeMs = 1) {
+ return {
+ getReadableFileInfo: vi
+ .fn()
+ .mockResolvedValue({ success: true, size: source.byteLength, mtimeMs, path: url }),
+ readBinaryFile: vi.fn(),
+ readFileChunk: vi.fn(async (_url: string, offset: number, length: number) => ({
+ success: true,
+ data: source.slice(offset, offset + length).buffer,
+ bytesRead: Math.min(length, source.byteLength - offset),
+ })),
+ };
+}
+
+describe("materializeLocalSourceFile (large file OPFS path)", () => {
+ const OPTS = { thresholdBytes: 4, chunkBytes: 3 };
+
+ it("streams a large file into OPFS in chunks and returns the exact bytes", async () => {
+ const source = new Uint8Array([10, 20, 30, 40, 50, 60, 70]);
+ const api = largeSourceApi("/rec/a.mp4", source);
+ stubElectronAPI(api);
+ stubOpfs(new FakeDir());
+
+ const file = await materializeLocalSourceFile("/rec/a.mp4", "a.mp4", OPTS);
+
+ expect(file.size).toBe(source.byteLength);
+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(source);
+ // 7 bytes / 3-byte chunks => 3 reads.
+ expect(api.readFileChunk).toHaveBeenCalledTimes(3);
+ expect(api.readBinaryFile).not.toHaveBeenCalled();
+
+ releaseLocalSourceFile("/rec/a.mp4");
+ });
+
+ it("reuses the cached copy on a second call without re-streaming", async () => {
+ const source = new Uint8Array([1, 2, 3, 4, 5, 6]);
+ const api = largeSourceApi("/rec/b.mp4", source);
+ stubElectronAPI(api);
+ stubOpfs(new FakeDir());
+
+ await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
+ const firstReads = api.readFileChunk.mock.calls.length;
+ await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
+
+ expect(api.readFileChunk.mock.calls.length).toBe(firstReads); // no new reads
+
+ releaseLocalSourceFile("/rec/b.mp4");
+ releaseLocalSourceFile("/rec/b.mp4");
+ });
+
+ it("keeps a cache entry that is still referenced by another active source", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+
+ stubElectronAPI(largeSourceApi("/rec/a.mp4", new Uint8Array([1, 2, 3, 4, 5])));
+ 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
+
+ // 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");
+ });
+
+ it("prunes a cache entry once it has been released", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+
+ stubElectronAPI(largeSourceApi("/rec/a.mp4", new Uint8Array([1, 2, 3, 4, 5])));
+ 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
+
+ releaseLocalSourceFile("/rec/a.mp4"); // 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
+
+ // A pruned; B (still active) and C remain.
+ expect(cacheDir(root)?.files.size).toBe(2);
+
+ releaseLocalSourceFile("/rec/b.mp4");
+ releaseLocalSourceFile("/rec/c.mp4");
+ });
+});
diff --git a/src/lib/exporter/localSourceFile.ts b/src/lib/exporter/localSourceFile.ts
index 969167364..0c478872b 100644
--- a/src/lib/exporter/localSourceFile.ts
+++ b/src/lib/exporter/localSourceFile.ts
@@ -1,3 +1,5 @@
+import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";
+
/**
* Loads a local recording as a `File` suitable for `web-demuxer`, without ever
* holding the whole recording in memory.
@@ -19,10 +21,6 @@
* an extra on-disk copy for the common case.
*/
-// Stay comfortably under Node's 2 GiB single-read cap so read-binary-file never
-// throws ERR_FS_FILE_TOO_LARGE. Anything larger is streamed via OPFS instead.
-const LARGE_FILE_THRESHOLD_BYTES = 1.5 * 1024 * 1024 * 1024;
-
// Chunk size for streaming a large file into OPFS. Large enough to keep IPC
// overhead low, small enough that peak memory stays bounded.
const COPY_CHUNK_BYTES = 32 * 1024 * 1024;
@@ -34,6 +32,49 @@ export interface MaterializeProgress {
totalBytes: number;
}
+export interface MaterializeOptions {
+ onProgress?: (progress: MaterializeProgress) => void;
+ /** Override the in-memory threshold (testing only). */
+ thresholdBytes?: number;
+ /** Override the OPFS copy chunk size (testing only). */
+ chunkBytes?: number;
+}
+
+/**
+ * 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.
+ */
+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 });
+ }
+}
+
+/**
+ * Releases a reference taken by {@link materializeLocalSourceFile} for a large
+ * (OPFS-streamed) source. No-op for small sources and for URLs never streamed.
+ */
+export function releaseLocalSourceFile(videoUrl: string): void {
+ const entry = activeSources.get(videoUrl);
+ if (!entry) return;
+ entry.refs -= 1;
+ if (entry.refs <= 0) activeSources.delete(videoUrl);
+}
+
+function activeCacheNames(): Set<string> {
+ const names = new Set<string>();
+ for (const entry of activeSources.values()) names.add(entry.cacheName);
+ return names;
+}
+
/** Stable non-cryptographic hash for building a cache key from a path. */
function hashString(input: string): string {
let hash = 5381;
@@ -49,25 +90,27 @@ function hashString(input: string): string {
*
* @param videoUrl Local file path or `file://` URL of the recording.
* @param filename Preferred file name for the returned `File`.
- * @param onProgress Optional progress callback for the large-file copy.
+ * @param options Progress callback and (testing) threshold/chunk overrides.
*/
export async function materializeLocalSourceFile(
videoUrl: string,
filename: string,
- onProgress?: (progress: MaterializeProgress) => void,
+ options?: MaterializeOptions,
): Promise<File> {
const api = window.electronAPI;
if (!api) {
throw new Error("Local source loading is only available in the desktop app.");
}
+ 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");
}
// Common case: small enough to read in one shot.
- if (info.size <= LARGE_FILE_THRESHOLD_BYTES) {
+ if (info.size <= threshold) {
const result = await api.readBinaryFile(videoUrl);
if (!result.success || !result.data) {
throw new Error(result.message || result.error || "Failed to read source video");
@@ -79,14 +122,14 @@ export async function materializeLocalSourceFile(
// Large recording: stream into OPFS and hand back a disk-backed File.
// web-demuxer detects the container from content, so the File name is
// irrelevant here — the OPFS entry keeps its cache-key name.
- return copyToOpfsFile(videoUrl, info.size, info.mtimeMs ?? 0, onProgress);
+ return copyToOpfsFile(videoUrl, info.size, info.mtimeMs ?? 0, options);
}
async function copyToOpfsFile(
videoUrl: string,
size: number,
mtimeMs: number,
- onProgress?: (progress: MaterializeProgress) => void,
+ options?: MaterializeOptions,
): Promise<File> {
const getDirectory = navigator.storage?.getDirectory?.bind(navigator.storage);
if (!getDirectory) {
@@ -103,33 +146,38 @@ async function copyToOpfsFile(
// the same recording reuse the cached copy instead of re-streaming gigabytes.
const cacheName = `${hashString(videoUrl)}-${size}-${Math.round(mtimeMs)}.bin`;
- await pruneStaleEntries(dir, cacheName);
+ // Keep the entry we are about to use plus anything a live demuxer still reads.
+ const keep = activeCacheNames();
+ keep.add(cacheName);
+ await pruneStaleEntries(dir, keep);
const handle = await dir.getFileHandle(cacheName, { create: true });
// Reuse a complete prior copy.
const existing = await handle.getFile();
if (existing.size === size) {
- onProgress?.({ copiedBytes: size, totalBytes: size });
+ options?.onProgress?.({ copiedBytes: size, totalBytes: size });
+ retainSource(videoUrl, cacheName);
return existing;
}
+ const chunkBytes = options?.chunkBytes ?? COPY_CHUNK_BYTES;
const writable = await handle.createWritable();
try {
let offset = 0;
while (offset < size) {
- const length = Math.min(COPY_CHUNK_BYTES, size - offset);
+ const length = Math.min(chunkBytes, size - offset);
const chunk = await window.electronAPI.readFileChunk(videoUrl, offset, length);
if (!chunk.success || !chunk.data) {
throw new Error(chunk.message || chunk.error || "Failed to read source video chunk");
}
- await writable.write(chunk.data);
- offset += chunk.data.byteLength;
- onProgress?.({ copiedBytes: offset, totalBytes: size });
// Guard against a short read that would otherwise loop forever.
if (chunk.data.byteLength === 0) {
throw new Error("Source video read returned no data before reaching the end.");
}
+ await writable.write(chunk.data);
+ offset += chunk.data.byteLength;
+ options?.onProgress?.({ copiedBytes: offset, totalBytes: size });
}
await writable.close();
} catch (error) {
@@ -153,11 +201,12 @@ async function copyToOpfsFile(
`Streamed copy is incomplete (${file.size} of ${size} bytes); the source video may still be in use.`,
);
}
+ retainSource(videoUrl, cacheName);
return file;
}
-/** Removes any cached copies in the directory other than the current key. */
-async function pruneStaleEntries(dir: FileSystemDirectoryHandle, keepName: string): Promise<void> {
+/** Removes cached copies in the directory whose names are not in `keep`. */
+async function pruneStaleEntries(dir: FileSystemDirectoryHandle, keep: Set<string>): Promise<void> {
// FileSystemDirectoryHandle async iteration is available in Chromium/Electron.
const entries = (
dir as unknown as {
@@ -167,7 +216,7 @@ async function pruneStaleEntries(dir: FileSystemDirectoryHandle, keepName: strin
if (!entries) return;
const toRemove: string[] = [];
for await (const name of entries) {
- if (name !== keepName) toRemove.push(name);
+ if (!keep.has(name)) toRemove.push(name);
}
await Promise.all(toRemove.map((name) => dir.removeEntry(name).catch(() => undefined)));
}
diff --git a/src/lib/exporter/sourceFileLimits.ts b/src/lib/exporter/sourceFileLimits.ts
new file mode 100644
index 000000000..fcd9de6a7
--- /dev/null
+++ b/src/lib/exporter/sourceFileLimits.ts
@@ -0,0 +1,12 @@
+/**
+ * Largest source file we are willing to read fully into memory in one shot.
+ *
+ * Node's `fs.readFile` (behind the `read-binary-file` IPC) throws
+ * `ERR_FS_FILE_TOO_LARGE` above 2 GiB, and a multi-GB `ArrayBuffer`/`Blob` would
+ * exhaust memory on typical machines anyway. Recordings above this threshold are
+ * streamed on demand instead (into OPFS for demuxing; skipped for the in-memory
+ * source-copy and waveform/decodeAudioData paths).
+ *
+ * Kept comfortably below the 2 GiB cap to leave headroom.
+ */
+export const MAX_IN_MEMORY_SOURCE_BYTES = 1.5 * 1024 * 1024 * 1024;
diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.ts
index 3d526dd14..706ef056a 100644
--- a/src/lib/exporter/streamingDecoder.ts
+++ b/src/lib/exporter/streamingDecoder.ts
@@ -1,6 +1,10 @@
import { WebDemuxer } from "web-demuxer";
import type { SpeedRegion, TrimRegion } from "@/components/video-editor/types";
-import { materializeLocalSourceFile } from "./localSourceFile";
+import {
+ type MaterializeProgress,
+ materializeLocalSourceFile,
+ releaseLocalSourceFile,
+} from "./localSourceFile";
const SOURCE_LOAD_TIMEOUT_MS = 60_000;
// Large local recordings are streamed into OPFS before demuxing, which is
@@ -181,13 +185,20 @@ 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;
/** Routes to the appropriate loader based on whether the source is local or remote. */
- private async loadSourceFile(videoUrl: string): Promise<File> {
+ private async loadSourceFile(
+ videoUrl: string,
+ onProgress?: (progress: MaterializeProgress) => void,
+ ): Promise<File> {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI) {
+ this.localSourceUrl = videoUrl;
return this.withTimeout(
- StreamingVideoDecoder.loadLocalSourceFile(videoUrl),
+ StreamingVideoDecoder.loadLocalSourceFile(videoUrl, onProgress),
LOCAL_SOURCE_LOAD_TIMEOUT_MS,
"Timed out while loading the source video.",
);
@@ -204,9 +215,12 @@ export class StreamingVideoDecoder {
* an OPFS-backed File so nothing multi-GB is held in memory; web-demuxer reads
* the File on demand. See {@link materializeLocalSourceFile}.
*/
- static async loadLocalSourceFile(videoUrl: string): Promise<File> {
+ static async loadLocalSourceFile(
+ videoUrl: string,
+ onProgress?: (progress: MaterializeProgress) => void,
+ ): Promise<File> {
const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
- return materializeLocalSourceFile(videoUrl, filename);
+ return materializeLocalSourceFile(videoUrl, filename, { onProgress });
}
/** Loads a remote or blob video URL via fetch. */
@@ -220,8 +234,11 @@ export class StreamingVideoDecoder {
return new File([blob], filename, { type: blob.type });
}
- async loadMetadata(videoUrl: string): Promise<DecodedVideoInfo> {
- const file = await this.loadSourceFile(videoUrl);
+ async loadMetadata(
+ videoUrl: string,
+ onSourceProgress?: (progress: MaterializeProgress) => void,
+ ): Promise<DecodedVideoInfo> {
+ const file = await this.loadSourceFile(videoUrl, onSourceProgress);
// 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;
@@ -761,6 +778,11 @@ export class StreamingVideoDecoder {
}
this.demuxer = null;
}
+
+ if (this.localSourceUrl) {
+ releaseLocalSourceFile(this.localSourceUrl);
+ this.localSourceUrl = null;
+ }
}
/** Wraps a promise with a hard timeout, rejecting with `message` if it exceeds `timeoutMs`. */
diff --git a/src/lib/exporter/types.ts b/src/lib/exporter/types.ts
index 138d97ecb..e779a27b6 100644
--- a/src/lib/exporter/types.ts
+++ b/src/lib/exporter/types.ts
@@ -11,7 +11,7 @@ export interface ExportProgress {
totalFrames: number;
percentage: number;
estimatedTimeRemaining: number; // seconds
- phase?: "extracting" | "finalizing";
+ phase?: "preparing" | "extracting" | "finalizing";
renderProgress?: number; // 0-100, GIF render phase
}
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index d2208982a..b89dfb74b 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -13,15 +13,13 @@ import { getPlatform } from "@/utils/platformUtils";
import { AudioProcessor } from "./audioEncoder";
import { FrameRenderer } from "./frameRenderer";
import { VideoMuxer } from "./muxer";
+import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";
import { StreamingVideoDecoder } from "./streamingDecoder";
import { TimestampedVideoFrameQueue } from "./timestampedVideoFrameQueue";
import type { ExportConfig, ExportProgress, ExportResult } from "./types";
const ENCODER_STALL_TIMEOUT_MS = 15_000;
const ENCODER_FLUSH_TIMEOUT_MS = 20_000;
-// The source-copy fast path reads the whole file into memory; stay under Node's
-// 2 GiB single-read cap so larger recordings fall back to the streaming path.
-const SOURCE_COPY_MAX_BYTES = 1.5 * 1024 * 1024 * 1024;
/**
* Waits for the encoder's queue to drain below maxEncodeQueue before returning.
@@ -248,7 +246,20 @@ export class VideoExporter {
const streamingDecoder = new StreamingVideoDecoder();
this.streamingDecoder = streamingDecoder;
- const videoInfo = await streamingDecoder.loadMetadata(this.config.videoUrl);
+ const videoInfo = await streamingDecoder.loadMetadata(
+ this.config.videoUrl,
+ ({ copiedBytes, totalBytes }) => {
+ // Large recordings are streamed into OPFS before demuxing; surface
+ // that copy as a "preparing" phase so the dialog is not stuck at 0%.
+ this.reportProgress({
+ currentFrame: 0,
+ totalFrames: 0,
+ percentage: totalBytes > 0 ? (copiedBytes / totalBytes) * 100 : 0,
+ estimatedTimeRemaining: 0,
+ phase: "preparing",
+ });
+ },
+ );
const sourceCopyResult = await this.trySourceCopyFastPath(videoInfo);
if (sourceCopyResult) {
return sourceCopyResult;
@@ -736,7 +747,11 @@ export class VideoExporter {
// out and let the (streaming) re-encode path handle them instead.
if (window.electronAPI.getReadableFileInfo) {
const info = await window.electronAPI.getReadableFileInfo(videoUrl);
- if (info.success && typeof info.size === "number" && info.size > SOURCE_COPY_MAX_BYTES) {
+ if (
+ info.success &&
+ typeof info.size === "number" &&
+ info.size > MAX_IN_MEMORY_SOURCE_BYTES
+ ) {
return null;
}
}