audio: keep blocking AudioOut writes on an even cadence #822

Manually merged
github merged 2 commits from gh-pr/822/head into gh-pr/822/base 2026-11-26 09:33:52 +00:00
Owner

@⁠6d4m on GitHub · 2026-09-25 05:12 UTC · original
6d4m:fix/audioout-write-pacing → main · +21 −2 · 1 files · 2 commits · merged 2026-09-25 08:33 UTC

Fixes slow, warbling audio in games that mix on a timer (Unity/FMOD titles such as PPSA03647 and PPSA09232).

Problem

QueueSdlAudio enforces a minimum cushion of queued audio before it lets the guest write again, but it only checks queue depth. Nothing stops the guest from refilling the queue as fast as it can, so its audio thread ends up running in bursts: several buffers queued back to back, then blocked for the whole cushion while it drains.

Measured on PPSA03647 with 256-frame blocks at 48 kHz, the interval between guest writes alternated between 0 ms and ~44 ms instead of a steady 5.33 ms buffer period:

before:  min 0.000 ms   max 43.95 ms
after:   min 5.01 ms    max 6.45 ms   (stddev ~0.003 ms)

The long-run rate is correct either way — 48000 frames/s in both cases — which is why this is easy to miss. Format, sample rate, buffer contents, queue depth and drain timeouts all look healthy. But a mixer driven by a timer cannot track a cadence that jumps between 0 ms and 44 ms, and the result is music that is slow and warbles.

Fix

Keep the cushion exactly as it was, and additionally hold writes to one buffer period so the cadence stays even. The wait is skipped when the stream is running low, so it can never cause an underrun, and the deadline is per-port so multiple output ports do not interfere with each other.

Testing

PPSA03647 (3D Mini Golf) on Linux, menu music, before and after. With the fix the music plays correctly and the write interval is steady at ~5.4 ms with microsecond-level deviation.

This is not Windows-specific in principle; it just does not show up as clearly there, since a bursty cadence is easier for a Windows audio backend to absorb.

AI assistance (OpenCode) was used for the measurements and this description; I reviewed the results before posting.

**@⁠6d4m** on GitHub · 2026-09-25 05:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/822) `6d4m:fix/audioout-write-pacing` → `main` · +21 −2 · 1 files · 2 commits · merged 2026-09-25 08:33 UTC Fixes slow, warbling audio in games that mix on a timer (Unity/FMOD titles such as PPSA03647 and PPSA09232). ## Problem `QueueSdlAudio` enforces a minimum cushion of queued audio before it lets the guest write again, but it only checks queue depth. Nothing stops the guest from refilling the queue as fast as it can, so its audio thread ends up running in bursts: several buffers queued back to back, then blocked for the whole cushion while it drains. Measured on PPSA03647 with 256-frame blocks at 48 kHz, the interval between guest writes alternated between 0 ms and ~44 ms instead of a steady 5.33 ms buffer period: ``` before: min 0.000 ms max 43.95 ms after: min 5.01 ms max 6.45 ms (stddev ~0.003 ms) ``` The long-run rate is correct either way — 48000 frames/s in both cases — which is why this is easy to miss. Format, sample rate, buffer contents, queue depth and drain timeouts all look healthy. But a mixer driven by a timer cannot track a cadence that jumps between 0 ms and 44 ms, and the result is music that is slow and warbles. ## Fix Keep the cushion exactly as it was, and additionally hold writes to one buffer period so the cadence stays even. The wait is skipped when the stream is running low, so it can never cause an underrun, and the deadline is per-port so multiple output ports do not interfere with each other. ## Testing PPSA03647 (3D Mini Golf) on Linux, menu music, before and after. With the fix the music plays correctly and the write interval is steady at ~5.4 ms with microsecond-level deviation. This is not Windows-specific in principle; it just does not show up as clearly there, since a bursty cadence is easier for a Windows audio backend to absorb. AI assistance (OpenCode) was used for the measurements and this description; I reviewed the results before posting.
The blocking queue check only enforced a minimum cushion, so the guest
could queue a burst of buffers and then be blocked for the whole cushion.
Measured on PPSA03647, intervals between guest writes alternated between
0 ms and ~44 ms instead of one 5.33 ms buffer period, while the average
rate stayed correct at 48000 frames/s. Mixers that run on a timer cannot
track that cadence and the music turns slow and warbling.

Keep the cushion as-is, but also hold writes to the buffer period, and
skip that wait when the stream is running low so it cannot underrun.

