Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

perf(mic): 10 ms Opus packets, mic timing in the log (#187)

Rafael Abud Ferreira4ca507e6e9dc
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index 92036f3..5dda9fc 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -135,6 +135,27 @@ struct StreamPlayer::Impl {
std::atomic<bool> micMuted{false};
std::atomic<float> micGain{1.0f};
std::atomic<uint32_t> audioSendTimestamp{0};
+ // The microphone's packets, every 10 s (issue #187, a mic heard late):
+ // how many went out, the longest encode + send, and how far the RTP
+ // clock (48 kHz, from the samples sent) is from the real one since the
+ // first packet: a receiver's jitter buffer grows with that gap.
+ struct MicStats {
+ uint64_t firstUs = 0, windowUs = 0, maxWorkUs = 0;
+ uint32_t firstTs = 0, packets = 0, skips = 0;
+ void skipped() { ++skips; }
+ void sent(uint64_t startUs, uint64_t endUs, uint32_t tsAfter, uint32_t frame) {
+ if (!firstUs) firstUs = windowUs = startUs, firstTs = tsAfter - frame;
+ ++packets;
+ maxWorkUs = std::max(maxWorkUs, endUs - startUs);
+ if (endUs - windowUs < 10000000) return;
+ const double realMs = static_cast<double>(endUs - firstUs) / 1000.0;
+ const double rtpMs = static_cast<double>(tsAfter - firstTs) / 48.0;
+ XC_LOGI("mic: %u packets in %.1f s (%u without one), encode + send up to %.2f ms, RTP clock %+.0f ms from real time",
+ packets, static_cast<double>(endUs - windowUs) / 1e6, skips, static_cast<double>(maxWorkUs) / 1000.0,
+ rtpMs - realMs);
+ windowUs = endUs, packets = skips = 0, maxWorkUs = 0;
+ }
+ } micStats;
bool encoderInitialized = false;
platform::Thread inputThread;
platform::Thread snapshotThread;
@@ -184,22 +205,29 @@ struct StreamPlayer::Impl {
}
if (!audioIn.isRecording()) {
if (!encoderInitialized) {
- encoderInitialized = audioEncoder.init(24000);
+ // 10 ms packets: the voice waits half as long to go out (20 ms
+ // before 2026-11-04).
+ encoderInitialized = audioEncoder.init(24000, 10);
if (!encoderInitialized) {
XC_LOGW("audio encoder: Opus init failed, mic input & meter will still operate");
}
}
audioIn.setMuted(micMuted.load());
audioIn.setGain(micGain.load());
+ audioIn.setFrameSize(audioEncoder.frameSamples());
audioIn.open([this](const int16_t* pcmFrames, size_t samples) {
if (!running) return;
if (!encoderInitialized) return;
auto s = current();
if (!s || !s->isOpen()) return;
+ const uint64_t t0 = platform::nowUs();
std::vector<uint8_t> opus;
if (audioEncoder.encode(pcmFrames, samples, opus)) {
uint32_t ts = audioSendTimestamp.fetch_add(static_cast<uint32_t>(samples));
s->sendAudio(opus.data(), opus.size(), ts);
+ micStats.sent(t0, platform::nowUs(), ts + static_cast<uint32_t>(samples), static_cast<uint32_t>(samples));
+ } else {
+ micStats.skipped();
}
});
input::setEmbeddedMicActive(true);
diff --git a/src/media/audio_encoder.cpp b/src/media/audio_encoder.cpp
index bfe14d7..33354db 100644
--- a/src/media/audio_encoder.cpp
+++ b/src/media/audio_encoder.cpp
@@ -35,7 +35,9 @@ AudioEncoder::~AudioEncoder() {
if (packet_) av_packet_free(&packet_);
}
-bool AudioEncoder::init(int bitrate) {
+bool AudioEncoder::init(int bitrate, int frameMs) {
+ frameMs = frameMs == 10 ? 10 : 20;
+ frameSamples_ = static_cast<size_t>(kSampleRate / 1000 * frameMs);
const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_OPUS);
if (!codec) {
XC_LOGE("audio encoder: Opus encoder not found in FFmpeg build");
@@ -53,7 +55,8 @@ bool AudioEncoder::init(int bitrate) {
ctx_->flags |= AV_CODEC_FLAG_LOW_DELAY;
ctx_->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
- av_opt_set_double(ctx_->priv_data, "opus_delay", 20.0, 0);
+ // The lookahead it may buffer: also the longest packet it makes.
+ av_opt_set_double(ctx_->priv_data, "opus_delay", static_cast<double>(frameMs), 0);
int rc = avcodec_open2(ctx_, codec, nullptr);
if (rc < 0) {
@@ -79,20 +82,20 @@ bool AudioEncoder::init(int bitrate) {
packet_ = av_packet_alloc();
if (!packet_) return false;
- XC_LOGI("audio encoder: Opus encoder initialized (%d Hz, %d ch, %d bps, 20ms frames)",
- kSampleRate, kChannels, bitrate);
+ XC_LOGI("audio encoder: Opus encoder initialized (%d Hz, %d ch, %d bps, %d ms frames)",
+ kSampleRate, kChannels, bitrate, frameMs);
return true;
}
bool AudioEncoder::encode(const int16_t* pcm, size_t samples, std::vector<uint8_t>& out) {
- if (!ctx_ || !frame_ || !packet_ || !pcm || samples < kFrameSize) return false;
+ if (!ctx_ || !frame_ || !packet_ || !pcm || samples < frameSamples_) return false;
constexpr int kSubframeSize = 120;
constexpr float kInv32768 = 1.0f / 32768.0f;
bool gotPacket = false;
// Feed 8 subframes of 120 samples (8 * 120 = 960 samples = 20 ms)
- for (size_t offset = 0; offset < kFrameSize; offset += kSubframeSize) {
+ for (size_t offset = 0; offset < frameSamples_; offset += kSubframeSize) {
int rc = av_frame_make_writable(frame_);
if (rc < 0) return false;
diff --git a/src/media/audio_encoder.h b/src/media/audio_encoder.h
index 3b09cb6..34c5c2b 100644
--- a/src/media/audio_encoder.h
+++ b/src/media/audio_encoder.h
@@ -24,18 +24,21 @@ public:
AudioEncoder(const AudioEncoder&) = delete;
AudioEncoder& operator=(const AudioEncoder&) = delete;
- // Initializes native Opus encoder (default 24 kbps VoIP)
- bool init(int bitrate = 24000);
+ // Initializes native Opus encoder (default 24 kbps VoIP), in packets of
+ // `frameMs` (10 or 20): its delay is about one packet more than that.
+ bool init(int bitrate = 24000, int frameMs = 20);
- // Encodes one 20 ms frame (960 mono S16 samples).
+ // Encodes one frame (frameSamples() mono S16 samples).
// Fills `out` with the encoded Opus packet bytes.
bool encode(const int16_t* pcm, size_t samples, std::vector<uint8_t>& out);
+ size_t frameSamples() const { return frameSamples_; }
private:
AVCodecContext* ctx_ = nullptr;
AVFrame* frame_ = nullptr;
AVPacket* packet_ = nullptr;
int64_t pts_ = 0;
+ size_t frameSamples_ = kFrameSize;
};
} // namespace xc::media
diff --git a/src/media/audio_in.h b/src/media/audio_in.h
index fc38121..16872df 100644
--- a/src/media/audio_in.h
+++ b/src/media/audio_in.h
@@ -15,7 +15,11 @@ class AudioIn {
public:
static constexpr int kSampleRate = 48000;
static constexpr int kChannels = 1;
- static constexpr size_t kFrameSize = 960; // 20 ms @ 48 kHz
+ static constexpr size_t kFrameSize = 960; // 20 ms @ 48 kHz (the default)
+ // The frames handed to the callback, in samples (before open()): 480 for
+ // 10 ms packets, a shorter wait before each one goes out.
+ void setFrameSize(size_t samples) { frameSize_ = samples; }
+ size_t frameSize() const { return frameSize_; }
using AudioCallback = std::function<void(const int16_t* pcm, size_t frames)>;
@@ -44,6 +48,7 @@ private:
std::atomic<bool> hardwareMuted_{false};
std::atomic<float> gain_{1.0f};
std::atomic<float> level_{0.0f};
+ std::atomic<size_t> frameSize_{kFrameSize};
AudioCallback callback_;
};
diff --git a/src/media/audio_in_common.cpp b/src/media/audio_in_common.cpp
index 6f2fa30..10bcdcc 100644
--- a/src/media/audio_in_common.cpp
+++ b/src/media/audio_in_common.cpp
@@ -36,11 +36,11 @@ void MicPipeline::process(int16_t* pcm, size_t n, bool muted, float gain, std::a
accumulated_.insert(accumulated_.end(), pcm, pcm + n);
- while (accumulated_.size() >= AudioIn::kFrameSize) {
+ while (accumulated_.size() >= frameSize_) {
if (cb) {
- cb(accumulated_.data(), AudioIn::kFrameSize);
+ cb(accumulated_.data(), frameSize_);
}
- accumulated_.erase(accumulated_.begin(), accumulated_.begin() + static_cast<long>(AudioIn::kFrameSize));
+ accumulated_.erase(accumulated_.begin(), accumulated_.begin() + static_cast<long>(frameSize_));
}
}
diff --git a/src/media/audio_in_common.h b/src/media/audio_in_common.h
index 412b8a3..35f3450 100644
--- a/src/media/audio_in_common.h
+++ b/src/media/audio_in_common.h
@@ -27,9 +27,14 @@ public:
void process(int16_t* pcm, size_t n, bool muted, float gain, std::atomic<float>& level,
const AudioIn::AudioCallback& cb);
void reset() { accumulated_.clear(); }
+ void setFrameSize(size_t samples) {
+ frameSize_ = samples;
+ accumulated_.clear();
+ }
private:
std::vector<int16_t> accumulated_;
+ size_t frameSize_ = AudioIn::kFrameSize;
};
} // namespace xc::media
diff --git a/src/media/audio_in_ps4.cpp b/src/media/audio_in_ps4.cpp
index 472ded8..d3ac12b 100644
--- a/src/media/audio_in_ps4.cpp
+++ b/src/media/audio_in_ps4.cpp
@@ -100,7 +100,7 @@ bool AudioIn::open(AudioCallback cb) {
return false;
}
running_ = true;
- impl_->mic.reset();
+ impl_->mic.setFrameSize(frameSize_);
platform::startThread(impl_->thread, [this, openedRate]() {
platform::setThreadAffinity(platform::ThreadRole::Audio, "ps4_audio_in");
diff --git a/src/media/audio_in_ps5.cpp b/src/media/audio_in_ps5.cpp
index 89bc5d5..d745d40 100644
--- a/src/media/audio_in_ps5.cpp
+++ b/src/media/audio_in_ps5.cpp
@@ -85,13 +85,17 @@ bool AudioIn::open(AudioCallback cb) {
return false;
}
running_ = true;
- impl_->mic.reset();
+ impl_->mic.setFrameSize(frameSize_);
impl_->thread = std::thread([this]() {
platform::setThreadAffinity(platform::ThreadRole::Audio, "ps5_audio_in");
std::vector<int16_t> grain(kGrain);
unsigned lastStatus = 0xFFFFFFFF;
uint64_t loopCount = 0;
+ // The capture's pace, every 10 s (issue #187, a mic heard late): the
+ // rate the port really delivers, its longest wait and how many
+ // grains came at once (a backlog being read).
+ uint64_t windowStartUs = 0, lastReturnUs = 0, maxGapUs = 0, windowGrains = 0, bunched = 0;
while (running_) {
int rc = sceAudioInInput(impl_->handle, grain.data());
@@ -102,6 +106,22 @@ bool AudioIn::open(AudioCallback cb) {
if (++loopCount == 1) {
XC_LOGI("audio in: first input buffer received (%u samples)", kGrain);
}
+ const uint64_t nowUs = platform::nowUs();
+ if (!windowStartUs) windowStartUs = nowUs;
+ if (lastReturnUs) {
+ const uint64_t gap = nowUs - lastReturnUs;
+ if (gap > maxGapUs) maxGapUs = gap;
+ if (gap < 1000) ++bunched;
+ }
+ lastReturnUs = nowUs;
+ ++windowGrains;
+ if (nowUs - windowStartUs >= 10000000) {
+ const double secs = static_cast<double>(nowUs - windowStartUs) / 1e6;
+ XC_LOGI("audio in: %.0f samples/s over %.1f s, longest wait %.1f ms, %llu of %llu grains at once",
+ static_cast<double>(windowGrains * kGrain) / secs, secs, static_cast<double>(maxGapUs) / 1000.0,
+ static_cast<unsigned long long>(bunched), static_cast<unsigned long long>(windowGrains));
+ windowStartUs = nowUs, maxGapUs = 0, windowGrains = 0, bunched = 0;
+ }
int silentState = sceAudioInGetSilentState(impl_->handle);
if (silentState != static_cast<int>(lastStatus)) {
diff --git a/src/media/audio_in_sdl.cpp b/src/media/audio_in_sdl.cpp
index f69f9e9..29effa6 100644
--- a/src/media/audio_in_sdl.cpp
+++ b/src/media/audio_in_sdl.cpp
@@ -39,7 +39,7 @@ bool AudioIn::open(AudioCallback cb) {
}
impl_->initedAudio = true;
}
- impl_->mic.reset();
+ impl_->mic.setFrameSize(frameSize_);
impl_->grains = 0;
// SDL's device thread, as samples come in: whole grains through the
// pipeline, the rest left in the stream for next time.
diff --git a/src/stream/rtcp_reporter.cpp b/src/stream/rtcp_reporter.cpp
index 484b546..8b34bdb 100644
--- a/src/stream/rtcp_reporter.cpp
+++ b/src/stream/rtcp_reporter.cpp
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
#include "stream/rtcp_reporter.h"
+#include "util/log.h"
#include <algorithm>
#include <chrono>
@@ -88,6 +89,19 @@ void RtcpReporter::onRtcp(const uint8_t* d, size_t n, uint64_t now) {
lastSr_ = (get32(d + off + 8) << 16) | (get32(d + off + 12) >> 16);
lastSrArrivalUs_ = now;
}
+ // The server's report on what we send it (the microphone), every
+ // 10 s in the log (issue #187): its loss and jitter as it sees them.
+ if ((pt == 200 || pt == 201) && clockRate_ == 48000 && now - lastSendReportLogUs_ >= 10000000) {
+ const size_t blocks = d[off] & 0x1F, first = pt == 200 ? 28 : 8;
+ for (size_t b = 0; b < blocks && first + (b + 1) * 24 <= len; ++b) {
+ const uint8_t* r = d + off + first + b * 24;
+ if (get32(r) != kMicSsrc) continue;
+ const uint32_t cumulative = get32(r + 4) & 0xFFFFFF;
+ XC_LOGI("mic, as the server gets it: %.1f%% lost lately, %u in all, jitter %.1f ms",
+ r[4] * 100.0 / 256.0, cumulative, get32(r + 12) / 48.0);
+ lastSendReportLogUs_ = now;
+ }
+ }
off += len;
}
}
diff --git a/src/stream/rtcp_reporter.h b/src/stream/rtcp_reporter.h
index e780f2b..8454115 100644
--- a/src/stream/rtcp_reporter.h
+++ b/src/stream/rtcp_reporter.h
@@ -19,6 +19,8 @@ namespace xc::stream {
// SSRC of our RTCP packets (receiver reports, NACK, PLI, REMB).
constexpr uint32_t kReceiverSsrc = 0x50534278; // "PSBx"
+// SSRC of the microphone's RTP stream (stream_session.cpp's audio packetizer).
+constexpr uint32_t kMicSsrc = 1;
class RtcpReporter final : public rtc::MediaHandler {
public:
@@ -50,6 +52,7 @@ private:
uint32_t lastSr_ = 0; // middle 32 bits of the last SR's NTP time
uint64_t lastSrArrivalUs_ = 0;
uint64_t lastReportUs_ = 0;
+ uint64_t lastSendReportLogUs_ = 0; // the server's report on the microphone, last logged
uint64_t bytesSinceReport_ = 0;
std::atomic<uint32_t> estimate_{0}, receiveRate_{0};
};
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index a584ce1..ff45980 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -512,14 +512,14 @@ struct StreamSession::Impl {
// Audio: sendrecv like the browser (the send side carries chat).
rtc::Description::Audio a("0", rtc::Description::Direction::SendRecv);
a.addOpusCodec(111, "minptime=10;useinbandfec=1;stereo=1");
- a.addSSRC(1, "audio");
+ a.addSSRC(kMicSsrc, "audio");
audio = pc->addTrack(a);
auto audioDepacketizer = std::make_shared<rtc::OpusRtpDepacketizer>();
audioDepacketizer->addToChain(std::make_shared<RtcpReporter>(48000, 0));
auto rtpConfig = std::make_shared<rtc::RtpPacketizationConfig>(
- 1, "audio", 111, rtc::OpusRtpPacketizer::DefaultClockRate);
+ kMicSsrc, "audio", 111, rtc::OpusRtpPacketizer::DefaultClockRate);
auto audioPacketizer = std::make_shared<rtc::OpusRtpPacketizer>(rtpConfig);
audioDepacketizer->addToChain(audioPacketizer);