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): prove the microphone fallback on real hardware
EtienneLescot767531b4cb41
diff --git a/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp b/electron/native/wgc-capture/src/wasapi_loopback_capture.cppindex 86364ab0c..6970670ce 100644--- a/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp+++ b/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp@@ -65,6 +65,32 @@ std::wstring normalizeDeviceName(const std::wstring& value) {return result;}+/**+ * Is `word` one of the space-separated words of `haystack`?+ *+ * Both sides have already been through `normalizeDeviceName`, so a word is+ * exactly what sits between two spaces.+ */+bool containsWord(const std::wstring& haystack, const std::wstring& word) {+ if (haystack.empty() || word.empty()) {+ return false;+ }+ size_t pos = 0;+ while (pos <= haystack.size()) {+ const size_t end = haystack.find(L' ', pos);+ const std::wstring candidate =+ haystack.substr(pos, end == std::wstring::npos ? std::wstring::npos : end - pos);+ if (candidate == word) {+ return true;+ }+ if (end == std::wstring::npos) {+ break;+ }+ pos = end + 1;+ }+ return false;+}+int scoreDeviceName(const std::wstring& candidateName, const std::wstring& candidateId, const std::wstring& requestedName) {const std::wstring candidate = normalizeDeviceName(candidateName);const std::wstring id = normalizeDeviceName(candidateId);@@ -82,15 +108,21 @@ int scoreDeviceName(const std::wstring& candidateName, const std::wstring& candireturn 800;}+ // Whole words from here down, never substrings. `candidate.find(word)` let a+ // requested "micro" match the "microphone" that begins almost every endpoint+ // name on Windows, so a name matching nothing still scored high enough to+ // win -- and the recording quietly used a microphone nobody asked for, with+ // the fallback warning unable to fire because a device HAD been resolved+ // (getopenscreen/openscreen#404).int score = 0;size_t pos = 0;while (pos < requested.size()) {const size_t end = requested.find(L' ', pos);const std::wstring word = requested.substr(pos, end == std::wstring::npos ? std::wstring::npos : end - pos);if (word.size() > 1 && word != L"microphone" && word != L"mic" && word != L"audio" && word != L"input") {- if (candidate.find(word) != std::wstring::npos) {+ if (containsWord(candidate, word)) {score += 100;- } else if (id.find(word) != std::wstring::npos) {+ } else if (containsWord(id, word)) {score += 50;}}diff --git a/package.json b/package.jsonindex 67cd2585b..f98c541ba 100644--- a/package.json+++ b/package.json@@ -67,6 +67,7 @@"test:wgc-window:win": "node scripts/test-windows-wgc-helper.mjs --window","test:wgc-audio:win": "node scripts/test-windows-wgc-helper.mjs --system-audio","test:wgc-mic:win": "node scripts/test-windows-wgc-helper.mjs --microphone",+ "test:wgc-mic-selection:win": "node scripts/test-windows-microphone-selection.mjs","test:wgc-mixed-audio:win": "node scripts/test-windows-wgc-helper.mjs --system-audio --microphone","test:wgc-webcam:win": "node scripts/test-windows-wgc-helper.mjs --webcam","test:wgc-full:win": "node scripts/test-windows-wgc-helper.mjs --webcam --system-audio --microphone",diff --git a/scripts/test-windows-microphone-selection.mjs b/scripts/test-windows-microphone-selection.mjsnew file mode 100644index 000000000..c06a51df8--- /dev/null+++ b/scripts/test-windows-microphone-selection.mjs@@ -0,0 +1,155 @@+/**+ * Which microphone does the helper actually open?+ *+ * WASAPI cannot run on Linux CI and there is no C++ test harness here, so the+ * selection rules are checked the only way that proves anything: by driving the+ * real helper on a real Windows machine and reading what it says it chose.+ *+ * What is being pinned is the pair of promises the recording flow rests on —+ * the microphone the user asked for is the one recorded, and when it cannot be+ * found the helper SAYS SO instead of quietly capturing something else+ * (getopenscreen/openscreen#404). The second half needs the first: a fuzzy name+ * match that resolved "some microphone" made the warning unreachable, because a+ * device had after all been resolved.+ *+ * npm run test:wgc-mic-selection:win+ *+ * Case 4 needs a real microphone name; pass one that exists on this machine+ * through OPENSCREEN_WGC_TEST_MICROPHONE_DEVICE_NAME, or it is skipped.+ */+import { spawn } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.join(__dirname, "..");+const HELPER =+ process.env.OPENSCREEN_WGC_CAPTURE_EXE ??+ path.join(ROOT, "electron", "native", "bin", "win32-x64", "wgc-capture.exe");+const REAL_MIC_NAME = process.env.OPENSCREEN_WGC_TEST_MICROPHONE_DEVICE_NAME ?? "";+const RECORD_MS = Number(process.env.OPENSCREEN_WGC_TEST_DURATION_MS ?? 2500);++if (process.platform !== "win32") {+ console.log("Windows only — skipping.");+ process.exit(0);+}+if (!fs.existsSync(HELPER)) {+ console.error(`Helper not found at ${HELPER}. Run: npm run build:native:win`);+ process.exit(1);+}++function runHelper(label, microphoneDeviceId, microphoneDeviceName) {+ return new Promise((resolve) => {+ const outputPath = path.join(os.tmpdir(), `wgc-mic-${label}.mp4`);+ const config = {+ schemaVersion: 2,+ recordingId: Date.now(),+ outputPath,+ sourceType: "display",+ sourceId: "screen:0:0",+ displayId: 0,+ fps: 30,+ videoWidth: 1280,+ videoHeight: 720,+ hasDisplayBounds: false,+ captureSystemAudio: false,+ captureMic: true,+ microphoneDeviceId,+ microphoneDeviceName,+ microphoneGain: 1,+ webcamEnabled: false,+ cursorCaptureMode: "editable-overlay",+ };++ const proc = spawn(HELPER, [JSON.stringify(config)], { windowsHide: true });+ let output = "";+ proc.stdout.on("data", (chunk) => {+ output += chunk.toString();+ });+ proc.stderr.on("data", (chunk) => {+ output += chunk.toString();+ });+ const stopTimer = setTimeout(() => {+ try {+ proc.stdin.write("stop\n");+ } catch {+ // The helper may already be gone; the kill below is the backstop.+ }+ }, RECORD_MS);+ const killTimer = setTimeout(() => proc.kill(), RECORD_MS + 6000);++ proc.on("close", () => {+ clearTimeout(stopTimer);+ clearTimeout(killTimer);+ fs.rmSync(outputPath, { force: true });+ resolve({+ defaulted: output.includes('"code":"microphone-defaulted"'),+ selected: output.match(/"microphoneDeviceName":"([^"]*)"/)?.[1] ?? null,+ });+ });+ });+}++const cases = [+ {+ label: "unresolvable-id-no-name",+ why: "the reported bug: a browser device id the helper cannot resolve, and no name to fall back on",+ deviceId: "0f6a4c1e9b2d47a3ba55d8e01c7f9a24",+ deviceName: "",+ expectDefaulted: true,+ },+ {+ label: "name-matches-nothing",+ why: "a name was supplied and matches no endpoint — the fuzzy match must not invent one",+ deviceId: "",+ deviceName: "A Microphone That Is Not Here",+ expectDefaulted: true,+ },+ {+ label: "plain-default-request",+ why: "no particular device was asked for, so the default endpoint is the right answer and no warning is due",+ deviceId: "default",+ deviceName: "",+ expectDefaulted: false,+ },+];++if (REAL_MIC_NAME) {+ cases.push({+ label: "real-device-name",+ why: "the happy path: a name that exists resolves, and stays silent",+ deviceId: "",+ deviceName: REAL_MIC_NAME,+ expectDefaulted: false,+ expectSelectedToMatch: true,+ });+} else {+ console.log(+ "NOTE: set OPENSCREEN_WGC_TEST_MICROPHONE_DEVICE_NAME to a real microphone to cover the happy path.\n",+ );+}++let failures = 0;+for (const testCase of cases) {+ const result = await runHelper(testCase.label, testCase.deviceId, testCase.deviceName);+ let ok = result.defaulted === testCase.expectDefaulted;+ if (ok && testCase.expectSelectedToMatch) {+ // Not string equality: WASAPI's friendly name is the app's label without+ // the USB ids Chromium appends, so the app's name contains the endpoint's.+ ok = Boolean(result.selected) && testCase.deviceName.includes(result.selected);+ }+ if (!ok) failures += 1;+ console.log(+ `${ok ? "PASS" : "FAIL"} ${testCase.label.padEnd(24)} defaulted=${String(result.defaulted).padEnd(5)} expected=${String(testCase.expectDefaulted).padEnd(5)} opened="${result.selected}"`,+ );+ console.log(` ${testCase.why}`);+}++console.log(+ failures === 0+ ? `\nAll ${cases.length} microphone selection cases behaved.`+ : `\n${failures} of ${cases.length} cases did not.`,+);+process.exit(failures === 0 ? 0 : 1);diff --git a/technical-documentation/architecture/recording.md b/technical-documentation/architecture/recording.mdindex 21375d89b..982884fe3 100644--- a/technical-documentation/architecture/recording.md+++ b/technical-documentation/architecture/recording.md@@ -59,6 +59,8 @@ Two consequences follow, and both were once bugs:Electron resolves selected sources, devices, and paths before launching the helper. The helper does not guess a DirectShow camera: Windows receives the resolved selection. A helper error is reported explicitly rather than silently switching a Windows native feature to browser capture.+The microphone is chosen the same way and carries the same requirement: the helper resolves it by name, and `RecordingPrefs` therefore carries `micDeviceName` beside `micDeviceId` so a HUD rebuilt for a new take knows it without waiting on its own device enumeration. A request that names no microphone, or names one matching no endpoint, makes the helper capture the Windows default input — it reports that as `microphone-defaulted` rather than doing it quietly. Name matching is by whole words: a requested "micro" matching the "microphone" that opens nearly every Windows endpoint name is how a name that fitted nothing still selected a device. `npm run test:wgc-mic-selection:win` drives the real helper through those cases, because WASAPI cannot run on Linux CI.+Two things follow from Windows matching a camera by **name** while Chromium selects one by **id**. First, the renderer reads both halves off the `MediaStreamTrack` it opened rather than from separate state, so a request can never carry one camera's id beside another's name — the failure that let the HUD preview show the chosen camera while the recording captured a different one. Second, a camera the helper cannot open is a warning (`webcam-unavailable`), not a failed recording: the take continues as screen and audio, and the renderer says so at that moment instead of leaving the absence to be discovered in the editor. The DirectShow fallback negotiates the camera's own format first and only asks for RGB32 — inserting a colour converter — when that format is one the helper cannot unpack, which is the only way devices absent from Media Foundation, such as NVIDIA Broadcast, can be captured at all.## Output files and sidecars