diff --git a/CMakeLists.txt b/CMakeLists.txt index bbe28ac0b2..d08a426a3e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1021,6 +1021,17 @@ if(X2W_WITH_OPUS) add_dependencies(startup_xapu_opus_check startup_stub_xapu) add_test(NAME startup_xapu_opus COMMAND startup_xapu_opus_check "$") set_tests_properties(startup_xapu_opus PROPERTIES TIMEOUT 60) + + # Bounded telemetry for the same optional decode path: decoded packets, dequeued completions and + # refusals by reason. Generates its tones with libopus; no captured packet is stored. + add_executable(startup_xapu_opus_count_check tests/startup_xapu_opus_count_check.cpp) + target_compile_features(startup_xapu_opus_count_check PRIVATE cxx_std_17) + target_include_directories(startup_xapu_opus_count_check PRIVATE src) + target_link_libraries(startup_xapu_opus_count_check PRIVATE Opus::opus) + set_target_properties(startup_xapu_opus_count_check PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_dependencies(startup_xapu_opus_count_check startup_stub_xapu) + add_test(NAME startup_xapu_opus_count COMMAND startup_xapu_opus_count_check "$") + set_tests_properties(startup_xapu_opus_count PROPERTIES TIMEOUT 60) endif() add_executable(startup_chad_check tests/startup_chad_check.cpp) diff --git a/docs/experiments/startup-opus-completion-count.md b/docs/experiments/startup-opus-completion-count.md new file mode 100644 index 0000000000..d4dd02effe --- /dev/null +++ b/docs/experiments/startup-opus-completion-count.md @@ -0,0 +1,65 @@ +# Startup Opus completion counters + +Refs [#1145](https://github.com/R0Y00/Xbox2Windows/issues/1145) and +[#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This note covers the optional Opus +decode path built with `-DX2W_WITH_OPUS=ON` and `X2W_XAPU_TYPED_COMPLETIONS=1`. + +## What is counted + +`xapu.dll` keeps process-wide saturating counters for: + +| Counter | Meaning | +|---|---| +| `type3` | readable type 3 commands seen while typed completions are on | +| `packets` | commands libopus decoded successfully | +| `completions` | type 3 results dequeued by the caller | +| `refusals` | sum of the refusal counters below | +| `invalid_argument` | a field or output range failed before libopus | +| `opus_error` | libopus rejected the packet | +| `capacity` | libopus reported `OPUS_BUFFER_TOO_SMALL` | +| `queue_full` | the per-connection queue was full | +| `short_command` | the decode fields crossed the readable header | +| `unknown_handle` | the command named a handle that was not connected | +| `out_of_memory` | a new decoder could not be created | +| `header` | the command header was null or unreadable | + +The counters start on the first readable type 3 command. A run with typed completions off reads +and writes nothing here. + +The audio sink also reports `accepted` and `not_open` submissions, so a run can distinguish an +endpoint that never opened from one that accepted decoded blocks. + +## Summary line + +At the last `XApuDisconnect`, and from `atexit` when a run never disconnects, the stand-in writes +one stable line when the counters moved since the previous summary: + +```text +x2w-audio XApu opus summary: type3=10 packets=2 completions=2 refusals=9 invalid_argument=3 opus_error=1 capacity=1 queue_full=1 short_command=1 unknown_handle=1 out_of_memory=0 header=1 +``` + +The line is written to stderr and to `X2W_TRAP_LOG`, like the other audio lines. It is a snapshot; +two threads can move different fields between their loads. Each field is exact on its own. + +## Test + +```powershell +cmake --preset dev -DX2W_WITH_OPUS=ON -DOpus_DIR=/lib/cmake/Opus +cmake --build --preset dev --target startup_stub_xapu startup_xapu_opus_count_check +ctest --preset dev --no-tests=error -R '^startup_xapu_opus_count$' -V +``` + +The fixture encodes synthetic 1 kHz tones with libopus and drives the real stand-in exports. It +checks two successful decodes and dequeues, a malformed packet, insufficient capacity, an invalid +rate, an out-of-range slot in both the legacy and typed-stream paths, a short command, an unknown +handle, a full queue, a null header, saturation at `UINT64_MAX`, one summary after the last +disconnect, and that typed completions off neither decode nor add a summary line. It passed in +Debug with libopus 1.5.2 on Windows 11 build 26300. + +## Limits + +The counters prove that the optional decode path ran and that the caller consumed the results. +They do not prove that the output was audible, that the desktop sink accepted the same block, or +that XMA/AcpHal works. The `startup_audio_output` fixture covers the sink's accepted/not-open +counters separately. The title run that produced the 27/11 audio observation was not available +locally, so this change adds the measurement, not the run receipt. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d62db935aa..f7e1dd56cd 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2998,8 +2998,8 @@ are copied from scratch only after the result is queued. ```powershell cmake --preset dev -DX2W_WITH_OPUS=ON -DOpus_DIR=/lib/cmake/Opus -cmake --build --preset dev --target startup_stub_xapu startup_xapu_queue_check startup_xapu_opus_check -ctest --preset dev --no-tests=error -R '^startup_xapu_(queue|opus)$' -V +cmake --build --preset dev --target startup_stub_xapu startup_xapu_queue_check startup_xapu_opus_check startup_xapu_opus_count_check +ctest --preset dev --no-tests=error -R '^startup_xapu_(queue|opus|opus_count)$' -V ``` `startup_xapu_opus` encodes generated 1 kHz tones with the same libopus and checks exact byte counts (3840 for @@ -3009,6 +3009,12 @@ an untouched output and an empty queue, a full queue that leaves the slot's stre starting a fresh decoder, a rate change on a live slot, and that type `3` decodes nothing with typed completions off. It is registered only in the optional build. +`startup_xapu_opus_count` uses the same libopus tones to check the bounded telemetry: decoded +packets, dequeued completions and each refusal reason. The stand-in writes one +`x2w-audio XApu opus summary:` line at the last disconnect or at process exit, and the audio sink +reports `accepted` and `not_open` submissions. See +[the completion-count note](experiments/startup-opus-completion-count.md). + `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), converts each submitted block (format, frame count, bytes) to it, and writes it through diff --git a/src/startup_stubs/audio_sink.cpp b/src/startup_stubs/audio_sink.cpp index 635f10040e..d8f1ca8671 100644 --- a/src/startup_stubs/audio_sink.cpp +++ b/src/startup_stubs/audio_sink.cpp @@ -124,7 +124,10 @@ void AudioSink::observe(bool withholding) Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* bytes) { const uint32_t call = calls_++; - if (!p_) return Submit::NotOpen; + if (!p_) { + ++r_.not_open; + return Submit::NotOpen; + } ResampleState trial = resample_; // committed only once the block is accepted if (!convert_block(in, bytes, frames, mix_, conv_buf_, &trial)) { ++r_.unsupported; @@ -132,7 +135,10 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt } const uint32_t out_frames = static_cast(conv_buf_.size() / mix_.frame_bytes()); const uint32_t pad = padding(); - if (pad == padding_failed) return Submit::NotOpen; + if (pad == padding_failed) { + ++r_.not_open; + return Submit::NotOpen; + } if (out_frames > buffer_frames_ - pad) { ++r_.rejected_full; return Submit::Full; @@ -141,9 +147,15 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt if (timer_.drained_start >= 0) timer_.resume(now_ms(), r_.consumed_frames); // the producer is back if (out_frames > 0) { BYTE* dst = nullptr; - if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) return Submit::NotOpen; + if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) { + ++r_.not_open; + return Submit::NotOpen; + } std::memcpy(dst, conv_buf_.data(), conv_buf_.size()); - if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) return Submit::NotOpen; + if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) { + ++r_.not_open; + return Submit::NotOpen; + } } resample_ = std::move(trial); if (r_.first_block < 0) { @@ -153,6 +165,7 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt r_.frames.push_back(out_frames); r_.peaks.push_back(block_peak(in, bytes, frames)); r_.submitted_frames += out_frames; + ++r_.accepted; if (!started_ && SUCCEEDED(p_->client->Start())) started_ = true; return Submit::Accepted; } diff --git a/src/startup_stubs/audio_sink.h b/src/startup_stubs/audio_sink.h index c55ffbf768..f00edbca1b 100644 --- a/src/startup_stubs/audio_sink.h +++ b/src/startup_stubs/audio_sink.h @@ -259,7 +259,8 @@ struct Report { uint64_t submitted_frames = 0; // frames written to the endpoint uint64_t consumed_frames = 0; // submitted frames minus frames still queued uint64_t clock_frames = 0; // IAudioClock position converted to frames - uint32_t unsupported = 0, rejected_full = 0; + uint64_t accepted = 0; // submit() calls that returned Submit::Accepted + uint32_t unsupported = 0, rejected_full = 0, not_open = 0; uint32_t padding_errors = 0; // GetCurrentPadding failed (e.g. the endpoint went away): not a measurement double drained_ms = 0, recovery_ms = -1; // recovery_ms < 0: not measured // Glitches: the render API exposes no discontinuity flag, so this stays "not available". diff --git a/src/startup_stubs/audio_telemetry.h b/src/startup_stubs/audio_telemetry.h new file mode 100644 index 0000000000..e7f9b3a671 --- /dev/null +++ b/src/startup_stubs/audio_telemetry.h @@ -0,0 +1,97 @@ +// Experimental (docs/startup-runtime.md): bounded counters for the optional Opus decode path. +// +// Every counter saturates at UINT64_MAX instead of wrapping. The values are process-wide and are +// read without a single coherent snapshot: a summary taken while another thread enqueues can show +// one field from before that enqueue and another from after it. Each field is exact on its own. +#pragma once + +#include +#include +#include + +namespace x2w_audio { + +inline void saturating_add(std::atomic& counter, std::uint64_t amount = 1) noexcept +{ + std::uint64_t seen = counter.load(std::memory_order_relaxed); + for (;;) { + const std::uint64_t next = amount > (std::numeric_limits::max)() - seen + ? (std::numeric_limits::max)() + : seen + amount; + if (next == seen || counter.compare_exchange_weak(seen, next, std::memory_order_relaxed, + std::memory_order_relaxed)) + return; + } +} + +// Counters for one process's type-3 Opus path. `type3_commands` counts every readable type-3 +// command while typed completions are on. `packets_decoded` counts calls libopus accepted with a +// non-empty packet. `decoded_completions` counts type-3 results dequeued by the caller, so a packet +// that decodes but is never consumed is not in it. The refusal fields name the first check that +// refused the command; `header` covers a null or unreadable XApuEnqueueCommand header. +struct OpusCounters { + std::atomic type3_commands{0}; + std::atomic packets_decoded{0}; + std::atomic decoded_completions{0}; + std::atomic refused_header{0}; + std::atomic refused_short_command{0}; + std::atomic refused_unknown_handle{0}; + std::atomic refused_queue_full{0}; + std::atomic refused_invalid_argument{0}; + std::atomic refused_opus_error{0}; + std::atomic refused_capacity{0}; + std::atomic refused_out_of_memory{0}; +}; + +struct OpusCounterSnapshot { + std::uint64_t type3_commands = 0; + std::uint64_t packets_decoded = 0; + std::uint64_t decoded_completions = 0; + std::uint64_t refused_header = 0; + std::uint64_t refused_short_command = 0; + std::uint64_t refused_unknown_handle = 0; + std::uint64_t refused_queue_full = 0; + std::uint64_t refused_invalid_argument = 0; + std::uint64_t refused_opus_error = 0; + std::uint64_t refused_capacity = 0; + std::uint64_t refused_out_of_memory = 0; +}; + +inline OpusCounterSnapshot snapshot(const OpusCounters& counters) noexcept +{ + return {counters.type3_commands.load(std::memory_order_relaxed), + counters.packets_decoded.load(std::memory_order_relaxed), + counters.decoded_completions.load(std::memory_order_relaxed), + counters.refused_header.load(std::memory_order_relaxed), + counters.refused_short_command.load(std::memory_order_relaxed), + counters.refused_unknown_handle.load(std::memory_order_relaxed), + counters.refused_queue_full.load(std::memory_order_relaxed), + counters.refused_invalid_argument.load(std::memory_order_relaxed), + counters.refused_opus_error.load(std::memory_order_relaxed), + counters.refused_capacity.load(std::memory_order_relaxed), + counters.refused_out_of_memory.load(std::memory_order_relaxed)}; +} + +inline std::uint64_t saturating_total(std::uint64_t& total, std::uint64_t value) noexcept +{ + total = value > (std::numeric_limits::max)() - total + ? (std::numeric_limits::max)() + : total + value; + return total; +} + +inline std::uint64_t refused_total(const OpusCounterSnapshot& s) noexcept +{ + std::uint64_t total = 0; + saturating_total(total, s.refused_header); + saturating_total(total, s.refused_short_command); + saturating_total(total, s.refused_unknown_handle); + saturating_total(total, s.refused_queue_full); + saturating_total(total, s.refused_invalid_argument); + saturating_total(total, s.refused_opus_error); + saturating_total(total, s.refused_capacity); + saturating_total(total, s.refused_out_of_memory); + return total; +} + +} // namespace x2w_audio diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index d5ec4ca384..8648ffe1a1 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -4,8 +4,10 @@ #define X2W_TRAP_MODULE_ID 3 #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/audio_telemetry.h" #include #include +#include #include #include #ifdef X2W_HAVE_OPUS @@ -28,6 +30,8 @@ // Older untyped-format fixtures describe their decode rate and buffer layout on the type 3 command. // Type 2 frees the slot's decoder and type 5 resets it. A command with no packet completes with 0 bytes. // A refused decode returns an error, queues nothing and leaves the output untouched. +// The same build keeps bounded counters for decoded packets, dequeued decoded completions and +// refusals by reason, and writes one stable summary at the last disconnect and at process exit. namespace { using u64 = std::uint64_t; constexpr long hr_ok = 0; @@ -50,6 +54,7 @@ struct QueueEntry { std::uint32_t slot = 0; std::uint32_t value = 0; // typed result +0x34: decoded bytes of a type 3 command #ifdef X2W_HAVE_OPUS + bool decoded = false; // this result came from a successful libopus call bool stream_command = false; unsigned char command_tag[16]{}; // sequence, options, caller context std::uint32_t frames = 0, input_bytes = 0; @@ -89,6 +94,64 @@ Connection* connections = nullptr; u64 next_handle = 0x5841500000000001ULL; bool timer_active = false; +#ifdef X2W_HAVE_OPUS +// Telemetry for the optional decode path. It starts with the first readable type-3 command, so a +// default run with typed completions off reads and writes nothing here. +x2w_audio::OpusCounters opus_counts; +std::atomic opus_counters_on{false}; +SRWLOCK opus_summary_lock = SRWLOCK_INIT; +x2w_audio::OpusCounterSnapshot reported_opus_counts{}; + +bool same_opus_counts(const x2w_audio::OpusCounterSnapshot& a, const x2w_audio::OpusCounterSnapshot& b) noexcept +{ + return a.type3_commands == b.type3_commands && a.packets_decoded == b.packets_decoded && + a.decoded_completions == b.decoded_completions && a.refused_header == b.refused_header && + a.refused_short_command == b.refused_short_command && + a.refused_unknown_handle == b.refused_unknown_handle && + a.refused_queue_full == b.refused_queue_full && + a.refused_invalid_argument == b.refused_invalid_argument && + a.refused_opus_error == b.refused_opus_error && a.refused_capacity == b.refused_capacity && + a.refused_out_of_memory == b.refused_out_of_memory; +} + +// Writes the totals since the previous summary, when they moved. Called at the last disconnect and +// from atexit, so a run that never disconnects still ends with one line on stderr and X2W_TRAP_LOG. +void log_opus_summary() noexcept +{ + if (!opus_counters_on.load(std::memory_order_relaxed)) return; + const x2w_audio::OpusCounterSnapshot now = x2w_audio::snapshot(opus_counts); + AcquireSRWLockExclusive(&opus_summary_lock); + const bool changed = !same_opus_counts(now, reported_opus_counts); + if (changed) reported_opus_counts = now; + ReleaseSRWLockExclusive(&opus_summary_lock); + if (!changed || (!now.type3_commands && !x2w_audio::refused_total(now))) return; + x2w_local::logf("x2w-audio XApu opus summary: type3=%llu packets=%llu completions=%llu refusals=%llu " + "invalid_argument=%llu opus_error=%llu capacity=%llu queue_full=%llu short_command=%llu " + "unknown_handle=%llu out_of_memory=%llu header=%llu", + static_cast(now.type3_commands), + static_cast(now.packets_decoded), + static_cast(now.decoded_completions), + static_cast(x2w_audio::refused_total(now)), + static_cast(now.refused_invalid_argument), + static_cast(now.refused_opus_error), + static_cast(now.refused_capacity), + static_cast(now.refused_queue_full), + static_cast(now.refused_short_command), + static_cast(now.refused_unknown_handle), + static_cast(now.refused_out_of_memory), + static_cast(now.refused_header)); +} + +void start_opus_counters() noexcept +{ + bool expected = false; + if (!opus_counters_on.compare_exchange_strong(expected, true, std::memory_order_relaxed)) return; + std::atexit(log_opus_summary); +} + +enum class DecodeRefusal { none, invalid_argument, opus_error, capacity, out_of_memory }; +#endif + // Makes room for one more entry, so a following place_result cannot fail. bool reserve_result(Connection& conn) noexcept { @@ -166,12 +229,16 @@ void drop_decoder(Connection& conn, std::uint32_t slot, bool destroy) noexcept } // Decodes the packet of a type 3 command into a scratch buffer, so a refusal never touches the -// caller's output. On S_OK, *pcm holds entry.value bytes of float PCM for *dest. Called with -// connection_lock held, which also guards the scratch buffer. -long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, const float** pcm, void** dest) noexcept +// caller's output. On S_OK, *pcm holds entry.value bytes of float PCM for *dest. `decoded_packet` +// distinguishes a libopus decode from the no-packet completion, and `refusal` names the first check +// that refused the command. Called with connection_lock held, which also guards the scratch buffer. +long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, const float** pcm, void** dest, + bool& decoded_packet, DecodeRefusal& refusal) noexcept { static float scratch[max_frames * 2]; static float planar[max_frames * 2]; + decoded_packet = false; + refusal = DecodeRefusal::none; std::uint32_t slot = 0, frames = 0, packet_bytes = 0, out_bytes = 0; std::uint32_t first_frame = 0; float rate_f = 0; @@ -192,7 +259,10 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, if (!packet && !packet_bytes) { // no packet: complete with 0 bytes, as without libopus return hr_ok; } - if (slot >= max_slots) return hr_invalid_arg; + if (slot >= max_slots) { + refusal = DecodeRefusal::invalid_argument; + return hr_invalid_arg; + } SlotDecoder& d = conn.decoders[slot]; const int rate = conn.opus_streams ? 48000 : rate_f == 8000.0f ? 8000 : rate_f == 12000.0f ? 12000 : rate_f == 16000.0f ? 16000 : rate_f == 24000.0f ? 24000 : rate_f == 48000.0f ? 48000 : 0; @@ -200,8 +270,10 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, frames && frames <= max_frames && out_bytes % (frames * 4) == 0 ? out_bytes / (frames * 4) : 0; if (!rate || (channels != 1 && channels != 2) || packet_bytes == 0 || packet_bytes > max_packet_bytes || !x2w_local::readable(reinterpret_cast(packet), packet_bytes) || - !x2w_local::writable(reinterpret_cast(out), out_bytes)) + !x2w_local::writable(reinterpret_cast(out), out_bytes)) { + refusal = DecodeRefusal::invalid_argument; return hr_invalid_arg; + } // A new rate or channel count gets a new decoder, which replaces the slot's only after a good decode. OpusDecoder* decoder = d.decoder; const bool fresh = !decoder || d.channels != static_cast(channels) || d.rate != rate; @@ -210,6 +282,7 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, decoder = opus_decoder_create(rate, static_cast(channels), &error); if (!decoder || error != OPUS_OK) { if (decoder) opus_decoder_destroy(decoder); + refusal = DecodeRefusal::out_of_memory; return hr_out_of_memory; } } @@ -217,6 +290,7 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, static_cast(packet_bytes), scratch, conn.opus_streams ? max_frames : static_cast(frames), 0); if (decoded < 0) { if (fresh) opus_decoder_destroy(decoder); + refusal = decoded == OPUS_BUFFER_TOO_SMALL ? DecodeRefusal::capacity : DecodeRefusal::opus_error; static LONG errors; if (x2w_local::first_calls(errors, 8)) x2w_local::logf("x2w-audio XApu decode slot=%u bytes=%u -> opus error %d", slot, packet_bytes, decoded); @@ -237,6 +311,7 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, } kept = planar; } + decoded_packet = true; *pcm = kept; *dest = reinterpret_cast(out); return hr_ok; @@ -342,6 +417,10 @@ extern "C" __declspec(noinline) long XApuDequeueResult(u64 rcx, u64 rdx, u64 r8, if (conn->count > 0) { entry = pop_result(*conn); hr = hr_ok; +#ifdef X2W_HAVE_OPUS + if (entry.decoded && typed_completions()) + x2w_audio::saturating_add(opus_counts.decoded_completions); +#endif } else { hr = hr_pending_results; } @@ -378,6 +457,12 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuEnqueueCommand", 3, rcx, rdx, r8, r9, _ReturnAddress()); if (!rdx || !x2w_local::readable(reinterpret_cast(rdx), command_header_size)) { +#ifdef X2W_HAVE_OPUS + if (typed_completions()) { + start_opus_counters(); + x2w_audio::saturating_add(opus_counts.refused_header); + } +#endif static LONG bad_cmd_calls; if (x2w_local::first_calls(bad_cmd_calls, 2)) x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx -> E_POINTER", rcx); @@ -388,7 +473,15 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 std::memcpy(&entry.slot, reinterpret_cast(rdx) + 4, sizeof(entry.slot)); #ifdef X2W_HAVE_OPUS const bool decode = entry.type == 3 && typed_completions(); + DecodeRefusal refusal = DecodeRefusal::none; + bool decoded_packet = false; + bool queue_refused = false; + if (decode) { + start_opus_counters(); + x2w_audio::saturating_add(opus_counts.type3_commands); + } if (decode && !x2w_local::readable(reinterpret_cast(rdx), decode_command_size)) { + x2w_audio::saturating_add(opus_counts.refused_short_command); x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx short decode command -> E_POINTER", rcx); return hr_pointer; } @@ -402,11 +495,13 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 void* dest = nullptr; // Refuse a full queue before touching any decoder state. hr = reserve_result(*conn) ? hr_ok : hr_out_of_memory; + queue_refused = hr != hr_ok; if (hr == hr_ok && conn->opus_streams && typed_completions()) { const auto* command = reinterpret_cast(rdx); if (!x2w_local::readable(command, entry.type == 1 ? 28 : 24)) { hr = hr_pointer; } else if (entry.slot >= max_slots) { + refusal = DecodeRefusal::invalid_argument; hr = hr_invalid_arg; } else { entry.stream_command = true; @@ -414,18 +509,29 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 if (entry.type == 1) { std::uint32_t channels = 0; std::memcpy(&channels, command + 24, 4); - if (channels != 1 && channels != 2) hr = hr_invalid_arg; - else if (conn->decoders[entry.slot].channels) hr = hr_invalid_arg; - else conn->decoders[entry.slot].channels = static_cast(channels); + if (channels != 1 && channels != 2) { + refusal = DecodeRefusal::invalid_argument; + hr = hr_invalid_arg; + } else if (conn->decoders[entry.slot].channels) { + refusal = DecodeRefusal::invalid_argument; + hr = hr_invalid_arg; + } else { + conn->decoders[entry.slot].channels = static_cast(channels); + } } } } if (hr == hr_ok && decode) { - hr = decode_packet(*conn, reinterpret_cast(rdx), entry, &pcm, &dest); + hr = decode_packet(*conn, reinterpret_cast(rdx), entry, &pcm, &dest, + decoded_packet, refusal); } else if (hr == hr_ok && (entry.type == 2 || entry.type == 5)) { drop_decoder(*conn, entry.slot, entry.type == 2); } if (hr == hr_ok) { + if (decode) { + entry.decoded = decoded_packet; + if (decoded_packet) x2w_audio::saturating_add(opus_counts.packets_decoded); + } place_result(*conn, entry); if (pcm) std::memcpy(dest, pcm, entry.value); } @@ -434,6 +540,22 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 #endif } ReleaseSRWLockExclusive(&connection_lock); +#ifdef X2W_HAVE_OPUS + if (decode && hr != hr_ok) { + if (!conn) + x2w_audio::saturating_add(opus_counts.refused_unknown_handle); + else if (queue_refused) + x2w_audio::saturating_add(opus_counts.refused_queue_full); + else if (refusal == DecodeRefusal::invalid_argument) + x2w_audio::saturating_add(opus_counts.refused_invalid_argument); + else if (refusal == DecodeRefusal::opus_error) + x2w_audio::saturating_add(opus_counts.refused_opus_error); + else if (refusal == DecodeRefusal::capacity) + x2w_audio::saturating_add(opus_counts.refused_capacity); + else if (refusal == DecodeRefusal::out_of_memory) + x2w_audio::saturating_add(opus_counts.refused_out_of_memory); + } +#endif static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; @@ -454,6 +576,9 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 while (*slot && (*slot)->handle != rcx) slot = &(*slot)->next; Connection* conn = *slot; if (conn) *slot = conn->next; +#ifdef X2W_HAVE_OPUS + const bool last_connection = conn && !connections; +#endif if (conn && !connections && timer_active) { timeEndPeriod(1); timer_active = false; @@ -470,5 +595,8 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 delete[] conn->entries; delete conn; x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); +#ifdef X2W_HAVE_OPUS + if (last_connection) log_opus_summary(); +#endif return hr_ok; } diff --git a/tests/startup_audio_output.cpp b/tests/startup_audio_output.cpp index d95dc1953d..bdb8af0554 100644 --- a/tests/startup_audio_output.cpp +++ b/tests/startup_audio_output.cpp @@ -24,11 +24,12 @@ int fail(const char* what, int code) void print_report(const char* name, const Report& r) { - std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " - "unsupported=%u rejected_full=%u padding_errors=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", - name, static_cast(r.first_block), r.frames.size(), static_cast(r.submitted_frames), - static_cast(r.consumed_frames), static_cast(r.clock_frames), - r.unsupported, r.rejected_full, r.padding_errors, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); + std::printf("%s: first_block=%lld submitted_blocks=%zu accepted=%llu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " + "unsupported=%u rejected_full=%u not_open=%u padding_errors=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", + name, static_cast(r.first_block), r.frames.size(), static_cast(r.accepted), + static_cast(r.submitted_frames), static_cast(r.consumed_frames), + static_cast(r.clock_frames), r.unsupported, r.rejected_full, r.not_open, + r.padding_errors, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); } // Polls until done() holds or ms elapse; every wait in this fixture goes through here. @@ -87,7 +88,7 @@ int run() wait_for(a, 300, [] { return false; }); const Report ra = a.report(); print_report("case a (no submission)", ra); - if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0) + if (ra.first_block != -1 || !ra.frames.empty() || ra.accepted != 0 || ra.submitted_frames != 0 || ra.consumed_frames != 0) return fail("case a reported accepted or consumed frames without a submission", 1); // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros. @@ -104,7 +105,7 @@ int run() wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; }); const Report rb = b.report(); print_report("case b (continuous with silence)", rb); - if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); + if (rb.first_block != 0 || rb.frames.size() != 8 || rb.accepted != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3); if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4); if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5); @@ -128,6 +129,7 @@ int run() wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; }); const Report rc = c.report(); print_report("case c (starvation)", rc); + if (rc.accepted != 3) return fail("case c accepted block count", 9); if (rc.drained_ms < 250) return fail("case c drained interval too short", 9); if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10); if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10); @@ -148,7 +150,7 @@ int run() if (d.submit(ch6_44, 441, blk6.data()) != Submit::Accepted) return fail("case d 5.1 44.1 kHz block not accepted", 13); const Report rd = d.report(); - if (rd.unsupported != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || + if (rd.unsupported != 1 || rd.accepted != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || rd.submitted_frames > resampled_frame_count(441, 44100, mix.rate)) return fail("case d report counts mismatch", 14); } diff --git a/tests/startup_xapu_opus_count_check.cpp b/tests/startup_xapu_opus_count_check.cpp new file mode 100644 index 0000000000..fe2b2334dc --- /dev/null +++ b/tests/startup_xapu_opus_count_check.cpp @@ -0,0 +1,389 @@ +// Source-built checks for the optional XApu Opus telemetry: decoded packets, dequeued decoded +// completions, refusals by reason, and the stable summary line. Synthetic tones are encoded here +// with libopus; no game data or captured packet is used. +#include "startup_stubs/audio_telemetry.h" + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using ConnectFn = long(__cdecl*)(const void* input, void* output, void** handle); +using GetResultCountFn = std::uint32_t(__cdecl*)(void* handle, std::uint64_t unused); +using DequeueResultFn = long(__cdecl*)(void* handle, void* result); +using EnqueueCommandFn = long(__cdecl*)(void* handle, const void* command, std::uint64_t r8, std::uint64_t r9); +using DisconnectFn = long(__cdecl*)(void* handle); + +constexpr long hr_ok = 0; +constexpr long hr_pointer = static_cast(0x80004003); +constexpr long hr_handle = static_cast(0x80070006); +constexpr long hr_out_of_memory = static_cast(0x8007000E); +constexpr long hr_invalid_arg = static_cast(0x80070057); +constexpr long hr_fail = static_cast(0x80004005); +constexpr std::size_t result_size = 0x58; +constexpr std::size_t max_queue_entries = 16384; +constexpr unsigned char fill = 0xCD; + +int failures = 0; +ConnectFn connect; +GetResultCountFn get_count; +DequeueResultFn dequeue; +EnqueueCommandFn enqueue; +DisconnectFn disconnect; +void* handle; + +void check(bool condition, const char* label) +{ + if (condition) return; + ++failures; + std::printf("FAIL: %s\n", label); +} + +template +void put(std::array& cmd, std::size_t offset, T value) +{ + std::memcpy(cmd.data() + offset, &value, sizeof(value)); +} + +// Type 3 command with the fields one title fills. +std::array decode_cmd(std::uint32_t slot, float rate, std::uint32_t frames, const void* packet, + std::uint32_t packet_bytes, void* out, std::uint32_t out_bytes) +{ + std::array cmd{}; + put(cmd, 0x00, std::uint32_t{3}); + put(cmd, 0x04, slot); + put(cmd, 0x1C, rate); + put(cmd, 0x24, frames); + put(cmd, 0x28, packet_bytes); + put(cmd, 0x2C, reinterpret_cast(packet)); + put(cmd, 0x34, out_bytes); + put(cmd, 0x38, reinterpret_cast(out)); + return cmd; +} + +std::array plain_cmd(std::uint32_t type, std::uint32_t slot) +{ + std::array cmd{}; + put(cmd, 0x00, type); + put(cmd, 0x04, slot); + return cmd; +} + +std::vector tone_packet(int rate, int frames) +{ + int error = OPUS_OK; + OpusEncoder* encoder = opus_encoder_create(rate, 1, OPUS_APPLICATION_AUDIO, &error); + if (!encoder || error != OPUS_OK) return {}; + std::vector pcm(static_cast(frames)); + for (int i = 0; i < frames; ++i) + pcm[static_cast(i)] = + 0.5f * static_cast(std::sin(6.283185307179586 * 1000.0 * i / rate)); + std::vector packet(4000); + const int n = opus_encode_float(encoder, pcm.data(), frames, packet.data(), static_cast(packet.size())); + opus_encoder_destroy(encoder); + if (n <= 0) return {}; + packet.resize(static_cast(n)); + return packet; +} + +std::vector filled(std::size_t floats) +{ + std::vector buffer(floats); + std::memset(buffer.data(), fill, floats * sizeof(float)); + return buffer; +} + +bool untouched(const std::vector& buffer, std::size_t from = 0) +{ + const auto* bytes = reinterpret_cast(buffer.data()); + for (std::size_t i = from * sizeof(float); i < buffer.size() * sizeof(float); ++i) + if (bytes[i] != fill) return false; + return true; +} + +struct Result { + std::uint32_t type = 0xFFFFFFFFu, slot = 0xFFFFFFFFu, bytes = 0xFFFFFFFFu; +}; + +Result pop() +{ + std::array raw{}; + Result result; + if (dequeue(handle, raw.data()) != hr_ok) return result; + std::memcpy(&result.type, raw.data(), 4); + std::memcpy(&result.slot, raw.data() + 4, 4); + std::memcpy(&result.bytes, raw.data() + 0x34, 4); + return result; +} + +void expect_refused(const char* label, long want, const std::array& cmd, + const std::vector& out) +{ + check(enqueue(handle, cmd.data(), 0, 0) == want, label); + check(get_count(handle, 0) == 0, label); + check(untouched(out), label); +} + +std::string read_log(const char* path) +{ + HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return {}; + std::string text; + char buffer[4096]; + for (;;) { + DWORD read = 0; + if (!ReadFile(file, buffer, sizeof(buffer), &read, nullptr) || read == 0) break; + text.append(buffer, read); + } + CloseHandle(file); + return text; +} + +struct Counts { + unsigned long long type3 = 0, packets = 0, completions = 0, refusals = 0; + unsigned long long invalid_argument = 0, opus_error = 0, capacity = 0, queue_full = 0; + unsigned long long short_command = 0, unknown_handle = 0, out_of_memory = 0, header = 0; +}; + +// Returns false on a malformed summary; counts every summary line in `lines`. +bool parse_summary(const std::string& text, Counts& counts, int& lines) +{ + counts = Counts{}; + lines = 0; + const char prefix[] = "x2w-audio XApu opus summary:"; + for (std::size_t start = 0; start < text.size();) { + const std::size_t end = text.find('\n', start); + const std::string line = text.substr(start, end == std::string::npos ? std::string::npos : end - start); + if (line.rfind(prefix, 0) == 0) { + Counts parsed; + const int fields = std::sscanf( + line.c_str(), + "x2w-audio XApu opus summary: type3=%llu packets=%llu completions=%llu refusals=%llu " + "invalid_argument=%llu opus_error=%llu capacity=%llu queue_full=%llu short_command=%llu " + "unknown_handle=%llu out_of_memory=%llu header=%llu", + &parsed.type3, &parsed.packets, &parsed.completions, &parsed.refusals, &parsed.invalid_argument, + &parsed.opus_error, &parsed.capacity, &parsed.queue_full, &parsed.short_command, + &parsed.unknown_handle, &parsed.out_of_memory, &parsed.header); + if (fields != 12) return false; + counts = parsed; + ++lines; + } + if (end == std::string::npos) break; + start = end + 1; + } + return true; +} + +void check_counts(const Counts& counts, const char* label) +{ + check(counts.type3 == 10, label); + check(counts.packets == 2, label); + check(counts.completions == 2, label); + check(counts.refusals == 9, label); + check(counts.invalid_argument == 3, label); + check(counts.opus_error == 1, label); + check(counts.capacity == 1, label); + check(counts.queue_full == 1, label); + check(counts.short_command == 1, label); + check(counts.unknown_handle == 1, label); + check(counts.out_of_memory == 0, label); + check(counts.header == 1, label); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return std::printf("usage: startup_xapu_opus_count_check \n"), 2; + + // The saturation contract is independent of the endpoint: prove the helper stops at UINT64_MAX. + std::atomic bounded{(std::numeric_limits::max)() - 1}; + x2w_audio::saturating_add(bounded, 2); + check(bounded == (std::numeric_limits::max)(), "counter saturates at UINT64_MAX"); + x2w_audio::saturating_add(bounded); + check(bounded == (std::numeric_limits::max)(), "a saturated counter stays at UINT64_MAX"); + + char temp_path[MAX_PATH]{}; + char log_path[MAX_PATH]{}; + if (!GetTempPathA(MAX_PATH, temp_path) || !GetTempFileNameA(temp_path, "x2w-opus-", 0, log_path)) + return std::printf("FAIL: cannot create the telemetry log path\n"), 2; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", "1"); + SetEnvironmentVariableA("X2W_TRAP_LOG", log_path); + + HMODULE module = LoadLibraryA(argv[1]); + if (!module) return std::printf("FAIL: cannot load %s\n", argv[1]), 2; + connect = reinterpret_cast(GetProcAddress(module, "XApuConnect")); + get_count = reinterpret_cast(GetProcAddress(module, "XApuGetResultCount")); + dequeue = reinterpret_cast(GetProcAddress(module, "XApuDequeueResult")); + enqueue = reinterpret_cast(GetProcAddress(module, "XApuEnqueueCommand")); + disconnect = reinterpret_cast(GetProcAddress(module, "XApuDisconnect")); + if (!connect || !get_count || !dequeue || !enqueue || !disconnect) + return std::printf("FAIL: missing export\n"), 2; + + std::array input{}; + const std::uint32_t buffer_bytes = 0x10000; + std::memcpy(input.data() + 0x0C, &buffer_bytes, sizeof(buffer_bytes)); + std::array output{}; + if (connect(input.data(), output.data(), &handle) != hr_ok || !handle) + return std::printf("FAIL: XApuConnect\n"), 2; + + const auto packet = tone_packet(48000, 960); + if (packet.empty()) return std::printf("FAIL: libopus produced no packet\n"), 2; + + // Two successful packets, each completion retired by the caller. + for (int i = 0; i < 2; ++i) { + auto out = filled(964); + const auto cmd = decode_cmd(0, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(handle, cmd.data(), 0, 0) == hr_ok, "valid packet accepted"); + const Result result = pop(); + check(result.type == 3 && result.slot == 0 && result.bytes == 3840, "valid packet completes with 3840 bytes"); + check(untouched(out, 960), "valid packet leaves guard floats untouched"); + } + + // Malformed packet: libopus refuses it. + { + const unsigned char bad[] = {0x03, 0x00}; + auto out = filled(960); + expect_refused("malformed packet -> E_FAIL", hr_fail, + decode_cmd(1, 48000.0f, 960, bad, sizeof(bad), out.data(), 3840), out); + } + // Insufficient output capacity: libopus reports OPUS_BUFFER_TOO_SMALL for a 20 ms packet in 80 frames. + { + auto out = filled(964); + expect_refused("insufficient capacity -> E_FAIL", hr_fail, + decode_cmd(1, 48000.0f, 80, packet.data(), static_cast(packet.size()), + out.data(), 320), out); + } + // Invalid argument before libopus. + { + auto out = filled(960); + expect_refused("rate 44100 -> E_INVALIDARG", hr_invalid_arg, + decode_cmd(1, 44100.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840), out); + } + // An out-of-range slot is classified in the legacy decode path. + { + auto out = filled(960); + expect_refused("legacy slot UINT32_MAX -> E_INVALIDARG", hr_invalid_arg, + decode_cmd((std::numeric_limits::max)(), 48000.0f, 960, packet.data(), + static_cast(packet.size()), out.data(), 3840), out); + } + // A type 3 header whose decode fields cross a guard page. + if (auto* pages = static_cast(VirtualAlloc(nullptr, 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) { + DWORD old = 0; + check(VirtualProtect(pages + 0x1000, 0x1000, PAGE_NOACCESS, &old) != FALSE, "guard page for short command"); + const auto full = decode_cmd(1, 48000.0f, 960, packet.data(), static_cast(packet.size()), + pages, 3840); + std::memcpy(pages + 0x1000 - 0x20, full.data(), 0x20); + check(enqueue(handle, pages + 0x1000 - 0x20, 0, 0) == hr_pointer, "short decode command -> E_POINTER"); + check(get_count(handle, 0) == 0, "short decode command queues nothing"); + VirtualFree(pages, 0, MEM_RELEASE); + } else { + check(false, "VirtualAlloc for short command"); + } + // A null header is a header refusal, not a type 3 one. + check(enqueue(handle, nullptr, 0, 0) == hr_pointer, "null command header -> E_POINTER"); + // A readable type 3 command on an unknown handle. + { + auto out = filled(960); + const auto cmd = decode_cmd(0, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(reinterpret_cast(0xDEADBEEFULL), cmd.data(), 0, 0) == hr_handle, + "unknown handle -> E_HANDLE"); + } + // Queue cap: the decode is refused before it touches the slot's decoder. + { + bool filled_up = true; + for (std::uint32_t i = 0; i < max_queue_entries && filled_up; ++i) + filled_up = enqueue(handle, plain_cmd(4, 99).data(), 0, 0) == hr_ok; + check(filled_up && get_count(handle, 0) == max_queue_entries, "queue fills to 16384 entries"); + auto out = filled(960); + const auto cmd = decode_cmd(1, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(handle, cmd.data(), 0, 0) == hr_out_of_memory, "full queue decode -> E_OUTOFMEMORY"); + check(untouched(out), "full queue refusal leaves output untouched"); + bool drained = true; + std::array raw{}; + for (std::size_t i = 0; i < max_queue_entries && drained; ++i) + drained = dequeue(handle, raw.data()) == hr_ok; + check(drained && get_count(handle, 0) == 0, "capped queue drains"); + } + + // The typed-stream path rejects an out-of-range slot before decode_packet; keep this connection + // open until the legacy connection closes so both refusals reach one summary line. + std::array stream_input = input; + const std::uint32_t process = 1; + std::memcpy(stream_input.data(), &process, sizeof(process)); + void* stream_handle = nullptr; + check(connect(stream_input.data(), output.data(), &stream_handle) == hr_ok && stream_handle, + "stream XApuConnect"); + { + auto out = filled(960); + const auto cmd = decode_cmd((std::numeric_limits::max)(), 48000.0f, 960, + packet.data(), static_cast(packet.size()), out.data(), 3840); + check(enqueue(stream_handle, cmd.data(), 0, 0) == hr_invalid_arg, + "stream slot UINT32_MAX -> E_INVALIDARG"); + check(get_count(stream_handle, 0) == 0, "stream slot refusal queues nothing"); + check(untouched(out), "stream slot refusal leaves output untouched"); + } + check(disconnect(handle) == hr_ok, "XApuDisconnect succeeds"); + check(disconnect(stream_handle) == hr_ok, "stream XApuDisconnect succeeds"); + + Counts counts; + int lines = 0; + const std::string log = read_log(log_path); + check(parse_summary(log, counts, lines), "summary line has the documented fields"); + check(lines == 1, "one summary line after the last disconnect"); + check_counts(counts, "summary counts successes and each refusal reason"); + + // Typed completions off: the same command is queued without decoding and the counters do not move. + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + void* second = nullptr; + check(connect(input.data(), output.data(), &second) == hr_ok && second != nullptr, "second XApuConnect"); + auto out = filled(960); + const auto untyped = decode_cmd(2, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(second, untyped.data(), 0, 0) == hr_ok, "untyped type 3 accepted"); + std::array raw{}; + check(dequeue(second, raw.data()) == hr_ok, "untyped type 3 completion"); + check(untouched(out), "untyped type 3 leaves output untouched"); + check(disconnect(second) == hr_ok, "second XApuDisconnect succeeds"); + Counts unchanged; + int after = 0; + check(parse_summary(read_log(log_path), unchanged, after), "summary still parses"); + check(after == 1, "typed completions off do not add a summary line"); + check(unchanged.packets == 2 && unchanged.completions == 2, "typed completions off do not move the counters"); + + FreeLibrary(module); + int at_exit_lines = 0; + check(parse_summary(read_log(log_path), counts, at_exit_lines), "summary parses after unload"); + check(at_exit_lines == 1, "process exit does not repeat an unchanged summary"); + + DeleteFileA(log_path); + SetEnvironmentVariableA("X2W_TRAP_LOG", nullptr); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", nullptr); + if (failures) return std::printf("%d failure(s)\n", failures), 1; + std::printf("PASS: startup_xapu_opus_count (%s)\n", opus_get_version_string()); + return 0; +}