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): answer the review on the microphone fix

EtienneLescotb7c9b495f76d
diff --git a/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp b/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp
index a65031e83..86364ab0c 100644
--- a/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp
+++ b/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp
@@ -168,19 +168,24 @@ bool WasapiLoopbackCapture::initialize(WasapiCaptureEndpoint endpoint, const std
}
}
- // A microphone was asked for and neither its id nor its name could name a
- // device, so the recording is about to capture whatever Windows calls the
- // default input. That is worth saying out loud: the caller sends an empty
- // name whenever it could not resolve one in time, and the take then sounds
- // like the wrong microphone with nothing anywhere explaining why
- // (getopenscreen/openscreen#404).
- if (endpoint == WasapiCaptureEndpoint::Microphone && !device_ && deviceName.empty()) {
- std::cerr << "{\"event\":\"warning\",\"code\":\"microphone-defaulted\","
- "\"message\":\"No microphone name was supplied; capturing the default input\"}"
- << std::endl;
- }
-
if (!device_) {
+ // A particular microphone was asked for and nothing here could find it,
+ // so the recording is about to capture whatever Windows calls the default
+ // input. Worth saying out loud, and keyed on the OUTCOME rather than on
+ // which lookup failed: the caller sends an empty name when it could not
+ // resolve one in time, but a name that simply matches no endpoint lands
+ // in exactly the same place. Either way the take sounds like the wrong
+ // microphone with nothing explaining why (getopenscreen/openscreen#404).
+ const bool wantedAParticularMicrophone =
+ endpoint == WasapiCaptureEndpoint::Microphone &&
+ ((!deviceId.empty() && deviceId != L"default") || !deviceName.empty());
+ if (wantedAParticularMicrophone) {
+ std::cerr << "{\"event\":\"warning\",\"code\":\"microphone-defaulted\","
+ "\"message\":\"The requested microphone could not be resolved; "
+ "capturing the default input\"}"
+ << std::endl;
+ }
+
const EDataFlow flow =
endpoint == WasapiCaptureEndpoint::SystemLoopback ? eRender : eCapture;
hr = deviceEnumerator_->GetDefaultAudioEndpoint(flow, eConsole, &device_);
diff --git a/electron/recording/nativeWindowsCaptureStop.test.ts b/electron/recording/nativeWindowsCaptureStop.test.ts
index 224b3d972..8c1d48caf 100644
--- a/electron/recording/nativeWindowsCaptureStop.test.ts
+++ b/electron/recording/nativeWindowsCaptureStop.test.ts
@@ -101,10 +101,19 @@ describe("readWebcamUnavailable", () => {
});
describe("readMicrophoneDefaulted", () => {
- it("sees the helper falling back to the default input", () => {
+ // The helper keys the event on the OUTCOME — it ended up on the default input
+ // — not on which lookup failed, so both routes to that fallback land here.
+ it("sees the fallback when no microphone name was supplied", () => {
+ const output =
+ '{"event":"warning","code":"microphone-defaulted","message":"The requested microphone could not be resolved; capturing the default input"}\n' +
+ "Recording started\n";
+ expect(readMicrophoneDefaulted(output)).toBe(true);
+ });
+
+ it("sees it when a supplied name matched no endpoint", () => {
const output =
"WARNING: Could not resolve microphone by name; using default capture endpoint\n" +
- '{"event":"warning","code":"microphone-defaulted","message":"No microphone name was supplied; capturing the default input"}\n';
+ '{"event":"warning","code":"microphone-defaulted","message":"The requested microphone could not be resolved; capturing the default input"}\n';
expect(readMicrophoneDefaulted(output)).toBe(true);
});
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx
index 68f1c6645..9c184438e 100644
--- a/src/components/launch/LaunchWindow.tsx
+++ b/src/components/launch/LaunchWindow.tsx
@@ -91,6 +91,7 @@ export function LaunchWindow() {
setMicrophoneEnabled,
microphoneDeviceId,
setMicrophoneDeviceId,
+ microphoneDeviceName,
setMicrophoneDeviceName,
systemAudioEnabled,
setSystemAudioEnabled,
@@ -160,7 +161,11 @@ export function LaunchWindow() {
devices: micDevices,
selectedDeviceId: selectedMicId,
setSelectedDeviceId: setSelectedMicId,
- } = useMicrophoneDevices(microphoneEnabled || isDeviceSettingsOpen, microphoneDeviceId);
+ } = useMicrophoneDevices(
+ microphoneEnabled || isDeviceSettingsOpen,
+ microphoneDeviceId,
+ microphoneDeviceName,
+ );
useEffect(() => {
if (selectedMicId && selectedMicId !== "default") {
diff --git a/src/hooks/useMicrophoneDevices.test.ts b/src/hooks/useMicrophoneDevices.test.ts
new file mode 100644
index 000000000..17c8eefb9
--- /dev/null
+++ b/src/hooks/useMicrophoneDevices.test.ts
@@ -0,0 +1,59 @@
+// @vitest-environment jsdom
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useMicrophoneDevices } from "./useMicrophoneDevices";
+
+const DEVICES = [
+ { kind: "audioinput", deviceId: "mic-a", label: "Realtek Array Microphone", groupId: "g1" },
+ { kind: "audioinput", deviceId: "mic-b", label: "Microphone (Logitech PRO X)", groupId: "g2" },
+ { kind: "videoinput", deviceId: "cam", label: "Webcam", groupId: "g3" },
+];
+
+const enumerateDevices = vi.fn(async () => DEVICES);
+
+Object.defineProperty(global.navigator, "mediaDevices", {
+ value: {
+ enumerateDevices,
+ getUserMedia: vi.fn(async () => ({ getTracks: () => [{ stop: vi.fn() }] })),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ },
+ configurable: true,
+});
+
+describe("useMicrophoneDevices", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ enumerateDevices.mockResolvedValue(DEVICES);
+ });
+
+ it("falls back to the first input when nothing is remembered", async () => {
+ const { result } = renderHook(() => useMicrophoneDevices(true));
+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-a"));
+ });
+
+ it("prefers the remembered microphone over the first input", async () => {
+ const { result } = renderHook(() => useMicrophoneDevices(true, "mic-b"));
+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-b"));
+ });
+
+ /**
+ * Chromium's device ids are per-origin salted, so the id one window persisted
+ * can name nothing in the next while the microphone itself is right there in
+ * the list. Falling through to the first input would silently swap the user's
+ * microphone — which is the bug, one layer down.
+ */
+ it("finds the remembered microphone by label when its id no longer matches", async () => {
+ const { result } = renderHook(() =>
+ useMicrophoneDevices(true, "stale-id", "Microphone (Logitech PRO X)"),
+ );
+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-b"));
+ });
+
+ it("still falls back to the first input when neither id nor label matches", async () => {
+ const { result } = renderHook(() =>
+ useMicrophoneDevices(true, "stale-id", "A microphone that left"),
+ );
+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-a"));
+ });
+});
diff --git a/src/hooks/useMicrophoneDevices.ts b/src/hooks/useMicrophoneDevices.ts
index 94ffe2eb0..55f059351 100644
--- a/src/hooks/useMicrophoneDevices.ts
+++ b/src/hooks/useMicrophoneDevices.ts
@@ -12,8 +12,17 @@ export interface MicrophoneDevice {
* list", which is the OS enumeration order and has nothing to do with what the
* user chose. The HUD window is destroyed and rebuilt for every recording, so
* without this its pick reverted on each take.
+ * @param preferredDeviceName The same choice by label, tried when the id finds
+ * nothing. Chromium's device ids are per-origin salted, so the id a previous
+ * window persisted can name nothing in this one while the microphone is sitting
+ * right there in the list — and falling through to the first input would then
+ * discard a choice that was perfectly resolvable.
*/
-export function useMicrophoneDevices(enabled: boolean = true, preferredDeviceId?: string) {
+export function useMicrophoneDevices(
+ enabled: boolean = true,
+ preferredDeviceId?: string,
+ preferredDeviceName?: string,
+) {
const [devices, setDevices] = useState<MicrophoneDevice[]>([]);
const [selectedDeviceId, setSelectedDeviceId] = useState<string>("default");
const [isLoading, setIsLoading] = useState(false);
@@ -23,6 +32,7 @@ export function useMicrophoneDevices(enabled: boolean = true, preferredDeviceId?
// getUserMedia() permission stream acquired and torn down on every open.
const selectedDeviceIdRef = useRef(selectedDeviceId);
const preferredDeviceIdRef = useRef(preferredDeviceId);
+ const preferredDeviceNameRef = useRef(preferredDeviceName);
// Synchronised in an effect rather than during render: React may discard a
// render without committing it, and a ref written there keeps the value
// anyway, which would resolve the selection against a device the committed
@@ -30,7 +40,8 @@ export function useMicrophoneDevices(enabled: boolean = true, preferredDeviceId?
useEffect(() => {
selectedDeviceIdRef.current = selectedDeviceId;
preferredDeviceIdRef.current = preferredDeviceId;
- }, [selectedDeviceId, preferredDeviceId]);
+ preferredDeviceNameRef.current = preferredDeviceName;
+ }, [selectedDeviceId, preferredDeviceId, preferredDeviceName]);
useEffect(() => {
if (!enabled) {
@@ -65,9 +76,14 @@ export function useMicrophoneDevices(enabled: boolean = true, preferredDeviceId?
const stillAvailable = audioInputs.some((d) => d.deviceId === currentId);
if ((currentId === "default" || !stillAvailable) && audioInputs.length > 0) {
const preferredId = preferredDeviceIdRef.current;
- const preferred = preferredId
- ? audioInputs.find((d) => d.deviceId === preferredId)
- : undefined;
+ const preferredName = preferredDeviceNameRef.current;
+ // By id, then by label, then whatever is first. Always an entry
+ // from THIS list, so the id and the label the caller ends up
+ // sending to the native helper describe the same device — the
+ // pairing that #387 and #404 were both about.
+ const preferred =
+ (preferredId ? audioInputs.find((d) => d.deviceId === preferredId) : undefined) ??
+ (preferredName ? audioInputs.find((d) => d.label === preferredName) : undefined);
setSelectedDeviceId(preferred?.deviceId ?? audioInputs[0].deviceId);
}
setIsLoading(false);