audio: fix popping and time-stretching in output #966

Manually merged
github merged 1 commit from gh-pr/966/head into gh-pr/966/base 2026-11-26 09:38:33 +00:00
Owner

@⁠mhakkuh on GitHub · 2026-10-02 00:18 UTC · original
mhakkuh:fix-audio-output-timing → main · +447 −62 · 3 files · 1 commits · merged 2026-10-02 09:22 UTC

Problem

On Linux, Kyty's audio output could produce audible popping and time-stretching/distortion, most noticeably during speech.

A short speech sample could sound as though it was being stretched in time, for example a short "hey" becoming an elongated/distorted "heEEeEy", accompanied by pops.

The issue was reproducible with the SDL audio backend.

Reproduction

Tested with:

  • OS: Linux
  • Audio backend: SDL
  • Output: 48 kHz stereo
  • Guest audio block size: 256 samples
  • Kyty build: KytyPS5-2026-10-01-b3e419f
  • Game tested: PPSA12544

The SDL audio device was opened at 48000 Hz, 2 channels, and 2048 SDL sample frames.

The game submits audio in 256-sample blocks, corresponding to approximately 5.333 ms per guest audio block.

Investigation

Increasing the SDL audio buffer/queue size did not resolve the problem.

The relevant behavior was found in AudioOutOutputs().

After each output submission, last_output_time was being reset to the current host process time:

m_out_ports[params[i].handle.GetId()].last_output_time =
    LibKernel::KernelGetProcessTime();

This made the guest audio timing dependent on host scheduling jitter. Small variations in when AudioOutOutputs() was processed could therefore affect subsequent audio pacing.

Fix

Advance last_output_time by the duration of one guest audio block instead of resetting it to the current host time:

for (uint32_t i = 0; i < num; i++) {
    auto& port = m_out_ports[params[i].handle.GetId()];

    const uint64_t block_time =
        (1000000ULL * port.samples_num) / port.freq;

    if (port.last_output_time == 0) {
        port.last_output_time = LibKernel::KernelGetProcessTime();
    } else {
        port.last_output_time += block_time;
    }
}

For the tested 48 kHz / 256-sample configuration, one guest audio block represents approximately 5.333 ms.

This keeps the output timing reference tied to the guest audio stream rather than continually resynchronizing it to the host's current scheduling time.

Result

Before the change:

  • Audible popping
  • Speech time-stretching/distortion
  • Short speech samples could become audibly elongated

After the change:

  • Speech plays at the expected timing
  • The time-stretching effect is no longer present
  • Popping was no longer reproducible in the tested scenario
  • No host PipeWire configuration changes were required

Verification

The fix was tested by rebuilding Kyty and running the same game and audio sequences that reproduced the issue.

The issue was reproducible before the change and was no longer reproducible after the change.

Increasing the SDL audio queue/buffer size was also tested separately and did not produce the same improvement, helping isolate the issue to output timing rather than simply insufficient buffering.

Scope

This change only modifies how last_output_time is maintained.

It does not modify the audio samples, guest sample rate, channel configuration, SDL audio format, SDL device buffer size, or host audio configuration.

**@⁠mhakkuh** on GitHub · 2026-10-02 00:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/966) `mhakkuh:fix-audio-output-timing` → `main` · +447 −62 · 3 files · 1 commits · merged 2026-10-02 09:22 UTC ## Problem On Linux, Kyty's audio output could produce audible popping and time-stretching/distortion, most noticeably during speech. A short speech sample could sound as though it was being stretched in time, for example a short "hey" becoming an elongated/distorted "heEEeEy", accompanied by pops. The issue was reproducible with the SDL audio backend. ### Reproduction Tested with: - OS: Linux - Audio backend: SDL - Output: 48 kHz stereo - Guest audio block size: 256 samples - Kyty build: `KytyPS5-2026-10-01-b3e419f` - Game tested: PPSA12544 The SDL audio device was opened at 48000 Hz, 2 channels, and 2048 SDL sample frames. The game submits audio in 256-sample blocks, corresponding to approximately 5.333 ms per guest audio block. ### Investigation Increasing the SDL audio buffer/queue size did not resolve the problem. The relevant behavior was found in `AudioOutOutputs()`. After each output submission, `last_output_time` was being reset to the current host process time: ```cpp m_out_ports[params[i].handle.GetId()].last_output_time = LibKernel::KernelGetProcessTime(); ``` This made the guest audio timing dependent on host scheduling jitter. Small variations in when `AudioOutOutputs()` was processed could therefore affect subsequent audio pacing. ### Fix Advance `last_output_time` by the duration of one guest audio block instead of resetting it to the current host time: ```cpp for (uint32_t i = 0; i < num; i++) { auto& port = m_out_ports[params[i].handle.GetId()]; const uint64_t block_time = (1000000ULL * port.samples_num) / port.freq; if (port.last_output_time == 0) { port.last_output_time = LibKernel::KernelGetProcessTime(); } else { port.last_output_time += block_time; } } ``` For the tested 48 kHz / 256-sample configuration, one guest audio block represents approximately 5.333 ms. This keeps the output timing reference tied to the guest audio stream rather than continually resynchronizing it to the host's current scheduling time. ### Result Before the change: - Audible popping - Speech time-stretching/distortion - Short speech samples could become audibly elongated After the change: - Speech plays at the expected timing - The time-stretching effect is no longer present - Popping was no longer reproducible in the tested scenario - No host PipeWire configuration changes were required ### Verification The fix was tested by rebuilding Kyty and running the same game and audio sequences that reproduced the issue. The issue was reproducible before the change and was no longer reproducible after the change. Increasing the SDL audio queue/buffer size was also tested separately and did not produce the same improvement, helping isolate the issue to output timing rather than simply insufficient buffering. ### Scope This change only modifies how `last_output_time` is maintained. It does not modify the audio samples, guest sample rate, channel configuration, SDL audio format, SDL device buffer size, or host audio configuration.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:38:32 +00:00
github manually merged commit d2e778a5f2 into gh-pr/966/base 2026-11-26 09:38:33 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 00:22 UTC · original · edited 2026-10-02 00:25 UTC

