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
test(wgc-capture): exercise automatic software fallback
My-Deniaac36d52d38e2
diff --git a/electron/native/README.md b/electron/native/README.mdindex 0d76b1451..79399d46b 100644--- a/electron/native/README.md+++ b/electron/native/README.md@@ -95,6 +95,7 @@ Smoke-test the helper with:```powershellnpm run test:wgc-helper:winnpm run test:wgc-helper:win -- --software-encoder+npm run test:wgc-helper:win -- --software-fallbacknpm run test:wgc-window:winnpm run test:wgc-audio:winnpm run test:wgc-mic:win@@ -102,6 +103,31 @@ npm run test:wgc-mixed-audio:winnpm run test:wgc-webcam:win```+`--software-encoder` keeps testing the explicit `software-preferred` path with+`preferSoftwareEncoder: true`. `--software-fallback` keeps+`preferSoftwareEncoder: false` and sets+`OPENSCREEN_WGC_TEST_INJECT_DEFAULT_SINK_WRITER_FAILURE_ONCE=1` only for the helper+child process. At the first default/non-software `MFCreateSinkWriterFromURL` call, the+helper returns `HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)` (`0x80070003`) exactly once.+The existing retry then performs the real local Microsoft software H.264 MFT registration,+creates the real fallback sink writer, captures and encodes real frames, and must report+`software-fallback`.++For a full-application test, set the same test-only variable before launching Electron and+remove it afterward:++```powershell+$env:OPENSCREEN_WGC_TEST_INJECT_DEFAULT_SINK_WRITER_FAILURE_ONCE = "1"+npm run dev+Remove-Item Env:OPENSCREEN_WGC_TEST_INJECT_DEFAULT_SINK_WRITER_FAILURE_ONCE+```++Only the exact value `1` enables this native test hook. It is not a preference or UI option,+and it is inert when absent. This is deterministic fault injection at the original+sink-writer failure boundary. It proves the application's automatic fallback behavior after+that controlled failure; it does **not** claim validation on a naturally affected machine+with a genuinely broken GPU driver or naturally missing hardware H.264 MFT.+To validate a specific native webcam manually:```powershelldiff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cppindex 95d9dcc74..30a3069d6 100644--- a/electron/native/wgc-capture/src/main.cpp+++ b/electron/native/wgc-capture/src/main.cpp@@ -396,6 +396,15 @@ int main(int argc, char* argv[]) {return 1;}+ char injectDefaultSinkWriterFailure[2]{};+ const DWORD injectDefaultSinkWriterFailureLength = GetEnvironmentVariableA(+ "OPENSCREEN_WGC_TEST_INJECT_DEFAULT_SINK_WRITER_FAILURE_ONCE",+ injectDefaultSinkWriterFailure,+ static_cast<DWORD>(sizeof(injectDefaultSinkWriterFailure)));+ const bool injectDefaultSinkWriterFailureOnce =+ injectDefaultSinkWriterFailureLength == 1 &&+ injectDefaultSinkWriterFailure[0] == '1';+std::cout << "{\"event\":\"ready\",\"schemaVersion\":2}" << std::endl;WgcSession session;@@ -506,6 +515,7 @@ int main(int argc, char* argv[]) {MFEncoderOptions encoderOptions{};encoderOptions.preferSoftwareEncoder = config.preferSoftwareEncoder;+ encoderOptions.injectDefaultSinkWriterFailureOnce = injectDefaultSinkWriterFailureOnce;MFEncoder encoder;if (!encoder.initialize(@@ -528,6 +538,8 @@ int main(int argc, char* argv[]) {<< "}" << std::endl;MFEncoder webcamEncoder;if (writeSeparateWebcam) {+ MFEncoderOptions webcamEncoderOptions = encoderOptions;+ webcamEncoderOptions.injectDefaultSinkWriterFailureOnce = false;const int webcamPixels = std::max(1, webcamCapture.width()) * std::max(1, webcamCapture.height());const int webcamBitrate = webcamPixels >= 1280 * 720 ? 8'000'000 : 4'000'000;if (!webcamEncoder.initialize(@@ -539,7 +551,7 @@ int main(int argc, char* argv[]) {session.device(),session.context(),nullptr,- encoderOptions)) {+ webcamEncoderOptions)) {std::cerr << "ERROR: Failed to initialize native webcam encoder" << std::endl;return 1;}diff --git a/electron/native/wgc-capture/src/mf_encoder.cpp b/electron/native/wgc-capture/src/mf_encoder.cppindex cf067150f..42b708910 100644--- a/electron/native/wgc-capture/src/mf_encoder.cpp+++ b/electron/native/wgc-capture/src/mf_encoder.cpp@@ -168,6 +168,10 @@ HRESULT ensureSoftwareH264EncoderRegisteredForProcess() {if (FAILED(result)) {std::cerr << "ERROR: MFTRegisterLocalByCLSID(CLSID_MSH264EncoderMFT) failed (hr=0x"<< std::hex << result << std::dec << ")" << std::endl;+ } else {+ std::cerr+ << "INFO: Registered the Microsoft software H.264 MFT locally for this helper process."+ << std::endl;}return result;}@@ -175,6 +179,8 @@ HRESULT ensureSoftwareH264EncoderRegisteredForProcess() {HRESULT createSinkWriterFromUrl(const std::wstring& outputPath,bool forceSoftwareEncoder,+ bool injectDefaultSinkWriterFailureOnce,+ bool& injectedDefaultSinkWriterFailure,Microsoft::WRL::ComPtr<IMFSinkWriter>& sinkWriter,SinkWriterCreateStage& failedStage) {// Default to the sink-writer creation step; the software-path steps below@@ -215,8 +221,25 @@ HRESULT createSinkWriterFromUrl(}failedStage = SinkWriterCreateStage::CreateSinkWriter;- return MFCreateSinkWriterFromURL(+ if (+ !forceSoftwareEncoder &&+ injectDefaultSinkWriterFailureOnce &&+ !injectedDefaultSinkWriterFailure) {+ injectedDefaultSinkWriterFailure = true;+ std::cerr+ << "TEST-ONLY: Injected default MFCreateSinkWriterFromURL failure "+ << "(hr=0x80070003); injection consumed exactly once."+ << std::endl;+ return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);+ }++ const HRESULT sinkWriterHr = MFCreateSinkWriterFromURL(outputPath.c_str(), nullptr, attributes.Get(), &sinkWriter);+ if (SUCCEEDED(sinkWriterHr) && forceSoftwareEncoder) {+ std::cerr << "INFO: Created the real software H.264 sink writer successfully."+ << std::endl;+ }+ return sinkWriterHr;}void logSinkWriterCreateFailure(HRESULT sinkWriterHr, const AudioInputFormat* audioFormat) {@@ -354,6 +377,8 @@ bool MFEncoder::initialize(setFrameRate(inputType.Get(), static_cast<UINT32>(fps_));setPixelAspectRatio(inputType.Get());+ bool injectedDefaultSinkWriterFailure = false;+auto resetSinkWriterAttempt = [&]() {sinkWriter_.Reset();videoStreamIndex_ = 0;@@ -372,6 +397,8 @@ bool MFEncoder::initialize(const HRESULT sinkWriterHr = createSinkWriterFromUrl(outputPath,forceSoftwareEncoder,+ options.injectDefaultSinkWriterFailureOnce,+ injectedDefaultSinkWriterFailure,sinkWriter_,failedStage);if (FAILED(sinkWriterHr)) {diff --git a/electron/native/wgc-capture/src/mf_encoder.h b/electron/native/wgc-capture/src/mf_encoder.hindex 502ba5cf2..8f5787481 100644--- a/electron/native/wgc-capture/src/mf_encoder.h+++ b/electron/native/wgc-capture/src/mf_encoder.h@@ -28,6 +28,7 @@ struct AudioInputFormat {struct MFEncoderOptions {bool preferSoftwareEncoder = false;+ bool injectDefaultSinkWriterFailureOnce = false;};constexpr const char* kVideoEncoderSelectionDefault = "default";diff --git a/scripts/test-windows-wgc-helper.mjs b/scripts/test-windows-wgc-helper.mjsindex d5ba55409..c6c69441e 100644--- a/scripts/test-windows-wgc-helper.mjs+++ b/scripts/test-windows-wgc-helper.mjs@@ -29,10 +29,26 @@ const CAPTURE_CURSOR =const WITH_SOFTWARE_ENCODER =process.env.OPENSCREEN_WGC_TEST_SOFTWARE_ENCODER === "true" ||process.argv.includes("--software-encoder");+const WITH_SOFTWARE_FALLBACK =+ process.env.OPENSCREEN_WGC_TEST_SOFTWARE_FALLBACK === "true" ||+ process.argv.includes("--software-fallback");+const INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV =+ "OPENSCREEN_WGC_TEST_INJECT_DEFAULT_SINK_WRITER_FAILURE_ONCE";+const INJECTION_MARKER = "TEST-ONLY: Injected default MFCreateSinkWriterFromURL failure";-function runHelper(config) {+if (WITH_SOFTWARE_ENCODER && WITH_SOFTWARE_FALLBACK) {+ throw new Error("--software-encoder and --software-fallback are mutually exclusive");+}++function runHelper(config, { injectDefaultSinkWriterFailure = false } = {}) {return new Promise((resolve, reject) => {+ const env = { ...process.env };+ delete env[INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV];+ if (injectDefaultSinkWriterFailure) {+ env[INJECT_DEFAULT_SINK_WRITER_FAILURE_ENV] = "1";+ }const child = spawn(HELPER_PATH, [JSON.stringify(config)], {+ env,stdio: ["pipe", "pipe", "pipe"],windowsHide: true,});@@ -276,7 +292,9 @@ const config = {let result;try {- result = await runHelper(config);+ result = await runHelper(config, {+ injectDefaultSinkWriterFailure: WITH_SOFTWARE_FALLBACK,+ });} finally {if (fixtureWindow) {fixtureWindow.child.kill();@@ -306,6 +324,7 @@ const webcamStreams =webcamOutputPath && fs.existsSync(webcamOutputPath) ? probeStreams(webcamOutputPath) : [];const hasVideo = streams.some((stream) => stream.codec_type === "video");const hasAudio = streams.some((stream) => stream.codec_type === "audio");+const videoStream = streams.find((stream) => stream.codec_type === "video");const webcamFormatLine = result.stdout.split(/\r?\n/).find((line) => line.includes('"event":"webcam-format"'));@@ -335,6 +354,26 @@ const nativeMicrophoneDiagnostics = result.stderrif (!hasVideo) {throw new Error(`WGC helper output has no video stream: ${outputPath}`);}+if (videoStream.codec_name !== "h264") {+ throw new Error(+ `WGC helper output video codec is ${videoStream.codec_name ?? "unknown"}, expected h264: ${outputPath}`,+ );+}+const videoDurationSeconds = Number(videoStream.duration);+const minimumPlausibleDurationSeconds = Math.max(0.5, (DURATION_MS / 1000) * 0.5);+const maximumPlausibleDurationSeconds = Math.max(+ minimumPlausibleDurationSeconds,+ (DURATION_MS / 1000) * 2 + 2,+);+if (+ !Number.isFinite(videoDurationSeconds) ||+ videoDurationSeconds < minimumPlausibleDurationSeconds ||+ videoDurationSeconds > maximumPlausibleDurationSeconds+) {+ throw new Error(+ `WGC helper output duration ${videoStream.duration ?? "unknown"}s is not plausible for a ${DURATION_MS}ms recording: ${outputPath}`,+ );+}if (WITH_WEBCAM && !webcamStreams.some((stream) => stream.codec_type === "video")) {throw new Error(`WGC helper webcam output has no video stream: ${webcamOutputPath}`);}@@ -347,13 +386,56 @@ if (`WGC helper did not apply requested cursor capture mode (${CAPTURE_CURSOR}): ${result.stdout}`,);}+const expectedEncoderSelection = WITH_SOFTWARE_FALLBACK+ ? "software-fallback"+ : WITH_SOFTWARE_ENCODER+ ? "software-preferred"+ : "default";if (- WITH_SOFTWARE_ENCODER &&- (!encoderSelection ||- typeof encoderSelection.video !== "string" ||- !encoderSelection.video.startsWith("software"))+ encoderSelection?.video !== expectedEncoderSelection ||+ encoderSelection.preferSoftwareEncoder !== WITH_SOFTWARE_ENCODER) {- throw new Error(`WGC helper did not use the requested software encoder path: ${result.stdout}`);+ throw new Error(+ `WGC helper encoder selection was ${JSON.stringify(encoderSelection)}, expected ${expectedEncoderSelection} with preferSoftwareEncoder=${WITH_SOFTWARE_ENCODER}: ${result.stdout}`,+ );+}++const combinedHelperOutput = `${result.stdout}\n${result.stderr}`;+const helperDiagnosticLines = combinedHelperOutput.split(/\r?\n/).filter(Boolean);+const injectionLines = helperDiagnosticLines.filter((line) => line.includes(INJECTION_MARKER));+const fallbackDiagnosticPatterns = [+ INJECTION_MARKER,+ "WARNING: Default MFCreateSinkWriterFromURL failed (hr=0x80070003)",+ "retrying with the Microsoft software H.264 encoder.",+ "INFO: Registered the Microsoft software H.264 MFT locally for this helper process.",+ "INFO: Created the real software H.264 sink writer successfully.",+];+const fallbackDiagnostics = WITH_SOFTWARE_FALLBACK+ ? helperDiagnosticLines.filter((line) =>+ fallbackDiagnosticPatterns.some((pattern) => line.includes(pattern)),+ )+ : [];+if (WITH_SOFTWARE_FALLBACK) {+ if (+ injectionLines.length !== 1 ||+ !injectionLines[0].includes("hr=0x80070003") ||+ !injectionLines[0].includes("consumed exactly once")+ ) {+ throw new Error(+ `Expected exactly one consumed 0x80070003 test-only injection, found ${injectionLines.length}: ${combinedHelperOutput}`,+ );+ }+ for (const pattern of fallbackDiagnosticPatterns.slice(1)) {+ if (!helperDiagnosticLines.some((line) => line.includes(pattern))) {+ throw new Error(+ `WGC helper fallback diagnostics are missing ${JSON.stringify(pattern)}: ${combinedHelperOutput}`,+ );+ }+ }+} else if (injectionLines.length !== 0) {+ throw new Error(+ `WGC helper unexpectedly injected a default sink-writer failure: ${combinedHelperOutput}`,+ );}if ((WITH_SYSTEM_AUDIO || WITH_MICROPHONE) && !hasAudio) {throw new Error(`WGC helper output has no audio stream: ${outputPath}`);@@ -396,6 +478,7 @@ console.log(selectedWebcamDeviceName: webcamFormat?.deviceName,nativeMicrophoneDiagnostics,nativeWebcamDiagnostics,+ fallbackDiagnostics,firstFrameLuma: frameLuma,},null,