audio: serialize blocking writes per output port #841

Closed
github-bot wants to merge 1 commit from gh-pr/841/head into gh-pr/841/base
Owner

@⁠6d4m on GitHub · 2026-09-26 00:30 UTC · original
6d4m:fix/audioout-per-port-lock-fork → main · +68 −23 · 1 files · 1 commits · closed without merging

Follow-up to #822, from the CodeRabbit review comment there.

AudioOutOutputs validates the handle under m_mutex, but the write happens after that lock is released, so two guest threads can enter QueueSdlAudio for the same port at once. With the write pacing from #822 that means both threads race on the port's output clock and interleave their writes into the same SDL stream.

This adds one mutex per output port, held across QueueSdlAudio and the last_output_time update. Locking the write but not the clock update would have left the race half open, since the pacing now derives each write's deadline from that field, so a concurrent batch could read it stale and two writes would end up sharing a deadline.

Two smaller points while I was in there:

  • The mutex lives outside PortOut because AudioOutClose does port = {} and would otherwise reset a live mutex.
  • Every handle in a batch is now bounds checked, not just the first. The old code validated params[0] and then indexed the port array with params[i].handle for the rest, so an invalid handle was already undefined behaviour.

Lock order is always m_mutex then the port mutex, so there is no cycle. AudioOutClose takes the same lock.

Verified no audible change on PPSA03647 and PPSA09232, which is what I would expect from a change that only closes a race that has not been observed firing.

Note: this branch is based on my fork's older main rather than current upstream, because pushing the newer workflow commits needs a token scope I do not have. The change itself applies on top of current main as is.

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

**@⁠6d4m** on GitHub · 2026-09-26 00:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/841) `6d4m:fix/audioout-per-port-lock-fork` → `main` · +68 −23 · 1 files · 1 commits · closed without merging Follow-up to #822, from the CodeRabbit review comment there. `AudioOutOutputs` validates the handle under `m_mutex`, but the write happens after that lock is released, so two guest threads can enter `QueueSdlAudio` for the same port at once. With the write pacing from #822 that means both threads race on the port's output clock and interleave their writes into the same SDL stream. This adds one mutex per output port, held across `QueueSdlAudio` and the `last_output_time` update. Locking the write but not the clock update would have left the race half open, since the pacing now derives each write's deadline from that field, so a concurrent batch could read it stale and two writes would end up sharing a deadline. Two smaller points while I was in there: - The mutex lives outside `PortOut` because `AudioOutClose` does `port = {}` and would otherwise reset a live mutex. - Every handle in a batch is now bounds checked, not just the first. The old code validated `params[0]` and then indexed the port array with `params[i].handle` for the rest, so an invalid handle was already undefined behaviour. Lock order is always `m_mutex` then the port mutex, so there is no cycle. `AudioOutClose` takes the same lock. Verified no audible change on PPSA03647 and PPSA09232, which is what I would expect from a change that only closes a race that has not been observed firing. Note: this branch is based on my fork's older `main` rather than current upstream, because pushing the newer workflow commits needs a token scope I do not have. The change itself applies on top of current `main` as is. AI assistance (OpenCode) was used for the investigation and this description; I reviewed the results before posting.
AudioOutOutputs validates the handle under m_mutex but queues the buffer
after that lock is released, so two guest threads can enter QueueSdlAudio
for the same port at once. With the write pacing from #822 that means both
threads race on the port's output clock and interleave their writes into
the same SDL stream.

Add one mutex per output port and hold it across QueueSdlAudio and the
last_output_time update, so the clock cannot be read stale by a concurrent
batch and two writes cannot share a deadline. The mutex lives outside
PortOut because AudioOutClose resets the port. AudioOutClose takes the same
lock, and every handle in a batch is now bounds checked rather than only
the first.

Lock order is always m_mutex then the port mutex, so there is no cycle.
Builds clean on Linux. Gameplay audio was verified unchanged on PPSA03647
and PPSA09232 for the pre-rebase version of this change; the rebase and the
review fixes have not been re-tested in game.

