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 camera names on word boundaries, and keep non-Latin names apart

EtienneLescotbdfeec7f788b
diff --git a/electron/native/wgc-capture/src/webcam_capture.cpp b/electron/native/wgc-capture/src/webcam_capture.cpp
index 9152e0e48..6377a799b 100644
--- a/electron/native/wgc-capture/src/webcam_capture.cpp
+++ b/electron/native/wgc-capture/src/webcam_capture.cpp
@@ -33,17 +33,37 @@ std::wstring readAllocatedString(IMFActivate* activate, REFGUID key) {
return result;
}
-bool containsInsensitive(const std::wstring& haystack, const std::wstring& needle) {
+/**
+ * Does one of these appear inside the other as WHOLE WORDS?
+ *
+ * Plain containment answered for devices that merely share a spelling: a
+ * requested "Logi" is inside "Logitech", and "Micro" inside "Microphone",
+ * neither of them as a word. Matching on that resolved a camera nobody asked
+ * for -- and resolving one is exactly what stops the request reaching the
+ * DirectShow fallback, where the cameras Media Foundation cannot enumerate live.
+ *
+ * Both sides arrive normalized, so a boundary is the start of the string, its
+ * 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;
+}
- std::wstring lowerHaystack = haystack;
- std::wstring lowerNeedle = needle;
- std::transform(lowerHaystack.begin(), lowerHaystack.end(), lowerHaystack.begin(), ::towlower);
- std::transform(lowerNeedle.begin(), lowerNeedle.end(), lowerNeedle.begin(), ::towlower);
- return lowerHaystack.find(lowerNeedle) != std::wstring::npos ||
- lowerNeedle.find(lowerHaystack) != std::wstring::npos;
+bool containsInsensitive(const std::wstring& haystack, const std::wstring& needle) {
+ return containsAsWords(haystack, needle) || containsAsWords(needle, haystack);
}
std::wstring normalizeDeviceName(const std::wstring& value) {
diff --git a/electron/recording/deviceNameMatching.test.ts b/electron/recording/deviceNameMatching.test.ts
index ef09f278e..38c8185cb 100644
--- a/electron/recording/deviceNameMatching.test.ts
+++ b/electron/recording/deviceNameMatching.test.ts
@@ -60,6 +60,30 @@ describe("scoreDeviceNameMatch", () => {
expect(scoreDeviceNameMatch("Logitech StreamCam", "{clsid}", " ")).toBe(0);
});
+ /**
+ * "Micro" is inside "Microphone", "Logi" inside "Logitech" — spelled there,
+ * but not as a word. Containment used to take either for a match and resolve
+ * a device nobody asked for.
+ */
+ it("refuses a request merely spelled inside a longer word", () => {
+ expect(scoreDeviceNameMatch("Microphone (Logitech StreamCam)", "{id}", "Micro")).toBe(0);
+ expect(scoreDeviceNameMatch("Logitech StreamCam", "{clsid}", "Logi")).toBe(0);
+ });
+
+ /**
+ * `[^a-z0-9]` stripped every non-Latin letter, so two different Japanese
+ * cameras both normalized to "a" and matched each other at 1000.
+ */
+ it("keeps non-Latin names apart", () => {
+ expect(scoreDeviceNameMatch("カメラ A", "{clsid}", "ウェブカメラ A")).toBe(0);
+ expect(scoreDeviceNameMatch("Веб-камера 1", "{clsid}", "Веб-камера 2")).toBe(0);
+ });
+
+ it("still matches identical non-Latin names", () => {
+ expect(scoreDeviceNameMatch("カメラ A", "{clsid}", "カメラ A")).toBe(1000);
+ expect(scoreDeviceNameMatch("摄像头(罗技)", "{clsid}", "摄像头(罗技)")).toBe(1000);
+ });
+
it("falls back to the identifier when the friendly name says nothing", () => {
expect(scoreDeviceNameMatch("", "usb elgato facecam 0fd9", "Elgato Facecam")).toBe(800);
});
diff --git a/electron/recording/deviceNameMatching.ts b/electron/recording/deviceNameMatching.ts
index b1c72c9e4..59dee29fd 100644
--- a/electron/recording/deviceNameMatching.ts
+++ b/electron/recording/deviceNameMatching.ts
@@ -27,14 +27,50 @@
* Windows-only scripts in `scripts/` that drive the real binary.
*/
-/** Lowercase, alphanumerics only, single-spaced — the shape both sides compare in. */
+/**
+ * Lowercase, letters and digits only, single-spaced — the shape both sides
+ * compare in.
+ *
+ * Unicode-aware, and not `[^a-z0-9]`: that stripped every non-Latin letter, so a
+ * Japanese "カメラ A" and "ウェブカメラ A" both collapsed to "a" and matched each
+ * other exactly, at the highest score there is. The C++ helpers use
+ * `std::iswalnum` on wide characters and never had that flaw; this is the copy
+ * that did.
+ */
export function normalizeDeviceName(value: string) {
return value
.toLowerCase()
- .replace(/[^a-z0-9]+/g, " ")
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
.trim();
}
+/**
+ * Does `needle` appear in `haystack` as whole words?
+ *
+ * Plain containment answers for devices that merely share a spelling: a
+ * requested "Micro" is inside "Microphone (Logitech StreamCam)", and "Logi"
+ * inside "Logitech", neither of them as a word. Both resolved a device nobody
+ * asked for — and resolving one is precisely what stops the caller from falling
+ * through to the provider that had the right one.
+ *
+ * Both sides are normalized, so a boundary is the start of the string, its end,
+ * or a space.
+ */
+function containsAsWords(haystack: string, needle: string) {
+ if (!haystack || !needle) {
+ return false;
+ }
+ for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + 1)) {
+ const startsOnBoundary = at === 0 || haystack[at - 1] === " ";
+ const after = at + needle.length;
+ const endsOnBoundary = after === haystack.length || haystack[after] === " ";
+ if (startsOnBoundary && endsOnBoundary) {
+ return true;
+ }
+ }
+ return false;
+}
+
/**
* How well a candidate device answers a requested name, or 0 for "not this one"
* — which callers must treat as a real answer rather than a weak match.
@@ -59,11 +95,11 @@ export function scoreDeviceNameMatch(
return 1000;
}
// One name being the other plus decoration is the ordinary case, and the only
- // inexact match worth trusting.
- if (candidate && (candidate.includes(requested) || requested.includes(candidate))) {
+ // inexact match worth trusting — provided the shared part is whole words.
+ if (containsAsWords(candidate, requested) || containsAsWords(requested, candidate)) {
return 900;
}
- if (id && (id.includes(requested) || requested.includes(id))) {
+ if (containsAsWords(id, requested) || containsAsWords(requested, id)) {
return 800;
}
return 0;
diff --git a/scripts/test-windows-camera-selection.mjs b/scripts/test-windows-camera-selection.mjs
index 790d3bd62..a9f3dcbc5 100644
--- a/scripts/test-windows-camera-selection.mjs
+++ b/scripts/test-windows-camera-selection.mjs
@@ -75,6 +75,10 @@ function runHelper(label, webcamDeviceName) {
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();
});
@@ -90,15 +94,23 @@ function runHelper(label, webcamDeviceName) {
}, 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 });
fs.rmSync(webcamPath, { 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,
opened: output.match(/"event":"webcam-format".*?"deviceName":"([^"]*)"/)?.[1] ?? null,
- scores: [...output.matchAll(/candidate \[\d+\] name="([^"]*)" score=(\d+)/g)].map(
- (m) => `${m[1]}=${m[2]}`,
+ // Which cameras Media Foundation actually offered. A negative case
+ // proves nothing if the camera it was meant to be tempted by was
+ // not among them.
+ candidates: [...output.matchAll(/candidate \[\d+\] name="([^"]*)" score=(\d+)/g)].map(
+ (match) => ({ name: match[1], score: Number(match[2]) }),
),
});
});
@@ -118,6 +130,12 @@ const cases = [
deviceName: "Logitech BRIO",
expectOpened: null,
},
+ {
+ label: "short-word-inside-a-brand",
+ why: '"Logi" is spelled inside "Logitech", but is not a word of it',
+ deviceName: "Logi",
+ expectOpened: null,
+ },
{
label: "nothing-like-it",
why: "a name with nothing in common must resolve to nothing, so the caller can fall through",
@@ -142,16 +160,40 @@ if (REAL_CAMERA) {
let failures = 0;
for (const testCase of cases) {
const result = await runHelper(testCase.label, testCase.deviceName);
- const ok =
- testCase.expectOpened === "any"
- ? Boolean(result.opened)
- : result.opened === testCase.expectOpened;
- if (!ok) failures += 1;
+
+ 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 (testCase.expectOpened === "any") {
+ if (!result.opened) problems.push("nothing was opened");
+ } else {
+ if (result.opened) problems.push(`opened "${result.opened}", and should have opened nothing`);
+ // A negative case only means something if the camera it was meant to be
+ // tempted by was on offer. With nothing enumerated it passes vacuously.
+ if (result.candidates.length === 0) {
+ problems.push("Media Foundation enumerated nothing, so this case proves nothing");
+ }
+ const scored = result.candidates.filter((candidate) => candidate.score > 0);
+ if (scored.length) {
+ problems.push(
+ `something scored above zero: ${scored.map((c) => `${c.name}=${c.score}`).join(", ")}`,
+ );
+ }
+ }
+
+ if (problems.length) failures += 1;
console.log(
- `${ok ? "PASS" : "FAIL"} ${testCase.label.padEnd(22)} requested="${testCase.deviceName}" opened=${result.opened === null ? "(none)" : `"${result.opened}"`}`,
+ `${problems.length ? "FAIL" : "PASS"} ${testCase.label.padEnd(22)} requested="${testCase.deviceName}" opened=${result.opened === null ? "(none)" : `"${result.opened}"`}`,
);
console.log(` ${testCase.why}`);
- if (result.scores.length) console.log(` scores: ${result.scores.join(" ")}`);
+ if (result.candidates.length) {
+ console.log(
+ ` enumerated: ${result.candidates.map((c) => `${c.name}=${c.score}`).join(" ")}`,
+ );
+ }
+ 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 ec6208f69..f6323f72e 100644
--- a/technical-documentation/architecture/recording.md
+++ b/technical-documentation/architecture/recording.md
@@ -60,8 +60,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 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. When a particular microphone was asked for — an id other than `default`, or a name — and neither finds an endpoint, the helper captures the Windows default input and says so as `microphone-defaulted` rather than doing it quietly. A request that asks for no particular microphone lands on that same default input and warns nothing: there it is the answer rather than a fallback. 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.
-
-The camera follows the same rule, and the same removal. "Logi Capture" and "Logitech StreamCam" are two real devices sharing no word, yet "logi" sits inside "logitech" — enough, under the scoring that used to bridge names differing by more than decoration, to win. Choosing a camera Media Foundation cannot enumerate then opened a different camera instead of returning nothing and letting the DirectShow fallback find the real one, which is where every camera Media Foundation cannot see actually lives, NVIDIA Broadcast among them. Scoring zero is what makes that fallback reachable, so it is a real answer rather than a weak match. `electron/recording/deviceNameMatching.ts` holds the rules and their unit tests for the Electron side; each helper carries its own copy in C++, covered by `npm run test:wgc-camera-selection:win` because Media Foundation cannot run on Linux CI either.
+The camera follows the same rule, and the same removals. "Logi Capture" and "Logitech StreamCam" are two real devices sharing no word, yet "logi" sits inside "logitech" — enough, under the scoring that used to bridge names differing by more than decoration, to win. Containment had to become whole-word for the same reason one layer down: a requested "Logi" is spelled inside "Logitech" without being a word of it, and plain containment resolved a camera on that alone. Choosing a camera Media Foundation cannot enumerate then opened a different camera instead of returning nothing and letting the DirectShow fallback find the real one, which is where every camera Media Foundation cannot see actually lives, NVIDIA Broadcast among them. Scoring zero is what makes that fallback reachable, so it is a real answer rather than a weak match. `electron/recording/deviceNameMatching.ts` holds the rules and their unit tests for the Electron side; each helper carries its own copy in C++, covered by `npm run test:wgc-camera-selection:win` because Media Foundation cannot run on Linux CI either.
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