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(capture): enumerate screens and windows in separate calls on X11
EtienneLescot3ae6a4905fa1
diff --git a/electron/ipc/desktopSourceTypes.test.ts b/electron/ipc/desktopSourceTypes.test.tsnew file mode 100644index 000000000..cff401277--- /dev/null+++ b/electron/ipc/desktopSourceTypes.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it, vi } from "vitest";+import { getSourcesByType, shouldEnumerateSourceTypesSeparately } from "./desktopSourceTypes";++describe("shouldEnumerateSourceTypesSeparately", () => {+ it("splits on Linux X11, including a bare Xvfb with no session variables", () => {+ expect(shouldEnumerateSourceTypesSeparately("linux", {})).toBe(true);+ expect(shouldEnumerateSourceTypesSeparately("linux", { XDG_SESSION_TYPE: "x11" })).toBe(true);+ });++ it("keeps one call on Wayland, where splitting would raise the portal twice", () => {+ expect(shouldEnumerateSourceTypesSeparately("linux", { XDG_SESSION_TYPE: "wayland" })).toBe(+ false,+ );+ expect(shouldEnumerateSourceTypesSeparately("linux", { WAYLAND_DISPLAY: "wayland-0" })).toBe(+ false,+ );+ });++ it("keeps one call on Windows and macOS", () => {+ expect(shouldEnumerateSourceTypesSeparately("win32", {})).toBe(false);+ expect(shouldEnumerateSourceTypesSeparately("darwin", {})).toBe(false);+ });+});++describe("getSourcesByType", () => {+ const opts: Electron.SourcesOptions = {+ types: ["screen", "window"],+ thumbnailSize: { width: 32, height: 18 },+ };++ it("asks one type per call, one call at a time, and concatenates in order", async () => {+ let inFlight = 0;+ let maxInFlight = 0;+ const getSources = vi.fn(async (o: Electron.SourcesOptions) => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 1));+ inFlight -= 1;+ return o.types.map((type) => `${type}:0`);+ });++ await expect(getSourcesByType(opts, getSources, true)).resolves.toEqual([+ "screen:0",+ "window:0",+ ]);+ expect(getSources.mock.calls.map(([o]) => o)).toEqual([+ { ...opts, types: ["screen"] },+ { ...opts, types: ["window"] },+ ]);+ expect(maxInFlight).toBe(1);+ });++ it("passes the request through untouched when not splitting", async () => {+ const getSources = vi.fn(async () => ["screen:0", "window:0"]);+ await getSourcesByType(opts, getSources, false);+ expect(getSources).toHaveBeenCalledExactlyOnceWith(opts);+ });++ it("passes a single-type request through as one call", async () => {+ const getSources = vi.fn(async () => ["screen:0"]);+ const screensOnly: Electron.SourcesOptions = { ...opts, types: ["screen"] };+ await getSourcesByType(screensOnly, getSources, true);+ expect(getSources).toHaveBeenCalledExactlyOnceWith(screensOnly);+ });++ it("propagates a failure of either call", async () => {+ const getSources = vi.fn(async (o: Electron.SourcesOptions) => {+ if (o.types[0] === "window") throw new Error("boom");+ return ["screen:0"];+ });+ await expect(getSourcesByType(opts, getSources, true)).rejects.toThrow("boom");+ });+});diff --git a/electron/ipc/desktopSourceTypes.ts b/electron/ipc/desktopSourceTypes.tsnew file mode 100644index 000000000..1185623ce--- /dev/null+++ b/electron/ipc/desktopSourceTypes.ts@@ -0,0 +1,35 @@+// Issue #462. On X11, one desktopCapturer.getSources call asking for both+// "screen" and "window" runs Chromium's two X11 capturers together, and the+// screen capturer's thumbnail grab then intermittently fails ("Failed to+// initialize pixel buffer"). What that costs depends on the Electron version:+// 41 never settles the call at all, 43 settles after its 3s ready timer with the+// screen silently missing. Measured under Xvfb, 8 runs per cell: the combined+// call failed 3/8 (Electron 43) and 4/8 (Electron 41); asked one type per call,+// 32 runs across both versions and both orders never lost the screen.+//+// So on X11 each type gets its own call, one after the other. Not on Wayland:+// there Electron serves both types from a single PipeWire capturer, and one+// call per type would raise the portal picker twice. Not on Windows or macOS+// either, where nothing points at this and the combined call is what ships.+export function shouldEnumerateSourceTypesSeparately(+ platform: NodeJS.Platform,+ env: Partial<NodeJS.ProcessEnv>,+): boolean {+ // The same test main.ts uses to put Chromium on its Wayland backend.+ const isWayland = env.XDG_SESSION_TYPE === "wayland" || env.WAYLAND_DISPLAY !== undefined;+ return platform === "linux" && !isWayland;+}++export async function getSourcesByType<T>(+ opts: Electron.SourcesOptions,+ getSources: (opts: Electron.SourcesOptions) => Promise<T[]>,+ separately: boolean,+): Promise<T[]> {+ if (!separately || opts.types.length < 2) return getSources(opts);+ const sources: T[] = [];+ // Sequential on purpose: running them in parallel is the failure.+ for (const type of opts.types) {+ sources.push(...(await getSources({ ...opts, types: [type] })));+ }+ return sources;+}diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex d17e51290..132a879cb 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -140,6 +140,7 @@ import {shouldEnumerateRecordingSources,shouldPersistSelectedSource,} from "../recording-source-settings";+import { getSourcesByType, shouldEnumerateSourceTypesSeparately } from "./desktopSourceTypes";import { registerNativeBridgeHandlers } from "./nativeBridge";import { createNativeMacMidCaptureErrorWatch } from "./nativeMacMidCaptureErrorWatch";import { registerRecordingPrefsHandlers } from "./recordingPrefs";@@ -1982,18 +1983,19 @@ export function registerIpcHandlers(// await it, and a renderer-side race would only stop *waiting* while this// keeps running and its reply goes to nobody. Rejecting is what turns an// indefinite spinner into the pickers' existing error branch.- // How long it actually took, under the existing diagnostic flag. The bound- // above turned an indefinite hang into a named failure, which is where the- // open question starts rather than ends: on a headless runner `openscreen- // sources` gets an answer within 20s four times in five while `record` --- // the same call with the same options -- exceeds 30s every time. A duration- // on both paths is what tells those apart; a threshold alone cannot.+ // How long it actually took, under the existing diagnostic flag. That+ // duration is what showed the headless hang (#462) to be bimodal -- ~17ms+ // or never -- and so not a threshold problem; see desktopSourceTypes.ts.const startedAt = Date.now();const diagnostic = isDiagnosticModeEnabled();let sources: Awaited<ReturnType<typeof desktopCapturer.getSources>>;try {sources = await withDeadline(- desktopCapturer.getSources(opts),+ getSourcesByType(+ opts,+ (typeOpts) => desktopCapturer.getSources(typeOpts),+ shouldEnumerateSourceTypesSeparately(process.platform, process.env),+ ),GET_SOURCES_TIMEOUT_MS,`Desktop source enumeration did not return within ${GET_SOURCES_TIMEOUT_MS}ms. ` +"This usually means the display or GPU stack cannot be reached — check that a display server is available.",diff --git a/src/cli/CliSourcesRunner.tsx b/src/cli/CliSourcesRunner.tsxindex dc02f9816..0e4bbdd0d 100644--- a/src/cli/CliSourcesRunner.tsx+++ b/src/cli/CliSourcesRunner.tsx@@ -110,16 +110,11 @@ async function enumerateMicrophones(): Promise<{}async function enumerateSources(): Promise<CliSourcesResult> {- // desktopCapturer.getSources is unbounded on the main side, and on a host- // whose GL stack is broken -- a CI runner, a container, a server where ANGLE- // cannot initialise -- it can simply never return. `openscreen sources` hung- // forever on four of five headless attempts, always here: the milestones show- // the renderer asking for its request and then going silent, which is the call- // immediately after.- //- // Bounded on this side rather than in the shared get-sources handler, which- // the GUI uses too and where a timeout would change behaviour nobody asked to- // change. Failing in twenty seconds with a reason beats hanging until killed.+ // desktopCapturer.getSources can simply never return: on X11, Electron 41 did+ // so whenever screens and windows were enumerated in one call (#462; the+ // get-sources handler now splits them, see desktopSourceTypes.ts). Bounded+ // here as well, below the handler's own 30s, so this more specific message+ // wins. Failing in twenty seconds with a reason beats hanging until killed.const sources = await withTimeout<Awaited<ReturnType<typeof window.electronAPI.getSources>> | null>(