From 602c906b50e7eb4c7ecf7b2a15cb5f2031a72169 Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:18:34 -0500 Subject: [PATCH] fix(audio): keep WASAPI samples with uncertain timestamps --- native/capture/windows/audio_chunks.h | 66 ++++++++++++++++++++ native/capture/windows/audio_chunks.test.cpp | 53 ++++++++++++++++ native/capture/windows/build.ps1 | 2 +- native/capture/windows/process_audio.cpp | 44 +++---------- 4 files changed, 130 insertions(+), 35 deletions(-) create mode 100644 native/capture/windows/audio_chunks.h create mode 100644 native/capture/windows/audio_chunks.test.cpp diff --git a/native/capture/windows/audio_chunks.h b/native/capture/windows/audio_chunks.h new file mode 100644 index 000000000..22adb3216 --- /dev/null +++ b/native/capture/windows/audio_chunks.h @@ -0,0 +1,66 @@ +#pragma once + +#include "process_audio.h" + +#include +#include + +#include + +namespace piik::capture { + +class AudioChunks { + public: + void Append(const BYTE* data, UINT32 frames, DWORD flags, UINT64 qpc) { + if ((flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) { + pending_.clear(); + consumed_ = 0; + timestamp_ = 0; + } + if (pending_.size() == consumed_) { + pending_.clear(); + consumed_ = 0; + if ((flags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR) == 0) { + timestamp_ = qpc; + } else if (timestamp_ == 0) { + // Estimate the first sample's time using the packet duration and QPC. + const auto now = static_cast(MFGetSystemTime()); + const auto duration = static_cast(frames) * 10'000'000 / kAudioSampleRate; + timestamp_ = now > duration ? now - duration : 1; + } + } + const auto bytes = static_cast(frames) * kAudioChannels * kAudioBytesPerSample; + if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0) { + pending_.insert(pending_.end(), bytes, 0); + } else { + pending_.insert(pending_.end(), data, data + bytes); + } + } + + const BYTE* Next() const { + return pending_.size() - consumed_ >= kAudioBytesPerChunk + ? pending_.data() + consumed_ + : nullptr; + } + + UINT64 Timestamp() const { return timestamp_; } + + void Consume() { + consumed_ += kAudioBytesPerChunk; + timestamp_ += kAudioChunkDuration100ns; + } + + void Compact() { + if (consumed_ > kAudioBytesPerChunk * 4) { + pending_.erase(pending_.begin(), pending_.begin() + static_cast(consumed_)); + consumed_ = 0; + } + } + + private: + std::vector pending_; + size_t consumed_ = 0; + UINT64 timestamp_ = 0; +}; + +} // namespace piik::capture diff --git a/native/capture/windows/audio_chunks.test.cpp b/native/capture/windows/audio_chunks.test.cpp new file mode 100644 index 000000000..97be5c806 --- /dev/null +++ b/native/capture/windows/audio_chunks.test.cpp @@ -0,0 +1,53 @@ +#include "audio_chunks.h" + +#include +#include + +using namespace piik::capture; + +int main() { + constexpr auto timestamp_error = AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR; + constexpr auto silent = AUDCLNT_BUFFERFLAGS_SILENT; + constexpr auto discontinuity = AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY; + constexpr auto half_frames = kAudioFramesPerChunk / 2; + constexpr auto half_bytes = kAudioBytesPerChunk / 2; + constexpr auto half_duration = kAudioChunkDuration100ns / 2; + std::array pcm; + pcm.fill(42); + AudioChunks chunks; + + const auto before = static_cast(MFGetSystemTime()); + chunks.Append(pcm.data(), half_frames, timestamp_error, 1); + const auto after = static_cast(MFGetSystemTime()); + const auto first = chunks.Timestamp(); + assert(first + half_duration >= before && first + half_duration <= after); + assert(chunks.Next() == nullptr); + + chunks.Append(nullptr, half_frames, silent | timestamp_error, 2); + const auto* chunk = chunks.Next(); + assert(chunk != nullptr && chunks.Timestamp() == first); + for (size_t i = 0; i < kAudioBytesPerChunk; ++i) { + assert(chunk[i] == (i < half_bytes ? 42 : 0)); + } + chunks.Consume(); + chunks.Append(pcm.data(), kAudioFramesPerChunk, timestamp_error, 3); + assert(chunks.Next() != nullptr && chunks.Timestamp() == first + kAudioChunkDuration100ns); + chunks.Consume(); + + chunks.Append(pcm.data(), half_frames, timestamp_error, 4); + pcm.fill(7); + const auto reset_before = static_cast(MFGetSystemTime()); + chunks.Append(pcm.data(), kAudioFramesPerChunk, discontinuity | timestamp_error, 5); + const auto reset_after = static_cast(MFGetSystemTime()); + chunk = chunks.Next(); + assert(chunk != nullptr && chunk[0] == 7 && chunk[kAudioBytesPerChunk - 1] == 7); + const auto restarted = chunks.Timestamp(); + assert(restarted + kAudioChunkDuration100ns >= reset_before && + restarted + kAudioChunkDuration100ns <= reset_after); + chunks.Consume(); + assert(chunks.Next() == nullptr); + + const auto trusted_qpc = restarted + kAudioChunkDuration100ns + 1'000; + chunks.Append(pcm.data(), kAudioFramesPerChunk, 0, trusted_qpc); + assert(chunks.Next() != nullptr && chunks.Timestamp() == trusted_qpc); +} diff --git a/native/capture/windows/build.ps1 b/native/capture/windows/build.ps1 index a93f87c00..8f0962ec3 100644 --- a/native/capture/windows/build.ps1 +++ b/native/capture/windows/build.ps1 @@ -69,7 +69,7 @@ Invoke-CaptureBuild ('{0} /out:"{1}" {2} "{3}" {4}' -f $linkCommand,$executableP if ($Check) { $vp8Object = Join-Path $outputPath 'vp8_encoder.obj' Invoke-CaptureBuild ('cl.exe {0} /DNDEBUG "{1}" /Fo:"{2}"' -f $compileFlags,(Join-Path $helperDirectory 'vp8_encoder.cpp'),$vp8Object) - foreach ($name in @('capture_geometry', 'capture_control', 'capture_target', 'output_worker', 'mft_event_reader', 'adaptive_encoder')) { + foreach ($name in @('audio_chunks', 'capture_geometry', 'capture_control', 'capture_target', 'output_worker', 'mft_event_reader', 'adaptive_encoder')) { $source = Join-Path $helperDirectory ($name + '.test.cpp') $object = Join-Path $outputPath ($name + '.test.obj') $executable = Join-Path $outputPath ($name + '.test.exe') diff --git a/native/capture/windows/process_audio.cpp b/native/capture/windows/process_audio.cpp index b97c89b09..f1481dbb9 100644 --- a/native/capture/windows/process_audio.cpp +++ b/native/capture/windows/process_audio.cpp @@ -9,6 +9,7 @@ #include #include +#include "audio_chunks.h" #include "capture_target.h" #include "process_audio.h" @@ -18,7 +19,6 @@ #include #include #include -#include using Microsoft::WRL::ComPtr; using Microsoft::WRL::FtmBase; @@ -195,9 +195,7 @@ HRESULT CaptureAudioFrames(ComPtr client, HANDLE process, bool loo if (counts.enabled) counts.primed = SUCCEEDED(result); } - std::vector pending; - size_t consumed = 0; - UINT64 nextTimestamp = 0; + AudioChunks chunks; const HANDLE process_waits[] = {process, sampleReady, stop_event}; const HANDLE system_waits[] = {sampleReady, stop_event}; while (SUCCEEDED(result)) { @@ -232,46 +230,24 @@ HRESULT CaptureAudioFrames(ComPtr client, HANDLE process, bool loo if (FAILED(result = processAlive())) break; BYTE* data = nullptr; DWORD flags = 0; - UINT64 devicePosition = 0; UINT64 qpcPosition = 0; - result = capture->GetBuffer(&data, &frames, &flags, &devicePosition, &qpcPosition); + result = capture->GetBuffer(&data, &frames, &flags, nullptr, &qpcPosition); if (FAILED(result)) break; + // GetBuffer returns AUDCLNT_S_BUFFER_EMPTY with zero frames and no buffer. + if (frames == 0) break; counts.Packet(frames, flags); - const size_t bytes = static_cast(frames) * format.nBlockAlign; - if ((flags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR) != 0) { - capture->ReleaseBuffer(frames); - continue; - } - if ((flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) { - pending.clear(); - consumed = 0; - } - if (pending.size() == consumed) { - pending.clear(); - consumed = 0; - nextTimestamp = qpcPosition; - } - if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0) { - pending.insert(pending.end(), bytes, 0); - } else { - pending.insert(pending.end(), data, data + bytes); - } + chunks.Append(data, frames, flags, qpcPosition); capture->ReleaseBuffer(frames); - while (pending.size() - consumed >= kAudioBytesPerChunk) { + while (const auto* chunk = chunks.Next()) { if (FAILED(result = processAlive())) break; counts.Assembled(); - result = writer(nextTimestamp, pending.data() + consumed, - kAudioBytesPerChunk); + result = writer(chunks.Timestamp(), chunk, kAudioBytesPerChunk); counts.Delivered(result); if (FAILED(result)) break; - consumed += kAudioBytesPerChunk; - nextTimestamp += kAudioChunkDuration100ns; + chunks.Consume(); } if (FAILED(result)) break; - if (consumed > kAudioBytesPerChunk * 4) { - pending.erase(pending.begin(), pending.begin() + static_cast(consumed)); - consumed = 0; - } + chunks.Compact(); } } if (client) client->Stop();