Intervals become ~5.4 ms with microsecond-level deviation and the menu
music plays correctly.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:33:50 +00:00
github manually merged commit 5344cb6284 into gh-pr/822/base 2026-11-26 09:33:52 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 05:19 UTC · original

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

PortOut now stores a deadline for the next blocking write. When the buffer period is nonzero and the SDL queue exceeds two prepared buffers, QueueSdlAudio resets a stale deadline or waits until a future deadline, then advances it by one buffer period. Existing queue-depth pacing and its 200 ms timeout remain unchanged.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🔵 Low · up to 0d8c8

Simultaneous writes to one audio port may produce audible pacing errors. Serialize per-port writes before merging, or accept this bounded risk.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 0d8c8

The change affects audio-write pacing, not access privileges or a new external interface. No introduced security issue was established, though concurrent access and failure recovery need clearer guarantees.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The direct new timing effect is confined to blocking writers on ports with sufficiently queued audio. The supplied evidence shows no new network, credential, persistence, or deployment path.

Trust Boundaries and Controls

  • observed — The existing blocking choice reaches the internal queue helper unchanged; the new wait does not force pacing on nonblocking Audio2 pushes.

Resilience and Maintainability Implications

  • observed — Validity checks and close use the port mutex, but output reads and updates port state without holding it. Whether callers must serialize output against close or other writes is not established by the inspected contract.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: pacing blocking AudioOut writes at an even cadence.
Description check ✅ Passed The description directly explains the audio pacing problem, the implemented fix, and the reported testing results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 05:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/822#issuecomment-5827230213) <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/822"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough `PortOut` now stores a deadline for the next blocking write. When the buffer period is nonzero and the SDL queue exceeds two prepared buffers, `QueueSdlAudio` resets a stale deadline or waits until a future deadline, then advances it by one buffer period. Existing queue-depth pacing and its 200 ms timeout remain unchanged. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"0d8c85a936cd92c099d582d5df57019641c47d18" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `0d8c8` <!-- final_review_risk_coverage:{"sourceCommitId":"0d8c85a936cd92c099d582d5df57019641c47d18","coveredCommitId":"0d8c85a936cd92c099d582d5df57019641c47d18","kind":"reviewed"} --> Simultaneous writes to one audio port may produce audible pacing errors. Serialize per-port writes before merging, or accept this bounded risk. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `0d8c8` The change affects audio-write pacing, not access privileges or a new external interface. No introduced security issue was established, though concurrent access and failure recovery need clearer guarantees. **Retained concerns** No architecture-level concerns identified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The direct new timing effect is confined to blocking writers on ports with sufficiently queued audio. The supplied evidence shows no new network, credential, persistence, or deployment path. **Trust Boundaries and Controls** - _observed_ — The existing blocking choice reaches the internal queue helper unchanged; the new wait does not force pacing on nonblocking Audio2 pushes. **Resilience and Maintainability Implications** - _observed_ — Validity checks and close use the port mutex, but output reads and updates port state without holding it. Whether callers must serialize output against close or other writes is not established by the inspected contract. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :----------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: pacing blocking AudioOut writes at an even cadence. | | Description check | ✅ Passed | The description directly explains the audio pacing problem, the implemented fix, and the reported testing results. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 05:19 UTC · original
On src/libs/audio.cpp line 395 (outdated):

@@ -375,6 +380,29 @@ bool Audio::QueueSdlAudio(PortOut* port, const void* data, bool blocking) {
 			}
 			Common::Thread::SleepMicro(1000);
 		}
