Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(recording): stream the native webcam to disk instead of losing it
Etienne Lescot41126c44483a
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex e5381999b..9e1fb7d0d 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -178,6 +178,8 @@ interface Window {recordingId: number;webcam: import("../src/lib/recordingSession").RecordedVideoAssetInput;cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;+ durationMs?: number;+ webcamOffsetMs?: number;}) => Promise<{success: boolean;path?: string;@@ -233,6 +235,7 @@ interface Window {recordingId: number;webcam: import("../src/lib/recordingSession").RecordedVideoAssetInput;cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;+ durationMs?: number;webcamOffsetMs?: number;}) => Promise<{success: boolean;diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 3800671e5..5fae3cbeb 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -439,6 +439,12 @@ type AttachNativeMacWebcamRecordingInput = {recordingId?: number;webcam?: RecordedVideoAssetInput;cursorCaptureMode?: CursorCaptureMode;+ /**+ * Webcam clip duration (ms), head start included. A streamed webcam file carries+ * no Duration header and the renderer no longer holds the blob to patch, so the+ * main process repairs the container on disk with this value.+ */+ durationMs?: number;/** See {@link ProjectMedia.webcamOffsetMs}. */webcamOffsetMs?: number;};@@ -2788,6 +2794,13 @@ export function registerIpcHandlers(}});+ // On-disk write streams for in-progress recordings, keyed by output file name.+ // Chunks append as they arrive so the renderer never buffers the full video (#616).+ // Declared here because both the webcam attach below and store-recorded-session+ // finalize through the same registry.+ const recordingStreams = new RecordingStreamRegistry();+ registerRecordingStreamHandlers(ipcMain, recordingStreams, resolveRecordingOutputPath);+/*** Writes a browser-recorded webcam clip next to a natively-recorded screen* video and rewrites the session manifest to include both.@@ -2817,7 +2830,7 @@ export function registerIpcHandlers(await fs.access(screenVideoPath, fsConstants.R_OK);- if (!payload.webcam?.fileName || !payload.webcam.videoData) {+ if (!payload.webcam?.fileName) {return {success: false,error: `Native ${platformLabel} webcam attachment is missing video data.`,@@ -2825,7 +2838,31 @@ export function registerIpcHandlers(}const webcamVideoPath = resolveRecordingOutputPath(payload.webcam.fileName);- await fs.writeFile(webcamVideoPath, Buffer.from(payload.webcam.videoData));+ // A streamed webcam arrives with an empty buffer: its bytes are already on+ // disk, so close the stream and keep the file rather than writing it here.+ // Nothing multi-gigabyte crosses IPC or gets flattened into one Buffer (#253).+ const webcamStreamed = await finalizeRecordingFile(+ recordingStreams,+ payload.webcam.fileName,+ webcamVideoPath,+ payload.webcam.videoData,+ );+ // Mirrors finalizeRecordingFile's own condition, so this fires exactly when+ // it wrote nothing and the session would point at a file that isn't there.+ if (+ !webcamStreamed &&+ !(payload.webcam.videoData && payload.webcam.videoData.byteLength > 0)+ ) {+ return {+ success: false,+ error: `Native ${platformLabel} webcam attachment is missing video data.`,+ };+ }+ // Streamed files lack the WebM Duration header, which the editor needs to+ // scale its timeline. Best-effort: a failed repair leaves the clip intact.+ if (webcamStreamed && isValidDurationMs(payload.durationMs)) {+ await repairRecordingContainer(webcamVideoPath, payload.durationMs);+ }const createdAt =typeof payload.recordingId === "number" && Number.isFinite(payload.recordingId)@@ -2892,11 +2929,6 @@ export function registerIpcHandlers(},);- // On-disk write streams for in-progress recordings, keyed by output file name.- // Chunks append as they arrive so the renderer never buffers the full video (#616).- const recordingStreams = new RecordingStreamRegistry();- registerRecordingStreamHandlers(ipcMain, recordingStreams, resolveRecordingOutputPath);-ipcMain.handle("store-recorded-session", async (_, payload: StoreRecordedSessionInput) => {try {return await storeRecordedSessionFiles(payload);diff --git a/electron/preload.ts b/electron/preload.tsindex 04b2427ae..8e018ed8e 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -209,6 +209,7 @@ contextBridge.exposeInMainWorld("electronAPI", {recordingId: number;webcam: { fileName: string; videoData: ArrayBuffer };cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;+ durationMs?: number;webcamOffsetMs?: number;}) => {return ipcRenderer.invoke("attach-native-linux-webcam-recording", payload);@@ -242,6 +243,7 @@ contextBridge.exposeInMainWorld("electronAPI", {recordingId: number;webcam: { fileName: string; videoData: ArrayBuffer };cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;+ durationMs?: number;webcamOffsetMs?: number;}) => {return ipcRenderer.invoke("attach-native-mac-webcam-recording", payload);diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex f5ec47faa..7a35fca77 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -143,6 +143,48 @@ export function webcamOffsetMsFrom(return -Math.round(nativeStartedAtMs - webcamStartedAtMs);}+/**+ * Turn a finished webcam recorder into the asset the native attach IPC wants, or+ * into the reason it cannot be saved. Shared by the macOS and Linux finalizers,+ * which differ only in the name they log under.+ *+ * A streamed recording resolves an empty blob by design — its bytes are already+ * on disk — so it hands over the file name alone and the main process closes the+ * stream and patches the duration there. Only a buffered recording is read into+ * memory, and flattening one of those into a single ArrayBuffer is exactly what+ * used to throw past ~2 GB and cost the user the whole camera track (#253).+ *+ * Never resolves to "nothing happened": every failure comes back with a reason,+ * because the screen recording still saves and a silent drop just opens the+ * editor with the camera mysteriously absent.+ */+export async function finalizeWebcamAsset(+ webcamRecorder: RecorderHandle,+ fileName: string,+ durationMs: number,+ platformLabel: string,+): Promise<{ asset?: RecordedVideoAssetInput; error?: string }> {+ try {+ if (webcamRecorder.recorder.state !== "inactive") {+ webcamRecorder.recorder.stop();+ }+ // Rejects on a mid-stream write failure, so a truncated recording lands in+ // the catch below rather than passing for a good one.+ const webcamBlob = await webcamRecorder.recordedBlobPromise;+ if (webcamRecorder.isStreaming()) {+ return { asset: { videoData: new ArrayBuffer(0), fileName } };+ }+ if (!webcamBlob || webcamBlob.size === 0) {+ return { error: "the webcam produced no data" };+ }+ const fixedWebcamBlob = await fixWebmDuration(webcamBlob, durationMs);+ return { asset: { videoData: await fixedWebcamBlob.arrayBuffer(), fileName } };+ } catch (error) {+ console.error(`Failed to finalize native ${platformLabel} webcam recording:`, error);+ return { error: error instanceof Error ? error.message : String(error) };+ }+}+export function useScreenRecorder(): UseScreenRecorderReturn {const t = useScopedT("editor");const [recording, setRecording] = useState(false);@@ -580,38 +622,23 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (activeWebcamRecorder && webcamRecorder.current === activeWebcamRecorder) {webcamRecorder.current = null;}- const webcamAssetPromise = (async (): Promise<RecordedVideoAssetInput | undefined> => {- if (!activeWebcamRecorder) {- return undefined;- }-- try {- if (activeWebcamRecorder.recorder.state !== "inactive") {- activeWebcamRecorder.recorder.stop();- }- const webcamBlob = await activeWebcamRecorder.recordedBlobPromise;- if (!webcamBlob || webcamBlob.size === 0) {- return undefined;- }- // The webcam MediaRecorder started before the native recording did (see- // webcamOffsetMs on NativeMacRecordingHandle), so its real content is- // longer than the screen's active `duration` by that same head start.- // Patching the WebM's declared duration to the screen's shorter duration- // would make that extra leading footage unseekable in a standard <video>- // element (which trusts the container's declared duration/seek range) --- // exactly the footage the editor needs to skip into to compensate for- // webcamOffsetMs, so it must stay reachable.- const webcamHeadStartMs = Math.max(0, -(activeNativeRecording.webcamOffsetMs ?? 0));- const fixedWebcamBlob = await fixWebmDuration(webcamBlob, duration + webcamHeadStartMs);- return {- videoData: await fixedWebcamBlob.arrayBuffer(),- fileName: `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`,- };- } catch (error) {- console.error("Failed to finalize native macOS webcam recording:", error);- return undefined;- }- })();+ // The webcam MediaRecorder started before the native recording did (see+ // webcamOffsetMs on NativeMacRecordingHandle), so its real content is+ // longer than the screen's active `duration` by that same head start.+ // Patching the WebM's declared duration to the screen's shorter duration+ // would make that extra leading footage unseekable in a standard <video>+ // element (which trusts the container's declared duration/seek range) --+ // exactly the footage the editor needs to skip into to compensate for+ // webcamOffsetMs, so it must stay reachable.+ const webcamHeadStartMs = Math.max(0, -(activeNativeRecording.webcamOffsetMs ?? 0));+ const webcamDurationMs = duration + webcamHeadStartMs;+ const webcamFileName = `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`;+ const webcamResultPromise: Promise<{+ asset?: RecordedVideoAssetInput;+ error?: string;+ }> = activeWebcamRecorder+ ? finalizeWebcamAsset(activeWebcamRecorder, webcamFileName, webcamDurationMs, "macOS")+ : Promise.resolve({});const clearNativeRecordingState = () => {nativeMacRecording.current = null;@@ -622,9 +649,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {segmentStartedAt.current = null;};+ let webcamSaved = false;try {const result = await window.electronAPI.stopNativeMacRecording(discard);- const webcamAsset = await webcamAssetPromise;+ const webcamResult = await webcamResultPromise;if (discard || result.discarded) {clearNativeRecordingState();return true;@@ -636,22 +664,28 @@ export function useScreenRecorder(): UseScreenRecorderReturn {return true;}- if (webcamAsset && result.path) {+ if (webcamResult.asset && result.path) {const attachResult = await window.electronAPI.attachNativeMacWebcamRecording({screenVideoPath: result.path,recordingId: activeNativeRecording.recordingId,- webcam: webcamAsset,+ webcam: webcamResult.asset,cursorCaptureMode,+ durationMs: webcamDurationMs,...(typeof activeNativeRecording.webcamOffsetMs === "number"? { webcamOffsetMs: activeNativeRecording.webcamOffsetMs }: {}),});if (attachResult.success) {result.session = attachResult.session;+ webcamSaved = true;} else {console.error("Failed to attach native macOS webcam recording:", attachResult.error);toast.error(attachResult.error ?? "Failed to store webcam recording");}+ } else if (webcamResult.error) {+ // The screen recording still saves, so without this the editor just+ // opens with the camera missing and nothing said about it (#253).+ toast.error(`Webcam not saved (${webcamResult.error}). The screen recording was kept.`);}clearNativeRecordingState();@@ -671,6 +705,12 @@ export function useScreenRecorder(): UseScreenRecorderReturn {activeNativeRecording.finalizing = false;return true;} finally {+ // A webcam stream that wasn't folded into a saved session has to be closed+ // and its partial file removed, or a discarded or failed take orphans a+ // half-written .webm now that the bytes go to disk as they arrive.+ if (activeWebcamRecorder && !webcamSaved) {+ await activeWebcamRecorder.discard().catch(() => undefined);+ }if (discardRecordingId.current === activeNativeRecording.recordingId) {discardRecordingId.current = null;}@@ -701,33 +741,18 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (activeWebcamRecorder && webcamRecorder.current === activeWebcamRecorder) {webcamRecorder.current = null;}- const webcamAssetPromise = (async (): Promise<RecordedVideoAssetInput | undefined> => {- if (!activeWebcamRecorder) {- return undefined;- }-- try {- if (activeWebcamRecorder.recorder.state !== "inactive") {- activeWebcamRecorder.recorder.stop();- }- const webcamBlob = await activeWebcamRecorder.recordedBlobPromise;- if (!webcamBlob || webcamBlob.size === 0) {- return undefined;- }- // See the identical comment in finalizeNativeMacRecording: the- // leading footage recorded while the portal picker was up must- // stay seekable, so the declared duration includes it.- const webcamHeadStartMs = Math.max(0, -(activeNativeRecording.webcamOffsetMs ?? 0));- const fixedWebcamBlob = await fixWebmDuration(webcamBlob, duration + webcamHeadStartMs);- return {- videoData: await fixedWebcamBlob.arrayBuffer(),- fileName: `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`,- };- } catch (error) {- console.error("Failed to finalize native Linux webcam recording:", error);- return undefined;- }- })();+ // See the identical comment in finalizeNativeMacRecording: the+ // leading footage recorded while the portal picker was up must+ // stay seekable, so the declared duration includes it.+ const webcamHeadStartMs = Math.max(0, -(activeNativeRecording.webcamOffsetMs ?? 0));+ const webcamDurationMs = duration + webcamHeadStartMs;+ const webcamFileName = `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`;+ const webcamResultPromise: Promise<{+ asset?: RecordedVideoAssetInput;+ error?: string;+ }> = activeWebcamRecorder+ ? finalizeWebcamAsset(activeWebcamRecorder, webcamFileName, webcamDurationMs, "Linux")+ : Promise.resolve({});const clearNativeRecordingState = () => {nativeLinuxRecording.current = null;@@ -738,9 +763,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {segmentStartedAt.current = null;};+ let webcamSaved = false;try {const result = await window.electronAPI.stopNativeLinuxRecording(discard);- const webcamAsset = await webcamAssetPromise;+ const webcamResult = await webcamResultPromise;if (discard || result.discarded) {clearNativeRecordingState();return true;@@ -752,22 +778,28 @@ export function useScreenRecorder(): UseScreenRecorderReturn {return true;}- if (webcamAsset && result.path) {+ if (webcamResult.asset && result.path) {const attachResult = await window.electronAPI.attachNativeLinuxWebcamRecording({screenVideoPath: result.path,recordingId: activeNativeRecording.recordingId,- webcam: webcamAsset,+ webcam: webcamResult.asset,cursorCaptureMode,+ durationMs: webcamDurationMs,...(typeof activeNativeRecording.webcamOffsetMs === "number"? { webcamOffsetMs: activeNativeRecording.webcamOffsetMs }: {}),});if (attachResult.success) {result.session = attachResult.session;+ webcamSaved = true;} else {console.error("Failed to attach native Linux webcam recording:", attachResult.error);toast.error(attachResult.error ?? "Failed to store webcam recording");}+ } else if (webcamResult.error) {+ // The screen recording still saves, so without this the editor just+ // opens with the camera missing and nothing said about it (#253).+ toast.error(`Webcam not saved (${webcamResult.error}). The screen recording was kept.`);}clearNativeRecordingState();@@ -787,6 +819,12 @@ export function useScreenRecorder(): UseScreenRecorderReturn {activeNativeRecording.finalizing = false;return true;} finally {+ // A webcam stream that wasn't folded into a saved session has to be closed+ // and its partial file removed, or a discarded or failed take orphans a+ // half-written .webm now that the bytes go to disk as they arrive.+ if (activeWebcamRecorder && !webcamSaved) {+ await activeWebcamRecorder.discard().catch(() => undefined);+ }if (discardRecordingId.current === activeNativeRecording.recordingId) {discardRecordingId.current = null;}@@ -1136,10 +1174,18 @@ export function useScreenRecorder(): UseScreenRecorderReturn {}if (webcamStream.current) {nativeWebcamRecorderStartedAtMs = performance.now();- nativeWebcamRecorder = createRecorderHandle(webcamStream.current, {- mimeType: selectMimeType(),- videoBitsPerSecond: BITRATE_BASE,- });+ // Stream to disk. Buffered in memory, a long take had to be flattened+ // into one ArrayBuffer at finalize -- past ~2GB that throws, and the+ // camera was dropped without a word (#253). The main process reuses the+ // recordingId we send here, so this name is the one finalize rebuilds.+ nativeWebcamRecorder = createRecorderHandle(+ webcamStream.current,+ {+ mimeType: selectMimeType(),+ videoBitsPerSecond: BITRATE_BASE,+ },+ `${RECORDING_FILE_PREFIX}${activeRecordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`,+ );} else {webcamAcquireId.current++;setWebcamEnabledState(false);@@ -1320,10 +1366,16 @@ export function useScreenRecorder(): UseScreenRecorderReturn {}if (webcamStream.current) {nativeWebcamRecorderStartedAtMs = performance.now();- nativeWebcamRecorder = createRecorderHandle(webcamStream.current, {- mimeType: selectMimeType(),- videoBitsPerSecond: BITRATE_BASE,- });+ // See the identical comment in the macOS path: stream to disk so a long+ // take is never flattened into one ArrayBuffer at finalize (#253).+ nativeWebcamRecorder = createRecorderHandle(+ webcamStream.current,+ {+ mimeType: selectMimeType(),+ videoBitsPerSecond: BITRATE_BASE,+ },+ `${RECORDING_FILE_PREFIX}${activeRecordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`,+ );} else {webcamAcquireId.current++;setWebcamEnabledState(false);diff --git a/src/hooks/webcamAsset.test.ts b/src/hooks/webcamAsset.test.tsnew file mode 100644index 000000000..e03a8719d--- /dev/null+++ b/src/hooks/webcamAsset.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it, vi } from "vitest";+import type { RecorderHandle } from "./recorderHandle";+import { finalizeWebcamAsset } from "./useScreenRecorder";++/**+ * The property under test is that a webcam track is never lost without a word.+ *+ * The native macOS/Linux paths used to buffer the whole camera clip in the+ * renderer and flatten it into one ArrayBuffer at finalize. Past ~2 GB (a take+ * of roughly 20 minutes at BITRATE_BASE) that throws, the throw was swallowed,+ * and the session was written screen-only — the editor opened normally with the+ * camera simply absent (#253). So each case below asserts one of two things:+ * that a streamed recording never gets read into memory at all, or that a+ * failure comes back with a reason the caller can put in front of the user.+ */++const FILE_NAME = "recording-1-webcam.webm";++function fakeHandle(overrides: Partial<RecorderHandle> & { state?: MediaRecorder["state"] }) {+ const { state = "recording", ...rest } = overrides;+ const stop = vi.fn();+ const handle = {+ recorder: { state, stop } as unknown as MediaRecorder,+ recordedBlobPromise: Promise.resolve(new Blob([])),+ isStreaming: () => false,+ discard: async () => undefined,+ ...rest,+ } as RecorderHandle;+ return { handle, stop };+}++describe("finalizeWebcamAsset", () => {+ it("hands over the file name alone when the clip streamed to disk", async () => {+ // The bytes are already on disk, so the empty buffer is the whole point:+ // nothing multi-gigabyte is flattened here or sent across IPC.+ const { handle } = fakeHandle({+ recordedBlobPromise: Promise.resolve(new Blob([])),+ isStreaming: () => true,+ });++ const result = await finalizeWebcamAsset(handle, FILE_NAME, 1_381_500, "macOS");++ expect(result.error).toBeUndefined();+ expect(result.asset).toEqual({ fileName: FILE_NAME, videoData: new ArrayBuffer(0) });+ });++ it("does not mistake a streamed clip's empty blob for a failed recording", async () => {+ // Guards the regression the streaming fix could have introduced: the empty+ // blob is by design, and treating it as "no data" would drop the camera+ // exactly the way the original bug did.+ const { handle } = fakeHandle({+ recordedBlobPromise: Promise.resolve(new Blob([])),+ isStreaming: () => true,+ });++ await expect(finalizeWebcamAsset(handle, FILE_NAME, 1_000, "Linux")).resolves.toMatchObject({+ asset: { fileName: FILE_NAME },+ });+ });++ it("reads a buffered clip into memory and passes its bytes through", async () => {+ // Short takes still buffer, and still have to arrive as bytes.+ const { handle } = fakeHandle({+ recordedBlobPromise: Promise.resolve(new Blob(["webcam bytes"])),+ });++ const result = await finalizeWebcamAsset(handle, FILE_NAME, 6_400, "macOS");++ expect(result.error).toBeUndefined();+ expect(+ new TextDecoder().decode(new Uint8Array(result.asset?.videoData ?? new ArrayBuffer(0))),+ ).toBe("webcam bytes");+ });++ it("reports a reason when a buffered clip came back empty", async () => {+ const { handle } = fakeHandle({+ recordedBlobPromise: Promise.resolve(new Blob([])),+ });++ const result = await finalizeWebcamAsset(handle, FILE_NAME, 1_000, "macOS");++ expect(result.asset).toBeUndefined();+ expect(result.error).toBeTruthy();+ });++ it("reports the reason when the recording rejects mid-stream", async () => {+ // A failed disk write rejects recordedBlobPromise. That must surface, not+ // pass for a good recording and not vanish into a console.error.+ vi.spyOn(console, "error").mockImplementation(() => undefined);+ const { handle } = fakeHandle({+ recordedBlobPromise: Promise.reject(new Error("Failed to write recording chunk to disk")),+ });++ const result = await finalizeWebcamAsset(handle, FILE_NAME, 1_000, "macOS");++ expect(result.asset).toBeUndefined();+ expect(result.error).toBe("Failed to write recording chunk to disk");+ vi.restoreAllMocks();+ });++ it("stops a still-running recorder, and leaves an already-stopped one alone", async () => {+ const running = fakeHandle({ state: "recording", isStreaming: () => true });+ await finalizeWebcamAsset(running.handle, FILE_NAME, 1_000, "macOS");+ expect(running.stop).toHaveBeenCalledTimes(1);++ const stopped = fakeHandle({ state: "inactive", isStreaming: () => true });+ await finalizeWebcamAsset(stopped.handle, FILE_NAME, 1_000, "macOS");+ expect(stopped.stop).not.toHaveBeenCalled();+ });+});