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): stop a webcam finalize from discarding the screen capture
Etienne Lescot8c8155dfc494
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 157a89f75..7d63b934b 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -2755,6 +2755,11 @@ export function registerIpcHandlers(detachNativeWindowsCaptureOutputDrain();}await stopCursorRecording();+ // Same as the discard path. `startCursorRecording` clears this on+ // the next recording anyway, so this is not what keeps the samples+ // from being written next to someone else's video -- it just stops+ // a lost take's telemetry from sitting in memory until then.+ pendingCursorRecordingData = null;// The helper never announced a finalized file, so what is on disk// is almost certainly an unindexed stub, and leaving those behind// just accumulates unplayable recordings the user cannot explain.diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cppindex 59dd3f83d..63cbcbba7 100644--- a/electron/native/wgc-capture/src/main.cpp+++ b/electron/native/wgc-capture/src/main.cpp@@ -1101,8 +1101,12 @@ int main(int argc, char* argv[]) {// arriving and keep taking the frame lock, racing the writer's last pass on// the shared D3D context at exactly the moment we can least afford a stall.beginStopStep("wgc-quiesce", stepBudgetMs);- session.quiesceCapture();- logStopStep("wgc-quiesce");+ // The drain outcome decides the shape of the whole rest of the shutdown:+ // a callback that never came back makes wgc-session-close skip the device+ // release, so a report that does not say which happened cannot be read.+ const bool wgcDrained = session.quiesceCapture();+ std::cerr << "[stop-timing] step=wgc-quiesce elapsed_ms=" << stopElapsedMs()+ << " drained=" << (wgcDrained ? "true" : "false") << std::endl;beginStopStep("microphone", stepBudgetMs);microphoneCapture.stop();logStopStep("microphone");@@ -1129,26 +1133,27 @@ int main(int argc, char* argv[]) {beginStopStep("encoder-finalize", shutdownBudgetMs);const bool screenFinalized = encoder.finalize();logStopStep("encoder-finalize");- bool webcamFinalized = true;- if (writeSeparateWebcam) {- beginStopStep("webcam-encoder-finalize", shutdownBudgetMs);- webcamFinalized = webcamEncoder.finalize();- logStopStep("webcam-encoder-finalize");+ if (!screenFinalized) {+ std::cerr << "ERROR: Failed to finalize the recording" << std::endl;}- // Report success the moment the files are durable, not at the end of the- // process's life. Finalize is what writes the MP4 index; everything after it- // is housekeeping that cannot improve the recording but can still wedge on a- // bad driver. Announcing here means a watchdog kill during teardown costs- // the user nothing -- the app reads this line and keeps the recording.+ // Report success the moment the screen file is durable, not at the end of+ // the process's life. Finalize is what writes the MP4 index; everything+ // after it is housekeeping that cannot improve that file but can still+ // wedge on a bad driver. Announcing here means a watchdog kill during+ // teardown costs the user nothing -- the app reads this line and keeps the+ // recording.//- // Which is exactly why the finalize results are checked. The app treats this- // line as proof the file is playable, so announcing it after a failed- // Finalize would hand the editor an MP4 with no index and call it a success.- if (!screenFinalized || !webcamFinalized) {- std::cerr << "ERROR: Failed to finalize the recording" << std::endl;- }- if (!encodeFailed && screenFinalized && webcamFinalized) {+ // Gated on the SCREEN finalize alone, and printed before the webcam's.+ // The app treats this line as proof the screen file is playable, so a+ // failed screen Finalize must not reach it. The webcam is a second,+ // optional file and must not be able to veto the first: letting it decide+ // meant one bad camera clip discarded a complete capture, and because both+ // finalizes share the same ceiling, a slow screen finalize could leave the+ // webcam step no budget at all and get the process killed before this line+ // ever ran. A webcam that fails below is an error on stderr and a non-zero+ // exit -- not a lost recording.+ if (!encodeFailed && screenFinalized) {std::cout << "{\"event\":\"recording-stopped\",\"schemaVersion\":2,\"screenPath\":\""<< jsonEscape(config.outputPath) << "\"";if (writeSeparateWebcam) {@@ -1158,6 +1163,16 @@ int main(int argc, char* argv[]) {std::cout << "Recording stopped. Output path: " << config.outputPath << std::endl;}+ bool webcamFinalized = true;+ if (writeSeparateWebcam) {+ beginStopStep("webcam-encoder-finalize", shutdownBudgetMs);+ webcamFinalized = webcamEncoder.finalize();+ logStopStep("webcam-encoder-finalize");+ if (!webcamFinalized) {+ std::cerr << "ERROR: Failed to finalize the webcam recording" << std::endl;+ }+ }+// Releasing the device goes last: by now no thread can still be holding the// D3D context.beginStopStep("wgc-session-close", stepBudgetMs);diff --git a/electron/recording/nativeWindowsCaptureStop.test.ts b/electron/recording/nativeWindowsCaptureStop.test.tsindex 1d77839bf..7ba34317c 100644--- a/electron/recording/nativeWindowsCaptureStop.test.ts+++ b/electron/recording/nativeWindowsCaptureStop.test.ts@@ -146,6 +146,27 @@ describe("waitForNativeWindowsCaptureStop", () => {await expect(pending).resolves.toEqual({ ok: true, screenVideoPath: "C:\\rec\\a.mp4" });});+ /**+ * The webcam is a second, optional file, and the helper announces the screen+ * recording before finalizing it precisely so a bad camera clip cannot veto a+ * complete capture. The exit code is non-zero and the reason is on stderr;+ * the screen MP4 is still finished and must still be kept.+ */+ it("keeps the screen recording when only the webcam failed to finalize", async () => {+ const pending = waitForNativeWindowsCaptureStop({+ proc: asProc(helper),+ targetPath: "C:\\rec\\a.mp4",+ readOutput: () =>+ "Recording stopped. Output path: C:\\rec\\a.mp4\n" ++ "[stop-timing] step=webcam-encoder-finalize elapsed_ms=900\n" ++ "ERROR: Failed to finalize the webcam recording\n",+ });++ helper.exit(1);++ await expect(pending).resolves.toEqual({ ok: true, screenVideoPath: "C:\\rec\\a.mp4" });+ });+it("classifies the helper's own shutdown watchdog as a stop timeout", async () => {const pending = waitForNativeWindowsCaptureStop({proc: asProc(helper),diff --git a/scripts/diagnostic-tool/diagnostic.mjs b/scripts/diagnostic-tool/diagnostic.mjsindex 3b08d798c..f19020ae5 100644--- a/scripts/diagnostic-tool/diagnostic.mjs+++ b/scripts/diagnostic-tool/diagnostic.mjs@@ -149,8 +149,12 @@ function buildConfig(opts) {function parseStopTiming(stderrText) {const lines = [];for (const line of stderrText.split(/\r?\n/)) {- const m = line.match(/\[stop-timing\]\s+step=(\S+)\s+elapsed_ms=(\d+)/);- if (m) lines.push({ step: m[1], elapsedMs: Number(m[2]) });+ // `phase` is the point of the whole log: `begin` is the step being+ // entered, `abandoned` names the step the shutdown watchdog gave up on.+ // Dropping it left the report unable to say which step hung -- the one+ // question a #252 bug report has to answer.+ const m = line.match(/\[stop-timing\]\s+step=(\S+)\s+elapsed_ms=(\d+)(?:\s+phase=(\S+))?/);+ if (m) lines.push({ step: m[1], elapsedMs: Number(m[2]), phase: m[3] ?? "end" });}return lines;}@@ -303,7 +307,14 @@ async function main() {console.log(`[diag] stop elapsed: ${report.stopElapsedMs}ms`);console.log(`[diag] stop timing steps:`);for (const entry of report.stopTiming) {- console.log(`[diag] ${entry.step.padEnd(28)} ${entry.elapsedMs}ms`);+ // Only the outcome of each step, so the summary reads as one line per+ // step rather than an entry-and-exit pair, and an abandoned step is+ // impossible to miss.+ if (entry.phase === "begin") {+ continue;+ }+ const suffix = entry.phase === "end" ? "" : ` <-- ${entry.phase.toUpperCase()}`;+ console.log(`[diag] ${entry.step.padEnd(28)} ${entry.elapsedMs}ms${suffix}`);}console.log(`[diag] report: ${outputPath}`);}diff --git a/scripts/test-windows-wgc-helper.mjs b/scripts/test-windows-wgc-helper.mjsindex 69c1c5716..849bbd6e9 100644--- a/scripts/test-windows-wgc-helper.mjs+++ b/scripts/test-windows-wgc-helper.mjs@@ -45,8 +45,18 @@ const WITH_STALLED_READBACK =process.env.OPENSCREEN_WGC_TEST_STALL_READBACK === "true" ||process.argv.includes("--stall-readback");const STALL_READBACK_MS = Number(process.env[STALL_READBACK_ENV] ?? 60_000);-/** The helper's own shutdown budget is 10s; anything past this is a hang. */-const STOP_HANG_LIMIT_MS = 30_000;+const STOP_BUDGET_ENV = "OPENSCREEN_WGC_STOP_BUDGET_MS";+/**+ * The helper's global shutdown ceiling, pinned into its environment below so+ * the harness and the helper cannot drift apart. It matters because the+ * encoder-finalize step is the one allowed to spend the whole ceiling — issue+ * #34 exists because a long software-encoder finalize legitimately takes+ * seconds — so a limit below it would kill a helper that was still working and+ * report it as the #252 hang.+ */+const STOP_BUDGET_MS = Number(process.env[STOP_BUDGET_ENV] ?? 50_000);+/** Past the helper's own ceiling it never ended itself, which IS issue #252. */+const STOP_HANG_LIMIT_MS = STOP_BUDGET_MS + 15_000;/** A healthy stop is well under a second. */const STOP_LATENCY_BUDGET_MS = 15_000;@@ -59,6 +69,7 @@ function runHelper(config, { injectDefaultSinkWriterFailure = false, stallReadbaconst env = { ...process.env };delete env[INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV];delete env[STALL_READBACK_ENV];+ env[STOP_BUDGET_ENV] = String(STOP_BUDGET_MS);if (injectDefaultSinkWriterFailure) {env[INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV] = "1";}@@ -124,9 +135,16 @@ function runHelper(config, { injectDefaultSinkWriterFailure = false, stallReadba});}-/** Every `[stop-timing] step=<name>` the helper emitted, in order. */+/**+ * Every `[stop-timing]` step the helper *finished*, in order.+ *+ * `phase=begin` is the same step announced on entry, so counting both listed+ * every step twice. `phase=abandoned` is kept: that step did end, just badly.+ */function readStopTimingSteps(stderr) {- return [...stderr.matchAll(/\[stop-timing\]\s+step=(\S+)/g)].map((match) => match[1]);+ return [...stderr.matchAll(/\[stop-timing\]\s+step=(\S+)\s+elapsed_ms=\d+(?:\s+phase=(\S+))?/g)]+ .filter((match) => match[2] !== "begin")+ .map((match) => match[1]);}function assertStopWasClean(result) {diff --git a/technical-documentation/architecture/recording.md b/technical-documentation/architecture/recording.mdindex c296743a3..01337f210 100644--- a/technical-documentation/architecture/recording.md+++ b/technical-documentation/architecture/recording.md@@ -68,7 +68,7 @@ Cursor samples are persisted as cursor telemetry rather than baked into editable## Known gaps- A window with odd client dimensions can produce black video: H.264 encoding requires even dimensions (`electron/native/wgc-capture/src/wgc_session.cpp:38`).-- The Windows helper's frame lock (`electron/native/wgc-capture/src/main.cpp`) is still held across blocking, uninterruptible D3D11 work: the WGC callback's `CopyResource`, and the video writer's `Map(D3D11_MAP_READ)` readback in `mf_encoder.cpp`. A driver that stalls inside either one still costs the recording. What no longer happens is a hang: stop detection runs on `CaptureControl::stopMutex`, which no frame thread ever touches, and a shutdown watchdog force-exits the helper if the sequence overruns `OPENSCREEN_WGC_STOP_BUDGET_MS` (10s), naming the step it died in. Getting the readback out of the lock, and picking the D3D adapter that actually drives the captured monitor instead of adapter 0, are the outstanding fixes (issue #252).+- The Windows helper's frame lock (`electron/native/wgc-capture/src/main.cpp`) is still held across blocking, uninterruptible D3D11 work: the WGC callback's `CopyResource`, and the video writer's `Map(D3D11_MAP_READ)` readback in `mf_encoder.cpp`. A driver that stalls inside either one still costs the recording. What no longer happens is a hang: stop detection runs on `CaptureControl::stopMutex`, which no frame thread ever touches, and a shutdown watchdog force-exits the helper when a step overruns its budget, naming the step it died in. Each step gets `OPENSCREEN_WGC_STEP_BUDGET_MS` (8s by default) and that is the bound which normally fires; the whole shutdown is capped by `OPENSCREEN_WGC_STOP_BUDGET_MS` (50s by default), which the encoder-finalize step alone is allowed to spend in full because a long software-encoder finalize legitimately takes seconds (issue #34). Getting the readback out of the lock, and picking the D3D adapter that actually drives the captured monitor instead of adapter 0, are the outstanding fixes (issue #252).- Linux/Wayland can produce no usable frames on the `getDisplayMedia` fallback because Chromium initializes Vulkan against the Ozone Wayland backend. The PipeWire helper path is unaffected.- On Linux the compositor's source picker appears on every recording. That is deliberate — see "Why Linux sends no source identity" — but it is an interruption, and there is currently no way to reuse a previous choice without also making it impossible to change.- Holding a portal session across the countdown means the compositor's "screen is being shared" indicator is up before recording begins. That is honest — access really has been granted — but the user can click it to revoke, or close the window they picked. The helper's exit surfaces as a rejected `waitUntilSourceSelected`; the session is not yet subscribed to the portal's `Session::Closed` signal, so a revocation is reported as a failed start rather than a specific message.