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 burning the step budget on a join that cannot succeed
EtienneLescotc51a70b55eda
diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cppindex c64d79703..a9e21d45c 100644--- a/electron/native/wgc-capture/src/main.cpp+++ b/electron/native/wgc-capture/src/main.cpp@@ -682,6 +682,16 @@ int main(int argc, char* argv[]) {// ordinary hardware, so the stop path can be regression-tested at all.const int testStallReadbackMs =std::max(0, readEnvInt("OPENSCREEN_WGC_TEST_STALL_READBACK_MS", 0));+ // Test-only: stall the WGC frame *callback* itself while it holds the+ // same frame lock, rather than the writer's readback -- the shape+ // getopenscreen/openscreen#460 actually reproduced on Intel HD 520+ // ("A WGC frame callback did not finish"). Distinct from+ // testStallReadbackMs above because quiesceCapture()'s drain only ever+ // sees the callback side: a stall placed in the writer instead leaves+ // callbacksInFlight_ at zero and wgcDrained true, which cannot exercise+ // the video-writer-join skip this stall exists to test.+ const int testStallFrameCallbackMs =+ std::max(0, readEnvInt("OPENSCREEN_WGC_TEST_STALL_FRAME_CALLBACK_MS", 0));std::cout << "{\"event\":\"ready\",\"schemaVersion\":2}" << std::endl;@@ -931,6 +941,18 @@ int main(int argc, char* argv[]) {}}+ // Gated on an already-arrived first frame: main() blocks up to 10s+ // waiting for firstFrameWritten before it will even print+ // recording-started, a startup budget this stall is meant to outlast+ // (it needs to still be asleep when `stop` arrives, seconds later).+ // Stalling the first frame trips that unrelated timeout instead of+ // reaching the steady-state shutdown path this exists to test, and+ // does not match the real report either -- getopenscreen/openscreen+ // #460's diagnostic shows recording-started succeeding before the+ // hang.+ if (testStallFrameCallbackMs > 0 && firstFrameWritten.load()) {+ std::this_thread::sleep_for(std::chrono::milliseconds(testStallFrameCallbackMs));+ }session.context()->CopyResource(latestFrameTexture.Get(), texture);latestFrameTimestampHns = timestampHns;if (!firstFrameWritten.exchange(true)) {@@ -1420,8 +1442,47 @@ int main(int argc, char* argv[]) {}logStopStep("audio-mixer");beginStopStep("video-writer-join", stepBudgetMs);- stopVideoWriter();- logStopStep("video-writer-join");+ if (wgcDrained) {+ stopVideoWriter();+ logStopStep("video-writer-join");+ } else {+ // wgc-quiesce already reported the frame callback stuck inside the+ // driver (getopenscreen/openscreen#460 on Intel HD 520: a+ // CopyResource that never returns), still holding the same+ // frame-state `mutex` writeVideoFrames takes for its own+ // per-iteration wait -- the one it also needs to notice+ // stopRequested. Joining is not a step that can time out here, it is+ // one that cannot ever succeed, and this is not the only step that+ // assumed it would: encoder.finalize() below resets the very D3D+ // device/context a still-blocked writer thread might resume touching+ // the moment that lock frees, and quiesceCapture()/stop() already+ // treat "leave everything alone and let process exit reclaim it" as+ // the only safe response to exactly this state. So this ends the+ // process here, on this thread, rather than pretending the rest of a+ // clean shutdown is reachable -- which cost nothing extra before+ // today: the same TerminateProcess happened anyway, just+ // stepBudgetMs later, once this step's own watchdog gave up waiting+ // on a join that could never return. detach() first, not because+ // TerminateProcess needs it (it does not touch the C++ runtime, no+ // std::thread destructor runs), but so nothing between here and the+ // kill can trip over a still-joinable thread.+ //+ // The fragmented sink writes moof+mdat incrementally, roughly once a+ // second, so this is not a new source of loss: whatever was already+ // on disk before the callback wedged is on disk regardless of+ // whether Finalize() ever runs, on this path or the slower one it+ // replaces.+ videoWriterThread.detach();+ std::cerr << "[stop-timing] step=video-writer-join elapsed_ms=" << stopElapsedMs()+ << " phase=abandoned encode_stage=" << encoder.encodeStage()+ << " audio_stage=" << encoder.audioStage() << " reason=frame-callback-stuck"+ << std::endl;+ std::cout << "{\"event\":\"stop-timeout\",\"schemaVersion\":2,\"step\":\"video-writer-join\"}"+ << std::endl;+ std::cout.flush();+ std::cerr.flush();+ TerminateProcess(GetCurrentProcess(), 3);+ }if (usesDxgiInput) {std::cerr << "[frame-drops] gpu_bridge_contended=" << contendedFrames.load() << std::endl;}@@ -1430,7 +1491,9 @@ int main(int argc, char* argv[]) {// the encoder's GPU readback, and audioMixer->stop() joined the only other// thread that writes to it. MFEncoder's own writerMutex_ deliberately does// NOT cover copyFrameToBuffer, so finalizing before those joins would race- // the staging texture -- do not reorder these.+ // the staging texture -- do not reorder these. Reaching this line at all+ // means wgcDrained was true above: the branch that was not is a+ // TerminateProcess call, not a fallthrough.beginStopStep("encoder-finalize", shutdownBudgetMs);const bool screenFinalized = encoder.finalize();logStopStep("encoder-finalize");diff --git a/scripts/test-windows-wgc-helper.mjs b/scripts/test-windows-wgc-helper.mjsindex 1e513c721..ee40838e6 100644--- a/scripts/test-windows-wgc-helper.mjs+++ b/scripts/test-windows-wgc-helper.mjs@@ -45,6 +45,20 @@ 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);+const STALL_FRAME_CALLBACK_ENV = "OPENSCREEN_WGC_TEST_STALL_FRAME_CALLBACK_MS";+/**+ * Reproduces getopenscreen/openscreen#460 on ordinary hardware: stalls the WGC+ * frame *callback* itself while it holds the frame lock, the shape that issue+ * actually reproduced on Intel HD 520 ("A WGC frame callback did not finish").+ * Distinct from WITH_STALLED_READBACK above -- that stalls the writer's own+ * readback, which quiesceCapture()'s drain cannot see (callbacksInFlight_+ * stays at zero), so it cannot exercise the video-writer-join skip this stall+ * exists to test.+ */+const WITH_STALLED_FRAME_CALLBACK =+ process.env.OPENSCREEN_WGC_TEST_STALL_FRAME_CALLBACK === "true" ||+ process.argv.includes("--stall-frame-callback");+const STALL_FRAME_CALLBACK_MS = Number(process.env[STALL_FRAME_CALLBACK_ENV] ?? 60_000);const STOP_BUDGET_ENV = "OPENSCREEN_WGC_STOP_BUDGET_MS";/*** The helper's global shutdown ceiling, pinned into its environment below so@@ -64,11 +78,15 @@ if (WITH_SOFTWARE_ENCODER && WITH_SOFTWARE_FALLBACK) {throw new Error("--software-encoder and --software-fallback are mutually exclusive");}-function runHelper(config, { injectDefaultSinkWriterFailure = false, stallReadbackMs = 0 } = {}) {+function runHelper(+ config,+ { injectDefaultSinkWriterFailure = false, stallReadbackMs = 0, stallFrameCallbackMs = 0 } = {},+) {return new Promise((resolve, reject) => {const env = { ...process.env };delete env[INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV];delete env[STALL_READBACK_ENV];+ delete env[STALL_FRAME_CALLBACK_ENV];env[STOP_BUDGET_ENV] = String(STOP_BUDGET_MS);if (injectDefaultSinkWriterFailure) {env[INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV] = "1";@@ -76,6 +94,9 @@ function runHelper(config, { injectDefaultSinkWriterFailure = false, stallReadbaif (stallReadbackMs > 0) {env[STALL_READBACK_ENV] = String(stallReadbackMs);}+ if (stallFrameCallbackMs > 0) {+ env[STALL_FRAME_CALLBACK_ENV] = String(stallFrameCallbackMs);+ }const child = spawn(HELPER_PATH, [JSON.stringify(config)], {env,stdio: ["pipe", "pipe", "pipe"],@@ -213,6 +234,48 @@ function startFixtureWindow() {});}+/**+ * Windows Graphics Capture delivers frames on compositor damage, not on a+ * fixed clock -- on a genuinely idle desktop the frame pool can go a full+ * test run without ever firing FrameArrived once. That is invisible to most+ * of this harness, which just needs *a* frame eventually, but the+ * stalled-frame-callback regression check needs one to land *inside* the+ * DURATION_MS window specifically, so the stall this injects is actually the+ * thing holding the frame lock when `stop` arrives.+ *+ * Moving the cursor alone does not reliably do this: most modern GPU/driver+ * combinations composite the cursor on its own hardware overlay plane, so+ * repositioning it never touches the desktop bitmap WGC captures (confirmed+ * empirically here -- frames=0 with a cursor-only nudge running the whole+ * test). A visible window changing position is not optional the way the+ * cursor is; DWM has to redraw the area it moved across. Returns a stop+ * function; always call it, paired failure or not, or the window and its+ * PowerShell host outlive the test process.+ */+function startScreenActivity() {+ const child = spawn(+ "powershell",+ [+ "-NoProfile",+ "-Command",+ "Add-Type -AssemblyName System.Windows.Forms; " ++ "$f = New-Object System.Windows.Forms.Form; " ++ "$f.StartPosition = 'Manual'; $f.Location = New-Object System.Drawing.Point(0,0); " ++ "$f.Size = New-Object System.Drawing.Size(200,200); " ++ "$f.TopMost = $true; $f.Show(); " ++ "$x = 0; " ++ "while ($true) { " ++ "$f.Location = New-Object System.Drawing.Point($x, 0); " ++ "$x = ($x + 20) % 200; " ++ "[System.Windows.Forms.Application]::DoEvents(); " ++ "Start-Sleep -Milliseconds 100; " ++ "}",+ ],+ { stdio: ["ignore", "ignore", "ignore"], windowsHide: false },+ );+ return () => child.kill();+}+function normalizeDeviceName(value) {return value.toLowerCase()@@ -413,16 +476,19 @@ const config = {},};+const stopScreenActivity = WITH_STALLED_FRAME_CALLBACK ? startScreenActivity() : null;let result;try {result = await runHelper(config, {injectDefaultSinkWriterFailure: WITH_SOFTWARE_FALLBACK,stallReadbackMs: WITH_STALLED_READBACK ? STALL_READBACK_MS : 0,+ stallFrameCallbackMs: WITH_STALLED_FRAME_CALLBACK ? STALL_FRAME_CALLBACK_MS : 0,});} finally {if (fixtureWindow) {fixtureWindow.child.kill();}+ stopScreenActivity?.();}// The regression check for issue #252. With the frame lock deliberately wedged@@ -453,6 +519,51 @@ if (WITH_STALLED_READBACK) {process.exit(0);}+// The regression check for getopenscreen/openscreen#460: a frame callback+// wedged inside the driver, confirmed on real hardware via a Save Diagnostics+// report. Before the fix, video-writer-join burned its whole step budget+// joining a thread parked behind that same stuck callback -- this asserts+// both that the helper still exits promptly (not the ~13s that step's own+// budget alone would cost) and that it took the specific skip path rather+// than any other route to exiting.+if (WITH_STALLED_FRAME_CALLBACK) {+ if (result.stopHung) {+ throw new Error(+ `Helper survived ${STOP_HANG_LIMIT_MS}ms past "stop" with a stalled frame callback. ` ++ "Its shutdown watchdog did not fire (issue #460).",+ );+ }+ const steps = readStopTimingSteps(result.stderr);+ if (!steps.includes("command-received")) {+ throw new Error(`Helper never acknowledged "stop". Steps seen: ${steps.join(", ") || "none"}`);+ }+ if (!result.stderr.includes("reason=frame-callback-stuck")) {+ throw new Error(+ `Helper did not take the video-writer-join skip path. stderr:\n${result.stderr}`,+ );+ }+ // wgc-quiesce's own drain is a fixed 5000ms, so a healthy skip lands+ // there plus the near-instant audio/microphone/webcam steps -- nowhere+ // near the ~13s (5s drain + the 8s step budget) the join it replaces+ // would have cost before this fix.+ const STALLED_FRAME_CALLBACK_LATENCY_BUDGET_MS = 10_000;+ if (+ result.stopLatencyMs !== null &&+ result.stopLatencyMs > STALLED_FRAME_CALLBACK_LATENCY_BUDGET_MS+ ) {+ throw new Error(+ `Stop took ${result.stopLatencyMs}ms with a stalled frame callback, over the ` ++ `${STALLED_FRAME_CALLBACK_LATENCY_BUDGET_MS}ms budget the video-writer-join skip should keep it under.`,+ );+ }+ console.log("WGC helper stalled-frame-callback stop check passed", {+ stopLatencyMs: result.stopLatencyMs,+ steps,+ });+ fs.rmSync(outputPath, { force: true });+ process.exit(0);+}+assertStopWasClean(result);if (result.code !== 0) {