Xbox Cloud Gaming app for PS5 Homebrew
C
Stream robustness: no freeze after a burst of loss, safe teardown, audio
Rafael Abud Ferreira06dff0a755e0
diff --git a/CMakeLists.txt b/CMakeLists.txtindex de5dd6f..cd6b75c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -118,6 +118,6 @@ else()enable_testing()add_executable(xcloud-tests tests/test_main.cpp)- target_link_libraries(xcloud-tests PRIVATE xcloud_stream xcloud_media xcloud_ui xc_ffmpeg)+ target_link_libraries(xcloud-tests PRIVATE xcloud_stream xcloud_media xcloud_ui xc_ffmpeg datachannel-static)add_test(NAME unit COMMAND xcloud-tests)endif()diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex 2ff29bd..2729fb1 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -63,6 +63,7 @@ void loadAutoplay() {if (opt == "cpudisplay") g_autoplay.cpuDisplay = true;if (opt == "hwdecode") g_autoplay.hwDecode = true;if (opt == "droptest") g_autoplay.dropTest = true;+ if (opt.rfind("loss=", 0) == 0) g_autoplay.videoLoss = std::atoi(opt.c_str() + 5);if (opt == "ai") g_autoplay.upscaler = 1;if (opt == "restore") g_autoplay.restore = true;if (opt.rfind("swap=", 0) == 0) display::gpu::setSwapImages(std::atoi(opt.c_str() + 5));diff --git a/src/app/autoplay.h b/src/app/autoplay.hindex 72265d2..bb58cac 100644--- a/src/app/autoplay.h+++ b/src/app/autoplay.h@@ -7,7 +7,8 @@// dump, repeat, idle (no A presses), threads=N (H.264 decoder threads),// rumbletest (rumbles the pad for 1.5 s at start), triggertest (the triggers// for 3 s), vibetest (each motor and trigger alone, announced, no game),-// droptest (the connection dropped at 20 s: the stream reconnects), detailtest (opens a game to+// droptest (the connection dropped at 20 s: the stream reconnects), loss=N+// (N% of the video packets held back until NACKed), detailtest (opens a game to// buy far down the list instead of playing, saves detail.ppm), imetest (opens// the system keyboard on the home screen), menutest (in the game: the menu,// 720p, back to 1080p), res=720p|1080p|1080p-hq|1440p, sharp=0..3 and@@ -52,6 +53,7 @@ struct Autoplay {bool imeTest = false; // open the system keyboard on the home screenbool menuTest = false; // in the game: open the menu, switch to 720pint decodeThreads = 1;+ int videoLoss = 0; // loss=N: N% of the video packets held back, delivered when NACKedint deband = -1; // deband=0..3: instead of the settingint sharpness = -1; // sharp=0..3: instead of the settingstd::string resolution; // res=720p|1080p|1440p: instead of the settingdiff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex ef39712..cc17565 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -83,6 +83,7 @@ struct StreamPlayer::Impl {std::atomic<uint64_t> displayUs{0}, displayCount{0}, displayMaxUs{0};std::atomic<uint64_t> decodeUs{0}, decodeCalls{0}, decodeMaxUs{0}, drawUs{0}, drawCalls{0}, drawMaxUs{0};int decodeThreads = 1;+ int simulatedLoss = 0;bool hwProbe = false;static void atomicMax(std::atomic<uint64_t>& a, uint64_t v) {@@ -108,9 +109,26 @@ struct StreamPlayer::Impl {std::atomic<float> micGain{1.0f};std::atomic<uint32_t> audioSendTimestamp{0};bool encoderInitialized = false;+ // Opening and closing the microphone happen on several threads (start,+ // reconnect, the end of the stream): one at a time.+ std::mutex micMutex;++ void closeMic() {+ std::lock_guard<std::mutex> lock(micMutex);+ audioIn.close();+ input::setEmbeddedMicActive(false);+ }void updateMicState() {+ std::lock_guard<std::mutex> lock(micMutex);if (!running) return;+ if (!micEnabled) {+ if (audioIn.isRecording()) {+ audioIn.close();+ input::setEmbeddedMicActive(false);+ }+ return;+ }if (!audioIn.isRecording()) {if (!encoderInitialized) {encoderInitialized = audioEncoder.init(24000);@@ -141,8 +159,7 @@ struct StreamPlayer::Impl {explicit Impl(xcloud::GssvClient& g) : gssv(g) {}void end(const std::string& reason) {- audioIn.close();- input::setEmbeddedMicActive(false);+ closeMic();{std::lock_guard<std::mutex> lock(mutex);if (endReason.empty()) endReason = reason;@@ -431,6 +448,7 @@ struct StreamPlayer::Impl {: gssv.resolution() == xcloud::Resolution::P1440 ? 40000000: gssv.resolution() == xcloud::Resolution::P1080HQ ? 30000000: 25000000;+ opts.simulatedVideoLoss = simulatedLoss;if (const char* loss = std::getenv("XC_SIM_LOSS")) opts.simulatedVideoLoss = std::atoi(loss);callbacks = cb;options = opts;@@ -594,12 +612,13 @@ struct StreamPlayer::Impl {if (auto s = current()) s->close();if (videoThread.joinable()) videoThread.join();if (audioThread.joinable()) audioThread.join();+ std::shared_ptr<stream::StreamSession> last;{std::lock_guard<std::mutex> lock(sessionMutex);- session.reset();+ last = std::move(session);}- audioIn.close();- input::setEmbeddedMicActive(false);+ last.reset(); // its teardown waits for libdatachannel's callbacks: not under the lock+ closeMic();media::audioStop();for (int i = 0; i < input::kMaxPads; ++i) {input::setRumble(0, 0, 0, i);@@ -716,6 +735,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::setSimulatedLoss(int percent) { impl_->simulatedLoss = std::clamp(percent, 0, 50); }StreamPlayer::Stats StreamPlayer::stats() const {Stats st;diff --git a/src/app/stream_player.h b/src/app/stream_player.hindex 06080de..dd753db 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);+ // 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 hardware// decoder and log how it does (the picture still comes from FFmpeg).void setHwDecodeProbe(bool on);diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 14a56e8..2638959 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -67,10 +67,12 @@ std::string stream(xcloud::GssvClient& gssv) {app::StreamPlayer player(gssv);if (g_autoplay.dump) player.dumpVideo(platform::dataDir() + "/stream.aus", 20);player.setDecodeThreads(g_autoplay.decodeThreads);+ player.setSimulatedLoss(g_autoplay.videoLoss);player.setHwDecodeProbe(g_autoplay.hwDecode);{std::lock_guard<std::mutex> lock(g_settingsMutex);player.setMicGain(g_settings.micGain);+ player.setMicEnabled(g_settings.micEnabled);media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));}std::string err;diff --git a/src/display/gpu.cpp b/src/display/gpu.cppindex 54279e8..ea37435 100644--- a/src/display/gpu.cpp+++ b/src/display/gpu.cpp@@ -157,7 +157,12 @@ std::atomic<uint64_t> g_shownId{0}, g_shownAtUs{0};uint64_t g_acquireWaitUs = 0, g_acquireWaitMaxUs = 0, g_acquires = 0;bool fail(const char* step, VkResult r) {- XC_LOGE("gpu: %s failed (%d)", step, static_cast<int>(r));+ // Acquire, submit and present fail every frame when they fail at all:+ // the first ones, then one in 600 (10 s).+ static std::atomic<uint64_t> failures{0};+ uint64_t n = failures++;+ if (n < 10 || n % 600 == 0) XC_LOGE("gpu: %s failed (%d), failure %llu", step, static_cast<int>(r),+ static_cast<unsigned long long>(n + 1));return false;}diff --git a/src/media/audio_out.cpp b/src/media/audio_out.cppindex af01408..59e8d97 100644--- a/src/media/audio_out.cpp+++ b/src/media/audio_out.cpp@@ -55,7 +55,10 @@ void loop() {// Blocks until the hardware wants the next grain (5.3 ms).int rc = sceAudioOutOutput(h, grain.data());if (rc < 0) {- XC_LOGW("sceAudioOutOutput: 0x%08x", static_cast<unsigned>(rc));+ static uint64_t failures = 0; // this thread only+ if (failures++ % 200 == 0) // the first, then one a second or so+ XC_LOGW("sceAudioOutOutput: 0x%08x (failure %llu)", static_cast<unsigned>(rc),+ static_cast<unsigned long long>(failures));std::this_thread::sleep_for(std::chrono::milliseconds(5));if (!g_running) break;}diff --git a/src/media/decoder.cpp b/src/media/decoder.cppindex ba1bf33..e4d3f8d 100644--- a/src/media/decoder.cpp+++ b/src/media/decoder.cpp@@ -155,13 +155,23 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out, uint32_len, len > 4 ? data[4] & 0x1f : -1);return false;}+ if (sent == AVERROR(EAGAIN)) {+ // The decoder was full and didn't take this packet: now that a+ // picture came out, hand it over again (it used to be lost, and the+ // pictures after it decoded against a missing reference).+ int again = avcodec_send_packet(ctx_, packet_);+ if (again < 0) {+ needsKeyframe_ = true;+ if (failuresLogged_++ < 20) XC_LOGI("h264 packet dropped: %s (%zu bytes)", averr(again).c_str(), len);+ }+ }if (frame_->decode_error_flags || (frame_->flags & AV_FRAME_FLAG_CORRUPT)) {needsKeyframe_ = true;} else if (frame_->flags & AV_FRAME_FLAG_KEY) {needsKeyframe_ = false;}if (frame_->format != AV_PIX_FMT_YUV420P && frame_->format != AV_PIX_FMT_YUVJ420P) {- XC_LOGW("unexpected pixel format %d", frame_->format);+ if (failuresLogged_++ < 20) XC_LOGW("unexpected pixel format %d", frame_->format);return false;}out.y = frame_->data[0];@@ -206,10 +216,17 @@ bool AudioDecoder::init() {}bool AudioDecoder::decode(const uint8_t* data, size_t len, std::vector<float>& out) {- if (!ctx_) return false;+ // An empty packet is "end of stream" to libavcodec: every packet after+ // it would be refused (no sound for the rest of the session).+ if (!ctx_ || !data || len == 0) return false;packet_->data = const_cast<uint8_t*>(data);packet_->size = static_cast<int>(len);- if (avcodec_send_packet(ctx_, packet_) < 0) return false;+ int rc = avcodec_send_packet(ctx_, packet_);+ if (rc == AVERROR_EOF) { // drained anyway: reset and retry once+ avcodec_flush_buffers(ctx_);+ rc = avcodec_send_packet(ctx_, packet_);+ }+ if (rc < 0) return false;bool any = false;while (avcodec_receive_frame(ctx_, frame_) == 0) {int n = frame_->nb_samples;diff --git a/src/stream/h264_receiver.cpp b/src/stream/h264_receiver.cppindex e2492f2..3f2a232 100644--- a/src/stream/h264_receiver.cpp+++ b/src/stream/h264_receiver.cpp@@ -183,12 +183,20 @@ bool H264Receiver::resync(rtc::message_vector& out) {++cur;++s;}- if (cur == packets_.end() || cur->first != s) return false; // incomplete yet+ if (cur == packets_.end()) return false; // the last frame isn't complete yet+ if (cur->first != s) {+ // A hole in this frame (lost for good, or not here yet): look on+ // from the hole for a later key frame instead of waiting for this+ // one, which was the freeze after a burst of loss.+ it = std::prev(cur);+ continue;+ }std::vector<uint8_t> frame;bool key = false;if (assemble(it->first, s, frame, key) && key) {nextSeq_ = it->first;packets_.erase(packets_.begin(), it); // older junk+ for (auto e = missing_.begin(); e != missing_.end() && e->first < nextSeq_;) e = missing_.erase(e);(void)out;return true;}@@ -309,6 +317,10 @@ void H264Receiver::incoming(rtc::message_vector& messages, const rtc::message_ca}resendNacks(now, send);drain(now, out, send);+ // 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).+ if (nextSeq_ < 0 && !packets_.empty()) askKeyframe(send);if (packets_.size() > kMaxBuffered) { // stuck: start overpackets_.clear();missing_.clear();diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex b80dad2..7137719 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -107,6 +107,13 @@ struct StreamSession::Impl {uint64_t lastKeyframeMs = 0;VideoReceiveStats videoStats;std::shared_ptr<RtcpReporter> videoReporter;+ // The video receiver (a media handler, which libdatachannel may still be+ // running after the session is gone) reaches the session through this.+ struct Guard {+ std::mutex mutex;+ Impl* self = nullptr;+ };+ std::shared_ptr<Guard> guard = std::make_shared<Guard>();std::atomic<int> otherInputReports{0};Impl(xcloud::GssvClient& g, StreamCallbacks c, StreamOptions o) : gssv(g), cb(std::move(c)), opt(o) {}@@ -470,11 +477,13 @@ struct StreamSession::Impl {video = pc->addTrack(v);// Our jitter buffer (NACK, whole frames only) in place of// H264RtpDepacketizer, which hands over frames with holes in them.+ guard->self = this;auto videoReceiver = std::make_shared<H264Receiver>(- [this] {- if (!open) return;+ [g = guard] {+ std::lock_guard<std::mutex> lock(g->mutex);+ if (!g->self || !g->self->open) return;try {- requestKeyframe();+ g->self->requestKeyframe();} catch (const std::exception& e) {XC_LOGW("keyframe request: %s", e.what());}@@ -623,6 +632,27 @@ struct StreamSession::Impl {}}+ // Before the session goes: no callback of libdatachannel's (they hold+ // `this`) may run any more. Each reset waits for a call in progress.+ void detach() {+ {+ std::lock_guard<std::mutex> lock(guard->mutex);+ guard->self = nullptr;+ }+ try {+ for (const auto& ch : {chat, control, input, message})+ if (ch) ch->resetCallbacks();+ for (const auto& track : {audio, video})+ if (track) {+ track->onFrame(nullptr);+ track->resetCallbacks();+ }+ if (pc) pc->resetCallbacks();+ } catch (const std::exception& e) {+ XC_LOGW("detaching the session: %s", e.what());+ }+ }+void close() {open = false;if (pc) {@@ -641,6 +671,7 @@ StreamSession::StreamSession(xcloud::GssvClient& gssv, StreamCallbacks callbacksStreamSession::~StreamSession() {impl_->closedNotified = true; // no callback while tearing downimpl_->close();+ impl_->detach();}bool StreamSession::start(std::string& err) {diff --git a/tests/test_main.cpp b/tests/test_main.cppindex d63b81f..11f17d2 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -8,6 +8,7 @@#include "app/crash_guard.h"#include "app/report.h"#include "media/audio_encoder.h"+#include "media/decoder.h"#include "input/tuning.h"#include "net/http.h"#include "platform/platform.h"@@ -19,6 +20,8 @@#include "ui/strings.h"#include "util/json.h"#include "auth/auth_manager.h"+#include "stream/h264_receiver.h"+#include "platform/platform.h"#include "auth/msa.h"#include "ui/image_cache.h"#include "xcloud/gssv.h"@@ -839,6 +842,64 @@ 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).+static void testH264Resync() {+ xc::stream::VideoReceiveStats stats;+ int keyframeAsks = 0;+ xc::stream::H264Receiver rx([&] { ++keyframeAsks; }, stats);+ auto packet = [](uint16_t seq, uint32_t ts, bool marker, uint8_t nal) {+ std::vector<uint8_t> b = {0x80, static_cast<uint8_t>((marker ? 0x80 : 0) | 102),+ static_cast<uint8_t>(seq >> 8), static_cast<uint8_t>(seq),+ static_cast<uint8_t>(ts >> 24), static_cast<uint8_t>(ts >> 16),+ static_cast<uint8_t>(ts >> 8), static_cast<uint8_t>(ts), 0, 0, 0, 7,+ nal, 0xAA, 0xBB};+ return rtc::make_message(reinterpret_cast<const std::byte*>(b.data()),+ reinterpret_cast<const std::byte*>(b.data()) + b.size());+ };+ size_t keyframesOut = 0, framesOut = 0;+ auto feed = [&](rtc::message_vector in) {+ rx.incoming(in, [](rtc::message_ptr) { return true; });+ for (const auto& m : in) {+ ++framesOut;+ if (m->size() > 4 && (static_cast<uint8_t>((*m)[4]) & 0x1F) == 5) ++keyframesOut;+ }+ };+ // The end of a frame from before (a boundary to start at), a key frame, a P frame.+ feed({packet(0, 0, true, 0x41), packet(1, 1500, true, 0x65), packet(2, 3000, true, 0x41)});+ CHECK(framesOut == 2 && keyframesOut == 1);+ // seq 4 never comes; seq 7 never comes; 9-10 a key frame.+ feed({packet(3, 4500, false, 0x41), packet(5, 6000, true, 0x41), packet(6, 7500, false, 0x41),+ packet(8, 7500, true, 0x41), packet(9, 9000, false, 0x65), packet(10, 9000, true, 0x65)});+ CHECK(framesOut == 2); // waiting for the retransmission+ xc::platform::sleepMs(200);+ feed({});+ CHECK(keyframesOut == 2); // resumed at the key frame+ CHECK(framesOut == 3);+ CHECK(stats.framesDropped >= 1);+ CHECK(keyframeAsks >= 1);+}++// An empty audio packet (seen after loss) must not end the sound.+static void testAudioDecoderEmptyPacket() {+ xc::media::AudioEncoder enc;+ xc::media::AudioDecoder dec;+ CHECK(enc.init(24000));+ CHECK(dec.init());+ std::vector<int16_t> pcm(960);+ for (size_t i = 0; i < pcm.size(); ++i) pcm[i] = static_cast<int16_t>(8000.0 * std::sin(i * 0.05));+ std::vector<uint8_t> opus;+ std::vector<float> out;+ CHECK(enc.encode(pcm.data(), pcm.size(), opus));+ CHECK(dec.decode(opus.data(), opus.size(), out));+ CHECK(!dec.decode(nullptr, 0, out));+ out.clear();+ CHECK(enc.encode(pcm.data(), pcm.size(), opus));+ CHECK(dec.decode(opus.data(), opus.size(), out));+ CHECK(!out.empty());+}+int main() {testReport();testCrashGuard();@@ -850,6 +911,8 @@ int main() {testSubscriptionPlan();testMicrosoftHost();testAudioEncoder();+ testH264Resync();+ testAudioDecoderEmptyPacket();testAutoDeband();testControllerTuning();testUpdater();