diff --git a/NX2_NOTES.md b/NX2_NOTES.md
index 19a82bc49a..5406b03187 100644
--- a/NX2_NOTES.md
+++ b/NX2_NOTES.md
@@ -201,6 +201,9 @@ With the patched decoder, games 1/3/4 only leave ~60-110 rare SIMD encodings in
| 143 | crashes with the split: CommandChunk::Record (null chunk), vkCmdEndRenderPass on the Vulkan worker | two threads recording into the scheduler: (a) the DMA pusher's split-method debug log read guest memory with the cache-flushing ReadBlock on the front; (b) with async presentation, Swapchain::AcquireNextImage -> Scheduler::Wait flushed the main scheduler from the present thread whenever its tick was not submitted yet (pre-existing race, the split made it frequent) | (a) ReadBlockUnsafe; (b) e4523ab: the present thread waits up to 20 ms for the GPU thread to submit, never flushes. Found with `EDEN_NX2_SPLIT_CHECK=1` (stack of any other thread using the scheduler while the back runs) |
| 144 | macros on the split's front (`EDEN_NX2_SPLIT=2`) need the registers they read before the back has them | the front keeps copies: every write it sends plus what the back changes on its own (constant buffer offset, shadow_scratch[0], macro bind pointer, shadow RAM). `EDEN_NX2_SPLIT_VERIFY=1` found three differences: writes still in the back's method sink at the handover; a multi-word run that changes the shadow RAM mode mid-run; and shadow_state.shadow_ram_control being the shadow copy of register 0x49 itself (a Replay write reads the mode back) | all three modelled: 0 differences in 40,193 checks (~165 million macro calls). Front: macros 128 ns a call (180 on one thread, cache-hot), drops ~55% of 3D state writes as same-value. Back: 50,000-66,500 draws a second against 41,500-47,000 without the split; frames 20.5 / 25.5 ms on two courses where the unsplit runs measured 25.6-40.7 ms. Default stays off until a clean A/B |
| 145 | is the split worth having on by default | clean A/B, nothing else running, 3 rounds each (profiler on in both): one thread 41,100 / 48,600 / 37,000 draws a second, frames 30.5 / 35.0 / 27.1 ms; `EDEN_NX2_SPLIT=2` 59,200 / 62,400 / 62,700 draws a second, frames 28.6 / 23.3 / 25.1 ms. Throughput 1.46x, frames 17% shorter (the back is now ~92% busy, ~53% of it draw setup); 0 crashes, 0 register differences in 57,089 checks after the front's fast paths (no guarded statics, inline ring writes) | on by default for Switch 2 titles (`EDEN_NX2_SPLIT=0` one thread, `=1` macros on the back). Default run without the profiler: 16.9 ms frames (~59 fps) on a light course |
+| 146 | title 4 aborts with InvalidHandle (0xE401) at its first movie, ~30 min into a new game | newer SDKs (`nn::codec::video::detail::InitializeServerContext`) open the decoder with gsv 906(u8, u64 library version 0x3'00030000) instead of 902; auto-stubbed, no handle came back | 906 hands out the 902 session (d8d11ec) |
+| 147 | title 1: Grand Prix cup-opening screen stays black, decoder registered but never started; then an abort with 2111-3604 (0x1c286f) when it did start | `nn::syncpt::sdk::CancelSyncPointEvent` sends 202 and always waits on the slot's event; we signalled it only for pending requests. Then the movie player reused slot 0, which NVN's fence waits had left signalled, read it as a decoded frame and found none | 202 always signals, 201 clears the slot's event first (b09629f) |
+| 148 | title 1/4 movies have no picture | the video decoder service (nn::codec::video, gsv 902/906/1002 -> vdec -> vdecsvc) completed frames without decoding | FFmpeg decodes on a thread per decoder service (`video_core/host1x/nx2_video_decoder`): 101 names the codec ("video/vp9") in an A buffer, 109 submits frames (A buffer, pts us). 311/314 reply NativeSyncHandles {~syncpoint, 0, value} on a syncpoint the service allocates, incremented per decoded frame, frames filling images in register/release order. gsv 911 creates the pool's images, 961 returns the CpuUserImageDescriptor that `ReadDecoderOutputImage*` copy out with (pitch-linear NV12/RGBA/BGRA, kinds 10/8/9). Title 1's Mushroom Cup opening (2560x1440 VP9, 1423 frames) decodes in real time and the game goes on to the race. Open: the picture on screen stays on the first frame: the game memcpys each frame into GPU memory (0x546000-byte NV12 buffer registered with gpu 101 before Start) and the texture cache never takes the later CPU writes. `EDEN_NX2_VDEC_DUMP=
` saves decoded frames |
Run settings used (in `build/bin/user/config/sdl2-config.ini`): `memory_layout_mode=4`
(12 GB). Debug knobs: `EDEN_NX2_TC_EXPECTED_MIB` / `EDEN_NX2_TC_CRITICAL_MIB` (collector thresholds),
diff --git a/src/core/hle/service/nx2_gsv.h b/src/core/hle/service/nx2_gsv.h
index 989a95dd1f..905e3a77a4 100644
--- a/src/core/hle/service/nx2_gsv.h
+++ b/src/core/hle/service/nx2_gsv.h
@@ -7,6 +7,10 @@
#include
#include
#include
+#include
+#include
+#include
+#include
#include
#include
#include
@@ -21,6 +25,7 @@
#include "common/alignment.h"
#include "common/settings.h"
+#include "common/thread.h"
#include "core/core.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/renderer_base.h"
@@ -43,10 +48,13 @@
#include "core/hle/kernel/k_transfer_memory.h"
#include "core/memory.h"
#include "video_core/host1x/host1x.h"
+#include "video_core/host1x/nx2_video_decoder.h"
#include "video_core/nx2.h"
#include "core/hle/service/hle_ipc.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/kernel_helpers.h"
+#include "core/hle/service/nvdrv/core/container.h"
+#include "core/hle/service/nvdrv/core/syncpoint_manager.h"
#include "core/hle/service/nvdrv/devices/nx2_stub_device.h"
#include "core/hle/service/nvdrv/nvdrv.h"
#include "core/hle/service/nvdrv/nvdrv_interface.h"
@@ -80,7 +88,7 @@ inline Kernel::KClientSession* CreateRawSession(Core::System& system, HLERequest
// Replies to a TIPC request with success and raw u32 data words. ResponseBuilder::Push(Result)
// writes the CMIF two-word result, which shifts TIPC data one word past where the client reads
// it (and past the copied size); TIPC has a one-word result followed directly by the data.
-inline void TipcReplyWords(HLERequestContext& ctx, std::initializer_list words) {
+inline void TipcReplyWords(HLERequestContext& ctx, std::span words) {
IPC::ResponseBuilder rb{ctx, static_cast(2 + words.size())};
rb.PushRaw(ResultSuccess.raw);
for (const u32 w : words) {
@@ -88,6 +96,10 @@ inline void TipcReplyWords(HLERequestContext& ctx, std::initializer_list wo
}
}
+inline void TipcReplyWords(HLERequestContext& ctx, std::initializer_list words) {
+ TipcReplyWords(ctx, std::span{words.begin(), words.size()});
+}
+
// Replies with success and a copied handle to a new session served by `iface`.
template
inline void ReturnRawSession(Core::System& system, HLERequestContext& ctx, std::shared_ptr iface) {
@@ -639,7 +651,9 @@ struct Nx2NativeObjects {
u32 memory{};
std::array preference{};
u64 size{};
+ u64 offset{}; // into its memory (images of a decoder pool share one)
bool window_pool{};
+ bool decoder{}; // a video decoder output image (gsv 911)
};
std::mutex mutex;
std::map memories;
@@ -681,6 +695,50 @@ inline Nx2ImageLayout Nx2CalculateImageLayout(const u32* preference) {
return layout;
}
+// Video decoder output images (nn::codec image pools, gsv 991/911/961). The preference
+// (MakeDecodeImagePreference) holds an output layout code at word 1 and (width - 1) |
+// (height - 1) << 16 at word 2. Codes come in pairs, one per CodecMode: 1/4 NV12 (format 3, what
+// the movie players use), 2/5 BGRA, 3/6 RGBA; the HDR codes (10-13) are written as RGBA. The
+// server picks the layout and describes it to the client with gsv 961: here pitch-linear rows,
+// NV12's half-height chroma plane below the luma plane, each plane padded to 128 rows.
+struct Nx2DecoderImageLayout {
+ u32 code;
+ u32 width;
+ u32 height;
+ Tegra::Host1x::Nx2PictureFormat format;
+ u64 pitch;
+ u64 chroma_offset;
+ u64 size;
+};
+
+inline Nx2DecoderImageLayout Nx2CalculateDecoderImageLayout(const u32* preference) {
+ using Tegra::Host1x::Nx2PictureFormat;
+ Nx2DecoderImageLayout layout{};
+ layout.code = preference[1];
+ layout.width = (preference[2] & 0xFFFF) + 1;
+ layout.height = (preference[2] >> 16) + 1;
+ switch (layout.code) {
+ case 1:
+ case 4:
+ layout.format = Nx2PictureFormat::Nv12;
+ break;
+ case 2:
+ case 5:
+ layout.format = Nx2PictureFormat::Bgra8;
+ break;
+ default:
+ layout.format = Nx2PictureFormat::Rgba8;
+ break;
+ }
+ const bool nv12 = layout.format == Nx2PictureFormat::Nv12;
+ constexpr u64 BlockRows = 128;
+ layout.pitch = Common::AlignUp(u64{layout.width} * (nv12 ? 1 : 4), 64);
+ layout.chroma_offset = layout.pitch * Common::AlignUp(u64{layout.height}, BlockRows);
+ layout.size = layout.chroma_offset +
+ (nv12 ? layout.pitch * Common::AlignUp((u64{layout.height} + 1) / 2, BlockRows) : 0);
+ return layout;
+}
+
// Placeholder for the Switch 2 display session (nn::vi2::sdk), handed out by gsv 305. Reply
// shapes read from the SDK: TIPC 1 -> u32 < 0x400, TIPC 3 -> u32 < 8, TIPC 11/31(u32) and
// 32(handle, u32) -> one handle at word 3 then the result. Handles returned here are events (a
@@ -1077,24 +1135,35 @@ private:
std::shared_ptr> m_capture_pending = std::make_shared>(false);
};
+// True the first time a Switch 2 video command is seen, so each one is logged once in full and new
+// or unexpected commands stand out.
+inline bool Nx2FirstVideoCommand(std::string_view service, u32 command) {
+ static std::mutex mutex;
+ static std::set> seen;
+ std::scoped_lock lk{mutex};
+ return seen.emplace(std::string{service}, command).second;
+}
+
// The Switch 2 video decoder (nn::codec::video::detail::ipc). gsv 902/906/1002 hand out a session
// whose TIPC 1 (CreateVideoDecoderService: handle at word 3, result at word 4) creates a decoder
// service, another session of this class. Layouts read from the SDK's nn::codec VP9 decoder:
// - 200(copy handle: work buffer transfer memory, u64 size, u32, u32, u32): initialize.
-// - 101(X: codec configuration, u32 0, u32 width, u32 height, u32 rate, u32 max input): configure.
-// - 3(): an event (copy handle at word 3, result at word 4) the client attaches as its
-// submission-ready event.
+// - 101(A: codec name, "video/vp9\0"; u32 width, u32 height, u32 rate, u32): configure.
+// - 3(): the submission-ready event (copy handle at word 3, result at word 4).
// - 6 / 207 / 8: start / stop / flush; 115: finalize.
-// - 311(u32 image id): register an output image (gsv 911 creates it); reply a 16-byte
-// NativeSyncHandle, all zero reading as already signalled. The client acquires output images
-// in registration/release order from a ring of its own (no IPC).
-// - 314(u32 image id, u32, NativeSyncHandle): give an output image back; reply a new handle.
+// - 311(u32 image id): register an output image (gsv 911 creates it); reply its NativeSyncHandle,
+// signalled once a frame has been decoded into the image. The client acquires output images in
+// registration/release order from a ring of its own (no IPC), so frames fill them in that order.
+// - 314(u32 image id, u32, NativeSyncHandle): give an output image back; the image may be
+// rewritten once that handle (the client's reads) has passed. Reply the image's next handle.
// - 212(u32 image id): unregister it.
// - 109(A: one compressed frame, u64 pts in us, u8 end of stream): submit input; reply a u64.
// - 213(): the next finished frame (16 words): u32 image id, u32 width, u32 height, u32 width,
-// u32 height, u32 colour space, u64 pts, u8 end of stream.
-// Frames are not decoded yet: each submitted frame completes at once into the next free output
-// image, so movies run to their end (with no picture) instead of stalling.
+// u32 height, u32 colour space, TimeSpan pts (ns), u8 end of stream.
+// A NativeSyncHandle is {u32 SyncCounterId (~syncpoint), u32 mode, u64 value}; clients wait on it
+// with nx2:syncpt 103/201. Each decoder service owns a syncpoint that counts its finished frames.
+// FFmpeg decodes on a thread of the session's own (a 1440p VP9 frame takes milliseconds, and the
+// service thread also serves presents and syncpoint waits) into the layout gsv 961 describes.
class INx2VideoSession final : public ServiceFramework {
public:
explicit INx2VideoSession(Core::System& system_, std::shared_ptr objects_,
@@ -1105,12 +1174,12 @@ public:
{1, &INx2VideoSession::CreateDecoderService, "CreateVideoDecoderService"},
{3, &INx2VideoSession::GetEvent, "GetEvent"},
{6, &INx2VideoSession::Succeed, "Start"},
- {8, &INx2VideoSession::Succeed, "Flush"},
+ {8, &INx2VideoSession::Flush, "Flush"},
{101, &INx2VideoSession::Configure, "Configure"},
{109, &INx2VideoSession::SubmitInput, "SubmitInputBuffer"},
{115, &INx2VideoSession::Succeed, "Finalize"},
{200, &INx2VideoSession::Succeed, "Initialize"},
- {207, &INx2VideoSession::Succeed, "Stop"},
+ {207, &INx2VideoSession::Flush, "Stop"},
{212, &INx2VideoSession::UnregisterBuffer, "UnregisterBuffer"},
{213, &INx2VideoSession::GetOutputInfo, "GetOutputInfo"},
{311, &INx2VideoSession::RegisterBuffer, "RegisterBuffer"},
@@ -1119,6 +1188,14 @@ public:
}
~INx2VideoSession() override {
+ if (m_worker.joinable()) {
+ {
+ std::scoped_lock lk{m_mutex};
+ m_quit = true;
+ }
+ m_cv.notify_all();
+ m_worker.join();
+ }
// The ready timer runs on the HostTiming thread: clear its event under its lock first.
{
std::scoped_lock lk{m_ready->mutex};
@@ -1130,23 +1207,58 @@ public:
if (m_event != nullptr) {
m_context.CloseEvent(m_event);
}
+ if (m_syncpoint != NoSyncpoint) {
+ NvdrvSyncpoints().FreeSyncpoint(m_syncpoint);
+ }
}
private:
- struct Output {
- u32 image;
+ struct Input {
+ std::vector data;
+ u64 pts; // us
+ bool end;
+ };
+ struct Decoded {
+ std::optional picture; // none: an empty end-of-stream frame
u64 pts;
bool end;
};
+ struct Output {
+ u32 image;
+ u32 width;
+ u32 height;
+ u64 pts;
+ bool end;
+ };
+ struct Fence {
+ u32 syncpoint;
+ u32 value;
+ };
+
+ static constexpr u32 NoSyncpoint = ~0U;
+ static constexpr size_t MaxQueuedInputs = 8;
+ static constexpr size_t MaxDecodedAhead = 2; // decoded frames held while no image is free
+ static constexpr u32 HostSyncpoints = 192; // Tegra::Host1x::SyncpointManager
void Log(HLERequestContext& ctx, std::string_view what) {
- if (m_logged++ < 64) {
- const auto* w = ctx.CommandBuffer();
- LOG_INFO(Service, "{} TIPC {} {}: [2]={:#x} [3]={:#x} [4]={:#x} [5]={:#x} [6]={:#x} [7]={:#x}",
- GetServiceName(), ctx.GetCommand(), what, w[2], w[3], w[4], w[5], w[6], w[7]);
+ const auto* w = ctx.CommandBuffer();
+ if (Nx2FirstVideoCommand(GetServiceName(), ctx.GetCommand())) {
+ LOG_INFO(Service, "{} TIPC {} {} (first use): words {:08x}", GetServiceName(),
+ ctx.GetCommand(), what, fmt::join(std::span{w, 12}, " "));
+ } else {
+ LOG_DEBUG(Service, "{} TIPC {} {}: [2]={:#x} [3]={:#x} [4]={:#x} [5]={:#x}",
+ GetServiceName(), ctx.GetCommand(), what, w[2], w[3], w[4], w[5]);
}
}
+ Nvidia::NvCore::SyncpointManager& NvdrvSyncpoints() {
+ return system.ServiceManager()
+ .GetService("nvdrv", true)
+ ->GetModule()
+ ->GetContainer()
+ .GetSyncpointManager();
+ }
+
void CreateDecoderService(HLERequestContext& ctx) {
Log(ctx, "create decoder service");
ReturnRawSession(system, ctx,
@@ -1160,10 +1272,24 @@ private:
void Configure(HLERequestContext& ctx) {
const auto* w = ctx.CommandBuffer();
- // Words 2-3 are the X descriptor of the configuration data.
- m_width = w[5];
- m_height = w[6];
+ std::string codec;
+ if (!ctx.BufferDescriptorA().empty()) {
+ const auto name = ctx.ReadBufferA(0);
+ codec.assign(reinterpret_cast(name.data()),
+ strnlen(reinterpret_cast(name.data()), name.size()));
+ }
Log(ctx, "configure");
+ LOG_INFO(Service, "{} configure codec \"{}\" {}x{} rate {}", GetServiceName(), codec, w[5],
+ w[6], w[7]);
+ {
+ std::scoped_lock lk{m_mutex};
+ m_codec = std::move(codec);
+ m_width = w[5];
+ m_height = w[6];
+ }
+ if (!m_worker.joinable()) {
+ m_worker = std::thread{[this] { DecodeLoop(); }};
+ }
TipcReplyWords(ctx, {});
}
@@ -1171,9 +1297,9 @@ private:
Log(ctx, "event");
if (m_event == nullptr) {
m_event = m_context.CreateEvent(fmt::format("{}:Ready", GetServiceName()));
- // Ready for input at all times (frames complete as they are submitted). The client
- // attaches it auto-clearing, so one signal is consumed by the first wait: re-signal
- // every 4 ms; a spurious wake only makes it check again.
+ // The client attaches it auto-clearing, so one signal is consumed by the first wait:
+ // while the input queue has room, re-signal every 4 ms; a spurious wake only makes it
+ // check again.
{
std::scoped_lock lk{m_ready->mutex};
m_ready->event = m_event;
@@ -1183,7 +1309,7 @@ private:
[ready = m_ready, &kernel = system.Kernel()](
s64, std::chrono::nanoseconds) -> std::optional {
std::scoped_lock lk{ready->mutex};
- if (ready->event != nullptr) {
+ if (ready->event != nullptr && ready->room.load(std::memory_order_relaxed)) {
ready->event->Signal(kernel);
}
return std::nullopt;
@@ -1197,32 +1323,50 @@ private:
rb.PushCopyObjects(ctx, m_event->GetReadableEvent());
}
+ // Queues an output image for the next decoded frame; returns the NativeSyncHandle words that
+ // signal once that frame is in it.
+ std::array HandOut(u32 image, std::optional release_fence) {
+ if (m_syncpoint == NoSyncpoint) {
+ m_syncpoint = NvdrvSyncpoints().AllocateSyncpoint(false);
+ m_sync_base = system.Host1x().GetSyncpointManager().GetGuestSyncpointValue(m_syncpoint);
+ LOG_INFO(Service, "{} counts decoded frames on syncpoint {} from {}",
+ GetServiceName(), m_syncpoint, m_sync_base);
+ }
+ u32 value;
+ {
+ std::scoped_lock lk{m_mutex};
+ m_free.push_back(image);
+ if (release_fence) {
+ m_release_fences[image] = *release_fence;
+ }
+ value = m_sync_base + ++m_handed;
+ }
+ m_cv.notify_one();
+ return {~m_syncpoint, 0, value, 0};
+ }
+
void RegisterBuffer(HLERequestContext& ctx) {
Log(ctx, "register output");
- GiveBack(ctx.CommandBuffer()[2]);
- TipcReplyWords(ctx, {0, 0, 0, 0});
+ const auto handle = HandOut(ctx.CommandBuffer()[2], std::nullopt);
+ TipcReplyWords(ctx, {handle[0], handle[1], handle[2], handle[3]});
}
void ReleaseBuffer(HLERequestContext& ctx) {
+ const auto* w = ctx.CommandBuffer();
Log(ctx, "release output");
- GiveBack(ctx.CommandBuffer()[2]);
- TipcReplyWords(ctx, {0, 0, 0, 0});
+ const auto handle = HandOut(w[2], Fence{~w[4], w[6]});
+ TipcReplyWords(ctx, {handle[0], handle[1], handle[2], handle[3]});
}
void UnregisterBuffer(HLERequestContext& ctx) {
Log(ctx, "unregister output");
- std::erase(m_free, ctx.CommandBuffer()[2]);
- TipcReplyWords(ctx, {});
- }
-
- // An output image is free again: a frame waiting for one completes into it.
- void GiveBack(u32 image) {
- if (!m_waiting.empty()) {
- m_outputs.push_back({image, m_waiting.front().pts, m_waiting.front().end});
- m_waiting.pop_front();
- return;
+ const u32 image = ctx.CommandBuffer()[2];
+ {
+ std::scoped_lock lk{m_mutex};
+ std::erase(m_free, image);
+ m_release_fences.erase(image);
}
- m_free.push_back(image);
+ TipcReplyWords(ctx, {});
}
void SubmitInput(HLERequestContext& ctx) {
@@ -1231,37 +1375,221 @@ private:
const u64 pts = u64{w[5]} | (u64{w[6]} << 32);
const bool end = (w[7] & 0xFF) != 0;
Log(ctx, "submit");
- if (!m_free.empty()) {
- m_outputs.push_back({m_free.front(), pts, end});
- m_free.pop_front();
- } else {
- m_waiting.push_back({0, pts, end});
+ Input input{{}, pts, end};
+ if (!ctx.BufferDescriptorA().empty()) {
+ const auto data = ctx.ReadBufferA(0);
+ input.data.assign(data.begin(), data.end());
}
+ {
+ std::scoped_lock lk{m_mutex};
+ m_inputs.push_back(std::move(input));
+ m_ready->room.store(m_inputs.size() < MaxQueuedInputs, std::memory_order_relaxed);
+ }
+ m_cv.notify_one();
const u64 id = ++m_submitted;
- if (m_event != nullptr) {
- m_event->Signal(system.Kernel());
- }
TipcReplyWords(ctx, {static_cast(id), static_cast(id >> 32)});
}
+ // Flush (8) and Stop (207): drop queued input and frames not yet in an image. Images already
+ // handed out keep their place, so the sync values stay in step with the client's ring.
+ void Flush(HLERequestContext& ctx) {
+ Log(ctx, ctx.GetCommand() == 8 ? "flush" : "stop");
+ {
+ std::scoped_lock lk{m_mutex};
+ m_inputs.clear();
+ m_flush = true;
+ m_ready->room.store(true, std::memory_order_relaxed);
+ }
+ m_cv.notify_one();
+ TipcReplyWords(ctx, {});
+ }
+
void GetOutputInfo(HLERequestContext& ctx) {
Log(ctx, "output info");
- if (m_outputs.empty()) {
+ std::optional