Xbox Cloud Gaming app for PS5 Homebrew
C
fix(ps4): restore 60 fps pipeline, libSceVideodec2 flush, SSE2 BT.709, and thread affinities
Rafael Abud Ferreira5e18fd3da475
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 06573e8..5c0652f 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -201,6 +201,7 @@ elseif(XC_TARGET_PS4)datachannel-static-lSceVideodec2-lSceVideoOut+ -lSceGnmDriver-lScePad-lSceAudioOut-lSceAudioIndiff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex 3027c8f..c6a1c9e 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -254,7 +254,6 @@ ui::UiCaps uiCaps() {bool coreStartup() {platform::init();- platform::setThreadAffinity(platform::ThreadRole::Main, "xcloud_main");const std::string dataDir = platform::dataDir();const std::string logPath = dataDir + "/xcloud.log";const std::string prevLogPath = dataDir + "/xcloud.prev.log";@@ -725,6 +724,7 @@ bool coreStartup() {g_core->streamScreen.emplace(fonts);g_core->streamScreen->setCaps(uiCaps());crash::startWatchdog(15000); // a main loop stuck for 15 s leaves a marker+ platform::setThreadAffinity(platform::ThreadRole::Main, "xcloud_main");return true;}@@ -1303,6 +1303,10 @@ void coreShutdown() {if (!workerDone || !pricesDone)XC_LOGW("closing: %s%s%s still busy, left to the exit", workerDone ? "" : "the worker",!workerDone && !pricesDone ? " and " : "", pricesDone ? "" : "the price loop");+ if (g_images) {+ g_images->stop();+ g_images.reset();+ }shell::beforeShutdown();input::shutdown();display::shutdown();diff --git a/src/app/price_loop.cpp b/src/app/price_loop.cppindex 7507243..fc14e94 100644--- a/src/app/price_loop.cpp+++ b/src/app/price_loop.cpp@@ -84,6 +84,7 @@ void setQueueClient(const xcloud::GssvClient* gssv) {namespace {void priceLoop() {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_price");json::Value cache = json::Value::object();{std::string text;diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex 2c1d7c6..c8832e6 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -127,6 +127,24 @@ struct StreamPlayer::Impl {std::atomic<uint32_t> audioSendTimestamp{0};bool encoderInitialized = false;platform::Thread inputThread;+ platform::Thread snapshotThread;+ platform::Thread screenThread;+ struct LatestPicture {+ media::Picture pic;+ std::vector<uint8_t> yPlane;+ std::vector<uint8_t> uPlane;+ std::vector<uint8_t> vPlane;+ stream::FrameMetadata meta;+ bool known = false;+ bool isHw = false;+ uint64_t arrivalUs = 0;+ uint64_t seq = 0;+ };+ std::mutex presentMutex;+ std::condition_variable presentCv;+ LatestPicture latestPic;+ uint64_t consumedPicSeq = 0;+ bool presentStop = false;std::mutex inputMutex;std::condition_variable inputCv;std::array<stream::GamepadFrame, input::kMaxPads> pendingPads{};@@ -191,6 +209,11 @@ struct StreamPlayer::Impl {}running = false;cv.notify_all();+ {+ std::lock_guard<std::mutex> lock(presentMutex);+ presentStop = true;+ }+ presentCv.notify_all();{std::lock_guard<std::mutex> lock(audioMutex_);}@@ -328,6 +351,104 @@ struct StreamPlayer::Impl {}}+ void asyncPresentLoop() {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "ps4_present");+ constexpr uint64_t kShownRing = 8;+ std::pair<uint64_t, uint64_t> inScreenQueue[kShownRing] = {}; // present id, arrival us+ uint64_t lastShownId = 0;+ uint64_t lastFramePresentUs = 0;+ bool loggedFirstPresent = false;+ LatestPicture cur;++ while (running) {+ {+ std::unique_lock<std::mutex> lock(presentMutex);+ presentCv.wait(lock, [&] { return !running || presentStop || latestPic.seq > consumedPicSeq; });+ if (!running || presentStop) break;+ consumedPicSeq = latestPic.seq;+ cur.pic = latestPic.pic;+ cur.meta = latestPic.meta;+ cur.known = latestPic.known;+ cur.isHw = latestPic.isHw;+ cur.arrivalUs = latestPic.arrivalUs;+ cur.seq = latestPic.seq;+ if (!cur.isHw) {+ cur.yPlane.swap(latestPic.yPlane);+ cur.uPlane.swap(latestPic.uPlane);+ cur.vPlane.swap(latestPic.vPlane);+ cur.pic.y = cur.yPlane.data();+ cur.pic.u = cur.uPlane.data();+ cur.pic.v = cur.pic.format == media::Picture::Format::Nv12 ? nullptr : cur.vPlane.data();+ }+ }++ bool screenshot = saveSnapshotIfAsked(cur.pic);+ std::lock_guard<std::recursive_mutex> lock(display::frameMutex());+ if (!loggedFirstPresent) {+ XC_LOGI("first draw %dx%d (%s, %s)", cur.pic.width, cur.pic.height,+ cur.pic.format == media::Picture::Format::Nv12 ? "NV12" : "YUV420P",+ cur.isHw ? "hardware" : "software");+ }+ uint64_t t2 = platform::nowUs();+ auto drawPic = [](const media::Picture& p, bool wait) {+ if (p.format == media::Picture::Format::Nv12) {+ return display::drawNv12(p.y, p.u, p.strideY, p.strideU, p.width, p.height, wait);+ }+ return display::drawYuv420(p.y, p.u, p.v, p.strideY, p.strideU, p.strideV, p.width, p.height, wait);+ };+ bool drawn = drawPic(cur.pic, false);+ if (!drawn) {+ drawn = drawPic(cur.pic, true);+ }+ if (!drawn) {+ ++lateFrames;+ continue;+ }+ uint64_t tDrawDone = platform::nowUs();+ display::present();+ uint64_t t3 = platform::nowUs();+ if (lastFramePresentUs > 0) {+ float dt = static_cast<float>(t3 - lastFramePresentUs) / 1000.0f;+ if (dt > 0.0f && dt < 250.0f) {+ std::lock_guard<std::mutex> lk(frametimesMutex);+ frametimesRing[frametimesHead % kFrametimeRing] = dt;+ ++frametimesHead;+ if (frametimesCount < kFrametimeRing) ++frametimesCount;+ }+ }+ lastFramePresentUs = t3;+ if (uint64_t id = display::lastPresentId()) {+ inScreenQueue[id % kShownRing] = {id, cur.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);+ }+ }+ }+ cur.meta.renderedMs = stream::clockMs();+ if (auto s = current(); s && cur.known) s->reportFrame(cur.meta);+ if (!loggedFirstPresent || (drawCalls % 600 == 0))+ XC_LOGI("frame %u: queued %.1f, decoded %.1f, shown %.1f ms after arrival", cur.meta.serverDataKey,+ cur.meta.submittedMs - cur.meta.firstPacketArrivalMs,+ cur.meta.decodedMs - cur.meta.firstPacketArrivalMs,+ cur.meta.renderedMs - cur.meta.firstPacketArrivalMs);+ if (screenshot) saveScreen();+ drawUs += tDrawDone - t2;+ ++drawCalls;+ atomicMax(drawMaxUs, tDrawDone - t2);+ if (!loggedFirstPresent) {+ loggedFirstPresent = true;+ XC_LOGI("first frame presented");+ }+ }+ }+void videoLoop() {platform::setThreadAffinity(platform::ThreadRole::VideoDecode, "xcloud_vdec");media::VideoDecoder decoder;@@ -336,6 +457,31 @@ struct StreamPlayer::Impl {return;}isHwDecode = decoder.isHardware();+ const bool useAsyncPresent = display::caps().asyncPresent;+ platform::Thread presentThread;+ if (useAsyncPresent) {+ {+ std::lock_guard<std::mutex> lock(presentMutex);+ latestPic.seq = 0;+ consumedPicSeq = 0;+ presentStop = false;+ }+ platform::startThread(presentThread, [this] { asyncPresentLoop(); }, 512u << 10);+ }+ struct PresentJoinGuard {+ Impl* self;+ platform::Thread& t;+ bool active;+ ~PresentJoinGuard() {+ if (!active) return;+ {+ std::lock_guard<std::mutex> lock(self->presentMutex);+ self->presentStop = true;+ }+ self->presentCv.notify_all();+ if (t.joinable()) t.join();+ }+ } presentGuard{this, presentThread, useAsyncPresent};VideoFrame frame;std::vector<uint8_t>& au = frame.data;// Timings of the frames handed to the decoder, by RTP timestamp:@@ -427,6 +573,33 @@ struct StreamPlayer::Impl {++qpCount;}pictureSize = (static_cast<uint32_t>(pic.width) << 16) | static_cast<uint32_t>(pic.height);+ if (useAsyncPresent) {+ {+ std::lock_guard<std::mutex> lock(presentMutex);+ if (latestPic.seq > consumedPicSeq) {+ ++droppedFrames;+ }+ latestPic.pic = pic;+ latestPic.meta = meta;+ latestPic.known = known;+ latestPic.isHw = decoder.isHardware();+ latestPic.arrivalUs = frame.arrivalUs;+ ++latestPic.seq;+ if (!latestPic.isHw) {+ size_t yBytes = static_cast<size_t>(pic.strideY) * pic.height;+ size_t uvH = (pic.height + 1) / 2;+ size_t uBytes = static_cast<size_t>(pic.strideU) * uvH;+ latestPic.yPlane.assign(pic.y, pic.y + yBytes);+ latestPic.uPlane.assign(pic.u, pic.u + uBytes);+ if (pic.format != media::Picture::Format::Nv12 && pic.v) {+ size_t vBytes = static_cast<size_t>(pic.strideV) * uvH;+ latestPic.vPlane.assign(pic.v, pic.v + vBytes);+ }+ }+ }+ 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.@@ -727,12 +900,13 @@ struct StreamPlayer::Impl {o[1] = clamp((c - 218 * d - 546 * e + 512) >> 10);o[2] = clamp((c + 2163 * d + 512) >> 10);}- std::thread([path, rgb = std::move(rgb), w, h]() mutable {+ if (snapshotThread.joinable()) snapshotThread.join();+ platform::startThread(snapshotThread, [path, rgb = std::move(rgb), w, h]() mutable {std::string data = "P6\n" + std::to_string(w) + " " + std::to_string(h) + "\n255\n";data.append(reinterpret_cast<const char*>(rgb.data()), rgb.size());bool ok = platform::writeFileAtomic(path, data);XC_LOGI("snapshot %dx%d -> %s: %s", w, h, path.c_str(), ok ? "ok" : "failed");- }).detach();+ }, 512u << 10);return true;}@@ -743,7 +917,8 @@ struct StreamPlayer::Impl {int w = 0, h = 0;if (!display::readBackRgb(rgb, w, h)) return;std::string path = screenPath;- std::thread([path, rgb = std::move(rgb), w, h]() mutable {+ if (screenThread.joinable()) screenThread.join();+ platform::startThread(screenThread, [path, rgb = std::move(rgb), w, h]() mutable {try {std::string data = "P6\n" + std::to_string(w) + " " + std::to_string(h) + "\n255\n";data.append(reinterpret_cast<const char*>(rgb.data()), rgb.size());@@ -753,7 +928,7 @@ struct StreamPlayer::Impl {} catch (const std::exception& e) {XC_LOGW("screen thread error: %s", e.what());}- }).detach();+ }, 512u << 10);} catch (const std::exception& e) {XC_LOGW("saveScreen failed: %s", e.what());}@@ -801,6 +976,8 @@ struct StreamPlayer::Impl {if (inputThread.joinable()) inputThread.join();if (videoThread.joinable()) videoThread.join();if (audioThread.joinable()) audioThread.join();+ if (snapshotThread.joinable()) snapshotThread.join();+ if (screenThread.joinable()) screenThread.join();std::shared_ptr<stream::StreamSession> last;{std::lock_guard<std::mutex> lock(sessionMutex);diff --git a/src/app/web_server.cpp b/src/app/web_server.cppindex a4008f4..9d2c1e4 100644--- a/src/app/web_server.cpp+++ b/src/app/web_server.cpp@@ -139,6 +139,7 @@ void WebServer::stop() {}void WebServer::threadLoop() {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_web");while (running_.load()) {pollfd pfd{listenFd_, POLLIN, 0};int pr = ::poll(&pfd, 1, 250);diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 6a98aea..9391a33 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -271,9 +271,13 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {setPriceAuth(g_xblAuth, g_xuid);platform::notify(ui::trf(ui::Str::SignedInAs, am.profile().gamertag), "signed in (notification)");static bool updateChecked = false;+ static platform::Thread s_updateThread;if (!updateChecked && (g_autoplay.title.empty() || !g_autoplay.updateFeed.empty())) {updateChecked = true;- std::thread(checkForUpdate).detach();+ platform::startThread(s_updateThread, [] {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_upd");+ checkForUpdate();+ }, 512u << 10);}std::vector<std::string> regions;for (const auto& r : gssv.session().regions) regions.push_back(r.name);@@ -523,6 +527,7 @@ namespace {std::mutex g_workerStateMutex;std::condition_variable g_workerStateCv;int g_workerState = 0;+platform::Thread g_workerThread;void setWorkerState(int state) {{@@ -536,10 +541,10 @@ void setWorkerState(int state) {void startWorker() {setWorkerState(1);- std::thread([] {+ platform::startThread(g_workerThread, [] {worker();setWorkerState(2);- }).detach();+ }, 2u << 20);}void requestQuit() {@@ -548,11 +553,19 @@ void requestQuit() {}bool waitForWorker(uint32_t ms) {- std::unique_lock<std::mutex> lock(g_workerStateMutex);- return g_workerStateCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_workerState != 1; });+ bool done = false;+ {+ std::unique_lock<std::mutex> lock(g_workerStateMutex);+ done = g_workerStateCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_workerState != 1; });+ }+ if (done && g_workerThread.joinable()) {+ g_workerThread.join();+ }+ return done;}void worker() {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_worker");if (g_autoplay.title == "BENCH") {platform::Thread t; // same big stack as the stream's video threadplatform::startThread(t, runDecodeBench);diff --git a/src/display/display.h b/src/display/display.hindex e4e8f4d..6ebd72f 100644--- a/src/display/display.h+++ b/src/display/display.h@@ -68,6 +68,7 @@ struct DisplayCaps {bool sharpen = false; // setSharpnessbool highRefreshSwitch = false; // setHighRefreshbool presentTiming = false; // lastPresentId / lastShown+ bool asyncPresent = false; // decouple YUV->RGBA conversion & flip wait onto a present thread};DisplayCaps caps();diff --git a/src/display/display_ps4.cpp b/src/display/display_ps4.cppindex 25185c9..fac2497 100644--- a/src/display/display_ps4.cpp+++ b/src/display/display_ps4.cpp@@ -21,6 +21,14 @@#include <orbis/libkernel.h>#include <orbis/VideoOut.h>+extern "C" {+int32_t sceGnmSubmitDone(void);+uint64_t sceKernelGetProcessTime(void);+int sceKernelUsleep(unsigned int microseconds);+int sceKernelMapNamedFlexibleMemory(void** address, size_t length, int protection, int flags, const char* name);+int sceKernelMunmap(void* address, size_t length);+}+namespace xc::display {namespace {@@ -35,13 +43,28 @@ constexpr int kMapProtection = 0x33; // RWint g_videoHandle = -1;void* g_mappedMemory = nullptr;+int64_t g_physAddr = 0;+bool g_isDirectMemory = false;uint8_t* g_buffers[kBuffers]{};int g_currentBuffer = 0;+int g_onScreenBuffer = 0;+int g_pendingBuffer = -1;int64_t g_flipMarker = 0;-std::array<int64_t, kBuffers> g_bufferMarker{-1, -1, -1};+int64_t g_pendingFlipMarker = -1;+uint64_t g_lastFlipCount = 0;+std::atomic<uint64_t> g_shownId{0};+std::atomic<uint64_t> g_shownAtUs{0};std::recursive_mutex g_frameMutex;std::atomic<int> g_sharpness{0};+struct SubmittedFlip {+ int64_t marker = 0;+ uint64_t submitUs = 0;+ uint64_t submitProcUs = 0;+};+constexpr size_t kSubmittedFlipRing = 16;+SubmittedFlip g_submittedFlips[kSubmittedFlipRing]{};+struct Overlay {std::vector<uint32_t> px;int x = 0, y = 0, w = 0, h = 0;@@ -70,16 +93,19 @@ struct RowScratch {};static RowScratch g_scratch;+// 2 helper threads (pinned to Core 4 and Core 5) + calling thread (Core 0 or Core 3)+// = 3 equal stripes of 360 rows (0..360, 360..720, 720..1080).class RowPool {public:- static constexpr int kNumWorkers = 4;+ static constexpr int kNumWorkers = 2;RowPool() {for (int i = 0; i < kNumWorkers; ++i) {- workers_[i] = std::thread([this, i]() {- platform::setThreadAffinity(platform::ThreadRole::Worker, "ps4_display");+ platform::startThread(workers_[i], [this, i]() {+ const char* tname = (i == 0) ? "ps4_disp_1" : "ps4_disp_2";+ platform::setThreadAffinity(platform::ThreadRole::Worker, tname);workerLoop(i);- });+ }, 512u << 10);}}@@ -104,11 +130,10 @@ public:taskSeq_++;cvWork_.notify_all();}- // Slice 4 is processed by caller (main thread or video thread)- int rowsPerSlice = kHeight / (kNumWorkers + 1); // 216 rows- int yStart = kNumWorkers * rowsPerSlice;- int yEnd = kHeight;- fn(yStart, yEnd);+ // Stripe 0 (rows 0..360) is processed by the calling thread+ constexpr int kRowsPerSlice = kHeight / (kNumWorkers + 1); // 360 rows+ fn(0, kRowsPerSlice);+ _mm_sfence();std::unique_lock<std::mutex> lock(mutex_);cvDone_.wait(lock, [this]() { return remaining_ == 0; });@@ -118,9 +143,9 @@ public:private:void workerLoop(int id) {- int rowsPerSlice = kHeight / (kNumWorkers + 1); // 216 rows- int yStart = id * rowsPerSlice;- int yEnd = (id + 1) * rowsPerSlice;+ constexpr int kRowsPerSlice = kHeight / (kNumWorkers + 1); // 360 rows+ int yStart = (id + 1) * kRowsPerSlice;+ int yEnd = (id == kNumWorkers - 1) ? static_cast<int>(kHeight) : (id + 2) * kRowsPerSlice;uint64_t lastSeq = 0;while (true) {@@ -135,6 +160,7 @@ private:if (task && *task) {(*task)(yStart, yEnd);+ _mm_sfence();}{@@ -146,7 +172,7 @@ private:}}- std::array<std::thread, kNumWorkers> workers_;+ std::array<platform::Thread, kNumWorkers> workers_;std::mutex runMutex_;std::mutex mutex_;std::condition_variable cvWork_;@@ -159,51 +185,256 @@ private:static std::unique_ptr<RowPool> g_rowPool;-inline __m128i yuvToRgbaSse(int y0, int y1, int y2, int y3,- int u0, int u1, int u2, int u3,- int v0, int v1, int v2, int v3) {- __m128i yVec = _mm_setr_epi32(y0 - 16, y1 - 16, y2 - 16, y3 - 16);- __m128i uVec = _mm_setr_epi32(u0 - 128, u1 - 128, u2 - 128, u3 - 128);- __m128i vVec = _mm_setr_epi32(v0 - 128, v1 - 128, v2 - 128, v3 - 128);-- __m128i c = _mm_mullo_epi32(yVec, _mm_set1_epi32(1192));- __m128i r = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(c, _mm_mullo_epi32(vVec, _mm_set1_epi32(1836))), _mm_set1_epi32(512)), 10);- __m128i g = _mm_srai_epi32(_mm_add_epi32(_mm_sub_epi32(_mm_sub_epi32(c, _mm_mullo_epi32(uVec, _mm_set1_epi32(218))), _mm_mullo_epi32(vVec, _mm_set1_epi32(546))), _mm_set1_epi32(512)), 10);- __m128i b = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(c, _mm_mullo_epi32(uVec, _mm_set1_epi32(2163))), _mm_set1_epi32(512)), 10);-- r = _mm_max_epi32(_mm_min_epi32(r, _mm_set1_epi32(255)), _mm_setzero_si128());- g = _mm_max_epi32(_mm_min_epi32(g, _mm_set1_epi32(255)), _mm_setzero_si128());- b = _mm_max_epi32(_mm_min_epi32(b, _mm_set1_epi32(255)), _mm_setzero_si128());-- __m128i rgba = _mm_or_si128(_mm_set1_epi32(static_cast<int>(0xFF000000u)),- _mm_or_si128(r, _mm_or_si128(_mm_slli_epi32(g, 8), _mm_slli_epi32(b, 16))));- return rgba;+// 8-pixel 16-bit SSE2 BT.709 Limited Range YUV -> A8B8G8R8 converter (adapted from XCloud4)+static inline void colorRgbEight(__m128i y16, __m128i u16, __m128i v16,+ __m128i& p_lo, __m128i& p_hi) {+ const __m128i y_bias = _mm_set1_epi16(16);+ const __m128i uv_bias = _mm_set1_epi16(128);+ const __m128i zero16 = _mm_setzero_si128();+ const __m128i round = _mm_set1_epi32(128);+ const __m128i k_y_r = _mm_set1_epi32((403 << 16) | (298 & 0xFFFF));+ const __m128i k_y_b = _mm_set1_epi32((541 << 16) | (298 & 0xFFFF));+ const __m128i k_y_gu = _mm_set1_epi32(((-55 & 0xFFFF) << 16) | (298 & 0xFFFF));+ const __m128i k_gv_0 = _mm_set1_epi32(-137 & 0xFFFF);+ const __m128i alpha = _mm_set1_epi16(static_cast<short>(0xFF00));++ __m128i c = _mm_max_epi16(_mm_sub_epi16(y16, y_bias), zero16);+ __m128i d = _mm_sub_epi16(u16, uv_bias);+ __m128i e = _mm_sub_epi16(v16, uv_bias);++ __m128i ce_lo = _mm_unpacklo_epi16(c, e);+ __m128i ce_hi = _mm_unpackhi_epi16(c, e);+ __m128i cd_lo = _mm_unpacklo_epi16(c, d);+ __m128i cd_hi = _mm_unpackhi_epi16(c, d);+ __m128i e0_lo = _mm_unpacklo_epi16(e, zero16);+ __m128i e0_hi = _mm_unpackhi_epi16(e, zero16);++ __m128i r_lo = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(ce_lo, k_y_r), round), 8);+ __m128i r_hi = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(ce_hi, k_y_r), round), 8);++ __m128i g_lo = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(cd_lo, k_y_gu), _mm_madd_epi16(e0_lo, k_gv_0)), round), 8);+ __m128i g_hi = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(cd_hi, k_y_gu), _mm_madd_epi16(e0_hi, k_gv_0)), round), 8);++ __m128i b_lo = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(cd_lo, k_y_b), round), 8);+ __m128i b_hi = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(cd_hi, k_y_b), round), 8);++ __m128i r16 = _mm_packs_epi32(r_lo, r_hi);+ __m128i g16 = _mm_packs_epi32(g_lo, g_hi);+ __m128i b16 = _mm_packs_epi32(b_lo, b_hi);++ __m128i r8 = _mm_packus_epi16(r16, r16);+ __m128i g8 = _mm_packus_epi16(g16, g16);+ __m128i b8 = _mm_packus_epi16(b16, b16);++ __m128i rg = _mm_unpacklo_epi8(r8, g8);+ __m128i ba = _mm_or_si128(_mm_unpacklo_epi8(b8, zero16), alpha);+ p_lo = _mm_unpacklo_epi16(rg, ba);+ p_hi = _mm_unpackhi_epi16(rg, ba);+}++static inline void unpackNv12UvEight(const uint8_t* uvPtr, __m128i& u16, __m128i& v16) {+ const __m128i mask_low = _mm_set1_epi16(0x00FF);+ __m128i uv_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(uvPtr));+ __m128i uv_dup = _mm_unpacklo_epi16(uv_bytes, uv_bytes);+ u16 = _mm_and_si128(uv_dup, mask_low);+ v16 = _mm_srli_epi16(uv_dup, 8);+}++static inline void unpackYuv420UvEight(const uint8_t* uPtr, const uint8_t* vPtr, __m128i& u16, __m128i& v16) {+ const __m128i zero = _mm_setzero_si128();+ uint32_t u4 = 0, v4 = 0;+ std::memcpy(&u4, uPtr, sizeof(u4));+ std::memcpy(&v4, vPtr, sizeof(v4));+ __m128i u_bytes = _mm_cvtsi32_si128(static_cast<int>(u4));+ __m128i v_bytes = _mm_cvtsi32_si128(static_cast<int>(v4));+ __m128i u_dup = _mm_unpacklo_epi8(u_bytes, u_bytes);+ __m128i v_dup = _mm_unpacklo_epi8(v_bytes, v_bytes);+ u16 = _mm_unpacklo_epi8(u_dup, zero);+ v16 = _mm_unpacklo_epi8(v_dup, zero);+}++// 1280 -> 1920 register shuffle for 8 source pixels -> 12 destination pixels+static inline void shuffleScale32(__m128i p_lo, __m128i p_hi,+ __m128i& out0, __m128i& out1, __m128i& out2) {+ out0 = _mm_shuffle_epi32(p_lo, _MM_SHUFFLE(2, 1, 0, 0));+ __m128i p23 = _mm_srli_si128(p_lo, 8);+ __m128i p44 = _mm_shuffle_epi32(p_hi, _MM_SHUFFLE(0, 0, 0, 0));+ out1 = _mm_unpacklo_epi64(p23, p44);+ out2 = _mm_shuffle_epi32(p_hi, _MM_SHUFFLE(3, 2, 2, 1));+}++static inline void colorRowNv12Scale1to1Sse2(const uint8_t* yRow, const uint8_t* uvRow, uint32_t* dstRow) {+ const __m128i zero = _mm_setzero_si128();+ for (int x = 0; x < 1920; x += 8) {+ __m128i y_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(yRow + x));+ __m128i y16 = _mm_unpacklo_epi8(y_bytes, zero);+ __m128i u16, v16, p_lo, p_hi;+ unpackNv12UvEight(uvRow + x, u16, v16);+ colorRgbEight(y16, u16, v16, p_lo, p_hi);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + x), p_lo);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + x + 4), p_hi);+ }+}++static inline void colorRowNv12Scale32SingleSse2(const uint8_t* yRow, const uint8_t* uvRow, uint32_t* dstRow) {+ const __m128i zero = _mm_setzero_si128();+ int dx = 0;+ for (int sx = 0; sx < 1280; sx += 8, dx += 12) {+ __m128i y_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(yRow + sx));+ __m128i y16 = _mm_unpacklo_epi8(y_bytes, zero);+ __m128i u16, v16, p_lo, p_hi, out0, out1, out2;+ unpackNv12UvEight(uvRow + sx, u16, v16);+ colorRgbEight(y16, u16, v16, p_lo, p_hi);+ shuffleScale32(p_lo, p_hi, out0, out1, out2);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + dx), out0);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + dx + 4), out1);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + dx + 8), out2);+ }+}++static inline void colorRowNv12Scale32DualSse2(const uint8_t* yRow, const uint8_t* uvRow,+ uint32_t* dstRow0, uint32_t* dstRow1) {+ colorRowNv12Scale32SingleSse2(yRow, uvRow, dstRow0);+ colorRowNv12Scale32SingleSse2(yRow, uvRow, dstRow1);+}++static inline void colorRowYuv420Scale1to1Sse2(const uint8_t* yRow, const uint8_t* uRow, const uint8_t* vRow,+ uint32_t* dstRow) {+ const __m128i zero = _mm_setzero_si128();+ for (int x = 0; x < 1920; x += 8) {+ __m128i y_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(yRow + x));+ __m128i y16 = _mm_unpacklo_epi8(y_bytes, zero);+ __m128i u16, v16, p_lo, p_hi;+ unpackYuv420UvEight(uRow + (x >> 1), vRow + (x >> 1), u16, v16);+ colorRgbEight(y16, u16, v16, p_lo, p_hi);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + x), p_lo);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + x + 4), p_hi);+ }+}++static inline void colorRowYuv420Scale32SingleSse2(const uint8_t* yRow, const uint8_t* uRow, const uint8_t* vRow,+ uint32_t* dstRow) {+ const __m128i zero = _mm_setzero_si128();+ int dx = 0;+ for (int sx = 0; sx < 1280; sx += 8, dx += 12) {+ __m128i y_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(yRow + sx));+ __m128i y16 = _mm_unpacklo_epi8(y_bytes, zero);+ __m128i u16, v16, p_lo, p_hi, out0, out1, out2;+ unpackYuv420UvEight(uRow + (sx >> 1), vRow + (sx >> 1), u16, v16);+ colorRgbEight(y16, u16, v16, p_lo, p_hi);+ shuffleScale32(p_lo, p_hi, out0, out1, out2);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + dx), out0);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + dx + 4), out1);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dstRow + dx + 8), out2);+ }+}++static inline void colorRowYuv420Scale32DualSse2(const uint8_t* yRow, const uint8_t* uRow, const uint8_t* vRow,+ uint32_t* dstRow0, uint32_t* dstRow1) {+ colorRowYuv420Scale32SingleSse2(yRow, uRow, vRow, dstRow0);+ colorRowYuv420Scale32SingleSse2(yRow, uRow, vRow, dstRow1);+}++inline void compositeOverlaySlice(uint32_t* dst, int yStart, int yEnd, const Overlay& ov) {+ int dy0 = std::max(yStart, ov.y);+ int dy1 = std::min(yEnd, ov.y + ov.h);+ if (dy0 >= dy1) return;+ int ox0 = std::max(0, -ov.x);+ int ox1 = std::min(ov.w, static_cast<int>(kWidth) - ov.x);+ if (ox0 >= ox1) return;++ _mm_sfence();+ for (int dy = dy0; dy < dy1; ++dy) {+ int oy = dy - ov.y;+ const uint32_t* sRow = ov.px.data() + oy * ov.w;+ uint32_t* dRow = dst + dy * kWidth;+ for (int ox = ox0; ox < ox1; ++ox) {+ uint32_t p = sRow[ox];+ uint32_t alpha = ((p >> 24) * ov.alpha) / 255;+ if (alpha == 0) continue;+ int px = ov.x + ox;+ if (alpha == 255) {+ dRow[px] = p;+ continue;+ }+ uint32_t inv = 255 - alpha;+ uint32_t bg = dRow[px];+ uint32_t r = (((p & 0xFF) * alpha) + ((bg & 0xFF) * inv)) / 255;+ uint32_t g = ((((p >> 8) & 0xFF) * alpha) + (((bg >> 8) & 0xFF) * inv)) / 255;+ uint32_t b = ((((p >> 16) & 0xFF) * alpha) + (((bg >> 16) & 0xFF) * inv)) / 255;+ dRow[px] = 0xFF000000u | (b << 16) | (g << 8) | r;+ }+ }}-inline void blendOverlayRow(uint32_t* dRow, int dy, const Overlay& ov) {- if (dy < ov.y || dy >= ov.y + ov.h) return;- int oy = dy - ov.y;- const uint32_t* sRow = ov.px.data() + oy * ov.w;- for (int ox = 0; ox < ov.w; ++ox) {- int px = ov.x + ox;- if (px < 0 || px >= static_cast<int>(kWidth)) continue;- uint32_t p = sRow[ox];- uint32_t alpha = ((p >> 24) * ov.alpha) / 255;- if (alpha == 0) continue;- if (alpha == 255) {- dRow[px] = p;- continue;+void pollFlipStatus() {+ if (g_videoHandle < 0 || g_flipMarker == 0) return;+ OrbisVideoOutFlipStatus status{};+ if (sceVideoOutGetFlipStatus(g_videoHandle, &status) != 0) return;++ if (status.currentBuffer >= 0 && status.currentBuffer < kBuffers) {+ g_onScreenBuffer = status.currentBuffer;+ }+ if (status.flipArg > 0) {+ uint64_t newId = static_cast<uint64_t>(status.flipArg);+ if (newId != g_shownId.load(std::memory_order_relaxed)) {+ uint64_t nowUs = platform::nowUs();+ uint64_t procNowUs = sceKernelGetProcessTime();+ const SubmittedFlip& sub = g_submittedFlips[newId % kSubmittedFlipRing];+ uint64_t shownUs = 0;+ if (sub.marker == status.flipArg && sub.submitUs > 0) {+ if (status.ptime > 0 && status.ptime >= sub.submitProcUs && status.ptime <= procNowUs) {+ shownUs = sub.submitUs + (status.ptime - sub.submitProcUs);+ } else if (nowUs >= sub.submitUs && (nowUs - sub.submitUs) <= 50000ULL) {+ shownUs = nowUs;+ }+ } else if (status.ptime > 0 && procNowUs >= status.ptime && (procNowUs - status.ptime) < 100000ULL) {+ uint64_t ageUs = procNowUs - status.ptime;+ if (nowUs > ageUs) shownUs = nowUs - ageUs;+ }+ g_shownAtUs.store(shownUs, std::memory_order_relaxed);+ g_shownId.store(newId, std::memory_order_release);+ }+ if (g_pendingBuffer >= 0 && status.flipArg >= g_pendingFlipMarker) {+ g_onScreenBuffer = g_pendingBuffer;+ g_pendingBuffer = -1;}- uint32_t inv = 255 - alpha;- uint32_t bg = dRow[px];- uint32_t r = (((p & 0xFF) * alpha) + ((bg & 0xFF) * inv)) / 255;- uint32_t g = ((((p >> 8) & 0xFF) * alpha) + (((bg >> 8) & 0xFF) * inv)) / 255;- uint32_t b = ((((p >> 16) & 0xFF) * alpha) + (((bg >> 16) & 0xFF) * inv)) / 255;- dRow[px] = 0xFF000000u | (b << 16) | (g << 8) | r;}+ if (g_pendingBuffer >= 0 && status.numGpuFlipPending == 0 && status.numFlipPending == 0 &&+ status.num != g_lastFlipCount) {+ g_onScreenBuffer = g_pendingBuffer;+ g_pendingBuffer = -1;+ }+ g_lastFlipCount = status.num;+}++void waitPendingFlip() {+ if (g_videoHandle < 0 || g_pendingBuffer < 0) return;+ for (int i = 0; i < 200; ++i) {+ pollFlipStatus();+ if (g_pendingBuffer < 0) return;+ sceKernelUsleep(250);+ }+ // Timeout fallback (50 ms): promote pending buffer so we never deadlock+ g_onScreenBuffer = g_pendingBuffer;+ g_pendingBuffer = -1;}-extern "C" int sceKernelMapNamedFlexibleMemory(void** address, size_t length, int protection, int flags, const char* name);+// Non-blocking backbuffer selection: with 3 buffers (1 on screen, at most 1 pending flip),+// there is always 1 free buffer ready for CPU conversion while the previous flip is in flight.+bool acquireBuffer(bool /*wait*/ = true) {+ if (g_videoHandle < 0) return false;+ pollFlipStatus();+ for (int i = 0; i < kBuffers; ++i) {+ int cand = (g_currentBuffer + 1 + i) % kBuffers;+ if (cand != g_onScreenBuffer && cand != g_pendingBuffer) {+ g_currentBuffer = cand;+ return true;+ }+ }+ g_currentBuffer = (g_onScreenBuffer + 1) % kBuffers;+ return true;+}} // namespace@@ -221,6 +452,7 @@ bool init(bool /*preferGpu*/) {void* mapped = nullptr;int64_t physAddr = 0;+ bool isDirect = false;int rc = -1;size_t directMemSize = sceKernelGetDirectMemorySize();if (directMemSize >= kMemoryBytes) {@@ -228,10 +460,16 @@ bool init(bool /*preferGpu*/) {kMemoryBytes, kMemoryAlignment, kMemoryTypeGarlic, &physAddr);if (rc == 0) {rc = sceKernelMapDirectMemory(&mapped, kMemoryBytes, kMapProtection, 0, physAddr, kMemoryAlignment);+ if (rc == 0 && mapped) {+ isDirect = true;+ } else {+ sceKernelReleaseDirectMemory(physAddr, kMemoryBytes);+ physAddr = 0;+ mapped = nullptr;+ }}}- if (rc != 0 || !mapped) {- // Fallback to flexible memory (reliable on all PS4 jailbreak environments)+ if (!isDirect || !mapped) {rc = sceKernelMapNamedFlexibleMemory(&mapped, kMemoryBytes, kMapProtection, 0, "display_fb");if (rc != 0 || !mapped) {XC_LOGE("display: allocate direct and flexible memory failed: 0x%08x", static_cast<unsigned>(rc));@@ -244,7 +482,17 @@ bool init(bool /*preferGpu*/) {}g_mappedMemory = mapped;+ g_physAddr = physAddr;+ g_isDirectMemory = isDirect;g_videoHandle = handle;+ g_currentBuffer = 0;+ g_onScreenBuffer = 0;+ g_pendingBuffer = -1;+ g_flipMarker = 0;+ g_pendingFlipMarker = -1;+ g_shownId = 0;+ g_shownAtUs = 0;+ std::memset(g_submittedFlips, 0, sizeof(g_submittedFlips));for (int i = 0; i < kBuffers; ++i) {g_buffers[i] = static_cast<uint8_t*>(mapped) + i * kFrameBytes;@@ -267,65 +515,59 @@ bool init(bool /*preferGpu*/) {g_rowPool = std::make_unique<RowPool>();- XC_LOGI("display: PS4 VideoOut initialized (3 linear 1080p buffers, handle %d, 4 SIMD worker threads)", handle);+ // Submit initial cleared buffer 0 and notify GnmDriver+ int64_t initMarker = ++g_flipMarker;+ uint64_t subProcUs = sceKernelGetProcessTime();+ uint64_t subUs = platform::nowUs();+ if (sceVideoOutSubmitFlip(handle, 0, ORBIS_VIDEO_OUT_FLIP_VSYNC, initMarker) == 0) {+ g_submittedFlips[static_cast<uint64_t>(initMarker) % kSubmittedFlipRing] = {initMarker, subUs, subProcUs};+ g_pendingBuffer = 0;+ g_pendingFlipMarker = initMarker;+ waitPendingFlip();+ }+ sceGnmSubmitDone();++ XC_LOGI("display: PS4 VideoOut initialized (3 linear 1080p buffers, handle %d, 3-stripe SIMD pool)", handle);return true;}void shutdown() {g_rowPool.reset();if (g_videoHandle >= 0) {+ waitPendingFlip();+ sceGnmSubmitDone();sceVideoOutClose(g_videoHandle);g_videoHandle = -1;}- g_mappedMemory = nullptr;+ if (g_mappedMemory) {+ sceKernelMunmap(g_mappedMemory, kMemoryBytes);+ g_mappedMemory = nullptr;+ }+ if (g_isDirectMemory && g_physAddr != 0) {+ sceKernelReleaseDirectMemory(g_physAddr, kMemoryBytes);+ g_physAddr = 0;+ g_isDirectMemory = false;+ }+ for (auto& b : g_buffers) b = nullptr;}std::recursive_mutex& frameMutex() { return g_frameMutex; }-namespace {-// Picks the back buffer for the next frame: not on screen, not queued.-// Without `wait`, gives up at once when all are busy.-bool acquireBuffer(bool wait = true) {- for (int attempt = 0; attempt < 4; ++attempt) {- OrbisVideoOutFlipStatus status{};- int64_t shown = g_flipMarker; // no status: assume everything shown- bool gotStatus = (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, &status) == 0);- if (gotStatus && status.flipArg > 0)- shown = status.flipArg;- int onScreen = -1;- if (gotStatus && status.currentBuffer >= 0 && status.currentBuffer < kBuffers) {- onScreen = status.currentBuffer;- } else {- for (int i = 0; i < kBuffers; ++i)- if (g_bufferMarker[i] >= 0 && g_bufferMarker[i] <= shown &&- (onScreen < 0 || g_bufferMarker[i] > g_bufferMarker[onScreen]))- onScreen = i;- }- int best = -1;- for (int i = 0; i < kBuffers; ++i) {- if (i == onScreen || (g_bufferMarker[i] >= 0 && g_bufferMarker[i] > shown)) continue;- if (best < 0 || g_bufferMarker[i] < g_bufferMarker[best]) best = i;- }- if (best >= 0) {- g_currentBuffer = best;- return true;- }- if (!wait) return false;- sceVideoOutWaitVblank(g_videoHandle);- }- // Flip status not moving: fall back to round robin.- g_currentBuffer = static_cast<int>(g_flipMarker % kBuffers);- return true;-}-} // namespace-void present() {if (g_videoHandle < 0) return;- int rc = sceVideoOutSubmitFlip(g_videoHandle, g_currentBuffer, ORBIS_VIDEO_OUT_FLIP_VSYNC, ++g_flipMarker);+ waitPendingFlip();+ int64_t marker = ++g_flipMarker;+ uint64_t subProcUs = sceKernelGetProcessTime();+ uint64_t subUs = platform::nowUs();+ int rc = sceVideoOutSubmitFlip(g_videoHandle, g_currentBuffer, ORBIS_VIDEO_OUT_FLIP_VSYNC, marker);if (rc != 0) {XC_LOGW("display: submit flip: 0x%08x", static_cast<unsigned>(rc));+ } else {+ g_submittedFlips[static_cast<uint64_t>(marker) % kSubmittedFlipRing] = {marker, subUs, subProcUs};+ g_pendingBuffer = g_currentBuffer;+ g_pendingFlipMarker = marker;}- g_bufferMarker[g_currentBuffer] = g_flipMarker;+ sceGnmSubmitDone();}void drawRgba(const uint32_t* pixels) {@@ -362,7 +604,12 @@ void drawRgba(const uint32_t* pixels) {});}-void pump() {}+void pump() {+ std::unique_lock<std::recursive_mutex> lock(g_frameMutex, std::try_to_lock);+ if (!lock.owns_lock()) return;+ pollFlipStatus();+ sceGnmSubmitDone();+}void idleWait(uint32_t ms) {platform::sleepMs(ms);@@ -371,11 +618,17 @@ void idleWait(uint32_t ms) {bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v,int strideY, int strideU, int strideV,int width, int height, bool wait) {- if (g_videoHandle < 0 || !y || !u || !v || width <= 0 || height <= 0) return false;+ int cw = (width + 1) / 2;+ if (g_videoHandle < 0 || !y || !u || !v || width <= 0 || height <= 0 ||+ strideY < width || strideU < cw || strideV < cw) return false;if (!acquireBuffer(wait)) return false;uint32_t* dst = reinterpret_cast<uint32_t*>(g_buffers[g_currentBuffer]);- g_scratch.update(width, height);+ const bool is1080p = (width == 1920 && height == 1080);+ const bool is720p = (width == 1280 && height == 720);+ if (!is1080p && !is720p) {+ g_scratch.update(width, height);+ }std::shared_ptr<const Overlay> activeOverlay;{@@ -383,47 +636,68 @@ bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v,activeOverlay = g_overlay;}- auto renderSlice = [y, u, v, strideY, strideU, strideV, dst, &activeOverlay](int yStart, int yEnd) {- const auto& mapX = g_scratch.mapX;- const auto& mapY = g_scratch.mapY;-- for (int dy = yStart; dy < yEnd; ++dy) {- int sy = mapY[dy];- const uint8_t* yRow = y + sy * strideY;- const uint8_t* uRow = u + (sy / 2) * strideU;- const uint8_t* vRow = v + (sy / 2) * strideV;- uint32_t* dRow = dst + dy * kWidth;-- for (int dx = 0; dx < static_cast<int>(kWidth); dx += 4) {- int sx0 = mapX[dx];- int sx1 = mapX[dx + 1];- int sx2 = mapX[dx + 2];- int sx3 = mapX[dx + 3];-- int y0 = yRow[sx0];- int y1 = yRow[sx1];- int y2 = yRow[sx2];- int y3 = yRow[sx3];-- int u0 = uRow[sx0 / 2];- int u1 = uRow[sx1 / 2];- int u2 = uRow[sx2 / 2];- int u3 = uRow[sx3 / 2];-- int v0 = vRow[sx0 / 2];- int v1 = vRow[sx1 / 2];- int v2 = vRow[sx2 / 2];- int v3 = vRow[sx3 / 2];-- __m128i rgba = yuvToRgbaSse(y0, y1, y2, y3, u0, u1, u2, u3, v0, v1, v2, v3);- _mm_stream_si128(reinterpret_cast<__m128i*>(&dRow[dx]), rgba);+ auto renderSlice = [y, u, v, strideY, strideU, strideV, is1080p, is720p, dst, &activeOverlay](int yStart, int yEnd) {+ if (is1080p) {+ for (int dy = yStart; dy < yEnd; ++dy) {+ const uint8_t* yRow = y + dy * strideY;+ const uint8_t* uRow = u + (dy >> 1) * strideU;+ const uint8_t* vRow = v + (dy >> 1) * strideV;+ colorRowYuv420Scale1to1Sse2(yRow, uRow, vRow, dst + dy * kWidth);}-- if (activeOverlay) {- _mm_sfence();- blendOverlayRow(dRow, dy, *activeOverlay);+ } else if (is720p) {+ int dy = yStart;+ while (dy < yEnd) {+ if ((dy % 3) == 0 && dy + 2 < yEnd) {+ int sy0 = (dy / 3) * 2;+ int sy1 = sy0 + 1;+ colorRowYuv420Scale32DualSse2(y + sy0 * strideY,+ u + (sy0 >> 1) * strideU,+ v + (sy0 >> 1) * strideV,+ dst + dy * kWidth,+ dst + (dy + 1) * kWidth);+ colorRowYuv420Scale32SingleSse2(y + sy1 * strideY,+ u + (sy1 >> 1) * strideU,+ v + (sy1 >> 1) * strideV,+ dst + (dy + 2) * kWidth);+ dy += 3;+ } else {+ int sy = (dy * 720) / 1080;+ colorRowYuv420Scale32SingleSse2(y + sy * strideY,+ u + (sy >> 1) * strideU,+ v + (sy >> 1) * strideV,+ dst + dy * kWidth);+ ++dy;+ }+ }+ } else {+ const auto& mapX = g_scratch.mapX;+ const auto& mapY = g_scratch.mapY;+ for (int dy = yStart; dy < yEnd; ++dy) {+ int sy = mapY[dy];+ const uint8_t* yRow = y + sy * strideY;+ const uint8_t* uRow = u + (sy >> 1) * strideU;+ const uint8_t* vRow = v + (sy >> 1) * strideV;+ uint32_t* dRow = dst + dy * kWidth;+ for (int dx = 0; dx < static_cast<int>(kWidth); dx += 8) {+ __m128i y16 = _mm_setr_epi16(+ yRow[mapX[dx + 0]], yRow[mapX[dx + 1]], yRow[mapX[dx + 2]], yRow[mapX[dx + 3]],+ yRow[mapX[dx + 4]], yRow[mapX[dx + 5]], yRow[mapX[dx + 6]], yRow[mapX[dx + 7]]);+ __m128i u16 = _mm_setr_epi16(+ uRow[mapX[dx + 0] >> 1], uRow[mapX[dx + 1] >> 1], uRow[mapX[dx + 2] >> 1], uRow[mapX[dx + 3] >> 1],+ uRow[mapX[dx + 4] >> 1], uRow[mapX[dx + 5] >> 1], uRow[mapX[dx + 6] >> 1], uRow[mapX[dx + 7] >> 1]);+ __m128i v16 = _mm_setr_epi16(+ vRow[mapX[dx + 0] >> 1], vRow[mapX[dx + 1] >> 1], vRow[mapX[dx + 2] >> 1], vRow[mapX[dx + 3] >> 1],+ vRow[mapX[dx + 4] >> 1], vRow[mapX[dx + 5] >> 1], vRow[mapX[dx + 6] >> 1], vRow[mapX[dx + 7] >> 1]);+ __m128i p_lo, p_hi;+ colorRgbEight(y16, u16, v16, p_lo, p_hi);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dRow + dx), p_lo);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dRow + dx + 4), p_hi);+ }}}+ if (activeOverlay) {+ compositeOverlaySlice(dst, yStart, yEnd, *activeOverlay);+ }};if (g_rowPool) {@@ -437,11 +711,16 @@ bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v,bool drawNv12(const uint8_t* y, const uint8_t* uv, int strideY, int strideUV,int width, int height, bool wait) {- if (g_videoHandle < 0 || !y || !uv || width <= 0 || height <= 0) return false;+ if (g_videoHandle < 0 || !y || !uv || width <= 0 || height <= 0 ||+ strideY < width || strideUV < width) return false;if (!acquireBuffer(wait)) return false;uint32_t* dst = reinterpret_cast<uint32_t*>(g_buffers[g_currentBuffer]);- g_scratch.update(width, height);+ const bool is1080p = (width == 1920 && height == 1080);+ const bool is720p = (width == 1280 && height == 720);+ if (!is1080p && !is720p) {+ g_scratch.update(width, height);+ }std::shared_ptr<const Overlay> activeOverlay;{@@ -449,48 +728,72 @@ bool drawNv12(const uint8_t* y, const uint8_t* uv, int strideY, int strideUV,activeOverlay = g_overlay;}- auto renderSlice = [y, uv, strideY, strideUV, dst, &activeOverlay](int yStart, int yEnd) {- const auto& mapX = g_scratch.mapX;- const auto& mapY = g_scratch.mapY;-- for (int dy = yStart; dy < yEnd; ++dy) {- int sy = mapY[dy];- const uint8_t* yRow = y + sy * strideY;- const uint8_t* uvRow = uv + (sy / 2) * strideUV;- uint32_t* dRow = dst + dy * kWidth;-- for (int dx = 0; dx < static_cast<int>(kWidth); dx += 4) {- int sx0 = mapX[dx];- int sx1 = mapX[dx + 1];- int sx2 = mapX[dx + 2];- int sx3 = mapX[dx + 3];-- int y0 = yRow[sx0];- int y1 = yRow[sx1];- int y2 = yRow[sx2];- int y3 = yRow[sx3];-- int u0 = uvRow[(sx0 / 2) * 2];- int v0 = uvRow[(sx0 / 2) * 2 + 1];-- int u1 = uvRow[(sx1 / 2) * 2];- int v1 = uvRow[(sx1 / 2) * 2 + 1];-- int u2 = uvRow[(sx2 / 2) * 2];- int v2 = uvRow[(sx2 / 2) * 2 + 1];-- int u3 = uvRow[(sx3 / 2) * 2];- int v3 = uvRow[(sx3 / 2) * 2 + 1];-- __m128i rgba = yuvToRgbaSse(y0, y1, y2, y3, u0, u1, u2, u3, v0, v1, v2, v3);- _mm_stream_si128(reinterpret_cast<__m128i*>(&dRow[dx]), rgba);+ auto renderSlice = [y, uv, strideY, strideUV, is1080p, is720p, dst, &activeOverlay](int yStart, int yEnd) {+ if (is1080p) {+ for (int dy = yStart; dy < yEnd; ++dy) {+ const uint8_t* yRow = y + dy * strideY;+ const uint8_t* uvRow = uv + (dy >> 1) * strideUV;+ colorRowNv12Scale1to1Sse2(yRow, uvRow, dst + dy * kWidth);}-- if (activeOverlay) {- _mm_sfence();- blendOverlayRow(dRow, dy, *activeOverlay);+ } else if (is720p) {+ int dy = yStart;+ while (dy < yEnd) {+ // Both dy=3*m and dy=3*m+1 sample sy=2*m: convert once and stream to both rows!+ if ((dy % 3) == 0 && dy + 2 < yEnd) {+ int sy0 = (dy / 3) * 2;+ int sy1 = sy0 + 1;+ colorRowNv12Scale32DualSse2(y + sy0 * strideY,+ uv + (sy0 >> 1) * strideUV,+ dst + dy * kWidth,+ dst + (dy + 1) * kWidth);+ colorRowNv12Scale32SingleSse2(y + sy1 * strideY,+ uv + (sy1 >> 1) * strideUV,+ dst + (dy + 2) * kWidth);+ dy += 3;+ } else {+ int sy = (dy * 720) / 1080;+ colorRowNv12Scale32SingleSse2(y + sy * strideY,+ uv + (sy >> 1) * strideUV,+ dst + dy * kWidth);+ ++dy;+ }+ }+ } else {+ const auto& mapX = g_scratch.mapX;+ const auto& mapY = g_scratch.mapY;+ for (int dy = yStart; dy < yEnd; ++dy) {+ int sy = mapY[dy];+ const uint8_t* yRow = y + sy * strideY;+ const uint8_t* uvRow = uv + (sy >> 1) * strideUV;+ uint32_t* dRow = dst + dy * kWidth;+ for (int dx = 0; dx < static_cast<int>(kWidth); dx += 8) {+ int c0 = (mapX[dx + 0] >> 1) * 2;+ int c1 = (mapX[dx + 1] >> 1) * 2;+ int c2 = (mapX[dx + 2] >> 1) * 2;+ int c3 = (mapX[dx + 3] >> 1) * 2;+ int c4 = (mapX[dx + 4] >> 1) * 2;+ int c5 = (mapX[dx + 5] >> 1) * 2;+ int c6 = (mapX[dx + 6] >> 1) * 2;+ int c7 = (mapX[dx + 7] >> 1) * 2;+ __m128i y16 = _mm_setr_epi16(+ yRow[mapX[dx + 0]], yRow[mapX[dx + 1]], yRow[mapX[dx + 2]], yRow[mapX[dx + 3]],+ yRow[mapX[dx + 4]], yRow[mapX[dx + 5]], yRow[mapX[dx + 6]], yRow[mapX[dx + 7]]);+ __m128i u16 = _mm_setr_epi16(+ uvRow[c0], uvRow[c1], uvRow[c2], uvRow[c3],+ uvRow[c4], uvRow[c5], uvRow[c6], uvRow[c7]);+ __m128i v16 = _mm_setr_epi16(+ uvRow[c0 + 1], uvRow[c1 + 1], uvRow[c2 + 1], uvRow[c3 + 1],+ uvRow[c4 + 1], uvRow[c5 + 1], uvRow[c6 + 1], uvRow[c7 + 1]);+ __m128i p_lo, p_hi;+ colorRgbEight(y16, u16, v16, p_lo, p_hi);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dRow + dx), p_lo);+ _mm_stream_si128(reinterpret_cast<__m128i*>(dRow + dx + 4), p_hi);+ }}}+ if (activeOverlay) {+ compositeOverlaySlice(dst, yStart, yEnd, *activeOverlay);+ }};if (g_rowPool) {@@ -522,32 +825,42 @@ void setSharpness(int amount) { g_sharpness = std::clamp(amount, 0, 256); }void setDeband(int) {}void setUpscaler(int) {}void setRestore(bool) {}-DisplayCaps caps() { return {}; }+DisplayCaps caps() {+ DisplayCaps c{};+ c.asyncPresent = true;+ return c;+}void setSwapImages(int) {}void setPresentWait(bool) {}bool canSwitchRefresh() { return false; }bool setHighRefresh(bool) { return false; }bool bringUpTest(int) { return false; }-uint64_t lastPresentId() { return static_cast<uint64_t>(g_flipMarker); }+uint64_t lastPresentId() {+ std::lock_guard<std::recursive_mutex> lock(g_frameMutex);+ return static_cast<uint64_t>(g_flipMarker);+}bool lastShown(uint64_t& id, uint64_t& atUs) {+ std::lock_guard<std::recursive_mutex> lock(g_frameMutex);if (g_videoHandle < 0) return false;- OrbisVideoOutFlipStatus status{};- if (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, &status) == 0 && status.flipArg > 0) {- id = static_cast<uint64_t>(status.flipArg);- atUs = platform::nowUs();+ pollFlipStatus();+ uint64_t sid = g_shownId.load(std::memory_order_acquire);+ uint64_t sat = g_shownAtUs.load(std::memory_order_relaxed);+ if (sid > 0 && sat > 0) {+ id = sid;+ atUs = sat;return true;}- id = static_cast<uint64_t>(g_flipMarker);- atUs = platform::nowUs();- return true;+ return false;}bool readBackRgb(std::vector<uint8_t>& rgb, int& width, int& height) {try {std::lock_guard<std::recursive_mutex> lock(g_frameMutex);- if (!g_buffers[g_currentBuffer]) return false;+ pollFlipStatus();+ int bufIdx = (g_onScreenBuffer >= 0 && g_onScreenBuffer < kBuffers) ? g_onScreenBuffer : g_currentBuffer;+ if (!g_buffers[bufIdx]) return false;width = kWidth;height = kHeight;- const uint32_t* base = reinterpret_cast<const uint32_t*>(g_buffers[g_currentBuffer]);+ const uint32_t* base = reinterpret_cast<const uint32_t*>(g_buffers[bufIdx]);rgb.resize(static_cast<size_t>(kWidth) * kHeight * 3);for (size_t i = 0; i < static_cast<size_t>(kWidth) * kHeight; ++i) {uint32_t p = base[i];diff --git a/src/media/audio_in_ps4.cpp b/src/media/audio_in_ps4.cppindex 886d648..0b807a7 100644--- a/src/media/audio_in_ps4.cpp+++ b/src/media/audio_in_ps4.cpp@@ -27,7 +27,7 @@ int sceSysmoduleLoadModuleInternal(uint32_t id);namespace xc::media {struct AudioIn::Impl {- std::thread thread;+ platform::Thread thread;int handle = -1;MicPipeline mic;};@@ -91,7 +91,7 @@ bool AudioIn::open(AudioCallback cb) {running_ = true;impl_->mic.reset();- impl_->thread = std::thread([this]() {+ platform::startThread(impl_->thread, [this]() {platform::setThreadAffinity(platform::ThreadRole::Audio, "ps4_audio_in");platform::setThreadRealtimePriority();std::vector<int16_t> grain(kGrain);@@ -122,7 +122,7 @@ bool AudioIn::open(AudioCallback cb) {bool isMuted = muted_.load(std::memory_order_relaxed) || hardwareMuted_.load(std::memory_order_relaxed);impl_->mic.process(grain.data(), grain.size(), isMuted, gain_.load(std::memory_order_relaxed), level_, callback_);}- });+ }, 512u << 10);XC_LOGI("audio in: PS4 microphone open (handle %d, 48 kHz mono S16)", impl_->handle);return true;diff --git a/src/media/audio_out_ps4.cpp b/src/media/audio_out_ps4.cppindex e5271c3..16ae969 100644--- a/src/media/audio_out_ps4.cpp+++ b/src/media/audio_out_ps4.cpp@@ -30,7 +30,7 @@ constexpr int kRate = AudioQueue::kRate;constexpr unsigned kGrain = 256;std::atomic<bool> g_running{false};-std::thread g_thread;+platform::Thread g_thread;int g_handle = -1;std::atomic<int> g_padSpeakerVolume{100};@@ -96,7 +96,7 @@ bool audioStart() {}g_running = true;audioQueue().open();- g_thread = std::thread(loop);+ platform::startThread(g_thread, loop, 512u << 10);XC_LOGI("audio output open (PS4 48 kHz float stereo, handle %d)", g_handle);return true;}diff --git a/src/media/decoder.cpp b/src/media/decoder.cppindex efd1494..d27f4b9 100644--- a/src/media/decoder.cpp+++ b/src/media/decoder.cpp@@ -120,6 +120,7 @@ bool VideoDecoder::init(int threads, bool preferHw) {preferHw_ = preferHw;isHw_ = false;consecutiveHwErrors_ = 0;+ consecutivePending_ = 0;// 1. Hardware video decoder (PS5 libSceVideodec2 via HwDecoder)if (preferHw_) {@@ -218,6 +219,7 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out, uint32_bool ok = hw_.decode(data, len, tag, hp);if (ok && !hp.error) {consecutiveHwErrors_ = 0;+ consecutivePending_ = 0;needsKeyframe_ = false;out.format = Picture::Format::Nv12;out.width = hp.width;@@ -235,6 +237,16 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out, uint32_}return true;}+ if (hp.pending) {+ ++consecutivePending_;+ if (consecutivePending_ <= 10) {+ pending_ = true;+ return false;+ }+ XC_LOGW("hwdec: priming ceiling exceeded (%d consecutive pending frames)", consecutivePending_);+ } else {+ consecutivePending_ = 0;+ }needsKeyframe_ = true;++consecutiveHwErrors_;diff --git a/src/media/decoder.h b/src/media/decoder.hindex 281b417..7b17ea2 100644--- a/src/media/decoder.h+++ b/src/media/decoder.h@@ -81,6 +81,7 @@ private:bool preferHw_ = true;bool isHw_ = false;int consecutiveHwErrors_ = 0;+ int consecutivePending_ = 0;bool needsKeyframe_ = true;bool profileLogged_ = false;bool pending_ = false;diff --git a/src/media/hw_decoder.h b/src/media/hw_decoder.hindex 164ae0d..0f1e5c3 100644--- a/src/media/hw_decoder.h+++ b/src/media/hw_decoder.h@@ -20,6 +20,7 @@ public:uint32_t width = 0, height = 0, pitch = 0, pitchBytes = 0, format = 0;uint64_t pts = 0;bool error = false;+ bool pending = false;};~HwDecoder();diff --git a/src/media/hw_decoder_ps4.cpp b/src/media/hw_decoder_ps4.cppindex fb47f3e..28b8098 100644--- a/src/media/hw_decoder_ps4.cpp+++ b/src/media/hw_decoder_ps4.cpp@@ -25,62 +25,97 @@ int sceKernelMapDirectMemory(void** address, size_t length, int protection, intint sceKernelMapNamedFlexibleMemory(void** address, size_t length, int protection, int flags, const char* name);int sceKernelMunmap(void* address, size_t length);-// PS4 libSceVideodec2 structures+// PS4 libSceVideodec2 ABI structures (verified against Orbis/Videodec2.h & XCloud4)struct Vdec2DecoderConfig {- uint64_t size;- uint32_t resourceType, codecType, profile, maxLevel;- int32_t maxWidth, maxHeight, maxDpbFrames;- uint32_t pipelineDepth;- uint64_t computeQueue, cpuAffinity;- int32_t cpuPriority;- uint32_t optimizeProgressive, checkMemoryType, reserved;+ uint64_t thisSize;+ uint32_t resourceType;+ uint32_t codecType;+ uint32_t profile;+ uint32_t maxLevel;+ int32_t maxFrameWidth;+ int32_t maxFrameHeight;+ int32_t maxDpbFrameCount;+ uint32_t decodePipelineDepth;+ void* computeQueue;+ uint64_t cpuAffinityMask;+ int32_t cpuThreadPriority;+ bool optimizeProgressiveVideo;+ bool checkMemoryType;+ uint8_t reserved0;+ uint8_t reserved1;+ void* extraConfigInfo;};struct Vdec2DecoderMemory {- uint64_t size, cpuSize;- void* cpu;- uint64_t gpuSize;- void* gpu;- uint64_t cpuGpuSize;- void* cpuGpu;- uint64_t maxFrameSize;- uint32_t frameAlignment, reserved;+ uint64_t thisSize;+ uint64_t cpuMemorySize;+ void* cpuMemory;+ uint64_t gpuMemorySize;+ void* gpuMemory;+ uint64_t cpuGpuMemorySize;+ void* cpuGpuMemory;+ uint64_t maxFrameBufferSize;+ uint32_t frameBufferAlignment;+ uint32_t reserved0;};struct Vdec2ComputeConfig {- uint64_t size;- uint16_t pipeId, queueId;- uint8_t checkMemoryType, reserved0;+ uint64_t thisSize;+ uint16_t computePipeId;+ uint16_t computeQueueId;+ bool checkMemoryType;+ uint8_t reserved0;uint16_t reserved1;};struct Vdec2ComputeMemory {- uint64_t size, cpuGpuSize;- void* cpuGpu;+ uint64_t thisSize;+ uint64_t cpuGpuMemorySize;+ void* cpuGpuMemory;};struct Vdec2Input {- uint64_t size;- void* au;- uint64_t auSize, pts, dts, attached;+ uint64_t thisSize;+ const void* auData;+ uint64_t auSize;+ uint64_t ptsData;+ uint64_t dtsData;+ uint64_t attachedData;};struct Vdec2Frame {- uint64_t size;- void* buffer;- uint64_t bufferSize;- uint32_t accepted, reserved;+ uint64_t thisSize;+ void* frameBuffer;+ uint64_t frameBufferSize;+ bool isAccepted;+ uint8_t reserved0[7];};struct Vdec2Output {- uint64_t size;- uint8_t valid, error, pictureCount, padding;- uint32_t codec, width, pitch, height, reserved;- void* buffer;- uint64_t bufferSize;- uint32_t frameFormat, pitchBytes;+ uint64_t thisSize;+ bool isValid;+ bool isErrorFrame;+ uint8_t pictureCount;+ uint8_t reserved0;+ uint32_t codecType;+ uint32_t frameWidth;+ uint32_t framePitch;+ uint32_t frameHeight;+ uint32_t reserved1;+ void* frameBuffer;+ uint64_t frameBufferSize;+ uint32_t frameFormat;+ uint32_t pitchBytes;};+static_assert(sizeof(Vdec2DecoderConfig) == 72, "PS4 OrbisVideodec2DecoderConfigInfo must be 72 bytes");+static_assert(sizeof(Vdec2DecoderMemory) == 72, "PS4 OrbisVideodec2DecoderMemoryInfo must be 72 bytes");+static_assert(sizeof(Vdec2ComputeConfig) == 16, "PS4 OrbisVideodec2ComputeConfigInfo must be 16 bytes");+static_assert(sizeof(Vdec2ComputeMemory) == 24, "PS4 OrbisVideodec2ComputeMemoryInfo must be 24 bytes");+static_assert(sizeof(Vdec2Input) == 48, "PS4 OrbisVideodec2InputData must be 48 bytes");+static_assert(sizeof(Vdec2Frame) == 32, "PS4 OrbisVideodec2FrameBuffer must be 32 bytes");+static_assert(sizeof(Vdec2Output) == 56, "PS4 OrbisVideodec2OutputInfo must be 56 bytes");+// PS4 libSceVideodec2 native functions linked via -lSceVideodec2int sceVideodec2QueryComputeMemoryInfo(Vdec2ComputeMemory* mem);int sceVideodec2AllocateComputeQueue(const Vdec2ComputeConfig* cfg, const Vdec2ComputeMemory* mem, void** queue);@@ -88,8 +123,9 @@ int sceVideodec2ReleaseComputeQueue(void* queue);int sceVideodec2QueryDecoderMemoryInfo(const Vdec2DecoderConfig* cfg, Vdec2DecoderMemory* mem);int sceVideodec2CreateDecoder(const Vdec2DecoderConfig* cfg, const Vdec2DecoderMemory* mem, void** decoder);int sceVideodec2DeleteDecoder(void* decoder);-int sceVideodec2Decode(void* decoder, Vdec2Input* input, Vdec2Frame* frame, Vdec2Output* output);+int sceVideodec2Decode(void* decoder, const Vdec2Input* input, Vdec2Frame* frame, Vdec2Output* output);int sceVideodec2Flush(void* decoder, Vdec2Frame* frame, Vdec2Output* output);+int sceVideodec2Reset(void* decoder);}namespace xc::media {@@ -97,12 +133,20 @@ namespace xc::media {namespace {constexpr uint32_t kVideodecModule = 0x00CF; // SCE_SYSMODULE_VIDEODEC2-constexpr int kMemoryTypeOnion = 0; // Coherent CPU+GPU-constexpr int kMemoryTypeGarlic = 3; // GPU Direct Memory-constexpr int kProtectionRw = 0x33;+constexpr int kMemoryTypeOnion = 0; // Coherent CPU+GPU (WB_ONION)+constexpr int kMemoryTypeGarlic = 3; // GPU Direct Memory (WC_GARLIC)+constexpr int kProtectionRw = 0x33; // CPU RW | GPU RW+constexpr size_t kInputRingSlots = 8;+constexpr size_t kInputSlotBytes = 2u << 20; // 2 MB per input slot+constexpr size_t kOutputRingSlots = 6;++inline size_t alignUp(size_t n, size_t align) {+ if (align < 0x4000) align = 0x4000;+ return (n + align - 1) & ~(align - 1);+}inline size_t align16k(size_t n) {- return (n + 0x3FFF) & ~static_cast<size_t>(0x3FFF);+ return alignUp(n, 0x4000);}struct DirectMem {@@ -116,18 +160,19 @@ struct FlexibleMem {size_t size = 0;};-DirectMem allocDirect(size_t size, int memoryType, const char* label) {+DirectMem allocDirect(size_t size, int memoryType, const char* label, size_t alignment = 0x4000) {DirectMem mem{};if (size == 0) return mem;- mem.size = align16k(size);+ if (alignment < 0x4000) alignment = 0x4000;+ mem.size = alignUp(size, alignment);int rc = sceKernelAllocateDirectMemory(0, static_cast<int64_t>(sceKernelGetDirectMemorySize()),- mem.size, 0x4000, memoryType, &mem.phys);+ mem.size, alignment, memoryType, &mem.phys);if (rc != 0) {XC_LOGW("hwdec: %s: allocate %zu bytes failed: 0x%08x", label, mem.size, static_cast<unsigned>(rc));mem.size = 0;return mem;}- rc = sceKernelMapDirectMemory(&mem.addr, mem.size, kProtectionRw, 0, mem.phys, 0x4000);+ rc = sceKernelMapDirectMemory(&mem.addr, mem.size, kProtectionRw, 0, mem.phys, alignment);if (rc != 0 || !mem.addr) {XC_LOGW("hwdec: %s: map %zu bytes failed: 0x%08x", label, mem.size, static_cast<unsigned>(rc));sceKernelReleaseDirectMemory(mem.phys, mem.size);@@ -136,6 +181,7 @@ DirectMem allocDirect(size_t size, int memoryType, const char* label) {mem.size = 0;return mem;}+ std::memset(mem.addr, 0, mem.size);return mem;}@@ -165,21 +211,29 @@ struct DecoderAllocations {FlexibleMem decCpuFlex;DirectMem decGpu;DirectMem decCpuGpu;- DirectMem frameBuf;+ DirectMem inputBufs[kInputRingSlots];+ DirectMem frameBufs[kOutputRingSlots];+ size_t inputSlot = 0;+ size_t outputSlot = 0;};static std::mutex s_allocMutex;static std::unordered_map<const HwDecoder*, DecoderAllocations> s_allocations;+void freeAllAllocations(DecoderAllocations& a) {+ for (auto& fb : a.frameBufs) freeDirect(fb);+ for (auto& ib : a.inputBufs) freeDirect(ib);+ freeDirect(a.decCpuGpu);+ freeDirect(a.decGpu);+ freeFlexible(a.decCpuFlex);+ freeDirect(a.decCpuDirect);+ freeDirect(a.computeBuf);+}+} // namespaceHwDecoder::~HwDecoder() {if (decoder_) {- Vdec2Frame frm{};- frm.size = sizeof(frm);- Vdec2Output out{};- out.size = sizeof(out);- sceVideodec2Flush(decoder_, &frm, &out);sceVideodec2DeleteDecoder(decoder_);decoder_ = nullptr;}@@ -191,12 +245,7 @@ HwDecoder::~HwDecoder() {std::lock_guard<std::mutex> lock(s_allocMutex);auto it = s_allocations.find(this);if (it != s_allocations.end()) {- freeDirect(it->second.frameBuf);- freeDirect(it->second.decCpuGpu);- freeDirect(it->second.decGpu);- freeFlexible(it->second.decCpuFlex);- freeDirect(it->second.decCpuDirect);- freeDirect(it->second.computeBuf);+ freeAllAllocations(it->second);s_allocations.erase(it);}}@@ -214,7 +263,6 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {}if (rc != 0) {- // Fallback: try loading firmware helper modules manuallyfor (const char* sprx : {"/system/common/lib/libSceVdecCore.sprx","/system/common/lib/libSceVdecSavc.sprx",@@ -232,11 +280,6 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {DecoderAllocations allocs{};auto rollback = [&]() {if (decoder_) {- Vdec2Frame frm{};- frm.size = sizeof(frm);- Vdec2Output out{};- out.size = sizeof(out);- sceVideodec2Flush(decoder_, &frm, &out);sceVideodec2DeleteDecoder(decoder_);decoder_ = nullptr;}@@ -244,41 +287,36 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {sceVideodec2ReleaseComputeQueue(computeQueue_);computeQueue_ = nullptr;}- freeDirect(allocs.frameBuf);+ freeAllAllocations(allocs);frameBuffer_ = nullptr;frameBufferSize_ = 0;- freeDirect(allocs.decCpuGpu);- freeDirect(allocs.decGpu);- freeFlexible(allocs.decCpuFlex);- freeDirect(allocs.decCpuDirect);- freeDirect(allocs.computeBuf);};// Query and allocate compute queue memoryVdec2ComputeMemory computeMem{};- computeMem.size = sizeof(computeMem);+ computeMem.thisSize = sizeof(computeMem);rc = sceVideodec2QueryComputeMemoryInfo(&computeMem);XC_LOGI("hwdec: compute memory query: rc=0x%08x, %llu bytes", static_cast<unsigned>(rc),- static_cast<unsigned long long>(computeMem.cpuGpuSize));- if (rc != 0 || computeMem.cpuGpuSize == 0) {+ static_cast<unsigned long long>(computeMem.cpuGpuMemorySize));+ if (rc != 0 || computeMem.cpuGpuMemorySize == 0) {return false;}- size_t computeBytes = align16k(computeMem.cpuGpuSize);+ size_t computeBytes = align16k(computeMem.cpuGpuMemorySize);allocs.computeBuf = allocDirect(computeBytes, kMemoryTypeOnion, "compute queue");if (!allocs.computeBuf.addr) {return false;}- computeMem.cpuGpu = allocs.computeBuf.addr;+ computeMem.cpuGpuMemory = allocs.computeBuf.addr;- // Allocate compute queue across pipes 0..4+ // Allocate compute queue across pipes 0..4 (checkMemoryType = false per XCloud4)void* queue = nullptr;for (uint16_t pipe = 0; pipe < 5; ++pipe) {Vdec2ComputeConfig compCfg{};- compCfg.size = sizeof(compCfg);- compCfg.pipeId = pipe;- compCfg.queueId = 0;- compCfg.checkMemoryType = 1;+ compCfg.thisSize = sizeof(compCfg);+ compCfg.computePipeId = pipe;+ compCfg.computeQueueId = 0;+ compCfg.checkMemoryType = false;rc = sceVideodec2AllocateComputeQueue(&compCfg, &computeMem, &queue);XC_LOGI("hwdec: compute queue pipe %u queue 0: rc=0x%08x, queue=%p", pipe, static_cast<unsigned>(rc), queue);@@ -291,82 +329,125 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {}computeQueue_ = queue;- // Query decoder memory requirements- Vdec2DecoderConfig decCfg{};- decCfg.size = sizeof(decCfg);- decCfg.resourceType = 1; // standard- decCfg.codecType = 1; // H.264 (AVC)- decCfg.profile = 100; // High profile- decCfg.maxLevel = 51; // Level 5.1- decCfg.maxWidth = maxWidth;- decCfg.maxHeight = maxHeight;- decCfg.maxDpbFrames = 4;- decCfg.pipelineDepth = 1;- decCfg.computeQueue = reinterpret_cast<uint64_t>(computeQueue_);- decCfg.cpuAffinity = 0x3F; // 6 user cores on PS4 Jaguar APU (cores 0..5)- decCfg.cpuPriority = 700;- decCfg.optimizeProgressive = 1;+ // Query decoder memory requirements with fallback profile/level presets+ struct Preset {+ uint32_t profile;+ uint32_t maxLevel;+ int32_t dpbFrames;+ uint32_t height;+ };+ const uint32_t codedHeight = static_cast<uint32_t>(maxHeight);+ const uint32_t altHeight = (maxHeight == 1088) ? 1080u : codedHeight;+ const Preset presets[] = {+ {100, 42, 4, codedHeight}, // High Profile, Level 4.2 (1920x1088 coded height)+ {100, 51, 4, codedHeight}, // High Profile, Level 5.1 (1920x1088 coded height)+ {100, 42, 4, altHeight}, // Fallback if firmware rejects 1088 at Level 4.2+ {66, 31, 4, altHeight}, // Baseline Profile, Level 3.1+ };+ Vdec2DecoderConfig decCfg{};Vdec2DecoderMemory decMem{};- decMem.size = sizeof(decMem);- rc = sceVideodec2QueryDecoderMemoryInfo(&decCfg, &decMem);- if (rc != 0) {- XC_LOGW("hwdec: sceVideodec2QueryDecoderMemoryInfo failed: 0x%08x", static_cast<unsigned>(rc));+ bool queryOk = false;+ for (const auto& p : presets) {+ std::memset(&decCfg, 0, sizeof(decCfg));+ decCfg.thisSize = sizeof(decCfg);+ decCfg.resourceType = 1; // standard+ decCfg.codecType = 1; // H.264 (AVC)+ decCfg.profile = p.profile;+ decCfg.maxLevel = p.maxLevel;+ decCfg.maxFrameWidth = maxWidth;+ decCfg.maxFrameHeight = p.height;+ decCfg.maxDpbFrameCount = p.dpbFrames;+ decCfg.decodePipelineDepth = 1;+ decCfg.computeQueue = computeQueue_;+ decCfg.cpuAffinityMask = 0x20;+ decCfg.cpuThreadPriority = 700;+ decCfg.optimizeProgressiveVideo = true;+ decCfg.checkMemoryType = false;++ std::memset(&decMem, 0, sizeof(decMem));+ decMem.thisSize = sizeof(decMem);+ rc = sceVideodec2QueryDecoderMemoryInfo(&decCfg, &decMem);+ if (rc == 0) {+ queryOk = true;+ break;+ }+ XC_LOGW("hwdec: QueryDecoderMemoryInfo(profile=%u, level=%u, h=%u) failed: 0x%08x",+ p.profile, p.maxLevel, p.height, static_cast<unsigned>(rc));+ }+ if (!queryOk) {rollback();return false;}- XC_LOGI("hwdec: decoder memory query: cpu=%llu gpu=%llu cpuGpu=%llu maxFrame=%llu bytes",- static_cast<unsigned long long>(decMem.cpuSize), static_cast<unsigned long long>(decMem.gpuSize),- static_cast<unsigned long long>(decMem.cpuGpuSize), static_cast<unsigned long long>(decMem.maxFrameSize));-- if (decMem.cpuSize > 0) {- size_t cpuBytes = align16k(decMem.cpuSize);- allocs.decCpuDirect = allocDirect(cpuBytes, kMemoryTypeOnion, "decoder cpu");- if (allocs.decCpuDirect.addr) {- decMem.cpu = allocs.decCpuDirect.addr;- decMem.cpuSize = allocs.decCpuDirect.size;- XC_LOGI("hwdec: decoder cpu %zu bytes allocated in direct Onion memory", cpuBytes);+ XC_LOGI("hwdec: decoder memory query: cpu=%llu gpu=%llu cpuGpu=%llu maxFrame=%llu align=%u",+ static_cast<unsigned long long>(decMem.cpuMemorySize),+ static_cast<unsigned long long>(decMem.gpuMemorySize),+ static_cast<unsigned long long>(decMem.cpuGpuMemorySize),+ static_cast<unsigned long long>(decMem.maxFrameBufferSize),+ decMem.frameBufferAlignment);++ if (decMem.cpuMemorySize > 0) {+ size_t cpuBytes = align16k(decMem.cpuMemorySize);+ void* cpuMem = nullptr;+ rc = sceKernelMapNamedFlexibleMemory(&cpuMem, cpuBytes, kProtectionRw, 0, "PSBoxVdecCpu");+ if (rc == 0 && cpuMem) {+ std::memset(cpuMem, 0, cpuBytes);+ decMem.cpuMemory = cpuMem;+ decMem.cpuMemorySize = cpuBytes;+ allocs.decCpuFlex = {cpuMem, cpuBytes};+ XC_LOGI("hwdec: decoder cpu %zu bytes allocated in flexible memory", cpuBytes);} else {- XC_LOGW("hwdec: direct onion memory for cpu failed, falling back to flexible memory");- void* cpuMem = nullptr;- rc = sceKernelMapNamedFlexibleMemory(&cpuMem, cpuBytes, kProtectionRw, 0, "PSBoxVdecCpu");- if (rc != 0 || !cpuMem) {- XC_LOGW("hwdec: allocate flexible memory %zu failed: 0x%08x", cpuBytes, static_cast<unsigned>(rc));+ allocs.decCpuDirect = allocDirect(cpuBytes, kMemoryTypeOnion, "decoder cpu");+ if (!allocs.decCpuDirect.addr) {rollback();return false;}- decMem.cpu = cpuMem;- decMem.cpuSize = cpuBytes;- allocs.decCpuFlex = {cpuMem, cpuBytes};- XC_LOGI("hwdec: decoder cpu %zu bytes allocated in flexible memory", cpuBytes);+ decMem.cpuMemory = allocs.decCpuDirect.addr;+ decMem.cpuMemorySize = allocs.decCpuDirect.size;+ XC_LOGI("hwdec: decoder cpu %zu bytes allocated in direct Onion memory", cpuBytes);}}- if (decMem.gpuSize > 0) {- allocs.decGpu = allocDirect(decMem.gpuSize, kMemoryTypeGarlic, "decoder gpu");+ if (decMem.gpuMemorySize > 0) {+ allocs.decGpu = allocDirect(decMem.gpuMemorySize, kMemoryTypeGarlic, "decoder gpu");if (!allocs.decGpu.addr) {rollback();return false;}- decMem.gpu = allocs.decGpu.addr;+ decMem.gpuMemory = allocs.decGpu.addr;+ decMem.gpuMemorySize = allocs.decGpu.size;}- if (decMem.cpuGpuSize > 0) {- allocs.decCpuGpu = allocDirect(decMem.cpuGpuSize, kMemoryTypeOnion, "decoder cpu+gpu");+ if (decMem.cpuGpuMemorySize > 0) {+ allocs.decCpuGpu = allocDirect(decMem.cpuGpuMemorySize, kMemoryTypeOnion, "decoder cpu+gpu");if (!allocs.decCpuGpu.addr) {rollback();return false;}- decMem.cpuGpu = allocs.decCpuGpu.addr;+ decMem.cpuGpuMemory = allocs.decCpuGpu.addr;+ decMem.cpuGpuMemorySize = allocs.decCpuGpu.size;}- frameBufferSize_ = align16k(decMem.maxFrameSize > 0 ? decMem.maxFrameSize : (static_cast<size_t>(maxWidth) * maxHeight * 3 / 2 + 64));- allocs.frameBuf = allocDirect(frameBufferSize_, kMemoryTypeOnion, "frame buffer");- if (!allocs.frameBuf.addr) {- rollback();- return false;+ for (size_t i = 0; i < kInputRingSlots; ++i) {+ allocs.inputBufs[i] = allocDirect(kInputSlotBytes, kMemoryTypeOnion, "input au ring");+ if (!allocs.inputBufs[i].addr) {+ rollback();+ return false;+ }}- frameBuffer_ = static_cast<uint8_t*>(allocs.frameBuf.addr);++ const size_t minCodedFrameBytes = static_cast<size_t>(maxWidth) * maxHeight * 3 / 2 + 64;+ size_t rawFrameSize = std::max<size_t>(static_cast<size_t>(decMem.maxFrameBufferSize), minCodedFrameBytes);+ size_t fbAlign = std::max<size_t>(decMem.frameBufferAlignment, 0x4000);+ frameBufferSize_ = alignUp(rawFrameSize, fbAlign);+ for (size_t i = 0; i < kOutputRingSlots; ++i) {+ allocs.frameBufs[i] = allocDirect(frameBufferSize_, kMemoryTypeOnion, "frame buffer ring", fbAlign);+ if (!allocs.frameBufs[i].addr) {+ rollback();+ return false;+ }+ }+ frameBuffer_ = static_cast<uint8_t*>(allocs.frameBufs[0].addr);rc = sceVideodec2CreateDecoder(&decCfg, &decMem, &decoder_);XC_LOGI("hwdec: sceVideodec2CreateDecoder -> 0x%08x", static_cast<unsigned>(rc));@@ -381,45 +462,130 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {s_allocations[this] = allocs;}- XC_LOGI("hwdec: PS4 decoder running, frame buffer %zu bytes", frameBufferSize_);+ XC_LOGI("hwdec: PS4 decoder running (%zu input slots, %zu output slots of %zu bytes)",+ kInputRingSlots, kOutputRingSlots, frameBufferSize_);return true;}bool HwDecoder::decode(const uint8_t* data, size_t len, uint64_t pts, Picture& out) {+ out = Picture{};if (!decoder_ || !data || len == 0 || !frameBuffer_) return false;+ void* inBuf = nullptr;+ void* outBuf = nullptr;+ size_t outBufSize = frameBufferSize_;+ size_t outSlotUsed = 0;+ {+ std::lock_guard<std::mutex> lock(s_allocMutex);+ auto it = s_allocations.find(this);+ if (it == s_allocations.end() || len > it->second.inputBufs[0].size) {+ return false;+ }+ size_t inSlot = it->second.inputSlot;+ it->second.inputSlot = (inSlot + 1) % kInputRingSlots;+ inBuf = it->second.inputBufs[inSlot].addr;+ std::memcpy(inBuf, data, len);++ outSlotUsed = it->second.outputSlot;+ outBuf = it->second.frameBufs[outSlotUsed].addr;+ outBufSize = it->second.frameBufs[outSlotUsed].size;+ }+Vdec2Input input{};- input.size = sizeof(input);- input.au = const_cast<uint8_t*>(data);+ input.thisSize = sizeof(input);+ input.auData = inBuf;input.auSize = len;- input.pts = pts;+ input.ptsData = pts;+ input.dtsData = pts;Vdec2Frame frame{};- frame.size = sizeof(frame);- frame.buffer = frameBuffer_;- frame.bufferSize = frameBufferSize_;+ frame.thisSize = sizeof(frame);+ frame.frameBuffer = outBuf;+ frame.frameBufferSize = outBufSize;Vdec2Output output{};- output.size = sizeof(output);+ output.thisSize = sizeof(output);- int rc = sceVideodec2Decode(decoder_, &input, &frame, &output);- if (rc != 0) {+ int decodeRc = sceVideodec2Decode(decoder_, &input, &frame, &output);+ if (decodeRc == 0 && frame.isAccepted) {+ std::lock_guard<std::mutex> lock(s_allocMutex);+ auto it = s_allocations.find(this);+ if (it != s_allocations.end() && it->second.outputSlot == outSlotUsed) {+ it->second.outputSlot = (outSlotUsed + 1) % kOutputRingSlots;+ }+ }+ if (decodeRc != 0 || output.isErrorFrame) {+ out.error = true;+ return false;+ }++ bool flushed = false;+ void* flushBuf = nullptr;+ size_t flushBufSize = 0;+ int flushRc = 0;+ if (decodeRc == 0 && (!output.isValid || output.pictureCount == 0)) {+ flushed = true;+ output = Vdec2Output{};+ output.thisSize = sizeof(output);++ Vdec2Frame flushFrame{};+ flushFrame.thisSize = sizeof(flushFrame);+ size_t flushSlot = 0;+ {+ std::lock_guard<std::mutex> lock(s_allocMutex);+ auto it = s_allocations.find(this);+ if (it != s_allocations.end()) {+ flushSlot = it->second.outputSlot;+ flushBuf = it->second.frameBufs[flushSlot].addr;+ flushBufSize = it->second.frameBufs[flushSlot].size;+ flushFrame.frameBuffer = flushBuf;+ flushFrame.frameBufferSize = flushBufSize;+ }+ }++ flushRc = sceVideodec2Flush(decoder_, &flushFrame, &output);+ if (flushRc == 0 && flushFrame.isAccepted) {+ std::lock_guard<std::mutex> lock(s_allocMutex);+ auto it = s_allocations.find(this);+ if (it != s_allocations.end() && it->second.outputSlot == flushSlot) {+ it->second.outputSlot = (flushSlot + 1) % kOutputRingSlots;+ }+ }+ }++ static int logged = 0;+ if ((decodeRc != 0 || flushRc != 0 || output.isValid) && logged < 12) {+ ++logged;+ XC_LOGI("hwdec: PS4 decode 0x%08x flush 0x%08x (flushed=%d): valid %d errFrame %d pictures %u, %ux%u pitch %u (%u bytes), format %u, buf %p",+ static_cast<unsigned>(decodeRc), static_cast<unsigned>(flushRc), flushed ? 1 : 0,+ static_cast<int>(output.isValid), static_cast<int>(output.isErrorFrame),+ static_cast<unsigned>(output.pictureCount),+ output.frameWidth, output.frameHeight, output.framePitch, output.pitchBytes,+ output.frameFormat, output.frameBuffer);+ }++ if (output.isErrorFrame) {+ out.error = true;return false;}- if (output.valid && output.pictureCount > 0) {- out.data = static_cast<const uint8_t*>(output.buffer ? output.buffer : frameBuffer_);- out.size = output.bufferSize ? output.bufferSize : frameBufferSize_;- out.width = output.width;- out.height = output.height;- out.pitch = output.pitch;- out.pitchBytes = output.pitchBytes ? output.pitchBytes : (output.width);+ if (output.isValid && output.pictureCount > 0) {+ const void* chosenBuf = output.frameBuffer ? output.frameBuffer : (flushed && flushBuf ? flushBuf : outBuf);+ size_t chosenSize = output.frameBufferSize ? output.frameBufferSize : (flushed && flushBufSize ? flushBufSize : outBufSize);+ out.data = static_cast<const uint8_t*>(chosenBuf);+ out.size = chosenSize;+ out.width = output.frameWidth;+ out.height = output.frameHeight;+ out.pitch = output.framePitch ? output.framePitch : output.frameWidth;+ out.pitchBytes = output.pitchBytes ? output.pitchBytes : out.pitch;out.format = output.frameFormat;out.pts = pts;- out.error = (output.error != 0);+ out.error = false;return true;}+ // Pipeline priming frame (rc == 0, !isValid, !isErrorFrame): not an error+ out.pending = true;return false;}diff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cppindex 0dc38c7..a28d0cf 100644--- a/src/platform/ps4/platform_ps4.cpp+++ b/src/platform/ps4/platform_ps4.cpp@@ -1130,25 +1130,51 @@ void setThreadAffinity(ThreadRole role, const char* name) {}};+ int targetPrio = 0;+switch (role) {case ThreadRole::Main:setSlot(0);+ targetPrio = 650;break;case ThreadRole::Network:setSlot(1);break;case ThreadRole::VideoDecode:- setSlot(2);- if (s_numAllowedCpus >= 4) setSlot(3);+ setSlot(s_numAllowedCpus >= 6 ? 5 : (s_numAllowedCpus >= 3 ? 2 : 0));+ targetPrio = 650;break;case ThreadRole::Audio:- setSlot(s_numAllowedCpus >= 5 ? 4 : 1);+ setSlot(1);break;case ThreadRole::Worker:- if (s_numAllowedCpus >= 6) {- setSlot(5);+ if (name && (std::strcmp(name, "ps4_present") == 0 || std::strcmp(name, "ps4_disp_0") == 0)) {+ setSlot(s_numAllowedCpus >= 3 ? 2 : 0);+ targetPrio = 650;+ } else if (name && std::strcmp(name, "ps4_disp_1") == 0) {+ setSlot(s_numAllowedCpus >= 4 ? 3 : 1);+ targetPrio = 650;+ } else if (name && std::strcmp(name, "ps4_disp_2") == 0) {+ setSlot(s_numAllowedCpus >= 5 ? 4 : 2);+ targetPrio = 650;} else {- setSlot(s_numAllowedCpus - 1);+ const bool isBgTask = name && (std::strcmp(name, "xcloud_img") == 0 ||+ std::strcmp(name, "xcloud_hydr") == 0 ||+ std::strcmp(name, "xcloud_price") == 0 ||+ std::strcmp(name, "xcloud_upd") == 0 ||+ std::strcmp(name, "xcloud_web") == 0);+ if (!isBgTask) {+ setSlot(0);+ }+ for (int s = 2; s < s_numAllowedCpus; ++s) {+ setSlot(s);+ }+ if (orbisMask == 0) {+ setSlot(s_numAllowedCpus - 1);+ }+ if (isBgTask) {+ targetPrio = 740;+ }}break;}@@ -1160,6 +1186,9 @@ void setThreadAffinity(ThreadRole role, const char* name) {XC_LOGI("thread %s pinned to role %d (mask 0x%llx)", name ? name : "unknown",static_cast<int>(role), static_cast<unsigned long long>(orbisMask));}+ if (targetPrio > 0) {+ scePthreadSetprio(scePthreadSelf(), targetPrio);+ }}void setThreadRealtimePriority() {diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex f861851..a584ce1 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -115,7 +115,7 @@ struct StreamSession::Impl {std::atomic<uint32_t> inputSequence{1};uint64_t lastKeepaliveMs = 0;std::atomic<bool> keepaliveInFlight{false};- std::thread keepaliveThread;+ platform::Thread keepaliveThread;uint64_t lastKeyframeMs = 0;VideoReceiveStats videoStats;std::shared_ptr<RtcpReporter> videoReporter;@@ -722,11 +722,11 @@ struct StreamSession::Impl {if (!keepaliveInFlight.load()) {if (keepaliveThread.joinable()) keepaliveThread.join();keepaliveInFlight = true;- keepaliveThread = std::thread([this] {+ platform::startThread(keepaliveThread, [this] {std::string err;if (!gssv.keepalive(err)) XC_LOGW("%s", err.c_str());keepaliveInFlight = false;- });+ }, 512u << 10);}}if (opt.keyframeIntervalSec > 0 && now - lastKeyframeMs >= static_cast<uint64_t>(opt.keyframeIntervalSec) * 1000u) {diff --git a/src/ui/canvas.cpp b/src/ui/canvas.cppindex 0bce569..86ce9a4 100644--- a/src/ui/canvas.cpp+++ b/src/ui/canvas.cpp@@ -168,16 +168,14 @@ void Canvas::gradientV(Rect r, Color top, Color bottom) {if (a >= 255) {std::fill_n(&row[b.x], b.w, c | 0xFF000000u);} else {- uint32_t sr = (c & 0xFF) * a;- uint32_t sg = ((c >> 8) & 0xFF) * a;- uint32_t sb = ((c >> 16) & 0xFF) * a;- uint32_t inv = 255 - a;+ uint32_t s_rb = (c & 0x00FF00FFu) * a + 0x00800080u;+ uint32_t s_g = (c & 0x0000FF00u) * a + 0x00008000u;+ uint32_t inv = 255 - a;for (int x = b.x; x < b.x + b.w; ++x) {uint32_t d = row[x];- uint32_t dr = (sr + (d & 0xFF) * inv + 127) / 255;- uint32_t dg = (sg + ((d >> 8) & 0xFF) * inv + 127) / 255;- uint32_t db = (sb + ((d >> 16) & 0xFF) * inv + 127) / 255;- row[x] = 0xFF000000u | (db << 16) | (dg << 8) | dr;+ uint32_t rb = ((s_rb + (d & 0x00FF00FFu) * inv) >> 8) & 0x00FF00FFu;+ uint32_t g = ((s_g + (d & 0x0000FF00u) * inv) >> 8) & 0x0000FF00u;+ row[x] = 0xFF000000u | rb | g;}}}@@ -286,8 +284,14 @@ void Canvas::drawImage(const Image& img, int x, int y, uint8_t opacity, int radiuint32_t* row = &px_[static_cast<size_t>(yy) * w_];const uint32_t* src = &img.px[static_cast<size_t>(yy - y) * img.w];bool cornerRow = radius > 0 && (circle || yy < y + radius || yy >= y + img.h - radius);- if (!cornerRow && opacity >= 255 && img.opaque) {- std::memcpy(&row[b.x], &src[b.x - x], static_cast<size_t>(b.w) * sizeof(uint32_t));+ if (!cornerRow && img.opaque) {+ if (opacity >= 255) {+ std::memcpy(&row[b.x], &src[b.x - x], static_cast<size_t>(b.w) * sizeof(uint32_t));+ } else {+ for (int xx = b.x; xx < b.x + b.w; ++xx) {+ blend(row[xx], src[xx - x], opacity);+ }+ }continue;}for (int xx = b.x; xx < b.x + b.w; ++xx) {diff --git a/src/ui/image_cache.cpp b/src/ui/image_cache.cppindex 388a15c..ab9a894 100644--- a/src/ui/image_cache.cpp+++ b/src/ui/image_cache.cpp@@ -98,17 +98,24 @@ ImageCache::ImageCache(std::function<void()> onReady, size_t budgetBytes, std::s::chmod(diskDir_.c_str(), 0777); // one made 0755 by an older versiontrimDisk();}- threads_.resize(3);+ threads_.resize(budget_ <= (64u << 20) ? 1 : 3);for (auto& t : threads_) platform::startThread(t, [this] { loop(); }, 2u << 20);}ImageCache::~ImageCache() {+ stop();+}++void ImageCache::stop() {{std::lock_guard<std::mutex> lock(mutex_);stop_ = true;+ jobs_.clear();}cv_.notify_all();- for (auto& t : threads_) t.join();+ for (auto& t : threads_) {+ if (t.joinable()) t.join();+ }}std::shared_ptr<const Image> ImageCache::get(const std::string& url, int w, int h) {diff --git a/src/ui/image_cache.h b/src/ui/image_cache.hindex 33f90f5..fce147f 100644--- a/src/ui/image_cache.h+++ b/src/ui/image_cache.h@@ -36,6 +36,7 @@ public:explicit ImageCache(std::function<void()> onReady, size_t budgetBytes = 160u << 20, std::string diskDir = {},size_t diskBudgetBytes = 256u << 20);~ImageCache();+ void stop();// The image scaled to w x h, or nullptr while it loads (or if it failed).std::shared_ptr<const Image> get(const std::string& url, int w, int h);diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 8b5b2ab..38c2fd8 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -6763,7 +6763,221 @@ static void testReleaseV155Features() {std::system(("rm -rf " + testDir).c_str());}+#if defined(__x86_64__) || defined(_M_X64)+#include <emmintrin.h>+#endif++static void testPs4VideoPipelineAndSse2Converter() {+ using namespace xc;+ // 1. HwDecoder::Picture default state including pending flag+ media::HwDecoder::Picture hp;+ CHECK(!hp.error);+ CHECK(!hp.pending);+ CHECK(hp.data == nullptr);++ // 1b. Verify PS4 HW decoder ring buffer slot progression during decode and flush+ constexpr size_t kOutputSlots = 6;+ auto simulateSlotAdvance = [](size_t currentSlot, bool decodeAccepted, bool needsFlush, bool flushAccepted) -> size_t {+ size_t slot = currentSlot;+ size_t outSlotUsed = slot;+ if (decodeAccepted) {+ slot = (outSlotUsed + 1) % kOutputSlots;+ }+ if (needsFlush) {+ size_t flushSlot = slot;+ if (flushAccepted) {+ slot = (flushSlot + 1) % kOutputSlots;+ }+ }+ return slot;+ };+ // Case A: decode accepted buffer, valid frame immediately (no flush needed) -> advances 1+ CHECK(simulateSlotAdvance(0, true, false, false) == 1);+ // Case B: decode accepted buffer, !valid -> flush accepts next slot -> advances 2+ CHECK(simulateSlotAdvance(0, true, true, true) == 2);+ // Case C: decode accepted buffer, !valid -> flush flushes without accepting new buffer -> advances 1+ CHECK(simulateSlotAdvance(0, true, true, false) == 1);+ // Case D: decode did not accept buffer, !valid -> flush accepts buffer -> advances 1+ CHECK(simulateSlotAdvance(0, false, true, true) == 1);+ // Case E: neither accepts buffer -> advances 0+ CHECK(simulateSlotAdvance(0, false, true, false) == 0);+ // Case F: wrap-around at ring boundary (slot 5 + 2 -> slot 1)+ CHECK(simulateSlotAdvance(5, true, true, true) == 1);++ // 2. ImageCache::stop() idempotency (called in coreShutdown before destructor)+ {+ ui::ImageCache cache([] {}, 4u << 20);+ cache.stop();+ cache.stop();+ }++#if defined(__x86_64__) || defined(_M_X64)+ // 3. Verify 8-pixel 16-bit SSE2 BT.709 Limited Range kernel and 3/2 (720p->1080p) shuffle+ auto colorRgbEightTest = [](__m128i y16, __m128i u16, __m128i v16, __m128i& p_lo, __m128i& p_hi) {+ const __m128i y_bias = _mm_set1_epi16(16);+ const __m128i uv_bias = _mm_set1_epi16(128);+ const __m128i zero16 = _mm_setzero_si128();+ const __m128i round = _mm_set1_epi32(128);+ const __m128i k_y_r = _mm_set1_epi32((403 << 16) | (298 & 0xFFFF));+ const __m128i k_y_b = _mm_set1_epi32((541 << 16) | (298 & 0xFFFF));+ const __m128i k_y_gu = _mm_set1_epi32(((-55 & 0xFFFF) << 16) | (298 & 0xFFFF));+ const __m128i k_gv_0 = _mm_set1_epi32(-137 & 0xFFFF);+ const __m128i alpha = _mm_set1_epi16(static_cast<short>(0xFF00));++ __m128i c = _mm_max_epi16(_mm_sub_epi16(y16, y_bias), zero16);+ __m128i d = _mm_sub_epi16(u16, uv_bias);+ __m128i e = _mm_sub_epi16(v16, uv_bias);++ __m128i ce_lo = _mm_unpacklo_epi16(c, e);+ __m128i ce_hi = _mm_unpackhi_epi16(c, e);+ __m128i cd_lo = _mm_unpacklo_epi16(c, d);+ __m128i cd_hi = _mm_unpackhi_epi16(c, d);+ __m128i e0_lo = _mm_unpacklo_epi16(e, zero16);+ __m128i e0_hi = _mm_unpackhi_epi16(e, zero16);++ __m128i r_lo = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(ce_lo, k_y_r), round), 8);+ __m128i r_hi = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(ce_hi, k_y_r), round), 8);++ __m128i g_lo = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(cd_lo, k_y_gu), _mm_madd_epi16(e0_lo, k_gv_0)), round), 8);+ __m128i g_hi = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(cd_hi, k_y_gu), _mm_madd_epi16(e0_hi, k_gv_0)), round), 8);++ __m128i b_lo = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(cd_lo, k_y_b), round), 8);+ __m128i b_hi = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(cd_hi, k_y_b), round), 8);++ __m128i r16 = _mm_packs_epi32(r_lo, r_hi);+ __m128i g16 = _mm_packs_epi32(g_lo, g_hi);+ __m128i b16 = _mm_packs_epi32(b_lo, b_hi);++ __m128i r8 = _mm_packus_epi16(r16, r16);+ __m128i g8 = _mm_packus_epi16(g16, g16);+ __m128i b8 = _mm_packus_epi16(b16, b16);++ __m128i rg = _mm_unpacklo_epi8(r8, g8);+ __m128i ba = _mm_or_si128(_mm_unpacklo_epi8(b8, zero16), alpha);+ p_lo = _mm_unpacklo_epi16(rg, ba);+ p_hi = _mm_unpackhi_epi16(rg, ba);+ };++ // Test boundary Y values: Y=0 (sub-black), Y=16 (black), Y=235 (white), Y=255 (super-white) with neutral UV=128+ __m128i y16 = _mm_setr_epi16(0, 16, 235, 255, 16, 235, 0, 255);+ __m128i u16 = _mm_set1_epi16(128);+ __m128i v16 = _mm_set1_epi16(128);+ __m128i p_lo, p_hi;+ colorRgbEightTest(y16, u16, v16, p_lo, p_hi);+ alignas(16) uint32_t px[8] = {};+ _mm_store_si128(reinterpret_cast<__m128i*>(px), p_lo);+ _mm_store_si128(reinterpret_cast<__m128i*>(px + 4), p_hi);+ CHECK(px[0] == 0xFF000000u); // Y=0 clamped to black+ CHECK(px[1] == 0xFF000000u); // Y=16 -> black+ CHECK(px[2] == 0xFFFFFFFFu); // Y=235 -> white+ CHECK(px[3] == 0xFFFFFFFFu); // Y=255 clamped to white++ // Test 3/2 horizontal register shuffle ([0, 0, 1, 2], [2, 3, 4, 4], [5, 6, 6, 7])+ __m128i s_lo = _mm_setr_epi32(10, 20, 30, 40);+ __m128i s_hi = _mm_setr_epi32(50, 60, 70, 80);+ __m128i out0 = _mm_shuffle_epi32(s_lo, _MM_SHUFFLE(2, 1, 0, 0));+ __m128i p23 = _mm_srli_si128(s_lo, 8);+ __m128i p44 = _mm_shuffle_epi32(s_hi, _MM_SHUFFLE(0, 0, 0, 0));+ __m128i out1 = _mm_unpacklo_epi64(p23, p44);+ __m128i out2 = _mm_shuffle_epi32(s_hi, _MM_SHUFFLE(3, 2, 2, 1));+ alignas(16) uint32_t scaled[12] = {};+ _mm_store_si128(reinterpret_cast<__m128i*>(scaled + 0), out0);+ _mm_store_si128(reinterpret_cast<__m128i*>(scaled + 4), out1);+ _mm_store_si128(reinterpret_cast<__m128i*>(scaled + 8), out2);+ const uint32_t expected[12] = {10, 10, 20, 30, 30, 40, 50, 50, 60, 70, 70, 80};+ for (int i = 0; i < 12; ++i) {+ CHECK(scaled[i] == expected[i]);+ }++ // Test unpackNv12UvEight and red conversion (verifying V channel is preserved, not zeroed)+ auto unpackNv12UvEightTest = [](const uint8_t* uvPtr, __m128i& u16, __m128i& v16) {+ const __m128i mask_low = _mm_set1_epi16(0x00FF);+ __m128i uv_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(uvPtr));+ __m128i uv_dup = _mm_unpacklo_epi16(uv_bytes, uv_bytes);+ u16 = _mm_and_si128(uv_dup, mask_low);+ v16 = _mm_srli_epi16(uv_dup, 8);+ };++ alignas(16) const uint8_t sampleUv[8] = {10, 20, 30, 40, 50, 60, 70, 80};+ __m128i testU16, testV16;+ unpackNv12UvEightTest(sampleUv, testU16, testV16);+ alignas(16) uint16_t uArr[8] = {};+ alignas(16) uint16_t vArr[8] = {};+ _mm_store_si128(reinterpret_cast<__m128i*>(uArr), testU16);+ _mm_store_si128(reinterpret_cast<__m128i*>(vArr), testV16);+ const uint16_t expectedU[8] = {10, 10, 30, 30, 50, 50, 70, 70};+ const uint16_t expectedV[8] = {20, 20, 40, 40, 60, 60, 80, 80};+ for (int i = 0; i < 8; ++i) {+ CHECK(uArr[i] == expectedU[i]);+ CHECK(vArr[i] == expectedV[i]);+ }++ // Pure Red (BT.709): Y=54, U=100, V=239. Must convert to vibrant red (R > 200), not green/cyan (R=0)!+ alignas(16) const uint8_t redUv[8] = {100, 239, 100, 239, 100, 239, 100, 239};+ __m128i redY16 = _mm_set1_epi16(54);+ __m128i redU16, redV16, redP_lo, redP_hi;+ unpackNv12UvEightTest(redUv, redU16, redV16);+ colorRgbEightTest(redY16, redU16, redV16, redP_lo, redP_hi);+ alignas(16) uint32_t redPx[8] = {};+ _mm_store_si128(reinterpret_cast<__m128i*>(redPx), redP_lo);+ _mm_store_si128(reinterpret_cast<__m128i*>(redPx + 4), redP_hi);+ uint32_t rVal = redPx[0] & 0xFF;+ uint32_t gVal = (redPx[0] >> 8) & 0xFF;+ uint32_t bVal = (redPx[0] >> 16) & 0xFF;+ CHECK(rVal > 200);+ CHECK(gVal < 40);+ CHECK(bVal < 40);+#endif++ // 4. Verify per-flip ptime timestamp resolution & stale observation rejection after >1s stall+ auto resolveFlipShownUs = [](int64_t flipArg, uint64_t ptime, uint64_t nowUs, uint64_t procNowUs,+ int64_t subMarker, uint64_t subUs, uint64_t subProcUs) -> uint64_t {+ uint64_t shownUs = 0;+ if (subMarker == flipArg && subUs > 0) {+ if (ptime > 0 && ptime >= subProcUs && ptime <= procNowUs) {+ shownUs = subUs + (ptime - subProcUs);+ } else if (nowUs >= subUs && (nowUs - subUs) <= 50000ULL) {+ shownUs = nowUs;+ }+ }+ return shownUs;+ };+ // Case A: Flip submitted at t=100,000 us, flipped at ptime=108,333 us (+8.33ms), but observed 2.05s later+ // after a network stall (t=2,156,400 us). Must resolve to 108,333 us (8.33ms), NOT 2,156,400 us!+ CHECK(resolveFlipShownUs(42, 108333ULL, 2156400ULL, 2156400ULL, 42, 100000ULL, 100000ULL) == 108333ULL);+ // Case B: Emulator/invalid ptime (0) observed 2.05s later after a stall -> must be rejected (0), never 2,156,400 us!+ CHECK(resolveFlipShownUs(42, 0ULL, 2156400ULL, 2156400ULL, 42, 100000ULL, 100000ULL) == 0ULL);+ // Case C: Emulator/invalid ptime (0) observed promptly within 8ms -> accepted as nowUs+ CHECK(resolveFlipShownUs(42, 0ULL, 108000ULL, 108000ULL, 42, 100000ULL, 100000ULL) == 108000ULL);++ // 5. Verify 1080p coded height (1920x1088) framebuffer sizing covers full 1088 luma + 540 chroma rows+ const size_t minCoded1088 = static_cast<size_t>(1920) * 1088 * 3 / 2 + 64;+ const size_t underSized1080 = static_cast<size_t>(1920) * 1080 * 3 / 2;+ const size_t rawFrameSize = std::max<size_t>(underSized1080, minCoded1088);+ const size_t alignedFrameSize = (rawFrameSize + 0x4000 - 1) & ~(static_cast<size_t>(0x4000) - 1);+ const size_t requiredNv12OffsetEnd = static_cast<size_t>(1920) * 1088 + static_cast<size_t>(1920) * (1080 / 2);+ CHECK(alignedFrameSize >= requiredNv12OffsetEnd);++ // 6. Verify SWAR Canvas::gradientV and opaque Canvas::drawImage alpha blending+ {+ ui::Canvas c(32, 16);+ c.clear(ui::rgba(20, 40, 60, 255));+ c.gradientV({0, 0, 32, 16}, ui::rgba(0, 0, 0, 0), ui::rgba(10, 20, 30, 200));+ CHECK((c.data()[0] & 0x00FFFFFFu) == (ui::rgba(20, 40, 60, 255) & 0x00FFFFFFu));+ ui::Image img;+ img.w = 16;+ img.h = 16;+ img.opaque = true;+ img.px.assign(16 * 16, ui::rgba(200, 100, 50, 255));+ c.drawImage(img, 0, 0, 128, 0);+ uint32_t blended = c.data()[0];+ CHECK(((blended >> 24) & 0xFF) == 0xFF);+ CHECK((blended & 0xFF) > 100 && (blended & 0xFF) < 120);+ }+}+int main() {+ testPs4VideoPipelineAndSse2Converter();testReleaseV155Features();testSizedUrl();testPhase1BugFixesAndPhase2Optimizations();