Also read the batch sample count and block time under the first port lock.
AudioOutClose resets the port, so the previous unlocked read could pick up
freq == 0 and divide by it, or a sample count belonging to a port that had
already been reopened. Unused ports are now skipped before pacing and
queueing, and AudioOutOpen and AudioOutSetVolume take the port lock as well
so they cannot race with a batch in QueueSdlAudio.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:37 +00:00
github-bot closed this pull request 2026-11-26 09:34:37 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 00:39 UTC · original · edited 2026-09-27 01:07 UTC

Review in Change Stack →

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: b69cafb2-fd4a-4f7c-b5ff-05f3424334ea

📥 Commits

Reviewing files that changed from the base of the PR and between fa325130ae2b936aa87967a25060c0adeb9d859a and cf70ec2bdd.

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

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

Audio adds a mutex for each output port. AudioOutOpen, AudioOutClose, and AudioOutSetVolume use these mutexes when accessing ports. AudioOutOutputs checks port usage and timing under port locks, skips out-of-range or unused ports, and queues audio or haptics while updating each port’s output clock. It returns the first port’s sample count saved before processing.

Suggested reviewers: nmzik

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to cf70e

The reported output races are addressed, and no new merge-blocking regression is established. The existing stale-handle limitation remains.

Security Architecture Review

Security architecture risk: 🔵 Low · up to cf70e

The change improves isolation of concurrent writes and does not appear to expand audio access. A busy output port can now delay operations on other ports during close. Handle reuse and batch-size validation remain separate, pre-existing issues.

Retained concerns

  • Low · reliability · inferred: Closing a busy output port can hold the global audio mutex while waiting for its port lock, delaying otherwise independent port operations. The duration and practical impact of repeated contention are not established.
Security review details

Security Blast Radius

  • inferred — The evidenced reach is guest-facing audio operations into local output-port state and SDL or controller-haptics sinks. The supplied evidence does not establish cross-tenant, network, or deployment-level exposure.

Security Findings and Attack Paths

  • observed — The unchanged public batch wrapper iterates caller-supplied num while filling a 32-entry local array without checking that num fits. This is a pre-existing input-boundary condition, not a regression established by the locking change.

Trust Boundaries and Controls

  • observed — Handle validation checks the port range and used state under the global mutex. Subsequent output access checks bounds and used state under the selected port lock, but those checks do not distinguish successive lifetimes of a reused slot.

Resilience and Maintainability Implications

  • inferred — Per-port serialization prevents close from resetting an actively queued port, but close can wait for blocking queue work while retaining the global mutex. That trades a port-lifetime race for potential contention across ports.

Hardening Proposals

  • proposed — Separately bound the public batch count before filling its local array, and consider generation-aware handles if closed handles must not address a reopened slot.
