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(recording): reconcile main's recording fixes into the v4 recording path

Etienne Lescot03fce380e425
diff --git a/electron/native/README.md b/electron/native/README.md
index 3577706e1..6b20fd8aa 100644
--- a/electron/native/README.md
+++ b/electron/native/README.md
@@ -83,7 +83,11 @@ Current V2 JSON shape:
The current helper implementation supports display/window video capture, system audio loopback, selected-microphone capture, Media Foundation webcam capture, and a DirectShow webcam fallback for virtual cameras that are not exposed through Media Foundation. Webcam frames are currently composed into the primary MP4 as a bottom-right picture-in-picture overlay. Browser `deviceId` values do not always map to Media Foundation symbolic links or WASAPI endpoint IDs, so the renderer passes both browser IDs and user-visible device names. For microphones, the helper tries the requested WASAPI endpoint ID first, then resolves an active capture endpoint by `microphoneDeviceName`, then falls back to the default endpoint. For webcams, Electron resolves a matching DirectShow filter CLSID for the selected label; the helper uses Media Foundation first, then that exact DirectShow filter when the requested camera is absent from Media Foundation.
-Encoder diagnostic on sink-writer failure: when `MFCreateSinkWriterFromURL` fails, the helper logs the registered H.264 video encoder MFT count (via `MFTEnumEx`), the registered AAC encoder count when audio was requested, and the hex HRESULT. If no H.264 encoder is registered, it additionally emits the four-bullet actionable error (missing Media Feature Pack / GPU driver registration / empty `HKLM:\SOFTWARE\Microsoft\Windows Media Foundation\Transforms` / reboot). If an H.264 encoder IS registered but the sink writer still failed, it logs a hint pointing at invalid output path, missing MP4 mux, or GPU driver incompatibility. The diagnostic runs only on the failure path — there is no pre-flight gating check, because `MFTEnumEx` and `MFCreateSinkWriterFromURL` can disagree about which H.264 encoders are "available" in non-interactive / Session 0 contexts, and a pre-flight zero-count would block a recording the sink writer can otherwise complete.
+Encoder selection: by default the helper keeps the existing sink-writer path first. If that path fails while setting up H.264, it retries with the Microsoft software H.264 encoder (`mfh264enc.dll`). The key of this retry is registering that encoder locally in the helper process via `MFTRegisterLocalByCLSID`, which makes a software H.264 encoder available even when the machine's hardware encoders are missing or broken; hardware transforms are disabled for the retry only as a secondary guard so the sink writer prefers the locally registered software encoder, not as the fallback mechanism itself. Set `preferSoftwareEncoder: true` in the helper JSON, or set `OPENSCREEN_WGC_PREFER_SOFTWARE_ENCODER=true` before launching Electron, to force the software path from the first attempt.
+
+The helper reports the outcome through the `encoder-selection` stdout event (`video` is `default`, `software-preferred`, or `software-fallback`). When the app sees `software-fallback` — the default encoder failed and the helper switched on its own — it shows a small dismissible notice in the recording HUD with a "Don't show again" option, because software encoding can raise CPU usage. An explicit `software-preferred` selection shows no notice, and the event stays available for diagnostics either way.
+
+Encoder diagnostic on final sink-writer failure: when the final `MFCreateSinkWriterFromURL` attempt fails, the helper logs the registered H.264 video encoder MFT count (via `MFTEnumEx`), the registered AAC encoder count when audio was requested, and the hex HRESULT. If no H.264 encoder is registered, it additionally emits the four-bullet actionable error (missing Media Feature Pack / GPU driver registration / empty `HKLM:\SOFTWARE\Microsoft\Windows Media Foundation\Transforms` / reboot). If an H.264 encoder IS registered but the sink writer still failed, it logs a hint pointing at invalid output path, missing MP4 mux, or GPU driver incompatibility. There is still no fail-fast pre-flight gate because `MFTEnumEx` and `MFCreateSinkWriterFromURL` can disagree about which H.264 encoders are available in non-interactive / Session 0 contexts.
Smoke-test the helper with:
diff --git a/src/components/video-editor/VideoPlayback.test.ts b/src/components/video-editor/VideoPlayback.test.ts
deleted file mode 100644
index 165512851..000000000
--- a/src/components/video-editor/VideoPlayback.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { createWebGLContextLostHandler } from "@/components/video-editor/VideoPlayback";
-
-describe("createWebGLContextLostHandler", () => {
- it("calls preventDefault on the lost event so Chromium can attempt restoration", () => {
- const regenerate = vi.fn();
- const handler = createWebGLContextLostHandler({ generation: 0, regenerate });
-
- const event = new Event("webglcontextlost");
- const preventDefaultSpy = vi.spyOn(event, "preventDefault");
- handler(event);
-
- expect(preventDefaultSpy).toHaveBeenCalledOnce();
- });
-
- it("triggers the regenerate callback so React can rebuild the Pixi app", () => {
- const regenerate = vi.fn();
- const handler = createWebGLContextLostHandler({ generation: 0, regenerate });
-
- handler(new Event("webglcontextlost"));
-
- expect(regenerate).toHaveBeenCalledOnce();
- });
-
- it("logs the generation captured at handler construction time", () => {
- const regenerate = vi.fn();
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
- const handler = createWebGLContextLostHandler({ generation: 7, regenerate });
-
- handler(new Event("webglcontextlost"));
-
- expect(warnSpy).toHaveBeenCalledWith(
- "[VideoPlayback] WebGL context lost, recreating Pixi app",
- { generation: 7 },
- );
- warnSpy.mockRestore();
- });
-});
diff --git a/src/components/video-editor/videoPlayback/cursorRenderer.test.ts b/src/components/video-editor/videoPlayback/cursorRenderer.test.ts
deleted file mode 100644
index e604510dd..000000000
--- a/src/components/video-editor/videoPlayback/cursorRenderer.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { CropRegion } from "../types";
-import { type CursorViewportRect, mapCursorToCroppedViewport } from "./cursorRenderer";
-
-const FULL_CROP: CropRegion = { x: 0, y: 0, width: 1, height: 1 };
-const VIEWPORT: CursorViewportRect = { x: 100, y: 50, width: 800, height: 400 };
-
-describe("mapCursorToCroppedViewport", () => {
- it("maps positions directly onto the viewport when there is no crop", () => {
- const center = mapCursorToCroppedViewport(0.5, 0.5, VIEWPORT, FULL_CROP);
- expect(center).toEqual({ px: 500, py: 250 });
-
- const topLeft = mapCursorToCroppedViewport(0, 0, VIEWPORT, FULL_CROP);
- expect(topLeft).toEqual({ px: 100, py: 50 });
-
- const bottomRight = mapCursorToCroppedViewport(1, 1, VIEWPORT, FULL_CROP);
- expect(bottomRight).toEqual({ px: 900, py: 450 });
- });
-
- it("re-normalizes a full-frame position into the cropped viewport", () => {
- // Crop the right-bottom half of the frame. A telemetry point at the frame
- // center (0.5, 0.5) sits at the top-left corner of this crop.
- const crop: CropRegion = { x: 0.5, y: 0.5, width: 0.5, height: 0.5 };
-
- const atCropOrigin = mapCursorToCroppedViewport(0.5, 0.5, VIEWPORT, crop);
- expect(atCropOrigin).toEqual({ px: 100, py: 50 });
-
- // The frame center of the crop (0.75, 0.75) maps to the viewport center.
- const atCropCenter = mapCursorToCroppedViewport(0.75, 0.75, VIEWPORT, crop);
- expect(atCropCenter).toEqual({ px: 500, py: 250 });
- });
-
- it("does not drift: a point on the visible cropped content keeps its relative offset", () => {
- // Regression test for issue #64. Before the fix the cursor was projected with
- // the full-frame normalized coordinate directly onto the cropped viewport,
- // which shifted (drifted) it away from the underlying pixel after cropping.
- const crop: CropRegion = { x: 0.2, y: 0.1, width: 0.6, height: 0.6 };
- const normX = 0.6; // inside the crop, but offset from the crop's own center
- const normY = 0.4;
-
- const mapped = mapCursorToCroppedViewport(normX, normY, VIEWPORT, crop);
-
- // Expected: re-normalize against the crop, then project onto the viewport.
- const expectedPx = VIEWPORT.x + ((normX - crop.x) / crop.width) * VIEWPORT.width;
- const expectedPy = VIEWPORT.y + ((normY - crop.y) / crop.height) * VIEWPORT.height;
- expect(mapped).toEqual({ px: expectedPx, py: expectedPy });
-
- // The naive (buggy) projection would have produced a different point.
- const buggyPx = VIEWPORT.x + normX * VIEWPORT.width;
- expect(mapped!.px).not.toBeCloseTo(buggyPx, 5);
- });
-
- it("returns null when the position falls outside the visible crop", () => {
- const crop: CropRegion = { x: 0.5, y: 0.5, width: 0.5, height: 0.5 };
- // (0.1, 0.1) is in the top-left of the frame, outside the bottom-right crop.
- expect(mapCursorToCroppedViewport(0.1, 0.1, VIEWPORT, crop)).toBeNull();
- });
-
- it("returns null for a degenerate crop", () => {
- expect(
- mapCursorToCroppedViewport(0.5, 0.5, VIEWPORT, { x: 0, y: 0, width: 0, height: 0 }),
- ).toBeNull();
- });
-});
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index f2be91d1d..185dc3249 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -2,6 +2,7 @@ import { fixWebmDuration } from "@fix-webm-duration/fix";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { useScopedT } from "@/contexts/I18nContext";
+import { MIC_GAIN_BOOST, mixAudioTracks } from "@/lib/audioMix";
import {
type NativeMacRecordingRequest,
parseMacDisplayIdFromSourceId,
@@ -13,6 +14,7 @@ import {
} from "@/lib/nativeWindowsRecording";
import type { CursorCaptureMode, RecordedVideoAssetInput } from "@/lib/recordingSession";
import { requestCameraAccess } from "@/lib/requestCameraAccess";
+import { loadUserPreferences, saveUserPreferences } from "@/lib/userPreferences";
import { createRecorderHandle, type RecorderHandle } from "./recorderHandle";
const TARGET_FRAME_RATE = 60;
@@ -44,7 +46,6 @@ const WEBCAM_FILE_SUFFIX = "-webcam";
const AUDIO_BITRATE_VOICE = 128_000;
const AUDIO_BITRATE_SYSTEM = 192_000;
-const MIC_GAIN_BOOST = 1.4;
const WEBCAM_TARGET_FRAME_RATE = 30;
type UseScreenRecorderReturn = {
@@ -73,6 +74,8 @@ type UseScreenRecorderReturn = {
setWebcamEnabled: (enabled: boolean) => Promise<boolean>;
cursorCaptureMode: CursorCaptureMode;
setCursorCaptureMode: (mode: CursorCaptureMode) => void;
+ softwareEncoderFallbackNoticeVisible: boolean;
+ dismissSoftwareEncoderFallbackNotice: (dontShowAgain?: boolean) => void;
};
type NativeWindowsRecordingHandle = {
@@ -110,6 +113,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const [systemAudioEnabled, setSystemAudioEnabled] = useState(false);
const [webcamEnabled, setWebcamEnabledState] = useState(false);
const [cursorCaptureMode, setCursorCaptureMode] = useState<CursorCaptureMode>("editable-overlay");
+ const [softwareEncoderFallbackNoticeVisible, setSoftwareEncoderFallbackNoticeVisible] =
+ useState(false);
// Seed from the main-process recording-prefs SSOT on mount, so choices
// made in the editor's Rec-mode stage (a different renderer window) carry
@@ -835,6 +840,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}
const request: NativeWindowsRecordingRequest = {
recordingId: activeRecordingId,
+ preferSoftwareEncoder: loadUserPreferences().preferSoftwareEncoder,
source: {
type: sourceType,
sourceId: selectedSource.id,
@@ -874,6 +880,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
throw new Error(result.error ?? "Native Windows capture failed.");
}
+ // Tell the user when the helper silently switched away from the default
+ // GPU encoder; an explicit software-preferred selection needs no notice.
+ setSoftwareEncoderFallbackNoticeVisible(
+ result.videoEncoderSelection === "software-fallback" &&
+ !loadUserPreferences().hideSoftwareEncoderFallbackNotice,
+ );
+
recordingId.current = result.recordingId;
nativeWindowsRecording.current = {
recordingId: result.recordingId,
@@ -963,9 +976,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}
}
if (!isCountdownRunActive(countdownRunToken)) {
- if (nativeWebcamRecorder && nativeWebcamRecorder.recorder.state !== "inactive") {
- nativeWebcamRecorder.recorder.stop();
- }
return true;
}
const request: NativeMacRecordingRequest = {
@@ -1012,15 +1022,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
};
const result = await window.electronAPI.startNativeMacRecording(request);
if (!result.success || !result.recordingId) {
- if (nativeWebcamRecorder && nativeWebcamRecorder.recorder.state !== "inactive") {
- nativeWebcamRecorder.recorder.stop();
- }
throw new Error(result.error ?? "Native macOS capture failed.");
}
if (!isCountdownRunActive(countdownRunToken)) {
- if (nativeWebcamRecorder && nativeWebcamRecorder.recorder.state !== "inactive") {
- nativeWebcamRecorder.recorder.stop();
- }
await window.electronAPI.stopNativeMacRecording(true);
return true;
}
@@ -1168,23 +1172,27 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
return;
}
- let screenMediaStream: MediaStream;
- const platform = await window.electronAPI.getPlatform();
+ // Capture screen + microphone in parallel: the gap between the two
+ // `getUserMedia` calls is the dominant source of the mic-vs-video lag at the
+ // start of the recording (issue #57).
+ const screenCapture = (async (): Promise<MediaStream> => {
+ const platform = await window.electronAPI.getPlatform();
+
+ if (platform === "win32") {
+ // getDisplayMedia + setDisplayMediaRequestHandler (main.ts) supplies the
+ // pre-selected source. Editable cursor mode excludes the system cursor so
+ // the editor can render a replacement; system mode bakes it into the video.
+ return navigator.mediaDevices.getDisplayMedia({
+ video: {
+ cursor: cursorCaptureMode === "editable-overlay" ? "never" : "always",
+ width: { max: TARGET_WIDTH },
+ height: { max: TARGET_HEIGHT },
+ frameRate: { ideal: TARGET_FRAME_RATE },
+ } as MediaTrackConstraints,
+ audio: systemAudioEnabled,
+ } as DisplayMediaStreamOptions);
+ }
- if (platform === "win32") {
- // getDisplayMedia + setDisplayMediaRequestHandler (main.ts) supplies the
- // pre-selected source. Editable cursor mode excludes the system cursor so
- // the editor can render a replacement; system mode bakes it into the video.
- screenMediaStream = await navigator.mediaDevices.getDisplayMedia({
- video: {
- cursor: cursorCaptureMode === "editable-overlay" ? "never" : "always",
- width: { max: TARGET_WIDTH },
- height: { max: TARGET_HEIGHT },
- frameRate: { ideal: TARGET_FRAME_RATE },
- } as MediaTrackConstraints,
- audio: systemAudioEnabled,
- } as DisplayMediaStreamOptions);
- } else {
const videoConstraints = {
mandatory: {
chromeMediaSource: CHROME_MEDIA_SOURCE,
@@ -1198,7 +1206,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
if (systemAudioEnabled) {
try {
- screenMediaStream = await navigator.mediaDevices.getUserMedia({
+ return navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: CHROME_MEDIA_SOURCE,
@@ -1210,48 +1218,66 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
} catch (audioErr) {
console.warn("System audio capture failed, falling back to video-only:", audioErr);
toast.error(t("recording.systemAudioUnavailable"));
- screenMediaStream = await navigator.mediaDevices.getUserMedia({
+ return navigator.mediaDevices.getUserMedia({
audio: false,
video: videoConstraints,
} as unknown as MediaStreamConstraints);
}
- } else {
- screenMediaStream = await navigator.mediaDevices.getUserMedia({
- audio: false,
- video: videoConstraints,
- } as unknown as MediaStreamConstraints);
}
- }
- screenStream.current = screenMediaStream;
- if (!isCountdownRunActive(countdownRunToken)) {
- teardownMedia();
- return;
- }
+ return navigator.mediaDevices.getUserMedia({
+ audio: false,
+ video: videoConstraints,
+ } as unknown as MediaStreamConstraints);
+ })();
- if (microphoneEnabled) {
- try {
- microphoneStream.current = await navigator.mediaDevices.getUserMedia({
- audio: microphoneDeviceId
- ? {
- deviceId: { exact: microphoneDeviceId },
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true,
- }
- : {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true,
- },
- video: false,
+ const micCapture: Promise<MediaStream | null> = microphoneEnabled
+ ? (async () => {
+ try {
+ return await navigator.mediaDevices.getUserMedia({
+ audio: microphoneDeviceId
+ ? {
+ deviceId: { exact: microphoneDeviceId },
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ }
+ : {
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ },
+ video: false,
+ });
+ } catch (audioError) {
+ console.warn("Failed to get microphone access:", audioError);
+ toast.error(t("recording.microphoneDenied"));
+ setMicrophoneEnabled(false);
+ return null;
+ }
+ })()
+ : Promise.resolve(null);
+
+ // Await both in-flight captures. If the screen capture rejects it would
+ // otherwise orphan a mic stream that resolved in parallel (leaving the
+ // screen/mic indicator on), so stop that stream before rethrowing.
+ let screenMediaStream: MediaStream;
+ try {
+ screenMediaStream = await screenCapture;
+ } catch (error) {
+ void micCapture
+ .then((micStream) => micStream?.getTracks().forEach((track) => track.stop()))
+ .catch(() => {
+ // Mic capture itself failed too; nothing left to stop.
});
- } catch (audioError) {
- console.warn("Failed to get microphone access:", audioError);
- toast.error(t("recording.microphoneDenied"));
- setMicrophoneEnabled(false);
- }
+ throw error;
}
+ const micMediaStream = await micCapture;
+
+ // Assign the refs before the cancellation check below so teardownMedia() can
+ // stop the freshly acquired streams if the countdown was cancelled mid-capture.
+ screenStream.current = screenMediaStream;
+ microphoneStream.current = micMediaStream;
if (!isCountdownRunActive(countdownRunToken)) {
teardownMedia();
@@ -1294,21 +1320,15 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const systemAudioTrack = screenMediaStream.getAudioTracks()[0];
const micAudioTrack = microphoneStream.current?.getAudioTracks()[0];
- if (systemAudioTrack && micAudioTrack) {
- const ctx = new AudioContext();
- mixingContext.current = ctx;
- const systemSource = ctx.createMediaStreamSource(new MediaStream([systemAudioTrack]));
- const micSource = ctx.createMediaStreamSource(new MediaStream([micAudioTrack]));
- const micGain = ctx.createGain();
- micGain.gain.value = MIC_GAIN_BOOST;
- const destination = ctx.createMediaStreamDestination();
- systemSource.connect(destination);
- micSource.connect(micGain).connect(destination);
- stream.current.addTrack(destination.stream.getAudioTracks()[0]);
- } else if (systemAudioTrack) {
- stream.current.addTrack(systemAudioTrack);
- } else if (micAudioTrack) {
- stream.current.addTrack(micAudioTrack);
+ const { context: mixingCtx, track: mixedTrack } = mixAudioTracks({
+ systemAudioTrack,
+ micAudioTrack,
+ });
+ if (mixingCtx) {
+ mixingContext.current = mixingCtx;
+ }
+ if (mixedTrack) {
+ stream.current.addTrack(mixedTrack);
}
try {
@@ -1674,6 +1694,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}
};
+ const dismissSoftwareEncoderFallbackNotice = (dontShowAgain = false) => {
+ if (dontShowAgain) {
+ saveUserPreferences({ hideSoftwareEncoderFallbackNotice: true });
+ }
+ setSoftwareEncoderFallbackNoticeVisible(false);
+ };
+
return {
recording,
paused,
@@ -1700,5 +1727,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
setWebcamEnabled,
cursorCaptureMode,
setCursorCaptureMode,
+ softwareEncoderFallbackNoticeVisible,
+ dismissSoftwareEncoderFallbackNotice,
};
}
diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.ts
index 8386ef9ca..7f57bce5f 100644
--- a/src/lib/ai-edition/document/migrate.ts
+++ b/src/lib/ai-edition/document/migrate.ts
@@ -275,6 +275,7 @@ export function migrateAxcutDocumentToProjectData(input: AxcutDocument): EditorP
padding: 50,
cropRegion: { x: 0, y: 0, width: 1, height: 1 } as CropRegion,
zoomRegions: [],
+ cameraFullscreenRegions: [],
autoZoomEnabled: false,
autoFocusAll: false,
trimRegions,