Review in Change Stack →

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

📝 Walkthrough

Walkthrough

Audio output latency and blocking queue capacity increase. Playback and capture setup set the SDL audio device sample-frame hint to 2048; playback also retrieves and logs the obtained audio specification. Output timestamps are maintained per port and advance by the port’s sample-block duration after the first output.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to e5cea

The timestamp change can consume the audio buffer’s intended scheduling cushion and reintroduce popping during rapid blocking submissions. Rebase the timestamp at queue-priming transitions before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to e5cea

The change remains within audio handling and does not establish increased privileges or a new sensitive destination. However, advancing playback timestamps during unpaced buffering can introduce delays that also block unrelated audio operations.

Retained concerns

  • Medium · reliability · inferred: The cumulative playback clock advances during unpaced priming, but entering or recovering primed playback does not rebase it. For rapid 256-frame submissions at 48 kHz, the first paced call can consequently sleep until roughly 200 ms after initial submission, rather than one block after the previous submission. This can consume the intended underrun cushion. AudioOut2 holds its shared port mutex throughout that sleep, extending the delay beyond the submitting context to other port operations. This is an inferred recovery and failure-containment regression, not evidence of permanent resource leakage.
Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is within the emulator process and its audio devices. The unchanged 32 output slots constrain port count, but the increased blocking threshold permits more queued guest PCM per SDL-backed port. This threshold is not a complete memory quota, particularly for nonblocking submission.

Trust Boundaries and Controls

  • observed — Public output calls retain handle validation, and open retains type and format checks. Guest PCM continues to reach the same SDL and haptics sinks; the changed ranges add no new privileged destination or handle authority.

Resilience and Maintainability Implications

  • observed — Closing a port closes its device resources and resets the complete port state. Queue underrun clears priming, and a backlog wait exceeding 200 ms clears the SDL queue. These recovery controls remain, but the separate timestamp-based sleep has no corresponding 200 ms deadline or priming-state rebase.

Hardening Proposals

  • proposed — Define a clock rebase policy for initial priming and underrun recovery while retaining cumulative progression during steady playback. Bound recovery pacing so a shared-lock submission cannot impose a long delay on unrelated port operations.
🚥 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
Title check ✅ Passed The title clearly identifies the audio output fix for popping and time-stretching. It matches the main purpose of the changes.
Description check ✅ Passed The description explains the audio timing problem, the last_output_time fix, testing, results, and scope. It is directly related to the changeset.
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.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.

Warning

