Capture PCM at set time when multiple AudioOut2 ports share a buffer #826

Manually merged
github merged 4 commits from gh-pr/826/head into gh-pr/826/base 2026-11-26 09:34:01 +00:00
Owner

@⁠EmK530 on GitHub · 2026-09-25 14:10 UTC · original
EmK530:fix/criware-audio → main · +87 −21 · 2 files · 4 commits · merged 2026-09-25 22:19 UTC

Summary

The CRIWARE audio engine renders multiple AudioOut2 ports in turn and passes the same scratch PCM buffer to sceAudioOut2PortSetAttributes for each port. Kyty previously retained the buffer pointer until ContextPush, after CRIWARE could already have overwritten it, causing silence in Neptunia ReVerse. The PS5 SDK AudioOut2 reference says the PCM buffer is copied by sceAudioOut2PortSetAttributes and may be freed when the call returns.

Change

Each AudioOut2 port now owns a copy of its PCM bytes at AudioOut2PortSetAttributes time. The queued output uses those bytes, kept alive through the synchronous backend submission. This replaces the earlier shared-pointer detection and snapshot fallback logic.

Testing

  • audio_out2_port_tests passes, including a regression that reuses and overwrites one scratch buffer across two ports before ContextPush.
  • Neptunia ReVerse (PPSA02721) launched with the checked-in launch.json arguments. The host output monitor captured nonzero PCM from kyty_emulator during the run.

Original PR demonstration: https://github.com/user-attachments/assets/ea8ae29b-2e95-4a99-a483-3cf73beaf1e2

AI usage

AI was involved in the process of debugging and zeroing in on the cause of this issue and implementing a fix. I have reviewed the changes in post, understood them and wrote this PR myself.

**@⁠EmK530** on GitHub · 2026-09-25 14:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/826) `EmK530:fix/criware-audio` → `main` · +87 −21 · 2 files · 4 commits · merged 2026-09-25 22:19 UTC # Summary The CRIWARE audio engine renders multiple AudioOut2 ports in turn and passes the same scratch PCM buffer to `sceAudioOut2PortSetAttributes` for each port. Kyty previously retained the buffer pointer until `ContextPush`, after CRIWARE could already have overwritten it, causing silence in Neptunia ReVerse. The PS5 SDK AudioOut2 reference says the PCM buffer is copied by `sceAudioOut2PortSetAttributes` and may be freed when the call returns. # Change Each AudioOut2 port now owns a copy of its PCM bytes at `AudioOut2PortSetAttributes` time. The queued output uses those bytes, kept alive through the synchronous backend submission. This replaces the earlier shared-pointer detection and snapshot fallback logic. # Testing - `audio_out2_port_tests` passes, including a regression that reuses and overwrites one scratch buffer across two ports before `ContextPush`. - Neptunia ReVerse (`PPSA02721`) launched with the checked-in `launch.json` arguments. The host output monitor captured nonzero PCM from `kyty_emulator` during the run. Original PR demonstration: https://github.com/user-attachments/assets/ea8ae29b-2e95-4a99-a483-3cf73beaf1e2 # AI usage AI was involved in the process of debugging and zeroing in on the cause of this issue and implementing a fix. I have reviewed the changes in post, understood them and wrote this PR myself.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:00 +00:00
github manually merged commit 096401e3d8 into gh-pr/826/base 2026-11-26 09:34:01 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 14:17 UTC · original · edited 2026-09-25 22:29 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: fa5a60e5-06a1-4c27-abb5-271086072f88

📥 Commits

Reviewing files that changed from the base of the PR and between 815a46f1ee and 94494980ba.

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

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


📝 Walkthrough

Walkthrough

Audio output ports now track whether their PCM snapshots are fresh. The code calculates PCM buffer size from the sample count, channel count, and data type. Setting PCM attributes clears the prior snapshot and captures PCM only when the pointer, audio handle, device, and calculated size meet the stated conditions. Queueing consumes the freshness flag and uses a snapshot only when it is fresh, the PCM pointer is shared, and the snapshot size is valid. Otherwise, it queues the current PCM pointer.

Suggested reviewers: nmzik

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 94494

No actionable issue remains in the reviewed audio snapshot change; it is ready to merge after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 94494

The change narrows when an existing PCM snapshot is used. The review found no new access path or weakened device check, but runtime isolation and caller-memory guarantees remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — In the visible output path, snapshot substitution is limited to used ports in the pushed context and feeds an existing device-backed audio output path. This does not establish process- or tenant-level isolation.