+
+		// The queue-depth check alone lets the guest emit a burst of buffers and then stall
+		// for the whole cushion, because nothing stops it from refilling the queue as fast
+		// as it can. The long-run rate still comes out right, but the guest's audio thread
+		// sees intervals alternating between ~0 ms and ~44 ms instead of one buffer period,
+		// and mixers that run on a timer cannot track that: the music ends up slow and
+		// warbling. Keep the cushion for latency, but also hold writes to the buffer period
+		// so the cadence stays even. If the stream is running low, write immediately.
+		if (buffer_us != 0) {
+			const auto now = std::chrono::steady_clock::now();
+			if (port->next_write.time_since_epoch().count() == 0 ||
+			    now > port->next_write + std::chrono::microseconds(buffer_us)) {
+				port->next_write = now;

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n 'QueueSdlAudio|AudioOutOutput|AudioOutOutputs|m_mutex|next_write' src/libs/audio.cpp src/libs/libAudio2.cpp src/libs/audio_internal.h
sed -n '95,120p;345,420p' src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6580


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- AudioOutOutputs and nearby methods ---'
sed -n '500,575p' src/libs/audio.cpp
printf '%s\n' '--- public AudioOutOutput entrypoints ---'
sed -n '880,970p' src/libs/audio.cpp
printf '%s\n' '--- handle lookup and port lifecycle ---'
sed -n '410,510p' src/libs/audio.cpp
sed -n '610,710p' src/libs/audio.cpp
printf '%s\n' '--- all AudioOutOutputs callers ---'
rg -n -C 5 'AudioInternal::AudioOutOutputs|AudioOutOutputs\(|AudioOutOutput\(' src --glob '*.{cpp,h,hpp}'
printf '%s\n' '--- PortOut declarations and lock-related members ---'
sed -n '70,155p' src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 19062


🏁 Script executed:

set -eu
sed -n '500,575p' src/libs/audio.cpp
sed -n '880,970p' src/libs/audio.cpp
sed -n '410,510p' src/libs/audio.cpp
sed -n '610,710p' src/libs/audio.cpp
rg -n -C 5 'AudioInternal::AudioOutOutputs|AudioOutOutputs\(|AudioOutOutput\(' src --glob '*.{cpp,h,hpp}'
sed -n '70,155p' src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 18846


🏁 Script executed:

set -eu
printf '%s\n' '--- AudioOutOutputs ---'
sed -n '500,575p' src/libs/audio.cpp
printf '%s\n' '--- public output APIs ---'
sed -n '880,970p' src/libs/audio.cpp
printf '%s\n' '--- port lookup/lifecycle ---'
sed -n '410,510p' src/libs/audio.cpp
sed -n '610,710p' src/libs/audio.cpp
printf '%s\n' '--- callers ---'
rg -n -C 5 'AudioInternal::AudioOutOutputs|AudioOutOutputs\(|AudioOutOutput\(' src --glob '*.{cpp,h,hpp}'

Repository: KytyPS5/KytyPS5

Length of output: 16002


Serialize each output port through its deadline update and stream write.

AudioOutOutput validates the handle under m_mutex, but Audio::AudioOutOutputs runs after that lock is released. Two calls for the same handle can therefore enter QueueSdlAudio concurrently. The calls race on PortOut::next_write, and their stream writes are not serialized with the deadline updates.

This can break the intended output cadence and cause audible pacing errors. Use a per-port mutex for all output modes. Acquire it before QueueSdlAudio, and acquire the same mutex in AudioOutClose before resetting the port. Keep the mutex outside PortOut, because AudioOutClose assigns port = {}.

Suggested fix
 	Common::Mutex m_mutex;
+	Common::Mutex m_out_port_mutex[OUT_PORTS_MAX];
 	PortOut       m_out_ports[OUT_PORTS_MAX];
 	PortIn        m_in_ports[IN_PORTS_MAX];
 	for (uint32_t i = 0; i < num; i++) {
+		const auto port_id = params[i].handle.GetId();
+		Common::LockGuard port_lock(m_out_port_mutex[port_id]);
-		auto& port = m_out_ports[params[i].handle.GetId()];
+		auto& port = m_out_ports[port_id];

 		QueueSdlAudio(&port, params[i].data, blocking);
 	}
 	if (AudioOutValid(handle)) {
+		Common::LockGuard port_lock(m_out_port_mutex[handle.GetId()]);
 		auto& port = m_out_ports[handle.GetId()];

 		CloseSdlDevice(&port);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 05:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/822#discussion_r4101348705) On `src/libs/audio.cpp` line 395 (outdated): ```diff @@ -375,6 +380,29 @@ bool Audio::QueueSdlAudio(PortOut* port, const void* data, bool blocking) { } Common::Thread::SleepMicro(1000); } + + // The queue-depth check alone lets the guest emit a burst of buffers and then stall + // for the whole cushion, because nothing stops it from refilling the queue as fast + // as it can. The long-run rate still comes out right, but the guest's audio thread + // sees intervals alternating between ~0 ms and ~44 ms instead of one buffer period, + // and mixers that run on a timer cannot track that: the music ends up slow and + // warbling. Keep the cushion for latency, but also hold writes to the buffer period + // so the cadence stays even. If the stream is running low, write immediately. + if (buffer_us != 0) { + const auto now = std::chrono::steady_clock::now(); + if (port->next_write.time_since_epoch().count() == 0 || + now > port->next_write + std::chrono::microseconds(buffer_us)) { + port->next_write = now; ``` _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash rg -n 'QueueSdlAudio|AudioOutOutput|AudioOutOutputs|m_mutex|next_write' src/libs/audio.cpp src/libs/libAudio2.cpp src/libs/audio_internal.h sed -n '95,120p;345,420p' src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6580 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- AudioOutOutputs and nearby methods ---' sed -n '500,575p' src/libs/audio.cpp printf '%s\n' '--- public AudioOutOutput entrypoints ---' sed -n '880,970p' src/libs/audio.cpp printf '%s\n' '--- handle lookup and port lifecycle ---' sed -n '410,510p' src/libs/audio.cpp sed -n '610,710p' src/libs/audio.cpp printf '%s\n' '--- all AudioOutOutputs callers ---' rg -n -C 5 'AudioInternal::AudioOutOutputs|AudioOutOutputs\(|AudioOutOutput\(' src --glob '*.{cpp,h,hpp}' printf '%s\n' '--- PortOut declarations and lock-related members ---' sed -n '70,155p' src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 19062 --- 🏁 Script executed: ```bash set -eu sed -n '500,575p' src/libs/audio.cpp sed -n '880,970p' src/libs/audio.cpp sed -n '410,510p' src/libs/audio.cpp sed -n '610,710p' src/libs/audio.cpp rg -n -C 5 'AudioInternal::AudioOutOutputs|AudioOutOutputs\(|AudioOutOutput\(' src --glob '*.{cpp,h,hpp}' sed -n '70,155p' src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 18846 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- AudioOutOutputs ---' sed -n '500,575p' src/libs/audio.cpp printf '%s\n' '--- public output APIs ---' sed -n '880,970p' src/libs/audio.cpp printf '%s\n' '--- port lookup/lifecycle ---' sed -n '410,510p' src/libs/audio.cpp sed -n '610,710p' src/libs/audio.cpp printf '%s\n' '--- callers ---' rg -n -C 5 'AudioInternal::AudioOutOutputs|AudioOutOutputs\(|AudioOutOutput\(' src --glob '*.{cpp,h,hpp}' ``` Repository: KytyPS5/KytyPS5 Length of output: 16002 --- </details> **Serialize each output port through its deadline update and stream write.** `AudioOutOutput` validates the handle under `m_mutex`, but `Audio::AudioOutOutputs` runs after that lock is released. Two calls for the same handle can therefore enter `QueueSdlAudio` concurrently. The calls race on `PortOut::next_write`, and their stream writes are not serialized with the deadline updates. This can break the intended output cadence and cause audible pacing errors. Use a per-port mutex for all output modes. Acquire it before `QueueSdlAudio`, and acquire the same mutex in `AudioOutClose` before resetting the port. Keep the mutex outside `PortOut`, because `AudioOutClose` assigns `port = {}`. <details> <summary>Suggested fix</summary> ```diff Common::Mutex m_mutex; + Common::Mutex m_out_port_mutex[OUT_PORTS_MAX]; PortOut m_out_ports[OUT_PORTS_MAX]; PortIn m_in_ports[IN_PORTS_MAX]; ``` ```diff for (uint32_t i = 0; i < num; i++) { + const auto port_id = params[i].handle.GetId(); + Common::LockGuard port_lock(m_out_port_mutex[port_id]); - auto& port = m_out_ports[params[i].handle.GetId()]; + auto& port = m_out_ports[port_id]; QueueSdlAudio(&port, params[i].data, blocking); } ``` ```diff if (AudioOutValid(handle)) { + Common::LockGuard port_lock(m_out_port_mutex[handle.GetId()]); auto& port = m_out_ports[handle.GetId()]; CloseSdlDevice(&port); ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0fb5ce5e2cba510150f14c2d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 05:19 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 08bdf1c6-0b14-4e18-9378-07ad511e2019

📥 Commits

Reviewing files that changed from the base of the PR and between 5a705dd15f and 0d8c85a936.

📒 Files selected for processing (1)
  • src/libs/audio.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 05:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/822#pullrequestreview-5313685017) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `08bdf1c6-0b14-4e18-9378-07ad511e2019` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 5a705dd15f9312f7db29baa91dfd93a2c895cb53 and 0d8c85a936cd92c099d582d5df57019641c47d18. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/audio.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠Nmzik on GitHub · 2026-09-25 08:29 UTC · original

@⁠6d4m Thanks!

**@⁠Nmzik** on GitHub · 2026-09-25 08:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/822#issuecomment-5829370557) @⁠6d4m Thanks!
This discussion has been locked. Commenting is limited to contributors.
No description provided.