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): name the camera the browser actually opened
EtienneLescot70c5b6f80726
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsxindex 7639936f6..14046bc39 100644--- a/src/components/launch/LaunchWindow.tsx+++ b/src/components/launch/LaunchWindow.tsx@@ -141,13 +141,19 @@ export function LaunchWindow() {// on its very first frame, and that `webcamDeviceId` is already the default// device when the button is clicked — so enabling the camera acquires the// right stream once instead of acquiring the default and then re-acquiring.+ //+ // Passing `webcamDeviceId` as the preferred device is what keeps the pick the+ // user made in the editor's Rec stage: this window is destroyed and rebuilt+ // for every recording, so the enumeration default would otherwise revert the+ // camera to whatever the OS lists first on each take.const {devices: cameraDevices,+ selectedDevice: selectedCamera,selectedDeviceId: selectedCameraId,setSelectedDeviceId: setSelectedCameraId,isLoading: isCameraDevicesLoading,error: cameraDevicesError,- } = useCameraDevices(true);+ } = useCameraDevices(true, webcamDeviceId);// The microphone list stays lazy: enumerating it asks for mic permission,// which would light the OS "in use" indicator just for opening the HUD.const {@@ -163,12 +169,18 @@ export function LaunchWindow() {}}, [selectedMicId, micDevices, setMicrophoneDeviceId, setMicrophoneDeviceName]);+ // Keyed on the chosen device's own fields, never on the `cameraDevices` array.+ // That array is rebuilt on every `devicechange`, and mirroring the selection+ // back on each rebuild put this effect in a tug-of-war with the preference+ // adoption inside `useCameraDevices`: the two wrote each other's value on+ // every commit and the HUD spun without ever settling.+ const selectedCameraLabel = selectedCamera?.label;useEffect(() => {if (selectedCameraId) {setWebcamDeviceId(selectedCameraId);- setWebcamDeviceName(cameraDevices.find((d) => d.deviceId === selectedCameraId)?.label);+ setWebcamDeviceName(selectedCameraLabel);}- }, [selectedCameraId, cameraDevices, setWebcamDeviceId, setWebcamDeviceName]);+ }, [selectedCameraId, selectedCameraLabel, setWebcamDeviceId, setWebcamDeviceName]);useEffect(() => {let cancelled = false;@@ -628,10 +640,31 @@ export function LaunchWindow() {setMicrophoneEnabled(!microphoneEnabled);}, [controlsLocked, microphoneEnabled, setMicrophoneEnabled]);+ /**+ * Write a camera choice back to the main-process recording prefs.+ *+ * The HUD used to be a reader of that SSOT and never a writer, while being+ * destroyed and rebuilt for every recording — so a camera picked here lived+ * exactly as long as one take, and the editor's Rec stage kept showing the+ * previous device. Best-effort on purpose: failing to persist a preference+ * must not stop a recording.+ */+ const persistCameraPrefs = useCallback(+ (patch: { camEnabled?: boolean; camDeviceId?: string }) => {+ void window.electronAPI?.setRecordingPrefs?.(patch).catch((error) => {+ console.warn("Failed to persist the camera preference:", error);+ });+ },+ [],+ );+const toggleWebcam = useCallback(() => {if (controlsLocked) return;- void setWebcamEnabled(!webcamEnabled);- }, [controlsLocked, setWebcamEnabled, webcamEnabled]);+ const next = !webcamEnabled;+ void setWebcamEnabled(next).then((ok) => {+ if (ok) persistCameraPrefs({ camEnabled: next });+ });+ }, [controlsLocked, persistCameraPrefs, setWebcamEnabled, webcamEnabled]);// Selecting a device never switches it on. If the device is already live the// recorder re-acquires on the id change; if it isn't, this just records which@@ -650,8 +683,9 @@ export function LaunchWindow() {setSelectedCameraId(device.deviceId);setWebcamDeviceId(device.deviceId);setWebcamDeviceName(device.label);+ persistCameraPrefs({ camDeviceId: device.deviceId });},- [setSelectedCameraId, setWebcamDeviceId, setWebcamDeviceName],+ [persistCameraPrefs, setSelectedCameraId, setWebcamDeviceId, setWebcamDeviceName],);const toggleDeviceSettings = useCallback(() => {diff --git a/src/hooks/useCameraDevices.loop.test.tsx b/src/hooks/useCameraDevices.loop.test.tsxnew file mode 100644index 000000000..97eb70df5--- /dev/null+++ b/src/hooks/useCameraDevices.loop.test.tsx@@ -0,0 +1,128 @@+// @vitest-environment jsdom+import { act, render, waitFor } from "@testing-library/react";+import { useEffect, useState } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useCameraDevices } from "./useCameraDevices";++/**+ * The HUD wires this hook into a cycle: it mirrors `selectedDevice` into the+ * recorder's `webcamDeviceId`, and hands that same value straight back as+ * `preferredDeviceId`. Testing the hook alone cannot see that — it takes both+ * halves in one tree — and the first version of the preference adoption spun at+ * ~1500 renders per 500 ms once a remembered-but-absent camera reappeared, with+ * the two effects writing each other's value on every commit. `webcamDeviceId`+ * is also a dependency of the recorder's getUserMedia effect, so the spin would+ * have hammered the camera hardware from the always-on recording toolbar.+ */++const devicechangeListeners: Array<() => void> = [];+let currentDevices: Array<{ kind: string; deviceId: string; label: string; groupId: string }> = [];++Object.defineProperty(global.navigator, "mediaDevices", {+ value: {+ enumerateDevices: vi.fn(async () => currentDevices),+ getUserMedia: vi.fn(),+ addEventListener: (_: string, cb: () => void) => devicechangeListeners.push(cb),+ removeEventListener: vi.fn(),+ },+ configurable: true,+});++const TWO_CAMERAS = [+ { kind: "videoinput", deviceId: "cam1", label: "VCam Camera", groupId: "g1" },+ { kind: "videoinput", deviceId: "cam2", label: "Logitech StreamCam", groupId: "g2" },+];++let renders = 0;+const observed = { selected: "", webcam: undefined as string | undefined };++/** Mirrors LaunchWindow's wiring: the hook's output feeds its own input. */+function Hud({ seedPrefs }: { seedPrefs: (set: (id: string) => void) => void }) {+ const [webcamDeviceId, setWebcamDeviceId] = useState<string | undefined>(undefined);+ const [, setWebcamDeviceName] = useState<string | undefined>(undefined);++ // useScreenRecorder seeds this from the main-process prefs, over IPC.+ useEffect(() => {+ seedPrefs(setWebcamDeviceId);+ }, [seedPrefs]);++ const { selectedDevice, selectedDeviceId } = useCameraDevices(true, webcamDeviceId);++ const selectedLabel = selectedDevice?.label;+ useEffect(() => {+ if (selectedDeviceId) {+ setWebcamDeviceId(selectedDeviceId);+ setWebcamDeviceName(selectedLabel);+ }+ }, [selectedDeviceId, selectedLabel]);++ renders += 1;+ observed.selected = selectedDeviceId;+ observed.webcam = webcamDeviceId;+ return null;+}++describe("useCameraDevices inside the HUD's write-back cycle", () => {+ beforeEach(() => {+ devicechangeListeners.length = 0;+ renders = 0;+ currentDevices = [...TWO_CAMERAS];+ });++ it("settles when a remembered camera that was absent finally appears", async () => {+ let seedNow: ((id: string) => void) | null = null;+ render(+ <Hud+ seedPrefs={(set) => {+ seedNow = set;+ }}+ />,+ );++ // Enumeration wins the race and falls back to the first device.+ await waitFor(() => {+ expect(observed.selected).toBe("cam1");+ });++ // The prefs land afterwards, naming a camera that is not plugged in yet —+ // a virtual camera whose app has not been started, say.+ await act(async () => {+ seedNow?.("camX");+ });+ expect(observed.selected).toBe("cam1");+ expect(observed.webcam).toBe("camX");++ // The user starts NVIDIA Broadcast, so camX shows up.+ currentDevices = [+ ...TWO_CAMERAS,+ { kind: "videoinput", deviceId: "camX", label: "Camera (NVIDIA Broadcast)", groupId: "g3" },+ ];+ const before = renders;+ await act(async () => {+ for (const notify of devicechangeListeners) notify();+ await new Promise((resolve) => setTimeout(resolve, 300));+ });++ // Both halves agree on the remembered camera, and the tree is quiet.+ expect(observed.selected).toBe("camX");+ expect(observed.webcam).toBe("camX");+ expect(renders - before).toBeLessThan(20);+ });++ it("stays quiet when a devicechange brings no actual change", async () => {+ render(<Hud seedPrefs={() => undefined} />);++ await waitFor(() => {+ expect(observed.selected).toBe("cam1");+ });++ const before = renders;+ await act(async () => {+ for (const notify of devicechangeListeners) notify();+ await new Promise((resolve) => setTimeout(resolve, 200));+ });++ expect(observed.selected).toBe("cam1");+ expect(renders - before).toBeLessThan(10);+ });+});diff --git a/src/hooks/useCameraDevices.test.ts b/src/hooks/useCameraDevices.test.tsindex 2bef6f046..a622ba78d 100644--- a/src/hooks/useCameraDevices.test.ts+++ b/src/hooks/useCameraDevices.test.ts@@ -85,6 +85,84 @@ describe("useCameraDevices", () => {expect(result.current.isLoading).toBe(false);});+ it("should prefer the restored device over the first enumerated one", async () => {+ const { result } = renderHook(() => useCameraDevices(true, "cam2"));++ await waitFor(() => {+ expect(result.current.selectedDeviceId).toBe("cam2");+ });+ });++ // The prefs arrive over IPC and routinely land after enumeration has already+ // settled on the first device. Losing the user's camera at that point is what+ // made a HUD rebuilt for a new recording revert to a virtual camera that emits+ // nothing, while the native helper was told to capture it by name.+ it("should adopt the restored device when it arrives after enumeration", async () => {+ const { result, rerender } = renderHook(+ ({ preferred }: { preferred?: string }) => useCameraDevices(true, preferred),+ { initialProps: { preferred: undefined as string | undefined } },+ );++ await waitFor(() => {+ expect(result.current.selectedDeviceId).toBe("cam1");+ });++ rerender({ preferred: "cam2" });++ await waitFor(() => {+ expect(result.current.selectedDeviceId).toBe("cam2");+ });+ });++ it("should ignore a restored device that is no longer plugged in", async () => {+ const { result } = renderHook(() => useCameraDevices(true, "cam-that-left"));++ await waitFor(() => {+ expect(result.current.selectedDeviceId).toBe("cam1");+ });+ });++ /**+ * The HUD feeds this hook's own output back in: `LaunchWindow` writes+ * `selectedDeviceId` into the recorder's `webcamDeviceId`, and hands that same+ * value back as `preferredDeviceId`. A rule that re-asserts the preference on+ * every render would ping-pong with that write-back forever, so the loop this+ * closes has to settle. Counts renders rather than asserting a value: a+ * converging hook renders a handful of times, one that oscillates renders+ * without end.+ */+ it("settles instead of oscillating when its own selection is fed back as the preference", async () => {+ let renders = 0;+ const { result, rerender } = renderHook(+ ({ preferred }: { preferred?: string }) => {+ renders += 1;+ return useCameraDevices(true, preferred);+ },+ { initialProps: { preferred: undefined as string | undefined } },+ );++ await waitFor(() => {+ expect(result.current.selectedDeviceId).toBe("cam1");+ });++ // The HUD hands back whatever this hook just selected, then the late prefs+ // name a different camera, which the hook adopts and hands back in turn.+ rerender({ preferred: result.current.selectedDeviceId });+ rerender({ preferred: "cam2" });++ await waitFor(() => {+ expect(result.current.selectedDeviceId).toBe("cam2");+ });++ const settled = renders;+ rerender({ preferred: result.current.selectedDeviceId });+ await new Promise((resolve) => setTimeout(resolve, 50));++ // Only the render this test asked for; the effect no longer has anything to say.+ expect(renders - settled).toBeLessThanOrEqual(2);+ expect(result.current.selectedDeviceId).toBe("cam2");+ });+it("should fall back to first available device when selected device is unplugged", async () => {const { result } = renderHook(() => useCameraDevices(true));diff --git a/src/hooks/useCameraDevices.ts b/src/hooks/useCameraDevices.tsindex bf402c7f0..6a2b45f5f 100644--- a/src/hooks/useCameraDevices.ts+++ b/src/hooks/useCameraDevices.ts@@ -6,13 +6,24 @@ export interface CameraDevice {groupId: string;}-export function useCameraDevices(enabled: boolean = false) {+/**+ * @param preferredDeviceId The camera the session already settled on — typically+ * the one restored from the recording prefs. It wins over "first in the list",+ * because the list order is the OS enumeration order and the first entry is+ * routinely a virtual camera that emits nothing. Without this, a HUD rebuilt for+ * a new recording silently reverted the user's pick to that first device, and+ * only the *name* reached the native helper, so the preview showed the chosen+ * camera while the recording captured the other one.+ */+export function useCameraDevices(enabled: boolean = false, preferredDeviceId?: string) {const [devices, setDevices] = useState<CameraDevice[]>([]);const [selectedDeviceId, setSelectedDeviceId] = useState<string>("");const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string | null>(null);const selectedDeviceIdRef = useRef(selectedDeviceId);selectedDeviceIdRef.current = selectedDeviceId;+ const preferredDeviceIdRef = useRef(preferredDeviceId);+ preferredDeviceIdRef.current = preferredDeviceId;useEffect(() => {if (!enabled) return;@@ -39,7 +50,11 @@ export function useCameraDevices(enabled: boolean = false) {const currentId = selectedDeviceIdRef.current;const stillAvailable = videoInputs.some((d) => d.deviceId === currentId);if (!currentId || !stillAvailable) {- setSelectedDeviceId(videoInputs[0]?.deviceId ?? "");+ const preferredId = preferredDeviceIdRef.current;+ const preferred = preferredId+ ? videoInputs.find((d) => d.deviceId === preferredId)+ : undefined;+ setSelectedDeviceId(preferred?.deviceId ?? videoInputs[0]?.deviceId ?? "");}setIsLoading(false);}@@ -60,5 +75,25 @@ export function useCameraDevices(enabled: boolean = false) {};}, [enabled]);- return { devices, selectedDeviceId, setSelectedDeviceId, isLoading, error };+ // The preference is restored over IPC while this list is being enumerated, so+ // it routinely lands *after* the effect above has already fallen back to the+ // first device. Adopting it here is what makes the two async sources converge+ // on the same camera instead of racing.+ useEffect(() => {+ if (!enabled || !preferredDeviceId) return;+ if (preferredDeviceId === selectedDeviceId) return;+ if (!devices.some((d) => d.deviceId === preferredDeviceId)) return;+ setSelectedDeviceId(preferredDeviceId);+ }, [enabled, preferredDeviceId, devices, selectedDeviceId]);++ // The selected entry itself, so callers can react to "which camera is chosen"+ // without depending on the identity of `devices`. `loadDevices` rebuilds that+ // array on every `devicechange`, and a caller that mirrors the selection back+ // into its own state — the HUD does — would re-fire on each rebuild and fight+ // the effect above for the value, swapping the two on every commit and never+ // settling. Depending on this object's fields instead makes the write-back+ // fire only when the chosen camera really changed.+ const selectedDevice = devices.find((d) => d.deviceId === selectedDeviceId);++ return { devices, selectedDevice, selectedDeviceId, setSelectedDeviceId, isLoading, error };}diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex a6da24d74..4c7c7a110 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -20,6 +20,7 @@ import type { CursorCaptureMode, RecordedVideoAssetInput } from "@/lib/recordingimport { requestCameraAccess } from "@/lib/requestCameraAccess";import { loadUserPreferences, saveUserPreferences } from "@/lib/userPreferences";import { createRecorderHandle, type RecorderHandle } from "./recorderHandle";+import { webcamDeviceIdentityFrom } from "./webcamDeviceIdentity";const TARGET_FRAME_RATE = 60;const MIN_FRAME_RATE = 30;@@ -318,6 +319,18 @@ export function useScreenRecorder(): UseScreenRecorderReturn {}}, []);+ /**+ * The camera to name in a native capture request. See+ * `webcamDeviceIdentityFrom` for why it is read off the live track rather than+ * off this hook's two separate pieces of state. Must be called before+ * `stopWebcamPreviewStream()`, which is why the Windows path captures it up+ * front instead of at the point of use.+ */+ const readWebcamDeviceIdentity = useCallback(+ () => webcamDeviceIdentityFrom(webcamStream.current, webcamDeviceId, webcamDeviceName),+ [webcamDeviceId, webcamDeviceName],+ );+const stopWebcamPreviewStream = useCallback(() => {if (!webcamStream.current) {return;@@ -1058,11 +1071,16 @@ export function useScreenRecorder(): UseScreenRecorderReturn {const displayId = Number(selectedSource.display_id);const sourceType = selectedSource.id.startsWith("window:") ? "window" : "display";const windowHandle = parseWindowHandleFromSourceId(selectedSource.id);+ let webcamIdentity = { deviceId: webcamDeviceId, deviceName: webcamDeviceName };if (webcamEnabled) {await waitForWebcamReady();if (!isCountdownRunActive(countdownRunToken)) {return true;}+ // Read the device off the live track before letting go of it: this is+ // the only moment where the id and the name are known to describe the+ // same camera (see readWebcamDeviceIdentity).+ webcamIdentity = readWebcamDeviceIdentity();// Release the renderer-side validation stream before asking the native// helper to open the same device: most webcams only allow one exclusive// capture session, and native (Media Foundation/DirectShow) now owns@@ -1098,8 +1116,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn {},webcam: {enabled: webcamEnabled,- deviceId: webcamDeviceId,- deviceName: webcamDeviceName,+ deviceId: webcamIdentity.deviceId,+ deviceName: webcamIdentity.deviceName,width: 0,height: 0,fps: WEBCAM_TARGET_FRAME_RATE,@@ -1248,8 +1266,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {},webcam: {enabled: webcamEnabled,- deviceId: webcamDeviceId,- deviceName: webcamDeviceName,+ // Same pairing rule as the Windows path; here the stream is still+ // open, so the identity can be read at the point of use.+ ...readWebcamDeviceIdentity(),width: 0,height: 0,fps: WEBCAM_TARGET_FRAME_RATE,diff --git a/src/hooks/webcamDeviceIdentity.test.ts b/src/hooks/webcamDeviceIdentity.test.tsnew file mode 100644index 000000000..db72bb645--- /dev/null+++ b/src/hooks/webcamDeviceIdentity.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import { webcamDeviceIdentityFrom } from "./webcamDeviceIdentity";++function streamWith(track: Partial<MediaStreamTrack> | null): MediaStream {+ return { getVideoTracks: () => (track ? [track] : []) } as unknown as MediaStream;+}++describe("webcamDeviceIdentityFrom", () => {+ it("takes both halves from the track the browser opened", () => {+ const stream = streamWith({+ label: "Camera (NVIDIA Broadcast)",+ getSettings: () => ({ deviceId: "nvidia-id" }),+ } as Partial<MediaStreamTrack>);++ expect(webcamDeviceIdentityFrom(stream, "stale-id", "VCam Camera")).toEqual({+ deviceId: "nvidia-id",+ deviceName: "Camera (NVIDIA Broadcast)",+ });+ });++ /**+ * The bug this exists to prevent. The HUD's own enumeration defaulted the NAME+ * to the first device — a virtual camera that emits nothing — while the prefs+ * restored the ID of the camera the user actually picked. Chromium honoured+ * the id and previewed the right camera; the native helper matched on the name+ * and recorded the wrong one, producing a zero-byte webcam file.+ */+ it("never pairs one camera's id with another camera's name", () => {+ const stream = streamWith({+ label: "Logitech StreamCam (046d:0893)",+ getSettings: () => ({ deviceId: "logitech-id" }),+ } as Partial<MediaStreamTrack>);++ const identity = webcamDeviceIdentityFrom(stream, "vcam-id", "VCam Camera");++ expect(identity.deviceId).toBe("logitech-id");+ expect(identity.deviceName).toBe("Logitech StreamCam (046d:0893)");+ });++ it("falls back to the known selection when there is no stream", () => {+ expect(webcamDeviceIdentityFrom(null, "picked-id", "Picked Camera")).toEqual({+ deviceId: "picked-id",+ deviceName: "Picked Camera",+ });+ });++ it("falls back to the known selection when there is no video track", () => {+ expect(webcamDeviceIdentityFrom(streamWith(null), "picked-id", "Picked Camera")).toEqual({+ deviceId: "picked-id",+ deviceName: "Picked Camera",+ });+ });++ // Chromium withholds labels until camera permission has been granted, and+ // reports an empty deviceId under some constraint combinations. Neither is a+ // reason to send an empty name to a helper that matches devices by name.+ it("keeps the known values when the track answers with empty strings", () => {+ const stream = streamWith({+ label: "",+ getSettings: () => ({ deviceId: "" }),+ } as Partial<MediaStreamTrack>);++ expect(webcamDeviceIdentityFrom(stream, "picked-id", "Picked Camera")).toEqual({+ deviceId: "picked-id",+ deviceName: "Picked Camera",+ });+ });+});diff --git a/src/hooks/webcamDeviceIdentity.ts b/src/hooks/webcamDeviceIdentity.tsnew file mode 100644index 000000000..070a67d4d--- /dev/null+++ b/src/hooks/webcamDeviceIdentity.ts@@ -0,0 +1,40 @@+export interface WebcamDeviceIdentity {+ deviceId: string | undefined;+ deviceName: string | undefined;+}++/**+ * The camera to name in a native capture request, read off the track the browser+ * actually opened rather than off two separate pieces of React state.+ *+ * Those two used to be fed by two independent async sources — the id restored+ * from the recording prefs over IPC, the name from the HUD window's own+ * `enumerateDevices()` — and whichever settled last won on its own. A request+ * could therefore carry one camera's id next to another camera's name, and since+ * Chromium selects by id while the native Windows helper matches by NAME, the+ * preview showed the chosen camera while the recording captured a different one+ * (getopenscreen/openscreen#387).+ *+ * `track.label` and `track.getSettings().deviceId` describe the same device by+ * construction, which is what makes the pair impossible to mismatch. The+ * fallbacks cover the cases where the track cannot answer: no stream yet, or a+ * label withheld until camera permission has been granted.+ *+ * Lives in its own module rather than inside `useScreenRecorder` so it can be+ * tested without dragging in the i18n context that hook depends on.+ */+export function webcamDeviceIdentityFrom(+ stream: MediaStream | null | undefined,+ fallbackDeviceId: string | undefined,+ fallbackDeviceName: string | undefined,+): WebcamDeviceIdentity {+ const track = stream?.getVideoTracks()[0];+ if (!track) {+ return { deviceId: fallbackDeviceId, deviceName: fallbackDeviceName };+ }++ return {+ deviceId: track.getSettings?.().deviceId || fallbackDeviceId,+ deviceName: track.label || fallbackDeviceName,+ };+}