Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Report each shown frame's timings to the server, as the web client does

Rafael Abud Ferreirafcaacd3ef4de
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index c591db6..843e61b 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -38,7 +38,13 @@ struct StreamPlayer::Impl {
std::mutex mutex;
std::condition_variable cv;
- std::deque<std::vector<uint8_t>> frames;
+ // An access unit, with what the server wants to hear about it.
+ struct VideoFrame {
+ std::vector<uint8_t> data;
+ uint32_t rtpTimestamp = 0;
+ double arrivalMs = 0; // StreamSession::clockMs()
+ };
+ std::deque<VideoFrame> frames;
std::atomic<bool> running{false};
std::string endReason;
platform::Thread videoThread, audioThread;
@@ -109,7 +115,11 @@ struct StreamPlayer::Impl {
end("could not start the H.264 decoder");
return;
}
- std::vector<uint8_t> au;
+ VideoFrame frame;
+ std::vector<uint8_t>& au = frame.data;
+ // Timings of the frames handed to the decoder, by RTP timestamp:
+ // pictures can come out later than their input.
+ std::deque<stream::FrameMetadata> inFlight;
int fullStreak = 0;
while (running) {
size_t backlog;
@@ -117,7 +127,7 @@ struct StreamPlayer::Impl {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&] { return !running || !frames.empty(); });
if (!running) break;
- au = std::move(frames.front());
+ frame = std::move(frames.front());
frames.pop_front();
backlog = frames.size();
}
@@ -135,9 +145,26 @@ struct StreamPlayer::Impl {
media::Picture pic;
const bool first = decodedFrames == 0 && !loggedFirstDecode;
if (first) XC_LOGI("first video decode: %zu bytes", au.size());
+ stream::FrameMetadata meta;
+ meta.serverDataKey = frame.rtpTimestamp;
+ meta.firstPacketArrivalMs = frame.arrivalMs;
+ meta.submittedMs = session->clockMs();
+ inFlight.push_back(meta);
+ if (inFlight.size() > 16) inFlight.pop_front();
uint64_t t0 = platform::nowUs();
- bool ok = decoder.decode(au.data(), au.size(), pic);
+ bool ok = decoder.decode(au.data(), au.size(), pic, frame.rtpTimestamp);
uint64_t t1 = platform::nowUs();
+ bool known = false;
+ if (ok) {
+ for (auto it = inFlight.begin(); it != inFlight.end(); ++it)
+ if (it->serverDataKey == pic.tag) {
+ meta = *it;
+ inFlight.erase(inFlight.begin(), it + 1); // and anything older: never coming
+ known = true;
+ break;
+ }
+ meta.decodedMs = session->clockMs();
+ }
decodeUs += t1 - t0;
++decodeCalls;
atomicMax(decodeMaxUs, t1 - t0);
@@ -182,6 +209,12 @@ struct StreamPlayer::Impl {
}
display::present();
uint64_t t3 = platform::nowUs();
+ meta.renderedMs = session->clockMs();
+ if (known) session->reportFrame(meta);
+ if (decodedFrames % 600 == 1)
+ XC_LOGI("frame %u: queued %.1f, decoded %.1f, shown %.1f ms after arrival", meta.serverDataKey,
+ meta.submittedMs - meta.firstPacketArrivalMs, meta.decodedMs - meta.firstPacketArrivalMs,
+ meta.renderedMs - meta.firstPacketArrivalMs);
if (screenshot) saveScreen();
drawUs += t3 - t2;
++drawCalls;
@@ -195,7 +228,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) {
+ cb.video = [this](const uint8_t* d, size_t n, uint32_t rtpTimestamp) {
if (n == 0) { // the depacketizer emits these after loss
keyframeWanted = true;
return;
@@ -208,7 +241,7 @@ struct StreamPlayer::Impl {
frames.clear();
keyframeWanted = true;
}
- frames.emplace_back(d, d + n);
+ frames.push_back({std::vector<uint8_t>(d, d + n), rtpTimestamp, session->clockMs()});
cv.notify_one();
};
cb.audio = [this](const uint8_t* d, size_t n, uint32_t) {
diff --git a/src/media/decoder.cpp b/src/media/decoder.cpp
index 91911c3..f4bab8b 100644
--- a/src/media/decoder.cpp
+++ b/src/media/decoder.cpp
@@ -123,13 +123,14 @@ bool VideoDecoder::init(int threads) {
return true;
}
-bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out) {
+bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out, uint32_t tag) {
// An empty packet means "end of stream" to libavcodec and would switch it
// to draining for good; the RTP depacketizer emits them after packet loss.
pending_ = false;
if (!ctx_ || len == 0) return false;
packet_->data = const_cast<uint8_t*>(data);
packet_->size = static_cast<int>(len);
+ packet_->pts = tag;
int rc = avcodec_send_packet(ctx_, packet_);
if (rc == AVERROR_EOF) {
// Drained anyway: reset and retry once.
@@ -171,6 +172,7 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out) {
out.strideV = frame_->linesize[2];
out.width = frame_->width;
out.height = frame_->height;
+ out.tag = frame_->pts == AV_NOPTS_VALUE ? 0 : static_cast<uint32_t>(frame_->pts);
return true;
}
diff --git a/src/media/decoder.h b/src/media/decoder.h
index 2854566..5805b71 100644
--- a/src/media/decoder.h
+++ b/src/media/decoder.h
@@ -22,6 +22,8 @@ struct Picture {
const uint8_t* v = nullptr;
int strideY = 0, strideU = 0, strideV = 0;
int width = 0, height = 0;
+ // The `tag` the access unit it came from was decoded with.
+ uint32_t tag = 0;
};
// Splits an Annex-B H.264 stream into access units (offset, length): at AUD
@@ -43,7 +45,9 @@ public:
bool init(int threads = 1);
// One Annex-B access unit in; true with `out` filled when a picture is
// ready. A false return without a picture is normal at stream start.
- bool decode(const uint8_t* data, size_t len, Picture& out);
+ // `tag` travels with the access unit and comes back on its picture
+ // (a picture can come out later than its input).
+ bool decode(const uint8_t* data, size_t len, Picture& out, uint32_t tag = 0);
// True after a decode error: the caller should ask for a key frame.
bool needsKeyframe() const { return needsKeyframe_; }
// The last decode() returned no picture without an error: the decoder
diff --git a/src/stream/input_packet.cpp b/src/stream/input_packet.cpp
index 3751548..3f129e9 100644
--- a/src/stream/input_packet.cpp
+++ b/src/stream/input_packet.cpp
@@ -51,6 +51,28 @@ std::vector<uint8_t> clientMetadataReport(uint32_t sequence, double timestampMs,
return b;
}
+std::vector<uint8_t> metadataReport(uint32_t sequence, double timestampMs, const std::vector<FrameMetadata>& frames) {
+ size_t count = std::min<size_t>(frames.size(), 30);
+ auto b = header(kReportMetadata, sequence, timestampMs, kHeaderSize + 1 + count * 28);
+ size_t o = kHeaderSize;
+ put8(b, o++, static_cast<uint8_t>(count));
+ // Times in tenths of a millisecond, wrapping like the web client's
+ // DataView.setUint32.
+ auto tenths = [](double ms) { return static_cast<uint32_t>(static_cast<uint64_t>(ms * 10.0)); };
+ for (size_t i = frames.size() - count; i < frames.size(); ++i) {
+ const FrameMetadata& f = frames[i];
+ put32(b, o, f.serverDataKey);
+ put32(b, o + 4, tenths(f.firstPacketArrivalMs));
+ put32(b, o + 8, tenths(f.submittedMs));
+ put32(b, o + 12, tenths(f.decodedMs));
+ put32(b, o + 16, tenths(f.renderedMs));
+ put32(b, o + 20, tenths(timestampMs));
+ put32(b, o + 24, tenths(timestampMs));
+ o += 28;
+ }
+ return b;
+}
+
std::vector<uint8_t> gamepadReport(uint32_t sequence, double timestampMs, const GamepadFrame& f) {
auto b = header(kReportGamepad, sequence, timestampMs, kHeaderSize + 1 + 23);
size_t o = kHeaderSize;
diff --git a/src/stream/input_packet.h b/src/stream/input_packet.h
index f86abc9..19618d6 100644
--- a/src/stream/input_packet.h
+++ b/src/stream/input_packet.h
@@ -56,8 +56,19 @@ struct Vibration {
uint8_t repeat = 0;
};
+// When one video frame arrived, was decoded and was shown, on the client's
+// clock (ms). The server matches it to the frame by `serverDataKey`, the
+// frame's RTP timestamp, and measures the stream's latency with it.
+struct FrameMetadata {
+ uint32_t serverDataKey = 0;
+ double firstPacketArrivalMs = 0, submittedMs = 0, decodedMs = 0, renderedMs = 0;
+};
+
// The first report on the channel: announces the client (touch points).
std::vector<uint8_t> clientMetadataReport(uint32_t sequence, double timestampMs, uint8_t maxTouchPoints = 1);
+// Frame timings, as the web client sends after each frame it shows (at most
+// 30 per report).
+std::vector<uint8_t> metadataReport(uint32_t sequence, double timestampMs, const std::vector<FrameMetadata>& frames);
std::vector<uint8_t> gamepadReport(uint32_t sequence, double timestampMs, const GamepadFrame& frame);
// Server -> client reports. Return false when `data` is another report type.
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index c1bb6df..483958a 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -647,6 +647,13 @@ void StreamSession::requestKeyframe() {
XC_LOGW("keyframe request: %s", e.what());
}
}
+void StreamSession::reportFrame(const FrameMetadata& frame) {
+ if (!impl_->open) return;
+ Impl::sendBinary(impl_->input, metadataReport(impl_->inputSequence++, impl_->nowMs(), {frame}));
+}
+
+double StreamSession::clockMs() const { return impl_->nowMs(); }
+
void StreamSession::completeTextInput(const std::string& id, const std::string& text) {
json::Value v = json::Value::object();
v.set("Text", text);
diff --git a/src/stream/stream_session.h b/src/stream/stream_session.h
index 3b54e42..e8aa210 100644
--- a/src/stream/stream_session.h
+++ b/src/stream/stream_session.h
@@ -78,6 +78,10 @@ public:
void sendGamepad(const GamepadFrame& frame);
void requestKeyframe();
+ // A frame shown: its timings go back to the server (see FrameMetadata).
+ void reportFrame(const FrameMetadata& frame);
+ // The clock FrameMetadata times are on, in ms.
+ double clockMs() const;
void completeTextInput(const std::string& id, const std::string& text);
void cancelTextInput(const std::string& id);
// Another stream tier mid-session (StreamOptions::resolutionAlias).
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 6edf7cf..ad9af94 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -94,6 +94,20 @@ static void testInputPacket() {
CHECK(p[30] == 1 && p[33] == 0); // physicality LE
CHECK(p[34] == 0 && p[37] == 1); // virtual physicality BE
+ FrameMetadata fm;
+ fm.serverDataKey = 0x01020304;
+ fm.firstPacketArrivalMs = 100.0;
+ fm.submittedMs = 100.05;
+ fm.decodedMs = 102.5;
+ fm.renderedMs = 110.0;
+ auto md = metadataReport(9, 111.0, {fm});
+ CHECK(md.size() == 14 + 1 + 28);
+ CHECK(md[0] == 1 && md[1] == 0 && md[2] == 9 && md[14] == 1);
+ CHECK(md[15] == 0x04 && md[18] == 0x01); // RTP timestamp, little-endian
+ CHECK(md[19] == 0xE8 && md[20] == 0x03); // 100 ms = 1000 tenths
+ CHECK(md[27] == 0x01 && md[28] == 0x04); // 102.5 ms = 1025
+ CHECK(md[39] == 0x56 && md[40] == 0x04); // report time 111 ms = 1110
+
uint8_t vib[13] = {128, 0, 0, 0, 50, 25, 0, 0, 0x10, 0x00, 0, 0, 1};
Vibration v;
CHECK(parseVibration(vib, sizeof vib, v) && v.leftMotor == 50 && v.rightMotor == 25 && v.durationMs == 16);