🚥 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 5 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly explains the per-port locking change, the race it addresses, the bounds-checking fix, lock order, validation, and branch context.
Title check ✅ Passed The title clearly and concisely identifies the main change: serializing blocking audio writes per output port.
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-26 00:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/841#issuecomment-5841598655) · edited 2026-09-27 01:07 UTC <!-- 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/841"><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 --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `b69cafb2-fd4a-4f7c-b5ff-05f3424334ea` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between fa325130ae2b936aa87967a25060c0adeb9d859a and cf70ec2bdd99e9e1510455d81c53cb082f3c17db. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/audio.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Audio adds a mutex for each output port. AudioOutOpen, AudioOutClose, and AudioOutSetVolume use these mutexes when accessing ports. AudioOutOutputs checks port usage and timing under port locks, skips out-of-range or unused ports, and queues audio or haptics while updating each port’s output clock. It returns the first port’s sample count saved before processing. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"cf70ec2bdd99e9e1510455d81c53cb082f3c17db" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `cf70e` <!-- final_review_risk_coverage:{"sourceCommitId":"cf70ec2bdd99e9e1510455d81c53cb082f3c17db","coveredCommitId":"cf70ec2bdd99e9e1510455d81c53cb082f3c17db","kind":"reviewed"} --> The reported output races are addressed, and no new merge-blocking regression is established. The existing stale-handle limitation remains. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `cf70e` The change improves isolation of concurrent writes and does not appear to expand audio access. A busy output port can now delay operations on other ports during close. Handle reuse and batch-size validation remain separate, pre-existing issues. **Retained concerns** - **Low · reliability · inferred:** Closing a busy output port can hold the global audio mutex while waiting for its port lock, delaying otherwise independent port operations. The duration and practical impact of repeated contention are not established. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The evidenced reach is guest-facing audio operations into local output-port state and SDL or controller-haptics sinks. The supplied evidence does not establish cross-tenant, network, or deployment-level exposure. **Security Findings and Attack Paths** - _observed_ — The unchanged public batch wrapper iterates caller-supplied num while filling a 32-entry local array without checking that num fits. This is a pre-existing input-boundary condition, not a regression established by the locking change. **Trust Boundaries and Controls** - _observed_ — Handle validation checks the port range and used state under the global mutex. Subsequent output access checks bounds and used state under the selected port lock, but those checks do not distinguish successive lifetimes of a reused slot. **Resilience and Maintainability Implications** - _inferred_ — Per-port serialization prevents close from resetting an actively queued port, but close can wait for blocking queue work while retaining the global mutex. That trades a port-lifetime race for potential contention across ports. **Hardening Proposals** - _proposed_ — Separately bound the public batch count before filling its local array, and consider generation-aware handles if closed handles must not address a reopened slot. </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 5 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 | | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ✅ Passed | The description clearly explains the per-port locking change, the race it addresses, the bounds-checking fix, lock order, validation, and branch context. | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: serializing blocking audio writes per output port. | | 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-26 00:39 UTC · original · edited 2026-09-27 01:00 UTC
On src/libs/audio.cpp line 513 (outdated):

@@ -497,24 +504,31 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking
 	EXIT_NOT_IMPLEMENTED(num == 0);
 	EXIT_NOT_IMPLEMENTED(!AudioOutValid(params[0].handle));
 
-	const auto& first_port = m_out_ports[params[0].handle.GetId()];
-
-	uint64_t block_time   = (1000000 * first_port.samples_num) / first_port.freq;
-	uint64_t current_time = LibKernel::KernelGetProcessTime();
-
-	uint64_t max_wait_time = 0;
+	const auto first_id      = params[0].handle.GetId();
+	const auto first_samples = m_out_ports[first_id].samples_num;
 
