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: snap illegal AAC sample rates to 48 kHz on Windows
超超超超超级喜欢你的达妮娅37590de81811
diff --git a/electron/native/wgc-capture/CMakeLists.txt b/electron/native/wgc-capture/CMakeLists.txtindex c2947df77..99041a02b 100644--- a/electron/native/wgc-capture/CMakeLists.txt+++ b/electron/native/wgc-capture/CMakeLists.txt@@ -89,3 +89,25 @@ target_link_libraries(cursor-sampler PRIVATEgdi32gdiplus)++add_executable(audio_sample_utils_test+ src/audio_sample_utils.cpp+ src/audio_sample_utils.h+ src/audio_sample_utils_test.cpp+)++target_compile_definitions(audio_sample_utils_test PRIVATE+ NOMINMAX+ WIN32_LEAN_AND_MEAN+ _WIN32_WINNT=0x0A00+)++target_compile_options(audio_sample_utils_test PRIVATE /EHsc /W4 /utf-8)++target_link_libraries(audio_sample_utils_test PRIVATE+ mf+ mfplat+ mfreadwrite+ mfuuid+ ole32+)diff --git a/electron/native/wgc-capture/src/audio_sample_utils.cpp b/electron/native/wgc-capture/src/audio_sample_utils.cppindex 5e60860c9..26fb57df5 100644--- a/electron/native/wgc-capture/src/audio_sample_utils.cpp+++ b/electron/native/wgc-capture/src/audio_sample_utils.cpp@@ -87,6 +87,21 @@ double readMappedChannel(const BYTE* source, const AudioInputFormat& format, sizreturn readSampleAsDouble(source, format, frameIndex, std::min(targetChannel, format.channels - 1));}+UINT32 aacCompatibleSampleRate(UINT32 sampleRate) {+ constexpr UINT32 kAacSampleRates[] = {+ 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000,+ };+ if (sampleRate == 0) {+ return 48000;+ }+ for (UINT32 rate : kAacSampleRates) {+ if (sampleRate == rate) {+ return rate;+ }+ }+ return 48000;+}+} // namespaceconstexpr int64_t HnsPerSecond = 10'000'000;@@ -100,10 +115,16 @@ bool sameAudioFormatForMixing(const AudioInputFormat& left, const AudioInputFormleft.avgBytesPerSec == right.avgBytesPerSec;}+// Microsoft AAC encoder (MFAudioFormat_AAC) sample rates. WASAPI loopback+// often reports 96000 or 192000; those are legal PCM mix rates but not AAC+// input rates, and SetInputMediaType then fails with MF_E_INVALIDMEDIATYPE+// (0xc00d36b4). Keep legal rates as-is so a working 44100/48000 path is+// unchanged; snap everything else (including 0) to 48000. The mixer already+// resamples through convertAudioWithGain when the source rate differs.AudioInputFormat makeAacCompatibleAudioFormat(const AudioInputFormat& source) {AudioInputFormat format{};format.subtype = MFAudioFormat_PCM;- format.sampleRate = source.sampleRate > 0 ? source.sampleRate : 48000;+ format.sampleRate = aacCompatibleSampleRate(source.sampleRate);format.channels = 2;format.bitsPerSample = 16;format.blockAlign = format.channels * (format.bitsPerSample / 8);diff --git a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp b/electron/native/wgc-capture/src/audio_sample_utils_test.cppnew file mode 100644index 000000000..81f5cfb78--- /dev/null+++ b/electron/native/wgc-capture/src/audio_sample_utils_test.cpp@@ -0,0 +1,325 @@+#include "audio_sample_utils.h"++#include <mfapi.h>+#include <mferror.h>+#include <mfidl.h>+#include <mfreadwrite.h>+#include <wrl/client.h>++#include <cstdint>+#include <iostream>+#include <string>+#include <vector>++namespace {++int g_ran = 0;+int g_failed = 0;++AudioInputFormat makeFormat(+ GUID subtype,+ UINT32 sampleRate,+ UINT32 channels,+ UINT32 bitsPerSample) {+ AudioInputFormat format{};+ format.subtype = subtype;+ format.sampleRate = sampleRate;+ format.channels = channels;+ format.bitsPerSample = bitsPerSample;+ format.blockAlign = channels * (bitsPerSample / 8);+ format.avgBytesPerSec = sampleRate * format.blockAlign;+ return format;+}++void expect(const char* name, bool ok, const std::string& detail) {+ g_ran += 1;+ if (ok) {+ std::cout << "PASS " << name << "\n";+ return;+ }+ g_failed += 1;+ std::cout << "FAIL " << name << " " << detail << "\n";+}++std::string describe(const AudioInputFormat& format) {+ return "sampleRate=" + std::to_string(format.sampleRate) ++ " channels=" + std::to_string(format.channels) ++ " bits=" + std::to_string(format.bitsPerSample);+}++std::wstring tempMp4Path() {+ wchar_t dir[MAX_PATH]{};+ GetTempPathW(MAX_PATH, dir);+ return std::wstring(dir) + L"openscreen-mf-aac-probe-" ++ std::to_wstring(GetCurrentProcessId()) + L".mp4";+}++HRESULT trySetAacPcmRate(UINT32 sampleRate, IMFAttributes* attributes = nullptr) {+ const std::wstring path = tempMp4Path();+ DeleteFileW(path.c_str());++ Microsoft::WRL::ComPtr<IMFSinkWriter> writer;+ HRESULT hr = MFCreateSinkWriterFromURL(path.c_str(), nullptr, attributes, &writer);+ if (FAILED(hr)) {+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> outputType;+ hr = MFCreateMediaType(&outputType);+ if (FAILED(hr)) {+ return hr;+ }+ outputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ outputType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_AAC);+ outputType->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2);+ outputType->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, sampleRate);+ outputType->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16);+ outputType->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, 24000);+ outputType->SetUINT32(MF_MT_AAC_PAYLOAD_TYPE, 0);++ DWORD streamIndex = 0;+ hr = writer->AddStream(outputType.Get(), &streamIndex);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> inputType;+ hr = MFCreateMediaType(&inputType);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }+ inputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ inputType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);+ inputType->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2);+ inputType->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, sampleRate);+ inputType->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16);+ inputType->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, 4);+ inputType->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, sampleRate * 4);+ inputType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);++ hr = writer->SetInputMediaType(streamIndex, inputType.Get(), nullptr);+ writer.Reset();+ DeleteFileW(path.c_str());+ return hr;+}++// Same rates as trySetAacPcmRate, but with an H.264 stream first — the helper's+// topology. Distinguishes "96 kHz AAC is illegal" from "audio-only MP4 sink+// writer refuses this type".+HRESULT trySetAacPcmRateWithVideo(UINT32 sampleRate) {+ const std::wstring path = tempMp4Path();+ DeleteFileW(path.c_str());++ Microsoft::WRL::ComPtr<IMFSinkWriter> writer;+ HRESULT hr = MFCreateSinkWriterFromURL(path.c_str(), nullptr, nullptr, &writer);+ if (FAILED(hr)) {+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> videoOut;+ hr = MFCreateMediaType(&videoOut);+ if (FAILED(hr)) {+ return hr;+ }+ videoOut->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);+ videoOut->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);+ videoOut->SetUINT32(MF_MT_AVG_BITRATE, 1'000'000);+ videoOut->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);+ MFSetAttributeSize(videoOut.Get(), MF_MT_FRAME_SIZE, 320, 240);+ MFSetAttributeRatio(videoOut.Get(), MF_MT_FRAME_RATE, 30, 1);+ MFSetAttributeRatio(videoOut.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);++ DWORD videoIndex = 0;+ hr = writer->AddStream(videoOut.Get(), &videoIndex);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> audioOut;+ hr = MFCreateMediaType(&audioOut);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }+ audioOut->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ audioOut->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_AAC);+ audioOut->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2);+ audioOut->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, sampleRate);+ audioOut->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16);+ audioOut->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, 24000);+ audioOut->SetUINT32(MF_MT_AAC_PAYLOAD_TYPE, 0);++ DWORD audioIndex = 0;+ hr = writer->AddStream(audioOut.Get(), &audioIndex);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> videoIn;+ hr = MFCreateMediaType(&videoIn);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }+ videoIn->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);+ videoIn->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32);+ videoIn->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);+ videoIn->SetUINT32(MF_MT_DEFAULT_STRIDE, 320 * 4);+ MFSetAttributeSize(videoIn.Get(), MF_MT_FRAME_SIZE, 320, 240);+ MFSetAttributeRatio(videoIn.Get(), MF_MT_FRAME_RATE, 30, 1);+ MFSetAttributeRatio(videoIn.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);+ hr = writer->SetInputMediaType(videoIndex, videoIn.Get(), nullptr);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> audioIn;+ hr = MFCreateMediaType(&audioIn);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }+ audioIn->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ audioIn->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);+ audioIn->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2);+ audioIn->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, sampleRate);+ audioIn->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16);+ audioIn->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, 4);+ audioIn->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, sampleRate * 4);+ audioIn->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);+ hr = writer->SetInputMediaType(audioIndex, audioIn.Get(), nullptr);+ writer.Reset();+ DeleteFileW(path.c_str());+ return hr;+}++} // namespace++int main() {+ const AudioInputFormat diagnostic = makeFormat(MFAudioFormat_Float, 96000, 8, 32);+ const AudioInputFormat snapped = makeAacCompatibleAudioFormat(diagnostic);+ expect(+ "diag-96000-8ch",+ snapped.sampleRate == 48000 && snapped.channels == 2 && snapped.bitsPerSample == 16 &&+ snapped.subtype == MFAudioFormat_PCM,+ describe(snapped));++ const AudioInputFormat keep48000 =+ makeAacCompatibleAudioFormat(makeFormat(MFAudioFormat_PCM, 48000, 2, 16));+ expect("keep-48000", keep48000.sampleRate == 48000, describe(keep48000));++ const AudioInputFormat keep44100 =+ makeAacCompatibleAudioFormat(makeFormat(MFAudioFormat_PCM, 44100, 2, 16));+ expect("keep-44100", keep44100.sampleRate == 44100, describe(keep44100));++ const AudioInputFormat zeroRate =+ makeAacCompatibleAudioFormat(makeFormat(MFAudioFormat_PCM, 0, 2, 16));+ expect("zero-rate", zeroRate.sampleRate == 48000, describe(zeroRate));++ const AudioInputFormat keep32000 =+ makeAacCompatibleAudioFormat(makeFormat(MFAudioFormat_PCM, 32000, 2, 16));+ expect("keep-32000", keep32000.sampleRate == 32000, describe(keep32000));++ const AudioInputFormat source96k = makeFormat(MFAudioFormat_PCM, 96000, 2, 16);+ const AudioInputFormat target48k = makeAacCompatibleAudioFormat(source96k);+ const UINT32 sourceFrames = 96000;+ std::vector<BYTE> source(static_cast<size_t>(sourceFrames) * source96k.blockAlign, 0);+ auto* samples = reinterpret_cast<int16_t*>(source.data());+ for (UINT32 frame = 0; frame < sourceFrames; frame += 1) {+ samples[frame * 2] = static_cast<int16_t>(frame % 32767);+ samples[frame * 2 + 1] = static_cast<int16_t>((frame * 3) % 32767);+ }+ std::vector<BYTE> converted;+ convertAudioWithGain(+ source.data(),+ static_cast<DWORD>(source.size()),+ source96k,+ target48k,+ 1.0,+ converted);+ const size_t convertedFrames =+ target48k.blockAlign == 0 ? 0 : converted.size() / target48k.blockAlign;+ const bool frameCountOk =+ convertedFrames == 48000 || convertedFrames == 47999 || convertedFrames == 48001;+ expect(+ "resample-frame-count",+ target48k.sampleRate == 48000 && frameCountOk,+ "frames=" + std::to_string(convertedFrames) + " " + describe(target48k));++ HRESULT mfHr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ if (FAILED(mfHr) && mfHr != RPC_E_CHANGED_MODE) {+ expect("mf-startup", false, "CoInitializeEx failed");+ } else {+ mfHr = MFStartup(MF_VERSION);+ expect("mf-startup", SUCCEEDED(mfHr), "MFStartup hr=" + std::to_string(static_cast<long>(mfHr)));+ if (SUCCEEDED(mfHr)) {+ const HRESULT rejectHr = trySetAacPcmRate(96000);+ char rejectHex[16]{};+ sprintf_s(rejectHex, "0x%08lx", static_cast<unsigned long>(rejectHr));+ std::cout << "MF_RAW mf-reject-96000 hr=" << rejectHex << "\n";+ expect(+ "mf-reject-96000",+ FAILED(rejectHr) && static_cast<unsigned long>(rejectHr) == 0xc00d36b4ul,+ std::string("want 0xc00d36b4 got ") + rejectHex);+ const HRESULT acceptHr = trySetAacPcmRate(48000);+ char acceptHex[16]{};+ sprintf_s(acceptHex, "0x%08lx", static_cast<unsigned long>(acceptHr));+ std::cout << "MF_RAW mf-accept-48000 hr=" << acceptHex << "\n";+ expect("mf-accept-48000", SUCCEEDED(acceptHr), std::string("hr=") + acceptHex);++ const HRESULT rejectAvHr = trySetAacPcmRateWithVideo(96000);+ char rejectAvHex[16]{};+ sprintf_s(rejectAvHex, "0x%08lx", static_cast<unsigned long>(rejectAvHr));+ std::cout << "MF_RAW mf-reject-96000-with-video hr=" << rejectAvHex << "\n";+ expect(+ "mf-reject-96000-with-video",+ FAILED(rejectAvHr),+ std::string("want fail got ") + rejectAvHex);+ const HRESULT acceptAvHr = trySetAacPcmRateWithVideo(48000);+ char acceptAvHex[16]{};+ sprintf_s(acceptAvHex, "0x%08lx", static_cast<unsigned long>(acceptAvHr));+ std::cout << "MF_RAW mf-accept-48000-with-video hr=" << acceptAvHex << "\n";+ expect(+ "mf-accept-48000-with-video",+ SUCCEEDED(acceptAvHr),+ std::string("hr=") + acceptAvHex);++ Microsoft::WRL::ComPtr<IMFAttributes> swAttr;+ const HRESULT attrHr = MFCreateAttributes(&swAttr, 1);+ if (FAILED(attrHr)) {+ expect("mf-reject-96000-sw-attr", false, "MFCreateAttributes failed");+ } else {+ swAttr->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, FALSE);+ const HRESULT rejectSwHr = trySetAacPcmRate(96000, swAttr.Get());+ char rejectSwHex[16]{};+ sprintf_s(rejectSwHex, "0x%08lx", static_cast<unsigned long>(rejectSwHr));+ std::cout << "MF_RAW mf-reject-96000-sw-attr hr=" << rejectSwHex << "\n";+ expect(+ "mf-reject-96000-sw-attr",+ FAILED(rejectSwHr),+ std::string("want fail got ") + rejectSwHex);+ const HRESULT acceptSwHr = trySetAacPcmRate(48000, swAttr.Get());+ char acceptSwHex[16]{};+ sprintf_s(acceptSwHex, "0x%08lx", static_cast<unsigned long>(acceptSwHr));+ std::cout << "MF_RAW mf-accept-48000-sw-attr hr=" << acceptSwHex << "\n";+ expect(+ "mf-accept-48000-sw-attr",+ SUCCEEDED(acceptSwHr),+ std::string("hr=") + acceptSwHex);+ }+ MFShutdown();+ }+ }++ std::cout << "ran " << g_ran << " tests\n";+ if (g_failed != 0) {+ std::cout << g_failed << " failed\n";+ return 1;+ }+ return 0;+}diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cppindex a9e21d45c..4f795257c 100644--- a/electron/native/wgc-capture/src/main.cpp+++ b/electron/native/wgc-capture/src/main.cpp@@ -810,17 +810,43 @@ int main(int argc, char* argv[]) {<< jsonEscape(wideToUtf8(microphoneCapture.selectedDeviceName())) << "\"";}std::cout << "}" << std::endl;- encoderAudioFormat = makeAacCompatibleAudioFormat(*audioFormat);+ AudioInputFormat sourceForEncoder = *audioFormat;+ const int forcedAacSourceRate = readEnvInt("OPENSCREEN_WGC_FORCE_AAC_SOURCE_RATE", 0);+ if (forcedAacSourceRate > 0) {+ sourceForEncoder.sampleRate = static_cast<UINT32>(forcedAacSourceRate);+ sourceForEncoder.avgBytesPerSec =+ sourceForEncoder.sampleRate * sourceForEncoder.blockAlign;+ }+ if (readEnvInt("OPENSCREEN_WGC_DISABLE_AAC_RATE_SNAP", 0) == 1) {+ encoderAudioFormat = sourceForEncoder;+ encoderAudioFormat.subtype = MFAudioFormat_PCM;+ encoderAudioFormat.channels = 2;+ encoderAudioFormat.bitsPerSample = 16;+ encoderAudioFormat.blockAlign = 4;+ encoderAudioFormat.avgBytesPerSec = encoderAudioFormat.sampleRate * 4;+ } else {+ encoderAudioFormat = makeAacCompatibleAudioFormat(sourceForEncoder);+ }+std::cout << "{\"event\":\"encoder-audio-format\",\"schemaVersion\":2,\"sampleRate\":"<< encoderAudioFormat.sampleRate<< ",\"channels\":" << encoderAudioFormat.channels<< ",\"bitsPerSample\":" << encoderAudioFormat.bitsPerSample+ << ",\"forcedSourceRate\":" << forcedAacSourceRate+ << ",\"snapDisabled\":"+ << (readEnvInt("OPENSCREEN_WGC_DISABLE_AAC_RATE_SNAP", 0) == 1 ? "true" : "false")+ << ",\"aacRateProbe\":"+ << (readEnvInt("OPENSCREEN_WGC_TEST_INJECT_AAC_RATE_PROBE", 0) == 1 ? "true"+ : "false")<< "}" << std::endl;}MFEncoderOptions encoderOptions{};encoderOptions.preferSoftwareEncoder = config.preferSoftwareEncoder;encoderOptions.injectDefaultSinkWriterFailureOnce = injectDefaultSinkWriterFailureOnce;+ encoderOptions.skipAacRateSnap = readEnvInt("OPENSCREEN_WGC_DISABLE_AAC_RATE_SNAP", 0) == 1;+ encoderOptions.injectAacRateProbe =+ readEnvInt("OPENSCREEN_WGC_TEST_INJECT_AAC_RATE_PROBE", 0) == 1;// OFF by default. The GPU path exists to dodge a Map() that wedges inside// the display driver on the machine in #252, and it demonstrably fixed// display and window capture there. It also broke recording outright fordiff --git a/electron/native/wgc-capture/src/mf_encoder.cpp b/electron/native/wgc-capture/src/mf_encoder.cppindex 4130b1326..b4dabcc54 100644--- a/electron/native/wgc-capture/src/mf_encoder.cpp+++ b/electron/native/wgc-capture/src/mf_encoder.cpp@@ -519,13 +519,15 @@ void setAudioFormat(IMFMediaType* type, UINT32 channels, UINT32 sampleRate, UINT// anything is built from it, not after.bool buildAacOutputType(const AudioInputFormat& audioFormat,+ bool skipAacRateSnap,Microsoft::WRL::ComPtr<IMFMediaType>& outputType) {if (audioFormat.sampleRate == 0 || audioFormat.channels == 0 || audioFormat.blockAlign == 0) {std::cerr << "ERROR: Invalid audio input format" << std::endl;return false;}- const AudioInputFormat encoderFormat = makeAacCompatibleAudioFormat(audioFormat);+ const AudioInputFormat encoderFormat =+ skipAacRateSnap ? audioFormat : makeAacCompatibleAudioFormat(audioFormat);const UINT32 aacBytesPerSecond = 24'000;if (!succeeded(MFCreateMediaType(&outputType), "MFCreateMediaType(audio output)")) {@@ -795,7 +797,7 @@ bool MFEncoder::initialize(// a construction argument. Null when the recording has no audio, which// is both the common case and a documented one for that call.Microsoft::WRL::ComPtr<IMFMediaType> audioOutputType;- if (audioFormat && !buildAacOutputType(*audioFormat, audioOutputType)) {+ if (audioFormat && !buildAacOutputType(*audioFormat, options.skipAacRateSnap, audioOutputType)) {return false;}@@ -859,7 +861,7 @@ bool MFEncoder::initialize(}}- if (audioFormat && !configureAudioStream(*audioFormat)) {+ if (audioFormat && !configureAudioStream(*audioFormat, options)) {return false;}@@ -946,12 +948,75 @@ bool MFEncoder::initialize(// that used to sit between the two -- now happens before the sink writer// exists. What is left is the input type, which is the same on both containers// and is set on a stream index the caller has already resolved.-bool MFEncoder::configureAudioStream(const AudioInputFormat& audioFormat) {+HRESULT probeAacPcmRate(UINT32 sampleRate) {+ wchar_t dir[MAX_PATH]{};+ GetTempPathW(MAX_PATH, dir);+ const std::wstring path = std::wstring(dir) + L"openscreen-wgc-aac-rate-probe-" ++ std::to_wstring(GetCurrentProcessId()) + L".mp4";+ DeleteFileW(path.c_str());++ Microsoft::WRL::ComPtr<IMFSinkWriter> writer;+ HRESULT hr = MFCreateSinkWriterFromURL(path.c_str(), nullptr, nullptr, &writer);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> outputType;+ hr = MFCreateMediaType(&outputType);+ if (FAILED(hr)) {+ DeleteFileW(path.c_str());+ return hr;+ }+ outputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ outputType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_AAC);+ setAudioFormat(outputType.Get(), 2, sampleRate, 16);+ outputType->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, 24'000);+ outputType->SetUINT32(MF_MT_AAC_PAYLOAD_TYPE, 0);++ DWORD streamIndex = 0;+ hr = writer->AddStream(outputType.Get(), &streamIndex);+ if (FAILED(hr)) {+ writer.Reset();+ DeleteFileW(path.c_str());+ return hr;+ }++ Microsoft::WRL::ComPtr<IMFMediaType> inputType;+ hr = MFCreateMediaType(&inputType);+ if (FAILED(hr)) {+ writer.Reset();+ DeleteFileW(path.c_str());+ return hr;+ }+ inputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);+ inputType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);+ setAudioFormat(inputType.Get(), 2, sampleRate, 16);+ inputType->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, 4);+ inputType->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, sampleRate * 4);+ inputType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);+ hr = writer->SetInputMediaType(streamIndex, inputType.Get(), nullptr);+ writer.Reset();+ DeleteFileW(path.c_str());+ return hr;+}++bool MFEncoder::configureAudioStream(const AudioInputFormat& audioFormat, const MFEncoderOptions& options) {if (!sinkWriter_) {return false;}- const AudioInputFormat encoderFormat = makeAacCompatibleAudioFormat(audioFormat);+ const AudioInputFormat encoderFormat =+ options.skipAacRateSnap ? audioFormat : makeAacCompatibleAudioFormat(audioFormat);++ if (options.injectAacRateProbe) {+ const HRESULT probeHr = probeAacPcmRate(encoderFormat.sampleRate);+ std::cerr << "TEST-ONLY: AAC rate probe sampleRate=" << encoderFormat.sampleRate+ << " hr=0x" << std::hex << probeHr << std::dec << std::endl;+ if (!succeeded(probeHr, "SetInputMediaType(audio)")) {+ return false;+ }+ }Microsoft::WRL::ComPtr<IMFMediaType> inputType;if (!succeeded(MFCreateMediaType(&inputType), "MFCreateMediaType(audio input)")) {diff --git a/electron/native/wgc-capture/src/mf_encoder.h b/electron/native/wgc-capture/src/mf_encoder.hindex 19fac7004..f7176c75d 100644--- a/electron/native/wgc-capture/src/mf_encoder.h+++ b/electron/native/wgc-capture/src/mf_encoder.h@@ -30,6 +30,17 @@ struct AudioInputFormat {struct MFEncoderOptions {bool preferSoftwareEncoder = false;bool injectDefaultSinkWriterFailureOnce = false;+ // Test-only. Keep the sample rate passed into initialize() instead of+ // running makeAacCompatibleAudioFormat again. The DISABLE_AAC_RATE_SNAP env+ // used to change only the JSON log: buildAacOutputType / configureAudioStream+ // snapped 96 kHz back to 48 kHz before SetInputMediaType, so the fail path+ // was unreachable.+ bool skipAacRateSnap = false;+ // Test-only. Before the production sink writer sees the audio type, run+ // MFCreateSinkWriterFromURL + SetInputMediaType on the encoder rate. Illegal+ // AAC rates fail that probe with MF_E_INVALIDMEDIATYPE (0xc00d36b4). Does+ // not invent the HRESULT — it calls the API.+ bool injectAacRateProbe = false;// A request, never a requirement. Every step of the GPU path degrades to// the CPU readback rather than failing the recording, so a machine without// a hardware H.264 encoder, without NV12 video-processor output, or with a@@ -175,7 +186,7 @@ private:// built before the sink writer exists (buildAacOutputType in the .cpp),// because MFCreateFMPEG4MediaSink takes both output types at construction:// a fragmented sink has all its streams before anything can be added to it.- bool configureAudioStream(const AudioInputFormat& audioFormat);+ bool configureAudioStream(const AudioInputFormat& audioFormat, const MFEncoderOptions& options);void releaseSinkWriter();Microsoft::WRL::ComPtr<IMFSinkWriter> sinkWriter_;diff --git a/scripts/build-windows-wgc-helper.mjs b/scripts/build-windows-wgc-helper.mjsindex 063d81b30..cfc7d057a 100644--- a/scripts/build-windows-wgc-helper.mjs+++ b/scripts/build-windows-wgc-helper.mjs@@ -95,3 +95,10 @@ console.log(`Built ${outputPath}`);console.log(`Copied ${distributablePath}`);console.log(`Built ${cursorSamplerOutputPath}`);console.log(`Copied ${cursorSamplerDistributablePath}`);++const audioUtilsTestPath = path.join(BUILD_DIR, "audio_sample_utils_test.exe");+if (!fs.existsSync(audioUtilsTestPath)) {+ throw new Error(`WGC helper build completed but ${audioUtilsTestPath} was not found.`);+}+await run(audioUtilsTestPath, [], { cwd: BUILD_DIR });+console.log(`Passed ${audioUtilsTestPath}`);