Trust Boundaries and Controls

  • observed — The caller supplies PCM attributes and a port handle. The entrypoint looks up an existing port before updating it; the snapshot copy uses the existing device and size checks, rather than introducing a new route to the backend.

Resilience and Maintainability Implications

  • observed — One-shot freshness prevents reuse of an older snapshot on repeated pushes. When freshness or the shared-buffer checks fail, output follows the existing pointer path.
🚥 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 4 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the main change: capturing PCM data when multiple AudioOut2 ports share a buffer.
Description check ✅ Passed The description directly explains the shared-buffer issue, the snapshot-based fix, and the reported testing results.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 14:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/826#issuecomment-5833912855) · edited 2026-09-25 22:29 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/826"><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**: `fa5a60e5-06a1-4c27-abb5-271086072f88` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 815a46f1ee94f25dca93f4c1c047436bda4c0e79 and 94494980ba3275bcf2583545dfdbd238880cb1b9. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/libAudio2.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Audio output ports now track whether their PCM snapshots are fresh. The code calculates PCM buffer size from the sample count, channel count, and data type. Setting PCM attributes clears the prior snapshot and captures PCM only when the pointer, audio handle, device, and calculated size meet the stated conditions. Queueing consumes the freshness flag and uses a snapshot only when it is fresh, the PCM pointer is shared, and the snapshot size is valid. Otherwise, it queues the current PCM pointer. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"94494980ba3275bcf2583545dfdbd238880cb1b9" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `94494` <!-- final_review_risk_coverage:{"sourceCommitId":"94494980ba3275bcf2583545dfdbd238880cb1b9","coveredCommitId":"94494980ba3275bcf2583545dfdbd238880cb1b9","kind":"reviewed"} --> No actionable issue remains in the reviewed audio snapshot change; it is ready to merge after normal checks. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `94494` The change narrows when an existing PCM snapshot is used. The review found no new access path or weakened device check, but runtime isolation and caller-memory guarantees remain unverified. **Retained concerns** No architecture-level concerns identified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — In the visible output path, snapshot substitution is limited to used ports in the pushed context and feeds an existing device-backed audio output path. This does not establish process- or tenant-level isolation. **Trust Boundaries and Controls** - _observed_ — The caller supplies PCM attributes and a port handle. The entrypoint looks up an existing port before updating it; the snapshot copy uses the existing device and size checks, rather than introducing a new route to the backend. **Resilience and Maintainability Implications** - _observed_ — One-shot freshness prevents reuse of an older snapshot on repeated pushes. When freshness or the shared-buffer checks fail, output follows the existing pointer path. </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 4 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 | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------- | | 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. | | Title check | ✅ Passed | The title clearly identifies the main change: capturing PCM data when multiple AudioOut2 ports share a buffer. | | Description check | ✅ Passed | The description directly explains the shared-buffer issue, the snapshot-based fix, and the reported testing results. | </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 14:17 UTC · original · edited 2026-09-25 15:16 UTC
On src/libs/libAudio2.cpp line 387 (outdated):

@@ -352,15 +353,41 @@ static bool audioout2_context_has_queueable_device(AudioOut2ContextHandle ctx) {
 	return false;
 }
 
