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): decode peaks natively, once per recording ever

Etienne Lescot33e9641bb142
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index f537dbbe8..8c4920fd3 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -295,6 +295,10 @@ interface Window {
message?: string;
error?: string;
}>;
+ getAudioPeaks: (
+ filePath: string,
+ durationSec: number,
+ ) => Promise<import("./media/audioPeaks").AudioPeaksResult>;
readFileChunk: (
filePath: string,
offset: number,
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 4baa9ee8f..0000ec0e7 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -55,6 +55,7 @@ import { LlmConfigStore } from "../ai-edition/llm-config-store";
import { mainLogBuffer } from "../diagnostics/main-log-buffer";
import { mainT } from "../i18n";
import { RECORDINGS_DIR } from "../main";
+import { type AudioPeaksResult, getAudioPeaks } from "../media/audioPeaks";
import {
readCursorRecordingFile as readCursorRecordingFileFrom,
readCursorSidecar,
@@ -3120,6 +3121,31 @@ export function registerIpcHandlers(
}
});
+ // Waveform peaks for a timeline clip, decoded natively (see media/audioPeaks).
+ // The renderer's own pipelines take ~12s on a 32-minute recording because they
+ // decode the whole track in Chromium; ffmpeg does the same work in ~2s off the
+ // UI process, and the result is cached on disk so it is paid once per file.
+ // `peaks: null` means "no native path available" — the caller falls back to
+ // its own decoding rather than losing the waveform.
+ ipcMain.handle(
+ "get-audio-peaks",
+ async (_, filePath: string, durationSec: number): Promise<AudioPeaksResult> => {
+ try {
+ // Same approval gate as every other read of a renderer-supplied path.
+ const normalizedPath = await approveReadableVideoPath(filePath);
+ if (!normalizedPath) {
+ return { success: false, message: "File path is not approved" };
+ }
+ const peaks = await getAudioPeaks(normalizedPath, durationSec);
+ return { success: true, peaks };
+ } catch (error) {
+ // A clip with no audio track lands here. Degrade quietly: the renderer
+ // draws no waveform, which is correct, and logs its own warning.
+ return { success: false, message: String(error) };
+ }
+ },
+ );
+
// 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;
diff --git a/electron/media/__fixtures__/peaks-sample.m4a b/electron/media/__fixtures__/peaks-sample.m4a
new file mode 100644
index 000000000..431172aa9
Binary files /dev/null and b/electron/media/__fixtures__/peaks-sample.m4a differ
diff --git a/electron/media/audioPeaks.test.ts b/electron/media/audioPeaks.test.ts
new file mode 100644
index 000000000..fb20b2677
--- /dev/null
+++ b/electron/media/audioPeaks.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { existsSync } from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { ffmpegCandidates, peakBlockCount, resolveFfmpeg } from "./audioPeaks";
+
+const ROOT = path.resolve(__dirname, "..", "..");
+
+describe("peakBlockCount", () => {
+ it("matches the browser pipelines' block maths", () => {
+ // Same formula as audioPeaksWorker.ts / streamingAudioPeaks.ts: a clip must
+ // not change shape depending on which pipeline drew it.
+ expect(peakBlockCount(10)).toBe(2000);
+ expect(peakBlockCount(60)).toBe(12000);
+ // Capped, so a 30-minute recording costs the same DOM/array budget as a
+ // 2-minute one.
+ expect(peakBlockCount(1951)).toBe(24000);
+ expect(peakBlockCount(99999)).toBe(24000);
+ });
+
+ it("never returns zero blocks for a sliver of audio", () => {
+ expect(peakBlockCount(0.001)).toBe(1);
+ });
+});
+
+describe("ffmpeg resolution", () => {
+ it("prefers the shared build the installer actually ships", () => {
+ const candidates = ffmpegCandidates(ROOT);
+ const shared = candidates.findIndex((c) => c.endsWith("ffmpeg-shared.exe"));
+ const vendorTree = candidates.findIndex((c) => c.includes("lgpl-shared"));
+ if (process.platform === "win32") {
+ expect(shared).toBeGreaterThanOrEqual(0);
+ // The static ffmpeg.exe is excluded from the Windows installer
+ // ("!win32-*/ffmpeg.exe"), so resolving to it would work in dev and fail
+ // in production. It must not be a candidate at all.
+ expect(
+ candidates.some((c) => c.endsWith(`bin${path.sep}win32-x64${path.sep}ffmpeg.exe`)),
+ ).toBe(false);
+ expect(shared).toBeLessThan(vendorTree);
+ }
+ });
+
+ it("honours the env override first", () => {
+ process.env.OPENSCREEN_FFMPEG_PATH = "/custom/ffmpeg";
+ try {
+ expect(ffmpegCandidates(ROOT)[0]).toBe("/custom/ffmpeg");
+ } finally {
+ process.env.OPENSCREEN_FFMPEG_PATH = undefined;
+ }
+ });
+
+ it("returns null rather than throwing when nothing is staged", () => {
+ expect(resolveFfmpeg(path.join(ROOT, "does", "not", "exist"))).toBeNull();
+ });
+});
+
+// Only runs where the binary is actually staged; skipped elsewhere rather than
+// failing a checkout that has not run scripts/fetch-ffmpeg.mjs.
+const staged = resolveFfmpeg(ROOT);
+describe.runIf(staged)("decoding a real file", () => {
+ it("produces peaks in range, with real signal in them", async () => {
+ // A synthetic 5s 440 Hz tone from ffmpeg's own lavfi source — no user
+ // recording in the repo, and a signal whose shape is known rather than
+ // "whatever this capture happened to contain".
+ const fixture = path.join(ROOT, "electron", "media", "__fixtures__", "peaks-sample.m4a");
+ if (!existsSync(fixture)) return;
+ const { getAudioPeaks } = await import("./audioPeaks");
+ const peaks = await getAudioPeaks(fixture, 5);
+ expect(peaks).not.toBeNull();
+ if (!peaks) return;
+ expect(peaks.length).toBe(peakBlockCount(5) * 2);
+ // [min, max] pairs, both inside [-1, 1], min <= 0 <= max (the folder starts
+ // each block at the silence baseline, like the worker does).
+ for (let i = 0; i < peaks.length; i += 2) {
+ expect(peaks[i]).toBeLessThanOrEqual(0);
+ expect(peaks[i + 1]).toBeGreaterThanOrEqual(0);
+ expect(peaks[i]).toBeGreaterThanOrEqual(-1);
+ expect(peaks[i + 1]).toBeLessThanOrEqual(1);
+ }
+ // Not all silence — otherwise everything above would pass on a pipeline
+ // that returned a zeroed array.
+ //
+ // The bound is tight rather than "> 0" because loose is the same as
+ // absent here: the mistakes worth catching are all scale errors — int16
+ // divided by 65536 instead of 32768, a stereo downmix halving the signal,
+ // a block whose samples never get compared — and every one of them is a
+ // factor of two. 0.214 is what ffmpeg itself decodes this fixture to
+ // (verified with `-f s16le` straight to a file), so this asserts the fold
+ // agrees with the decoder rather than restating the fixture's nominal
+ // amplitude, which lavfi's volume filter does not actually deliver.
+ let mn = 0;
+ let mx = 0;
+ for (const v of peaks) {
+ if (v < mn) mn = v;
+ if (v > mx) mx = v;
+ }
+ expect(mx).toBeCloseTo(0.214, 1);
+ expect(mn).toBeCloseTo(-0.205, 1);
+ }, 120_000);
+});
diff --git a/electron/media/audioPeaks.ts b/electron/media/audioPeaks.ts
new file mode 100644
index 000000000..056cab54e
--- /dev/null
+++ b/electron/media/audioPeaks.ts
@@ -0,0 +1,288 @@
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync } from "node:fs";
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { app } from "electron";
+
+/**
+ * Waveform peaks for the timeline, computed in the main process with ffmpeg.
+ *
+ * WHY THIS EXISTS. The renderer had two pipelines and both decode the whole
+ * audio track in Chromium, which is the entire cost. Measured head-to-head on a
+ * 32-minute screen recording (68 MB):
+ *
+ * decodeAudioData (whole track) 12003 ms, 714 MB resident
+ * WebCodecs chunk-by-chunk streaming 12259 ms, ~192 kB resident
+ * ffmpeg -vn -ac 1 -ar 16000 ~2000 ms, nothing resident
+ *
+ * The two browser paths differ only in memory; ffmpeg is ~6x faster than both
+ * because a native AAC decoder is simply faster than Chromium's, and it runs
+ * off the UI process entirely. The peaks then get cached on disk, so the cost
+ * is paid once per recording rather than once per session.
+ *
+ * ponytail: the CLI, not libav bindings in the compositor addon. The addon
+ * would avoid a process spawn — worth ~20 ms against a ~2000 ms decode — for a
+ * new Rust surface, an N-API entry point and a build story on three platforms.
+ * Revisit only if peaks ever need to share a decode with something else.
+ */
+
+/** IPC reply. `peaks: null` on success means "no native ffmpeg here" — a
+ * fallback signal, not a failure. */
+export interface AudioPeaksResult {
+ success: boolean;
+ peaks?: Float32Array | null;
+ message?: string;
+}
+
+/** PCM the peaks are computed from. Mono (ffmpeg downmixes) so channels are
+ * already averaged, and 16 kHz because peak buckets are at most 200/s: that
+ * still leaves 80 samples per bucket, far more than a min/max needs. */
+const PCM_RATE = 16_000;
+
+/** Matches `audioPeaksWorker.ts` and `streamingAudioPeaks.ts` so all three
+ * render identically — a clip must not change shape with the pipeline. */
+const MAX_PEAK_BLOCKS = 24_000;
+const PEAK_BLOCKS_PER_SEC = 200;
+
+/** A recording whose audio takes longer than this to decode is not a recording,
+ * it is a wedged ffmpeg. ~30x the worst measured case. */
+const DECODE_TIMEOUT_MS = 60_000;
+
+/**
+ * Where to find an ffmpeg that actually exists at runtime, in priority order.
+ *
+ * Note the Windows shape: `electron-builder.json5` deliberately excludes the
+ * STATIC `ffmpeg.exe` (109 MB) from the installer, so resolving to it would
+ * work in dev and fail in production — the exact class of bug that is invisible
+ * until someone runs the packaged app. The SHARED build is 1 MB and links the
+ * same `av*.dll` set the compositor already ships, so that is the one that gets
+ * packaged (see the `filter` in electron-builder.json5) and the one preferred
+ * here.
+ */
+export function ffmpegCandidates(here: string = process.cwd()): string[] {
+ const tag = `${process.platform}-${process.arch}`;
+ const exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
+ const env = process.env.OPENSCREEN_FFMPEG_PATH?.trim();
+ const roots: string[] = [];
+ // `app` is absent when this module is imported by a test.
+ const appPath = (() => {
+ try {
+ return typeof app?.getAppPath === "function" ? app.getAppPath() : null;
+ } catch {
+ return null;
+ }
+ })();
+ if (appPath) roots.push(appPath);
+ if (process.resourcesPath) roots.push(process.resourcesPath);
+ roots.push(here);
+
+ const names =
+ process.platform === "win32"
+ ? [
+ // Staged flat by fetch-ffmpeg.mjs, beside the av*.dll set it links
+ // against — the only ffmpeg the Windows installer carries.
+ "ffmpeg-shared.exe",
+ // The unpacked vendor tree, present in a dev checkout that has not
+ // re-run the fetch script.
+ path.join("ffmpeg-n8.1.2-win64-lgpl-shared", "bin", exe),
+ ]
+ : [exe];
+ return [
+ ...(env ? [env] : []),
+ ...roots.flatMap((root) =>
+ names.map((n) => path.join(root, "electron", "native", "bin", tag, n)),
+ ),
+ ];
+}
+
+let cachedFfmpeg: string | null | undefined;
+
+/** First candidate that exists, or null when none does (callers fall back). */
+export function resolveFfmpeg(here?: string): string | null {
+ if (cachedFfmpeg !== undefined && here === undefined) return cachedFfmpeg;
+ const found = ffmpegCandidates(here).find((p) => existsSync(p)) ?? null;
+ if (here === undefined) cachedFfmpeg = found;
+ return found;
+}
+
+/** Number of min/max blocks for a clip of `durationSec`. */
+export function peakBlockCount(durationSec: number): number {
+ return Math.min(MAX_PEAK_BLOCKS, Math.max(1, Math.ceil(durationSec * PEAK_BLOCKS_PER_SEC)));
+}
+
+/**
+ * Folds a stream of mono int16 samples into `[min0, max0, min1, max1, ...]`.
+ *
+ * Incremental on purpose: the PCM for a 32-minute recording is 62 MB and never
+ * needs to exist all at once. Kept as a class rather than a closure so it holds
+ * only the counters it needs, not an enclosing scope.
+ */
+class PeakFolder {
+ private readonly peaks: Float32Array;
+ private readonly samplesPerBlock: number;
+ private sampleIndex = 0;
+ /** int16 straddling a chunk boundary: its low byte arrived, its high byte did not. */
+ private pendingLowByte: number | null = null;
+
+ constructor(
+ private readonly blocks: number,
+ totalSamples: number,
+ ) {
+ this.peaks = new Float32Array(blocks * 2);
+ this.samplesPerBlock = Math.max(1, totalSamples / blocks);
+ }
+
+ push(chunk: Buffer): void {
+ let offset = 0;
+ if (this.pendingLowByte !== null && chunk.length > 0) {
+ this.addSample((chunk[0] << 8) | this.pendingLowByte);
+ this.pendingLowByte = null;
+ offset = 1;
+ }
+ const end = chunk.length - ((chunk.length - offset) % 2);
+ for (let i = offset; i < end; i += 2) {
+ this.addSample(chunk.readInt16LE(i));
+ }
+ if (end < chunk.length) this.pendingLowByte = chunk[end];
+ }
+
+ private addSample(raw: number): void {
+ // readInt16LE is signed; the hand-assembled straddling sample is not.
+ const signed = raw > 32767 ? raw - 65536 : raw;
+ const value = signed / 32768;
+ const block = Math.min(this.blocks - 1, Math.floor(this.sampleIndex / this.samplesPerBlock));
+ const lo = block * 2;
+ if (value < this.peaks[lo]) this.peaks[lo] = value;
+ if (value > this.peaks[lo + 1]) this.peaks[lo + 1] = value;
+ this.sampleIndex++;
+ }
+
+ result(): Float32Array {
+ return this.peaks;
+ }
+}
+
+/** Runs ffmpeg and folds its PCM straight into peaks. Never buffers the audio. */
+async function decodePeaks(
+ ffmpeg: string,
+ filePath: string,
+ durationSec: number,
+): Promise<Float32Array> {
+ const blocks = peakBlockCount(durationSec);
+ const folder = new PeakFolder(blocks, durationSec * PCM_RATE);
+ const child = spawn(
+ ffmpeg,
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-i",
+ filePath,
+ "-vn",
+ "-ac",
+ "1",
+ "-ar",
+ String(PCM_RATE),
+ "-f",
+ "s16le",
+ "-",
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+
+ return new Promise<Float32Array>((resolve, reject) => {
+ let stderr = "";
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ reject(new Error(`ffmpeg timed out after ${DECODE_TIMEOUT_MS}ms on ${filePath}`));
+ }, DECODE_TIMEOUT_MS);
+
+ child.stdout.on("data", (c: Buffer) => folder.push(c));
+ child.stderr.on("data", (c: Buffer) => {
+ stderr = (stderr + c.toString()).slice(-2048);
+ });
+ child.once("error", (err) => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ child.once("close", (code) => {
+ clearTimeout(timer);
+ // A file with no audio track exits non-zero. That is not an error worth
+ // surfacing — it is a clip that legitimately has no waveform — but it is
+ // the caller's job to decide, so it still rejects, with the reason.
+ if (code !== 0) {
+ reject(new Error(`ffmpeg exited ${code}${stderr ? `: ${stderr.trim()}` : ""}`));
+ return;
+ }
+ resolve(folder.result());
+ });
+ });
+}
+
+/**
+ * Cache key: path plus size plus mtime. A recording is immutable in practice,
+ * but keying on identity alone would serve stale peaks for a re-encoded or
+ * replaced file, and that failure is silent and confusing.
+ */
+async function cacheKey(filePath: string): Promise<string> {
+ const info = await stat(filePath);
+ return createHash("sha1")
+ .update(`${filePath}:${info.size}:${info.mtimeMs}`)
+ .digest("hex")
+ .slice(0, 32);
+}
+
+/** Null outside Electron (tests, any headless use): decoding still works, it
+ * just is not cached, rather than the whole call failing on a missing `app`. */
+function cacheDir(): string | null {
+ try {
+ return typeof app?.getPath === "function"
+ ? path.join(app.getPath("userData"), "audio-peaks")
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Peaks for `filePath`, from disk when they have been computed before.
+ *
+ * The cache is what makes this feel instant: peaks for a given recording never
+ * change, so the ~2s decode is paid once ever rather than once per session.
+ * Returns null when no ffmpeg is available, so the renderer can fall back to
+ * its own pipelines instead of losing the waveform.
+ */
+export async function getAudioPeaks(
+ filePath: string,
+ durationSec: number,
+): Promise<Float32Array | null> {
+ const ffmpeg = resolveFfmpeg();
+ if (!ffmpeg || !durationSec || durationSec <= 0) return null;
+
+ const dir = cacheDir();
+ const cachePath = dir ? path.join(dir, `${await cacheKey(filePath)}.f32`) : null;
+ if (cachePath) {
+ try {
+ const cached = await readFile(cachePath);
+ // A Buffer's memory may not be 4-byte aligned and its byteOffset is
+ // almost never 0 — copy rather than viewing it in place.
+ return new Float32Array(
+ cached.buffer.slice(cached.byteOffset, cached.byteOffset + cached.byteLength),
+ );
+ } catch {
+ // Not cached yet.
+ }
+ }
+
+ const peaks = await decodePeaks(ffmpeg, filePath, durationSec);
+ if (cachePath && dir) {
+ try {
+ await mkdir(dir, { recursive: true });
+ await writeFile(cachePath, Buffer.from(peaks.buffer));
+ } catch {
+ // A cache we cannot write is a slower next launch, not a failure.
+ }
+ }
+ return peaks;
+}
diff --git a/electron/preload.ts b/electron/preload.ts
index 1fa241719..82dd2b409 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -284,6 +284,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
getReadableFileInfo: (filePath: string) => {
return ipcRenderer.invoke("get-readable-file-info", filePath);
},
+ /** Native waveform peaks, disk-cached. See electron/media/audioPeaks.ts. */
+ getAudioPeaks: (filePath: string, durationSec: number) => {
+ return ipcRenderer.invoke("get-audio-peaks", filePath, durationSec);
+ },
readFileChunk: (filePath: string, offset: number, length: number) => {
return ipcRenderer.invoke("read-file-chunk", filePath, offset, length);
},
diff --git a/scripts/fetch-ffmpeg.mjs b/scripts/fetch-ffmpeg.mjs
index 1c42a92ce..9a98bcf1a 100644
--- a/scripts/fetch-ffmpeg.mjs
+++ b/scripts/fetch-ffmpeg.mjs
@@ -457,7 +457,15 @@ async function fetchSharedDlls(tag, binDir) {
fs.copyFileSync(lib, dest);
}
}
- console.log(`Vendored ${libs.length} shared librar(ies) -> ${binDir}`);
+ // The shared CLI too, beside the DLLs it links against. 1 MB, against
+ // the 109 MB of the static exe the installer excludes — and unlike that
+ // one, this is spawned at runtime: electron/media/audioPeaks.ts decodes
+ // waveform peaks with it, ~6x faster than either browser pipeline and
+ // off the UI process. Named apart from `ffmpeg.exe` on purpose, so the
+ // packager's `!win32-*/ffmpeg.exe` rule keeps dropping the static build
+ // while this one ships under the plain `win32-*/*` include.
+ fs.copyFileSync(exe, path.join(binDir, "ffmpeg-shared.exe"));
+ console.log(`Vendored ${libs.length} shared librar(ies) + ffmpeg-shared.exe -> ${binDir}`);
}
if (sdkDest) vendorFfmpegSdk(tmp, sdkDest);
console.log("LGPL verified: safe to ship with an MIT app.");
diff --git a/src/hooks/useAudioPeaks.ts b/src/hooks/useAudioPeaks.ts
index ed57671ca..da7512e2c 100644
--- a/src/hooks/useAudioPeaks.ts
+++ b/src/hooks/useAudioPeaks.ts
@@ -91,6 +91,22 @@ async function computePeaksForUrl(
durationSec?: number,
): Promise<Float32Array> {
const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);
+
+ // Native first. Both browser pipelines below decode the whole track in
+ // Chromium — 12s on a 32-minute recording, whichever one runs — where ffmpeg
+ // in the main process takes ~2s and caches the result on disk, so the second
+ // time it is free. Anything that stops this from working (no ffmpeg staged,
+ // an unapproved path, a clip with no audio) falls through rather than
+ // dropping the waveform.
+ if (!isRemoteUrl && durationSec && window.electronAPI?.getAudioPeaks) {
+ try {
+ const native = await window.electronAPI.getAudioPeaks(videoUrl, durationSec);
+ if (native.success && native.peaks && native.peaks.length > 0) return native.peaks;
+ } catch {
+ // Fall through to the browser pipelines.
+ }
+ }
+
if (!isRemoteUrl && window.electronAPI?.getReadableFileInfo) {
const info = await window.electronAPI.getReadableFileInfo(videoUrl);
const decodedBytes = (durationSec ?? 0) * DECODED_BYTES_PER_SEC;