⚠️ This pull request shows signs of AI-generated slop (description_diff_mismatch). It has been flagged by CodeRabbit slop detection and should be reviewed carefully.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 00:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/966#issuecomment-5943220683) · edited 2026-10-02 00:25 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/966?cs_source=review_comment"><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 Audio output latency and blocking queue capacity increase. Playback and capture setup set the SDL audio device sample-frame hint to `2048`; playback also retrieves and logs the obtained audio specification. Output timestamps are maintained per port and advance by the port’s sample-block duration after the first output. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"e5ceacb005b82733dbadb0f9778e65128cc672eb" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `e5cea` <!-- final_review_risk_coverage:{"sourceCommitId":"e5ceacb005b82733dbadb0f9778e65128cc672eb","coveredCommitId":"e5ceacb005b82733dbadb0f9778e65128cc672eb","kind":"reviewed"} --> The timestamp change can consume the audio buffer’s intended scheduling cushion and reintroduce popping during rapid blocking submissions. Rebase the timestamp at queue-priming transitions before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `e5cea` The change remains within audio handling and does not establish increased privileges or a new sensitive destination. However, advancing playback timestamps during unpaced buffering can introduce delays that also block unrelated audio operations. **Retained concerns** - **Medium · reliability · inferred:** The cumulative playback clock advances during unpaced priming, but entering or recovering primed playback does not rebase it. For rapid 256-frame submissions at 48 kHz, the first paced call can consequently sleep until roughly 200 ms after initial submission, rather than one block after the previous submission. This can consume the intended underrun cushion. AudioOut2 holds its shared port mutex throughout that sleep, extending the delay beyond the submitting context to other port operations. This is an inferred recovery and failure-containment regression, not evidence of permanent resource leakage. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The demonstrated exposure is within the emulator process and its audio devices. The unchanged 32 output slots constrain port count, but the increased blocking threshold permits more queued guest PCM per SDL-backed port. This threshold is not a complete memory quota, particularly for nonblocking submission. **Trust Boundaries and Controls** - _observed_ — Public output calls retain handle validation, and open retains type and format checks. Guest PCM continues to reach the same SDL and haptics sinks; the changed ranges add no new privileged destination or handle authority. **Resilience and Maintainability Implications** - _observed_ — Closing a port closes its device resources and resets the complete port state. Queue underrun clears priming, and a backlog wait exceeding 200 ms clears the SDL queue. These recovery controls remain, but the separate timestamp-based sleep has no corresponding 200 ms deadline or priming-state rebase. **Hardening Proposals** - _proposed_ — Define a clock rebase policy for initial priming and underrun recovery while retaining cumulative progression during steady playback. Bound recovery pacing so a shared-lock submission cannot impose a long delay on unrelated port operations. </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 | | :------------------------: | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly identifies the audio output fix for popping and time-stretching. It matches the main purpose of the changes. | | Description check | ✅ Passed | The description explains the audio timing problem, the `last_output_time` fix, testing, results, and scope. It is directly related to the changeset. | | 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 --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts > Autopilot is currently an internal CodeRabbit preview. <!-- autopilot:end --> > [!WARNING] > ⚠️ This pull request shows signs of AI-generated slop (description_diff_mismatch). It has been flagged by CodeRabbit slop detection and should be reviewed carefully. <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=966)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 00:22 UTC · original
On src/libs/audio.cpp line 593 (outdated):

@@ -578,7 +582,16 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking
 	}
 
 	for (uint32_t i = 0; i < num; i++) {
-		m_out_ports[params[i].handle.GetId()].last_output_time = LibKernel::KernelGetProcessTime();
+		auto& port = m_out_ports[params[i].handle.GetId()];
+
+		const uint64_t block_time =
+			(1000000ULL * port.samples_num) / port.freq;
+
+		if (port.last_output_time == 0) {
+			port.last_output_time = LibKernel::KernelGetProcessTime();
+		} else {
+			port.last_output_time += block_time;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Exclude queue priming from the pacing deadline.

When a caller submits blocking buffers rapidly, QueueSdlAudio() allows unpaced submissions until queue_primed becomes true. This increment advances last_output_time during every priming submission.

With 256 frames at 48 kHz, about 38 rapid submissions advance the timestamp by about 197 ms. The next submission then sleeps toward that future deadline at Lines 397–400. That wait consumes nearly the entire queue cushion and leaves playback exposed to scheduling jitter again. SDL queues submitted input for later consumption. (wiki.libsdl.org)

Rebase the pacing timestamp when the queue becomes primed. Preserve block-duration increments after that transition, and apply the same reset when the queue is cleared or becomes unprimed.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 00:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/966#discussion_r4161774079) On `src/libs/audio.cpp` line 593 (outdated): ```diff @@ -578,7 +582,16 @@ uint32_t Audio::AudioOutOutputs(OutputParam* params, uint32_t num, bool blocking } for (uint32_t i = 0; i < num; i++) { - m_out_ports[params[i].handle.GetId()].last_output_time = LibKernel::KernelGetProcessTime(); + auto& port = m_out_ports[params[i].handle.GetId()]; + + const uint64_t block_time = + (1000000ULL * port.samples_num) / port.freq; + + if (port.last_output_time == 0) { + port.last_output_time = LibKernel::KernelGetProcessTime(); + } else { + port.last_output_time += block_time; ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Exclude queue priming from the pacing deadline.** When a caller submits blocking buffers rapidly, `QueueSdlAudio()` allows unpaced submissions until `queue_primed` becomes true. This increment advances `last_output_time` during every priming submission. With 256 frames at 48 kHz, about 38 rapid submissions advance the timestamp by about 197 ms. The next submission then sleeps toward that future deadline at Lines 397–400. That wait consumes nearly the entire queue cushion and leaves playback exposed to scheduling jitter again. SDL queues submitted input for later consumption. ([wiki.libsdl.org](https://wiki.libsdl.org/SDL3/SDL_GetAudioStreamQueued?utm_source=openai)) Rebase the pacing timestamp when the queue becomes primed. Preserve block-duration increments after that transition, and apply the same reset when the queue is cleared or becomes unprimed. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:eaf2fa08e2a8d02a2abad710 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 00:22 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: c4903d6b-03f2-4472-86d8-2867e9491770

📥 Commits

Reviewing files that changed from the base of the PR and between b3e419ff11 and e5ceacb005b82733dbadb0f9778e65128cc672eb.

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

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 00:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/966#pullrequestreview-5387069266) · **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**: `c4903d6b-03f2-4472-86d8-2867e9491770` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between b3e419ff1101999525fa2d061ada1d102cf788b1 and e5ceacb005b82733dbadb0f9778e65128cc672eb. </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 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.