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(audio): boost the mic only over system audio, and clamp the mix once
EtienneLescot343c4078ba20
diff --git a/electron/native/wgc-capture/src/audio_sample_utils.cpp b/electron/native/wgc-capture/src/audio_sample_utils.cppindex 4e7fb4ee9..54e77e40f 100644--- a/electron/native/wgc-capture/src/audio_sample_utils.cpp+++ b/electron/native/wgc-capture/src/audio_sample_utils.cpp@@ -437,7 +437,8 @@ void mixAudioInPlace(std::vector<BYTE>& destination,const BYTE* source,DWORD byteCount,- const AudioInputFormat& format) {+ const AudioInputFormat& format,+ double sourceGain) {if (!source || byteCount == 0 || destination.empty()) {return;}@@ -449,7 +450,8 @@ void mixAudioInPlace(const auto* input = reinterpret_cast<const float*>(source);const size_t sampleCount = mixByteCount / sizeof(float);for (size_t index = 0; index < sampleCount; index += 1) {- output[index] = static_cast<float>(std::clamp(output[index] + input[index], -1.0f, 1.0f));+ output[index] = static_cast<float>(+ std::clamp(static_cast<double>(output[index]) + static_cast<double>(input[index]) * sourceGain, -1.0, 1.0));}return;}@@ -460,7 +462,7 @@ void mixAudioInPlace(const size_t sampleCount = mixByteCount / sizeof(int16_t);for (size_t index = 0; index < sampleCount; index += 1) {output[index] = clampTo<int16_t>(- static_cast<double>(output[index]) + static_cast<double>(input[index]));+ static_cast<double>(output[index]) + static_cast<double>(input[index]) * sourceGain);}return;}@@ -471,7 +473,7 @@ void mixAudioInPlace(const size_t sampleCount = mixByteCount / sizeof(int32_t);for (size_t index = 0; index < sampleCount; index += 1) {output[index] = clampTo<int32_t>(- static_cast<double>(output[index]) + static_cast<double>(input[index]));+ static_cast<double>(output[index]) + static_cast<double>(input[index]) * sourceGain);}}}@@ -573,13 +575,13 @@ void AudioMixer::pushMicrophone(const BYTE* data, DWORD byteCount) {if (paused_) {return;}- append(- microphoneQueue_,- data,- byteCount,- microphoneFormat_,- microphoneGain_,- microphoneDecimator_);+ // The microphone is stored at unity and `microphoneGain_` is applied by+ // mixLoop inside the sum. Applying it here instead would clamp a hot+ // boosted mic to the rails in PCM16 BEFORE the system stream is mixed+ // in: the queue would hold a flat-topped signal and the mix would add+ // further distortion on top of it, with whatever headroom the opposite+ // polarity of the system stream offered already destroyed.+ append(microphoneQueue_, data, byteCount, microphoneFormat_, 1.0, microphoneDecimator_);}cv_.notify_all();}@@ -691,7 +693,9 @@ void AudioMixer::mixLoop() {}if (includeMicrophone_) {pop(microphoneQueue_, sourceChunk, chunkBytes);- mixAudioInPlace(mixedChunk, sourceChunk.data(), static_cast<DWORD>(sourceChunk.size()), format_);+ mixAudioInPlace(+ mixedChunk, sourceChunk.data(), static_cast<DWORD>(sourceChunk.size()), format_,+ microphoneGain_);}}diff --git a/electron/native/wgc-capture/src/audio_sample_utils.h b/electron/native/wgc-capture/src/audio_sample_utils.hindex d1eaa49a8..f869d5e94 100644--- a/electron/native/wgc-capture/src/audio_sample_utils.h+++ b/electron/native/wgc-capture/src/audio_sample_utils.h@@ -63,11 +63,18 @@ void convertAudioWithGain(double gain,std::vector<BYTE>& destination,AudioDecimatorState& decimator);+// Mixes `source` into `destination`, scaling the source by `sourceGain` first.+// The gain rides in the double-domain sum and the result is clamped exactly+// once, at the write: a source whose scaled samples exceed full scale must+// saturate against the OTHER sources too (sum-then-clamp), not arrive+// pre-flattened by its own conversion (clamp-then-sum, which distorts twice+// and loses whatever headroom the opposite polarity of the mix had).void mixAudioInPlace(std::vector<BYTE>& destination,const BYTE* source,DWORD byteCount,- const AudioInputFormat& format);+ const AudioInputFormat& format,+ double sourceGain = 1.0);class AudioMixer {public:diff --git a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp b/electron/native/wgc-capture/src/audio_sample_utils_test.cppindex 6297cbe0b..7b7177fad 100644--- a/electron/native/wgc-capture/src/audio_sample_utils_test.cpp+++ b/electron/native/wgc-capture/src/audio_sample_utils_test.cpp@@ -1351,6 +1351,101 @@ int main() {runMixer(true, "-with-mic");}+ // --- Gain staging: where the microphone gain clamps ----------------------+ //+ // The microphone used to be boosted at push time, clamping to the rails in+ // PCM16 before the system stream was mixed in -- a hot boosted mic arrived+ // flat-topped and the sum then distorted again on top of it. The gain now+ // rides in the double-domain sum and the result clamps exactly once, at the+ // write. DC levels make every post-fill output sample an exact number, so+ // the three cases below pin the arithmetic itself rather than a tendency.+ //+ // float32 in, PCM16 out, both 48 kHz -- the interpolation branch, which is+ // what an ordinary machine's microphone packet takes.+ {+ const AudioInputFormat f32stereo = makeFormat(MFAudioFormat_Float, 48000, 2, 32);+ const auto dcPacket = [&](double value, size_t frames) {+ std::vector<BYTE> bytes(frames * f32stereo.blockAlign, 0);+ auto* samples = reinterpret_cast<float*>(bytes.data());+ for (size_t i = 0; i < frames; i += 1) {+ samples[i * 2] = static_cast<float>(value);+ samples[i * 2 + 1] = static_cast<float>(value);+ }+ return bytes;+ };+ const auto steadySample = [&](bool includeSystem, double system, double mic,+ double gain) -> int {+ std::mutex guard;+ std::vector<BYTE> collected;+ AudioMixer mixer(+ target48k, f32stereo, f32stereo, includeSystem, true, gain,+ [&](const BYTE* data, DWORD byteCount, int64_t, int64_t) {+ std::scoped_lock lock(guard);+ collected.insert(collected.end(), data, data + byteCount);+ return true;+ });+ expect("gain-stage-mixer-start", mixer.start(), "");+ mixer.beginTimeline();+ // Far more than the 10 ms cadence can consume in the wait window, so+ // no pop() ever zero-fills into the measured region.+ const auto systemPackets = dcPacket(system, 48000);+ const auto micPackets = dcPacket(mic, 48000);+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);+ for (int burst = 0; burst < 20; burst += 1) {+ if (includeSystem) {+ mixer.pushSystem(systemPackets.data(), static_cast<DWORD>(systemPackets.size()));+ }+ mixer.pushMicrophone(micPackets.data(), static_cast<DWORD>(micPackets.size()));+ std::this_thread::sleep_for(std::chrono::milliseconds(25));+ std::scoped_lock lock(guard);+ // 2 s of output is well past queue fill-in; DC never varies after.+ if (collected.size() >= 2 * 48000 * target48k.blockAlign) {+ break;+ }+ if (std::chrono::steady_clock::now() > deadline) {+ break;+ }+ }+ mixer.stop();+ const size_t frames = collected.size() / target48k.blockAlign;+ // The bursts span ~0.65 s of real time and mixLoop emits on the+ // clock, so that is what there is; 0.5 s is far past queue fill-in+ // and DC never varies after it.+ expect("gain-stage-produced-output", frames >= 24000, "frames=" + std::to_string(frames));+ // The last written sample: every one of them is the same number once+ // both queues have delivered, which is what DC buys us.+ const auto* out = reinterpret_cast<const int16_t*>(collected.data());+ return out[(frames - 1) * 2];+ };++ // (1) 0.9 * 1.4 - 0.5 = 0.76 -> 24903. The old clamp-then-sum path read+ // 0.5 (16384) here because the boosted mic was already flat at 1.0.+ {+ const int got = steadySample(true, -0.5, 0.9, 1.4);+ char detail[96]{};+ sprintf_s(detail, "got=%d want=24903", got);+ std::cout << "GAIN_RAW mix-over-system " << detail << std::endl;+ expect("mixer-mic-gain-applied-at-mix", std::abs(got - 24903) <= 2, detail);+ }+ // (2) 0.9 * 1.4 + 0.5 = 1.76 -> clamped once at the rail.+ {+ const int got = steadySample(true, 0.5, 0.9, 1.4);+ char detail[96]{};+ sprintf_s(detail, "got=%d want=32767", got);+ std::cout << "GAIN_RAW sum-clamp " << detail << std::endl;+ expect("mixer-sum-clamps-once-at-rail", got >= 32766, detail);+ }+ // (3) Unity passthrough: the level a mic-only take must ride at, since+ // the request now sends 1.0 when there is no system audio to sit over.+ {+ const int got = steadySample(false, 0.0, 0.9, 1.0);+ char detail[96]{};+ sprintf_s(detail, "got=%d want=29490", got);+ std::cout << "GAIN_RAW unity " << detail << std::endl;+ expect("mixer-unity-gain-passthrough", std::abs(got - 29490) <= 2, detail);+ }+ }+HRESULT mfHr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);if (FAILED(mfHr) && mfHr != RPC_E_CHANGED_MODE) {skip("mf-startup", "CoInitializeEx failed — no Media Foundation on this host");diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex de9161b48..eda9becaa 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -1222,7 +1222,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {enabled: microphoneEnabled,deviceId: microphoneDeviceId,deviceName: microphoneDeviceName,- gain: MIC_GAIN_BOOST,+ // Same rule as mixAudioTracks: boosted only when the mic has to+ // sit over system audio; at unity on its own so a hot mic does+ // not get +2.9 dB of unconditional gain in the native mixer.+ gain: systemAudioEnabled ? MIC_GAIN_BOOST : 1,},},webcam: {@@ -1383,7 +1386,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn {enabled: microphoneEnabled,deviceId: microphoneDeviceId,deviceName: microphoneDeviceName,- gain: MIC_GAIN_BOOST,+ // Boosted only over system audio, like the Windows request above.+ gain: systemAudioEnabled ? MIC_GAIN_BOOST : 1,},},webcam: {@@ -1486,7 +1490,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn {// microphone get the empty headphone jack recorded, because the// helper then fell back to the session default source....(microphoneDeviceName ? { deviceName: microphoneDeviceName } : {}),- gain: MIC_GAIN_BOOST,+ // Boosted only over system audio, like the Windows request above.+ gain: systemAudioEnabled ? MIC_GAIN_BOOST : 1,},},cursor: { mode: cursorCaptureMode },