Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(windows): write a real tone instead of silence for the keep-alive

abduznik9f47d2d019ae
diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cpp
index 4ee39fc3c..88c0d1572 100644
--- a/electron/native/wgc-capture/src/main.cpp
+++ b/electron/native/wgc-capture/src/main.cpp
@@ -812,15 +812,16 @@ int wmain(int argc, wchar_t* argv[]) {
}
};
// getopenscreen/openscreen#724: confirmed on real hardware that a mic-only
- // recording lets Windows idle the render endpoint and drop the headset, while
+ // recording lets a wireless headset's own idle timer fire and drop it, while
// the same recording with system audio (which reads the render endpoint via
- // loopback) does not -- so writing silence to it is enough to prevent this.
- // Independent of captureSystemAudio, since mic-only is exactly the case that
- // otherwise leaves the endpoint untouched. Non-fatal: a recording with no
- // output device to keep alive, or one where another app holds it exclusively,
- // is unaffected either way.
+ // loopback) does not. Only needed when system audio is off: loopback capture
+ // already keeps the endpoint busy with real content on its own, so running
+ // this alongside it would be redundant and would additionally get captured
+ // into the recording's system-audio track, which mic-only never touches.
+ // Non-fatal: a recording with no output device to keep alive, or one where
+ // another app holds it exclusively, is unaffected either way.
const bool renderKeepAliveEnabled =
- readEnvInt("OPENSCREEN_WGC_DISABLE_AUDIO_KEEPALIVE", 0) != 1;
+ !config.captureSystemAudio && readEnvInt("OPENSCREEN_WGC_DISABLE_AUDIO_KEEPALIVE", 0) != 1;
WasapiRenderKeepAlive renderKeepAlive;
bool renderKeepAliveActive = false;
const auto stopRenderKeepAliveIfActive = [&]() {
diff --git a/electron/native/wgc-capture/src/wasapi_render_keepalive.cpp b/electron/native/wgc-capture/src/wasapi_render_keepalive.cpp
index d8a9c306c..56ef58b54 100644
--- a/electron/native/wgc-capture/src/wasapi_render_keepalive.cpp
+++ b/electron/native/wgc-capture/src/wasapi_render_keepalive.cpp
@@ -1,11 +1,73 @@
#include "wasapi_render_keepalive.h"
#include <chrono>
+#include <cmath>
+#include <cstring>
#include <iostream>
+#include <ksmedia.h>
namespace {
constexpr REFERENCE_TIME BufferDurationHns = 10'000'000;
+// Quiet enough to be inaudible in any real listening scenario, loud enough to be
+// genuine, non-zero signal rather than something a downstream limiter/gate could
+// treat as silence.
+constexpr double ToneAmplitude = 0.01;
+constexpr double ToneFrequencyHz = 1000.0;
+
+bool isFloatFormat(const WAVEFORMATEX* format) {
+ if (format->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
+ return true;
+ }
+ if (format->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
+ format->cbSize >= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)) {
+ const auto* extensible = reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(format);
+ return extensible->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
+ }
+ return false;
+}
+
+constexpr double TwoPi = 2.0 * 3.14159265358979323846;
+
+// Fills `frameCount` frames of `data` with a quiet sine tone at the format
+// described by `format`, starting at `phase` radians and returning the phase to
+// continue from on the next call, so the waveform stays continuous across
+// separate GetBuffer/ReleaseBuffer calls instead of clicking at each boundary.
+double writeToneFrames(BYTE* data, UINT32 frameCount, const WAVEFORMATEX* format, double phase) {
+ const double phaseStep = TwoPi * ToneFrequencyHz / format->nSamplesPerSec;
+ const bool isFloat = isFloatFormat(format);
+ const UINT16 bitsPerSample = format->wBitsPerSample;
+
+ for (UINT32 frame = 0; frame < frameCount; ++frame) {
+ const double sampleValue = std::sin(phase) * ToneAmplitude;
+ phase += phaseStep;
+ if (phase >= TwoPi) {
+ // Wrap rather than let phase grow unboundedly over a long recording,
+ // which would eventually lose precision in the sine's argument.
+ phase -= TwoPi;
+ }
+
+ for (UINT16 channel = 0; channel < format->nChannels; ++channel) {
+ BYTE* sampleData = data + frame * format->nBlockAlign + channel * (bitsPerSample / 8);
+ if (isFloat && bitsPerSample == 32) {
+ const float value = static_cast<float>(sampleValue);
+ std::memcpy(sampleData, &value, sizeof(value));
+ } else if (bitsPerSample == 16) {
+ const int16_t value = static_cast<int16_t>(sampleValue * 32767.0);
+ std::memcpy(sampleData, &value, sizeof(value));
+ } else if (bitsPerSample == 32) {
+ // 32-bit integer PCM.
+ const int32_t value = static_cast<int32_t>(sampleValue * 2147483647.0);
+ std::memcpy(sampleData, &value, sizeof(value));
+ }
+ // Any other bit depth is left zeroed (silence for that sample) rather
+ // than risking a malformed write -- this is a best-effort keep-alive,
+ // not a guarantee of coverage for every possible device format.
+ }
+ }
+
+ return phase;
+}
} // namespace
@@ -61,14 +123,15 @@ bool WasapiRenderKeepAlive::start() {
return false;
}
- // Prime the full buffer with silence before Start() so there's no gap for the
+ // Prime the full buffer with the tone before Start() so there's no gap for the
// audio engine to glitch on.
BYTE* data = nullptr;
hr = renderClient_->GetBuffer(bufferFrameCount_, &data);
if (FAILED(hr)) {
return false;
}
- renderClient_->ReleaseBuffer(bufferFrameCount_, AUDCLNT_BUFFERFLAGS_SILENT);
+ tonePhase_ = writeToneFrames(data, bufferFrameCount_, mixFormat_, tonePhase_);
+ renderClient_->ReleaseBuffer(bufferFrameCount_, 0);
stopRequested_ = false;
hr = audioClient_->Start();
@@ -114,7 +177,8 @@ void WasapiRenderKeepAlive::renderLoop() {
if (framesAvailable > 0) {
BYTE* data = nullptr;
if (SUCCEEDED(renderClient_->GetBuffer(framesAvailable, &data))) {
- renderClient_->ReleaseBuffer(framesAvailable, AUDCLNT_BUFFERFLAGS_SILENT);
+ tonePhase_ = writeToneFrames(data, framesAvailable, mixFormat_, tonePhase_);
+ renderClient_->ReleaseBuffer(framesAvailable, 0);
}
}
diff --git a/electron/native/wgc-capture/src/wasapi_render_keepalive.h b/electron/native/wgc-capture/src/wasapi_render_keepalive.h
index b7feeed07..e13a78212 100644
--- a/electron/native/wgc-capture/src/wasapi_render_keepalive.h
+++ b/electron/native/wgc-capture/src/wasapi_render_keepalive.h
@@ -9,9 +9,21 @@
// alive, and loopback capture already does that as a side effect when it runs.
//
// This opens an ordinary render stream on the same default output device and
-// writes silence to it for as long as a recording is running, independent of
-// whether system audio is being captured, since mic-only is exactly the case that
-// leaves the endpoint untouched otherwise.
+// writes a near-inaudible tone to it for as long as a recording is running,
+// independent of whether system audio is being captured, since mic-only is
+// exactly the case that leaves the endpoint untouched otherwise.
+//
+// Real signal, not digital silence: confirmed on real hardware that writing
+// AUDCLNT_BUFFERFLAGS_SILENT packets does not reliably stop a wireless headset's
+// own idle timer from firing, while writing an actual (if very quiet) tone does.
+// This matches the earlier finding that system-audio loopback capture (which
+// reads real audio, when something is playing) prevents the drop but mic-only
+// capture (which touches nothing) does not -- some headsets' firmware appears to
+// require genuine signal, not merely a live but silent stream, to register as
+// activity. The tone amplitude is low enough (1%) to be inaudible in practice and
+// is never captured into the recording itself, since this writes to the render
+// endpoint and the recording only captures it when system-audio (loopback) is
+// also on -- the same case that already doesn't need this workaround.
//
// Kill-switch: set OPENSCREEN_WGC_DISABLE_AUDIO_KEEPALIVE=1 to turn this off.
@@ -46,4 +58,8 @@ private:
UINT32 bufferFrameCount_ = 0;
std::thread thread_;
std::atomic<bool> stopRequested_ = false;
+ // Carries the tone's phase across GetBuffer/ReleaseBuffer calls so the
+ // waveform is continuous instead of restarting (and clicking) at each one.
+ // Only ever touched from the render thread, so no synchronization needed.
+ double tonePhase_ = 0.0;
};