Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

perf(stream): fewer skipped frames, shorter audio delay, PS4 stutter fixes (#317)

Rafael Abud Ferreiraf844019b1142
diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cpp
index 239132d..f4f9426 100644
--- a/src/app/autoplay.cpp
+++ b/src/app/autoplay.cpp
@@ -27,6 +27,7 @@ namespace xc::app {
Autoplay g_autoplay;
std::atomic<bool> g_syntheticA{false};
+std::atomic<float> g_syntheticRightX{0.0f}, g_syntheticLeftY{0.0f};
namespace {
// The home screen was saved: the tests that start from it may go.
@@ -102,6 +103,12 @@ void loadAutoplay() {
if (opt == "dump") g_autoplay.dump = true;
if (opt == "repeat") g_autoplay.runs = 2;
if (opt == "idle") g_autoplay.idle = true;
+ if (opt == "hz60") g_autoplay.hz60 = true;
+ if (opt == "fnplay") g_autoplay.fnPlay = true;
+ if (opt == "legacy") g_autoplay.legacy = true;
+ if (opt == "imgtest") g_autoplay.imgTest = true;
+ // Threads pinned by role (platform.h), to measure it again.
+ if (opt == "pin") platform::setNoThreadPinning(false);
if (opt == "rumbletest") input::setRumble(200, 200, 1500);
if (opt == "triggertest") input::setTriggerRumble(255, 128, 3000);
if (opt == "queuetest" || opt == "padspktest") g_autoplay.padSpkTest = true;
diff --git a/src/app/autoplay.h b/src/app/autoplay.h
index fe3a3b4..ea61a81 100644
--- a/src/app/autoplay.h
+++ b/src/app/autoplay.h
@@ -60,6 +60,10 @@ struct Autoplay {
bool v150Test = false; // "v150test": verify new settings order and search gratis filter
bool claimTest = false; // "claimtest": test free game acquisition, library persistence, and game launch
bool vkTest = false; // the GPU presenting instead of the CPU display
+ bool hz60 = false; // hz60: streams stay at 60 Hz output (no 120 Hz switch)
+ bool fnPlay = false; // fnplay: Fortnite gameplay for measurements (Play once, then the camera turns and the player runs)
+ bool legacy = false; // legacy: the stream as it was tuned before 2026-11-04 (the A/B baseline)
+ bool imgTest = false; // imgtest: 25 s before the end, one picture drawn with each look (img_*.ppm)
bool cpuDisplay = false; // the CPU display even where the GPU comes up
int upscaler = -1; // ai: Anime4K instead of the setting
bool restore = false; // restore: Anime4K Restore before the upscale
@@ -108,6 +112,7 @@ struct Autoplay {
};
extern Autoplay g_autoplay;
extern std::atomic<bool> g_syntheticA; // A held down for the game
+extern std::atomic<float> g_syntheticRightX, g_syntheticLeftY; // sticks for the game (fnplay)
void loadAutoplay();
// After loadAutoplay(), before the settings are read. Starting in autoplay
diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cpp
index a4d252c..43831de 100644
--- a/src/app/cli_main.cpp
+++ b/src/app/cli_main.cpp
@@ -174,7 +174,7 @@ int cmdStream(auth::AuthManager& am, const std::string& titleId, int seconds, co
std::atomic<uint64_t> videoFrames{0}, videoBytes{0}, audioPackets{0}, keyFrames{0};
std::atomic<bool> closed{false};
stream::StreamCallbacks cb;
- cb.video = [&](const uint8_t* d, size_t n, uint32_t) {
+ cb.video = [&](const uint8_t* d, size_t n, uint32_t, uint64_t) {
++videoFrames;
videoBytes += n;
// An IDR slice (NAL type 5) after a 4-byte start code anywhere in the AU.
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index 5dda9fc..8de5dde 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -76,6 +76,7 @@ struct StreamPlayer::Impl {
uint32_t rtpTimestamp = 0;
double arrivalMs = 0; // StreamSession::clockMs()
uint64_t arrivalUs = 0; // platform::nowUs(), for the display latency
+ uint64_t firstPacketUs = 0; // its first packet came (before the retransmission wait), 0 unknown
};
std::deque<VideoFrame> frames;
std::atomic<bool> running{false};
@@ -98,6 +99,7 @@ struct StreamPlayer::Impl {
std::atomic<uint64_t> vibrations{0}, lateFrames{0};
std::atomic<uint64_t> triggerVibrations{0};
std::atomic<uint64_t> displayUs{0}, displayCount{0}, displayMaxUs{0};
+ std::atomic<uint64_t> glassUs{0}, glassCount{0}, glassMaxUs{0}; // first packet to the screen
std::atomic<uint64_t> decodeUs{0}, decodeCalls{0}, decodeMaxUs{0}, drawUs{0}, drawCalls{0}, drawMaxUs{0};
std::atomic<uint64_t> qpSumX100{0}, qpCount{0}; // pictures' quantiser since the last stats()
int decodeThreads = 1;
@@ -131,6 +133,8 @@ struct StreamPlayer::Impl {
media::AudioIn audioIn;
media::AudioEncoder audioEncoder;
+ std::atomic<bool> highRefreshOutput{false}; // setHighRefreshOutput()
+ std::atomic<bool> legacy{false}; // setLegacyTuning()
std::atomic<bool> micEnabled{true};
std::atomic<bool> micMuted{false};
std::atomic<float> micGain{1.0f};
@@ -205,9 +209,9 @@ struct StreamPlayer::Impl {
}
if (!audioIn.isRecording()) {
if (!encoderInitialized) {
- // 10 ms packets: the voice waits half as long to go out (20 ms
- // before 2026-11-04).
- encoderInitialized = audioEncoder.init(24000, 10);
+ // 10 ms packets: the voice waits half as long to go out
+ // (20 ms before 2026-11-04, the legacy A/B baseline).
+ encoderInitialized = audioEncoder.init(24000, legacy ? 20 : 10);
if (!encoderInitialized) {
XC_LOGW("audio encoder: Opus init failed, mic input & meter will still operate");
}
@@ -297,10 +301,65 @@ struct StreamPlayer::Impl {
}
}
+ // The sound's delay: what waits in the audio queue. Once a second, if
+ // even its lowest point over the last 5 s stayed above the target, up to
+ // 20 ms is cut out (crossfaded); a pull that found it dry raises the
+ // target 10 ms (up to 100), a minute without one lowers it 5 (down to
+ // 40). A network burst would otherwise leave the sound that much later
+ // for good (it sat at ~100 ms).
+ struct AudioLatency {
+ uint64_t nextMs = 0, calmSinceMs = 0;
+ int targetMs = 40;
+ bool warm = false; // past the first 3 s, while the queue fills
+ size_t lows[5] = {SIZE_MAX, SIZE_MAX, SIZE_MAX, SIZE_MAX, SIZE_MAX}; // each second's lowest
+ size_t lowNext = 0;
+ void reset() {
+ nextMs = 0, targetMs = 40, warm = false, lowNext = 0;
+ for (size_t& l : lows) l = SIZE_MAX;
+ media::audioQueue().setRefill(0);
+ }
+ void update(uint64_t now) {
+ auto& q = media::audioQueue();
+ if (!nextMs) nextMs = now + 3000;
+ q.setRefill(static_cast<size_t>(targetMs) * 48); // what a dry queue fills back to
+ if (now < nextMs) return;
+ nextMs = now + 1000;
+ if (!warm) {
+ warm = true, calmSinceMs = now;
+ q.takeUnderruns(), q.takeLowWater(); // the start's own
+ return;
+ }
+ const uint64_t dry = q.takeUnderruns();
+ lows[lowNext++ % 5] = q.takeLowWater();
+ if (dry) {
+ if (targetMs < 100) {
+ targetMs = std::min(targetMs + 10, 100);
+ XC_LOGI("audio: ran dry (%llu grains), target %d ms", static_cast<unsigned long long>(dry), targetMs);
+ }
+ calmSinceMs = now;
+ return;
+ }
+ if (now - calmSinceMs >= 60000 && targetMs > 40) {
+ targetMs -= 5, calmSinceMs = now;
+ XC_LOGI("audio: steady for a minute, target %d ms", targetMs);
+ }
+ if (lowNext < 5) return; // 5 s seen first
+ size_t low = SIZE_MAX;
+ for (size_t l : lows) low = std::min(low, l);
+ const size_t target = static_cast<size_t>(targetMs) * 48;
+ if (low != SIZE_MAX && low > target + 480) {
+ const size_t cut = std::min<size_t>(low - target, 960);
+ if (q.cutAhead(cut))
+ for (size_t& l : lows) l = l == SIZE_MAX ? l : l - std::min(l, cut); // the queue is that much shorter
+ }
+ }
+ } audioLatency;
+
void audioLoop() {
platform::setThreadAffinity(platform::ThreadRole::Audio, "xcloud_adec");
platform::setThreadRealtimePriority();
audioDecoder.resetPlc();
+ audioLatency.reset();
QueuedAudioPacket packet;
bool first = true;
uint32_t lastRtpTimestamp = 0;
@@ -375,16 +434,15 @@ struct StreamPlayer::Impl {
XC_LOGI("first audio packet decoded: %zu samples", pcm.size() / 2);
}
if (decoded) {
- // When audio buffer builds up beyond healthy headroom (>= 100 ms) due to network bursts,
- // decode stale packets in Opus to preserve continuous LPC/CELT filter history,
- // but skip pushing into AudioQueue until queue drains to healthy target (~60 ms).
- // This keeps audio latency at ~40-60 ms, perfectly in sync with 22-25 ms video,
- // and completely eliminates 240-700 ms bufferbloat cuts.
- size_t queued = media::audioQueue().queuedFrames();
- if (queued >= kOpusFrameSamples * 5) {
- continue;
+ if (legacy) {
+ // Before 2026-11-04 (A/B baseline): a packet dropped whole
+ // past 100 ms queued, which left the queue at ~100 ms.
+ if (media::audioQueue().queuedFrames() >= kOpusFrameSamples * 5) continue;
+ media::audioPush(pcm.data(), pcm.size() / 2);
+ } else {
+ media::audioPush(pcm.data(), pcm.size() / 2);
+ audioLatency.update(platform::nowMs());
}
- media::audioPush(pcm.data(), pcm.size() / 2);
}
}
}
@@ -533,14 +591,50 @@ struct StreamPlayer::Impl {
if (hwProbe && !decoder.isHardware()) XC_LOGI("hwdec: probe %s", hwOk ? "running" : "failed to start");
uint64_t hwUs = 0, hwMaxUs = 0, hwPictures = 0, hwCalls = 0, hwLogAt = platform::nowMs() + 1000;
constexpr uint64_t kShownRing = 8;
- std::pair<uint64_t, uint64_t> inScreenQueue[kShownRing] = {}; // present id, arrival us
- uint64_t lastShownId = 0;
+ struct OnItsWay {
+ uint64_t id = 0, arrivalUs = 0, firstPacketUs = 0;
+ };
+ OnItsWay inScreenQueue[kShownRing] = {}; // presented, not yet known on the screen
+ uint64_t lastShownId = 0, lastPresentedId = 0;
uint64_t lastFramePresentUs = 0;
const uint64_t maxLagUs = uint64_t{display::caps().maxVideoLagMs} * 1000;
bool lagAwaitingIdr = false;
+ // Display latency: from the frame's arrival (and from its first
+ // packet) to the TV, once the GPU says it is on the screen.
+ auto noteShown = [&] {
+ uint64_t shownId = 0, shownAt = 0;
+ if (!display::lastShown(shownId, shownAt) || shownId == lastShownId) return;
+ lastShownId = shownId;
+ const auto& q = inScreenQueue[shownId % kShownRing];
+ if (q.id != shownId) return;
+ if (shownAt > q.arrivalUs) {
+ uint64_t lat = shownAt - q.arrivalUs;
+ displayUs += lat;
+ ++displayCount;
+ atomicMax(displayMaxUs, lat);
+ }
+ if (q.firstPacketUs && shownAt > q.firstPacketUs) {
+ uint64_t lat = shownAt - q.firstPacketUs;
+ glassUs += lat;
+ ++glassCount;
+ atomicMax(glassMaxUs, lat);
+ }
+ };
while (running) {
{
std::unique_lock<std::mutex> lock(mutex);
+ // While a frame is on its way to the screen, look every 2 ms
+ // (the GPU is asked without waiting) so its time is known
+ // within 2 ms instead of at the next frame.
+ while (running && frames.empty() && lastPresentedId > lastShownId) {
+ if (cv.wait_for(lock, std::chrono::milliseconds(2)) == std::cv_status::no_timeout) continue;
+ lock.unlock();
+ {
+ std::lock_guard<std::recursive_mutex> displayLock(display::frameMutex());
+ noteShown();
+ }
+ lock.lock();
+ }
cv.wait(lock, [&] { return !running || !frames.empty(); });
if (!running) break;
frame = std::move(frames.front());
@@ -658,16 +752,22 @@ struct StreamPlayer::Impl {
presentCv.notify_one();
continue;
}
- // When a burst of frames arrives after network wait/jitter, fast-forward decode
- // stale frames in FFmpeg without waiting for vblank present, keeping reference
- // picture state intact while draining backlog in ~3.4ms per frame.
- // Present only once caught up to the live edge (backlog <= 1).
+ // Behind the live edge (frames that came at once after a pause in
+ // delivery or a retransmission): the frame is decoded, keeping the
+ // references, but not shown. At 120 Hz a couple of frames are shown
+ // instead (a refresh or two drains them); a longer backlog, or a
+ // frame already over 35 ms old with others waiting, is skipped. At
+ // 60 Hz a second frame waiting is skipped: showing it would hold
+ // the next ones back a refresh.
size_t pendingFrames = 0;
{
std::lock_guard<std::mutex> lock(mutex);
pendingFrames = frames.size();
}
- if (pendingFrames > 1) {
+ const bool behind = highRefreshOutput && !legacy
+ ? pendingFrames > 2 || (pendingFrames > 0 && platform::nowUs() - frame.arrivalUs > 35000)
+ : pendingFrames > 1;
+ if (behind) {
++droppedFrames;
continue;
}
@@ -706,21 +806,10 @@ struct StreamPlayer::Impl {
}
}
lastFramePresentUs = t3;
- // Display latency: network arrival to the TV, once the GPU says
- // the frame is on the screen (a frame or so later).
if (uint64_t id = display::lastPresentId()) {
- inScreenQueue[id % kShownRing] = {id, frame.arrivalUs};
- uint64_t shownId = 0, shownAt = 0;
- if (display::lastShown(shownId, shownAt) && shownId != lastShownId) {
- lastShownId = shownId;
- const auto& q = inScreenQueue[shownId % kShownRing];
- if (q.first == shownId && shownAt > q.second) {
- uint64_t lat = shownAt - q.second;
- displayUs += lat;
- ++displayCount;
- atomicMax(displayMaxUs, lat);
- }
- }
+ inScreenQueue[id % kShownRing] = {id, frame.arrivalUs, frame.firstPacketUs};
+ lastPresentedId = id;
+ noteShown();
}
meta.renderedMs = stream::clockMs();
if (auto s = current(); s && known) s->reportFrame(meta);
@@ -733,6 +822,7 @@ struct StreamPlayer::Impl {
++drawCalls;
atomicMax(drawMaxUs, t3 - t2);
if (decodedFrames == 1) XC_LOGI("first frame presented");
+ if (imageTestWanted.exchange(false)) imageTest(pic, drawPic);
}
}
@@ -741,7 +831,7 @@ struct StreamPlayer::Impl {
if (!media::audioStart()) XC_LOGW("no audio output: playing without sound");
stream::StreamCallbacks cb;
- cb.video = [this](const uint8_t* d, size_t n, uint32_t rtpTimestamp) {
+ cb.video = [this](const uint8_t* d, size_t n, uint32_t rtpTimestamp, uint64_t firstPacketUs) {
if (n == 0) { // the depacketizer emits these after loss
keyframeWanted = true;
return;
@@ -770,7 +860,8 @@ struct StreamPlayer::Impl {
frames.clear();
keyframeWanted = true;
}
- frames.push_back({std::vector<uint8_t>(d, d + n), rtpTimestamp, stream::clockMs(), platform::nowUs()});
+ frames.push_back(
+ {std::vector<uint8_t>(d, d + n), rtpTimestamp, stream::clockMs(), platform::nowUs(), firstPacketUs});
cv.notify_one();
};
cb.audio = [this](const uint8_t* d, size_t n, uint32_t rtpTimestamp) {
@@ -855,6 +946,7 @@ struct StreamPlayer::Impl {
opts.maxBitrate = std::min(opts.maxBitrate, deviceCap);
if (opts.resolutionAlias == "1080HQ") opts.resolutionAlias = "1080";
}
+ if (legacy) opts.keyframeIntervalSec = 5;
opts.simulatedVideoLoss = simulatedLoss;
if (const char* loss = std::getenv("XC_SIM_LOSS")) opts.simulatedVideoLoss = std::atoi(loss);
callbacks = cb;
@@ -975,6 +1067,45 @@ struct StreamPlayer::Impl {
}
// The scan-out buffer just presented, at full resolution.
+ // Measurements (autoplay "imgtest"): this picture drawn again with each
+ // look (upscaler, sharpening), a 1280x720 crop of the 4K output
+ // saved for each (img_<name>.ppm). The stream is left with the defaults.
+ std::atomic<bool> imageTestWanted{false};
+ template <class Draw>
+ void imageTest(const media::Picture& pic, const Draw& drawPic) {
+ struct Look {
+ const char* name;
+ int upscaler, sharpness; // stream_screen.cpp's applyUpscaler mode, kSharpAmount
+ };
+ static constexpr Look kLooks[] = {
+ {"1_clean_med", 2, 176}, {"2_fsr_med", 0, 176}, {"3_clean_high", 2, 256}, {"4_clean_low", 2, 96},
+ {"5_clean_off", 2, 0}, {"6_fsr_off", 0, 0}, {"7_a4k_med", 1, 176}, {"8_a4k_clean_med", 3, 176},
+ {"9_default", 2, 176},
+ };
+ for (const Look& look : kLooks) {
+ display::setUpscaler(look.upscaler & 1);
+ display::setRestore(look.upscaler >= 2);
+ display::setSharpness(look.sharpness);
+ std::vector<uint8_t> rgb;
+ int w = 0, h = 0;
+ {
+ std::lock_guard<std::recursive_mutex> lock(display::frameMutex());
+ if (!drawPic(pic, true)) continue;
+ display::present();
+ if (!display::readBackRgb(rgb, w, h)) continue;
+ }
+ if (std::string(look.name) == "9_default") break;
+ const int cw = std::min(1280, w), ch = std::min(720, h), x0 = std::min(1100, w - cw), y0 = std::min(300, h - ch);
+ std::string data = "P6\n" + std::to_string(cw) + " " + std::to_string(ch) + "\n255\n";
+ for (int y = 0; y < ch; ++y)
+ data.append(reinterpret_cast<const char*>(rgb.data() + (static_cast<size_t>(y0 + y) * w + x0) * 3),
+ static_cast<size_t>(cw) * 3);
+ const std::string path = platform::dataDir() + "/img_" + look.name + ".ppm";
+ XC_LOGI("image test: %s (%dx%d of %dx%d) %s", look.name, cw, ch, w, h,
+ platform::writeFileAtomic(path, data) ? "saved" : "not saved");
+ }
+ }
+
void saveScreen() {
try {
std::vector<uint8_t> rgb;
@@ -1182,6 +1313,8 @@ void StreamPlayer::dumpVideo(const std::string& path, int seconds) {
XC_LOGI("dumping video to %s: %s", path.c_str(), impl_->dumpFile ? "ok" : "failed");
}
+void StreamPlayer::requestImageTest() { impl_->imageTestWanted = true; }
+
void StreamPlayer::requestSnapshot(const std::string& path) {
std::lock_guard<std::mutex> lock(impl_->snapshotMutex);
impl_->snapshotPath = path;
@@ -1222,6 +1355,9 @@ StreamPlayer::Stats StreamPlayer::stats() const {
uint64_t dn = impl_->displayCount.exchange(0), du2 = impl_->displayUs.exchange(0);
st.displayAvgUs = dn ? du2 / dn : 0;
st.displayMaxUs = impl_->displayMaxUs.exchange(0);
+ uint64_t gn = impl_->glassCount.exchange(0), gu = impl_->glassUs.exchange(0);
+ st.glassAvgUs = gn ? gu / gn : 0;
+ st.glassMaxUs = impl_->glassMaxUs.exchange(0);
if (auto s = impl_->current()) {
const auto& v = s->videoStats();
st.rtpPackets = v.packets;
@@ -1229,6 +1365,7 @@ StreamPlayer::Stats StreamPlayer::stats() const {
st.rtpRecovered = v.recovered;
st.rtpNacks = v.nacks;
st.rtpDroppedFrames = v.framesDropped;
+ st.rtpGapMs = v.maxGapMs.exchange(0), st.rtpBurst = v.maxBurst.exchange(0), st.rtpLateMs = v.maxLateMs.exchange(0);
st.keyframeRequests += v.keyframeRequests;
st.rtpKbps = v.receiveRate / 1000;
st.rttMs = s->rttMs();
@@ -1241,6 +1378,17 @@ StreamPlayer::Stats StreamPlayer::stats() const {
return st;
}
+void StreamPlayer::setLegacyTuning(bool on) {
+ impl_->legacy = on;
+ if (on) XC_LOGI("stream: legacy tuning (measurement baseline)");
+}
+
+void StreamPlayer::setHighRefreshOutput(bool on) {
+ impl_->highRefreshOutput = on;
+ XC_LOGI("video: %s output, frames that come at once %s", on ? "120 Hz" : "60 Hz",
+ on ? "shown up to 2 behind" : "skipped from the second one waiting");
+}
+
void StreamPlayer::setMicEnabled(bool enabled) {
impl_->micEnabled = enabled;
impl_->updateMicState();
diff --git a/src/app/stream_player.h b/src/app/stream_player.h
index 933c14e..dab8928 100644
--- a/src/app/stream_player.h
+++ b/src/app/stream_player.h
@@ -59,7 +59,15 @@ public:
void dumpVideo(const std::string& path, int seconds);
// Writes the next decoded picture, half size, as a binary PPM.
void requestSnapshot(const std::string& path);
+ // Measurements: the next picture drawn with each look, crops saved (autoplay "imgtest").
+ void requestImageTest();
// Voice chat / microphone controls
+ // Measurements only (autoplay "legacy"): the stream as it was tuned
+ // before 2026-11-04, to compare against. Before start().
+ void setLegacyTuning(bool on);
+ // The screen shows this stream at 119.88 Hz: a couple of frames that
+ // came at once are shown instead of skipped (a refresh drains them).
+ void setHighRefreshOutput(bool on);
void setMicEnabled(bool enabled);
bool micEnabled() const;
void setMicMuted(bool muted);
@@ -74,6 +82,7 @@ public:
uint64_t decodeFailures = 0, queueResets = 0, keyframeRequests = 0, queued = 0;
// RTP: packets lost, recovered by NACK, frames the jitter buffer dropped.
uint64_t rtpPackets = 0, rtpLost = 0, rtpRecovered = 0, rtpNacks = 0, rtpDroppedFrames = 0;
+ uint64_t rtpGapMs = 0, rtpBurst = 0, rtpLateMs = 0; // VideoReceiveStats::maxGapMs..., this interval
uint64_t rtpKbps = 0, rembKbps = 0, vibrations = 0;
uint64_t lateFrames = 0; // decoded, not drawn: both flips still queued
int rttMs = -1; // to the stream server
@@ -82,6 +91,7 @@ public:
uint64_t decodeAvgUs = 0, decodeMaxUs = 0, drawAvgUs = 0, drawMaxUs = 0;
// Network arrival to on the screen (GPU path), since the last call.
uint64_t displayAvgUs = 0, displayMaxUs = 0;
+ uint64_t glassAvgUs = 0, glassMaxUs = 0; // from the frame's first packet to the screen
// The pictures' average quantiser since the last call (lower: finer); -1 none.
double qpAvg = -1;
bool isHwDecode = false;
diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cpp
index e22827b..09f148b 100644
--- a/src/app/stream_screen.cpp
+++ b/src/app/stream_screen.cpp
@@ -303,12 +303,13 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
if (g_ui) g_ui->setCircleConfirms(prof.circleConfirms);
// 120 Hz (VRR) for this game's stream: active when enabled in profile,
// or defaulted on when the display supports switching refresh (menus stay at 60 Hz).
- bool want120 = prof.highRefresh || (!hasCustom && display::canSwitchRefresh());
+ bool want120 = (prof.highRefresh || (!hasCustom && display::canSwitchRefresh())) && !g_autoplay.hz60;
highRefresh_ = want120 && display::setHighRefresh(true);
media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));
media::audioSetVoiceRouting(g_settings.voiceRouting);
if (g_player) {
+ g_player->setHighRefreshOutput(highRefresh_);
g_player->setMicGain(g_settings.micGainFactor());
}
@@ -628,6 +629,8 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
}
input::ControllerState sent = input::applyPadMap(padIn, padMap_);
if (g_syntheticA) sent.btnA = true;
+ if (float x = g_syntheticRightX; x != 0.0f) sent.rightStickX = x;
+ if (float y = g_syntheticLeftY; y != 0.0f) sent.leftStickY = y;
// While another window has the focus on the cloud console (a
// publisher's page such as NetEase's terms in Marvel Rivals,
// which then shows its own pad-driven cursor), touch input is
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index 9391a33..aaec27e 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -118,6 +118,7 @@ std::string endedToast(const std::string& result) {
if (result.find("KickForStopCommand") != std::string::npos) return ui::tr(ui::Str::EndedOnXbox);
if (result.find("KickByNewSession") != std::string::npos) return ui::tr(ui::Str::EndedByOtherDevice);
if (result.find("KickForServerShutdown") != std::string::npos) return ui::tr(ui::Str::EndedXboxOff);
+ if (result.find("KickForBeingIdle") != std::string::npos) return ui::tr(ui::Str::EndedIdle);
return {};
}
diff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cpp
index c4cbafe..ee540e3 100644
--- a/src/app/worker_stream.cpp
+++ b/src/app/worker_stream.cpp
@@ -16,7 +16,9 @@
#include "xcloud/regions.h"
#include <algorithm>
+#include <atomic>
#include <cmath>
+#include <cstdio>
#include <cstdlib>
#include <vector>
@@ -107,6 +109,7 @@ std::string stream(xcloud::GssvClient& gssv) {
XC_LOGI("stream: video decoder %s", preferHw ? "hardware preferred" : "software (CPU)");
player.setMicGain(g_settings.micGainFactor());
player.setMicEnabled(g_settings.micEnabled);
+ player.setLegacyTuning(g_autoplay.legacy);
int cap = g_autoplay.bitrateMbps > 0 ? g_autoplay.bitrateMbps : g_settings.maxBitrateMbps;
player.setMaxBitrate(cap);
media::audioSetVolume(g_settings.gameVolume / 100.0f);
@@ -171,7 +174,37 @@ std::string stream(xcloud::GssvClient& gssv) {
XC_LOGI("resolution probe (%s): %dp at most", gssv.isHome() ? "own Xbox" : "cloud", tallest);
};
app::StreamPlayer::Stats last{};
+ uint64_t nextSnapCheck = 0;
+ // A watch on this loop (issue #317: a PS4 stream froze for good with no
+ // line logged, the "no video" check never firing): past 5 s without a
+ // pass, which step it is stuck in goes into the log, once a stall.
+ struct LoopWatch {
+ std::atomic<const char*> step{"start"};
+ std::atomic<uint64_t> beatMs{platform::nowMs()};
+ std::atomic<bool> stop{false};
+ platform::Thread thread;
+ void run() {
+ bool told = false;
+ while (!stop) {
+ for (int i = 0; i < 10 && !stop; ++i) platform::sleepMs(100);
+ const uint64_t idle = platform::nowMs() - beatMs.load();
+ if (idle > 5000 && !told) {
+ XC_LOGW("stream loop: stuck for %llu ms in \"%s\"", static_cast<unsigned long long>(idle), step.load());
+ told = true;
+ } else if (idle <= 5000 && told) {
+ XC_LOGW("stream loop: going again after \"%s\"", step.load());
+ told = false;
+ }
+ }
+ }
+ } watch;
+ platform::startThread(watch.thread, [&watch] { watch.run(); }, 64u << 10);
+ auto beat = [&watch](const char* step) {
+ watch.step = step;
+ watch.beatMs = platform::nowMs();
+ };
while (player.running() && !g_cancel) {
+ beat("loop");
uint64_t elapsed = platform::nowMs() - started;
if (!g_autoplay.title.empty()) {
if (elapsed >= static_cast<uint64_t>(g_autoplay.seconds) * 1000u) {
@@ -186,6 +219,19 @@ std::string stream(xcloud::GssvClient& gssv) {
((elapsed >= 22000 && elapsed < 22300) ||
(elapsed >= 26000 && elapsed < 26300) ||
(elapsed >= 70000 && (elapsed % 6000 < 300)));
+ if (g_autoplay.fnPlay) {
+ // Fortnite: nothing pressed for 150 s (the match is reached by
+ // hand, through the web gamepad, as Fortnite's lobby and its
+ // pop-ups change from one session to the next); then the
+ // camera keeps turning and the player runs for 4 s of every 10
+ // and jumps: motion like a game's, the same each run.
+ press = false;
+ const bool moving = elapsed >= 150000;
+ const float t = static_cast<float>(elapsed % 8000) / 8000.0f;
+ g_syntheticRightX = moving ? 0.7f * std::sin(t * 6.2831853f) : 0.0f;
+ g_syntheticLeftY = moving && elapsed % 10000 < 4000 ? -1.0f : 0.0f;
+ if (moving && elapsed % 10000 >= 4000 && elapsed % 10000 < 4200) press = true;
+ }
if (press != g_syntheticA.exchange(press)) XC_LOGI("autoplay: A %s", press ? "down" : "up");
static bool dropped = false;
if (g_autoplay.dropTest && !dropped && elapsed >= 20000) {
@@ -204,6 +250,21 @@ std::string stream(xcloud::GssvClient& gssv) {
snapshot4 = true;
player.requestSnapshot(platform::dataDir() + "/frame4.ppm");
}
+ static bool imageTested = false;
+ if (g_autoplay.imgTest && !imageTested && elapsed + 25000 >= static_cast<uint64_t>(g_autoplay.seconds) * 1000u) {
+ imageTested = true;
+ player.requestImageTest();
+ }
+ // A capture asked for from outside (the file snap.req appears): now.ppm.
+ if (elapsed >= nextSnapCheck) {
+ nextSnapCheck = elapsed + 500;
+ const std::string req = platform::dataDir() + "/snap.req";
+ std::string unused;
+ if (platform::readFile(req, unused)) {
+ std::remove(req.c_str());
+ player.requestSnapshot(platform::dataDir() + "/now.ppm");
+ }
+ }
if (elapsed >= nextPeriodicShot) {
nextPeriodicShot = elapsed + 30000;
player.requestSnapshot(platform::dataDir() + "/frame" + std::to_string(periodicShotIdx++) + ".ppm");
@@ -213,12 +274,16 @@ std::string stream(xcloud::GssvClient& gssv) {
uint64_t tickNow = platform::nowMs();
double dt = lastTickAt ? (tickNow - lastTickAt) / 1000.0 : 1.0;
nextTick = tickNow + 1000;
+ beat("player.tick (reconnects, keyframe requests)");
player.tick();
+ beat("player.stats (counters, round trip)");
auto st = player.stats();
+ beat("the stats line");
XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, "
"%llu queued, %llu audio; rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, "
"%llu frames dropped; %llu kbps (remb %llu); %llu rumble; decode %.1f/%.1f ms (%s), draw %.1f/%.1f ms, %llu late; "
- "rtt %d ms; %dx%d; on screen %.1f/%.1f ms after arrival; qp %.1f",
+ "rtt %d ms; %dx%d; on screen %.1f/%.1f ms after arrival; qp %.1f; packets %llu ms apart at most, "
+ "%llu frames at once, a frame %llu ms late; first packet to screen %.1f/%.1f ms",
static_cast<unsigned long long>(st.videoFrames), static_cast<unsigned long long>(st.decodedFrames),
static_cast<unsigned long long>(st.droppedFrames), static_cast<unsigned long long>(st.decodeFailures),
static_cast<unsigned long long>(st.queueResets), static_cast<unsigned long long>(st.keyframeRequests),
@@ -230,7 +295,9 @@ std::string stream(xcloud::GssvClient& gssv) {
st.decodeAvgUs / 1000.0, st.decodeMaxUs / 1000.0, st.isHwDecode ? "HW" : "SW",
st.drawAvgUs / 1000.0, st.drawMaxUs / 1000.0,
static_cast<unsigned long long>(st.lateFrames), st.rttMs, st.width, st.height,
- st.displayAvgUs / 1000.0, st.displayMaxUs / 1000.0, st.qpAvg);
+ st.displayAvgUs / 1000.0, st.displayMaxUs / 1000.0, st.qpAvg,
+ static_cast<unsigned long long>(st.rtpGapMs), static_cast<unsigned long long>(st.rtpBurst),
+ static_cast<unsigned long long>(st.rtpLateMs), st.glassAvgUs / 1000.0, st.glassMaxUs / 1000.0);
if (st.rttMs > 0 && (bestRtt < 0 || st.rttMs < bestRtt)) bestRtt = st.rttMs;
tallest = std::max(tallest, st.height);
if (!probeDone && platform::nowMs() - started >= 20000) {
@@ -292,8 +359,11 @@ std::string stream(xcloud::GssvClient& gssv) {
}
last = st;
}
+ beat("sleep");
platform::sleepMs(100);
}
+ watch.stop = true;
+ if (watch.thread.joinable()) watch.thread.join();
{
std::lock_guard<std::mutex> lock(g_playerMutex);
g_player = nullptr;
@@ -361,7 +431,8 @@ std::string stream(xcloud::GssvClient& gssv) {
bool normalEnd = g_cancel || autoplayDone || reason == "stopped" ||
reason.find("KickForStopCommand") != std::string::npos ||
reason.find("KickByNewSession") != std::string::npos ||
- reason.find("KickForServerShutdown") != std::string::npos;
+ reason.find("KickForServerShutdown") != std::string::npos ||
+ reason.find("KickForBeingIdle") != std::string::npos;
if (!normalEnd) {
g_gameClosedOnServer = reason.rfind("the game closed on the server", 0) == 0;
return "ERROR: " + ui::trf(ui::Str::StreamFailed, reason);
diff --git a/src/display/gpu.cpp b/src/display/gpu.cpp
index c95ccd7..457abd4 100644
--- a/src/display/gpu.cpp
+++ b/src/display/gpu.cpp
@@ -173,6 +173,9 @@ std::atomic<bool> g_restore{false}; // Anime4K Restore before the upscale
uint32_t g_frame = 0;
uint32_t g_swapImages = 3;
bool g_noPresentWait = true;
+// The longest a frame waits for the GPU or a free swapchain image (250 ms).
+constexpr uint64_t kGpuWaitNs = 250'000'000ull;
+uint32_t g_gpuTimeouts = 0;
PFN_vkWaitForPresentKHR vkWaitForPresentKHR = nullptr;
// The last frame known on the screen: its present id and when (us).
std::atomic<uint64_t> g_shownId{0}, g_shownAtUs{0};
@@ -926,7 +929,13 @@ uint32_t asBits(float f) {
bool beginFrame(bool wait) {
if (!g.ready) return false;
if (g.fencePending) {
- vkWaitForFences(g.device, 1, &g.fence, VK_TRUE, UINT64_MAX);
+ // The previous frame's GPU work, a few ms at most: bounded, so a hung
+ // GPU or display costs this frame (drawn on a later call) instead of
+ // freezing the video thread and, through the frame mutex, the app.
+ if (vkWaitForFences(g.device, 1, &g.fence, VK_TRUE, kGpuWaitNs) == VK_TIMEOUT) {
+ if (g_gpuTimeouts++ % 60 == 0) XC_LOGW("gpu: the previous frame is still not done after 250 ms (%u times)", g_gpuTimeouts);
+ return false;
+ }
g.fencePending = false;
}
if (g.frameOpen) return true; // drawn twice without a present: draw over it
@@ -955,13 +964,15 @@ bool beginFrame(bool wait) {
}
}
uint64_t t0 = platform::nowUs();
- VkResult r = vkAcquireNextImageKHR(g.device, g.swapchain, wait ? UINT64_MAX : 0, g.acquired, VK_NULL_HANDLE,
+ VkResult r = vkAcquireNextImageKHR(g.device, g.swapchain, wait ? kGpuWaitNs : 0, g.acquired, VK_NULL_HANDLE,
&g.frameIndex);
if (r == VK_ERROR_OUT_OF_DATE_KHR && g.wsi.createSurface) {
if (!recreateSwapchain()) return false;
- r = vkAcquireNextImageKHR(g.device, g.swapchain, wait ? UINT64_MAX : 0, g.acquired, VK_NULL_HANDLE,
+ r = vkAcquireNextImageKHR(g.device, g.swapchain, wait ? kGpuWaitNs : 0, g.acquired, VK_NULL_HANDLE,
&g.frameIndex);
}
+ if (r == VK_TIMEOUT && wait && g_gpuTimeouts++ % 60 == 0)
+ XC_LOGW("gpu: no free image after 250 ms (%u times)", g_gpuTimeouts);
if (r == VK_NOT_READY || r == VK_TIMEOUT) return false;
if (r == VK_SUBOPTIMAL_KHR) g.needSwapchain = true;
uint64_t waited = platform::nowUs() - t0;
@@ -1288,6 +1299,16 @@ void setPresentWait(bool on) { g_noPresentWait = !on; }
uint64_t lastPresentId() { return g.presented; }
bool lastShown(uint64_t& id, uint64_t& atUs) {
+ // What reached the screen since the last look, asked now without
+ // waiting (the thread that presents calls this, as beginFrame does).
+ if (g.ready && g.presentWait && g.swapchain && g.presented > g_shownId) {
+ for (uint64_t p = g.presented; p > g_shownId; --p)
+ if (vkWaitForPresentKHR(g.device, g.swapchain, p, 0) == VK_SUCCESS) {
+ g_shownAtUs = platform::nowUs();
+ g_shownId = p;
+ break;
+ }
+ }
id = g_shownId;
atUs = g_shownAtUs;
return id != 0;
@@ -1309,7 +1330,7 @@ void setSwapImages(int count) { g_swapImages = static_cast<uint32_t>(std::clamp(
bool readBack(std::vector<uint8_t>& rgb, int& width, int& height) {
if (!g.ready || g.lastPresented == UINT32_MAX) return false;
if (g.fencePending) {
- vkWaitForFences(g.device, 1, &g.fence, VK_TRUE, UINT64_MAX);
+ if (vkWaitForFences(g.device, 1, &g.fence, VK_TRUE, 1'000'000'000ull) == VK_TIMEOUT) return false;
g.fencePending = false;
}
size_t bytes = static_cast<size_t>(g.boxW) * g.boxH * 4;
@@ -1335,7 +1356,10 @@ bool readBack(std::vector<uint8_t>& rgb, int& width, int& height) {
submit.pCommandBuffers = &g.cmd;
vkResetFences(g.device, 1, &g.fence);
if (vkQueueSubmit(g.queue, 1, &submit, g.fence) != VK_SUCCESS) return false;
- vkWaitForFences(g.device, 1, &g.fence, VK_TRUE, UINT64_MAX);
+ if (vkWaitForFences(g.device, 1, &g.fence, VK_TRUE, 1'000'000'000ull) == VK_TIMEOUT) {
+ g.fencePending = true; // still the GPU's: the next frame waits for it
+ return false;
+ }
width = static_cast<int>(g.boxW);
height = static_cast<int>(g.boxH);
rgb.resize(static_cast<size_t>(width) * height * 3);
diff --git a/src/media/audio_queue.cpp b/src/media/audio_queue.cpp
index 7c86e67..9b0d69d 100644
--- a/src/media/audio_queue.cpp
+++ b/src/media/audio_queue.cpp
@@ -11,6 +11,7 @@
#include <algorithm>
#include <cmath>
+#include <utility>
namespace xc::media {
@@ -18,6 +19,7 @@ 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);
+ started_ = true;
if (queue_.size() > kMaxQueued * 2) {
size_t cut = queue_.size() - kTrimTo * 2;
stats_.trimmed += cut / 2;
@@ -37,6 +39,15 @@ void AudioQueue::pull(float* out, size_t frames) {
{
std::lock_guard<std::mutex> lock(mutex_);
size_t depth = queue_.size() / 2;
+ const size_t refill = refill_.load(std::memory_order_relaxed);
+ bool justDry = false, resumed = false; // this pull: ran dry (what is left plays out), or refilled
+ if (started_) {
+ lowWater_ = std::min(lowWater_, depth);
+ // Run dry: with a refill level, one event (the silence until it
+ // is back up is meant); without, each grain short.
+ if (depth < frames && (!refill || !refilling_)) ++underruns_;
+ if (depth < frames && refill && !refilling_) refilling_ = justDry = true;
+ }
stats_.depthSum += depth;
stats_.depthMax = std::max<uint64_t>(stats_.depthMax, depth);
++stats_.pulls;
@@ -47,7 +58,12 @@ void AudioQueue::pull(float* out, size_t frames) {
static_cast<unsigned long long>(stats_.empty), stats_.trimmed * 1000.0 / kRate);
stats_ = {};
}
- if (queue_.empty()) {
+ // After running dry, silence until the queue is back to the refill
+ // level (the latency control's target): playing each packet as it
+ // comes would run dry again at the next burst, a crackle every few
+ // grains instead of one gap.
+ if (refilling_ && depth >= refill) refilling_ = false, resumed = true;
+ if (queue_.empty() || (refilling_ && !justDry)) {
++stats_.empty;
std::fill(out, out + frames * 2, 0.0f);
return;
@@ -55,6 +71,14 @@ void AudioQueue::pull(float* out, size_t frames) {
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));
+ if (resumed) { // back after a gap: a 1 ms ramp in, no click
+ constexpr size_t kRamp = 48;
+ for (size_t i = 0; i < kRamp * 2 && i < n; i += 2) {
+ const float f = static_cast<float>(i / 2) / static_cast<float>(kRamp);
+ out[i] *= f;
+ out[i + 1] *= f;
+ }
+ }
if (n < frames * 2) {
// Soft ramp-out on the tail of partial buffer to eliminate underrun pops
constexpr size_t kFade = 48;
@@ -76,6 +100,37 @@ void AudioQueue::pull(float* out, size_t frames) {
void AudioQueue::clear() {
std::lock_guard<std::mutex> lock(mutex_);
queue_.clear();
+ started_ = false;
+ refilling_ = false;
+ lowWater_ = SIZE_MAX;
+ underruns_ = 0;
+}
+
+size_t AudioQueue::takeLowWater() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return std::exchange(lowWater_, SIZE_MAX);
+}
+
+uint64_t AudioQueue::takeUnderruns() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return std::exchange(underruns_, 0);
+}
+
+bool AudioQueue::cutAhead(size_t frames) {
+ constexpr size_t kLead = kRate / 100; // 10 ms left as it is (it may be playing next)
+ constexpr size_t kFade = kRate / 200; // 5 ms crossfade
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (frames == 0 || queue_.size() / 2 < kLead + frames + kFade) return false;
+ // Overlap-add: the 5 ms before the cut fade out into the 5 ms after it.
+ const size_t a = kLead * 2, b = (kLead + frames) * 2;
+ for (size_t i = 0; i < kFade; ++i) {
+ const float w = (static_cast<float>(i) + 0.5f) / static_cast<float>(kFade);
+ for (size_t c = 0; c < 2; ++c)
+ queue_[a + i * 2 + c] = queue_[a + i * 2 + c] * (1.0f - w) + queue_[b + i * 2 + c] * w;
+ }
+ queue_.erase(queue_.begin() + static_cast<long>(a + kFade * 2), queue_.begin() + static_cast<long>(b + kFade * 2));
+ stats_.trimmed += frames;
+ return true;
}
void AudioQueue::setVolume(float gain) { volume_ = std::clamp(gain, 0.0f, 2.0f); }
diff --git a/src/media/audio_queue.h b/src/media/audio_queue.h
index 42b3d36..46ae481 100644
--- a/src/media/audio_queue.h
+++ b/src/media/audio_queue.h
@@ -48,6 +48,19 @@ public:
float volume() const { return volume_; }
size_t queuedFrames() const;
Stats stats() const;
+ // For a latency control: the least that was queued at a pull since the
+ // last call (frames; SIZE_MAX when there was no pull), and the pulls that
+ // found it run dry since the last call (not counting before the sound
+ // started).
+ size_t takeLowWater();
+ uint64_t takeUnderruns();
+ // `frames` taken out about 10 ms ahead of what plays next, the two sides
+ // of the cut crossfaded over 5 ms (no click): the queue that much shorter.
+ // False when too little is queued for it.
+ bool cutAhead(size_t frames);
+ // After it runs dry, how much is queued again before the sound resumes
+ // (frames; 0: at once, as before 2026-11-04). Any thread.
+ void setRefill(size_t frames) { refill_ = frames; }
private:
mutable std::mutex mutex_;
@@ -55,6 +68,11 @@ private:
std::atomic<bool> open_{false};
std::atomic<float> volume_{1.0f};
Stats stats_; // under mutex_
+ size_t lowWater_ = SIZE_MAX; // under mutex_: takeLowWater()
+ uint64_t underruns_ = 0; // ...takeUnderruns()
+ bool started_ = false; // something was pushed since clear()
+ bool refilling_ = false; // ran dry: silent until setRefill()'s level
+ std::atomic<size_t> refill_{0};
};
// The one audio_out.h's audioPush() fills; the backend pulls from it and
diff --git a/src/media/decoder.cpp b/src/media/decoder.cpp
index 0ce4b08..bb807be 100644
--- a/src/media/decoder.cpp
+++ b/src/media/decoder.cpp
@@ -259,8 +259,15 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out, uint32_
// fed P-frames it has no references for, so switching to it froze the stream.
return false;
#endif
- if (consecutiveHwErrors_ >= 5) {
- XC_LOGE("hwdec: consecutive decode errors, falling back to CPU software decoder");
+ // A broken frame (a lost reference, a corrupt slice): the key frame
+ // asked for above brings the hardware decoder back, as on the PS4.
+ // Only errors that outlast several of them (~2 s at 60 fps) move the
+ // stream to FFmpeg for good: one CPU thread does not keep up with
+ // 1080p60, so that fallback is a last resort. Until then, this frame
+ // is lost.
+ if (consecutiveHwErrors_ < 120) return false;
+ if (consecutiveHwErrors_ == 120) {
+ XC_LOGE("hwdec: %d decode errors in a row, falling back to the CPU software decoder", consecutiveHwErrors_);
isHw_ = false;
if (ctx_) avcodec_flush_buffers(ctx_);
}
diff --git a/src/platform/android/platform_android.cpp b/src/platform/android/platform_android.cpp
index 2e9c71f..2904ff0 100644
--- a/src/platform/android/platform_android.cpp
+++ b/src/platform/android/platform_android.cpp
@@ -120,6 +120,8 @@ std::string diagnostics() { return {}; }
std::string platformName() { return "Android"; }
size_t imageCacheBudget() { return 96u << 20; }
+void setNoThreadPinning(bool) {}
+
void setThreadAffinity(ThreadRole, const char*) {}
void setThreadRealtimePriority() {}
diff --git a/src/platform/linux/platform_linux.cpp b/src/platform/linux/platform_linux.cpp
index a49997a..81de612 100644
--- a/src/platform/linux/platform_linux.cpp
+++ b/src/platform/linux/platform_linux.cpp
@@ -172,6 +172,8 @@ std::string diagnostics() { return {}; }
std::string platformName() { return "Linux"; }
size_t imageCacheBudget() { return 160u << 20; }
+void setNoThreadPinning(bool) {}
+
void setThreadAffinity(ThreadRole role, const char* name) {
if (name && *name) {
pthread_setname_np(pthread_self(), name);
diff --git a/src/platform/platform.h b/src/platform/platform.h
index cb3cc96..a3da60c 100644
--- a/src/platform/platform.h
+++ b/src/platform/platform.h
@@ -68,6 +68,10 @@ enum class ThreadRole {
Worker, // Core 4..7: Background tasks, library hydration, image decoding
};
void setThreadAffinity(ThreadRole role, const char* name = nullptr);
+// Whether setThreadAffinity() only names the thread (the console's default)
+// or pins it by role (measurements: autoplay "pin"). Before the first call;
+// the console only, a no-op elsewhere.
+void setNoThreadPinning(bool on);
void setThreadRealtimePriority();
// Short on-screen message: the PS5's system notification; in the desktop
diff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cpp
index 5bce055..a49b972 100644
--- a/src/platform/ps4/platform_ps4.cpp
+++ b/src/platform/ps4/platform_ps4.cpp
@@ -1128,6 +1128,8 @@ void notify(const std::string& text, const std::string& forLog) {
sceKernelSendNotificationRequest(0, &req, sizeof req, 0);
}
+void setNoThreadPinning(bool) {}
+
void setThreadAffinity(ThreadRole role, const char* name) {
if (name && *name) {
pthread_set_name_np(pthread_self(), name);
diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cpp
index 5d58f54..acc493c 100644
--- a/src/platform/ps5/platform_ps5.cpp
+++ b/src/platform/ps5/platform_ps5.cpp
@@ -22,6 +22,7 @@
#include <pthread_np.h>
#include <sched.h>
#include <sys/cpuset.h>
+#include <string>
#include <sys/socket.h>
extern "C" {
@@ -268,6 +269,17 @@ void notify(const std::string& text, const std::string& forLog) {
sceKernelSendNotificationRequest(0, &req, sizeof req, 0);
}
+namespace {
+// The threads keep the scheduler's choice unless setNoThreadPinning(false):
+// measured in Fortnite (2026-11-04), pinning by role did nothing for the
+// video and made the sound run dry more often (the four audio threads then
+// share one core). It never took before that day either: the cpuset query
+// failed with the SDK's mask size.
+std::atomic<bool> g_noThreadPinning{true};
+} // namespace
+
+void setNoThreadPinning(bool on) { g_noThreadPinning = on; }
+
void setThreadAffinity(ThreadRole role, const char* name) {
if (name && *name) {
pthread_set_name_np(pthread_self(), name);
@@ -276,11 +288,22 @@ void setThreadAffinity(ThreadRole role, const char* name) {
static bool s_procMaskQueried = false;
static int s_allowedCpus[32];
static int s_numAllowedCpus = 0;
+ // The kernel's cpuset is smaller than the SDK's (256 CPUs): the full
+ // size gets ERANGE, so the sizes it may take are tried down to 64 CPUs.
+ static size_t s_maskSize = sizeof(cpuset_t);
if (!s_procMaskQueried) {
s_procMaskQueried = true;
- CPU_ZERO(&s_procMask);
- int grc = pthread_getaffinity_np(pthread_self(), sizeof(cpuset_t), &s_procMask);
+ int grc = -1;
+ for (size_t size : {sizeof(cpuset_t), size_t{16}, size_t{8}}) {
+ if (size > sizeof(cpuset_t)) continue;
+ CPU_ZERO(&s_procMask);
+ grc = pthread_getaffinity_np(pthread_self(), size, &s_procMask);
+ if (grc == 0) {
+ s_maskSize = size;
+ break;
+ }
+ }
if (grc == 0) {
for (int i = 0; i < 32; ++i) {
if (CPU_ISSET(i, &s_procMask)) {
@@ -288,13 +311,13 @@ void setThreadAffinity(ThreadRole role, const char* name) {
}
}
}
- XC_LOGI("ps5 cpuset: %d allowed cpus detected (grc=%d)", s_numAllowedCpus, grc);
- for (int i = 0; i < s_numAllowedCpus; ++i) {
- XC_LOGI(" cpu slot %d: logical core %d", i, s_allowedCpus[i]);
- }
+ std::string list;
+ for (int i = 0; i < s_numAllowedCpus; ++i) list += (i ? "," : "") + std::to_string(s_allowedCpus[i]);
+ XC_LOGI("ps5 cpuset: %d allowed cpus (%s), mask of %zu bytes (grc=%d)%s", s_numAllowedCpus, list.c_str(),
+ s_maskSize, grc, g_noThreadPinning ? "; threads left unpinned" : "");
}
- if (s_numAllowedCpus <= 1) {
+ if (s_numAllowedCpus <= 1 || g_noThreadPinning) {
return;
}
@@ -329,7 +352,7 @@ void setThreadAffinity(ThreadRole role, const char* name) {
}
break;
}
- int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpuset_t), &mask);
+ int rc = pthread_setaffinity_np(pthread_self(), s_maskSize, &mask);
if (rc != 0) {
XC_LOGW("pthread_setaffinity_np(%s): %d", name ? name : "thread", rc);
} else {
diff --git a/src/platform/windows/platform_windows.cpp b/src/platform/windows/platform_windows.cpp
index fb2df1b..15e60f7 100644
--- a/src/platform/windows/platform_windows.cpp
+++ b/src/platform/windows/platform_windows.cpp
@@ -272,6 +272,8 @@ void Thread::join() {
#endif
}
+void setNoThreadPinning(bool) {}
+
void setThreadAffinity(ThreadRole role, const char* name) {
#if defined(_WIN32) || defined(__CYGWIN__)
(void)name;
diff --git a/src/stream/h264_receiver.cpp b/src/stream/h264_receiver.cpp
index cb79257..c61cd4f 100644
--- a/src/stream/h264_receiver.cpp
+++ b/src/stream/h264_receiver.cpp
@@ -12,6 +12,14 @@
namespace xc::stream {
+namespace {
+void raiseMax(std::atomic<uint64_t>& a, uint64_t v) {
+ uint64_t cur = a.load(std::memory_order_relaxed);
+ while (v > cur && !a.compare_exchange_weak(cur, v, std::memory_order_relaxed)) {
+ }
+}
+} // namespace
+
namespace {
// How long a hole may wait for its retransmission (a couple of RTTs), how
@@ -160,7 +168,7 @@ void H264Receiver::noteGap(int64_t from, int64_t to, uint64_t now, const rtc::me
void H264Receiver::resendNacks(uint64_t now, const rtc::message_callback& send) {
std::vector<int64_t> seqs;
for (auto& [s, m] : missing_)
- if (m.nacks < kMaxNacks && now - m.lastNackMs >= kRenackMs) {
+ if (m.nacks < kMaxNacks && now - m.lastNackMs >= renackMs()) {
m.lastNackMs = now;
++m.nacks;
seqs.push_back(s);
@@ -273,7 +281,7 @@ void H264Receiver::drain(uint64_t now, rtc::message_vector& out, const rtc::mess
auto m = missing_.find(hole);
uint64_t since = m != missing_.end() ? m->second.sinceMs : now;
if (m == missing_.end()) missing_[hole] = Missing{now, now, 0};
- if (now - since < waitMs_) return; // give the retransmission time
+ if (now - since < lossWaitMs()) return; // give the retransmission time
// Lost for good: drop what we have of this frame and resync on
// the next key frame.
++stats_.framesDropped;
@@ -298,6 +306,11 @@ void H264Receiver::drain(uint64_t now, rtc::message_vector& out, const rtc::mess
}
if (key) waitingKeyframe_ = false;
++stats_.framesOut;
+ if (lastFrameMs_) {
+ const int64_t late = static_cast<int64_t>(now - lastFrameMs_) - static_cast<int32_t>(ts - lastFrameTs_) / 90;
+ if (late > 0) raiseMax(stats_.maxLateMs, static_cast<uint64_t>(late));
+ }
+ lastFrameMs_ = now, lastFrameTs_ = ts;
out.push_back(rtc::make_message(asBytes(frame), asBytes(frame) + frame.size(), std::make_shared<rtc::FrameInfo>(ts)));
}
}
@@ -330,6 +343,16 @@ void H264Receiver::accept(const uint8_t* d, size_t n, uint64_t now, const rtc::m
int64_t seq = unwrap(rawSeq);
if (nextSeq_ >= 0 && seq < nextSeq_) return; // too late or duplicate
if (hasPacket(seq)) return;
+ // A frame's first packet (the first with its timestamp): when it came.
+ const uint32_t ts = (uint32_t(d[4]) << 24) | (uint32_t(d[5]) << 16) | (uint32_t(d[6]) << 8) | d[7];
+ if (!anyTs_ || ts != lastNewTs_) {
+ bool known = false;
+ for (const auto& f : firstPacket_) known |= f.second && f.first == ts;
+ if (!known) {
+ firstPacket_[firstPacketNext_++ % kFirstPacketRing] = {ts, platform::nowUs()};
+ lastNewTs_ = ts, anyTs_ = true;
+ }
+ }
if (end - off > kMaxPayload) {
// Larger than a slot: cut short it would corrupt the NAL unit. Left
// as a hole instead, NACKed when the next packet shows it (and
@@ -342,7 +365,6 @@ void H264Receiver::accept(const uint8_t* d, size_t n, uint64_t now, const rtc::m
}
if (missing_.erase(seq)) ++stats_.recovered;
- uint32_t ts = (uint32_t(d[4]) << 24) | (uint32_t(d[5]) << 16) | (uint32_t(d[6]) << 8) | d[7];
bool marker = (d[1] & 0x80) != 0;
putPacket(seq, ts, marker, d + off, end - off);
@@ -364,10 +386,13 @@ void H264Receiver::incoming(rtc::message_vector& messages, const rtc::message_ca
}
for (auto& message : messages) {
if (message->type == rtc::Message::Control) continue; // RTCP: handled down the chain
+ if (lastPacketMs_) raiseMax(stats_.maxGapMs, now - lastPacketMs_);
+ lastPacketMs_ = now;
accept(reinterpret_cast<const uint8_t*>(message->data()), message->size(), now, send);
}
resendNacks(now, send);
drain(now, out, send);
+ raiseMax(stats_.maxBurst, out.size());
// Still without a key frame: ask again (askKeyframe allows one every
// 300 ms), as the request or the key frame itself may have been lost;
// otherwise the picture stays frozen until the buffer overflows (seconds).
@@ -381,4 +406,22 @@ void H264Receiver::incoming(rtc::message_vector& messages, const rtc::message_ca
messages.swap(out);
}
+uint64_t H264Receiver::firstPacketUs(uint32_t rtpTimestamp) const {
+ for (const auto& f : firstPacket_)
+ if (f.second && f.first == rtpTimestamp) return f.second;
+ return 0;
+}
+
+uint64_t H264Receiver::lossWaitMs() const {
+ const int rtt = rttMs_;
+ if (rtt <= 0) return waitMs_;
+ return std::clamp<uint64_t>(static_cast<uint64_t>(rtt) * 2 + 30, waitMs_, 300);
+}
+
+uint64_t H264Receiver::renackMs() const {
+ const int rtt = rttMs_;
+ if (rtt <= 0) return kRenackMs;
+ return std::clamp<uint64_t>(static_cast<uint64_t>(rtt) + 10, kRenackMs, 250);
+}
+
} // namespace xc::stream
diff --git a/src/stream/h264_receiver.h b/src/stream/h264_receiver.h
index c044690..fe0e19d 100644
--- a/src/stream/h264_receiver.h
+++ b/src/stream/h264_receiver.h
@@ -12,6 +12,7 @@
// caller's callback) and nothing is shown until that key frame: a short
// freeze instead of corruption.
#pragma once
+#include <atomic>
#include "stream/video_stats.h"
@@ -37,6 +38,21 @@ public:
// retransmission cannot be tested this way: SRTP drops it as a replay).
void setSimulatedLoss(int percent) { simulatedLoss_ = percent; }
+ // When the first packet of the frame with this RTP timestamp came
+ // (platform::nowUs()), 0 when not known: for the latency up to the
+ // screen. On libdatachannel's thread (the frame's onFrame callback).
+ uint64_t firstPacketUs(uint32_t rtpTimestamp) const;
+
+ // The connection's round trip (ms; any thread, once a second): how long
+ // a retransmission takes to come. A frame waits for its lost packets
+ // 2 RTT + 30 ms (90..300 ms) and NACKs again after an RTT (50..250 ms):
+ // with a fixed 90 ms, a 68 ms connection had no time for a second try
+ // and a 141 ms one none for the first (the frame dropped, the picture
+ // frozen until the next key frame).
+ void setRttMs(int rttMs) { rttMs_ = rttMs; }
+ uint64_t lossWaitMs() const;
+ uint64_t renackMs() const;
+
private:
static constexpr size_t kMaxPayload = 1536; // a larger payload is treated as lost (accept())
struct PacketSlot {
@@ -80,10 +96,19 @@ private:
std::function<void()> onKeyframeNeeded_;
VideoReceiveStats& stats_;
uint64_t waitMs_ = 300;
+ std::atomic<int> rttMs_{-1};
std::unique_ptr<PacketSlot[]> ring_;
size_t packetCount_ = 0;
std::map<int64_t, Missing> missing_;
int64_t highest_ = -1; // highest extended sequence number seen
+ uint64_t lastPacketMs_ = 0; // VideoReceiveStats::maxGapMs
+ static constexpr size_t kFirstPacketRing = 64;
+ std::pair<uint32_t, uint64_t> firstPacket_[kFirstPacketRing] = {}; // RTP timestamp, its first packet (us)
+ size_t firstPacketNext_ = 0;
+ uint32_t lastNewTs_ = 0;
+ bool anyTs_ = false;
+ uint64_t lastFrameMs_ = 0; // ...maxLateMs: the previous frame handed on
+ uint32_t lastFrameTs_ = 0;
int64_t nextSeq_ = -1; // first packet of the next frame to emit; -1 = resync
bool waitingKeyframe_ = true;
uint32_t mediaSsrc_ = 0;
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index ff45980..1b545a8 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -119,6 +119,7 @@ struct StreamSession::Impl {
uint64_t lastKeyframeMs = 0;
VideoReceiveStats videoStats;
std::shared_ptr<RtcpReporter> videoReporter;
+ H264Receiver* videoReceiverRaw = nullptr; // owned by the video track
// The video receiver (a media handler, which libdatachannel may still be
// running after the session is gone) reaches the session through this.
struct Guard {
@@ -554,10 +555,11 @@ struct StreamSession::Impl {
},
videoStats);
videoReceiver->setSimulatedLoss(opt.simulatedVideoLoss);
+ videoReceiverRaw = videoReceiver.get();
videoReporter = std::make_shared<RtcpReporter>(90000, opt.maxBitrate);
videoReceiver->addToChain(videoReporter);
video->setMediaHandler(videoReceiver);
- video->onFrame([this](rtc::binary data, rtc::FrameInfo info) {
+ video->onFrame([this, receiver = videoReceiver.get()](rtc::binary data, rtc::FrameInfo info) {
static thread_local bool s_netPinned = false;
if (!s_netPinned) {
platform::setThreadAffinity(platform::ThreadRole::Network, "xcloud_net");
@@ -571,7 +573,9 @@ struct StreamSession::Impl {
static_cast<unsigned long long>(now - last));
padsStale = true;
}
- if (cb.video) cb.video(reinterpret_cast<const uint8_t*>(data.data()), data.size(), info.timestamp);
+ if (cb.video)
+ cb.video(reinterpret_cast<const uint8_t*>(data.data()), data.size(), info.timestamp,
+ receiver->firstPacketUs(info.timestamp));
});
XC_LOGI("webrtc: createPeer completed");
}
@@ -900,7 +904,11 @@ void StreamSession::close() { impl_->close(); }
int StreamSession::rttMs() const {
try {
if (impl_->pc)
- if (auto rtt = impl_->pc->rtt()) return static_cast<int>(rtt->count());
+ if (auto rtt = impl_->pc->rtt()) {
+ const int ms = static_cast<int>(rtt->count());
+ if (impl_->videoReceiverRaw) impl_->videoReceiverRaw->setRttMs(ms); // its loss wait follows it
+ return ms;
+ }
} catch (const std::exception&) {
}
return -1;
diff --git a/src/stream/stream_session.h b/src/stream/stream_session.h
index 57ace8d..9ecf72d 100644
--- a/src/stream/stream_session.h
+++ b/src/stream/stream_session.h
@@ -29,7 +29,8 @@ struct TextInputRequest {
};
struct StreamCallbacks {
- std::function<void(const uint8_t* data, size_t len, uint32_t rtpTimestamp)> video;
+ // `firstPacketUs`: when the frame's first packet came (platform::nowUs()), 0 if unknown.
+ std::function<void(const uint8_t* data, size_t len, uint32_t rtpTimestamp, uint64_t firstPacketUs)> video;
std::function<void(const uint8_t* data, size_t len, uint32_t rtpTimestamp)> audio;
std::function<void(const Vibration&)> vibration;
// The server will end the session for inactivity in `seconds` unless
@@ -51,8 +52,10 @@ struct StreamCallbacks {
struct StreamOptions {
int connectTimeoutMs = 30000;
// The web client asks for a key frame this often to recover from loss
- // without NACK; 0 disables.
- int keyframeIntervalSec = 5;
+ // without NACK; 0 disables. Off: this client NACKs and asks for a key
+ // frame when a frame is lost for good, and each periodic one cost a
+ // 20-25 ms decode and a dip in the picture every 5 s.
+ int keyframeIntervalSec = 0;
// Stream tier requested on the control channel after connecting, as the
// xbox.com client does ("userRequestedResolutionUpdate"): "720", "720HQ",
// "1080", "1080HQ" or "1440" (the HQ tiers and 1440 need Game Pass
diff --git a/src/stream/video_stats.h b/src/stream/video_stats.h
index e2a0dc4..c34bc4d 100644
--- a/src/stream/video_stats.h
+++ b/src/stream/video_stats.h
@@ -18,6 +18,11 @@ struct VideoReceiveStats {
std::atomic<uint64_t> keyframeRequests{0};
std::atomic<uint32_t> receiveRate{0}; // bits/s, last report interval
std::atomic<uint32_t> estimate{0}; // bits/s offered to the server (REMB)
+ // Since the last read (StreamPlayer::stats() takes them): the longest
+ // wait between two video packets, the most frames handed on at once,
+ // and how much later a frame was ready than its RTP time says (a pause
+ // in delivery, or a frame held for a retransmission).
+ mutable std::atomic<uint64_t> maxGapMs{0}, maxBurst{0}, maxLateMs{0};
};
} // namespace xc::stream
diff --git a/src/ui/i18n/strings_de.inc b/src/ui/i18n/strings_de.inc
index 2e6d6ce..df3f497 100644
--- a/src/ui/i18n/strings_de.inc
+++ b/src/ui/i18n/strings_de.inc
@@ -416,4 +416,5 @@ constexpr Column kGerman = {
"Um kostenlose Spiele außer Fortnite ohne Game Pass zu streamen, aktivieren Sie 'Preview-Funktionen' in den App-Einstellungen und auf xbox.com/play.", // F2pPreviewRequiredDesc
"Dieses Konto muss 'Preview-Funktionen' im Profil auf xbox.com/play aktivieren, um werbefinanziertes Free-to-Play-Streaming freizuschalten.", // F2pPreviewAccountNeededDesc
"Spieler", // MenuPlayer
+ "Die Sitzung wurde wegen Inaktivität beendet", // EndedIdle
};
diff --git a/src/ui/i18n/strings_en.inc b/src/ui/i18n/strings_en.inc
index 4400d01..daaa690 100644
--- a/src/ui/i18n/strings_en.inc
+++ b/src/ui/i18n/strings_en.inc
@@ -416,4 +416,5 @@ constexpr Column kEnglish = {
"To stream free-to-play games beyond Fortnite without Game Pass, enable 'Preview Features' in app Settings and on xbox.com/play.", // F2pPreviewRequiredDesc
"This account needs to enable 'Preview Features' in its profile on xbox.com/play to unlock ad-supported free-to-play streaming.", // F2pPreviewAccountNeededDesc
"Player", // MenuPlayer
+ "The stream ended after a while without input", // EndedIdle
};
diff --git a/src/ui/i18n/strings_es.inc b/src/ui/i18n/strings_es.inc
index 8ea70d6..045a151 100644
--- a/src/ui/i18n/strings_es.inc
+++ b/src/ui/i18n/strings_es.inc
@@ -416,4 +416,5 @@ constexpr Column kSpanish = {
"Para transmitir juegos gratuitos además de Fortnite en cuentas sin Game Pass, activa 'Funciones Preview' en Ajustes y en xbox.com/play.", // F2pPreviewRequiredDesc
"Esta cuenta necesita habilitar 'Funciones Preview' en su perfil en xbox.com/play para desbloquear el streaming con anuncios de juegos gratuitos.", // F2pPreviewAccountNeededDesc
"Jugador", // MenuPlayer
+ "La sesión terminó por inactividad", // EndedIdle
};
diff --git a/src/ui/i18n/strings_fr.inc b/src/ui/i18n/strings_fr.inc
index 8e56225..b1d0168 100644
--- a/src/ui/i18n/strings_fr.inc
+++ b/src/ui/i18n/strings_fr.inc
@@ -416,4 +416,5 @@ constexpr Column kFrench = {
"Pour jouer aux jeux gratuits autres que Fortnite sans Game Pass, activez les 'Fonctionnalités Preview' dans les Paramètres et sur xbox.com/play.", // F2pPreviewRequiredDesc
"Ce compte doit activer les 'Fonctionnalités Preview' sur son profil sur xbox.com/play pour débloquer le streaming gratuit avec publicités.", // F2pPreviewAccountNeededDesc
"Joueur", // MenuPlayer
+ "La session s’est terminée pour inactivité", // EndedIdle
};
diff --git a/src/ui/i18n/strings_it.inc b/src/ui/i18n/strings_it.inc
index d48b4ca..0df08ec 100644
--- a/src/ui/i18n/strings_it.inc
+++ b/src/ui/i18n/strings_it.inc
@@ -416,4 +416,5 @@ constexpr Column kItalian = {
"Per giocare a titoli gratuiti oltre a Fortnite senza Game Pass, abilita 'Funzionalità Preview' nelle Impostazioni e su xbox.com/play.", // F2pPreviewRequiredDesc
"Questo account deve abilitare le 'Funzionalità Preview' nel profilo su xbox.com/play per sbloccare lo streaming gratuito supportato da annunci.", // F2pPreviewAccountNeededDesc
"Giocatore", // MenuPlayer
+ "La sessione è terminata per inattività", // EndedIdle
};
diff --git a/src/ui/i18n/strings_pt_br.inc b/src/ui/i18n/strings_pt_br.inc
index 7adf595..bcaa489 100644
--- a/src/ui/i18n/strings_pt_br.inc
+++ b/src/ui/i18n/strings_pt_br.inc
@@ -416,4 +416,5 @@ constexpr Column kPortugueseBR = {
"Para transmitir jogos gratuitos além de Fortnite em contas sem Game Pass, ative os 'Recursos Preview' nas Configurações do app e no site xbox.com/play.", // F2pPreviewRequiredDesc
"Esta conta precisa habilitar os 'Recursos Preview' no perfil em xbox.com/play para liberar o streaming com anúncios de jogos gratuitos.", // F2pPreviewAccountNeededDesc
"Jogador", // MenuPlayer
+ "O streaming foi encerrado por inatividade", // EndedIdle
};
diff --git a/src/ui/strings.h b/src/ui/strings.h
index 163ece5..d1ad7d1 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -425,6 +425,7 @@ enum class Str {
F2pPreviewRequiredDesc,
F2pPreviewAccountNeededDesc,
MenuPlayer, // game menu, a USB controller's: the player it plays as
+ EndedIdle, // toast: the server ended the stream after a while without input
Count
};
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 8248a91..5559dcb 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -1570,6 +1570,22 @@ static void testAudioEncoder() {
// A burst of loss: a frame lost for good, then a frame with a hole of its
// own, then a complete key frame. The receiver must resume at that key frame
// (it used to stop at the frame with the hole: a freeze of seconds).
+// The wait for a retransmission follows the round trip: none known keeps
+// the default; a slow connection gets time for a NACK and a second try.
+static void testH264LossWaitFollowsRtt() {
+ xc::stream::VideoReceiveStats stats;
+ xc::stream::H264Receiver rx([] {}, stats);
+ CHECK(rx.lossWaitMs() == 90 && rx.renackMs() == 50);
+ rx.setRttMs(15); // this console's connection: as before
+ CHECK(rx.lossWaitMs() == 90 && rx.renackMs() == 50);
+ rx.setRttMs(68); // issue #317 (PS4): 166 ms, a second NACK after 78
+ CHECK(rx.lossWaitMs() == 166 && rx.renackMs() == 78);
+ rx.setRttMs(141); // issue #342: 300 ms at most
+ CHECK(rx.lossWaitMs() == 300 && rx.renackMs() == 151);
+ rx.setRttMs(-1); // not measured any more: the default again
+ CHECK(rx.lossWaitMs() == 90);
+}
+
static void testH264Resync() {
xc::stream::VideoReceiveStats stats;
int keyframeAsks = 0;
@@ -2387,6 +2403,49 @@ static void testDrawNv12() {
// The audio queue: bounded at ~250 ms (cut back to 140 ms, oldest first),
// silence past its end, the volume, and what the periodic log counts.
+static void testAudioQueueLatency() {
+ media::AudioQueue q;
+ q.open();
+ CHECK(q.takeLowWater() == SIZE_MAX && q.takeUnderruns() == 0);
+ std::vector<float> out(512);
+ q.pull(out.data(), 256); // before any sound: not a dry pull
+ CHECK(q.takeUnderruns() == 0);
+ std::vector<float> tone(4800 * 2, 0.5f); // 100 ms, constant
+ q.push(tone.data(), 4800);
+ q.pull(out.data(), 256);
+ q.pull(out.data(), 256);
+ CHECK(q.takeLowWater() == 4800 - 256); // the lowest seen at a pull
+ CHECK(q.takeLowWater() == SIZE_MAX);
+ const size_t before = q.queuedFrames();
+ CHECK(q.cutAhead(960));
+ CHECK(q.queuedFrames() == before - 960);
+ // Both sides of the cut were 0.5: the crossfade keeps it 0.5, no click.
+ std::vector<float> rest(before * 2);
+ q.pull(rest.data(), q.queuedFrames());
+ bool flat = true;
+ for (size_t i = 0; i < (before - 960) * 2; ++i) flat &= std::abs(rest[i] - 0.5f) < 1e-4f;
+ CHECK(flat);
+ CHECK(!q.cutAhead(960)); // nothing queued
+ q.pull(out.data(), 256); // dry, after sound
+ CHECK(q.takeUnderruns() == 1);
+ q.clear();
+ q.pull(out.data(), 256);
+ CHECK(q.takeUnderruns() == 0); // cleared: not started again
+
+ // A refill level: after running dry the sound waits for 40 ms queued.
+ q.setRefill(1920);
+ q.push(tone.data(), 300); // 6 ms: plays out, then dry
+ q.pull(out.data(), 256);
+ q.pull(out.data(), 256); // dry: refilling (one event, not one per grain)
+ CHECK(q.takeUnderruns() == 1);
+ q.push(tone.data(), 960); // 20 ms: under the level, still silent
+ q.pull(out.data(), 256);
+ CHECK(out[100] == 0.0f && q.queuedFrames() == 960 && q.takeUnderruns() == 0);
+ q.push(tone.data(), 1200); // 45 ms queued: resumes, ramping in
+ q.pull(out.data(), 256);
+ CHECK(out[0] == 0.0f && std::abs(out[400] - 0.5f) < 1e-4f && q.queuedFrames() == 2160 - 256);
+}
+
static void testAudioQueue() {
media::AudioQueue q;
std::vector<float> in(48 * 2 * 10, 0.25f); // 10 ms
@@ -6995,6 +7054,7 @@ int main() {
testVisibleSettingsRows();
testMissingFont();
testNullBackendsM1();
+ testAudioQueueLatency();
testAudioQueue();
testMicPipeline();
testDs5TriggerEffects();
@@ -7016,6 +7076,7 @@ int main() {
testSubscriptionPlan();
testMicrosoftHost();
testAudioEncoder();
+ testH264LossWaitFollowsRtt();
testH264Resync();
testH264PaddingPacket();
testAudioDecoderEmptyPacket();