Skip to content

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

perf(waveform): share the decode; stop holding 714 MB to draw 400 bars

Etienne Lescotd0c7b3db6e02
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 705bad5ad..195028588 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -257,7 +257,9 @@ const ClipWaveform = memo(function ClipWaveform({
sourceStartSec: number;
sourceEndSec: number;
}) {
- const peaks = useAudioPeaks(videoUrl);
+ // The duration is what tells `useAudioPeaks` whether this recording is small
+ // enough to decode whole — the file's byte size does not, on compressed video.
+ const peaks = useAudioPeaks(videoUrl, assetDurationSec);
const bars = useMemo(() => {
if (!peaks || peaks.length === 0 || !assetDurationSec) return null;
const totalBlocks = Math.floor(peaks.length / 2);
diff --git a/src/hooks/useAudioPeaks.test.ts b/src/hooks/useAudioPeaks.test.ts
new file mode 100644
index 000000000..77a850b78
--- /dev/null
+++ b/src/hooks/useAudioPeaks.test.ts
@@ -0,0 +1,87 @@
+// Two properties that decide whether a long recording's waveform appears
+// quickly or not at all: which pipeline a file is routed to, and how many times
+// it is decoded.
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useAudioPeaks } from "./useAudioPeaks";
+
+const streamingCalls = vi.fn();
+const inMemoryCalls = vi.fn();
+
+vi.mock("./streamingAudioPeaks", () => ({
+ computePeaksFromFileStreaming: async () => {
+ streamingCalls();
+ return new Float32Array([0, 1]);
+ },
+}));
+
+vi.mock("@/lib/exporter/localSourceFile", () => ({
+ materializeLocalSourceFile: async (_url: string, name: string) => ({ name }),
+ releaseLocalSourceFile: () => {},
+}));
+
+vi.mock("@/lib/exporter/streamingDecoder", () => ({
+ loadFileAsArrayBuffer: async () => {
+ inMemoryCalls();
+ return { data: new ArrayBuffer(8) };
+ },
+}));
+
+// A 68 MB file — comfortably under the 256 MB in-memory threshold, which is
+// exactly why routing on file size sent a 32-minute recording down the
+// decode-everything path.
+const FILE_BYTES = 68 * 1024 * 1024;
+const THIRTY_TWO_MINUTES = 1951;
+
+beforeEach(() => {
+ streamingCalls.mockClear();
+ inMemoryCalls.mockClear();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ getReadableFileInfo: async () => ({ success: true, size: FILE_BYTES }),
+ };
+});
+
+afterEach(cleanup);
+
+describe("useAudioPeaks", () => {
+ it("streams a long recording instead of decoding it whole", async () => {
+ const { result } = renderHook(() => useAudioPeaks("/tmp/long-a.mp4", THIRTY_TWO_MINUTES));
+ await waitFor(() => expect(result.current).not.toBeNull());
+ expect(streamingCalls).toHaveBeenCalledOnce();
+ // The whole point: 68 MB on disk is 656 MB decoded, so this must NOT be
+ // the path that reads the file and hands it to decodeAudioData.
+ expect(inMemoryCalls).not.toHaveBeenCalled();
+ });
+
+ it("keeps decoding short clips in memory", async () => {
+ // Only the ROUTE is asserted: the in-memory path then needs a real
+ // AudioContext and a Worker, neither of which jsdom has.
+ renderHook(() => useAudioPeaks("/tmp/short-a.mp4", 20));
+ await waitFor(() => expect(inMemoryCalls).toHaveBeenCalled());
+ expect(streamingCalls).not.toHaveBeenCalled();
+ });
+
+ it("decodes a file once, however many clips mount it and however often", async () => {
+ const url = "/tmp/long-b.mp4";
+ // Three clips of the same asset, mounted together.
+ const a = renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+ const b = renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+ const c = renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+ await waitFor(() => expect(a.result.current).not.toBeNull());
+ await waitFor(() => expect(b.result.current).not.toBeNull());
+ await waitFor(() => expect(c.result.current).not.toBeNull());
+ expect(streamingCalls).toHaveBeenCalledOnce();
+
+ // Unmount everything — this is a Media↔Edit tab switch — and come back.
+ // With the cache scoped to a component ref, this re-decoded the whole
+ // recording every single time.
+ act(() => {
+ a.unmount();
+ b.unmount();
+ c.unmount();
+ });
+ const again = renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+ await waitFor(() => expect(again.result.current).not.toBeNull());
+ expect(streamingCalls).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/hooks/useAudioPeaks.ts b/src/hooks/useAudioPeaks.ts
index daa0abf09..ed57671ca 100644
--- a/src/hooks/useAudioPeaks.ts
+++ b/src/hooks/useAudioPeaks.ts
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, 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";
@@ -62,17 +62,43 @@ 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.
+ * Bytes one second of decoded audio occupies in an `AudioBuffer`: Float32,
+ * stereo, 44.1 kHz. An estimate on purpose — it picks the pipeline, before
+ * anything has been decoded and while the real rate is still unknown.
*/
-async function computePeaksForUrl(videoUrl: string, signal?: AbortSignal): Promise<Float32Array> {
+const DECODED_BYTES_PER_SEC = 44_100 * 2 * 4;
+
+/**
+ * Routes to the right peaks pipeline. Small/remote files use the original
+ * decodeAudioData → worker path. Recordings too big to hold decoded 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.
+ *
+ * "Too big" is measured on the DECODED size, estimated from duration — not on
+ * the file's bytes, which is close to meaningless here and is what this used to
+ * compare. Compression ratio is the entire point of a screen recording: a
+ * 32-minute capture is 68 MB on disk and 656 MB decoded, and the in-memory path
+ * then `slice()`s every channel again for the worker transfer. That is ~1.4 GB
+ * of transient allocation to draw 400 bars, and it sat comfortably under a
+ * 256 MB *file* threshold — so the streaming path built for exactly this case
+ * never ran. (`ffmpeg -vn -f null` decodes the same track in 2.1s: that is the
+ * floor all that allocation was being piled onto.)
+ */
+async function computePeaksForUrl(
+ videoUrl: string,
+ signal?: AbortSignal,
+ durationSec?: number,
+): 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 decodedBytes = (durationSec ?? 0) * DECODED_BYTES_PER_SEC;
+ if (
+ info.success &&
+ ((typeof info.size === "number" && info.size > MAX_IN_MEMORY_SOURCE_BYTES) ||
+ decodedBytes > MAX_IN_MEMORY_SOURCE_BYTES)
+ ) {
const filename = (videoUrl.split(/[\\/]/).pop() || "video").replace(/^file:/, "");
// signal also aborts the OPFS copy (unless the export shares it).
const file = await materializeLocalSourceFile(videoUrl, filename, { signal });
@@ -89,16 +115,49 @@ async function computePeaksForUrl(videoUrl: string, signal?: AbortSignal): Promi
return computePeaksInWorker(audioBuffer, signal);
}
+/**
+ * Peaks describe a FILE, so they are cached per file, at module scope.
+ *
+ * This used to be a `useRef` Map, i.e. one cache per mounted component. Peaks
+ * for a 32-minute recording cost seconds and (before the routing fix above) a
+ * gigabyte-plus of transient allocation, and that was paid again for every clip
+ * of the same asset, and again from scratch on every remount — switching
+ * Media↔Edit re-decoded the whole recording, which is what "the waveform takes
+ * ages to appear" actually was.
+ *
+ * `inFlight` is the other half: N clips of one asset mounting together must
+ * share a single decode instead of racing N of them.
+ */
+const peaksCache = new Map<string, Float32Array>();
+const peaksInFlight = new Map<string, Promise<Float32Array>>();
+
+function loadPeaks(videoUrl: string, durationSec?: number): Promise<Float32Array> {
+ const existing = peaksInFlight.get(videoUrl);
+ if (existing) return existing;
+ // Deliberately NOT wired to any component's AbortSignal: the work is shared,
+ // so one subscriber unmounting must not cancel it for the others. An unmount
+ // drops the result instead — and the cache means the next mount is free.
+ const promise = computePeaksForUrl(videoUrl, undefined, durationSec)
+ .then((p) => {
+ peaksCache.set(videoUrl, p);
+ return p;
+ })
+ .finally(() => {
+ peaksInFlight.delete(videoUrl);
+ });
+ peaksInFlight.set(videoUrl, promise);
+ return promise;
+}
+
/**
* 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
- * decode failure (silent degradation). Results are cached in a ref scoped to the
- * hook instance, so they survive re-renders and waveform toggles but not unmount.
+ * decode failure (silent degradation). `durationSec` only picks the pipeline
+ * (see `computePeaksForUrl`); omitting it is safe, just slower on long files.
*/
-export function useAudioPeaks(videoUrl?: string): Float32Array | null {
- const cacheRef = useRef<Map<string, Float32Array>>(new Map());
+export function useAudioPeaks(videoUrl?: string, durationSec?: number): Float32Array | null {
const [peaks, setPeaks] = useState<Float32Array | null>(() =>
- videoUrl ? (cacheRef.current.get(videoUrl) ?? null) : null,
+ videoUrl ? (peaksCache.get(videoUrl) ?? null) : null,
);
useEffect(() => {
@@ -107,7 +166,7 @@ export function useAudioPeaks(videoUrl?: string): Float32Array | null {
return;
}
- const cached = cacheRef.current.get(videoUrl);
+ const cached = peaksCache.get(videoUrl);
if (cached) {
setPeaks(cached);
return;
@@ -115,27 +174,21 @@ export function useAudioPeaks(videoUrl?: string): Float32Array | null {
setPeaks(null);
let cancelled = false;
- const controller = new AbortController();
- (async () => {
- try {
- const p = await computePeaksForUrl(videoUrl, controller.signal);
- if (cancelled) return;
- cacheRef.current.set(videoUrl, p);
- setPeaks(p);
- } catch (err) {
- // AbortError means the effect cleaned up, so no state update needed.
+ loadPeaks(videoUrl, durationSec)
+ .then((p) => {
+ if (!cancelled) setPeaks(p);
+ })
+ .catch((err: unknown) => {
if (err instanceof DOMException && err.name === "AbortError") return;
// No audio track or unsupported format: degrade to no waveform, but log
// so an unexpectedly-missing waveform is diagnosable.
console.warn("useAudioPeaks: could not decode audio for waveform:", err);
if (!cancelled) setPeaks(null);
- }
- })();
+ });
return () => {
cancelled = true;
- controller.abort();
};
}, [videoUrl]);