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(waveform): take ffmpeg's word when a recording has no audio track

Etienne Lescot9e00d11a2736
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.ts
index 30f5fd718..2b5782aa6 100644
--- a/electron/ai-edition/document-service.test.ts
+++ b/electron/ai-edition/document-service.test.ts
@@ -68,6 +68,77 @@ describe("DocumentService", () => {
await expect(service.getProject("proj/with/slash")).rejects.toBeInstanceOf(ProjectFileError);
});
+ // Issue #348 — recording with no camera AND no microphone is the default for
+ // anyone capturing a screen demo, and the failure lands at REOPEN, where the
+ // recording exists on disk but the user cannot get to it. The recorder writes
+ // no audio stream at all in that configuration (confirmed with ffprobe on real
+ // captures) and `cameraTrack: null`, so this is the exact on-disk shape.
+ describe("camera-less, microphone-less recordings", () => {
+ // Windows path separators on purpose: the reporter is on Windows 11 and
+ // `path.join` gives us the host's, so this stays honest on all three.
+ async function writeCamlessProject(originalPath: string, sizeBytes?: number) {
+ const doc = await service.createProject("Screen demo, no cam no mic");
+ const asset: AxcutAsset = {
+ id: "asset_camless",
+ kind: "video",
+ label: path.basename(originalPath),
+ originalPath,
+ sizeBytes,
+ // No `audio` (the probe never populates it) and no camera link.
+ cameraTrack: null,
+ transcriptionFailure: {
+ kind: "no-audio",
+ message: "No audio track found in this video.",
+ },
+ };
+ await service.saveProject({
+ ...doc,
+ assets: [asset],
+ project: { ...doc.project, primaryAssetId: asset.id },
+ });
+ return doc.project.id;
+ }
+
+ it("reopens, and stays listed", async () => {
+ const screenPath = path.join(mediaDir, "screen-demo.mp4");
+ await fs.writeFile(screenPath, "screen bytes", "utf8");
+ const projectId = await writeCamlessProject(screenPath);
+
+ const reopened = await service.getProject(projectId);
+ expect(reopened.assets[0]?.cameraTrack).toBeNull();
+ expect(reopened.assets[0]?.originalPath).toBe(screenPath);
+ // A document that throws here is dropped by listProjects' skip-on-error
+ // catch, which presents to the user as "my project vanished" rather than
+ // as an error — so the absence of a throw is not enough to assert.
+ const summaries = await service.listProjects();
+ expect(summaries.map((s) => s.id)).toContain(projectId);
+ // Re-decided on every open, so it must survive the round trip or the
+ // whole recording is re-extracted for transcription each time.
+ expect(reopened.assets[0]?.transcriptionFailure?.kind).toBe("no-audio");
+ });
+
+ it("does not hand the relinker's webcam to an asset that never had one", async () => {
+ // The relink only runs when something is actually broken, so move the
+ // screen file — and register a link that DOES carry a webcam, which is
+ // the shape that produced #265 (screen recording used as the webcam).
+ const screenBytes = "screen bytes";
+ const screenPath = path.join(mediaDir, "moved-screen-demo.mp4");
+ const webcamPath = path.join(mediaDir, "moved-screen-demo-webcam.mp4");
+ await fs.writeFile(screenPath, screenBytes, "utf8");
+ await fs.writeFile(webcamPath, "webcam bytes", "utf8");
+ await registerMediaLinks(mediaDir, screenPath, { webcamVideoPath: webcamPath });
+
+ const projectId = await writeCamlessProject(
+ path.join(mediaDir, "gone", "moved-screen-demo.mp4"),
+ Buffer.byteLength(screenBytes),
+ );
+
+ const reopened = await service.getProject(projectId);
+ expect(reopened.assets[0]?.originalPath).toBe(screenPath);
+ expect(reopened.assets[0]?.cameraTrack).toBeNull();
+ });
+ });
+
// Issue #212 — a project authored on another machine opens with every asset
// pointing at a path that does not exist here. The relink runs on this read,
// not on import, so a document already saved broken still recovers.
diff --git a/src/hooks/useAudioPeaks.test.ts b/src/hooks/useAudioPeaks.test.ts
index 0783cd2d9..321781490 100644
--- a/src/hooks/useAudioPeaks.test.ts
+++ b/src/hooks/useAudioPeaks.test.ts
@@ -10,8 +10,12 @@ const streamingCalls = vi.fn();
const inMemoryCalls = vi.fn();
vi.mock("./streamingAudioPeaks", () => ({
- computePeaksFromFileStreaming: async () => {
+ computePeaksFromFileStreaming: async (file: { name: string }) => {
streamingCalls();
+ // A recording captured with no microphone and no system audio has no audio
+ // stream at all (verified with ffprobe on real camera-less captures), so
+ // every decode of it fails — the same way, every time.
+ if (file.name.startsWith("silent")) throw new Error("no audio track");
return new Float32Array([0, 1]);
},
}));
@@ -85,4 +89,75 @@ describe("useAudioPeaks", () => {
await waitFor(() => expect(again.result.current).not.toBeNull());
expect(streamingCalls).toHaveBeenCalledOnce();
});
+
+ // Issue #348 — a project recorded with no camera AND no microphone. The
+ // recorder writes an MP4 with no audio stream at all, so the decode below can
+ // never succeed. Caching only successes meant this file re-read itself whole
+ // on every mount, forever; a recording WITH a mic paid it once. That
+ // asymmetry is the bug.
+ it("gives up on a file with no audio track once, not once per mount", async () => {
+ const url = "/tmp/silent-no-mic.mp4";
+ const first = renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+ await waitFor(() => expect(streamingCalls).toHaveBeenCalledOnce());
+ expect(first.result.current).toBeNull();
+
+ act(() => first.unmount());
+ const second = renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+ await waitFor(() => expect(second.result.current).toBeNull());
+ act(() => second.unmount());
+ renderHook(() => useAudioPeaks(url, THIRTY_TWO_MINUTES));
+
+ // The decode is never retried: "this file has no waveform" is a permanent
+ // answer and is remembered as one.
+ expect(streamingCalls).toHaveBeenCalledOnce();
+ });
+
+ // The other half of #348, and the expensive half: ffmpeg answers "no audio
+ // track" in ~2s, and the renderer used to spend a 175 MB copy into OPFS plus
+ // a full Chromium decode re-discovering it — on every project open, since a
+ // module-scope cache starts empty each launch.
+ it("takes ffmpeg's word for it when a recording has no audio track", async () => {
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ getReadableFileInfo: async () => ({ success: true, size: FILE_BYTES }),
+ getAudioPeaks: async () => ({
+ success: false,
+ message: "Cannot find wanted stream in the input file",
+ }),
+ };
+ const { result } = renderHook(() =>
+ useAudioPeaks("/tmp/no-mic-recording.mp4", THIRTY_TWO_MINUTES),
+ );
+ await waitFor(() => expect(result.current).not.toBeNull());
+ // A verdict, not a gap: no browser pipeline runs at all.
+ expect(streamingCalls).not.toHaveBeenCalled();
+ expect(inMemoryCalls).not.toHaveBeenCalled();
+ expect(result.current).toHaveLength(0);
+ });
+
+ it("still falls back to a browser pipeline when the host has no ffmpeg", async () => {
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ getReadableFileInfo: async () => ({ success: true, size: FILE_BYTES }),
+ // The documented "no native ffmpeg here" signal — a gap, not a verdict.
+ getAudioPeaks: async () => ({ success: true, peaks: null }),
+ };
+ renderHook(() => useAudioPeaks("/tmp/no-ffmpeg-host.mp4", THIRTY_TWO_MINUTES));
+ await waitFor(() => expect(streamingCalls).toHaveBeenCalledOnce());
+ });
+
+ it("decodes nothing until the duration is known", async () => {
+ const url = "/tmp/pending-duration.mp4";
+ const view = renderHook(({ d }: { d: number | undefined }) => useAudioPeaks(url, d), {
+ initialProps: { d: undefined as number | undefined },
+ });
+ // Without a duration `computePeaksForUrl` cannot reach the cheap native
+ // tier and falls through to reading the whole file into memory — for a
+ // waveform `ClipWaveform` could not draw anyway, since it needs the same
+ // duration to lay bars out.
+ expect(streamingCalls).not.toHaveBeenCalled();
+ expect(inMemoryCalls).not.toHaveBeenCalled();
+
+ view.rerender({ d: THIRTY_TWO_MINUTES });
+ await waitFor(() => expect(view.result.current).not.toBeNull());
+ expect(streamingCalls).toHaveBeenCalledOnce();
+ });
});
diff --git a/src/hooks/useAudioPeaks.ts b/src/hooks/useAudioPeaks.ts
index da7512e2c..3db9e6fcb 100644
--- a/src/hooks/useAudioPeaks.ts
+++ b/src/hooks/useAudioPeaks.ts
@@ -95,15 +95,29 @@ async function computePeaksForUrl(
// 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.
+ // time it is free.
+ //
+ // Only ONE of the three replies is a reason to fall through (see
+ // `AudioPeaksResult`): `peaks: null` means "no native ffmpeg on this host",
+ // which is the gap the browser pipelines exist to cover. `success: false`
+ // means ffmpeg RAN and found nothing to decode — a verdict, not a gap.
+ //
+ // Falling through on that verdict is issue #348's real cost: a recording made
+ // with no mic and no system audio has no audio stream at all, ffmpeg says so
+ // in ~2s, and the renderer then spent a 175 MB copy into OPFS plus a full
+ // Chromium decode re-discovering it on every project open. Empty peaks rather
+ // than a throw, so the answer caches like any other and is never recomputed.
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;
+ if (native.success) {
+ if (native.peaks && native.peaks.length > 0) return native.peaks;
+ if (native.peaks !== null) return new Float32Array(0);
+ } else {
+ return new Float32Array(0);
+ }
} catch {
- // Fall through to the browser pipelines.
+ // The IPC itself failed — that IS a gap, so fall through.
}
}
@@ -143,11 +157,18 @@ async function computePeaksForUrl(
*
* `inFlight` is the other half: N clips of one asset mounting together must
* share a single decode instead of racing N of them.
+ *
+ * FAILURE IS CACHED TOO (`null`), which is why the value type is nullable and
+ * why lookups go through `has()` rather than truthiness. A file with no audio
+ * fails deterministically, so retrying it is pure cost — and on a host with no
+ * native ffmpeg that retry is the whole-file browser decode. Caching only
+ * successes meant a recording WITH a mic paid for its waveform once while one
+ * WITHOUT paid, and threw away, the same work on every mount (issue #348).
*/
-const peaksCache = new Map<string, Float32Array>();
+const peaksCache = new Map<string, Float32Array | null>();
const peaksInFlight = new Map<string, Promise<Float32Array>>();
-function loadPeaks(videoUrl: string, durationSec?: number): 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,
@@ -158,6 +179,12 @@ function loadPeaks(videoUrl: string, durationSec?: number): Promise<Float32Array
peaksCache.set(videoUrl, p);
return p;
})
+ .catch((err: unknown) => {
+ // "This file has no waveform" is an answer, and a permanent one — record
+ // it so the decode is never attempted again for this file.
+ peaksCache.set(videoUrl, null);
+ throw err;
+ })
.finally(() => {
peaksInFlight.delete(videoUrl);
});
@@ -168,8 +195,14 @@ function loadPeaks(videoUrl: string, durationSec?: number): Promise<Float32Array
/**
* 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). `durationSec` only picks the pipeline
- * (see `computePeaksForUrl`); omitting it is safe, just slower on long files.
+ * decode failure (silent degradation).
+ *
+ * Nothing is decoded until `durationSec` is known. It is not a hint: it is what
+ * routes the work to the cheap native ffmpeg tier (`computePeaksForUrl` skips
+ * that tier without it and falls through to reading the whole file into memory),
+ * and `ClipWaveform` cannot draw a single bar without it either. Starting early
+ * therefore bought nothing and cost a full-file read — so the effect waits, and
+ * re-runs when the probed duration arrives.
*/
export function useAudioPeaks(videoUrl?: string, durationSec?: number): Float32Array | null {
const [peaks, setPeaks] = useState<Float32Array | null>(() =>
@@ -182,13 +215,13 @@ export function useAudioPeaks(videoUrl?: string, durationSec?: number): Float32A
return;
}
- const cached = peaksCache.get(videoUrl);
- if (cached) {
- setPeaks(cached);
+ if (peaksCache.has(videoUrl)) {
+ setPeaks(peaksCache.get(videoUrl) ?? null);
return;
}
setPeaks(null);
+ if (!durationSec) return;
let cancelled = false;
loadPeaks(videoUrl, durationSec)
@@ -206,7 +239,7 @@ export function useAudioPeaks(videoUrl?: string, durationSec?: number): Float32A
return () => {
cancelled = true;
};
- }, [videoUrl]);
+ }, [videoUrl, durationSec]);
return peaks;
}