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): match microphone names on word boundaries

EtienneLescotc43d1e8779dd
diff --git a/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp b/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp
index 69fc58272..49239ad01 100644
--- a/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp
+++ b/electron/native/wgc-capture/src/wasapi_loopback_capture.cpp
@@ -65,6 +65,34 @@ std::wstring normalizeDeviceName(const std::wstring& value) {
return result;
}
+/**
+ * Does `needle` appear in `haystack` as whole words?
+ *
+ * Plain containment is what let a requested "Micro" answer for
+ * "Microphone (Logitech StreamCam)" -- the request is inside the name, just not
+ * as a word -- and a requested "Logi" for "Logitech". Either resolved an
+ * endpoint nobody asked for, and silenced the fallback warning by doing so.
+ *
+ * Both sides are normalized, so a boundary is the start of the string, the end,
+ * or a space.
+ */
+bool containsAsWords(const std::wstring& haystack, const std::wstring& needle) {
+ if (haystack.empty() || needle.empty()) {
+ return false;
+ }
+ size_t pos = haystack.find(needle);
+ while (pos != std::wstring::npos) {
+ const bool startsOnBoundary = pos == 0 || haystack[pos - 1] == L' ';
+ const size_t after = pos + needle.size();
+ const bool endsOnBoundary = after == haystack.size() || haystack[after] == L' ';
+ if (startsOnBoundary && endsOnBoundary) {
+ return true;
+ }
+ pos = haystack.find(needle, pos + 1);
+ }
+ return false;
+}
+
/**
* How well a candidate endpoint answers a requested name, or 0 for "not this
* one" -- which the caller must treat as a real answer.
@@ -91,10 +119,10 @@ int scoreDeviceName(const std::wstring& candidateName, const std::wstring& candi
if (candidate == requested) {
return 1000;
}
- if (!candidate.empty() && (candidate.find(requested) != std::wstring::npos || requested.find(candidate) != std::wstring::npos)) {
+ if (containsAsWords(candidate, requested) || containsAsWords(requested, candidate)) {
return 900;
}
- if (!id.empty() && (id.find(requested) != std::wstring::npos || requested.find(id) != std::wstring::npos)) {
+ if (containsAsWords(id, requested) || containsAsWords(requested, id)) {
return 800;
}
diff --git a/scripts/test-windows-microphone-selection.mjs b/scripts/test-windows-microphone-selection.mjs
index 4d7e28a49..7d5b8444a 100644
--- a/scripts/test-windows-microphone-selection.mjs
+++ b/scripts/test-windows-microphone-selection.mjs
@@ -65,6 +65,10 @@ function runHelper(label, microphoneDeviceId, microphoneDeviceName) {
const proc = spawn(HELPER, [JSON.stringify(config)], { windowsHide: true });
let output = "";
+ let spawnError = null;
+ proc.on("error", (error) => {
+ spawnError = error.message;
+ });
proc.stdout.on("data", (chunk) => {
output += chunk.toString();
});
@@ -80,13 +84,23 @@ function runHelper(label, microphoneDeviceId, microphoneDeviceName) {
}, RECORD_MS);
const killTimer = setTimeout(() => proc.kill(), RECORD_MS + 6000);
- proc.on("close", () => {
+ proc.on("close", (code, signal) => {
clearTimeout(stopTimer);
clearTimeout(killTimer);
fs.rmSync(outputPath, { force: true });
resolve({
+ // A helper that dies can still have printed everything expected, so
+ // how it ended is part of the result rather than something to skip.
+ spawnError,
+ code,
+ signal,
defaulted: output.includes('"code":"microphone-defaulted"'),
selected: output.match(/"microphoneDeviceName":"([^"]*)"/)?.[1] ?? null,
+ // Which endpoints the helper actually saw. A negative case proves
+ // nothing if the device it was meant to be tempted by was absent.
+ candidates: [...output.matchAll(/Native microphone candidate: (.+?) score=(\d+)/g)].map(
+ (match) => ({ name: match[1].trim(), score: Number(match[2]) }),
+ ),
});
});
});
@@ -102,11 +116,25 @@ const cases = [
},
{
label: "name-matches-nothing",
- why: "a name was supplied and matches no endpoint — the fuzzy match must not invent one",
+ why: "a name was supplied and matches no endpoint — the match must not invent one",
deviceId: "",
deviceName: "A Microphone That Is Not Here",
expectDefaulted: true,
},
+ {
+ label: "short-word-inside-a-name",
+ why: '"Micro" sits inside the "Microphone" that opens nearly every Windows endpoint name — containment must be whole words',
+ deviceId: "",
+ deviceName: "Micro",
+ expectDefaulted: true,
+ },
+ {
+ label: "short-word-inside-a-brand",
+ why: '"Logi" sits inside "Logitech" — the same mistake one word along',
+ deviceId: "",
+ deviceName: "Logi",
+ expectDefaulted: true,
+ },
{
label: "shares-a-brand-only",
why: "another device from the same maker is still another device — a shared brand must not answer for it",
@@ -141,17 +169,40 @@ if (REAL_MIC_NAME) {
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);
+
+ const problems = [];
+ if (result.spawnError) problems.push(`could not start the helper: ${result.spawnError}`);
+ if (result.signal) problems.push(`helper killed by ${result.signal}`);
+ if (result.code !== 0 && result.code !== null) problems.push(`helper exited ${result.code}`);
+ if (result.defaulted !== testCase.expectDefaulted) {
+ problems.push(`defaulted=${result.defaulted}, expected ${testCase.expectDefaulted}`);
+ }
+ // A case that supplies a name is only meaningful if the helper had endpoints
+ // to be tempted by; with none enumerated it would pass whatever the rules
+ // say. A case supplying no name never reaches enumeration at all, and that
+ // short circuit IS the behaviour under test there.
+ const scoringWasExercised = testCase.deviceName !== "";
+ if (testCase.expectDefaulted && scoringWasExercised && result.candidates.length === 0) {
+ problems.push("no endpoint was enumerated, so this case proves nothing");
}
- if (!ok) failures += 1;
+ if (testCase.expectDefaulted && result.candidates.some((c) => c.score > 0)) {
+ const scored = result.candidates
+ .filter((c) => c.score > 0)
+ .map((c) => `${c.name}=${c.score}`)
+ .join(", ");
+ problems.push(`something scored above zero: ${scored}`);
+ }
+ if (testCase.expectSelectedToMatch) {
+ const matches = Boolean(result.selected) && testCase.deviceName.includes(result.selected);
+ if (!matches) problems.push(`opened "${result.selected}", which is not what was asked for`);
+ }
+
+ if (problems.length) 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}"`,
+ `${problems.length ? "FAIL" : "PASS"} ${testCase.label.padEnd(24)} defaulted=${String(result.defaulted).padEnd(5)} opened="${result.selected}"`,
);
console.log(` ${testCase.why}`);
+ for (const problem of problems) console.log(` -> ${problem}`);
}
console.log(
diff --git a/technical-documentation/architecture/recording.md b/technical-documentation/architecture/recording.md
index 0abea732e..b6cc0f6fd 100644
--- a/technical-documentation/architecture/recording.md
+++ b/technical-documentation/architecture/recording.md
@@ -59,7 +59,7 @@ 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 deliberately strict — equal once normalized, or one containing the other, and nothing weaker. A tier that scored shared *words* used to bridge the rest and answered for devices that were not the same one: a requested "micro" matches the "microphone" that opens nearly every Windows endpoint name, so a name fitting nothing still selected a device and the fallback warning could not fire. `npm run test:wgc-mic-selection:win` drives the real helper through those cases, because WASAPI cannot run on Linux CI.
+The microphone is chosen the same way and carries the same requirement: the helper resolves it by id first and by name when that finds nothing — and the id it is given is Chromium's, which names nothing outside the renderer, so the name is what actually does the work. `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 deliberately strict — equal once normalized, or one containing the other, and nothing weaker. Containment is measured in whole words, and a tier that scored shared *words* has been dropped entirely. Both answered for devices that were not the same one: a requested "micro" sits inside the "microphone" that opens nearly every Windows endpoint name, and "logi" inside "logitech", so a name fitting nothing still selected a device — and silenced the fallback warning by resolving one. `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.