Xbox Cloud Gaming app for PS5 Homebrew
C
Lower audio delay, a bitrate cap and the game's volume
Rafael Abud Ferreira8526615e30c7
diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex 4161dd9..e8b28e3 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -122,6 +122,8 @@ bool saveSettings(const ui::SettingsChoice& choice) {g_settings.deband = choice.deband;g_settings.upscaler = choice.upscaler;g_settings.highRefresh = choice.highRefresh;+ g_settings.maxBitrateMbps = choice.maxBitrateMbps;+ g_settings.gameVolume = choice.gameVolume;g_settings.save(settingsPath()); // warns itselfXC_LOGI("settings saved: language %s, %s, region %s", code.c_str(), g_settings.resolution.c_str(),g_settings.region.empty() ? "auto" : g_settings.region.c_str());@@ -241,6 +243,8 @@ int main(int argc, char** argv) {choice.deband = g_settings.deband;choice.upscaler = g_settings.upscaler;choice.highRefresh = g_settings.highRefresh;+ choice.maxBitrateMbps = g_settings.maxBitrateMbps;+ choice.gameVolume = g_settings.gameVolume;g_ui->setAllow1440(allow1440Locked());g_ui->setUpdateState(XC_APP_VERSION, {}, false); // Settings shows this version before any checkg_ui->setSettings(choice);diff --git a/src/app/settings.cpp b/src/app/settings.cppindex cd40698..b017ede 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -51,6 +51,8 @@ bool Settings::load(const std::string& path) {gestureHints = static_cast<int>((*j)["gestureHints"].asInt(gestureHints));micEnabled = (*j)["micEnabled"].asBool(micEnabled);highRefresh = (*j)["highRefresh"].asBool(highRefresh);+ maxBitrateMbps = static_cast<int>(std::clamp<int64_t>((*j)["maxBitrateMbps"].asInt(maxBitrateMbps), 0, 40));+ gameVolume = static_cast<int>(std::clamp<int64_t>((*j)["gameVolume"].asInt(gameVolume), 0, 200));micGain = static_cast<int>(std::clamp<int64_t>((*j)["micGain"].asInt(micGain), 0, 2));audioRoute = static_cast<int>(std::clamp<int64_t>((*j)["audioRoute"].asInt(audioRoute), 0, 1));skippedUpdate = (*j)["skippedUpdate"].str();@@ -158,6 +160,8 @@ bool Settings::save(const std::string& path) const {v.set("gestureHints", gestureHints);v.set("micEnabled", micEnabled);v.set("highRefresh", highRefresh);+ v.set("maxBitrateMbps", maxBitrateMbps);+ v.set("gameVolume", gameVolume);v.set("micGain", micGain);v.set("audioRoute", audioRoute);v.set("skippedUpdate", skippedUpdate);diff --git a/src/app/settings.h b/src/app/settings.hindex 9531dc7..0fe32e5 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -72,6 +72,8 @@ struct Settings {// Voice chat & Audio routingbool micEnabled = true;bool highRefresh = false; // 119.88 Hz output (VRR where the console turns it on) while streaming+ int maxBitrateMbps = 0; // the stream's bitrate cap: 0 automatic (the tier's), else 20, 15, 10 or 5+ int gameVolume = 100; // percent: 25, 50, 75, 100 or 150int micGain = 1; // 0: 50%, 1: 100%, 2: 150%int audioRoute = 0; // 0: TV/HDMI (Main), 1: DualSense Speaker / Headset (Pad)// The release the user said "Not now" to: not offered again on start.diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex cc17565..f1f5779 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -84,6 +84,7 @@ struct StreamPlayer::Impl {std::atomic<uint64_t> decodeUs{0}, decodeCalls{0}, decodeMaxUs{0}, drawUs{0}, drawCalls{0}, drawMaxUs{0};int decodeThreads = 1;int simulatedLoss = 0;+ int maxBitrateMbps = 0;bool hwProbe = false;static void atomicMax(std::atomic<uint64_t>& a, uint64_t v) {@@ -448,6 +449,8 @@ struct StreamPlayer::Impl {: gssv.resolution() == xcloud::Resolution::P1440 ? 40000000: gssv.resolution() == xcloud::Resolution::P1080HQ ? 30000000: 25000000;+ if (maxBitrateMbps > 0) // the user's cap (Wi-Fi): REMB never offers more+ opts.maxBitrate = std::min<uint32_t>(opts.maxBitrate, static_cast<uint32_t>(maxBitrateMbps) * 1000000u);opts.simulatedVideoLoss = simulatedLoss;if (const char* loss = std::getenv("XC_SIM_LOSS")) opts.simulatedVideoLoss = std::atoi(loss);callbacks = cb;@@ -735,6 +738,7 @@ void StreamPlayer::stop() { impl_->stop(); }void StreamPlayer::setHwDecodeProbe(bool on) { impl_->hwProbe = on; }void StreamPlayer::setDecodeThreads(int threads) { impl_->decodeThreads = std::max(1, threads); }+void StreamPlayer::setMaxBitrate(int mbps) { impl_->maxBitrateMbps = std::max(0, mbps); }void StreamPlayer::setSimulatedLoss(int percent) { impl_->simulatedLoss = std::clamp(percent, 0, 50); }StreamPlayer::Stats StreamPlayer::stats() const {diff --git a/src/app/stream_player.h b/src/app/stream_player.hindex dd753db..5e9cda2 100644--- a/src/app/stream_player.h+++ b/src/app/stream_player.h@@ -83,6 +83,8 @@ public:Stats stats() const;// Before start(): H.264 decoder threads (more than 1 = frame threading).void setDecodeThreads(int threads);+ // Before start(): the video bitrate offered to the server, in Mbps (0: the tier's).+ void setMaxBitrate(int mbps);// Test: hold back this percentage of the video packets (see H264Receiver).void setSimulatedLoss(int percent);// Before start(): also run every frame through the PS5's hardwarediff --git a/src/app/worker.cpp b/src/app/worker.cppindex 5b51dcd..283ce74 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -73,6 +73,11 @@ std::string stream(xcloud::GssvClient& gssv) {std::lock_guard<std::mutex> lock(g_settingsMutex);player.setMicGain(g_settings.micGain);player.setMicEnabled(g_settings.micEnabled);+ player.setMaxBitrate(g_settings.maxBitrateMbps);+ media::audioSetVolume(g_settings.gameVolume / 100.0f);+ XC_LOGI("stream: bitrate cap %s, game volume %d%%",+ g_settings.maxBitrateMbps ? (std::to_string(g_settings.maxBitrateMbps) + " Mbps").c_str() : "automatic",+ g_settings.gameVolume);media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));}std::string err;diff --git a/src/media/audio_out.cpp b/src/media/audio_out.cppindex 59e8d97..865dae3 100644--- a/src/media/audio_out.cpp+++ b/src/media/audio_out.cpp@@ -6,6 +6,7 @@#include <atomic>#include <cstring>+#include <algorithm>#include <deque>#include <mutex>#include <thread>@@ -26,11 +27,19 @@ namespace {constexpr int kRate = 48000;constexpr unsigned kGrain = 256;-constexpr size_t kMaxQueued = kRate * 120 / 1000;+// 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 stereostd::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)@@ -42,11 +51,23 @@ void loop() {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));@@ -100,6 +121,8 @@ bool audioStart() {return true;}+void audioSetVolume(float gain) { g_volume = std::clamp(gain, 0.0f, 2.0f); }+void audioSetRoute(AudioRoute route) {g_route.store(route);}@@ -126,8 +149,11 @@ 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)- g_queue.erase(g_queue.begin(), g_queue.begin() + static_cast<long>(g_queue.size() - kMaxQueued * 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::mediadiff --git a/src/media/audio_out.h b/src/media/audio_out.hindex cbe714c..0fc3e97 100644--- a/src/media/audio_out.h+++ b/src/media/audio_out.h@@ -17,8 +17,10 @@ bool audioStart();void audioStop();void audioSetRoute(AudioRoute route);AudioRoute audioRoute();-// Drops the oldest samples when more than ~120 ms is queued, to keep-// latency bounded when the network delivers a burst.+// The game's volume: 1 as it comes, up to 2 (louder, clipped at full scale).+void audioSetVolume(float gain);+// Past ~60 ms queued (a burst from the network) cuts back to ~40 ms, the+// oldest samples first, to keep the sound close to the picture.void audioPush(const float* interleaved, size_t frames);} // namespace xc::mediadiff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 321ed47..4e2f8d1 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -1219,6 +1219,10 @@ void AppUi::setRegions(std::vector<std::string> regions, const std::string& defadirty_ = true;}+// Settings' bitrate caps (Mbps, after Automatic) and game volumes (percent).+constexpr int kBitrateCaps[] = {20, 15, 10, 5};+constexpr int kVolumes[] = {25, 50, 75, 100, 150};+std::vector<std::string> AppUi::settingOptions(int row) const {// Caller holds mutex_.std::vector<std::string> out;@@ -1245,6 +1249,11 @@ std::vector<std::string> AppUi::settingOptions(int row) const {// Updates: Cross acts, no list.} else if (row == 9) {out = {tr(Str::Deactivated), tr(Str::HighRefreshOn)};+ } else if (row == 10) {+ out.push_back(tr(Str::BitrateAuto));+ for (int mbps : kBitrateCaps) out.push_back(std::to_string(mbps) + " Mbps");+ } else if (row == 11) {+ for (int v : kVolumes) out.push_back(std::to_string(v) + " %");} else if (row == 8) {out.push_back(tr(Str::LoginCountryOff));for (const char* country : kLoginCountries) out.push_back(loginCountryName(country));@@ -1270,6 +1279,16 @@ int AppUi::settingSelected(int row) const {if (row == 6) return settings_.lightBarMode;if (row == 7) return 0;if (row == 9) return settings_.highRefresh ? 1 : 0;+ if (row == 10) {+ for (size_t i = 0; i < std::size(kBitrateCaps); ++i)+ if (kBitrateCaps[i] == settings_.maxBitrateMbps) return static_cast<int>(i) + 1;+ return 0;+ }+ if (row == 11) {+ for (size_t i = 0; i < std::size(kVolumes); ++i)+ if (kVolumes[i] == settings_.gameVolume) return static_cast<int>(i);+ return 3; // 100 %+ }if (row == 8) {for (size_t i = 0; i < std::size(kLoginCountries); ++i)if (settings_.loginCountry == kLoginCountries[i]) return static_cast<int>(i) + 1;@@ -1299,6 +1318,10 @@ void AppUi::applySetting(int row, int index) {} else if (row == 7) {} else if (row == 9) {settings_.highRefresh = index == 1;+ } else if (row == 10) {+ settings_.maxBitrateMbps = index == 0 ? 0 : kBitrateCaps[index - 1];+ } else if (row == 11) {+ settings_.gameVolume = kVolumes[index];} else if (row == 8) {settings_.loginCountry = index == 0 ? std::string() : kLoginCountries[index - 1];} else {@@ -3204,8 +3227,8 @@ void AppUi::drawSettings(Canvas& c) {const char* labels[kSettingRows] = {tr(Str::Language), tr(Str::Resolution), tr(Str::Region),tr(Str::Deadzone), tr(Str::TriggerRumble), tr(Str::ConfirmButton),tr(Str::LightBar), tr(Str::Updates), tr(Str::LoginCountry),- tr(Str::HighRefresh)};- constexpr int kRowW = 1200, kRowH = 56, kGap = 8;+ tr(Str::HighRefresh), tr(Str::BitrateCap), tr(Str::GameVolume)};+ constexpr int kRowW = 1200, kRowH = 50, kGap = 6;Rect rows[kSettingRows];int y = 262;for (int i = 0; i < kSettingRows; ++i) {diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex ce58c65..0dc3180 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -114,12 +114,14 @@ struct SettingsChoice {int deband = 3;int upscaler = 2;bool highRefresh = false; // 120 Hz output while a game streams+ int maxBitrateMbps = 0; // 0 automatic, else 20 / 15 / 10 / 5+ int gameVolume = 100; // percent: 25 / 50 / 75 / 100 / 150};// The largest stick dead zone Settings offers, in percent of the travel.constexpr int kMaxDeadzone = 30;-constexpr int kSettingRows = 10; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,- // sign-in country, 120 Hz output+constexpr int kSettingRows = 12; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,+ // sign-in country, 120 Hz output, bitrate cap, game volume// The countries "Sign in as another country" offers (xcloud::loginCountryAddress).constexpr const char* kLoginCountries[] = {"br", "jp", "kr", "pl", "us"};diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex 5e141e3..cd512c6 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -266,6 +266,9 @@ constexpr Column kEnglish = {"On (in games)", // HighRefreshOn"Unstable connection", // ConnectionUnstable"Session: %s", // SessionSummary+ "Maximum bitrate", // BitrateCap+ "Automatic", // BitrateAuto+ "Game volume", // GameVolume};constexpr Column kPortugueseBR = {@@ -502,6 +505,9 @@ constexpr Column kPortugueseBR = {"Ativada (nos jogos)", // HighRefreshOn"Conexão instável", // ConnectionUnstable"Sessão: %s", // SessionSummary+ "Bitrate máximo", // BitrateCap+ "Automático", // BitrateAuto+ "Volume do jogo", // GameVolume};constexpr Column kSpanish = {@@ -738,6 +744,9 @@ constexpr Column kSpanish = {"Activada (en los juegos)", // HighRefreshOn"Conexión inestable", // ConnectionUnstable"Sesión: %s", // SessionSummary+ "Bitrate máximo", // BitrateCap+ "Automático", // BitrateAuto+ "Volumen del juego", // GameVolume};constexpr Column kFrench = {@@ -974,6 +983,9 @@ constexpr Column kFrench = {"Activée (en jeu)", // HighRefreshOn"Connexion instable", // ConnectionUnstable"Session : %s", // SessionSummary+ "Débit maximal", // BitrateCap+ "Automatique", // BitrateAuto+ "Volume du jeu", // GameVolume};constexpr Column kGerman = {@@ -1210,6 +1222,9 @@ constexpr Column kGerman = {"An (in Spielen)", // HighRefreshOn"Instabile Verbindung", // ConnectionUnstable"Sitzung: %s", // SessionSummary+ "Maximale Bitrate", // BitrateCap+ "Automatisch", // BitrateAuto+ "Spiellautstärke", // GameVolume};constexpr Column kItalian = {@@ -1446,6 +1461,9 @@ constexpr Column kItalian = {"Attiva (nei giochi)", // HighRefreshOn"Connessione instabile", // ConnectionUnstable"Sessione: %s", // SessionSummary+ "Bitrate massimo", // BitrateCap+ "Automatico", // BitrateAuto+ "Volume del gioco", // GameVolume};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex 9d31c26..862d352 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -243,6 +243,9 @@ enum class Str {HighRefreshOn, // ... its "on" choice (while a game streams; the menus stay at 60 Hz)ConnectionUnstable, // in a game: frames lost, video stalled or the round trip far upSessionSummary, // notification at the end of a game (%s: minutes, resolution, Mbps, loss, ms)+ BitrateCap, // Settings row: the stream's bitrate cap (for Wi-Fi)+ BitrateAuto, // ... its default: the resolution's own+ GameVolume, // Settings row: the game's sound levelCount};