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: stream >2GB recordings into OPFS so long videos can export

my_macdfdcbc6274dd
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index 72e73d792..b7314ea7c 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -217,6 +217,25 @@ interface Window {
message?: string;
error?: string;
}>;
+ getReadableFileInfo: (filePath: string) => Promise<{
+ success: boolean;
+ size?: number;
+ mtimeMs?: number;
+ path?: string;
+ message?: string;
+ error?: string;
+ }>;
+ readFileChunk: (
+ filePath: string,
+ offset: number,
+ length: number,
+ ) => Promise<{
+ success: boolean;
+ data?: ArrayBuffer;
+ bytesRead?: number;
+ message?: string;
+ error?: string;
+ }>;
preparePreviewAudioTrack: (filePath: string) => Promise<{
success: boolean;
path?: string | null;
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index d8a1ee55a..8478ae00a 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -2580,6 +2580,76 @@ export function registerIpcHandlers(
}
});
+ // Stat an approved video file. Used to decide whether a recording is small
+ // enough to slurp via read-binary-file, or large enough that it must be
+ // streamed in chunks (Node's fs.readFile caps a single read at 2 GiB, so any
+ // recording above that can never be loaded whole — see read-file-chunk).
+ ipcMain.handle("get-readable-file-info", async (_, filePath: string) => {
+ try {
+ const normalizedPath = await approveReadableVideoPath(filePath);
+ if (!normalizedPath) {
+ return {
+ success: false,
+ message: "File path is not approved or is not a supported video file",
+ };
+ }
+
+ const stat = await fs.stat(normalizedPath);
+ return {
+ success: true,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ path: normalizedPath,
+ };
+ } catch (error) {
+ console.error("Failed to stat file:", error);
+ return {
+ success: false,
+ message: "Failed to stat file",
+ error: String(error),
+ };
+ }
+ });
+
+ // Read a byte range [offset, offset+length) from an approved video file.
+ // Lets the renderer stream a >2 GiB recording into OPFS one chunk at a time
+ // instead of materialising the whole file in memory, which fs.readFile cannot
+ // do (2 GiB cap) and a 16 GB machine cannot hold for multi-GB recordings.
+ ipcMain.handle("read-file-chunk", async (_, filePath: string, offset: number, length: number) => {
+ try {
+ const normalizedPath = await approveReadableVideoPath(filePath);
+ if (!normalizedPath) {
+ return {
+ success: false,
+ message: "File path is not approved or is not a supported video file",
+ };
+ }
+ if (!Number.isFinite(offset) || offset < 0 || !Number.isFinite(length) || length <= 0) {
+ return { success: false, message: "Invalid chunk range" };
+ }
+
+ const handle = await fs.open(normalizedPath, "r");
+ try {
+ const buffer = Buffer.allocUnsafe(length);
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
+ return {
+ success: true,
+ data: buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + bytesRead),
+ bytesRead,
+ };
+ } finally {
+ await handle.close();
+ }
+ } catch (error) {
+ console.error("Failed to read file chunk:", error);
+ return {
+ success: false,
+ message: "Failed to read file chunk",
+ error: String(error),
+ };
+ }
+ });
+
ipcMain.handle("prepare-preview-audio-track", async (_, filePath: string) => {
try {
return await prepareSupplementalPreviewAudioTrack(filePath);
diff --git a/electron/preload.ts b/electron/preload.ts
index e0d246bda..32e014953 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -177,6 +177,12 @@ contextBridge.exposeInMainWorld("electronAPI", {
readBinaryFile: (filePath: string) => {
return ipcRenderer.invoke("read-binary-file", filePath);
},
+ getReadableFileInfo: (filePath: string) => {
+ return ipcRenderer.invoke("get-readable-file-info", filePath);
+ },
+ readFileChunk: (filePath: string, offset: number, length: number) => {
+ return ipcRenderer.invoke("read-file-chunk", filePath, offset, length);
+ },
preparePreviewAudioTrack: (filePath: string) => {
return ipcRenderer.invoke("prepare-preview-audio-track", filePath);
},
diff --git a/src/lib/captioning/extractMono16k.ts b/src/lib/captioning/extractMono16k.ts
index bce9a9fd8..09988fac3 100644
--- a/src/lib/captioning/extractMono16k.ts
+++ b/src/lib/captioning/extractMono16k.ts
@@ -1,9 +1,14 @@
+import { materializeLocalSourceFile } from "@/lib/exporter/localSourceFile";
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();
@@ -29,13 +34,11 @@ async function fetchWithTimeout(url: string, signal?: AbortSignal): Promise<Resp
async function loadSourceVideoFile(videoUrl: string, signal?: AbortSignal): Promise<File> {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
- if (!isRemoteUrl && window.electronAPI?.readBinaryFile) {
- const result = await window.electronAPI.readBinaryFile(videoUrl);
- if (!result.success || !result.data) {
- throw new Error(result.message || result.error || "Failed to read source video");
- }
- const filename = (result.path || videoUrl).split(/[\\/]/).pop() || "video";
- return new File([result.data], filename, { type: "video/webm" });
+ 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.
+ const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
+ return materializeLocalSourceFile(videoUrl, filename);
}
const response = await fetchWithTimeout(videoUrl, signal);
@@ -149,7 +152,9 @@ export async function extractMono16kFromVideoUrl(
}
};
- const primary = await tryDecodeAudioDataPath();
+ // 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;
}
diff --git a/src/lib/exporter/localSourceFile.test.ts b/src/lib/exporter/localSourceFile.test.ts
new file mode 100644
index 000000000..3c60f1056
--- /dev/null
+++ b/src/lib/exporter/localSourceFile.test.ts
@@ -0,0 +1,86 @@
+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.
+ */
+
+function stubElectronAPI(api: Record<string, unknown>) {
+ vi.stubGlobal("window", { ...globalThis.window, electronAPI: api } as unknown);
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("materializeLocalSourceFile", () => {
+ 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({
+ getReadableFileInfo: vi.fn().mockResolvedValue({
+ success: true,
+ size: bytes.byteLength,
+ mtimeMs: 1,
+ path: "/tmp/small.mp4",
+ }),
+ readBinaryFile: vi.fn().mockResolvedValue({
+ success: true,
+ data: bytes.buffer,
+ path: "/tmp/small.mp4",
+ }),
+ });
+
+ const file = await materializeLocalSourceFile("/tmp/small.mp4", "small.mp4");
+
+ expect(file).toBeInstanceOf(File);
+ expect(file.size).toBe(bytes.byteLength);
+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(bytes);
+ });
+
+ it("does not stream a small file through readFileChunk", async () => {
+ const readFileChunk = vi.fn();
+ stubElectronAPI({
+ getReadableFileInfo: vi
+ .fn()
+ .mockResolvedValue({ success: true, size: 10, mtimeMs: 1, path: "/tmp/s.mp4" }),
+ readBinaryFile: vi
+ .fn()
+ .mockResolvedValue({ success: true, data: new Uint8Array(10).buffer, path: "/tmp/s.mp4" }),
+ readFileChunk,
+ });
+
+ await materializeLocalSourceFile("/tmp/s.mp4", "s.mp4");
+
+ expect(readFileChunk).not.toHaveBeenCalled();
+ });
+
+ it("throws when the file cannot be stat-ed", async () => {
+ stubElectronAPI({
+ getReadableFileInfo: vi
+ .fn()
+ .mockResolvedValue({ success: false, message: "File path is not approved" }),
+ readBinaryFile: vi.fn(),
+ });
+
+ await expect(materializeLocalSourceFile("/tmp/missing.mp4", "x.mp4")).rejects.toThrow(
+ /not approved/,
+ );
+ });
+
+ it("throws when the single-shot read fails", async () => {
+ stubElectronAPI({
+ getReadableFileInfo: vi
+ .fn()
+ .mockResolvedValue({ success: true, size: 10, mtimeMs: 1, path: "/tmp/s.mp4" }),
+ readBinaryFile: vi
+ .fn()
+ .mockResolvedValue({ success: false, message: "Failed to read binary file" }),
+ });
+
+ await expect(materializeLocalSourceFile("/tmp/s.mp4", "s.mp4")).rejects.toThrow(
+ /Failed to read binary file/,
+ );
+ });
+});
diff --git a/src/lib/exporter/localSourceFile.ts b/src/lib/exporter/localSourceFile.ts
new file mode 100644
index 000000000..969167364
--- /dev/null
+++ b/src/lib/exporter/localSourceFile.ts
@@ -0,0 +1,173 @@
+/**
+ * Loads a local recording as a `File` suitable for `web-demuxer`, without ever
+ * holding the whole recording in memory.
+ *
+ * The naive path — `electronAPI.readBinaryFile` → `new File([arrayBuffer])` —
+ * breaks for long recordings in two ways:
+ * 1. The main process reads with Node's `fs.readFile`, which throws
+ * `ERR_FS_FILE_TOO_LARGE` for any file above 2 GiB (a hard cap on a single
+ * read). A 2h 1080p60 recording is ~6-7 GB, so it can never be read.
+ * 2. Even if it could, a multi-GB `ArrayBuffer`/`Blob` in the renderer would
+ * exhaust memory on typical machines (e.g. 16 GB RAM).
+ *
+ * `web-demuxer` reads a `File` on demand (it slices the file inside its worker),
+ * so it does not need the bytes up front. For recordings above a safe threshold
+ * 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.
+ *
+ * Small recordings keep the original in-memory path — it is simpler and avoids
+ * 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;
+
+const OPFS_CACHE_DIR = "openscreen-source-cache";
+
+export interface MaterializeProgress {
+ copiedBytes: number;
+ totalBytes: number;
+}
+
+/** Stable non-cryptographic hash for building a cache key from a path. */
+function hashString(input: string): string {
+ let hash = 5381;
+ for (let i = 0; i < input.length; i++) {
+ hash = ((hash << 5) + hash + input.charCodeAt(i)) | 0;
+ }
+ return (hash >>> 0).toString(36);
+}
+
+/**
+ * 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 onProgress Optional progress callback for the large-file copy.
+ */
+export async function materializeLocalSourceFile(
+ videoUrl: string,
+ filename: string,
+ onProgress?: (progress: MaterializeProgress) => void,
+): Promise<File> {
+ const api = window.electronAPI;
+ if (!api) {
+ throw new Error("Local source loading is only available in the desktop app.");
+ }
+
+ 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) {
+ const result = await api.readBinaryFile(videoUrl);
+ if (!result.success || !result.data) {
+ throw new Error(result.message || result.error || "Failed to read source video");
+ }
+ const name = (result.path || filename).split(/[\\/]/).pop() || filename;
+ return new File([result.data], name, { type: "video/mp4" });
+ }
+
+ // 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);
+}
+
+async function copyToOpfsFile(
+ videoUrl: string,
+ size: number,
+ mtimeMs: number,
+ onProgress?: (progress: MaterializeProgress) => void,
+): Promise<File> {
+ const getDirectory = navigator.storage?.getDirectory?.bind(navigator.storage);
+ if (!getDirectory) {
+ throw new Error(
+ "This recording is larger than 2 GB and cannot be exported: " +
+ "local storage (OPFS) is unavailable to stream it.",
+ );
+ }
+
+ const root = await getDirectory();
+ const dir = await root.getDirectoryHandle(OPFS_CACHE_DIR, { create: true });
+
+ // 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`;
+
+ await pruneStaleEntries(dir, cacheName);
+
+ 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 });
+ return existing;
+ }
+
+ const writable = await handle.createWritable();
+ try {
+ let offset = 0;
+ while (offset < size) {
+ const length = Math.min(COPY_CHUNK_BYTES, 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.close();
+ } catch (error) {
+ try {
+ await writable.abort();
+ } catch {
+ // ignore abort failure; surface the original error
+ }
+ // Drop the partial copy so a retry does not resume from a corrupt file.
+ try {
+ await dir.removeEntry(cacheName);
+ } catch {
+ // ignore cleanup failure
+ }
+ throw error;
+ }
+
+ const file = await handle.getFile();
+ if (file.size !== size) {
+ throw new Error(
+ `Streamed copy is incomplete (${file.size} of ${size} bytes); the source video may still be in use.`,
+ );
+ }
+ return file;
+}
+
+/** Removes any cached copies in the directory other than the current key. */
+async function pruneStaleEntries(dir: FileSystemDirectoryHandle, keepName: string): Promise<void> {
+ // FileSystemDirectoryHandle async iteration is available in Chromium/Electron.
+ const entries = (
+ dir as unknown as {
+ keys?: () => AsyncIterableIterator<string>;
+ }
+ ).keys?.();
+ if (!entries) return;
+ const toRemove: string[] = [];
+ for await (const name of entries) {
+ if (name !== keepName) toRemove.push(name);
+ }
+ await Promise.all(toRemove.map((name) => dir.removeEntry(name).catch(() => undefined)));
+}
diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.ts
index 472da8195..3d526dd14 100644
--- a/src/lib/exporter/streamingDecoder.ts
+++ b/src/lib/exporter/streamingDecoder.ts
@@ -1,7 +1,12 @@
import { WebDemuxer } from "web-demuxer";
import type { SpeedRegion, TrimRegion } from "@/components/video-editor/types";
+import { materializeLocalSourceFile } from "./localSourceFile";
const SOURCE_LOAD_TIMEOUT_MS = 60_000;
+// Large local recordings are streamed into OPFS before demuxing, which is
+// bounded by disk/IPC throughput rather than a network round-trip. Allow far
+// more time than a remote fetch so a multi-GB copy is not cut off mid-way.
+const LOCAL_SOURCE_LOAD_TIMEOUT_MS = 15 * 60_000;
const EPSILON_SEC = 0.001;
/**
* Build a full WebCodecs-compatible AV1 codec string from the AV1CodecConfigurationRecord.
@@ -141,12 +146,20 @@ export async function loadFileAsArrayBuffer(
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI) {
- const { blob } = await StreamingVideoDecoder.loadLocalSourceFile(videoUrl);
- return { data: await blob.arrayBuffer(), contentType: "" };
+ // This path loads the entire file into an ArrayBuffer (it feeds the trim
+ // waveform), so it deliberately uses the single-shot read rather than the
+ // OPFS streaming loader. Recordings above ~2 GiB fail here and the caller
+ // (useAudioPeaks) degrades to no waveform — the export path does not rely
+ // on this function.
+ const result = await window.electronAPI.readBinaryFile(videoUrl);
+ if (!result.success || !result.data) {
+ throw new Error(result.message || result.error || "Failed to read source video");
+ }
+ return { data: result.data, contentType: "" };
}
- const { blob } = await StreamingVideoDecoder.loadRemoteSourceFile(videoUrl);
- return { data: await blob.arrayBuffer(), contentType: blob.type };
+ const file = await StreamingVideoDecoder.loadRemoteSourceFile(videoUrl);
+ return { data: await file.arrayBuffer(), contentType: file.type };
}
/** Caller must close the VideoFrame after use. */
@@ -170,12 +183,12 @@ export class StreamingVideoDecoder {
private metadata: DecodedVideoInfo | null = null;
/** Routes to the appropriate loader based on whether the source is local or remote. */
- private async loadSourceFile(videoUrl: string): Promise<{ file: File; blob: Blob }> {
+ private async loadSourceFile(videoUrl: string): Promise<File> {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI) {
return this.withTimeout(
StreamingVideoDecoder.loadLocalSourceFile(videoUrl),
- SOURCE_LOAD_TIMEOUT_MS,
+ LOCAL_SOURCE_LOAD_TIMEOUT_MS,
"Timed out while loading the source video.",
);
}
@@ -186,39 +199,29 @@ export class StreamingVideoDecoder {
);
}
- /** Loads a local video file via the Electron IPC bridge. */
- static async loadLocalSourceFile(videoUrl: string): Promise<{ file: File; blob: Blob }> {
- const result = await window.electronAPI.readBinaryFile(videoUrl);
- if (!result.success || !result.data) {
- throw new Error(result.message || result.error || "Failed to read source video");
- }
-
- const filename = (result.path || videoUrl).split(/[\\/]/).pop() || "video";
- const blob = new Blob([result.data]);
- return {
- blob,
- file: new File([blob], filename, {
- type: blob.type || "application/octet-stream",
- }),
- };
+ /**
+ * Loads a local video file for demuxing. Large recordings are streamed into
+ * 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> {
+ const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
+ return materializeLocalSourceFile(videoUrl, filename);
}
/** Loads a remote or blob video URL via fetch. */
- static async loadRemoteSourceFile(videoUrl: string): Promise<{ file: File; blob: Blob }> {
+ static async loadRemoteSourceFile(videoUrl: string): Promise<File> {
const response = await fetch(videoUrl);
if (!response.ok) {
throw new Error(`Failed to fetch source video: ${response.status} ${response.statusText}`);
}
const blob = await response.blob();
const filename = videoUrl.split("/").pop() || "video";
- return {
- blob,
- file: new File([blob], filename, { type: blob.type }),
- };
+ return new File([blob], filename, { type: blob.type });
}
async loadMetadata(videoUrl: string): Promise<DecodedVideoInfo> {
- const { file } = await this.loadSourceFile(videoUrl);
+ const file = await this.loadSourceFile(videoUrl);
// 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;
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 8f239656c..d2208982a 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -19,6 +19,9 @@ 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.
@@ -728,6 +731,16 @@ export class VideoExporter {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI?.readBinaryFile) {
+ // The source-copy fast path reads the whole file into a Blob. That is
+ // impossible for recordings above Node's 2 GiB single-read cap, so bail
+ // 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) {
+ return null;
+ }
+ }
+
const result = await window.electronAPI.readBinaryFile(videoUrl);
if (!result.success || !result.data) {
return null;