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: address review — prune race, chunk cap, MIME, streaming waveform

my_maca977187b3375
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 8478ae00a..ae8f5525d 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -2611,6 +2611,10 @@ export function registerIpcHandlers(
}
});
+ // Cap renderer-requested chunk sizes so a buggy or compromised renderer
+ // cannot make the main process allocate an arbitrarily large buffer.
+ const MAX_IPC_CHUNK_BYTES = 64 * 1024 * 1024;
+
// 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
@@ -2627,6 +2631,9 @@ export function registerIpcHandlers(
if (!Number.isFinite(offset) || offset < 0 || !Number.isFinite(length) || length <= 0) {
return { success: false, message: "Invalid chunk range" };
}
+ if (length > MAX_IPC_CHUNK_BYTES) {
+ return { success: false, message: "Requested chunk size exceeds limit" };
+ }
const handle = await fs.open(normalizedPath, "r");
try {
diff --git a/src/hooks/streamingAudioPeaks.ts b/src/hooks/streamingAudioPeaks.ts
new file mode 100644
index 000000000..a0560089b
--- /dev/null
+++ b/src/hooks/streamingAudioPeaks.ts
@@ -0,0 +1,151 @@
+import { WebDemuxer } from "web-demuxer";
+import { audioDataFrameToMono } from "@/lib/captioning/extractMono16kWebDemuxer";
+
+/**
+ * Streaming trim-waveform peaks for recordings too large to load into memory.
+ *
+ * The default waveform path reads the whole file and runs `decodeAudioData`,
+ * which needs the full bytes up front — impossible for multi-GB recordings.
+ * This module demuxes the audio track with web-demuxer (which reads the File
+ * on demand), decodes it chunk by chunk with WebCodecs `AudioDecoder`, and
+ * folds every decoded frame straight into min/max peak buckets, closing the
+ * frame immediately. Peak memory is the buckets array (≤ 24k blocks ≈ 192 kB)
+ * plus a handful of in-flight frames, regardless of recording length.
+ *
+ * Output matches `audioPeaksWorker.ts` exactly: Float32Array of length 2*N,
+ * `[min0, max0, min1, max1, ...]`, N = min(24000, ceil(duration * 200)), with
+ * min/max starting from 0 (silence baseline) and channels averaged per sample.
+ */
+
+const DECODE_QUEUE_BACKPRESSURE = 20;
+const LOAD_TIMEOUT_MS = 60_000;
+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;
+
+function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const id = window.setTimeout(() => reject(new Error(message)), ms);
+ promise
+ .then((v) => {
+ window.clearTimeout(id);
+ resolve(v);
+ })
+ .catch((e) => {
+ window.clearTimeout(id);
+ reject(e instanceof Error ? e : new Error(String(e)));
+ });
+ });
+}
+
+/**
+ * Computes trim-waveform peaks from a (typically OPFS-backed) File without ever
+ * holding the decoded PCM in memory. Throws on no/unsupported audio track; the
+ * caller (useAudioPeaks) degrades to no waveform.
+ */
+export async function computePeaksFromFileStreaming(
+ file: File,
+ signal?: AbortSignal,
+): Promise<Float32Array> {
+ const wasmUrl = new URL("./wasm/web-demuxer.wasm", window.location.href).href;
+ const demuxer = new WebDemuxer({ wasmFilePath: wasmUrl });
+ try {
+ await withTimeout(
+ demuxer.load(file),
+ LOAD_TIMEOUT_MS,
+ "Timed out while parsing the source video for the waveform.",
+ );
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
+
+ const mediaInfo = await withTimeout(
+ demuxer.getMediaInfo(),
+ 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 {
+ audioConfig = await demuxer.getDecoderConfig("audio");
+ } catch {
+ throw new Error("No audio track found in this video.");
+ }
+ const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);
+ if (!codecCheck.supported) {
+ throw new Error(`Audio codec not supported for waveform: ${audioConfig.codec}`);
+ }
+ const sampleRate = audioConfig.sampleRate || 48_000;
+
+ 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, ...]
+
+ const foldFrame = (frame: AudioData) => {
+ const startSample = Math.round((frame.timestamp / 1e6) * sampleRate);
+ const mono = audioDataFrameToMono(frame);
+ frame.close();
+ for (let i = 0; i < mono.length; i++) {
+ const pos = startSample + i;
+ if (pos < 0 || pos >= totalSamples) continue;
+ let block = Math.floor((pos / totalSamples) * blocks);
+ if (block >= blocks) block = blocks - 1;
+ const sample = mono[i];
+ if (sample < peaks[block * 2]) peaks[block * 2] = sample;
+ if (sample > peaks[block * 2 + 1]) peaks[block * 2 + 1] = sample;
+ }
+ };
+
+ let decodedFrames = 0;
+ let decodeError: DOMException | null = null;
+ const decoder = new AudioDecoder({
+ output: (data: AudioData) => {
+ decodedFrames++;
+ foldFrame(data);
+ },
+ error: (e: DOMException) => {
+ decodeError = e;
+ },
+ });
+ 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));
+ }
+ }
+ } finally {
+ try {
+ await reader.cancel();
+ } 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) {
+ throw new Error("Decoded zero audio frames from this video.");
+ }
+ return peaks;
+ } finally {
+ try {
+ demuxer.destroy();
+ } catch {
+ /* already destroyed */
+ }
+ }
+}
diff --git a/src/hooks/useAudioPeaks.ts b/src/hooks/useAudioPeaks.ts
index 337f50344..d6eb687a5 100644
--- a/src/hooks/useAudioPeaks.ts
+++ b/src/hooks/useAudioPeaks.ts
@@ -1,5 +1,8 @@
import { useEffect, useRef, useState } from "react";
+import { materializeLocalSourceFile, releaseLocalSourceFile } from "@/lib/exporter/localSourceFile";
+import { MAX_IN_MEMORY_SOURCE_BYTES } from "@/lib/exporter/sourceFileLimits";
import { loadFileAsArrayBuffer } from "@/lib/exporter/streamingDecoder";
+import { computePeaksFromFileStreaming } from "./streamingAudioPeaks";
let _audioCtx: AudioContext | null = null;
/** Returns the shared AudioContext, creating it lazily on first call. */
@@ -58,6 +61,33 @@ function computePeaksInWorker(
});
}
+/**
+ * Routes to the right peaks pipeline for the source size. Small/remote files
+ * use the original decodeAudioData → worker path. Local recordings above the
+ * in-memory limit stream instead: the file is materialized into OPFS (reused by
+ * the export afterwards) and its audio is decoded chunk-by-chunk into peaks, so
+ * the whole recording is never held in memory.
+ */
+async function computePeaksForUrl(videoUrl: string, signal?: AbortSignal): Promise<Float32Array> {
+ const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
+ if (!isRemoteUrl && window.electronAPI?.getReadableFileInfo) {
+ 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);
+ try {
+ return await computePeaksFromFileStreaming(file, signal);
+ } finally {
+ releaseLocalSourceFile(file.name);
+ }
+ }
+ }
+
+ const { data: arrayBuffer } = await loadFileAsArrayBuffer(videoUrl);
+ const audioBuffer = await getAudioCtx().decodeAudioData(arrayBuffer);
+ return computePeaksInWorker(audioBuffer, signal);
+}
+
/**
* Decodes audio from `videoUrl` into paired [min, max] peaks (length = 2 * N
* blocks). Returns `null` while decoding, and stays `null` on no audio track or
@@ -88,11 +118,7 @@ export function useAudioPeaks(videoUrl?: string): Float32Array | null {
(async () => {
try {
- const { data: arrayBuffer } = await loadFileAsArrayBuffer(videoUrl);
- if (cancelled) return;
- const audioBuffer = await getAudioCtx().decodeAudioData(arrayBuffer);
- if (cancelled) return;
- const p = await computePeaksInWorker(audioBuffer, controller.signal);
+ const p = await computePeaksForUrl(videoUrl, controller.signal);
if (cancelled) return;
cacheRef.current.set(videoUrl, p);
setPeaks(p);
diff --git a/src/lib/captioning/extractMono16kWebDemuxer.ts b/src/lib/captioning/extractMono16kWebDemuxer.ts
index f86b6dc57..3a00aa0bf 100644
--- a/src/lib/captioning/extractMono16kWebDemuxer.ts
+++ b/src/lib/captioning/extractMono16kWebDemuxer.ts
@@ -10,7 +10,8 @@ function webDemuxerWasmUrl(): string {
return new URL("../exporter/wasm/web-demuxer.wasm", window.location.href).href;
}
-function audioDataFrameToMono(frame: AudioData): Float32Array {
+/** Mixes one WebCodecs AudioData frame down to mono (averaged across channels). */
+export function audioDataFrameToMono(frame: AudioData): Float32Array {
const frames = frame.numberOfFrames;
const ch = frame.numberOfChannels;
const out = new Float32Array(frames);
diff --git a/src/lib/exporter/localSourceFile.test.ts b/src/lib/exporter/localSourceFile.test.ts
index 16b7c0007..705bd11d3 100644
--- a/src/lib/exporter/localSourceFile.test.ts
+++ b/src/lib/exporter/localSourceFile.test.ts
@@ -268,4 +268,78 @@ describe("materializeLocalSourceFile (large file OPFS path)", () => {
// The partial copy is cleaned up and holds no live reference.
expect(cacheDir(root)?.files.size ?? 0).toBe(0);
});
+
+ it("does not prune an entry that is still being written by a concurrent copy", async () => {
+ const root = new FakeDir();
+ stubOpfs(root);
+
+ const sourceA = new Uint8Array([1, 2, 3, 4, 5, 6]);
+ const sourceB = new Uint8Array([7, 8, 9, 10, 11]);
+ let releaseFirstChunk!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ releaseFirstChunk = resolve;
+ });
+ const sources: Record<string, Uint8Array> = {
+ "/rec/a.mp4": sourceA,
+ "/rec/b.mp4": sourceB,
+ };
+ // One shared API serving both URLs; A's first chunk read blocks on the gate
+ // so A sits mid-copy while B runs to completion (including B's prune pass).
+ const api = {
+ getReadableFileInfo: vi.fn(async (url: string) => ({
+ success: true,
+ size: sources[url].byteLength,
+ mtimeMs: 1,
+ path: url,
+ })),
+ readBinaryFile: vi.fn(),
+ readFileChunk: vi.fn(async (url: string, offset: number, length: number) => {
+ if (url === "/rec/a.mp4" && offset === 0) await gate;
+ const bytes = sources[url];
+ return {
+ success: true,
+ data: bytes.slice(offset, offset + length).buffer,
+ bytesRead: Math.min(length, bytes.byteLength - offset),
+ };
+ }),
+ };
+ stubElectronAPI(api);
+
+ const aPromise = materializeLocalSourceFile("/rec/a.mp4", "a.mp4", OPTS);
+ // Wait until A is inside its gated first chunk read (past retain + prune).
+ while (!api.readFileChunk.mock.calls.some(([url]) => url === "/rec/a.mp4")) {
+ await new Promise((r) => setTimeout(r, 0));
+ }
+
+ const b = await materializeLocalSourceFile("/rec/b.mp4", "b.mp4", OPTS);
+ // B's prune must have kept A's in-progress entry alive.
+ expect(cacheDir(root)?.files.size).toBe(2);
+
+ releaseFirstChunk();
+ const a = await aPromise;
+ expect(new Uint8Array(await a.arrayBuffer())).toEqual(sourceA);
+
+ releaseLocalSourceFile(a.name);
+ releaseLocalSourceFile(b.name);
+ });
+});
+
+describe("materializeLocalSourceFile (MIME inference)", () => {
+ it.each([
+ ["/tmp/clip.webm", "video/webm"],
+ ["/tmp/clip.mp4", "video/mp4"],
+ ["/tmp/clip.mov", "video/quicktime"],
+ ["/tmp/clip.bin", "application/octet-stream"],
+ ])("infers the MIME type of %s as %s", async (path, expected) => {
+ stubElectronAPI({
+ getReadableFileInfo: vi.fn().mockResolvedValue({ success: true, size: 4, mtimeMs: 1, path }),
+ readBinaryFile: vi
+ .fn()
+ .mockResolvedValue({ success: true, data: new Uint8Array(4).buffer, path }),
+ });
+
+ const file = await materializeLocalSourceFile(path, "clip");
+
+ expect(file.type).toBe(expected);
+ });
});
diff --git a/src/lib/exporter/localSourceFile.ts b/src/lib/exporter/localSourceFile.ts
index f247d45d5..62b1b6237 100644
--- a/src/lib/exporter/localSourceFile.ts
+++ b/src/lib/exporter/localSourceFile.ts
@@ -70,6 +70,23 @@ function activeCacheNames(): Set<string> {
return new Set(activeCacheRefs.keys());
}
+const MIME_BY_EXTENSION: Record<string, string> = {
+ mp4: "video/mp4",
+ m4v: "video/mp4",
+ mov: "video/quicktime",
+ webm: "video/webm",
+ mkv: "video/x-matroska",
+ avi: "video/x-msvideo",
+};
+
+/** Infers a video MIME type from the file extension (recordings can be mp4 or webm). */
+function mimeTypeForPath(p: string): string {
+ const clean = p.toLowerCase().split(/[?#]/, 1)[0];
+ const dot = clean.lastIndexOf(".");
+ const ext = dot >= 0 ? clean.slice(dot + 1) : "";
+ return MIME_BY_EXTENSION[ext] ?? "application/octet-stream";
+}
+
/** Stable non-cryptographic hash for building a cache key from a path. */
function hashString(input: string): string {
let hash = 5381;
@@ -111,7 +128,7 @@ export async function materializeLocalSourceFile(
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" });
+ return new File([result.data], name, { type: mimeTypeForPath(name) });
}
// Large recording: stream into OPFS and hand back a disk-backed File.
@@ -141,63 +158,72 @@ async function copyToOpfsFile(
// the same recording reuse the cached copy instead of re-streaming gigabytes.
const cacheName = `${hashString(videoUrl)}-${size}-${Math.round(mtimeMs)}.bin`;
- // 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);
+ // 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);
+ try {
+ await pruneStaleEntries(dir, activeCacheNames());
- const handle = await dir.getFileHandle(cacheName, { create: true });
+ 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 });
- retainCache(cacheName);
- return existing;
- }
+ // Reuse a complete prior copy.
+ const existing = await handle.getFile();
+ if (existing.size === size) {
+ options?.onProgress?.({ copiedBytes: size, totalBytes: size });
+ 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(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");
+ const chunkBytes = options?.chunkBytes ?? COPY_CHUNK_BYTES;
+ const writable = await handle.createWritable();
+ try {
+ let offset = 0;
+ while (offset < size) {
+ 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");
+ }
+ // 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 });
}
- // 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
}
- await writable.write(chunk.data);
- offset += chunk.data.byteLength;
- options?.onProgress?.({ copiedBytes: offset, totalBytes: size });
+ throw error;
}
- await writable.close();
- } catch (error) {
- try {
- await writable.abort();
- } catch {
- // ignore abort failure; surface the original 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.`,
+ );
}
- // Drop the partial copy so a retry does not resume from a corrupt file.
- try {
- await dir.removeEntry(cacheName);
- } catch {
- // ignore cleanup failure
+ 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);
+ if (!activeCacheRefs.has(cacheName)) {
+ 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.`,
- );
- }
- retainCache(cacheName);
- return file;
}
/** Removes cached copies in the directory whose names are not in `keep`. */
diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.ts
index f4cd6819a..79af8bf99 100644
--- a/src/lib/exporter/streamingDecoder.ts
+++ b/src/lib/exporter/streamingDecoder.ts
@@ -151,13 +151,12 @@ export async function loadFileAsArrayBuffer(
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
if (!isRemoteUrl && window.electronAPI) {
- // This path loads the entire file into an ArrayBuffer (it feeds the trim
- // waveform) and cannot stream, since decodeAudioData needs the whole file.
- // readBinaryFile also copies the bytes in the main process during IPC, so a
- // large recording would exhaust memory and crash. The waveform is cosmetic,
- // so skip it above the in-memory limit; useAudioPeaks (the only caller)
- // catches the throw and degrades to no waveform. The export path streams
- // instead and does not rely on this function.
+ // This path loads the entire file into an ArrayBuffer for decodeAudioData,
+ // and readBinaryFile also copies the bytes in the main process during IPC,
+ // so a large recording would exhaust memory and crash. Callers must route
+ // oversized files elsewhere (useAudioPeaks streams peaks via
+ // computePeaksFromFileStreaming); this guard is a safety net for any
+ // caller that does not.
const info = await window.electronAPI.getReadableFileInfo?.(videoUrl);
if (info?.success && typeof info.size === "number" && info.size > MAX_IN_MEMORY_SOURCE_BYTES) {
throw new Error("Recording is too large to load into memory for waveform rendering.");