Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Audio: a portable AudioQueue, the PS5 sound in *_ps5.cpp, null backends

Rafael Abud Ferreira8d2f8d192b28
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 30a5218..b81a51f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -70,7 +70,10 @@ endif()
# --- Media: H.264 / Opus decoding -------------------------------------------
include(cmake/deps/ffmpeg.cmake)
-add_library(xcloud_media STATIC src/media/decoder.cpp src/media/audio_out.cpp src/media/audio_in.cpp src/media/audio_encoder.cpp)
+# The audio queue and the microphone's framing are shared; the sound
+# devices are backends (audio_*_ps5.cpp, audio_*_sdl.cpp, audio_*_null.cpp).
+add_library(xcloud_media STATIC src/media/decoder.cpp src/media/audio_queue.cpp src/media/audio_in_common.cpp
+ src/media/audio_encoder.cpp)
target_link_libraries(xcloud_media PUBLIC xcloud_core PRIVATE xc_ffmpeg)
# --- Menus: software-rendered UI, Game Pass library ---------------------------
@@ -129,6 +132,8 @@ if(XCLOUD_PS5)
src/media/hw_decoder_ps5.cpp
src/input/controller_ps5.cpp
src/input/kbm_ps5.cpp
+ src/media/audio_out_ps5.cpp
+ src/media/audio_in_ps5.cpp
)
target_include_directories(xcloud_app PRIVATE "${PS5_RADV}/include")
# The USB keyboard / mouse backend kept the warnings it had in xcloud_core.
@@ -145,6 +150,8 @@ else()
src/input/controller_null.cpp
src/input/kbm_null.cpp
src/media/hw_decoder_null.cpp
+ src/media/audio_out_null.cpp
+ src/media/audio_in_null.cpp
)
target_link_libraries(xcloud_backends_null PUBLIC xcloud_core)
if(NOT MSVC)
diff --git a/src/media/audio_in_common.cpp b/src/media/audio_in_common.cpp
new file mode 100644
index 0000000..6f2fa30
--- /dev/null
+++ b/src/media/audio_in_common.cpp
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+#include "media/audio_in_common.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace xc::media {
+
+void MicPipeline::process(int16_t* pcm, size_t n, bool muted, float gain, std::atomic<float>& level,
+ const AudioIn::AudioCallback& cb) {
+ float peak = 0.0f;
+ if (muted) {
+ std::fill(pcm, pcm + n, 0);
+ } else {
+ for (size_t i = 0; i < n; ++i) {
+ int16_t& s = pcm[i];
+ if (std::fabs(gain - 1.0f) > 0.01f) {
+ float scaled = static_cast<float>(s) * gain;
+ scaled = std::clamp(scaled, -32768.0f, 32767.0f);
+ s = static_cast<int16_t>(scaled);
+ }
+ float a = std::abs(static_cast<float>(s)) / 32768.0f;
+ if (a > peak) peak = a;
+ }
+ }
+
+ // Perceptual scale: speech in DualSense typically has 500..6000 amplitude
+ float scaledPeak = std::clamp(std::sqrt(peak * 3.5f), 0.0f, 1.0f);
+
+ float prev = level.load(std::memory_order_relaxed);
+ // Smooth natural VU decay (~350ms falloff)
+ float nextLevel = (scaledPeak >= prev) ? scaledPeak : (prev * 0.96f);
+ if (nextLevel < 0.01f) nextLevel = 0.0f;
+ level.store(nextLevel, std::memory_order_relaxed);
+
+ accumulated_.insert(accumulated_.end(), pcm, pcm + n);
+
+ while (accumulated_.size() >= AudioIn::kFrameSize) {
+ if (cb) {
+ cb(accumulated_.data(), AudioIn::kFrameSize);
+ }
+ accumulated_.erase(accumulated_.begin(), accumulated_.begin() + static_cast<long>(AudioIn::kFrameSize));
+ }
+}
+
+} // namespace xc::media
diff --git a/src/media/audio_in_common.h b/src/media/audio_in_common.h
new file mode 100644
index 0000000..412b8a3
--- /dev/null
+++ b/src/media/audio_in_common.h
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// What every microphone backend (audio_in_ps5.cpp, audio_in_sdl.cpp) does
+// with the samples it reads: the gain, muting, the level meter and the
+// 20 ms frames the Opus encoder takes.
+#pragma once
+
+#include "media/audio_in.h"
+
+#include <atomic>
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+namespace xc::media {
+
+class MicPipeline {
+public:
+ MicPipeline() { accumulated_.reserve(AudioIn::kFrameSize + kGrain); }
+ // The grain the PS5 reads (5.3 ms); the desktop hands its samples over
+ // in the same steps, so the meter falls back as fast.
+ static constexpr size_t kGrain = 256;
+
+ // One grain of `n` mono S16 samples, changed in place (the gain, or
+ // silence while muted): `level` (the meter, 0..1) follows its peak and
+ // each full 20 ms frame goes to `cb`.
+ void process(int16_t* pcm, size_t n, bool muted, float gain, std::atomic<float>& level,
+ const AudioIn::AudioCallback& cb);
+ void reset() { accumulated_.clear(); }
+
+private:
+ std::vector<int16_t> accumulated_;
+};
+
+} // namespace xc::media
diff --git a/src/media/audio_in_null.cpp b/src/media/audio_in_null.cpp
new file mode 100644
index 0000000..bdd3250
--- /dev/null
+++ b/src/media/audio_in_null.cpp
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// No microphone (xcloud-tests, psbox-headless): "recording" with nothing
+// coming, so the stream's voice chat path still opens and closes.
+#include "media/audio_in.h"
+#include "util/log.h"
+
+namespace xc::media {
+
+struct AudioIn::Impl {};
+
+AudioIn::AudioIn() : impl_(std::make_unique<Impl>()) {}
+
+AudioIn::~AudioIn() {
+ close();
+}
+
+bool AudioIn::open(AudioCallback cb) {
+ if (running_) return true;
+ callback_ = std::move(cb);
+ running_ = true;
+ XC_LOGI("audio in: host audio input stub started");
+ return true;
+}
+
+void AudioIn::close() {
+ if (!running_) return;
+ running_ = false;
+ level_.store(0.0f, std::memory_order_relaxed);
+ hardwareMuted_.store(false, std::memory_order_relaxed);
+ callback_ = nullptr;
+ XC_LOGI("audio in: closed");
+}
+
+} // namespace xc::media
diff --git a/src/media/audio_in.cpp b/src/media/audio_in_ps5.cpp
similarity index 68%
rename from src/media/audio_in.cpp
rename to src/media/audio_in_ps5.cpp
index 1ac4416..69a2272 100644
--- a/src/media/audio_in.cpp
+++ b/src/media/audio_in_ps5.cpp
@@ -1,16 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
+// The microphone on the PS5 (audio_in.h): libSceAudioIn read by a thread of
+// its own in 256-sample grains; gain, mute, the meter and the 20 ms frames
+// are audio_in_common.h's. audio_in_sdl.cpp and audio_in_null.cpp stand in
+// elsewhere.
#include "media/audio_in.h"
#include "input/controller.h"
+#include "media/audio_in_common.h"
#include "util/log.h"
-#include <algorithm>
-#include <cmath>
-#include <cstring>
#include <thread>
#include <vector>
-#if defined(XCLOUD_PS5)
extern "C" {
struct SceUserServiceInitializeParams {
uint32_t priority;
@@ -24,15 +25,13 @@ int sceAudioInClose(int handle);
int sceAudioInGetSilentState(int handle);
int sceAudioInSetGain(int handle, int gain);
}
-#endif
namespace xc::media {
struct AudioIn::Impl {
std::thread thread;
-#if defined(XCLOUD_PS5)
int handle = -1;
-#endif
+ MicPipeline mic;
};
AudioIn::AudioIn() : impl_(std::make_unique<Impl>()) {}
@@ -45,7 +44,6 @@ bool AudioIn::open(AudioCallback cb) {
if (running_) return true;
callback_ = std::move(cb);
-#if defined(XCLOUD_PS5)
static bool initialised = false;
if (!initialised) {
int rc = sceAudioInInit();
@@ -69,7 +67,7 @@ bool AudioIn::open(AudioCallback cb) {
}
XC_LOGI("audio in: opening port for user 0x%08x (%d)...", static_cast<unsigned>(userId), userId);
- constexpr unsigned kGrain = 256;
+ constexpr unsigned kGrain = MicPipeline::kGrain;
// type 0 = VoiceChat (or type 1 = General); param 0 = S16 mono
impl_->handle = sceAudioInOpen(userId, 0, 0, kGrain, kSampleRate, 0);
if (impl_->handle < 0) {
@@ -86,12 +84,10 @@ bool AudioIn::open(AudioCallback cb) {
return false;
}
running_ = true;
+ impl_->mic.reset();
impl_->thread = std::thread([this]() {
- constexpr unsigned kGrain = 256;
std::vector<int16_t> grain(kGrain);
- std::vector<int16_t> accumulated;
- accumulated.reserve(kFrameSize + kGrain);
unsigned lastStatus = 0xFFFFFFFF;
uint64_t loopCount = 0;
@@ -117,50 +113,12 @@ bool AudioIn::open(AudioCallback cb) {
}
bool isMuted = muted_.load(std::memory_order_relaxed) || hardwareMuted_.load(std::memory_order_relaxed);
- float currentGain = gain_.load(std::memory_order_relaxed);
-
- float peak = 0.0f;
- if (isMuted) {
- std::fill(grain.begin(), grain.end(), 0);
- } else {
- for (auto& s : grain) {
- if (std::fabs(currentGain - 1.0f) > 0.01f) {
- float scaled = static_cast<float>(s) * currentGain;
- scaled = std::clamp(scaled, -32768.0f, 32767.0f);
- s = static_cast<int16_t>(scaled);
- }
- float a = std::abs(static_cast<float>(s)) / 32768.0f;
- if (a > peak) peak = a;
- }
- }
-
- // Perceptual scale: speech in DualSense typically has 500..6000 amplitude
- float scaledPeak = std::clamp(std::sqrt(peak * 3.5f), 0.0f, 1.0f);
-
- float prev = level_.load(std::memory_order_relaxed);
- // Smooth natural VU decay (~350ms falloff)
- float nextLevel = (scaledPeak >= prev) ? scaledPeak : (prev * 0.96f);
- if (nextLevel < 0.01f) nextLevel = 0.0f;
- level_.store(nextLevel, std::memory_order_relaxed);
-
- accumulated.insert(accumulated.end(), grain.begin(), grain.end());
-
- while (accumulated.size() >= kFrameSize) {
- if (callback_) {
- callback_(accumulated.data(), kFrameSize);
- }
- accumulated.erase(accumulated.begin(), accumulated.begin() + static_cast<long>(kFrameSize));
- }
+ impl_->mic.process(grain.data(), grain.size(), isMuted, gain_.load(std::memory_order_relaxed), level_, callback_);
}
});
XC_LOGI("audio in: PS5 audio input opened (handle %d, 48 kHz mono S16)", impl_->handle);
return true;
-#else
- running_ = true;
- XC_LOGI("audio in: host audio input stub started");
- return true;
-#endif
}
void AudioIn::close() {
@@ -173,12 +131,10 @@ void AudioIn::close() {
impl_->thread.join();
}
-#if defined(XCLOUD_PS5)
if (impl_->handle >= 0) {
sceAudioInClose(impl_->handle);
impl_->handle = -1;
}
-#endif
callback_ = nullptr;
XC_LOGI("audio in: closed");
}
diff --git a/src/media/audio_out.cpp b/src/media/audio_out.cpp
deleted file mode 100644
index 865dae3..0000000
--- a/src/media/audio_out.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-// SPDX-License-Identifier: GPL-3.0-or-later
-// Copyright (C) 2026 RafaelNGP
-#include "media/audio_out.h"
-
-#include "util/log.h"
-
-#include <atomic>
-#include <cstring>
-#include <algorithm>
-#include <deque>
-#include <mutex>
-#include <thread>
-#include <vector>
-
-#if defined(XCLOUD_PS5)
-extern "C" {
-int sceAudioOutInit(void);
-int sceAudioOutOpen(int userId, int type, int index, unsigned len, unsigned freq, unsigned param);
-int sceAudioOutOutput(int handle, const void* ptr);
-int sceAudioOutClose(int handle);
-}
-#endif
-
-namespace xc::media {
-
-namespace {
-
-constexpr int kRate = 48000;
-constexpr unsigned kGrain = 256;
-// The queue's bound: past 60 ms (a burst from the network) it is cut back to
-// 40 ms, the oldest samples first. It used to hold up to 120 ms: that much
-// delay behind the picture (Moonlight keeps 40-50 ms).
-constexpr size_t kMaxQueued = kRate * 60 / 1000;
-constexpr size_t kTrimTo = kRate * 40 / 1000;
-
-std::mutex g_mutex;
-std::deque<float> g_queue; // interleaved stereo
-std::atomic<bool> g_running{false};
-std::atomic<float> g_volume{1.0f};
-// Measured for the log every ~10 s (under g_mutex): the queue's depth at each
-// grain, the grains that found it empty, what was cut.
-uint64_t g_depthSum = 0, g_depthMax = 0, g_grains = 0, g_underruns = 0, g_trimmed = 0;
-std::thread g_thread;
-
-#if defined(XCLOUD_PS5)
-int g_handle = -1;
-std::atomic<AudioRoute> g_route{AudioRoute::Main};
-
-void loop() {
- std::vector<float> grain(kGrain * 2);
- while (g_running) {
- {
- std::lock_guard<std::mutex> lock(g_mutex);
- size_t depth = g_queue.size() / 2;
- g_depthSum += depth;
- g_depthMax = std::max<uint64_t>(g_depthMax, depth);
- if (depth == 0) ++g_underruns;
- if (++g_grains == 1875) { // 256-frame grains: ~10 s
- XC_LOGI("audio out: queue %.1f ms on average (max %.1f), %llu empty grains, %.0f ms cut",
- g_depthSum * 1000.0 / kRate / g_grains, g_depthMax * 1000.0 / kRate,
- static_cast<unsigned long long>(g_underruns), g_trimmed * 1000.0 / kRate);
- g_depthSum = g_depthMax = g_grains = g_underruns = g_trimmed = 0;
- }
- size_t n = std::min(grain.size(), g_queue.size());
- std::copy(g_queue.begin(), g_queue.begin() + static_cast<long>(n), grain.begin());
- g_queue.erase(g_queue.begin(), g_queue.begin() + static_cast<long>(n));
- std::fill(grain.begin() + static_cast<long>(n), grain.end(), 0.0f);
- }
- if (float v = g_volume.load(); v != 1.0f)
- for (float& s : grain) s = std::clamp(s * v, -1.0f, 1.0f);
- int h = g_handle;
- if (h < 0) {
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- continue;
- }
- // Blocks until the hardware wants the next grain (5.3 ms).
- int rc = sceAudioOutOutput(h, grain.data());
- if (rc < 0) {
- static uint64_t failures = 0; // this thread only
- if (failures++ % 200 == 0) // the first, then one a second or so
- XC_LOGW("sceAudioOutOutput: 0x%08x (failure %llu)", static_cast<unsigned>(rc),
- static_cast<unsigned long long>(failures));
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- if (!g_running) break;
- }
- }
-}
-#else
-std::atomic<AudioRoute> g_route{AudioRoute::Main};
-#endif
-
-} // namespace
-
-bool audioStart() {
- if (g_running) return true;
-#if defined(XCLOUD_PS5)
- // Once per process: a second sceAudioOutInit answers "already
- // initialised" (0x8026000E on this firmware, 0x8026000C elsewhere).
- static bool initialised = false;
- if (!initialised) {
- int rc = sceAudioOutInit();
- if (rc < 0 && rc != static_cast<int>(0x8026000C) && rc != static_cast<int>(0x8026000E)) {
- XC_LOGE("sceAudioOutInit: 0x%08x", static_cast<unsigned>(rc));
- return false;
- }
- initialised = true;
- }
- // Port 0 (MAIN): primary system output. PS5 OS automatically routes
- // to HDMI/TV or connected headphones (DualSense 3.5mm / USB / Bluetooth).
- g_handle = sceAudioOutOpen(0xFF, 0, 0, kGrain, kRate, 4);
- if (g_handle < 0) {
- XC_LOGE("sceAudioOutOpen: 0x%08x", static_cast<unsigned>(g_handle));
- return false;
- }
- g_running = true;
- g_thread = std::thread(loop);
- XC_LOGI("audio output open (48 kHz float stereo, handle %d)", g_handle);
-#else
- g_running = true;
-#endif
- return true;
-}
-
-void audioSetVolume(float gain) { g_volume = std::clamp(gain, 0.0f, 2.0f); }
-
-void audioSetRoute(AudioRoute route) {
- g_route.store(route);
-}
-
-AudioRoute audioRoute() {
- return g_route.load();
-}
-
-void audioStop() {
- if (!g_running) return;
- g_running = false;
- if (g_thread.joinable()) g_thread.join();
-#if defined(XCLOUD_PS5)
- if (g_handle >= 0) {
- sceAudioOutClose(g_handle);
- g_handle = -1;
- }
-#endif
- std::lock_guard<std::mutex> lock(g_mutex);
- g_queue.clear();
-}
-
-void audioPush(const float* interleaved, size_t frames) {
- if (!g_running) return;
- std::lock_guard<std::mutex> lock(g_mutex);
- g_queue.insert(g_queue.end(), interleaved, interleaved + frames * 2);
- if (g_queue.size() > kMaxQueued * 2) {
- size_t cut = g_queue.size() - kTrimTo * 2;
- g_trimmed += cut / 2;
- g_queue.erase(g_queue.begin(), g_queue.begin() + static_cast<long>(cut));
- }
-}
-
-} // namespace xc::media
diff --git a/src/media/audio_out_null.cpp b/src/media/audio_out_null.cpp
new file mode 100644
index 0000000..95b2514
--- /dev/null
+++ b/src/media/audio_out_null.cpp
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// No sound device (xcloud-tests, psbox-headless): the sound pushed is queued
+// as on the PS5 (the queue keeps itself to ~60 ms) and never played.
+#include "media/audio_out.h"
+
+#include "media/audio_queue.h"
+
+#include <atomic>
+
+namespace xc::media {
+
+namespace {
+std::atomic<bool> g_running{false};
+} // namespace
+
+bool audioStart() {
+ if (g_running) return true;
+ g_running = true;
+ audioQueue().open();
+ return true;
+}
+
+void audioStop() {
+ if (!g_running) return;
+ g_running = false;
+ audioQueue().close();
+ audioQueue().clear();
+}
+
+} // namespace xc::media
diff --git a/src/media/audio_out_ps5.cpp b/src/media/audio_out_ps5.cpp
new file mode 100644
index 0000000..6e08f88
--- /dev/null
+++ b/src/media/audio_out_ps5.cpp
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// Sound out on the PS5 (audio_out.h): libSceAudioOut's main port, fed by a
+// thread of its own in 256-frame grains from the shared queue
+// (audio_queue.h). audio_out_sdl.cpp and audio_out_null.cpp stand in
+// elsewhere.
+#include "media/audio_out.h"
+
+#include "media/audio_queue.h"
+#include "util/log.h"
+
+#include <atomic>
+#include <chrono>
+#include <thread>
+#include <vector>
+
+extern "C" {
+int sceAudioOutInit(void);
+int sceAudioOutOpen(int userId, int type, int index, unsigned len, unsigned freq, unsigned param);
+int sceAudioOutOutput(int handle, const void* ptr);
+int sceAudioOutClose(int handle);
+}
+
+namespace xc::media {
+
+namespace {
+
+constexpr int kRate = AudioQueue::kRate;
+constexpr unsigned kGrain = 256;
+
+std::atomic<bool> g_running{false};
+std::thread g_thread;
+int g_handle = -1;
+
+void loop() {
+ std::vector<float> grain(kGrain * 2);
+ AudioQueue& queue = audioQueue();
+ while (g_running) {
+ queue.pull(grain.data(), kGrain); // silence past what is queued
+ int h = g_handle;
+ if (h < 0) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ continue;
+ }
+ // Blocks until the hardware wants the next grain (5.3 ms).
+ int rc = sceAudioOutOutput(h, grain.data());
+ if (rc < 0) {
+ static uint64_t failures = 0; // this thread only
+ if (failures++ % 200 == 0) // the first, then one a second or so
+ XC_LOGW("sceAudioOutOutput: 0x%08x (failure %llu)", static_cast<unsigned>(rc),
+ static_cast<unsigned long long>(failures));
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ if (!g_running) break;
+ }
+ }
+}
+
+} // namespace
+
+bool audioStart() {
+ if (g_running) return true;
+ // Once per process: a second sceAudioOutInit answers "already
+ // initialised" (0x8026000E on this firmware, 0x8026000C elsewhere).
+ static bool initialised = false;
+ if (!initialised) {
+ int rc = sceAudioOutInit();
+ if (rc < 0 && rc != static_cast<int>(0x8026000C) && rc != static_cast<int>(0x8026000E)) {
+ XC_LOGE("sceAudioOutInit: 0x%08x", static_cast<unsigned>(rc));
+ return false;
+ }
+ initialised = true;
+ }
+ // Port 0 (MAIN): primary system output. PS5 OS automatically routes
+ // to HDMI/TV or connected headphones (DualSense 3.5mm / USB / Bluetooth).
+ g_handle = sceAudioOutOpen(0xFF, 0, 0, kGrain, kRate, 4);
+ if (g_handle < 0) {
+ XC_LOGE("sceAudioOutOpen: 0x%08x", static_cast<unsigned>(g_handle));
+ return false;
+ }
+ g_running = true;
+ audioQueue().open();
+ g_thread = std::thread(loop);
+ XC_LOGI("audio output open (48 kHz float stereo, handle %d)", g_handle);
+ return true;
+}
+
+void audioStop() {
+ if (!g_running) return;
+ g_running = false;
+ audioQueue().close();
+ if (g_thread.joinable()) g_thread.join();
+ if (g_handle >= 0) {
+ sceAudioOutClose(g_handle);
+ g_handle = -1;
+ }
+ audioQueue().clear();
+}
+
+} // namespace xc::media
diff --git a/src/media/audio_queue.cpp b/src/media/audio_queue.cpp
new file mode 100644
index 0000000..7586141
--- /dev/null
+++ b/src/media/audio_queue.cpp
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The audio queue (audio_queue.h) and the parts of audio_out.h every
+// backend shares: pushing, the volume, the route.
+#include "media/audio_queue.h"
+
+#include "media/audio_out.h"
+#include "util/log.h"
+
+#include <algorithm>
+
+namespace xc::media {
+
+void AudioQueue::push(const float* interleaved, size_t frames) {
+ if (!open_) return;
+ std::lock_guard<std::mutex> lock(mutex_);
+ queue_.insert(queue_.end(), interleaved, interleaved + frames * 2);
+ if (queue_.size() > kMaxQueued * 2) {
+ size_t cut = queue_.size() - kTrimTo * 2;
+ stats_.trimmed += cut / 2;
+ queue_.erase(queue_.begin(), queue_.begin() + static_cast<long>(cut));
+ }
+}
+
+void AudioQueue::pull(float* out, size_t frames) {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ size_t depth = queue_.size() / 2;
+ stats_.depthSum += depth;
+ stats_.depthMax = std::max<uint64_t>(stats_.depthMax, depth);
+ if (depth == 0) ++stats_.empty;
+ ++stats_.pulls;
+ stats_.frames += frames;
+ if (stats_.frames >= static_cast<uint64_t>(kRate) * 10) { // ~10 s (the PS5's 1875 grains of 256)
+ XC_LOGI("audio out: queue %.1f ms on average (max %.1f), %llu empty grains, %.0f ms cut",
+ stats_.depthSum * 1000.0 / kRate / stats_.pulls, stats_.depthMax * 1000.0 / kRate,
+ static_cast<unsigned long long>(stats_.empty), stats_.trimmed * 1000.0 / kRate);
+ stats_ = {};
+ }
+ size_t n = std::min(frames * 2, queue_.size());
+ std::copy(queue_.begin(), queue_.begin() + static_cast<long>(n), out);
+ queue_.erase(queue_.begin(), queue_.begin() + static_cast<long>(n));
+ std::fill(out + n, out + frames * 2, 0.0f);
+ }
+ if (float v = volume_.load(); v != 1.0f)
+ for (size_t i = 0; i < frames * 2; ++i) out[i] = std::clamp(out[i] * v, -1.0f, 1.0f);
+}
+
+void AudioQueue::clear() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ queue_.clear();
+}
+
+void AudioQueue::setVolume(float gain) { volume_ = std::clamp(gain, 0.0f, 2.0f); }
+
+size_t AudioQueue::queuedFrames() const {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return queue_.size() / 2;
+}
+
+AudioQueue::Stats AudioQueue::stats() const {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return stats_;
+}
+
+AudioQueue& audioQueue() {
+ static AudioQueue queue;
+ return queue;
+}
+
+namespace {
+// Kept for the backends that can pick an output (none yet: the PS5's
+// main port follows the system's own routing, the desktop plays on the
+// default device).
+std::atomic<AudioRoute> g_route{AudioRoute::Main};
+} // namespace
+
+void audioSetVolume(float gain) { audioQueue().setVolume(gain); }
+void audioSetRoute(AudioRoute route) { g_route.store(route); }
+AudioRoute audioRoute() { return g_route.load(); }
+void audioPush(const float* interleaved, size_t frames) { audioQueue().push(interleaved, frames); }
+
+} // namespace xc::media
diff --git a/src/media/audio_queue.h b/src/media/audio_queue.h
new file mode 100644
index 0000000..60204cc
--- /dev/null
+++ b/src/media/audio_queue.h
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The game's sound on its way to the speakers, shared by every audio-out
+// backend (audio_out_ps5.cpp, audio_out_sdl.cpp, audio_out_null.cpp):
+// pushed as it is decoded, pulled by the device a grain at a time, silence
+// when it runs dry. Past ~60 ms queued (a burst from the network) it is cut
+// back to ~40 ms, the oldest samples first, to keep the sound close to the
+// picture. Its depth, the pulls that found it empty and what was cut are
+// logged every ~10 s of sound.
+#pragma once
+
+#include <atomic>
+#include <cstddef>
+#include <cstdint>
+#include <deque>
+#include <mutex>
+
+namespace xc::media {
+
+class AudioQueue {
+public:
+ static constexpr int kRate = 48000;
+ // It used to hold up to 120 ms: that much delay behind the picture
+ // (Moonlight keeps 40-50 ms). Stereo frames.
+ static constexpr size_t kMaxQueued = kRate * 60 / 1000;
+ static constexpr size_t kTrimTo = kRate * 40 / 1000;
+
+ // Since the last log (reset by it).
+ struct Stats {
+ uint64_t pulls = 0, empty = 0; // pulls, those that found it empty
+ uint64_t frames = 0; // pulled
+ uint64_t depthSum = 0, depthMax = 0, trimmed = 0; // frames: queued at each pull, cut
+ };
+
+ // Interleaved stereo frames; ignored while closed.
+ void push(const float* interleaved, size_t frames);
+ // `frames` stereo frames into `out`: what is queued, silence past it, at
+ // the volume (clipped at full scale).
+ void pull(float* out, size_t frames);
+ // A backend opens it as its device starts; closing stops the pushes
+ // (clear() then empties it, once the device is done).
+ void open() { open_ = true; }
+ void close() { open_ = false; }
+ bool isOpen() const { return open_; }
+ void clear();
+ // 1 as it comes, up to 2 (louder).
+ void setVolume(float gain);
+ float volume() const { return volume_; }
+ size_t queuedFrames() const;
+ Stats stats() const;
+
+private:
+ mutable std::mutex mutex_;
+ std::deque<float> queue_; // interleaved stereo
+ std::atomic<bool> open_{false};
+ std::atomic<float> volume_{1.0f};
+ Stats stats_; // under mutex_
+};
+
+// The one audio_out.h's audioPush() fills; the backend pulls from it and
+// opens / closes it with its device.
+AudioQueue& audioQueue();
+
+} // namespace xc::media
diff --git a/tools/check-platform-boundaries.sh b/tools/check-platform-boundaries.sh
index d99907d..24b4db8 100755
--- a/tools/check-platform-boundaries.sh
+++ b/tools/check-platform-boundaries.sh
@@ -26,8 +26,6 @@ allowed=(
'ps5/*' # link stubs and compat headers for the PS5 SDK
# Legacy: these still pick their PS5 code with #if. Each comes off the
# list once it is split into a PS5 backend and a portable part.
- 'src/media/audio_out.cpp' # TODO(M1): portable AudioQueue + audio_out_ps5.cpp / an SDL backend
- 'src/media/audio_in.cpp' # TODO(M1): audio_in_ps5.cpp / an SDL backend
'src/app/crash_guard.cpp' # TODO(M2): crash_guard_ps5.cpp / POSIX / Windows (SEH)
)