+static size_t audioout2_pcm_bytes(const AudioOut2PortStateEntry& state) {
+	const auto data_type = state.data_format & 0x7fu;
+	const auto bytes     = (data_type == 0 ? 4u : (data_type == 1 ? 2u : 0u));
+	return static_cast<size_t>(state.samples_num) * audioout2_data_format_channels(state.data_format) * bytes;
+}
+
 static void audioout2_queue_context_audio(AudioOut2ContextHandle ctx, bool blocking) {
 	std::vector<AudioInternal::OutputParam> params;
 	params.reserve(AudioInternal::OUT_PORTS_MAX);
 
+    // Snapshots of ports whose pointer is shared with another port in the same context.
+    std::vector<std::vector<uint8_t>> shared_pcm;
+    shared_pcm.reserve(AudioInternal::OUT_PORTS_MAX);
+
 	g_audioout2_port_mutex.Lock();
 	for (const auto& state: g_audioout2_ports) {
 		if (state.used && state.context == ctx && state.audio_handle > 0 &&
 		    state.pcm_data != nullptr && params.size() < AudioInternal::OUT_PORTS_MAX) {
-			params.push_back(AudioInternal::OutputParam {state.audio_handle, state.pcm_data});
+			const void* data = state.pcm_data;
+
+			bool shared = false;
+			for (const auto& other: g_audioout2_ports) {
+				if (&other != &state && other.used && other.context == ctx &&
+				    other.pcm_data == state.pcm_data) {
+					shared = true;
+					break;
+				}
+			}
+			if (shared && state.pcm_snapshot.size() == audioout2_pcm_bytes(state) &&
+			    !state.pcm_snapshot.empty()) {
+				shared_pcm.push_back(state.pcm_snapshot);
+				data = shared_pcm.back().data();

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not replay a snapshot on a later push.

If two ports retain the same PCM pointer, a second AudioOut2ContextPush can occur without another AudioOut2PortSetAttributes call. After the caller updates that buffer, this size check still selects the snapshots from the first push. The second push therefore outputs stale audio. Track whether each snapshot has already been submitted. When no new snapshot exists, use the current PCM pointer instead.

✅ Addressed in commits 3700dab to 9449498

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 14:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/826#discussion_r4105408917) · edited 2026-09-25 15:16 UTC On `src/libs/libAudio2.cpp` line 387 (outdated): ```diff @@ -352,15 +353,41 @@ static bool audioout2_context_has_queueable_device(AudioOut2ContextHandle ctx) { return false; } +static size_t audioout2_pcm_bytes(const AudioOut2PortStateEntry& state) { + const auto data_type = state.data_format & 0x7fu; + const auto bytes = (data_type == 0 ? 4u : (data_type == 1 ? 2u : 0u)); + return static_cast<size_t>(state.samples_num) * audioout2_data_format_channels(state.data_format) * bytes; +} + static void audioout2_queue_context_audio(AudioOut2ContextHandle ctx, bool blocking) { std::vector<AudioInternal::OutputParam> params; params.reserve(AudioInternal::OUT_PORTS_MAX); + // Snapshots of ports whose pointer is shared with another port in the same context. + std::vector<std::vector<uint8_t>> shared_pcm; + shared_pcm.reserve(AudioInternal::OUT_PORTS_MAX); + g_audioout2_port_mutex.Lock(); for (const auto& state: g_audioout2_ports) { if (state.used && state.context == ctx && state.audio_handle > 0 && state.pcm_data != nullptr && params.size() < AudioInternal::OUT_PORTS_MAX) { - params.push_back(AudioInternal::OutputParam {state.audio_handle, state.pcm_data}); + const void* data = state.pcm_data; + + bool shared = false; + for (const auto& other: g_audioout2_ports) { + if (&other != &state && other.used && other.context == ctx && + other.pcm_data == state.pcm_data) { + shared = true; + break; + } + } + if (shared && state.pcm_snapshot.size() == audioout2_pcm_bytes(state) && + !state.pcm_snapshot.empty()) { + shared_pcm.push_back(state.pcm_snapshot); + data = shared_pcm.back().data(); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Do not replay a snapshot on a later push.** If two ports retain the same PCM pointer, a second `AudioOut2ContextPush` can occur without another `AudioOut2PortSetAttributes` call. After the caller updates that buffer, this size check still selects the snapshots from the first push. The second push therefore outputs stale audio. Track whether each snapshot has already been submitted. When no new snapshot exists, use the current PCM pointer instead. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:557cd8e723c731d914f18ef9 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 3700dab to 9449498
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 14:17 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: ec607b4c-b663-4bc8-a945-01a303a66df1

📥 Commits

Reviewing files that changed from the base of the PR and between 7e1c2d1532 and 815a46f1ee.

📒 Files selected for processing (1)
  • src/libs/libAudio2.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 14:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/826#pullrequestreview-5318756800) · **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**: `ec607b4c-b663-4bc8-a945-01a303a66df1` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7e1c2d1532cd0421ccd7b9fdc61bd2eb7b535d46 and 815a46f1ee94f25dca93f4c1c047436bda4c0e79. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/libAudio2.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 22:19 UTC · original

@⁠EmK530 Thanks!

**@⁠Nmzik** on GitHub · 2026-09-25 22:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/826#issuecomment-5840441682) @⁠EmK530 Thanks!
This discussion has been locked. Commenting is limited to contributors.
No description provided.