-	for (uint32_t i = 0; i < num; i++) {
-		uint64_t next_time = m_out_ports[params[i].handle.GetId()].last_output_time + block_time;
-		uint64_t wait_time = (next_time > current_time ? next_time - current_time : 0);
-		max_wait_time      = (wait_time > max_wait_time ? wait_time : max_wait_time);
+	uint64_t block_time = 0;
+	{
+		Common::LockGuard port_lock(m_out_port_mutex[first_id]);
+		block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq;

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '110,140p;385,570p' src/libs/audio.cpp
sed -n '350,380p' src/libs/libAudio2.cpp
git diff 2aaf0c9ba3a4322a219b60a254a882716440bb36 fa325130ae2b936aa87967a25060c0adeb9d859a -- src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 11704


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- audio.cpp declarations and queue helper ---'
sed -n '1,115p' src/libs/audio.cpp
printf '%s\n' '--- audio.cpp output/open/close/volume paths ---'
sed -n '385,565p' src/libs/audio.cpp
printf '%s\n' '--- handle definition and audio output callers ---'
rg -n -C 4 'struct Id|class Id|Id::Create|AudioOutOutputs|audioout2_close_audio_handle|audio_handle|AudioOutOpen|AudioOutSetVolume' src/libs
printf '%s\n' '--- relevant libAudio2 lifecycle ---'
sed -n '300,390p' src/libs/libAudio2.cpp

Repository: KytyPS5/KytyPS5

Length of output: 31448


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- QueueSdlAudio and adjacent helpers ---'
rg -n -C 12 'QueueSdlAudio|OpenSdlDevice\\(PortOut|CloseSdlDevice|volume\\[|samples_num|format|stream' src/libs/audio.cpp
printf '%s\n' '--- exported output validation ---'
sed -n '900,945p' src/libs/audio.cpp
printf '%s\n' '--- AudioOut2 port creation and destruction ---'
sed -n '580,670p' src/libs/libAudio2.cpp

Repository: KytyPS5/KytyPS5

Length of output: 418


🏁 Script executed:

#!/bin/bash
set -e
line=$(rg -n -F 'QueueSdlAudio' src/libs/audio.cpp | head -n 1 | cut -d: -f1)
printf 'QueueSdlAudio reference: %s\n' "$line"
start=$((line-45))
if [ "$start" -lt 1 ]; then start=1; fi
end=$((line+35))
sed -n "${start},${end}p" src/libs/audio.cpp
printf '%s\n' '--- exported output validation ---'
sed -n '900,945p' src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4108


🏁 Script executed:

#!/bin/bash
set -e
rg -n '^bool Audio::QueueSdlAudio|^const void\* Audio::PrepareOutputBuffer' src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 315


🏁 Script executed:

#!/bin/bash
set -e
sed -n '275,390p' src/libs/audio.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4278


Synchronize port lifetime and reject stale output batches.

AudioOutOutputs validates the first handle, releases m_mutex, and reads samples_num without synchronization. AudioOutClose can clear the port before AudioOutOutputs acquires the port mutex. The later division can then use freq == 0 and crash.

PrepareOutputBuffer and QueueSdlAudio read samples_num, format, volume, channels_num, freq, and stream through PortOut. Lock the per-port mutex after m_mutex in AudioOutOpen and AudioOutSetVolume so these reads cannot race with updates.

Read first_samples under the first port lock. Recheck used after every port lock and skip unused ports before pacing or queueing.

These checks do not protect reopened ports. Audio::Id contains only the reusable port index. An old batch can acquire the lock after close and reopen, observe used == true, and queue stale data into the new port. Add a generation to the handle and validate it under the port lock, or hold the lifecycle lock across the complete output operation so close and reopen cannot occur during that operation.

Suggested output-path fix
-	const auto first_samples = m_out_ports[first_id].samples_num;
-
-	uint64_t block_time = 0;
+	uint32_t first_samples = 0;
+	uint64_t block_time    = 0;
 	{
 		Common::LockGuard port_lock(m_out_port_mutex[first_id]);
-		block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq;
+		const auto& first = m_out_ports[first_id];
+		if (!first.used || first.freq == 0) {
+			return 0;
+		}
+		first_samples = first.samples_num;
+		block_time    = (1000000ULL * first.samples_num) / first.freq;
 	}

Add if (!port.used) { continue; } immediately after acquiring each port lock in both loops.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 00:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/841#discussion_r4109584246) · edited 2026-09-27 01:00 UTC On `src/libs/audio.cpp` line 513 (outdated): ```diff @@ -497,24 +504,31 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking EXIT_NOT_IMPLEMENTED(num == 0); EXIT_NOT_IMPLEMENTED(!AudioOutValid(params[0].handle)); - const auto& first_port = m_out_ports[params[0].handle.GetId()]; - - uint64_t block_time = (1000000 * first_port.samples_num) / first_port.freq; - uint64_t current_time = LibKernel::KernelGetProcessTime(); - - uint64_t max_wait_time = 0; + const auto first_id = params[0].handle.GetId(); + const auto first_samples = m_out_ports[first_id].samples_num; - for (uint32_t i = 0; i < num; i++) { - uint64_t next_time = m_out_ports[params[i].handle.GetId()].last_output_time + block_time; - uint64_t wait_time = (next_time > current_time ? next_time - current_time : 0); - max_wait_time = (wait_time > max_wait_time ? wait_time : max_wait_time); + uint64_t block_time = 0; + { + Common::LockGuard port_lock(m_out_port_mutex[first_id]); + block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq; ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '110,140p;385,570p' src/libs/audio.cpp sed -n '350,380p' src/libs/libAudio2.cpp git diff 2aaf0c9ba3a4322a219b60a254a882716440bb36 fa325130ae2b936aa87967a25060c0adeb9d859a -- src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 11704 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- audio.cpp declarations and queue helper ---' sed -n '1,115p' src/libs/audio.cpp printf '%s\n' '--- audio.cpp output/open/close/volume paths ---' sed -n '385,565p' src/libs/audio.cpp printf '%s\n' '--- handle definition and audio output callers ---' rg -n -C 4 'struct Id|class Id|Id::Create|AudioOutOutputs|audioout2_close_audio_handle|audio_handle|AudioOutOpen|AudioOutSetVolume' src/libs printf '%s\n' '--- relevant libAudio2 lifecycle ---' sed -n '300,390p' src/libs/libAudio2.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 31448 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- QueueSdlAudio and adjacent helpers ---' rg -n -C 12 'QueueSdlAudio|OpenSdlDevice\\(PortOut|CloseSdlDevice|volume\\[|samples_num|format|stream' src/libs/audio.cpp printf '%s\n' '--- exported output validation ---' sed -n '900,945p' src/libs/audio.cpp printf '%s\n' '--- AudioOut2 port creation and destruction ---' sed -n '580,670p' src/libs/libAudio2.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 418 --- 🏁 Script executed: ```bash #!/bin/bash set -e line=$(rg -n -F 'QueueSdlAudio' src/libs/audio.cpp | head -n 1 | cut -d: -f1) printf 'QueueSdlAudio reference: %s\n' "$line" start=$((line-45)) if [ "$start" -lt 1 ]; then start=1; fi end=$((line+35)) sed -n "${start},${end}p" src/libs/audio.cpp printf '%s\n' '--- exported output validation ---' sed -n '900,945p' src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4108 --- 🏁 Script executed: ```bash #!/bin/bash set -e rg -n '^bool Audio::QueueSdlAudio|^const void\* Audio::PrepareOutputBuffer' src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 315 --- 🏁 Script executed: ```bash #!/bin/bash set -e sed -n '275,390p' src/libs/audio.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4278 --- </details> **Synchronize port lifetime and reject stale output batches.** `AudioOutOutputs` validates the first handle, releases `m_mutex`, and reads `samples_num` without synchronization. `AudioOutClose` can clear the port before `AudioOutOutputs` acquires the port mutex. The later division can then use `freq == 0` and crash. `PrepareOutputBuffer` and `QueueSdlAudio` read `samples_num`, `format`, `volume`, `channels_num`, `freq`, and `stream` through `PortOut`. Lock the per-port mutex after `m_mutex` in `AudioOutOpen` and `AudioOutSetVolume` so these reads cannot race with updates. Read `first_samples` under the first port lock. Recheck `used` after every port lock and skip unused ports before pacing or queueing. These checks do not protect reopened ports. `Audio::Id` contains only the reusable port index. An old batch can acquire the lock after close and reopen, observe `used == true`, and queue stale data into the new port. Add a generation to the handle and validate it under the port lock, or hold the lifecycle lock across the complete output operation so close and reopen cannot occur during that operation. <details> <summary>Suggested output-path fix</summary> ```diff - const auto first_samples = m_out_ports[first_id].samples_num; - - uint64_t block_time = 0; + uint32_t first_samples = 0; + uint64_t block_time = 0; { Common::LockGuard port_lock(m_out_port_mutex[first_id]); - block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq; + const auto& first = m_out_ports[first_id]; + if (!first.used || first.freq == 0) { + return 0; + } + first_samples = first.samples_num; + block_time = (1000000ULL * first.samples_num) / first.freq; } ``` Add `if (!port.used) { continue; }` immediately after acquiring each port lock in both loops. </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1b22ca78335ef2d575af357b --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 00:39 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: a7d64ce4-f9d1-461e-a8d5-d3ec0d934c39

📥 Commits

Reviewing files that changed from the base of the PR and between fd2e15ee73 and fa325130ae2b936aa87967a25060c0adeb9d859a.

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

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 00:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/841#pullrequestreview-5323826540) · **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**: `a7d64ce4-f9d1-461e-a8d5-d3ec0d934c39` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between fd2e15ee737ea9a671619246129bc2aae7e0bfda and fa325130ae2b936aa87967a25060c0adeb9d859a. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/audio.cpp` </details> **Included review availability:** This review used your included allowance. 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

@⁠6d4m on GitHub · 2026-09-27 00:52 UTC · original
On src/libs/audio.cpp line 513 (outdated):

@@ -497,24 +504,31 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking
 	EXIT_NOT_IMPLEMENTED(num == 0);
 	EXIT_NOT_IMPLEMENTED(!AudioOutValid(params[0].handle));
 
-	const auto& first_port = m_out_ports[params[0].handle.GetId()];
-
-	uint64_t block_time   = (1000000 * first_port.samples_num) / first_port.freq;
-	uint64_t current_time = LibKernel::KernelGetProcessTime();
-
-	uint64_t max_wait_time = 0;
+	const auto first_id      = params[0].handle.GetId();
+	const auto first_samples = m_out_ports[first_id].samples_num;
 
-	for (uint32_t i = 0; i < num; i++) {
-		uint64_t next_time = m_out_ports[params[i].handle.GetId()].last_output_time + block_time;
-		uint64_t wait_time = (next_time > current_time ? next_time - current_time : 0);
-		max_wait_time      = (wait_time > max_wait_time ? wait_time : max_wait_time);
+	uint64_t block_time = 0;
+	{
+		Common::LockGuard port_lock(m_out_port_mutex[first_id]);
+		block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq;

Thanks, all three taken.

  • first_samples and block_time are now read under the first port lock, with used and freq == 0 guards, and the call returns 0 if that port is gone.
  • Both loops recheck used after taking the port lock and skip the port before pacing or queueing.
  • AudioOutOpen and AudioOutSetVolume take the port lock after m_mutex as well, so they cannot race with a batch reading the port in QueueSdlAudio.

One more change while resolving the conflict with #843: the vibration branch no longer takes m_mutex. It needed that when the port lifetime was guarded only by the global lock; the port lock covers it now, and taking m_mutex while holding a port lock would invert the order used by AudioOutOpen/AudioOutClose.

The stale-batch-after-reopen case is not addressed. That needs a generation in Audio::Id, which is a larger change than this PR, so I left it out deliberately.

Also rebased onto bec67b7, it had gone conflicting.

**@⁠6d4m** on GitHub · 2026-09-27 00:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/841#discussion_r4113576940) On `src/libs/audio.cpp` line 513 (outdated): ```diff @@ -497,24 +504,31 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking EXIT_NOT_IMPLEMENTED(num == 0); EXIT_NOT_IMPLEMENTED(!AudioOutValid(params[0].handle)); - const auto& first_port = m_out_ports[params[0].handle.GetId()]; - - uint64_t block_time = (1000000 * first_port.samples_num) / first_port.freq; - uint64_t current_time = LibKernel::KernelGetProcessTime(); - - uint64_t max_wait_time = 0; + const auto first_id = params[0].handle.GetId(); + const auto first_samples = m_out_ports[first_id].samples_num; - for (uint32_t i = 0; i < num; i++) { - uint64_t next_time = m_out_ports[params[i].handle.GetId()].last_output_time + block_time; - uint64_t wait_time = (next_time > current_time ? next_time - current_time : 0); - max_wait_time = (wait_time > max_wait_time ? wait_time : max_wait_time); + uint64_t block_time = 0; + { + Common::LockGuard port_lock(m_out_port_mutex[first_id]); + block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq; ``` Thanks, all three taken. - `first_samples` and `block_time` are now read under the first port lock, with `used` and `freq == 0` guards, and the call returns 0 if that port is gone. - Both loops recheck `used` after taking the port lock and skip the port before pacing or queueing. - `AudioOutOpen` and `AudioOutSetVolume` take the port lock after `m_mutex` as well, so they cannot race with a batch reading the port in `QueueSdlAudio`. One more change while resolving the conflict with #843: the vibration branch no longer takes `m_mutex`. It needed that when the port lifetime was guarded only by the global lock; the port lock covers it now, and taking `m_mutex` while holding a port lock would invert the order used by `AudioOutOpen`/`AudioOutClose`. The stale-batch-after-reopen case is not addressed. That needs a generation in `Audio::Id`, which is a larger change than this PR, so I left it out deliberately. Also rebased onto `bec67b7`, it had gone conflicting.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-27 01:00 UTC · original
On src/libs/audio.cpp line 513 (outdated):

@@ -497,24 +504,31 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking
 	EXIT_NOT_IMPLEMENTED(num == 0);
 	EXIT_NOT_IMPLEMENTED(!AudioOutValid(params[0].handle));
 
-	const auto& first_port = m_out_ports[params[0].handle.GetId()];
-
-	uint64_t block_time   = (1000000 * first_port.samples_num) / first_port.freq;
-	uint64_t current_time = LibKernel::KernelGetProcessTime();
-
-	uint64_t max_wait_time = 0;
+	const auto first_id      = params[0].handle.GetId();
+	const auto first_samples = m_out_ports[first_id].samples_num;
 
-	for (uint32_t i = 0; i < num; i++) {
-		uint64_t next_time = m_out_ports[params[i].handle.GetId()].last_output_time + block_time;
-		uint64_t wait_time = (next_time > current_time ? next_time - current_time : 0);
-		max_wait_time      = (wait_time > max_wait_time ? wait_time : max_wait_time);
+	uint64_t block_time = 0;
+	{
+		Common::LockGuard port_lock(m_out_port_mutex[first_id]);
+		block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq;

@6d4m, thanks for the update. The current audio.cpp shows the first-port guards, per-port used checks, and port locks in AudioOutOpen and AudioOutSetVolume. Removing m_mutex from the vibration branch also preserves the stated lock order.

The stale-batch-after-reopen case remains possible because Audio::Id contains only a reusable port index. I’ll leave this thread open for that case. Would you like me to open a follow-up issue for generation-based handle validation?

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-27 01:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/841#discussion_r4113603241) On `src/libs/audio.cpp` line 513 (outdated): ```diff @@ -497,24 +504,31 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking EXIT_NOT_IMPLEMENTED(num == 0); EXIT_NOT_IMPLEMENTED(!AudioOutValid(params[0].handle)); - const auto& first_port = m_out_ports[params[0].handle.GetId()]; - - uint64_t block_time = (1000000 * first_port.samples_num) / first_port.freq; - uint64_t current_time = LibKernel::KernelGetProcessTime(); - - uint64_t max_wait_time = 0; + const auto first_id = params[0].handle.GetId(); + const auto first_samples = m_out_ports[first_id].samples_num; - for (uint32_t i = 0; i < num; i++) { - uint64_t next_time = m_out_ports[params[i].handle.GetId()].last_output_time + block_time; - uint64_t wait_time = (next_time > current_time ? next_time - current_time : 0); - max_wait_time = (wait_time > max_wait_time ? wait_time : max_wait_time); + uint64_t block_time = 0; + { + Common::LockGuard port_lock(m_out_port_mutex[first_id]); + block_time = (1000000 * m_out_ports[first_id].samples_num) / m_out_ports[first_id].freq; ``` `@6d4m`, thanks for the update. The current `audio.cpp` shows the first-port guards, per-port `used` checks, and port locks in `AudioOutOpen` and `AudioOutSetVolume`. Removing `m_mutex` from the vibration branch also preserves the stated lock order. The stale-batch-after-reopen case remains possible because `Audio::Id` contains only a reusable port index. I’ll leave this thread open for that case. Would you like me to open a follow-up issue for generation-based handle validation? _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.