From c3008116398bafb740fd1138d1ee089ddb18ff1f Mon Sep 17 00:00:00 2001 From: Usif <19160089+Im-Usif@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:54:20 +0300 Subject: [PATCH 01/64] [GPU/AGC] Faster command stream, compute dispatches and render slices (#1153) * Kernel: keep paced usleep naps above the spin limit sceKernelUsleep spins for 50 us or less and waits on a high-resolution timer above that. A thread that feeds an audio context has its sleep halved while the device runs short (AudioOut2Exports.ProducerSleepMicroseconds), which turns a nap just over the limit into a spin: 51 us becomes 25 us. Guest worker threads that push audio and nap just over 50 us between polls then spin instead of sleeping, and the process takes several more cores whenever the audio queue runs low. A sleep that was above the spin limit now stays above it after the producer adjustment. * DispatchChain: no barrier between same-program writes the guest left unordered Inside a chain whose dispatches all run one program, a dispatch whose only overlaps with the chain are plain writes over plain writes, or atomic accesses over atomic accesses, now joins without a barrier. The guest orders compute dispatches only with its own wait and cache events, which already end the chain with a full barrier; it put none between these dispatches, so it does not rely on their order. The common case is culling: consecutive dispatches append through an atomic counter into one output buffer at disjoint offsets, and each of them used to take a draining barrier. A read of a chain write, a write over a chain read, an atomic access against a plain one, image conflicts and a different program keep their barrier. Atomic bindings are tracked apart from plain reads and writes, and chain spans are merged on commit so long runs keep short lists. SHARPEMU_CHAIN_SAME_PROGRAM_WRITES=0 restores a barrier at every overlap; GPU_SYNC counts the joins as chain_same_program. * GPU: compute rebind tickets for direct dispatches The command thread rebinds a kept compute program at every direct dispatch (new user data, stage inputs, resource materialization), and that work sits on the stream's critical path. At a direct dispatch the interpreter now scans the packets that follow it in its buffer on a shadow copy of the compute registers (shader register writes and tables, events, write-data packets and inert NOPs pass; any other packet ends the scan) and requests a ticket for each direct dispatch it finds. Three worker threads run those rebinds with every guest read recorded. A dispatch takes its ticket where it would rebind only when the ticket is finished, was made for the same kept program, registers, groups and initiator, and every byte it read still holds: no pending GPU write, publication, store or GPU-dirty byte over it, and the bytes read the same. Otherwise the dispatch rebinds as before. A ticket worker never compiles, links or raises a fatal: where the command thread would, the speculative resolve throws SerialResolveRequiredException and the dispatch rebinds serially. SHARPEMU_COMPUTE_TICKETS=0 turns tickets off. SHARPEMU_COMPUTE_TICKETS=verify also rebinds every taken dispatch on the command thread, compares the two and keeps the serial result (mismatches on the [PERF][TICKETS] line under SHARPEMU_PROFILE_RENDER). * GPU: slice joins keep segments whose metadata saw only consumed clears A render-worker slice segment fails its join when any metadata event reached a used image's metadata since the segment was recorded, and its items then run on the render thread. A clear that an earlier stream item consumed between the recording and the join is such an event, but the recorded use still holds: the worker stops at a pending clear, so it recorded the use with none, and the clear ran before the segment. Metadata events now record whether they changed only clear state (a slice's clear bit, a register clear, a fill tracked on a registered DCC surface). A use passes the join when every event at its metadata since the segment began was such a change and no slice its view covers is still clear (every slice for a 3D view). Registrations, invalidations, removals and an overflowed event ring still fail it. * GPU: cheaper ticket read checks; queued stores and fills in the check The command thread validates every compute ticket's guest reads before it uses the ticket. Two of its tests are now cheaper with the same result: a shadow test returns at once when no known write is newer than the executed position or the range lies outside the known writes' bounds, which are published with the shadow snapshot; and the pending-write query takes its lock only when the lock-free MayHavePending filter says the range may have pending writes (also in the resolve workers' read check). The check now also covers work the stream queued after the ticket read and has not run yet, which leaves raw guest memory unchanged: a queued fill or copy over a read range refuses the ticket, and a range with queued stores is read through the store overlay, the view the serial rebind reads. * GPU: compute tickets refuse reads their take cannot check again A ticket's take checks again only the reads its worker logged. A read the worker could not serve (unreadable, GPU-owned, pending, served from a known GPU write, or a failed overlay read) left no entry, so the materializer could resolve without those bytes while the serial rebind at the take served them; the worker now refuses the ticket instead. A clean read keeps its class in the read log and the take checks it again with the command thread's clean test, which also refuses a page a GPU write may own and an image's GPU-modified bytes. * GPU: command stream store index keeps large stores as ranges and filters page tests HasPendingStores tested every page of a read against a concurrent dictionary, and every queued store noted each of its pages when it was posted and again when it landed. A store over more than 16 pages is now kept as one range (a single-page overlay read it overlaps scans the ordered store queue instead of a page queue), and a count per bucket of pages answers most page tests without the dictionary. * GPU: pooled buffers for posted word copies A posted word copy allocated a new array for its bytes, up to 16 MiB, every time, which churned the large object heap and drove gen2 collections. Copies of 64 KiB or more now rent a buffer from a bounded pool (64 KiB classes, at most 48 MiB idle); the queued store returns it once it lands on the render thread, or the command stream returns it when the copy is refused. A store keeps its own length, since a pooled buffer can be longer. * Agc: write register and indirect draw packets in one piece sceAgcCbSetShRegistersDirect read its (offset, value) entries a dword at a time and wrote each SET_SH_REG packet as a header, an offset and one write per value. sceAgcDcbDrawIndexIndirect wrote its five dwords in four writes, and sceAgcCbSetShRegisterRangeDirect allocated its NOP marker and its SET_SH_REG packet apart, each with its own cursor update and header write. These exports run for most draws, and every guest memory access goes through its own mapping lookup and write notification. The register list now comes in one read, and each run of consecutive registers is built in full and written with one allocation and one write. The indirect draw writes its packet in one write. A register range takes its marker and packet in one allocation, and writes the marker and header in one write, when both packets fit without the buffer-full callback; otherwise they are allocated apart as before, so the callback still runs between the two packets. The guest bytes, the cursor and the returned packet address stay the same, in buffers too full for a packet too. A range whose marker and header cannot be written returns null with the one allocation in place; nothing is rolled back or allocated again. * Cpu: AGC packet writers and register patches take the leaf import tiers The import dispatch has two cheaper tiers for exports that cannot park the calling guest thread. The leaf tier runs an export without the full import bookkeeping; the trivial tier also leaves out the import call frame and the stack and block handling, for exports that read only argument registers and never block or call back into the guest. sceAgcCbSetShRegistersDirect already took the leaf tier, while sceAgcCbSetShRegisterRangeDirect and sceAgcDcbDrawIndexIndirect took the full path. They now take the leaf tier, which keeps the import call frame their buffer-full callback needs. sceAgcSet{Cx,Sh,Uc}RegIndirectPatchAddRegisters and sceAgcCreatePrimState only read argument registers and the guest memory those point to, so they take the trivial tier. * GPU: eager readbacks of hot buffers once their writer has finished A guest read of GPU-written memory marks its window hot, and the next GPU write into a hot window made it a candidate for an eager readback. The readback started at the next batch submit and waited on the readback queue for its writer, and a hot write ended rendering early to flush its batch. The CPU consumed few of those readbacks, so they were off unless SHARPEMU_EAGER_READBACKS=1. Eager readbacks are now always on. A candidate remembers the tick of its newest write and is not looked at again before the GPU completes that tick, so its copy starts with nothing left to wait for. The render thread pumps them between command items: the pump lands finished readbacks and starts the candidates whose writer completed. While every candidate still waits for its writer it costs one compare, and readbacks in flight are checked at most every 50 us. A hot write no longer flushes the batch. A faulting buffer of up to 512 KiB has a hot entry of its own, so a write anywhere in it makes it a candidate even past a window boundary; larger buffers keep one entry per 512 KiB window. Hot entries live 4,096 batches instead of 512, mapped buffers are read ahead too, and up to 16 readbacks run at a time instead of 4. A landing that went stale still counts a strike, and three strikes still mute the window. * GPU: windowed device-address programs sweep only their handle windows Before a device-address program runs, the buffer cache uploads every CPU-dirty page of every GPU-mapped span (the sweep), unless every range the program reads is bounded exactly. Most programs that fail that test read through a handle plus a run-time offset: a scalar address read, or a global read with a scalar base, adds a zero-extended 32-bit offset and a signed immediate to the handle's 64-bit base, so it reaches only [base + first byte, base + 2^32 + end byte). A program's device-address ranges now mark it windowed when every range it does not bound exactly is such a read-only handle with a plannable base, with the widest window measured from the evaluated range base. A preparation whose device-address stages are all bounded or windowed, with at least one windowed, sweeps the mapped spans cut to the union of its windows; a window that would wrap the 48-bit address space keeps the full sweep. A render worker's segment carries the windows of its windowed dispatches to the join, which cuts the spans current at the join to them; one dispatch that is not windowed keeps the full sweep for the whole segment. Each set of swept spans keeps its own state (touch tick, plan, epoch, registrations and observation): the mapped spans one, reset when their key changes, and windowed spans one each in a table of eight, tied to the key of the mapped spans they were cut from. A windowed sweep leaves the dirty pages outside its windows to the next sweep that covers them. * GPU: slice joins apply the pending depth clears of their segments A render worker stopped at every depth draw whose HTILE slice held a pending clear, and the draw and the rest of its slice ran on the render thread. The worker now notes a clear entry for each depth view with HTILE it first acquires in a segment: the view, its HTILE address and base layer, the draw's clear value and the area of the segment's first rendering with the view. A pending HTILE clear passes when the segment holds an entry for the view. The draw's own depth clear, or an earlier use of the image other than as depth, still stops the worker, and an item that stops it takes its entries out of the segment. At the join, a depth use with an entry passes the metadata check when only clear-state events reached its metadata, even with a covered slice still waiting on a clear. After the other checks, the join refuses the segment when an entry whose base layer is still clear has no rendering area, or when the entry's image has another use in the segment. The prologue then records each entry whose base layer is still clear ahead of the segment, after the image uses are applied, as the render thread's first acquisition of the view would: it consumes the clear state and clears the area with the draw's value (an empty rendering with a depth clear load). Stencil is left untouched. * GPU: an image used the frame before counts as used where overlaps park aliases Where an overlapping request decides whether a cached image is safe to park or delete, an image counted as used only when the current frame had used it. Two aliases of the same memory that a title uses every frame then swapped at each one's first use in a frame, each request parking the other alias. An image the frame before used now counts as used too, in the serial lookup and the render workers' read-only lookup alike, so both aliases stay registered. An alias unused for a whole frame is parked as before. * GPU: slice joins apply native color clears that only update a registration A render worker stopped at a native color clear that was not settled, and the item and the rest of its slice ran on the render thread. A clear that is unsettled only because the image's metadata registration is not current (no slice holds a clear code, so the render thread's apply would update the registration and record nothing) now passes, and the segment carries it as an entry instead of a settled use. After every other check of the join, the join refuses the segment when an entry would now record a clear, when its metadata cannot be read or lies outside its slices, or when its metadata is GPU-dirty. Otherwise it runs the apply of each entry in stream order. The worker decides with a read-only prediction of the apply. Unlike the settled check, the prediction reads the slices of an image whose registration is not current, and it reports unreadable metadata instead of failing on it. * VideoOut: a deeper command queue overlaps the command thread and the render side The command queue held 1,024 items, and a producer that filled it waited until the render thread had drained it to half. Each fill of the render thread's units pulled at most one batch of items, however many slices the render workers could record ahead. The command thread and the render side took turns. The queue now holds 4,096 items, or a larger configured depth, and a waiting producer resumes once the queue is an eighth below its cap. A fill cuts slices up to the look-ahead limit (two per render worker) instead of stopping after a batch, so the workers keep recording while the render thread joins. * GPU: dispatch replay with a new flattened table A compute dispatch replays the sealed dispatch before it, keeping its pipeline, descriptors and storage bindings and pushing only new user data, when its stage inputs are equal. Programs that bind a flattened resource table never sealed, so every dispatch of them took the full binding path, even in long runs where only the table changes from one dispatch to the next. A compute program whose one replay refusal is its flattened table now seals a replay basis too. A dispatch whose stage differs from the sealed one only in its flattened table replays with the table uploaded again, as the full path uploads it, and only that descriptor pushed; the other pushed descriptors stay bound. This needs push descriptors, and where the native state is shadowed, the compute descriptor shadow must still hold the sealed set: its table entry takes the new descriptor, so the next full commit compares against it. A dispatch with the same table replays as before. A render worker's dispatch whose bindings took a stream copy (a read-only range copied into the slice arena as it stood at that item) is no longer captured for replay. The replay keeps the sealed descriptors, so a later dispatch would read the earlier item's copy. * GPU: deferred dispatch runs resolve direct dispatches on workers A direct dispatch of a kept compute program rebinds the program on the command thread (new user data, stage inputs, resource materialization), which keeps that work on the stream's critical path through long runs of dispatches. From the third direct dispatch of one kept program in a row, the command thread now copies the dispatch's compute registers and queues it at its stream position as a member of a deferred run; an open run then takes every deferrable dispatch, whatever its program. Six worker threads (never more than half the logical processors) rebind and decode the members with every guest read recorded. Whichever thread finishes a member finalizes every member that is ready, in stream order: it checks the member's reads against the pending writes of the members before it and publishes the member's own write marks. A worker that finds the finalizer busy goes on resolving, and the holder looks at the head once more before it leaves. While a run is open no release passes its first member, so those checks see every earlier write. Programs with shader calls, a decoded kernel or no fast materialization, and empty or indirect dispatches, stay on the command thread. A run holds only direct dispatches, compute-range shader register writes and tables, the cache and flush events that only queue a barrier in stream order, and inert NOPs and markers. Any other packet, the end of the buffer, or ring memory the guest has not written yet first waits at the barrier: the command thread resolves the members no worker took yet itself and waits until every member is finalized, so every later consumer sees complete marks. A shader table applied during a run is logged before its check. A member found to write one, or a member a worker could not resolve (a read it cannot serve and log, a pending or rejected program, a decoded fill, copy or clear, a linked program), cancels the members from that point and rolls the stream back: the compute registers and the raw shader register mirror are restored as they stood at that member's issue, the packets run again from there, and deferral is held off until the next barrier. A table found GPU-written closes the run before its live read. A member whose reads no longer hold at its stream position is resolved again on the render thread. The identity recheck turn of a deferred member moves to the program's next dispatch on the command thread, which resolves it from scratch. The compute ticket scan stops at the dispatch that would start a run. * ShaderCompiler: materialization programs select branches on lowered registers A materialization program chose the active sources of a plan with resource branches through RuntimeValueEvaluator.EvaluateActiveSources on every run. Each draw built a clean evaluator with its own inputs, and for a plan that writes memory a write guard with another evaluator, inputs and read list, and every condition went through the evaluator's caches. The program now lowers the conditions and the written buffers' descriptor words once per plan into registers (ShaderResourcePlan.BranchSelection) and walks the blocks on them. The walk keeps its state in a per-thread scratch that it takes out of its slot, so a guest read that selects for another draw on the same thread gets its own; TryRunInto keeps its active sources in its own scratch. Clean reads have effects (a resolve worker logs them, and a read can send the draw back to the stream), so the walk reads exactly what the evaluator reads, in its order: each visited block's condition, operand by operand, with every success kept for the call; both arms of a select; a refused word reads as zero only through a null base. For a plan that writes memory, the written descriptors then go through the write guard's own test, now a static helper both share, against the words the conditions read. A plan whose conditions or written descriptors do not lower (a first-lane read, for one) and a draw without a clean reader keep the evaluator's walk. * GPU: overlaps keep only recurring aliases from the frames before An image the frame before used counted as used, so every alias of the last two frames over the same memory stayed registered, each watching its pages. ASTRO BOT reached a page's limit of 127 watches on its world map ("Cannot add a write watch"). An image now counts as used from the frames before only when each of the two frames before used it. Two aliases a title uses every frame still stay registered; an image used in one frame only is parked after it, as before. --- .../Native/DirectExecutionBackend.Imports.cs | 8 +- .../Agc/AgcExports.CommandStream.cs | 32 + .../Agc/AgcExports.DeferredDispatchRuns.cs | 644 ++++++++++++++++++ .../Agc/AgcExports.DrawPackets.cs | 7 +- .../Agc/AgcExports.RegisterPackets.cs | 59 +- .../Agc/AgcExports.ResolvePool.cs | 14 +- src/SharpEmu.Libs/Agc/AgcExports.cs | 16 +- src/SharpEmu.Libs/Agc/AgcPacketWrites.cs | 7 +- .../Gpu/Buffers/GuestBufferCache.cs | 356 ++++++++-- .../Gpu/GpuCommands/DeferredDispatchRuns.cs | 62 ++ .../GpuCommandInterpreter.ComputeTickets.cs | 254 +++++++ .../GpuCommandInterpreter.Draws.cs | 39 ++ .../GpuCommandInterpreter.Registers.cs | 41 ++ .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 137 ++++ .../Gpu/GpuCommands/ICommandStreamHost.cs | 14 + .../Registers/ShaderProgramRegisters.cs | 34 + .../Gpu/GpuCommands/ResolveReadLog.cs | 15 +- .../Gpu/GpuCommands/ShaderRegisterMirror.cs | 22 + src/SharpEmu.Libs/Gpu/Images/CachedImage.cs | 3 + .../Gpu/Images/GuestImageCache.Metadata.cs | 103 ++- .../GuestImageCache.NativeColorClear.cs | 51 ++ .../Gpu/Images/GuestImageCache.Overlap.cs | 20 +- .../Gpu/Images/GuestImageCache.Slices.cs | 35 +- .../Gpu/Images/GuestImageCache.Tracking.cs | 9 + .../Gpu/Pipelines/ComputeTickets.cs | 382 +++++++++++ .../Gpu/Pipelines/DeferredDispatchInputs.cs | 28 + .../Gpu/Pipelines/ShaderPipelineCache.cs | 249 ++++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 40 ++ .../Gpu/Rendering/DispatchChain.cs | 123 +++- .../Gpu/Rendering/IRenderHost.cs | 4 +- .../Gpu/Rendering/PendingGpuWrites.cs | 23 + .../Gpu/Rendering/RenderExecutor.Compute.cs | 93 +++ .../Rendering/RenderExecutor.PendingWrites.cs | 45 +- .../Gpu/Rendering/RenderRecorder.Compute.cs | 18 +- .../Gpu/Rendering/RenderRecorder.cs | 68 +- .../Gpu/Rendering/ShaderStageResources.cs | 5 + .../Gpu/Vulkan/GpuSyncProfile.cs | 2 +- .../Kernel/KernelRuntimeCompatExports.cs | 4 +- .../VideoOut/PendingStorePages.cs | 127 ++++ .../VideoOut/RenderPhaseProfile.cs | 1 + src/SharpEmu.Libs/VideoOut/StoreBufferPool.cs | 84 +++ .../VulkanVideoPresenter.CommandStream.cs | 85 ++- .../VulkanVideoPresenter.CommandThread.cs | 143 ++-- .../VulkanVideoPresenter.Descriptors.cs | 85 +++ .../VulkanVideoPresenter.DrawReplay.cs | 118 +++- .../VulkanVideoPresenter.KernelWrites.cs | 25 +- .../VulkanVideoPresenter.Pipelines.cs | 33 +- .../VulkanVideoPresenter.Rendering.cs | 11 +- .../VideoOut/VulkanVideoPresenter.Slices.cs | 279 +++++++- .../Resources/DeviceAddressRangePlanner.cs | 45 +- .../MaterializationProgram.Branches.cs | 420 ++++++++++++ .../Resources/MaterializationProgram.cs | 33 +- .../Resources/ResourceBranchWriteGuard.cs | 35 +- .../Resources/RuntimeValueEvaluator.cs | 2 + .../Resources/ShaderResourcePlan.cs | 24 +- .../Agc/AgcPackedRegisterPacketTests.cs | 371 ++++++++++ .../Agc/AgcSetShRegisterRangeTests.cs | 10 +- .../Cpu/ImportLeafTierTests.cs | 50 ++ .../Buffers/GuestBufferAsyncReadbackTests.cs | 19 +- .../Buffers/GuestBufferEagerReadbackTests.cs | 152 +++++ .../Buffers/GuestBufferWindowSweepTests.cs | 102 +++ .../GpuCommands/CommandStreamTestSupport.cs | 4 + .../GpuCommands/DeferredDispatchRunTests.cs | 179 +++++ .../Gpu/GpuCommands/ResolveReadLogTests.cs | 20 + .../Images/GuestImageCacheTests.BlockAlias.cs | 8 +- .../Gpu/Images/GuestImageCacheTests.Lookup.cs | 44 +- .../Images/GuestImageCacheTests.Metadata.cs | 75 ++ .../GuestImageCacheTests.NativeColorClear.cs | 31 + .../GuestImageCacheTests.SliceDepthClears.cs | 46 ++ .../Gpu/Pipelines/ComputeTicketTests.cs | 284 ++++++++ .../Gpu/Rendering/DispatchChainTests.cs | 111 ++- .../Gpu/Rendering/DispatchTableReplayTests.cs | 97 +++ .../Gpu/Rendering/PendingGpuWritesTests.cs | 23 + .../Rendering/RenderExecutorTestSupport.cs | 15 + .../VideoOut/CommandStreamStoreIndexTests.cs | 67 ++ .../VideoOut/PendingStorePagesTests.cs | 97 +++ .../VideoOut/ResolveWorkerReadTests.cs | 59 ++ .../VideoOut/SliceRecordingTests.cs | 41 ++ .../VideoOut/StoreBufferPoolTests.cs | 75 ++ .../Resources/DeviceAddressWindowTests.cs | 99 +++ .../Resources/ResourceBranchTests.cs | 406 ++++++++++- 81 files changed, 6792 insertions(+), 309 deletions(-) create mode 100644 src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs create mode 100644 src/SharpEmu.Libs/Gpu/GpuCommands/DeferredDispatchRuns.cs create mode 100644 src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/ComputeTickets.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/DeferredDispatchInputs.cs create mode 100644 src/SharpEmu.Libs/VideoOut/PendingStorePages.cs create mode 100644 src/SharpEmu.Libs/VideoOut/StoreBufferPool.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs create mode 100644 tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Cpu/ImportLeafTierTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferEagerReadbackTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferWindowSweepTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SliceDepthClears.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchTableReplayTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreIndexTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/PendingStorePagesTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/ResolveWorkerReadTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/StoreBufferPoolTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceAddressWindowTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs index de4abc582..4ee718157 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs @@ -1724,7 +1724,11 @@ nid is "1j3S3n-tTW4" or // sceKernelGetTscFrequency "ob5xAW4ln-0" or // strchr "9yDWMxEFdJU" or // strrchr - "V++UgBtQhn0"; // sceAgcGetDataPacketPayloadAddress + "V++UgBtQhn0" or // sceAgcGetDataPacketPayloadAddress + "d-6uF9sZDIU" or // sceAgcSetCxRegIndirectPatchAddRegisters + "z2duB-hHQSM" or // sceAgcSetShRegIndirectPatchAddRegisters + "vRoArM9zaIk" or // sceAgcSetUcRegIndirectPatchAddRegisters + "D9sr1xGUriE"; // sceAgcCreatePrimState private unsafe ulong DispatchTrivialLeaf( CpuContext cpuContext, @@ -1949,6 +1953,8 @@ private bool IsLeafImport(string nid) "LtTouSCZjHM" or // sceAgcCbNop "k3GhuSNmBLU" or // sceAgcCbDispatch "UZbQjYAwwXM" or // sceAgcCbSetShRegistersDirect + "n2fD4A+pb+g" or // sceAgcCbSetShRegisterRangeDirect + "t1vNu082-jM" or // sceAgcDcbDrawIndexIndirect "JrtiDtKeS38" or // sceAgcAcbResetQueue "cFazmnXpJOE" or // sceAgcAcbEventWrite "KT-hTp-Ch14" or // sceAgcAcbAcquireMem diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index b766f8f5c..8fdb6a2df 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -255,9 +255,25 @@ internal IDeferredWorkSink? Sink _host.RenderHost is { } renderHost && _host.ResolveWorkerCount > 0 ? new ResolvePool(this, renderHost, _host.ResolveWorkerCount) : null; + ReplaceDispatchRuns(value is not null); + _computeTicketPool?.Dispose(); + _computeTicketPool = value is not null && _executor is not null && _pipelines is { SupportsParallelResolution: true } pipelines && + ComputeTickets.Mode != ComputeTickets.TicketMode.Off + ? new ComputeTickets(pipelines, reads => _host.BeginWorkerResolve(long.MaxValue, reads), () => _host.EndWorkerResolve(), + reads => _host.ValidateTicketReads(reads), ComputeTickets.WorkerCount, verify: ComputeTickets.Mode == ComputeTickets.TicketMode.Verify) + : null; + if (_pipelines is not null) + { + _pipelines.Tickets = _computeTicketPool; + } } } + // SHARPEMU_COMPUTE_TICKETS: worker rebinds for direct dispatches, with the command stream on its own thread. + private ComputeTickets? _computeTicketPool; + + internal ComputeTickets? ComputeTicketPool => _computeTicketPool; + private bool Producing => Sink is { IsProducerThread: true }; private sealed class ExecutorSink(CommandStreamTranslation owner) : IResolvedCommandSink @@ -304,6 +320,12 @@ public void RunDeferred(DeferredWork work) return; } + if (work is DeferredDispatch dispatch) + { + JoinDeferredDispatch(dispatch); + return; + } + RunDeferred(work, _recorder!); } @@ -319,6 +341,13 @@ internal void RunDeferred(DeferredWork work, RenderRecorder recorder) break; case DeferredDraw deferred: recorder.Record(deferred.Record!); + break; + case DeferredDispatch dispatch: + if (!dispatch.Cancelled) + { + recorder.Record(dispatch.Record!); + } + break; default: throw _host.Fatal($"The deferred work is unknown: {work.GetType().Name}."); @@ -345,6 +374,9 @@ internal void CompleteDeferred(DeferredWork work) case DeferredDraw deferred: CompleteDeferredDraw(deferred); break; + case DeferredDispatch dispatch: + CompleteDeferredDispatch(dispatch); + break; } } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs b/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs new file mode 100644 index 000000000..ea9b127ca --- /dev/null +++ b/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs @@ -0,0 +1,644 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; + +namespace SharpEmu.Libs.Agc; + +public static partial class AgcExports +{ + // A direct dispatch the command thread issued to the deferred dispatch workers. It is queued at its stream position at + // issue; Done is set when the finalizer, in stream order, found it valid or cancelled it. A cancelled member records + // nothing: the command thread runs it again after the rollback. + internal sealed record DeferredDispatch : DeferredWork + { + public override bool IsDispatch => true; + + public readonly DeferredDispatchInputs Inputs = new(); + public ulong SubmitId; + public long Sequence; + public int Index; + public int TableMark; + public int Depth; + public ulong CursorAddress; + public uint PacketOffset; + public int RawUndoMark; + public uint UserDataMarker; + public long FrontendImageVersion; + public ResolvedDispatch? Record; + // The worker could not resolve the member: the run rolls back to it and the command thread runs it. + public bool Refused; + public bool Cancelled; + // 1 once the worker no longer touches the member. + public int Resolved; + public readonly List Marks = new(); + public readonly ResolveReadLog Reads = new(); + public readonly ManualResetEventSlim Done = new(false); + + public void Reset() + { + Inputs.Reset(); + Record = null; + Refused = false; + Cancelled = false; + Resolved = 0; + FrontendImageVersion = 0; + Marks.Clear(); + Reads.Clear(); + Done.Reset(); + } + } + + internal sealed partial class CommandStreamTranslation + { + // Six workers, but never more than half the logical processors. + private static readonly int DeferredDispatchWorkers = Math.Clamp(Environment.ProcessorCount / 2, 1, 6); + + private DeferredDispatchRuns? _dispatchRuns; + + internal IDeferredDispatchRuns? DispatchRuns => _dispatchRuns; + + private void ReplaceDispatchRuns(bool create) + { + _dispatchRuns?.Dispose(); + _dispatchRuns = create && _executor is not null && _pipelines is { SupportsParallelResolution: true } && _host.RenderHost is { } renderHost + ? new DeferredDispatchRuns(this, renderHost, DeferredDispatchWorkers) + : null; + } + + private static void WaitDone(DeferredDispatch deferred) + { + var spinner = new SpinWait(); + while (!deferred.Done.IsSet && spinner.Count < 200) + { + spinner.SpinOnce(sleep1Threshold: -1); + } + + deferred.Done.Wait(); + } + + private bool ValidateDispatchReads(DeferredDispatch deferred) => + deferred.FrontendImageVersion == _pipelines!.FrontendImageVersion && _host.ValidateWorkerReads(deferred.Reads); + + // On a render worker: a cancelled member records nothing; a valid one records the worker's record while its reads hold. + private bool CanRecordDeferredDispatch(DeferredDispatch deferred) + { + WaitDone(deferred); + return deferred.Cancelled || ValidateDispatchReads(deferred); + } + + private void RecycleDispatch(DeferredDispatch deferred) + { + if (Volatile.Read(ref deferred.Resolved) != 1 || _dispatchRuns is not { } runs) + { + // The worker may still hold a cancelled member; the collector takes it. + return; + } + + deferred.Reset(); + runs.Return(deferred); + } + + private void CompleteDeferredDispatch(DeferredDispatch deferred) + { + _executor!.PendingWrites.Release(deferred.Sequence); + if (Volatile.Read(ref deferred.Resolved) == 1 && deferred.Record is { } record) + { + _pool!.Return(record); + deferred.Record = null; + } + + RecycleDispatch(deferred); + } + + // On the render thread at the member's stream position. + private void JoinDeferredDispatch(DeferredDispatch deferred) + { + WaitDone(deferred); + if (deferred.Cancelled) + { + _executor!.PendingWrites.Release(deferred.Sequence); + if (Volatile.Read(ref deferred.Resolved) == 1 && deferred.Record is { } dropped) + { + _pool!.Return(dropped); + deferred.Record = null; + } + + RecycleDispatch(deferred); + return; + } + + var record = deferred.Record!; + if (!ValidateDispatchReads(deferred)) + { + _pool!.Return(record); + record = ResolveDispatchOnThisThread(deferred); + } + + deferred.Record = null; + _recorder!.Record(record); + RecycleDispatch(deferred); + } + + // The member resolved on the render thread from its inputs, as the command thread would have resolved it. + private ResolvedDispatch ResolveDispatchOnThisThread(DeferredDispatch deferred) + { + var executor = _joinExecutor ??= new RenderExecutor(_host.RenderHost!, _pipelines!, _joinSink ??= new CapturingSink(), _executor!.PendingWrites, _pool); + var inputs = deferred.Inputs; + if (!_pipelines!.RunDeferredRebind(inputs, out var program)) + { + program = new ComputeProgram { Available = false }; + } + + var record = executor.ResolveDeferredDispatch(deferred.SubmitId, inputs.Compute, inputs.GroupsX, inputs.GroupsY, inputs.GroupsZ, inputs.Initiator, + program, serialOnly: true) ?? throw _host.Fatal("The serial resolve of a deferred dispatch produced no record."); + record.Sequence = deferred.Sequence; + return record; + } + + // Issues, resolves and finalizes deferred dispatch runs. From the third direct dispatch of one kept compute program + // in a row, the command thread copies each dispatch's compute registers and queues it at its stream position; an open + // run then takes every deferrable dispatch, whatever its program. Workers rebind and decode the members in any order. + // Whichever thread finishes a member finalizes every member that is ready, in stream order, under the finalize lock: + // it checks the member's reads against the marks of the members before it and publishes the member's own write + // marks. A shader table the command thread applied during the run is logged; a member found to write one, or a + // member a worker could not resolve, rolls the run back to that point. The command thread waits for the run at the + // barrier before any packet a run cannot hold. + private sealed class DeferredDispatchRuns : IDeferredDispatchRuns, IDisposable + { + private const int Capacity = 1024; + private const int TableCapacity = 4096; + private const uint DispatchPacketDwords = 5; + + private readonly CommandStreamTranslation _owner; + private readonly Thread[] _threads; + private readonly ConcurrentQueue _queue = new(); + private readonly SemaphoreSlim _wake = new(0); + private readonly ConcurrentQueue _spare = new(); + private int _parked; + private volatile bool _stopping; + + // The open run. The command thread writes _items, _issued and the table log; the finalizer reads them and writes + // _cursor, _poison and _rewind under _finalize. + private readonly DeferredDispatch?[] _items = new DeferredDispatch?[Capacity]; + private int _issued; + private int _cursor; + private int _poison = int.MaxValue; + private DeferredRewind? _rewind; + private readonly (ulong Address, ulong Size, int Member)[] _tables = new (ulong, ulong, int)[TableCapacity]; + private int _tableCount; + private readonly object _finalize = new(); + private readonly ManualResetEventSlim _drained = new(true); + + // Command thread only. + private RenderExecutor? _helper; + private bool _suppressed; + private KeptComputeProgram? _lastKept; + private int _sameCount; + + public DeferredDispatchRuns(CommandStreamTranslation owner, IRenderHost host, int workers) + { + _owner = owner; + _threads = new Thread[workers]; + for (var index = 0; index < workers; index++) + { + var executor = new RenderExecutor(host, owner._pipelines!, new CapturingSink(), owner._executor!.PendingWrites, owner._pool); + _threads[index] = new Thread(() => Run(executor)) { IsBackground = true, Name = $"SharpEmu deferred dispatch worker {index}" }; + _threads[index].Start(); + } + } + + public bool IsOpen => _issued != 0; + + public bool Active => _issued != 0 || _suppressed; + + public bool StopsTicketScan => !_suppressed; + + public bool WouldDefer(ComputeStageRegisters compute, uint initiator) => + compute.Address != 0 && _owner._pipelines!.FindDeferrableKept(compute, initiator) is not null; + + public void Return(DeferredDispatch deferred) => _spare.Enqueue(deferred); + + public void BreakChain() + { + _lastKept = null; + _sameCount = 0; + } + + public DeferredIssue TryIssue(in DeferredIssueSite site, uint groupsX, uint groupsY, uint groupsZ, uint initiator) + { + if (Volatile.Read(ref _poison) != int.MaxValue) + { + return DeferredIssue.Rewind; + } + + if (_suppressed) + { + return DeferredIssue.NotEligible; + } + + var state = _owner.RequireCurrent(); + var compute = _owner.RequireTypedRegisters(state).Shader.Compute; + if (compute.Address == 0 || RenderExecutor.IsEmptyDirectDispatch(compute, initiator, groupsX, groupsY, groupsZ)) + { + BreakChain(); + return DeferredIssue.NotEligible; + } + + var kept = _owner._pipelines!.FindDeferrableKept(compute, initiator); + if (kept is null) + { + BreakChain(); + return DeferredIssue.NotEligible; + } + + // An open run takes any deferrable dispatch; only a run's start needs three of one program in a row. + var joins = _issued != 0; + if (!ReferenceEquals(kept, _lastKept)) + { + _lastKept = kept; + _sameCount = 1; + if (!joins) + { + return DeferredIssue.NotEligible; + } + } + else if (++_sameCount < 3 && !joins) + { + return DeferredIssue.NotEligible; + } + + if (_issued == Capacity || _tableCount >= TableCapacity - 1) + { + return DeferredIssue.NotEligible; + } + + var item = _spare.TryDequeue(out var spare) ? spare : new DeferredDispatch(); + if (!_owner._pipelines.ClaimDeferral(kept, compute, groupsX, groupsY, groupsZ, initiator, item.Inputs)) + { + item.Reset(); + _spare.Enqueue(item); + return DeferredIssue.NotEligible; + } + + var index = _issued; + item.SubmitId = site.SubmitId; + item.Index = index; + item.TableMark = _tableCount; + item.Depth = site.Depth; + item.CursorAddress = site.CursorAddress; + item.PacketOffset = site.PacketOffset; + item.RawUndoMark = site.RawUndoMark; + item.UserDataMarker = site.UserDataMarker; + state.FrameDispatchCount++; + item.Sequence = _owner.Sink!.EnqueueDeferred(item, isDraw: false); + if (index == 0) + { + // No release may pass the run's first member until the run closes (PendingGpuWrites.HoldFrom). + _owner._executor!.PendingWrites.HoldFrom(item.Sequence); + } + + _items[index] = item; + Volatile.Write(ref _issued, index + 1); + _queue.Enqueue(item); + Interlocked.MemoryBarrier(); + if (Volatile.Read(ref _parked) > 0) + { + _wake.Release(); + } + + return DeferredIssue.Issued; + } + + public bool NoteTable(ulong address, ulong size) + { + var member = _issued; + if (member == 0) + { + return true; + } + + var count = _tableCount; + if (count == TableCapacity) + { + return false; + } + + _tables[count] = (address, size, member); + Volatile.Write(ref _tableCount, count + 1); + // The finalizer publishes marks and then reads the log; this logs and then reads the marks: one of the two sees + // the other. + Interlocked.MemoryBarrier(); + return true; + } + + public DeferredRewind? Barrier() + { + var issued = _issued; + if (issued == 0) + { + _suppressed = false; + return null; + } + + if (Volatile.Read(ref _cursor) != issued) + { + // The members no worker took yet are resolved here instead of waiting for them. + var helper = _helper ??= new RenderExecutor(_owner._host.RenderHost!, _owner._pipelines!, new CapturingSink(), + _owner._executor!.PendingWrites, _owner._pool); + while (Volatile.Read(ref _cursor) != issued && _queue.TryDequeue(out var queued)) + { + Process(helper, queued); + } + + var spinner = new SpinWait(); + while (Volatile.Read(ref _cursor) != issued && spinner.Count < 100) + { + spinner.SpinOnce(sleep1Threshold: -1); + } + + while (Volatile.Read(ref _cursor) != issued) + { + _drained.Reset(); + Interlocked.MemoryBarrier(); + if (Volatile.Read(ref _cursor) != issued) + { + // The barrier finalizes what is ready itself, so a member no worker finalized cannot stall the run. + lock (_finalize) + { + AdvanceLocked(); + } + + if (Volatile.Read(ref _cursor) != issued) + { + _drained.Wait(1); + } + } + } + } + + DeferredRewind? rewind; + lock (_finalize) + { + rewind = _poison != int.MaxValue ? _rewind : null; + Array.Clear(_items, 0, issued); + _cursor = 0; + _tableCount = 0; + _poison = int.MaxValue; + _rewind = null; + Volatile.Write(ref _issued, 0); + } + + _owner._executor!.PendingWrites.EndHold(); + if (rewind is not null) + { + _suppressed = true; + BreakChain(); + } + + return rewind; + } + + private void Run(RenderExecutor executor) + { + SharpEmu.HLE.Host.HostLaneReservation.ApplyToHostWorkerThread(); + VideoOut.RenderPhaseProfile.AttachResolveWorker(); + while (!_stopping) + { + if (!_queue.TryDequeue(out var item)) + { + var spinner = new SpinWait(); + while (spinner.Count < 50 && _queue.IsEmpty) + { + spinner.SpinOnce(sleep1Threshold: -1); + } + + if (!_queue.TryDequeue(out item)) + { + Interlocked.Increment(ref _parked); + if (!_queue.TryDequeue(out item)) + { + _wake.Wait(); + Interlocked.Decrement(ref _parked); + continue; + } + + Interlocked.Decrement(ref _parked); + } + } + + Process(executor, item); + } + } + + // On a worker, or on the command thread helping at a barrier. + private void Process(RenderExecutor executor, DeferredDispatch item) + { + if (!Volatile.Read(ref item.Cancelled)) + { + Resolve(executor, item); + } + + // A full fence: a failed TryEnter below takes no lock, and the holder's last look at the head must see this + // store. + Interlocked.Exchange(ref item.Resolved, 1); + // A worker that finds the finalizer busy goes on resolving; the holder looks at the head once more after it + // leaves, so it finalizes this member too. + while (Monitor.TryEnter(_finalize)) + { + try + { + AdvanceLocked(); + } + finally + { + Monitor.Exit(_finalize); + } + + Interlocked.MemoryBarrier(); + if (!HeadReady()) + { + return; + } + } + } + + // A member at the cursor the finalizer can take now. + private bool HeadReady() + { + var cursor = Volatile.Read(ref _cursor); + if (cursor >= Volatile.Read(ref _issued)) + { + return false; + } + + return cursor >= Volatile.Read(ref _poison) || (_items[cursor] is { } head && Volatile.Read(ref head.Resolved) != 0); + } + + private void Resolve(RenderExecutor executor, DeferredDispatch item) + { + var host = _owner._host; + var pipelines = _owner._pipelines!; + item.FrontendImageVersion = pipelines.FrontendImageVersion; + host.BeginStrictWorkerResolve(item.Sequence, item.Reads); + ShaderProgramCache.SpeculativeResolve = true; + try + { + var inputs = item.Inputs; + if (!pipelines.RunDeferredRebind(inputs, out var program) || + executor.ResolveDeferredDispatch(item.SubmitId, inputs.Compute, inputs.GroupsX, inputs.GroupsY, inputs.GroupsZ, inputs.Initiator, + program, serialOnly: false) is not { } record) + { + item.Refused = true; + return; + } + + record.Sequence = item.Sequence; + executor.CollectDispatchWrites(record, item.Marks); + item.Record = record; + } + catch (Exception) + { + // SerialResolveRequiredException where the command thread would compile, raise a fatal or read what the + // worker cannot log: the command thread runs the member again and reports any real failure itself. + item.Refused = true; + } + finally + { + ShaderProgramCache.SpeculativeResolve = false; + host.EndWorkerResolve(); + } + } + + // Under _finalize: finalizes the members that are ready, in stream order. + private void AdvanceLocked() + { + var issued = Volatile.Read(ref _issued); + var pending = _owner._executor!.PendingWrites; + while (_cursor < issued) + { + var item = _items[_cursor]!; + if (_cursor >= _poison) + { + Cancel(item); + Volatile.Write(ref _cursor, _cursor + 1); + continue; + } + + if (Volatile.Read(ref item.Resolved) == 0) + { + break; + } + + if (item.Refused || !ReadsHold(item, pending)) + { + PoisonAt(_cursor, table: false); + Cancel(item); + Volatile.Write(ref _cursor, _cursor + 1); + continue; + } + + foreach (var mark in item.Marks) + { + pending.Mark(mark.Address, mark.Size, item.Sequence, mark.Kind); + } + + Interlocked.MemoryBarrier(); + var tables = Volatile.Read(ref _tableCount); + for (var index = item.TableMark; index < tables; index++) + { + var (address, size, member) = _tables[index]; + if (member > item.Index && Overlaps(item.Marks, address, size)) + { + PoisonAt(member, table: true); + break; + } + } + + item.Done.Set(); + Volatile.Write(ref _cursor, _cursor + 1); + } + + if (_cursor == issued) + { + _drained.Set(); + } + } + + // The member's reads against the marks before it: the marks of the run's earlier members stay pending until the + // run closes, so every write they make before this member is seen here. + private static bool ReadsHold(DeferredDispatch item, PendingGpuWrites pending) + { + var released = pending.Released; + var reads = item.Reads; + for (var index = 0; index < reads.Count; index++) + { + var bytes = reads.Bytes(index, out var address); + var size = (ulong)bytes.Length; + if (pending.MayHavePending(address, size) && pending.HasPendingBetween(address, size, released, item.Sequence)) + { + return false; + } + } + + return true; + } + + private static bool Overlaps(List marks, ulong address, ulong size) + { + foreach (var mark in marks) + { + if (mark.Address < address + size && address < mark.Address + mark.Size) + { + return true; + } + } + + return false; + } + + // Members from member on are cancelled. A table a member writes rolls back to the state at the issue of the member + // before it, and the packets run again from just after that member's dispatch; a member a worker could not resolve + // rolls back to its own issue, and the packets run again from its dispatch. + private void PoisonAt(int member, bool table) + { + if (member >= _poison) + { + return; + } + + var source = table ? _items[member - 1]! : _items[member]!; + _rewind = new DeferredRewind + { + Depth = source.Depth, + CursorAddress = source.CursorAddress, + Offset = table ? source.PacketOffset + DispatchPacketDwords : source.PacketOffset, + Compute = source.Inputs.Compute.Copy(), + RawUndoMark = source.RawUndoMark, + UserDataMarker = source.UserDataMarker, + }; + Volatile.Write(ref _poison, member); + } + + private static void Cancel(DeferredDispatch item) + { + item.Cancelled = true; + item.Done.Set(); + } + + public void Dispose() + { + _stopping = true; + _wake.Release(_threads.Length); + foreach (var thread in _threads) + { + thread.Join(); + } + } + } + } +} diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs index 83f34a456..c7264c54d 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs @@ -249,11 +249,8 @@ public static int DcbDrawIndexIndirect(CpuContext ctx) var drawInitiator = (modifier & (1UL << 32)) != 0 ? 2u : ((modifierBits >> 3) & 0x20u) | 2u; if (commandBufferAddress == 0 || - !TryAllocateCommandDwords(ctx, commandBufferAddress, 5, out var commandAddress) || - !TryWriteUInt32(ctx, commandAddress, Pm4(5, ItDrawIndexIndirect, 0)) || - !TryWriteUInt32(ctx, commandAddress + 4, dataOffset) || - !ctx.TryWriteUInt64(commandAddress + 8, registerLocations) || - !TryWriteUInt32(ctx, commandAddress + 16, drawInitiator)) + !TryEmitCommandDwords(ctx, commandBufferAddress, out var commandAddress, Pm4(5, ItDrawIndexIndirect, 0), dataOffset, + (uint)registerLocations, (uint)(registerLocations >> 32), drawInitiator)) { return ReturnPointer(ctx, 0); } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs index 1d1e7262b..9cd6ae3ae 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Buffers.Binary; using SharpEmu.HLE; using SharpEmu.Libs.Diagnostics; using SharpEmu.Libs.Kernel; @@ -33,20 +34,24 @@ public static int CbSetShRegistersDirect(CpuContext ctx) return ReturnPointer(ctx, 0); } - var registers = new RegisterDefaultValue[registerCount]; - for (uint index = 0; index < registerCount; index++) + // The (offset, value) entries come in one read, and each run of consecutive registers is built in full and + // written with one allocation and one write. + var entries = new byte[registerCount * 8]; + if (!ctx.Memory.TryRead(registersAddress, entries)) { - var entryAddress = registersAddress + ((ulong)index * 8); - if (!TryReadUInt32(ctx, entryAddress, out var offset) || - !TryReadUInt32(ctx, entryAddress + sizeof(uint), out var value)) - { - return ReturnPointer(ctx, 0); - } + return ReturnPointer(ctx, 0); + } - registers[index] = new RegisterDefaultValue(offset, value); + var registers = new RegisterDefaultValue[registerCount]; + for (var index = 0; index < registers.Length; index++) + { + registers[index] = new RegisterDefaultValue( + BinaryPrimitives.ReadUInt32LittleEndian(entries.AsSpan(index * 8)), + BinaryPrimitives.ReadUInt32LittleEndian(entries.AsSpan((index * 8) + sizeof(uint)))); } Array.Sort(registers, static (left, right) => left.Offset.CompareTo(right.Offset)); + var packet = new uint[registers.Length + 2]; ulong firstCommandAddress = 0; var startIndex = 0; while (startIndex < registers.Length) @@ -60,25 +65,19 @@ public static int CbSetShRegistersDirect(CpuContext ctx) var valueCount = (uint)(endIndex - startIndex); var packetDwords = valueCount + 2; - if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress) || - !TryWriteUInt32(ctx, commandAddress, Pm4(packetDwords, ItSetShReg, 0)) || - !TryWriteUInt32(ctx, commandAddress + 4, registers[startIndex].Offset & 0xFFFFu)) + packet[0] = Pm4(packetDwords, ItSetShReg, 0); + packet[1] = registers[startIndex].Offset & 0xFFFFu; + for (var index = startIndex; index < endIndex; index++) { - return ReturnPointer(ctx, 0); + packet[2 + index - startIndex] = registers[index].Value; } - firstCommandAddress = firstCommandAddress == 0 ? commandAddress : firstCommandAddress; - for (var index = startIndex; index < endIndex; index++) + if (!TryEmitCommandDwords(ctx, commandBufferAddress, out var commandAddress, packet.AsSpan(0, (int)packetDwords))) { - if (!TryWriteUInt32( - ctx, - commandAddress + 8 + ((ulong)(index - startIndex) * sizeof(uint)), - registers[index].Value)) - { - return ReturnPointer(ctx, 0); - } + return ReturnPointer(ctx, 0); } + firstCommandAddress = firstCommandAddress == 0 ? commandAddress : firstCommandAddress; startIndex = endIndex; } @@ -109,7 +108,21 @@ public static int CbSetShRegisterRangeDirect(CpuContext ctx) ulong commandAddress; using (AgcRegisterPacketProfile.Measure(AgcRegisterPacketProfile.Phase.PacketSetup)) { - if (!TryEmitCommandDwords(ctx, commandBufferAddress, out _, Pm4(2, ItNop, RZero), CbSetShRegisterRangeMarker) || + // The marker and the SET_SH_REG packet take one allocation, and the marker and header one write, when both + // packets fit without the buffer-full callback. Otherwise they are allocated apart, so a callback runs + // between them as it would for two separate packets. + if (TryAllocateFittingCommandDwords(ctx, commandBufferAddress, 2 + packetDwords, out var markerAddress)) + { + if (!TryWriteCommandDwords(ctx, markerAddress, Pm4(2, ItNop, RZero), CbSetShRegisterRangeMarker, + Pm4(packetDwords, ItSetShReg, 0), offset)) + { + AgcRegisterPacketProfile.RecordResult(false); + return ReturnPointer(ctx, 0); + } + + commandAddress = markerAddress + 8; + } + else if (!TryEmitCommandDwords(ctx, commandBufferAddress, out _, Pm4(2, ItNop, RZero), CbSetShRegisterRangeMarker) || !TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out commandAddress) || !TryWriteCommandDwords(ctx, commandAddress, Pm4(packetDwords, ItSetShReg, 0), offset)) { diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs b/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs index b08416eff..b4afdd50a 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs @@ -146,6 +146,11 @@ private static void WaitResolved(DeferredDraw deferred) // render thread takes the draw in order through JoinDeferredDraw. internal bool CanRecordDeferred(DeferredWork work) { + if (work is DeferredDispatch dispatch) + { + return CanRecordDeferredDispatch(dispatch); + } + if (work is not DeferredDraw deferred) { return true; @@ -167,8 +172,13 @@ internal bool CanRecordDeferred(DeferredWork work) return deferred.SerialReason is null && deferred.Record is not null && ValidateDeferredReads(deferred); } - // At the stream position of a slice segment: whether a worker-resolved draw it recorded still holds. - internal bool ValidateDeferred(DeferredWork work) => work is not DeferredDraw deferred || ValidateDeferredReads(deferred); + // At the stream position of a slice segment: whether a worker-resolved draw or dispatch it recorded still holds. + internal bool ValidateDeferred(DeferredWork work) => work switch + { + DeferredDraw deferred => ValidateDeferredReads(deferred), + DeferredDispatch dispatch => dispatch.Cancelled || ValidateDispatchReads(dispatch), + _ => true, + }; private bool ValidateDeferredReads(DeferredDraw deferred) => deferred.FrontendImageVersion == _pipelines!.FrontendImageVersion && _host.ValidateWorkerReads(deferred.Reads); diff --git a/src/SharpEmu.Libs/Agc/AgcExports.cs b/src/SharpEmu.Libs/Agc/AgcExports.cs index 49e2e9b69..50fd37fbc 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.cs @@ -496,6 +496,11 @@ private static bool TryAllocateCommandDwords(CpuContext ctx, ulong commandBuffer bool isMarker = false) => TryPrepareCommandDwords(ctx, commandBufferAddress, sizeDwords, true, out commandAddress, isMarker); + // Allocates only when the buffer has room without the guest's buffer-full callback. Otherwise the cursor stays where it + // was, and a caller that splits the same packets over several allocations runs the callback where those would. + private static bool TryAllocateFittingCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, out ulong commandAddress) + => TryPrepareCommandDwords(ctx, commandBufferAddress, sizeDwords, true, out commandAddress, callBufferFull: false); + // Guest threads run HLE exports concurrently. Two exports appending to one command buffer both read its cursor before // either stores it back, and the second packet overwrites the first: a game's DCB lost the header of a // SET_SH_REG to a concurrent PopMarker (seen as "The packet opcode is unknown" right after a PopMarker). @@ -522,7 +527,7 @@ private static int CommandBufferStripe(ulong commandBufferAddress) => (int)((commandBufferAddress * 0x9E3779B97F4A7C15UL) >> 58); private static bool TryPrepareCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, bool advanceCursor, - out ulong commandAddress, bool isMarker = false) + out ulong commandAddress, bool isMarker = false, bool callBufferFull = true) { var gate = _commandBufferLocks[CommandBufferStripe(commandBufferAddress)]; lock (gate) @@ -542,7 +547,7 @@ private static bool TryPrepareCommandDwords(CpuContext ctx, ulong commandBufferA } return TryPrepareCommandDwordsLocked(ctx, commandBufferAddress, sizeDwords, advanceCursor, gate, writers, isMarker, - out commandAddress); + callBufferFull, out commandAddress); } } @@ -576,7 +581,7 @@ private static bool TryReadCommandBufferState(CpuContext ctx, ulong commandBuffe } private static bool TryPrepareCommandDwordsLocked(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, bool advanceCursor, - object gate, ConcurrentDictionary writers, bool isMarker, out ulong commandAddress) + object gate, ConcurrentDictionary writers, bool isMarker, bool callBufferFull, out ulong commandAddress) { commandAddress = 0; if (sizeDwords == 0 || @@ -588,6 +593,11 @@ private static bool TryPrepareCommandDwordsLocked(CpuContext ctx, ulong commandB var remainingDwords = GetRemainingCommandDwords(cursorUp, cursorDown, reservedDwords); if (sizeDwords > remainingDwords) { + if (!callBufferFull) + { + return false; + } + TraceAgc($"agc.cmd_alloc_full buf=0x{commandBufferAddress:X16} need={sizeDwords} remaining={remainingDwords} callback=0x{callback:X16}"); var scheduler = GuestThreadExecution.Scheduler; ulong callbackResult = 0; diff --git a/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs b/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs index 6752cc98b..1b60d51c2 100644 --- a/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs +++ b/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs @@ -7,9 +7,10 @@ namespace SharpEmu.Libs.Agc; // - Marker names are read in chunks within a page. // - A release reads its six stack words in one read. // - The submitted command scan uses a copy loaded a page at a time. -// Register ranges always use the ordinary marker allocation/write, packet allocation/header and payload-copy sequence. -// Push markers retain ordinary allocation/header/name-word writes after name resolution. There is no combined packet -// write, cursor rollback or speculative write followed by replay in either emitter. +// The switch leaves packet emission alone. A register range allocates its marker and packet together, with one write +// for the marker and header, only when both fit without the buffer-full callback, and otherwise apart; the payload +// copy follows either way. Push markers retain ordinary allocation/header/name-word writes after name resolution. +// Neither emitter rolls the cursor back or writes speculatively and replays. // The retained read optimizations have separate input-stability and read-effect contracts. internal static class AgcPacketWrites { diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index 533caf4b2..66f0d64b8 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -441,7 +441,7 @@ public void PrepareBufferAllocations(ReadOnlySpan ranges) BumpGpuModifiedVersion(); } - NoteHotWindowWrite(guestAddress, size); + NoteHotWindowWrite(buffer, guestAddress, size); } else OverlayGuestPublications?.Invoke(buffer, buffer.Offset(guestAddress), guestAddress, size); @@ -1033,8 +1033,67 @@ internal GuestSpan DeviceAddressFaultRange(ulong pageAddress, ulong pageSize) // runs once per tick (and when the mapping changes; new buffers register with the current // tick), and uploads only visit buffers in blocks the tracker does not know to be clean. // Hot pages stay dirty and writable, so every preparation still re-uploads them. - private ulong _bdaTouchTick = ulong.MaxValue; - private ulong _bdaTouchMapping; + // A program whose device-address reads reach only its handles' windows prepares just the mapped spans inside them. Each + // set of prepared spans keeps its own state: the mapped spans one, reset when their key changes, and the windowed spans + // one each in a small table, tied to the key of the mapped spans they were cut from. + private sealed class BdaSweepState + { + public bool InUse; + public ulong Mapping; + public ulong FullMapping; + public ulong TouchTick = ulong.MaxValue; + public bool Swept; + public long Epoch = -1; + public long Registrations = -1; + public long Observation = -1; + public GuestPageTracker.SweepPlan? Plan; + public bool PlanBuilt; + + public void Reset(ulong mapping, ulong fullMapping) + { + InUse = true; + Mapping = mapping; + FullMapping = fullMapping; + TouchTick = ulong.MaxValue; + Swept = false; + Epoch = -1; + Registrations = -1; + Observation = -1; + Plan = null; + PlanBuilt = false; + } + } + + private const int BdaWindowStateCount = 8; + private readonly BdaSweepState _bdaFull = new(); + private readonly BdaSweepState[] _bdaWindowStates = Enumerable.Range(0, BdaWindowStateCount).Select(_ => new BdaSweepState()).ToArray(); + private int _bdaWindowNext; + + private BdaSweepState FullBdaState(ulong mapping) + { + if (!_bdaFull.InUse || _bdaFull.Mapping != mapping) + { + _bdaFull.Reset(mapping, mapping); + } + + return _bdaFull; + } + + private BdaSweepState WindowBdaState(ulong mapping, ulong fullMapping) + { + foreach (var state in _bdaWindowStates) + { + if (state.InUse && state.Mapping == mapping && state.FullMapping == fullMapping) + { + return state; + } + } + + var fresh = _bdaWindowStates[_bdaWindowNext]; + _bdaWindowNext = (_bdaWindowNext + 1) % BdaWindowStateCount; + fresh.Reset(mapping, fullMapping); + return fresh; + } public static ulong MappingKey(IReadOnlyCollection spans) { @@ -1044,13 +1103,65 @@ public static ulong MappingKey(IReadOnlyCollection spans) return mapping; } + // The mapped spans (sorted and disjoint) cut to the union of the windows, which are sorted and merged in place. + public static void ClipSpansToWindows(IReadOnlyList spans, List<(ulong Start, ulong End)> windows, List into) + { + into.Clear(); + if (windows.Count == 0) + { + return; + } + + windows.Sort(static (left, right) => left.Start.CompareTo(right.Start)); + var merged = 0; + for (var index = 1; index < windows.Count; index++) + { + if (windows[index].Start <= windows[merged].End) + { + windows[merged] = (windows[merged].Start, Math.Max(windows[merged].End, windows[index].End)); + } + else + { + windows[++merged] = windows[index]; + } + } + + windows.RemoveRange(merged + 1, windows.Count - merged - 1); + var window = 0; + for (var index = 0; index < spans.Count && window < windows.Count; index++) + { + var spanStart = spans[index].Address; + var spanEnd = spanStart + spans[index].Size; + while (window < windows.Count && windows[window].End <= spanStart) + { + window++; + } + + for (var current = window; current < windows.Count && windows[current].Start < spanEnd; current++) + { + var start = Math.Max(spanStart, windows[current].Start); + var end = Math.Min(spanEnd, windows[current].End); + if (start < end) + { + into.Add(new GuestSpan(start, end - start)); + } + } + } + } + public void PrepareBda(IEnumerable mapped) { var spans = mapped as IReadOnlyList ?? mapped.ToList(); PrepareBda(spans, MappingKey(spans)); } - public void PrepareBda(IReadOnlyList spans, ulong mapping) + public void PrepareBda(IReadOnlyList spans, ulong mapping) => PrepareBda(spans, FullBdaState(mapping)); + + // The windows are the mapped spans cut to a windowed program's handle windows (ClipSpansToWindows). + public void PrepareWindowedBda(IReadOnlyList windows, ulong windowMapping, ulong fullMapping) => + PrepareBda(windows, WindowBdaState(windowMapping, fullMapping)); + + private void PrepareBda(IReadOnlyList spans, BdaSweepState state) { if (SubmissionScheduler.ReadOnlyThread) { @@ -1071,24 +1182,22 @@ public void PrepareBda(IReadOnlyList spans, ulong mapping) } else { - if (_retirementPolicy.CurrentTick != _bdaTouchTick || mapping != _bdaTouchMapping) + if (_retirementPolicy.CurrentTick != state.TouchTick) { for (var index = 0; index < spans.Count; index++) TouchBuffersInRange(spans[index].Address, spans[index].Size); - _bdaTouchTick = _retirementPolicy.CurrentTick; - _bdaTouchMapping = mapping; + state.TouchTick = _retirementPolicy.CurrentTick; } var epoch = _tracker.CpuDirtyEpoch; var registrations = _registrationGeneration; - if (mapping != _bdaSweepMapping || registrations != _bdaSweepRegistrations || - (epoch != _bdaSweepEpoch && (!ObservationGated || _observation != _bdaSweepObservation))) + if (!state.Swept || registrations != state.Registrations || + (epoch != state.Epoch && (!ObservationGated || _observation != state.Observation))) { - if (!_bdaSweepPlanBuilt || mapping != _bdaSweepPlanMapping) + if (!state.PlanBuilt) { - _bdaSweepPlan = GuestPageTracker.PlanSweep(spans); - _bdaSweepPlanMapping = mapping; - _bdaSweepPlanBuilt = true; + state.Plan = GuestPageTracker.PlanSweep(spans); + state.PlanBuilt = true; } // The buffers' copies are collected as the sweep visits them and staged when it ends. @@ -1096,7 +1205,7 @@ public void PrepareBda(IReadOnlyList spans, ulong mapping) _inDeviceAddressSweep = true; try { - if (_bdaSweepPlan is { } plan && _bufferPages.Complete) + if (state.Plan is { } plan && _bufferPages.Complete) { _handleWindows.Sort(); // Only a registered buffer has anything to upload, so only the pages buffers cover are looked at. @@ -1128,13 +1237,13 @@ public void PrepareBda(IReadOnlyList spans, ulong mapping) } } - _bdaSweepEpoch = epoch; - _bdaSweepMapping = mapping; - _bdaSweepRegistrations = registrations; - _bdaSweepObservation = _observation; + state.Swept = true; + state.Epoch = epoch; + state.Registrations = registrations; + state.Observation = _observation; Interlocked.Increment(ref BdaSweeps); } - else if (epoch != _bdaSweepEpoch) + else if (epoch != state.Epoch) { Interlocked.Increment(ref BdaSweepsSkipped); } @@ -1154,12 +1263,12 @@ public void PrepareBoundedBda(IReadOnlyList spans, ulong mapping) throw SubmissionScheduler.ReadOnlyViolation("bda"); } - if (_retirementPolicy.CurrentTick != _bdaTouchTick || mapping != _bdaTouchMapping) + var state = FullBdaState(mapping); + if (_retirementPolicy.CurrentTick != state.TouchTick) { for (var index = 0; index < spans.Count; index++) TouchBuffersInRange(spans[index].Address, spans[index].Size); - _bdaTouchTick = _retirementPolicy.CurrentTick; - _bdaTouchMapping = mapping; + state.TouchTick = _retirementPolicy.CurrentTick; } _faultProcessPending = true; @@ -1296,12 +1405,8 @@ private void RecordSweepBarrier(CommandBuffer native, PipelineStageFlags sourceS VulkanSynchronization.PipelineBarrier(_device.Vk, native, sourceStages, destinationStages, 0, 1, &barrier, 0, null, 0, null, BarrierSource.Sweep); } - private long _bdaSweepEpoch = -1; - // Every registration advances it: a new owner needs its first upload even when no CPU write moved the epoch. private long _registrationGeneration; - private long _bdaSweepRegistrations = -1; - private long _bdaSweepObservation = -1; private long _observation; public static long BdaSweeps; public static long BdaSweepsSkipped; @@ -1313,11 +1418,7 @@ private void RecordSweepBarrier(CommandBuffer native, PipelineStageFlags sourceS public bool ObservationGated { get; set; } public void NoteObservation() => _observation++; - private ulong _bdaSweepMapping; - private GuestPageTracker.SweepPlan? _bdaSweepPlan; private readonly PageCoverage _bufferPages = new(); - private ulong _bdaSweepPlanMapping; - private bool _bdaSweepPlanBuilt; // The uploads of the running sweep: each one's copies are a run of _sweepCopies, with source // offsets inside its own bytes until they are staged. @@ -1795,38 +1896,65 @@ private bool ReadMemoryOrAwaitShutdown(ulong guestAddress, ulong size, bool isWr } private const ulong ReadbackWindowBytes = 512 * 1024; - private const long HotWindowLifetime = 512; - private const int MaxEagerReadbacks = 4; + private const long HotWindowLifetime = 4096; + private const int MaxEagerReadbacks = 16; private const int MaxAsyncReadbackAttempts = 4; private const int MaxReadbackSlotWaits = 64; private const int EagerStrikeLimit = 3; private const long EagerMuteBatches = 4096; + private static readonly long EagerLandCheckTicks = System.Diagnostics.Stopwatch.Frequency / 20_000; private readonly Dictionary _hotWindows = new(); private readonly HashSet _eagerCandidates = new(); + // The tick of each candidate's newest write; the candidate is not looked at again before the GPU completes it. + private readonly Dictionary _eagerWaitTicks = new(); private readonly List _eagerDownloads = new(); + // The completed tick at which the pump next looks at the candidates: the earliest one a candidate waits for, or 0 once a + // landing freed a download. + private ulong _nextEagerTick = ulong.MaxValue; + private long _lastEagerPump; private long _batchSerial; private static long _reportedEagerStarted; private static long _reportedEagerUsed; private static long _reportedEagerStale; private static long _reportedEagerMuted; - private readonly record struct HotWindow(ulong Address, ulong Size, long LastHit, int Strikes = 0, long MutedUntil = 0); + private readonly record struct HotWindow(ulong Key, ulong Address, ulong Size, long LastHit, int Strikes = 0, long MutedUntil = 0); - // Eager readbacks are off unless SHARPEMU_EAGER_READBACKS=1: the CPU consumes few of them, while each still ends - // rendering early to flush its batch and downloads its whole window. - internal bool EagerReadbacksEnabled { get; set; } = - string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_EAGER_READBACKS"), "1", StringComparison.Ordinal); + // A window the guest read back is read ahead after its next GPU write, once that write's tick has completed: the copy + // waits on nothing, and it usually lands before the guest reads the window again. + internal bool EagerReadbacksEnabled { get; set; } = true; internal long EagerReadbacksStarted { get; private set; } internal long EagerReadbacksUsed { get; private set; } + // A buffer of up to one window has a hot entry of its own, so a GPU write anywhere in it starts its readback. Its key is the + // buffer address with bit 0 set: buffers are page aligned and window keys window aligned. A larger buffer keeps one entry + // per aligned window. + private ulong HotKeyFor(ulong guestAddress, ulong size) => + FindOwner(guestAddress, Math.Max(size, 1)) is { Size: <= ReadbackWindowBytes } buffer + ? buffer.CpuAddress | 1 + : guestAddress & ~(ReadbackWindowBytes - 1); + + // The write that makes a candidate is in the tick being recorded. + private void AddEagerCandidate(ulong key) + { + _eagerCandidates.Add(key); + var tick = _scheduler.CurrentTick; + if (!_eagerWaitTicks.TryGetValue(key, out var waiting) || waiting < tick) + { + _eagerWaitTicks[key] = tick; + } + + _nextEagerTick = Math.Min(_nextEagerTick, tick); + } + private void NoteHotReadback(ulong guestAddress, ulong size) { - var key = guestAddress & ~(ReadbackWindowBytes - 1); + var key = HotKeyFor(guestAddress, size); _hotWindows[key] = _hotWindows.TryGetValue(key, out var hot) ? hot with { Address = guestAddress, Size = size, LastHit = _batchSerial } - : new HotWindow(guestAddress, size, _batchSerial); + : new HotWindow(key, guestAddress, size, _batchSerial); } internal long EagerReadbacksWasted { get; private set; } @@ -1863,46 +1991,44 @@ private void NoteEagerOutcome(ulong key, bool wasted) } } - private void NoteHotWindowWrite(ulong guestAddress, ulong size) + private void NoteHotWindowWrite(GpuBuffer buffer, ulong guestAddress, ulong size) { if (!EagerReadbacksEnabled || _hotWindows.Count == 0 || size == 0) { return; } + if (buffer.Size <= ReadbackWindowBytes) + { + NoteHotWrite(buffer.CpuAddress | 1); + return; + } + var last = (guestAddress + size - 1) & ~(ReadbackWindowBytes - 1); for (var key = guestAddress & ~(ReadbackWindowBytes - 1); key <= last; key += ReadbackWindowBytes) { - if (_hotWindows.TryGetValue(key, out var hot) && _batchSerial - hot.LastHit <= HotWindowLifetime && - _batchSerial >= hot.MutedUntil) - { - _eagerCandidates.Add(key); - HotWritePending |= hot.Strikes == 0; - } + NoteHotWrite(key); } } - public bool HotWritePending { get; private set; } + private void NoteHotWrite(ulong key) + { + if (_hotWindows.TryGetValue(key, out var hot) && _batchSerial - hot.LastHit <= HotWindowLifetime && + _batchSerial >= hot.MutedUntil) + { + AddEagerCandidate(key); + } + } public void OnBatchSubmitted() { _batchSerial++; - HotWritePending = false; if (AsyncReadback is not { } readback) { return; } - for (var index = _eagerDownloads.Count - 1; index >= 0; index--) - { - var pending = _eagerDownloads[index]; - if (readback.IsComplete(pending.Ticket)) - { - _eagerDownloads.RemoveAt(index); - _ = CompleteReadMemoryOnGpu(pending, consumed: false); - } - } - + LandEagerReadbacks(readback); if ((_batchSerial & 1023) == 0) { foreach (var key in _hotWindows.Where(pair => _batchSerial - pair.Value.LastHit > HotWindowLifetime && _batchSerial >= pair.Value.MutedUntil) @@ -1912,35 +2038,114 @@ public void OnBatchSubmitted() } } + if (_eagerCandidates.Count != 0) + { + StartEagerCandidates(_scheduler.Timeline.CompletedTick); + } + } + + // On the GPU queue thread between command items: lands the finished eager readbacks and starts the candidates whose + // writer has completed. While every candidate still waits for its writer and no readback is in flight it is one compare; + // readbacks in flight are checked at most every EagerLandCheckTicks. + internal void PumpEagerReadbacks() + { + if ((_eagerCandidates.Count == 0 && _eagerDownloads.Count == 0) || AsyncReadback is not { } readback) + { + return; + } + + var now = System.Diagnostics.Stopwatch.GetTimestamp(); + var due = _eagerCandidates.Count != 0 && _scheduler.Timeline.CompletedTick >= _nextEagerTick; + if (!due && (_eagerDownloads.Count == 0 || now - _lastEagerPump < EagerLandCheckTicks)) + { + return; + } + + _lastEagerPump = now; + if (LandEagerReadbacks(readback)) + { + _nextEagerTick = 0; + } + if (_eagerCandidates.Count == 0) { return; } + _scheduler.Timeline.RefreshCompletedTick(); + var capped = StartEagerCandidates(_scheduler.Timeline.CompletedTick); + // Capped, the next landing frees a download; otherwise the pump waits for the earliest writer a candidate waits for. + var next = ulong.MaxValue; + if (!capped) + { + foreach (var key in _eagerCandidates) + { + next = Math.Min(next, _eagerWaitTicks.TryGetValue(key, out var waiting) ? waiting : 0); + } + } + + _nextEagerTick = next; + } + + // True when a readback landed. + private bool LandEagerReadbacks(VulkanAsyncReadback readback) + { + var landed = false; + for (var index = _eagerDownloads.Count - 1; index >= 0; index--) + { + var pending = _eagerDownloads[index]; + if (readback.IsComplete(pending.Ticket)) + { + _eagerDownloads.RemoveAt(index); + _ = CompleteReadMemoryOnGpu(pending, consumed: false); + landed = true; + } + } + + return landed; + } + + // Starts the candidates whose newest write completed by the given tick; true when the readbacks in flight reached the cap + // before every candidate was looked at. + private bool StartEagerCandidates(ulong completed) + { List? settled = null; + var capped = false; foreach (var key in _eagerCandidates) { if (_eagerDownloads.Count >= MaxEagerReadbacks) { + capped = true; break; } - if (!_hotWindows.TryGetValue(key, out var hot) || _batchSerial - hot.LastHit > HotWindowLifetime || - _batchSerial < hot.MutedUntil || StartEagerReadback(hot) != EagerStart.Deferred) + if (!_hotWindows.TryGetValue(key, out var hot) || _batchSerial - hot.LastHit > HotWindowLifetime) { (settled ??= []).Add(key); + continue; } - } - if (settled is null) - { - return; + if (_eagerWaitTicks.TryGetValue(key, out var waitTick) && waitTick > completed) + { + continue; + } + + if (_batchSerial < hot.MutedUntil || StartEagerReadback(hot) != EagerStart.Deferred) + { + (settled ??= []).Add(key); + } } - foreach (var key in settled) + if (settled is not null) { - _eagerCandidates.Remove(key); + foreach (var key in settled) + { + _eagerCandidates.Remove(key); + _eagerWaitTicks.Remove(key); + } } + + return capped; } private enum EagerStart @@ -1952,7 +2157,7 @@ private enum EagerStart private EagerStart StartEagerReadback(HotWindow hot) { - if (FindOwner(hot.Address, hot.Size) is not { IsMapped: false } buffer) + if (FindOwner(hot.Address, hot.Size) is not { } buffer) { return EagerStart.Nothing; } @@ -1968,6 +2173,20 @@ private EagerStart StartEagerReadback(HotWindow hot) return EagerStart.Nothing; } + // The copy starts only once the window's newest writer has finished, so it never waits on the readback queue. + var waitTick = 0UL; + foreach (var copy in copies) + { + waitTick = Math.Max(waitTick, copy.Buffer.LastGpuWriteTickIn(copy.SourceOffset, copy.Size)); + } + + if (waitTick > _scheduler.Timeline.CompletedTick) + { + _eagerWaitTicks[hot.Key] = waitTick; + _nextEagerTick = Math.Min(_nextEagerTick, waitTick); + return EagerStart.Deferred; + } + if (!TryBeginDownloadAsync(copies, out var ticket, out var writeTicks, out _)) { return EagerStart.Deferred; @@ -1980,7 +2199,7 @@ private EagerStart StartEagerReadback(HotWindow hot) _eagerDownloads.Add(new PendingDownload { - HotKey = hot.Address & ~(ReadbackWindowBytes - 1), + HotKey = hot.Key, Ticket = ticket, Copies = copies, WriteTicks = writeTicks, @@ -2058,6 +2277,7 @@ private void AbandonEagerReadbacks() _eagerDownloads.Clear(); _eagerCandidates.Clear(); + _eagerWaitTicks.Clear(); } private static readonly bool GuestReadsAwaitOffQueue = diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredDispatchRuns.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredDispatchRuns.cs new file mode 100644 index 000000000..13e27dd1c --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredDispatchRuns.cs @@ -0,0 +1,62 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands.Registers; + +namespace SharpEmu.Libs.Gpu.GpuCommands; + +// The interpreter's side of deferred dispatch runs: a run of direct dispatches whose rebinds workers resolve while the +// command thread reads on. Inside a run the interpreter applies only compute-range shader register writes, shader register +// tables, cache and flush events, inert NOPs and markers, and direct dispatches; anything else first waits at the barrier, +// which gives every later consumer complete write marks. A rollback restores the compute registers and the raw register +// mirror as they stood at a member's issue and moves the packet cursor back to that member. +public interface IDeferredDispatchRuns +{ + // Members were issued since the last barrier. + bool IsOpen { get; } + + // A run is open, or deferral is held off after a rollback until the next barrier. + bool Active { get; } + + DeferredIssue TryIssue(in DeferredIssueSite site, uint groupsX, uint groupsY, uint groupsZ, uint initiator); + + // Waits until every member issued is finalized or cancelled, closes the run, and returns the rollback a poisoned member + // asks for, or null. Without an open run it only ends the hold-off of a rollback. + DeferredRewind? Barrier(); + + // A shader register table applied while a run is open, before its contents are checked; false when the log is full (the + // caller closes the run first). + bool NoteTable(ulong address, ulong size); + + // A packet other than a run packet ended the chain of same-program dispatches. + void BreakChain(); + + // The compute ticket scan stops at the dispatch that would start a run: its workers resolve that dispatch and the ones + // after it. + bool StopsTicketScan { get; } + + // Whether a dispatch with these registers could be issued to a run (the compute ticket scan's test). + bool WouldDefer(ComputeStageRegisters compute, uint initiator); +} + +public enum DeferredIssue +{ + NotEligible, + Issued, + // A member was poisoned: the caller waits at the barrier and rolls back. + Rewind, +} + +// Where a member was issued: the cursor (depth and buffer), the dispatch packet's offset, the raw-mirror undo log length and +// the user-data marker at issue. +public readonly record struct DeferredIssueSite(ulong SubmitId, int Depth, ulong CursorAddress, uint PacketOffset, int RawUndoMark, uint UserDataMarker); + +public sealed class DeferredRewind +{ + public int Depth; + public ulong CursorAddress; + public uint Offset; + public ComputeStageRegisters Compute = null!; + public int RawUndoMark; + public uint UserDataMarker; +} diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs new file mode 100644 index 000000000..a85bafbd3 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs @@ -0,0 +1,254 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; + +namespace SharpEmu.Libs.Gpu.GpuCommands; + +public sealed partial class GpuCommandInterpreter +{ + private const int TicketScanChunkDwords = 256; + private const uint TicketTableEntries = 512; + + private RegisterBanks? _ticketShadow; + private uint[]? _ticketWords; + private ulong[]? _ticketFound; + private byte[]? _ticketTable; + + // SHARPEMU_COMPUTE_TICKETS: requests a ticket for each direct dispatch that follows this one in its buffer, with the + // compute registers predicted on a shadow copy. Shader register writes and tables, events, write-data packets and inert + // NOPs pass; any other packet ends the scan, so nothing between two scanned dispatches changes a register the prediction + // does not follow. A wrong prediction only costs the ticket: the dispatch compares the real registers before it takes + // one, and the bytes the ticket read before it uses one. + private void ScanComputeTickets(ComputeTickets tickets, in PacketContext packet, ulong requestedThrough) + { + var found = _ticketFound ??= new ulong[ComputeTickets.MaxLead]; + var count = 0; + var stopped = ScanComputeTicketsCore(tickets, in packet, requestedThrough, found, ref count); + tickets.EndScan(this, packet.PacketAddress, found.AsSpan(0, count), stopped); + } + + // True when the scan ended at a packet it cannot pass or at the end of the buffer; false when it stopped for its own + // limits. + private bool ScanComputeTicketsCore(ComputeTickets tickets, in PacketContext packet, ulong requestedThrough, ulong[] found, ref int count) + { + if (packet.Remaining <= packet.Length) + { + return true; + } + + var start = packet.PacketAddress + (ulong)packet.Length * sizeof(uint); + var remaining = packet.Remaining - packet.Length; + var available = (int)Math.Min(remaining, (uint)ComputeTickets.MaxScanDwords); + var words = _ticketWords ??= new uint[ComputeTickets.MaxScanDwords]; + var read = 0; + var shadow = _ticketShadow ??= new RegisterBanks(_host.Fatal); + shadow.Shader.Compute = TypedRegisters.Shader.Compute.Copy(); + var position = 0; + // The third dispatch of one shader in a row starts a deferred dispatch run, whose workers resolve it and the dispatches + // after it: tickets past it would go unused. + var runStops = _runs is { StopsTicketScan: true }; + var runAddress = TypedRegisters.Shader.Compute.Address; + var runLength = 1; + while (position < available) + { + if (!EnsureTicketWords(start, words, ref read, position + 1, available)) + { + return true; + } + + var header = words[position]; + if (header == PacketHeader.FillerHeader) + { + position++; + continue; + } + + var length = (int)PacketHeader.Length(header); + if (header == 0 || length < 2) + { + return true; + } + + if (length > available - position) + { + break; + } + + if (!EnsureTicketWords(start, words, ref read, position + length, available) || PacketHeader.IsPredicated(header)) + { + return true; + } + + var opcode = PacketHeader.Opcode(header); + var address = start + (ulong)position * sizeof(uint); + var payload = words.AsSpan(position + 1, length - 1); + if (opcode == PacketOpcode.SetShaderRegister) + { + var offset = payload[0]; + var values = (uint)length - 2; + if (offset != RegisterBankLayout.ShaderRegisterNop) + { + if (offset >= RegisterBankLayout.ShaderRegisterCount || values > RegisterBankLayout.ShaderRegisterCount - offset) + { + return true; + } + + var context = new PacketContext(header & ~1u, address, (uint)position, (uint)(available - position), (uint)available); + if (RegisterWriteTable.WriteShaderPacket(shadow, in context, offset, payload.Slice(1, (int)values)) != values) + { + return true; + } + } + } + else if (opcode == PacketOpcode.SetShaderRegisterIndirect) + { + if (length != 5 || !ScanShaderRegisterTable(shadow, address, (payload[0] & 0xFFFF_FFFCu) | ((ulong)payload[1] << 32), payload[3] & 0x3FFFu)) + { + return true; + } + } + else if (opcode == PacketOpcode.Nop) + { + var custom = PacketHeader.CustomCode(header); + if (custom == PacketCustomCode.ShaderRegisterTable) + { + if (length < 4 || !ScanShaderRegisterTable(shadow, address, Address(payload[1], payload[2]), payload[0])) + { + return true; + } + } + else if (custom == PacketCustomCode.Zero && !payload.IsEmpty && (payload[0] & 0xFFFF_0000u) == MarkerMagic) + { + // The marker ids with a side effect (MarkerPacket) are flips. The user-data markers only set an interpreter + // property no register write reads. + if ((payload[0] & 0xFFFu) is 0x777 or 0x778 or 0x781) + { + return true; + } + } + else if (!(custom is PacketCustomCode.Zero or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or PacketCustomCode.AcquireMemory or + PacketCustomCode.WriteData)) + { + // An acquire is a GPU ordering point and a write-data writes memory only: neither changes a register, and a + // ticket checks its reads when it is taken. + return true; + } + } + else if (opcode is PacketOpcode.EventWrite or PacketOpcode.WriteData) + { + // Events order GPU work and change no register; a dispatch's ticket checks its reads when it is taken. + } + else if (opcode == PacketOpcode.DispatchDirect && length == 5) + { + if (runStops) + { + var compute = shadow.Shader.Compute.Address; + runLength = compute == runAddress ? runLength + 1 : 1; + runAddress = compute; + if (runLength >= 3 && _runs!.WouldDefer(shadow.Shader.Compute, payload[3])) + { + return true; + } + } + + if (address > requestedThrough) + { + tickets.Request(this, address, shadow.Shader.Compute, payload[0], payload[1], payload[2], payload[3]); + found[count++] = address; + if (count == found.Length || tickets.LeadCount >= ComputeTickets.MaxLead) + { + return false; + } + } + } + else + { + return true; + } + + position += length; + } + + return (uint)position >= remaining; + } + + // Reads the command words up to needed, in chunks, so a scan that stops early reads little. + private bool EnsureTicketWords(ulong start, uint[] words, ref int read, int needed, int available) + { + if (needed <= read) + { + return true; + } + + var target = Math.Min(available, Math.Max(needed, read + TicketScanChunkDwords)); + if (!TryReadCommand(start + (ulong)read * sizeof(uint), MemoryMarshal.AsBytes(words.AsSpan(read, target - read)))) + { + return false; + } + + read = target; + return true; + } + + // A shader register table as the packet would apply it: the copy retained at submission when there is one, otherwise + // the guest bytes. False for a table the GPU wrote, one too large, or one the scan cannot read: the scan ends there. + private bool ScanShaderRegisterTable(RegisterBanks shadow, ulong packetAddress, ulong tableAddress, uint count) + { + if (count == 0) + { + return true; + } + + const int entryBytes = 2 * sizeof(uint); + if (tableAddress == 0 || count > TicketTableEntries || tableAddress > ulong.MaxValue - (ulong)count * entryBytes) + { + return false; + } + + var bytes = (int)count * entryBytes; + if (!_submittedCommands.IsEmpty && _host.HasGpuWrittenCommandData(tableAddress, (ulong)bytes)) + { + return false; + } + + ReadOnlySpan table; + if (_submittedRegisterTables is { } tables && tables.TryGetValue(packetAddress, out var submitted) && submitted.Length == bytes) + { + table = submitted; + } + else + { + var buffer = _ticketTable ??= new byte[(int)TicketTableEntries * entryBytes]; + if (!TryReadCommand(tableAddress, buffer.AsSpan(0, bytes))) + { + return false; + } + + table = buffer.AsSpan(0, bytes); + } + + for (var index = 0; index < bytes; index += entryBytes) + { + var rawOffset = BinaryPrimitives.ReadUInt32LittleEndian(table[index..]); + var value = BinaryPrimitives.ReadUInt32LittleEndian(table[(index + sizeof(uint))..]); + var offset = RegisterBankLayout.Normalize(rawOffset); + if (offset == RegisterBankLayout.ShaderRegisterNop || rawOffset == RegisterTableSentinel) + { + continue; + } + + if (offset >= RegisterBankLayout.ShaderRegisterCount) + { + return false; + } + + RegisterWriteTable.WriteShaderEntry(shadow, offset, value, tableAddress); + } + + return true; + } +} diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs index c23d10780..293d139de 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs @@ -475,6 +475,45 @@ internal uint DispatchDirectPacket(in PacketContext packet, ReadOnlySpan p throw _host.Fatal($"The dispatch header is not supported: header=0x{packet.Header:X8} address=0x{packet.PacketAddress:X16}."); } + // A member of a deferred dispatch run goes to the run's workers; any other dispatch closes an open run first (a + // poisoned member rolls the packets back instead). + if (_runs is { } runs) + { + var execution = RequireExecution(); + var depth = execution.Depth - 1; + var site = new DeferredIssueSite(SubmitId, depth, execution.At(depth).Address, packet.Offset, _runUndo.Count, UserDataMarker); + var issue = runs.TryIssue(in site, payload[0], payload[1], payload[2], payload[3]); + if (issue == DeferredIssue.Issued) + { + return 4; + } + + if ((issue == DeferredIssue.Rewind || runs.IsOpen) && CloseRunInHandler()) + { + return 4; + } + } + + if (_host.ComputeTickets is { } tickets) + { + if (tickets.NeedsScan(this, packet.PacketAddress, out var requestedThrough)) + { + ScanComputeTickets(tickets, in packet, requestedThrough); + } + + tickets.BeginDispatch(this, packet.PacketAddress); + try + { + DispatchDirect(payload[0], payload[1], payload[2], payload[3]); + } + finally + { + tickets.EndDispatch(); + } + + return 4; + } + DispatchDirect(payload[0], payload[1], payload[2], payload[3]); return 4; } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Registers.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Registers.cs index 01dca0a76..4c45433f8 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Registers.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Registers.cs @@ -147,6 +147,15 @@ internal uint SetShaderRegisterPacket(in PacketContext packet, ReadOnlySpan tableBlock = stackalloc byte[entriesPerBlock * entryBytes]; Span beforeSynchronization = stackalloc byte[entriesPerBlock * entryBytes]; + // A shader table inside an open run is logged before its check, so a member finalized after the check that writes it + // rolls the run back; a table the check finds GPU-written closes the run before the live read. + if (_runs is { IsOpen: true } runs) + { + if (bank != RegisterBank.Shader || !runs.NoteTable(tableAddress, (ulong)count * entryBytes)) + { + if (CloseRunInHandler()) + { + return; + } + } + } + var gpuWritten = !_submittedCommands.IsEmpty && _host.HasGpuWrittenCommandData(tableAddress, (ulong)count * entryBytes); + if (gpuWritten && _runs is { IsOpen: true } && CloseRunInHandler()) + { + return; + } + byte[]? retained = null; if (_submittedRegisterTables is { } tables && tables.TryGetValue(packet.PacketAddress, out var submitted) && (ulong)submitted.Length == (ulong)count * entryBytes && !gpuWritten) @@ -316,6 +343,20 @@ private void ApplyRegisterTable(RegisterBank bank, ulong tableAddress, uint coun throw _host.Fatal($"The shader table register is outside the bank: offset=0x{offset:X8} raw=0x{rawOffset:X8} value=0x{value:X8} table=0x{tableAddress:X16}."); } + // A rollback restores only the compute registers, so an entry outside them closes the run first. + if (_runs is { IsOpen: true }) + { + if (offset < RunComputeRangeStart && CloseRunInHandler()) + { + return; + } + + if (_runs.IsOpen) + { + NoteRunUndo(offset); + } + } + Registers.Shader[offset] = value; RegisterWriteTable.WriteShaderEntry(TypedRegisters, offset, value, tableAddress); break; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index b0259b07f..c2b658548 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -53,6 +53,11 @@ public sealed partial class GpuCommandInterpreter private SoftWait? _softWait; private bool _suspendedForLanding; private ulong _packetAddress; + // The deferred dispatch runs of the stream thread, the rollback a handler asked for, and the raw shader register + // mirror's undo log while a run is open. + private IDeferredDispatchRuns? _runs; + private DeferredRewind? _rewind; + private readonly List<(uint Offset, uint Value, bool Written)> _runUndo = new(); public GpuCommandInterpreter(ICommandStreamHost host, int queueId, int interruptEventId) { @@ -255,6 +260,7 @@ public SubmissionProgress Process(PacketCursorStack execution, ulong address, ui _submittedRegisterTables = registerTables; _submittedCommandAddress = address; _execution = execution; + _runs = _host.DispatchRuns; try { RunPackets(execution, 0); @@ -362,6 +368,12 @@ private void RunPackets(PacketCursorStack execution, int stopDepth) if (cursor.Offset == cursor.DwordCount) { + // A run belongs to its buffer; it closes before the buffer does. + if (_runs is { Active: true } && CloseRun(execution)) + { + continue; + } + execution.Pop(); continue; } @@ -392,6 +404,11 @@ private void RunPackets(PacketCursorStack execution, int stopDepth) // Ring memory the guest has not written yet; retry after it appends more. if (header == 0 && cursor.FollowedChunkAdvance) { + if (_runs is { Active: true } && CloseRun(execution)) + { + continue; + } + execution.Suspended = true; return; } @@ -450,6 +467,17 @@ 0 or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or _packetWindowGeneration++; } + // Any packet but a run packet closes an open run first, and breaks the chain of same-program dispatches that + // opens one. + if (_runs is { } runs && !IsRunPacket(header, payload)) + { + runs.BreakChain(); + if (runs.Active && CloseRun(execution)) + { + continue; + } + } + var packet = new PacketContext(header & ~1u, packetAddress, offset, remaining, total); _packetAddress = packetAddress; uint consumed; @@ -465,6 +493,15 @@ 0 or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or SharpEmu.Libs.Diagnostics.PacketHandlerTally.Note(opcode, header, Stopwatch.GetTimestamp() - handlerStarted - (SharpEmu.Libs.Diagnostics.PacketHandlerTally.WaitedTicks - waitedBefore)); } + + // The handler closed a run whose member was poisoned; the packets run again from the rollback point. + if (_rewind is { } rewind) + { + _rewind = null; + ApplyRewind(execution, rewind); + continue; + } + if (consumed > remaining) { throw _host.Fatal($"The handler consumed more than the buffer holds: consumed={consumed} remaining={remaining} header=0x{header:X8} address=0x{packetAddress:X16}."); @@ -498,6 +535,106 @@ 0 or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or } } + // The packets a deferred dispatch run may hold: shader register writes in the compute range only (a rollback restores + // the compute registers), shader register tables (an entry outside the compute range closes the run first), the events + // that only queue a GPU barrier in stream order or do nothing, inert NOPs and markers but flips, and direct dispatches. + private static bool IsRunPacket(uint header, ReadOnlySpan payload) + { + switch (PacketHeader.Opcode(header)) + { + case PacketOpcode.EventWrite: + return !payload.IsEmpty && IsRunEvent(payload[0]); + case PacketOpcode.SetShaderRegister: + return !payload.IsEmpty && (payload[0] == RegisterBankLayout.ShaderRegisterNop || payload[0] >= RunComputeRangeStart); + case PacketOpcode.SetShaderRegisterIndirect: + case PacketOpcode.DispatchDirect: + return true; + case PacketOpcode.Nop: + var custom = PacketHeader.CustomCode(header); + if (custom is PacketCustomCode.ShaderRegisterTable or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker) + { + return true; + } + + return custom == PacketCustomCode.Zero && + (payload.IsEmpty || (payload[0] & 0xFFFF_0000u) != MarkerMagic || (payload[0] & 0xFFFu) is not (0x777 or 0x778 or 0x781)); + default: + return false; + } + } + + // The cache and flush events RaiseEvent turns into a global barrier, and the ones it ignores. + private static bool IsRunEvent(uint control) + { + var type = control & 0x3Fu; + var index = (control >> 8) & 0x7u; + return type is 0x07 or 0x0F or 0x10 or 0x0D or 0x0E or 0x12 or 0x17 or 0x18 or 0x19 or 0x1A or 0x1B || + (type is 0x16 or 0x31 or 0x2A or 0x2C or 0x2E && index is 0 or 7); + } + + // COMPUTE_DISPATCH_INITIATOR, the first register of the compute range (RegisterBanks.PrepareShaderWrite). + private const uint RunComputeRangeStart = 0x200; + + // Closes the open run; true when a poisoned member rolled the packets back (the caller continues the loop). + private bool CloseRun(PacketCursorStack execution) + { + if (_runs!.Barrier() is not { } rewind) + { + _runUndo.Clear(); + return false; + } + + ApplyRewind(execution, rewind); + return true; + } + + // Inside a handler: closes the open run; true when the handler must stop, so the loop rolls the packets back. + private bool CloseRunInHandler() + { + if (_runs!.Barrier() is not { } rewind) + { + _runUndo.Clear(); + return false; + } + + _rewind = rewind; + return true; + } + + private void ApplyRewind(PacketCursorStack execution, DeferredRewind rewind) + { + var depth = execution.Depth - 1; + ref var cursor = ref execution.At(depth); + if (depth != rewind.Depth || cursor.Address != rewind.CursorAddress) + { + throw _host.Fatal($"A deferred dispatch run rolled back to another buffer: depth={depth}/{rewind.Depth} address=0x{cursor.Address:X16}/0x{rewind.CursorAddress:X16}."); + } + + for (var index = _runUndo.Count - 1; index >= rewind.RawUndoMark; index--) + { + var (offset, value, written) = _runUndo[index]; + Registers.Shader.Restore(offset, value, written); + } + + _runUndo.Clear(); + const uint computeCount = RegisterBankLayout.ShaderRegisterCount - RunComputeRangeStart; + TypedRegisters.PrepareShaderWrite(RunComputeRangeStart, computeCount); + rewind.Compute.CopyTo(TypedRegisters.Shader.Compute); + TypedRegisters.MarkWritten(RegisterStamps.ShaderBitsFor(RunComputeRangeStart, computeCount)); + UserDataMarker = rewind.UserDataMarker; + cursor.Offset = rewind.Offset; + cursor.DeferredAdvance = 0; + _packetWindowGeneration++; + execution.MadeProgress = true; + } + + // The raw mirror's register before a write inside an open run. + private void NoteRunUndo(uint offset) + { + var (value, written) = Registers.Shader.Peek(offset); + _runUndo.Add((offset, value, written)); + } + private sealed class PacketWindow { public const int CapacityDwords = 256; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs index fdec4e545..3a3b1b557 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs @@ -139,6 +139,20 @@ void EndWorkerResolve() // At the stream position of the draw: whether the bytes a worker read are what it would read now. bool ValidateWorkerReads(ResolveReadLog reads) => true; + // As BeginWorkerResolve, but a read the worker cannot serve and log refuses the resolve (SerialResolveRequiredException): + // a deferred dispatch member rolls back to the command thread instead. + void BeginStrictWorkerResolve(long sequence, ResolveReadLog reads) => BeginWorkerResolve(sequence, reads); + + // The deferred dispatch runs of the stream thread, or null. + IDeferredDispatchRuns? DispatchRuns => null; + + // SHARPEMU_COMPUTE_TICKETS: the worker rebinds direct dispatches take ahead of the stream, or null. + SharpEmu.Libs.Gpu.Pipelines.ComputeTickets? ComputeTickets => null; + + // At a compute ticket's take: whether the bytes its worker read are what the stream would read now. The ticket was + // requested ahead of earlier dispatches, so writes they posted since must refuse it. + bool ValidateTicketReads(ResolveReadLog reads) => ValidateWorkerReads(reads); + // Runs commands other threads posted to this worker. Called before every packet. void RunPendingCommands(); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/ShaderProgramRegisters.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/ShaderProgramRegisters.cs index c0dc9cb22..9bfe0b0b3 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/ShaderProgramRegisters.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/ShaderProgramRegisters.cs @@ -300,6 +300,40 @@ public ComputeStageRegisters Copy() copy.UserScalars = UserScalars.Copy(); return copy; } + + // Copies every register into target, which keeps its own user scalar set: a holder that copies registers often reuses + // one object instead of allocating two per copy. + public void CopyTo(ComputeStageRegisters target) + { + target.Address = Address; + target.ProgramChecksum = ProgramChecksum; + target.ThreadsX = ThreadsX; + target.ThreadsY = ThreadsY; + target.ThreadsZ = ThreadsZ; + target.VectorRegisterCount = VectorRegisterCount; + target.Priority = Priority; + target.FloatMode = FloatMode; + target.Dx10Clamp = Dx10Clamp; + target.DebugMode = DebugMode; + target.IeeeMode = IeeeMode; + target.RequireForwardProgress = RequireForwardProgress; + target.HalfPrecisionOverflow = HalfPrecisionOverflow; + target.ThreadgroupConfiguration = ThreadgroupConfiguration; + target.WaveSize = WaveSize; + target.ScratchEnable = ScratchEnable; + target.UserScalarCount = UserScalarCount; + target.ThreadGroupIdXEnable = ThreadGroupIdXEnable; + target.ThreadGroupIdYEnable = ThreadGroupIdYEnable; + target.ThreadGroupIdZEnable = ThreadGroupIdZEnable; + target.ThreadGroupSizeEnable = ThreadGroupSizeEnable; + target.ThreadIdComponentCount = ThreadIdComponentCount; + target.LocalDataShareSize = LocalDataShareSize; + target.SharedVectorRegisters = SharedVectorRegisters; + var scalars = target.UserScalars; + scalars.Values = UserScalars.Values; + scalars.Kinds = UserScalars.Kinds; + scalars.Count = UserScalars.Count; + } } // The shader bank: the program registers of every stage and their user scalars. diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs index 6d6cb688c..d9e3000f7 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs @@ -7,12 +7,14 @@ namespace SharpEmu.Libs.Gpu.GpuCommands; public sealed class SerialResolveRequiredException(string reason) : Exception(reason); // The guest bytes a worker read while it resolved a draw ahead of the stream, so the stream -// position can check them before it records the draw. Adjacent reads merge into one range. +// position can check them before it records the draw. Adjacent reads of one class merge into one range: a clean read (one +// the command thread refuses while a GPU write may own its page or an image's bytes) is checked again with that test. public sealed class ResolveReadLog { private ulong[] _addresses = new ulong[64]; private int[] _offsets = new int[64]; private int[] _lengths = new int[64]; + private bool[] _clean = new bool[64]; private byte[] _bytes = new byte[2048]; private int _byteCount; @@ -22,7 +24,9 @@ public sealed class ResolveReadLog public long Version; public long Publications; - public void Add(ulong address, ReadOnlySpan bytes) + public void Add(ulong address, ReadOnlySpan bytes) => Add(address, bytes, clean: false); + + public void Add(ulong address, ReadOnlySpan bytes, bool clean) { if (_byteCount + bytes.Length > _bytes.Length) { @@ -30,7 +34,8 @@ public void Add(ulong address, ReadOnlySpan bytes) } bytes.CopyTo(_bytes.AsSpan(_byteCount)); - if (Count != 0 && _addresses[Count - 1] + (ulong)_lengths[Count - 1] == address && _offsets[Count - 1] + _lengths[Count - 1] == _byteCount) + if (Count != 0 && _clean[Count - 1] == clean && _addresses[Count - 1] + (ulong)_lengths[Count - 1] == address && + _offsets[Count - 1] + _lengths[Count - 1] == _byteCount) { _lengths[Count - 1] += bytes.Length; _byteCount += bytes.Length; @@ -42,11 +47,13 @@ public void Add(ulong address, ReadOnlySpan bytes) Array.Resize(ref _addresses, Count * 2); Array.Resize(ref _offsets, Count * 2); Array.Resize(ref _lengths, Count * 2); + Array.Resize(ref _clean, Count * 2); } _addresses[Count] = address; _offsets[Count] = _byteCount; _lengths[Count] = bytes.Length; + _clean[Count] = clean; _byteCount += bytes.Length; Count++; } @@ -58,6 +65,8 @@ public void Add(ulong address, uint word) Add(address, bytes); } + public bool IsClean(int index) => _clean[index]; + public ReadOnlySpan Bytes(int index, out ulong address) { address = _addresses[index]; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ShaderRegisterMirror.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ShaderRegisterMirror.cs index e0e2b2ad4..c26ed8a96 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ShaderRegisterMirror.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ShaderRegisterMirror.cs @@ -65,6 +65,28 @@ public void SetRange(uint firstOffset, ReadOnlySpan values) values.CopyTo(_values.AsSpan((int)firstOffset, values.Length)); } + // A bank register as it stands, and put back as it stood (a deferred dispatch run's rollback). + internal (uint Value, bool Written) Peek(uint offset) => + (_values[offset], (_written[offset / BitsPerWord] & (1ul << (int)(offset % BitsPerWord))) != 0); + + internal void Restore(uint offset, uint value, bool written) + { + _values[offset] = value; + if (written) + { + MarkWritten(offset); + return; + } + + ref var word = ref _written[offset / BitsPerWord]; + var bit = 1ul << (int)(offset % BitsPerWord); + if ((word & bit) != 0) + { + word &= ~bit; + _bankCount--; + } + } + public bool ContainsKey(uint offset) => TryGetValue(offset, out _); public bool TryGetValue(uint offset, out uint value) diff --git a/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs b/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs index 9a69d6112..84a137485 100644 --- a/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs +++ b/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs @@ -116,6 +116,9 @@ public sealed unsafe partial class CachedImage : IDisposable public ResourceSlotIdentifier DepthOwner; public ulong LastAccessTick; public int RecencyEntryIndex; + // The frame of the use before the last one (collection ticks), or ulong.MaxValue for none. An image used in each of the + // two frames before the current one is a recurring alias, which an overlapping request keeps registered. + public ulong PreviousUseTick = ulong.MaxValue; public bool Parked; public ulong ParkedTick; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs index 19bd143ed..be34d5c20 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs @@ -399,7 +399,8 @@ private void TraceMetadataBinding(in ImageRequest request) } private const int MetadataEventSlots = 1024; - private readonly (long Generation, ulong Address)[] _metadataEvents = new (long, ulong)[MetadataEventSlots]; + // ClearOnly marks an event that changed only clear state: a slice's clear bit, a register clear or a tracked DCC fill. + private readonly (long Generation, ulong Address, bool ClearOnly)[] _metadataEvents = new (long, ulong, bool)[MetadataEventSlots]; private long _metadataGeneration = 1; public long MetadataGeneration => Volatile.Read(ref _metadataGeneration); @@ -420,7 +421,7 @@ internal static string TakeMetadataChangeReport() return parts.Count == 0 ? "none" : string.Join(",", parts); } - private void NoteMetadataChange(ulong address, + private void NoteMetadataChange(ulong address, bool clearOnly = false, [System.Runtime.CompilerServices.CallerMemberName] string caller = "", [System.Runtime.CompilerServices.CallerLineNumber] int line = 0) { if (RenderPhaseProfile.Enabled) @@ -429,7 +430,7 @@ private void NoteMetadataChange(ulong address, } var generation = _metadataGeneration + 1; - _metadataEvents[generation & (MetadataEventSlots - 1)] = (generation, address); + _metadataEvents[generation & (MetadataEventSlots - 1)] = (generation, address, clearOnly); Volatile.Write(ref _metadataGeneration, generation); } @@ -463,6 +464,92 @@ private bool MetadataUnchangedSince(long generation, ulong address) return true; } + // Whether every metadata event at the address since the generation changed only clear state. + private bool OnlyClearsSince(long generation, ulong address) + { + var current = _metadataGeneration; + if (current - generation >= MetadataEventSlots) + { + return false; + } + + for (var at = current; at > generation; at--) + { + var entry = _metadataEvents[at & (MetadataEventSlots - 1)]; + if (entry.Address == address && !entry.ClearOnly) + { + return false; + } + } + + return true; + } + + // Whether a tracked clear waits on a slice the view covers (every slice for a 3D view). An entry that is missing, + // invalidated or a pending DCC fill counts as waiting. + private bool AnyCoveredSliceClear(ulong address, in ImageViewDescription view) + { + if (!_surfaceMetadata.TryGetValue(address, out var found) || found.Invalidated || found.Kind == SurfaceMetadataKind.PendingDcc) + { + return true; + } + + var count = found.Kind == SurfaceMetadataKind.Dcc ? found.DccSliceCount : 32u; + var first = 0u; + var end = count; + if (view.Type != ImageViewType.Type3D && view.LayerCount < count && view.BaseLayer < count) + { + first = view.BaseLayer; + end = Math.Min(count, view.BaseLayer + view.LayerCount); + } + + for (var slice = first; slice < end; slice++) + { + if (found.IsSliceClear(slice)) + { + return true; + } + } + + return false; + } + + // A slice segment can be recorded before a clear that an earlier stream item then runs and consumes. Its use still + // holds when only clear-state events reached the metadata since the segment began and no slice the use's view covers + // waits on a clear now: the recording worker stops at a pending clear, so it saw none, and the clear ran before the + // segment. A use whose segment applies the view's pending clear at its join (clearApplied) may still find a covered + // slice waiting on a clear. + private bool ConsumedClearsOnly(in ImageSliceUse use, CachedImage image, long generation, bool requestChanged, bool imageChanged, + bool clearApplied = false) + { + var view = use.Request.View; + if (requestChanged) + { + var address = use.Request.Description.Metadata.Range.Address; + if (!OnlyClearsSince(generation, address) || (!clearApplied && AnyCoveredSliceClear(address, in view))) + { + return false; + } + } + + if (imageChanged) + { + var address = image.Description.Metadata.Range.Address; + if (!OnlyClearsSince(generation, address) || (!clearApplied && AnyCoveredSliceClear(address, in view))) + { + return false; + } + } + + return true; + } + + internal bool ConsumedClearsOnlyForTest(long generation, ulong address, ImageViewDescription view) + { + using var held = _lock.Read(); + return !MetadataUnchangedSince(generation, address) && OnlyClearsSince(generation, address) && !AnyCoveredSliceClear(address, in view); + } + public bool IsMetadata(ulong address) { using var held = _lock.Read(); @@ -543,7 +630,7 @@ public bool ClearMetadata(ulong address) } found.ClearMask = uint.MaxValue; - NoteMetadataChange(address); + NoteMetadataChange(address, clearOnly: true); return true; } @@ -568,8 +655,10 @@ public bool TryAbsorbDccFill(ulong address, ulong size, uint fillValue) }; using var held = _lock.Hold(); RecordMetadataEvent("dcc-fill-request", address, size, fillValue); - NoteMetadataChange(address); - if (!_surfaceMetadata.TryGetValue(address, out var found) || found.Invalidated) + var known = _surfaceMetadata.TryGetValue(address, out var found); + // Only a fill tracked on a registered DCC surface changes clear state alone. + NoteMetadataChange(address, clearOnly: known && !found!.Invalidated && found.Kind == SurfaceMetadataKind.Dcc && !found.NativeColorClear); + if (!known || found!.Invalidated) { IncludeMetadataWriteRange(address, size); // The fill may precede color-target discovery; a pending entry stays invisible until then. @@ -688,7 +777,7 @@ public bool SetMetadataSlice(ulong address, uint slice, bool isClear) return false; } - NoteMetadataChange(address); + NoteMetadataChange(address, clearOnly: true); found.SetSliceClear(slice, isClear); return true; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs index 6c8031db0..039714599 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs @@ -9,6 +9,19 @@ namespace SharpEmu.Libs.Gpu.Images; +// What ApplyNativeColorClear would do for a request. +internal enum NativeColorClearPrediction : byte +{ + // Nothing: the registration is current and no slice holds a clear code. + Settled, + // A registration update only: no slice holds a clear code, so it records nothing. + RegistrationOnly, + // A clear to record. + ClearCode, + // A view outside its slices, or metadata that cannot be read. + BadView, +} + public sealed unsafe partial class GuestImageCache { internal void SynchronizeColorMetadata(in ImageRequest request) @@ -122,6 +135,44 @@ internal bool NativeColorClearSettled(ResourceSlotIdentifier imageIdentifier, in return true; } + // What ApplyNativeColorClear would do for the request, read-only. Unlike the settled check it reads the slices of an + // image whose registration is not current; metadata it cannot read is BadView, so the caller stops and the serial + // apply decides. + [SkipLocalsInit] + internal NativeColorClearPrediction PredictNativeColorClear(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) + { + var description = request.Description; + var metadata = description.Metadata; + if (!metadata.NativeColorClear) return NativeColorClearPrediction.Settled; + var metadataKind = metadata.Kind == MetadataKind.Cmask ? SurfaceMetadataKind.CMask : SurfaceMetadataKind.Dcc; + var view = request.View; + var layers = description.TransferLayers; + var volumeTexture = description.IsVolume && view.Type == ImageViewType.Type3D; + var layerCount = volumeTexture ? description.Extent.Depth : view.LayerCount; + var sliceSize = metadata.Range.Size / layers; + if (sliceSize == 0 || metadata.ColorMetadataBaseLayer >= layers || + layerCount > layers - metadata.ColorMetadataBaseLayer) + return NativeColorClearPrediction.BadView; + + bool registered; + using (_lock.Read()) + { + registered = NativeColorClearRegistered(imageIdentifier, in metadata, metadataKind, layers); + } + + Span bytes = stackalloc byte[4096]; + for (uint slice = 0; slice < layerCount; slice++) + { + var address = metadata.Range.Address + sliceSize * (metadata.ColorMetadataBaseLayer + slice); + if (!_backing.TryReadBacking(address, bytes[..1])) + return NativeColorClearPrediction.BadView; + if (TryInspectColorClear(request, view.BaseLayer + slice, address, sliceSize, bytes, out _)) + return NativeColorClearPrediction.ClearCode; + } + + return registered ? NativeColorClearPrediction.Settled : NativeColorClearPrediction.RegistrationOnly; + } + private bool NativeColorClearRegistered(ResourceSlotIdentifier imageIdentifier, in MetadataDescription metadata, SurfaceMetadataKind metadataKind, uint layers) => _slots.TryGet(imageIdentifier) is { } image && diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs index 2200b7e85..147c524a9 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs @@ -453,6 +453,24 @@ private ResourceSlotIdentifier ResolveDepthOverlap(in ImageDescription requested return replacementImageIdentifier; } + // Whether an overlapping cached image counts as used this frame, so it is not safe to park or delete. A recurring alias + // counts too, one used in each of the two frames before this one: two aliases of the same memory that a title uses every + // frame both stay registered instead of swapping at each one's first use. An image the frame before used but the one + // before it did not is parked as before, so the one-off images a title places in the same memory frame after frame do + // not pile up (each registered image watches its pages, and a page holds at most 127 watches). The serial overlap and + // the render workers' read-only overlap must agree. + private bool UsedThisFrameForOverlap(CachedImage cached) + { + if (!cached.Registered) + { + return false; + } + + var lastUse = _recencyQueue.GetLastUseTick(cached.RecencyEntryIndex); + return lastUse >= _collectionTick || + (lastUse + 1 == _collectionTick && cached.PreviousUseTick != ulong.MaxValue && cached.PreviousUseTick + 2 == _collectionTick); + } + private OverlapResolution ResolveOverlap(in ImageDescription requested, ImageRole role, ResourceSlotIdentifier cachedImageIdentifier, ResourceSlotIdentifier mergedImageIdentifier) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ImageOverlap); @@ -466,7 +484,7 @@ private OverlapResolution ResolveOverlap(in ImageDescription requested, ImageRol var currentTick = _scheduler.CurrentTick; // A title submits dozens of command buffers per frame, so an image it writes early in a frame and reads late // in it is past the removal window in between. As in collection, an image used this frame is not stale. - var usedThisFrame = cached.Registered && _recencyQueue.GetLastUseTick(cached.RecencyEntryIndex) >= _collectionTick; + var usedThisFrame = UsedThisFrameForOverlap(cached); var safeToDelete = !usedThisFrame && currentTick - Math.Min(currentTick, cached.LastAccessTick) > TicksBeforeRemoval; if (requested.FirstLevel != 0 || cachedInfo.FirstLevel != 0) { diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs index 882e47917..bdefaf170 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs @@ -235,7 +235,7 @@ private bool TryResolveOverlapForSlice(in ImageDescription requested, ImageRole ref readonly var cachedInfo = ref cached.Description; var currentTick = _scheduler.CurrentTick; - var usedThisFrame = cached.Registered && _recencyQueue.GetLastUseTick(cached.RecencyEntryIndex) >= _collectionTick; + var usedThisFrame = UsedThisFrameForOverlap(cached); var safeToDelete = !usedThisFrame && currentTick - Math.Min(currentTick, cached.LastAccessTick) > TicksBeforeRemoval; if (requested.Data.Address == cachedInfo.Data.Address && requested.BlockExtent.Width == cachedInfo.BlockExtent.Width && requested.BlockExtent.Height == cachedInfo.BlockExtent.Height && @@ -711,7 +711,10 @@ public bool WouldClearImageFromBuffer(ulong address, ulong size, uint packedClea }; } - public bool ValidateSliceImages(List uses, ulong lookupGeneration, long metadataGeneration) + // depthClears are the depth views whose pending HTILE clear the segment's join applies itself: a depth use of one of them + // passes when only clear-state events reached its metadata, even with a covered slice still waiting on a clear. + public bool ValidateSliceImages(List uses, ulong lookupGeneration, long metadataGeneration, + IReadOnlyList<(ResourceSlotIdentifier Image, ImageViewDescription View)>? depthClears = null) { using var held = _lock.Read(); foreach (var use in uses) @@ -738,8 +741,13 @@ public bool ValidateSliceImages(List uses, ulong lookupGeneration return SliceLookupFailed(SliceLookupFailure.ChangedAtJoin, use.Request.Role); } - if ((use.Request.Description.HasMetadata && !MetadataUnchangedSince(metadataGeneration, use.Request.Description.Metadata.Range.Address)) || - (image.Description.HasMetadata && !MetadataUnchangedSince(metadataGeneration, image.Description.Metadata.Range.Address))) + var requestChanged = use.Request.Description.HasMetadata && + !MetadataUnchangedSince(metadataGeneration, use.Request.Description.Metadata.Range.Address); + var imageChanged = image.Description.HasMetadata && + !MetadataUnchangedSince(metadataGeneration, image.Description.Metadata.Range.Address); + if ((requestChanged || imageChanged) && + !ConsumedClearsOnly(in use, image, metadataGeneration, requestChanged, imageChanged, + use.Request.Role == ImageRole.DepthTarget && HasDepthClear(depthClears, use.Image, use.Request.View))) { return SliceLookupFailed(SliceLookupFailure.MetadataChangedAtJoin, use.Request.Role); } @@ -748,6 +756,25 @@ public bool ValidateSliceImages(List uses, ulong lookupGeneration return true; } + private static bool HasDepthClear(IReadOnlyList<(ResourceSlotIdentifier Image, ImageViewDescription View)>? clears, ResourceSlotIdentifier image, + in ImageViewDescription view) + { + if (clears is null) + { + return false; + } + + for (var index = 0; index < clears.Count; index++) + { + if (clears[index].Image == image && clears[index].View == view) + { + return true; + } + } + + return false; + } + // Applies in stream order what a slice's recording thread only read: recency, refreshes from // guest memory, GPU ownership, metadata registration and readback scheduling. public void ApplySliceUse(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs index d57c9040f..a3a67f099 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs @@ -33,6 +33,7 @@ private void AddToIndex(ResourceSlotIdentifier imageIdentifier) image.Registered = true; InvalidateLookups(image.Description.Data.Address, image.Description.Data.End); image.RecencyEntryIndex = _recencyQueue.Insert(imageIdentifier, _collectionTick); + image.PreviousUseTick = ulong.MaxValue; _totalUsedMemory += image.AccountedSize; } @@ -258,6 +259,14 @@ private void TouchImage(CachedImage image) { if (image.Registered) { + // The first use in a frame keeps the frame of the use before it: an image used in each of the two frames before + // the current one is a recurring alias (UsedThisFrameForOverlap). + var lastUse = _recencyQueue.GetLastUseTick(image.RecencyEntryIndex); + if (lastUse < _collectionTick) + { + image.PreviousUseTick = lastUse; + } + _recencyQueue.Touch(image.RecencyEntryIndex, _collectionTick); } } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ComputeTickets.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ComputeTickets.cs new file mode 100644 index 000000000..d7883db4f --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ComputeTickets.cs @@ -0,0 +1,382 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// SHARPEMU_COMPUTE_TICKETS (on by default; 0 turns it off, verify checks it): a direct dispatch of a kept compute program +// takes its resource rebind from a worker thread instead of rebinding on the command thread. At a direct dispatch the +// interpreter scans the packets that follow it on a shadow copy of the compute registers and requests a ticket for each +// direct dispatch it finds; a worker runs the program's rebind (user data, stage inputs, resource materialization) with +// every guest read recorded. The dispatch takes the ticket where it would rebind only when the ticket is finished, was made +// for the same kept program, registers, groups and initiator, and its reads still hold (no GPU write, publication, pending +// write or store since); otherwise it rebinds as before. verify rebinds every taken dispatch on the command thread as well, +// compares the two and keeps the serial result. +public sealed class ComputeTickets : IDisposable +{ + public enum TicketMode + { + Off, + On, + Verify, + } + + public static readonly TicketMode Mode = Environment.GetEnvironmentVariable("SHARPEMU_COMPUTE_TICKETS") switch + { + "0" => TicketMode.Off, + "verify" => TicketMode.Verify, + _ => TicketMode.On, + }; + + public const int WorkerCount = 3; + + // Dispatches requested ahead of the command thread, and the lead below which a dispatch scans again. + public const int MaxLead = 48; + public const int LowWater = 8; + public const int MaxScanDwords = 4096; + + internal sealed class Ticket + { + public object? Owner; + public ulong Address; + public ComputeStageRegisters Compute = null!; + public uint GroupsX; + public uint GroupsY; + public uint GroupsZ; + public uint Initiator; + public KeptComputeProgram? Kept; + public ProgramSourceEntry? Entry; + public ShaderSource? BaseSource; + public Gen5ComputeSystemRegisters SystemRegisters; + public bool GpuThreadCounts; + public long Registrations; + public readonly ResolveReadLog Reads = new(); + public ComputeProgram? Program; + public ShaderSource? Source; + public bool Refused; + + // 0 queued or running, 1 done, 2 abandoned by the command thread. + public int State; + + public void Reset() + { + Owner = null; + Compute = null!; + Kept = null; + Entry = null; + BaseSource = null; + Program = null; + Source = null; + Refused = false; + Reads.Clear(); + State = 0; + } + } + + private static ComputeTickets? _reported; + + private readonly ShaderPipelineCache _pipelines; + private readonly Action _beginWorker; + private readonly Action _endWorker; + private readonly Func _validate; + private readonly BlockingCollection? _queue; + private readonly List? _manual; + private readonly Thread[] _threads; + private readonly Queue _lead = new(); + private readonly ConcurrentQueue _spare = new(); + private object? _currentOwner; + private ulong _currentAddress; + private bool _hasCurrent; + private object? _scanOwner; + private ulong _scanFrontier; + private ulong _rescanAt; + + public long Requested; + public long Served; + public long NotReady; + public long NoTicket; + public long Unused; + public long Refused; + public long Verified; + public long Mismatches; + + // workers > 0: that many threads; 0: each ticket runs when it is requested; below 0: tickets wait for RunManual (tests). + internal ComputeTickets(ShaderPipelineCache pipelines, Action beginWorker, Action endWorker, Func validate, + int workers, bool verify = false) + { + _pipelines = pipelines; + _beginWorker = beginWorker; + _endWorker = endWorker; + _validate = validate; + Verify = verify; + _threads = []; + if (workers > 0) + { + _queue = new BlockingCollection(); + _threads = new Thread[workers]; + for (var index = 0; index < workers; index++) + { + _threads[index] = new Thread(Run) { IsBackground = true, Name = $"SharpEmu compute ticket worker {index}" }; + _threads[index].Start(); + } + } + else if (workers < 0) + { + _manual = []; + } + + _reported = this; + } + + public bool Verify { get; } + + internal int LeadCount => _lead.Count; + + // The interpreter marks the direct dispatch packet it executes; only that dispatch takes a ticket. + public void BeginDispatch(object owner, ulong address) + { + _currentOwner = owner; + _currentAddress = address; + _hasCurrent = true; + } + + public void EndDispatch() => _hasCurrent = false; + + // Whether the interpreter scans ahead at this dispatch, and the last dispatch the previous scan already covered (the scan + // skips dispatches up to it). Inside the range of the previous scan it scans again only from the dispatch that scan marked, + // and never when that scan ended at a packet it cannot pass. + public bool NeedsScan(object owner, ulong address, out ulong requestedThrough) + { + requestedThrough = 0; + if (_lead.TryPeek(out var head) && !ReferenceEquals(head.Owner, owner)) + { + DropAll(); + } + + DropBefore(owner, address); + var inside = ReferenceEquals(_scanOwner, owner) && address <= _scanFrontier; + if (inside && address < _rescanAt) + { + return false; + } + + requestedThrough = inside ? _scanFrontier : 0; + return true; + } + + // The end of a scan from the dispatch at address: the dispatches it covered, so the next scan starts from the one LowWater + // dispatches before its end, never inside its range when it ended at a packet it cannot pass. + public void EndScan(object owner, ulong address, ReadOnlySpan found, bool stopped) + { + var continued = ReferenceEquals(_scanOwner, owner) && address <= _scanFrontier; + _scanOwner = owner; + if (found.IsEmpty) + { + _scanFrontier = continued ? _scanFrontier : address; + _rescanAt = ulong.MaxValue; + return; + } + + _scanFrontier = found[^1]; + _rescanAt = stopped ? ulong.MaxValue : found[Math.Max(0, found.Length - LowWater)]; + } + + // Tests observe what the scan predicted. + internal Action? RequestObserver { get; set; } + + // A dispatch the scan predicted: copied registers, then a worker rebinds it if a kept program matches. + internal void Request(object owner, ulong address, ComputeStageRegisters compute, uint groupsX, uint groupsY, uint groupsZ, uint initiator) + { + RequestObserver?.Invoke(address, compute, groupsX, groupsY, groupsZ, initiator); + if (_lead.Count >= MaxLead) + { + return; + } + + var ticket = _spare.TryDequeue(out var spare) ? spare : new Ticket(); + ticket.Owner = owner; + ticket.Address = address; + ticket.Compute = compute.Copy(); + ticket.GroupsX = groupsX; + ticket.GroupsY = groupsY; + ticket.GroupsZ = groupsZ; + ticket.Initiator = initiator; + ticket.GpuThreadCounts = false; + if (!_pipelines.PrepareComputeTicket(ticket)) + { + Recycle(ticket); + return; + } + + Interlocked.Increment(ref Requested); + _lead.Enqueue(ticket); + if (_queue is not null) + { + _queue.Add(ticket); + } + else if (_manual is not null) + { + _manual.Add(ticket); + } + else + { + RunTicket(ticket); + } + } + + internal void RunManual() + { + foreach (var ticket in _manual!) + { + RunTicket(ticket); + } + + _manual.Clear(); + } + + // At the rebind of the marked dispatch: its ticket, finished, made for this kept program and inputs, with reads that + // still hold; otherwise null and the caller rebinds. The caller recycles a returned ticket after it took the result. + internal Ticket? TryTake(KeptComputeProgram kept, ComputeStageRegisters compute, uint initiator, uint groupsX, uint groupsY, uint groupsZ) + { + if (!_hasCurrent) + { + return null; + } + + DropBefore(_currentOwner!, _currentAddress); + if (!_lead.TryPeek(out var ticket) || !ReferenceEquals(ticket.Owner, _currentOwner) || ticket.Address != _currentAddress) + { + Interlocked.Increment(ref NoTicket); + return null; + } + + _lead.Dequeue(); + if (Volatile.Read(ref ticket.State) != 1) + { + Interlocked.Increment(ref NotReady); + Abandon(ticket); + return null; + } + + if (ticket.Refused || !ShaderPipelineCache.TicketMatches(ticket, kept, compute, initiator, groupsX, groupsY, groupsZ) || !_validate(ticket.Reads)) + { + Interlocked.Increment(ref Refused); + Recycle(ticket); + return null; + } + + Interlocked.Increment(ref Served); + return ticket; + } + + internal void NoteVerify(bool same) + { + Interlocked.Increment(ref Verified); + if (!same) + { + Interlocked.Increment(ref Mismatches); + } + } + + internal void Recycle(Ticket ticket) + { + ticket.Reset(); + _spare.Enqueue(ticket); + } + + private void DropBefore(object owner, ulong address) + { + while (_lead.TryPeek(out var head) && ReferenceEquals(head.Owner, owner) && head.Address < address) + { + _lead.Dequeue(); + Interlocked.Increment(ref Unused); + Abandon(head); + } + } + + private void DropAll() + { + while (_lead.TryDequeue(out var ticket)) + { + Interlocked.Increment(ref Unused); + Abandon(ticket); + } + } + + // A ticket the command thread no longer wants: recycled now if it is finished, otherwise by its worker. + private void Abandon(Ticket ticket) + { + if (Interlocked.CompareExchange(ref ticket.State, 2, 0) == 1) + { + Recycle(ticket); + } + } + + private void Run() + { + HostLaneReservation.ApplyToHostWorkerThread(); + VideoOut.RenderPhaseProfile.AttachResolveWorker(); + foreach (var ticket in _queue!.GetConsumingEnumerable()) + { + RunTicket(ticket); + } + } + + private void RunTicket(Ticket ticket) + { + _beginWorker(ticket.Reads); + ShaderProgramCache.SpeculativeResolve = true; + try + { + _pipelines.RunComputeTicket(ticket); + } + catch (Exception) + { + // The command thread rebinds and reports any real failure itself (SerialResolveRequiredException where it + // would compile or raise a fatal). + ticket.Refused = true; + } + finally + { + ShaderProgramCache.SpeculativeResolve = false; + _endWorker(); + } + + if (Interlocked.CompareExchange(ref ticket.State, 1, 0) == 2) + { + Recycle(ticket); + } + } + + // SHARPEMU_PROFILE_RENDER: the counts since the last report. + public static string TakeReport() + { + if (_reported is not { } tickets) + { + return "[PERF][TICKETS] off"; + } + + return FormattableString.Invariant( + $"[PERF][TICKETS] requested={Interlocked.Exchange(ref tickets.Requested, 0)} served={Interlocked.Exchange(ref tickets.Served, 0)} not_ready={Interlocked.Exchange(ref tickets.NotReady, 0)} no_ticket={Interlocked.Exchange(ref tickets.NoTicket, 0)} unused={Interlocked.Exchange(ref tickets.Unused, 0)} refused={Interlocked.Exchange(ref tickets.Refused, 0)} verified={Interlocked.Exchange(ref tickets.Verified, 0)} mismatches={Interlocked.Exchange(ref tickets.Mismatches, 0)}"); + } + + public void Dispose() + { + _queue?.CompleteAdding(); + foreach (var thread in _threads) + { + thread.Join(); + } + + if (ReferenceEquals(_reported, this)) + { + _reported = null; + } + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/DeferredDispatchInputs.cs b/src/SharpEmu.Libs/Gpu/Pipelines/DeferredDispatchInputs.cs new file mode 100644 index 000000000..3b59ba076 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/DeferredDispatchInputs.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.ShaderCompiler; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// What a worker needs to rebind a deferred dispatch member, taken on the command thread at issue: the kept program's entry +// and base source, and the member's own compute registers and dimensions. +internal sealed class DeferredDispatchInputs +{ + public readonly ComputeStageRegisters Compute = new(); + public ProgramSourceEntry? Entry; + public ShaderSource? BaseSource; + public Gen5ComputeSystemRegisters SystemRegisters; + public bool GpuThreadCounts; + public uint GroupsX; + public uint GroupsY; + public uint GroupsZ; + public uint Initiator; + + public void Reset() + { + Entry = null; + BaseSource = null; + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 429974ad8..8d7b71e75 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -1069,6 +1069,9 @@ private static int BoundColorSlots(ContextRegisters context, Span slots) return null; } + // SHARPEMU_COMPUTE_TICKETS: worker rebinds that direct dispatches take ahead of the command thread, or null. + internal ComputeTickets? Tickets { get; set; } + public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ) => GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect: false); @@ -1110,10 +1113,14 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia return WithPrediction(previous, kept.Kernel, kept.Source, kept.SystemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect); } - if (kept.Entry is { } entry && ++kept.Rebinds % IdentityRecheckPeriod != 0) + if (kept.Entry is { } entry && !kept.RecheckDue && ++kept.Rebinds % IdentityRecheckPeriod != 0) { _computeRebound.Increment(); - var rebound = RebindComputeProgram(kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ); + // A direct dispatch takes the rebind a compute ticket worker made ahead of it, while the ticket still holds. + var rebound = !indirect && Tickets is { } tickets && + tickets.TryTake(kept, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ) is { } ticket + ? TakeComputeTicket(tickets, ticket, kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ) + : RebindComputeProgram(kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ); KeepComputeProgram(kept, rebound, compute, dimensionX, dimensionY, dimensionZ); return WithPrediction(rebound, kept.Kernel, kept.Source, kept.SystemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect); } @@ -1136,6 +1143,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia } kept.Source = source; + kept.RecheckDue = false; kept.SystemRegisters = systemRegisters; kept.Kernel = decoded is not null && program.Available && !program.Consumed ? KernelFor(decoded) : null; kept.Entry = program.Available && !program.Consumed && source is not null ? ShaderProgramCache.LastEntry : null; @@ -1164,25 +1172,241 @@ private ComputeProgram RebindComputeProgram(KeptComputeProgram kept, ProgramSour uint dimensionX, uint dimensionY, uint dimensionZ) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); - var userData = UserData(compute.UserScalars, compute.UserScalarCount, probeWrittenRegisters: false, compute.Address, "compute").ToArray(); - var source = kept.Source! with { UserData = userData }; + var source = RebindSource(kept.Source!, compute); kept.Source = source; + if (!TryRebindProgram(entry, source, kept.SystemRegisters, kept.GpuThreadCounts, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, + out var program, out var rejection)) + { + ReportShaderSkip(source, rejection); + return new ComputeProgram { Available = false }; + } + + return program; + } + + private static ShaderSource RebindSource(ShaderSource kept, ComputeStageRegisters compute) => + kept with { UserData = UserData(compute.UserScalars, compute.UserScalarCount, probeWrittenRegisters: false, compute.Address, "compute").ToArray() }; + + // The rebind of a kept program's entry for new user data and dimensions. It touches no kept state, so a ticket worker runs + // it as well (reads recorded between BeginWorkerResolve and EndWorkerResolve). + private bool TryRebindProgram(ProgramSourceEntry entry, ShaderSource source, Gen5ComputeSystemRegisters systemRegisters, bool gpuThreadCounts, + ComputeStageRegisters compute, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, out ComputeProgram program, + out string rejection) + { var input = ComputeStageInputResolver.Resolve(compute, source.Registered, dispatchInitiator, !_host.ComputeWave64Supported, dimensionX, dimensionY, dimensionZ, - kept.GpuThreadCounts); + gpuThreadCounts); var pushDataCursor = ComputePushDataCursor(input); var options = new StageCompileOptions { - ComputeInfo = input, ComputeSystemRegisters = kept.SystemRegisters, - ComputeDispatch = CountedDispatch(input, kept.SystemRegisters, dimensionX, dimensionY, dimensionZ, kept.GpuThreadCounts), + ComputeInfo = input, ComputeSystemRegisters = systemRegisters, + ComputeDispatch = CountedDispatch(input, systemRegisters, dimensionX, dimensionY, dimensionZ, gpuThreadCounts), }; - if (!_programs.TryGetProgramForEntry(entry, source, options, _strictShaders, ref pushDataCursor, out var handle, out var stage, out var rejection)) + if (!_programs.TryGetProgramForEntry(entry, source, options, _strictShaders, ref pushDataCursor, out var handle, out var stage, out rejection)) { - ReportShaderSkip(source, rejection); - return new ComputeProgram { Available = false }; + program = null!; + return false; } input.Stage = stage; - return new ComputeProgram { Program = handle, Input = input }; + program = new ComputeProgram { Program = handle, Input = input }; + return true; + } + + // SHARPEMU_COMPUTE_TICKETS, on the command thread: the kept program a scanned dispatch would rebind. Programs with shader + // calls or without a fast materialization rebind on the command thread only. + internal bool PrepareComputeTicket(ComputeTickets.Ticket ticket) + { + var compute = ticket.Compute; + var registrations = ShaderHeaderRegistry.Registrations; + KeptComputeProgram? kept = null; + if (!_registry.HasFrontend && _keptComputes is { } all && all.TryGetValue(compute.Address, out var keptList)) + { + foreach (var candidate in keptList) + { + if (candidate.Registrations == registrations && candidate.DispatchInitiator == ticket.Initiator && + candidate.GpuThreadCounts == ticket.GpuThreadCounts && SameComputeShape(candidate.Registers, compute)) + { + kept = candidate; + break; + } + } + } + + if (kept is null || kept.Entry is not { } entry || kept.Source is not { } source || entry.HasShaderCalls || + !SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.CanMaterializeFast(entry.Plan)) + { + return false; + } + + ticket.Kept = kept; + ticket.Entry = entry; + ticket.BaseSource = source; + ticket.SystemRegisters = kept.SystemRegisters; + ticket.GpuThreadCounts = kept.GpuThreadCounts; + ticket.Registrations = registrations; + return true; + } + + // On a ticket worker, between BeginWorkerResolve and EndWorkerResolve. + internal void RunComputeTicket(ComputeTickets.Ticket ticket) + { + var source = RebindSource(ticket.BaseSource!, ticket.Compute); + if (!TryRebindProgram(ticket.Entry!, source, ticket.SystemRegisters, ticket.GpuThreadCounts, ticket.Compute, ticket.Initiator, + ticket.GroupsX, ticket.GroupsY, ticket.GroupsZ, out var program, out _)) + { + ticket.Refused = true; + return; + } + + ticket.Program = program; + ticket.Source = source; + } + + // On the command thread: the kept program a direct dispatch would rebind, when a deferred dispatch worker may rebind it + // (as a ticket worker could), or null. + internal KeptComputeProgram? FindDeferrableKept(ComputeStageRegisters compute, uint dispatchInitiator) + { + if (_registry.HasFrontend || _keptComputes is not { } all || !all.TryGetValue(compute.Address, out var keptList)) + { + return null; + } + + var registrations = ShaderHeaderRegistry.Registrations; + KeptComputeProgram? kept = null; + foreach (var candidate in keptList) + { + if (candidate.Registrations == registrations && candidate.DispatchInitiator == dispatchInitiator && !candidate.GpuThreadCounts && + SameComputeShape(candidate.Registers, compute)) + { + kept = candidate; + break; + } + } + + return kept is { Entry: { HasShaderCalls: false } entry, Source: not null, Kernel: null } && + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.CanMaterializeFast(entry.Plan) + ? kept + : null; + } + + // On the command thread: takes a direct dispatch for a deferred dispatch worker. The kept state is left as the rebind + // path leaves it, but for the program, which the worker resolves: the program's next dispatch on the command thread + // rebinds. An identity recheck turn moves to that dispatch, unless a recheck already waits for one. + internal bool ClaimDeferral(KeptComputeProgram kept, ComputeStageRegisters compute, uint dimensionX, uint dimensionY, uint dimensionZ, + uint dispatchInitiator, DeferredDispatchInputs inputs) + { + if ((kept.Rebinds + 1) % IdentityRecheckPeriod == 0) + { + if (kept.RecheckDue) + { + return false; + } + + kept.RecheckDue = true; + } + + kept.Rebinds++; + _computeRebound.Increment(); + inputs.Entry = kept.Entry; + inputs.BaseSource = kept.Source; + inputs.SystemRegisters = kept.SystemRegisters; + inputs.GpuThreadCounts = kept.GpuThreadCounts; + inputs.GroupsX = dimensionX; + inputs.GroupsY = dimensionY; + inputs.GroupsZ = dimensionZ; + inputs.Initiator = dispatchInitiator; + compute.CopyTo(inputs.Compute); + kept.Program = null; + if (kept.Registers is { } registers && SameComputeShape(registers, compute)) + { + registers.UserScalars.CopyFrom(compute.UserScalars, compute.UserScalarCount); + } + else + { + kept.Registers = compute.Copy(); + } + + kept.DimensionX = dimensionX; + kept.DimensionY = dimensionY; + kept.DimensionZ = dimensionZ; + return true; + } + + // A deferred member's rebind: on a worker between BeginWorkerResolve and EndWorkerResolve, or on the render thread. + internal bool RunDeferredRebind(DeferredDispatchInputs inputs, out ComputeProgram program) + { + var source = RebindSource(inputs.BaseSource!, inputs.Compute); + return TryRebindProgram(inputs.Entry!, source, inputs.SystemRegisters, inputs.GpuThreadCounts, inputs.Compute, inputs.Initiator, + inputs.GroupsX, inputs.GroupsY, inputs.GroupsZ, out program, out _); + } + + internal static bool TicketMatches(ComputeTickets.Ticket ticket, KeptComputeProgram kept, ComputeStageRegisters compute, uint dispatchInitiator, + uint dimensionX, uint dimensionY, uint dimensionZ) => + ReferenceEquals(ticket.Kept, kept) && ReferenceEquals(ticket.Entry, kept.Entry) && ticket.Registrations == ShaderHeaderRegistry.Registrations && + ticket.Initiator == dispatchInitiator && ticket.GroupsX == dimensionX && ticket.GroupsY == dimensionY && ticket.GroupsZ == dimensionZ && + ticket.GpuThreadCounts == kept.GpuThreadCounts && ticket.SystemRegisters == kept.SystemRegisters && + kept.Source is { } source && ticket.BaseSource is { } baseSource && (baseSource with { UserData = source.UserData }) == source && + SameComputeShape(ticket.Compute, compute) && SameUserScalars(ticket.Compute.UserScalars, compute.UserScalars, compute.UserScalarCount); + + private ComputeProgram TakeComputeTicket(ComputeTickets tickets, ComputeTickets.Ticket ticket, KeptComputeProgram kept, ProgramSourceEntry entry, + ComputeStageRegisters compute, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ) + { + var program = ticket.Program!; + var source = ticket.Source!; + tickets.Recycle(ticket); + if (!tickets.Verify) + { + kept.Source = source; + return program; + } + + var serial = RebindComputeProgram(kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ); + tickets.NoteVerify(SameRebind(program, source, serial, kept.Source!)); + return serial; + } + + internal static bool SameRebind(ComputeProgram ticket, ShaderSource ticketSource, ComputeProgram serial, ShaderSource serialSource) + { + if (ticket.Available != serial.Available || ticket.Program != serial.Program || !ticketSource.UserData.AsSpan().SequenceEqual(serialSource.UserData)) + { + return false; + } + + var left = ticket.Input.Stage; + var right = serial.Input.Stage; + if (left.Program?.Hash != right.Program?.Hash) + { + return false; + } + + var a = left.Resources; + var b = right.Resources; + if (a is null || b is null) + { + return ReferenceEquals(a, b); + } + + return SameWords(a.Buffers, b.Buffers) && SameWords(a.Images, b.Images) && SameWords(a.Samplers, b.Samplers) && + a.FlattenedResourceTable.AsSpan().SequenceEqual(b.FlattenedResourceTable) && a.UserData.AsSpan().SequenceEqual(b.UserData) && + a.DeviceAddressRanges.AsSpan().SequenceEqual(b.DeviceAddressRanges); + } + + private static bool SameWords(uint[][] left, uint[][] right) + { + if (left.Length != right.Length) + { + return false; + } + + for (var index = 0; index < left.Length; index++) + { + if (!left[index].AsSpan().SequenceEqual(right[index])) + { + return false; + } + } + + return true; } private static bool SameUserScalars(UserScalarRegisters kept, UserScalarRegisters current, int count) => @@ -1816,6 +2040,9 @@ internal sealed class KeptComputeProgram public ProgramSourceEntry? Entry; public ShaderPipelineCache.KernelDemand? Kernel; public long Rebinds; + // The identity recheck turn came while one of the program's dispatches was deferred: its next dispatch on the command + // thread resolves it from scratch. + public bool RecheckDue; public long Registrations; public uint DispatchInitiator; public bool GpuThreadCounts; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 7c61a24e1..392f0ae7e 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -531,6 +531,11 @@ public bool TryGetProgram(ShaderSource source, StageCompileOptions options, bool { if (strictShaders) { + if (_speculative) + { + throw new GpuCommands.SerialResolveRequiredException("speculative strict rejection"); + } + throw SubmissionScheduler.Fatal(exception.Message); } @@ -548,6 +553,17 @@ private sealed class ShaderProgramPendingException() : Exception("The linked pro [ThreadStatic] private static ProgramSourceEntry? _lastEntry; + // A speculative resolve (a compute ticket worker) never raises a fatal, compiles or links: where the command thread would, + // it asks for the serial resolve instead, so a ticket made from bytes the guest is still writing only costs its refusal. + [ThreadStatic] + private static bool _speculative; + + internal static bool SpeculativeResolve + { + get => _speculative; + set => _speculative = value; + } + internal static ProgramSourceEntry? LastEntry => _lastEntry; internal bool TryGetProgramForEntry(ProgramSourceEntry entry, ShaderSource source, StageCompileOptions options, bool strictShaders, @@ -569,6 +585,11 @@ internal bool TryGetProgramForEntry(ProgramSourceEntry entry, ShaderSource sourc { if (strictShaders) { + if (_speculative) + { + throw new GpuCommands.SerialResolveRequiredException("speculative strict rejection"); + } + throw SubmissionScheduler.Fatal(exception.Message); } @@ -676,6 +697,11 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa }; if (entry.Plan.DeviceRecordCounts is { } counts && !counts.SupportsDescriptors(entry.Plan, inputs)) { + if (_speculative) + { + throw new GpuCommands.SerialResolveRequiredException("speculative device record fallback"); + } + var handle = GetOrCompileCore(source, options.WithoutDeviceRecordCounts(), ref pushDataCursor, out stage, deferLinking); if (runtimeFallback is null) { @@ -686,6 +712,11 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa } var hasShaderCalls = entry.HasShaderCalls; + if (hasShaderCalls && _speculative) + { + throw new GpuCommands.SerialResolveRequiredException("speculative shader calls"); + } + if (hasShaderCalls && !_compiler.LinkedShaderCallsSupported) throw new ShaderProgramRejectedException( $"The backend does not support linked shader calls: backend={_compiler.BackendName} stage={source.Label} hash=0x{source.Hash:X16}."); @@ -756,6 +787,11 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa System.Diagnostics.Stopwatch.GetTimestamp() - started, materialized ? snapshot : null); if (!materialized) { + if (_speculative) + { + throw new GpuCommands.SerialResolveRequiredException("speculative materialization failure"); + } + var message = $"The shader resources could not be materialized: stage={source.Label} hash=0x{source.Hash:X16} shader=0x{source.Address:X16} reason={materializationFailure}."; if (materializationFailure is ResourceMaterializationFailure.IncompatibleImageCandidates or ResourceMaterializationFailure.ImageCapacityExceeded) throw new ShaderProgramRejectedException(message); @@ -969,6 +1005,8 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa // A ready program serves while this one is prepared; it is never translated again for another specialization. if (runtimeFallback is not null) throw new ShaderProgramPendingException(); + if (_speculative) + throw new GpuCommands.SerialResolveRequiredException("speculative permutation compile"); try { permutation = MakePermutation(source, options, entry, specialization, pushDataCursor, key, sourceWasCached, snapshot, @@ -2661,6 +2699,8 @@ private static ShaderProgramInfo CreateProgramInfo( InstanceOffsetScalarRegister = entry.EmbeddedFetch?.InstanceOffsetScalarRegister ?? ShaderProgramInfo.NoScalarRegister, UsesDeviceAddresses = info.UsesDeviceAddresses, DeviceAddressReadsBounded = entry.Plan.DeviceAddressReadsBounded, + DeviceAddressReadsWindowed = entry.Plan.DeviceAddressReadsWindowed, + DeviceAddressWindowBytes = entry.Plan.DeviceAddressWindowBytes, ConstantStoreValue = FindConstantStoreValue(entry.Program), HasBitwiseExclusiveOr = entry.HasBitwiseExclusiveOr, ConstantFill = entry.ConstantFill, diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs index ac8da911a..287645d85 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs @@ -13,10 +13,21 @@ internal sealed class DispatchChain private const int MaxSpans = 1024; private const ulong IndirectArgumentBytes = 12; - private readonly List _touched = new(); + // SHARPEMU_CHAIN_SAME_PROGRAM_WRITES (on unless "0"): inside a chain whose dispatches all run one program, a dispatch + // whose only overlaps with the chain are plain writes over plain writes, or atomic accesses over atomic accesses, + // takes no barrier. The guest orders compute dispatches only with its own wait and cache events, which end the chain + // with a full barrier; it put none between these dispatches, so it does not rely on their order (an append through + // an atomic counter is the common case). A read of a chain write, a write over a chain read, an atomic access against + // a plain one, image conflicts and a different program keep the barrier. + internal static bool SameProgramWrites { get; set; } = + !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_CHAIN_SAME_PROGRAM_WRITES"), "0", StringComparison.Ordinal); + + private readonly List _read = new(); private readonly List _written = new(); - private readonly List _recordTouched = new(); + private readonly List _atomic = new(); + private readonly List _recordRead = new(); private readonly List _recordWritten = new(); + private readonly List _recordAtomic = new(); private bool _open; private bool _conservative; private bool _readImages; @@ -25,6 +36,12 @@ internal sealed class DispatchChain private bool _recordReadsImages; private bool _recordWritesImages; private long _promotions; + private ulong _recordProgram; + private ulong _program; + private bool _oneProgram; + + // The chain's distinct spans (tests). + internal int SpanCount => _read.Count + _written.Count + _atomic.Count; public bool NeedsHazardBarrier(ResolvedDispatch record, in ShaderStageResources stage, long promotions) { @@ -40,23 +57,36 @@ public bool NeedsHazardBarrier(ResolvedDispatch record, in ShaderStageResources return record.HasStorageWrites; } - if (_conservative || _recordConservative || _touched.Count > MaxSpans) + if (_conservative || _recordConservative || _read.Count > MaxSpans || _written.Count > MaxSpans || _atomic.Count > MaxSpans) { GpuSyncProfile.CountChain(ChainDecision.Conservative); Reset(); return true; } - if ((_recordReadsImages && _wroteImages) || (_recordWritesImages && (_wroteImages || _readImages)) || - Overlaps(_recordTouched, _written) || Overlaps(_recordWritten, _touched)) + var images = (_recordReadsImages && _wroteImages) || (_recordWritesImages && (_wroteImages || _readImages)); + // An atomic access against a plain one is ordered like any other read and write. + var readAfterWrite = Overlaps(_recordRead, _written) || Overlaps(_recordRead, _atomic) || Overlaps(_recordAtomic, _written); + var writeAfterRead = Overlaps(_recordWritten, _read) || Overlaps(_recordWritten, _atomic) || Overlaps(_recordAtomic, _read); + if (!images && !readAfterWrite && !writeAfterRead) { - GpuSyncProfile.CountChain(ChainDecision.Overlap); - Reset(); - return true; + if (!Overlaps(_recordWritten, _written) && !Overlaps(_recordAtomic, _atomic)) + { + GpuSyncProfile.CountChain(ChainDecision.Skipped); + return false; + } + + // A program without a hash is never "the same program". + if (SameProgramWrites && _oneProgram && _recordProgram != 0 && _recordProgram == _program) + { + GpuSyncProfile.CountChain(ChainDecision.SameProgramWrites); + return false; + } } - GpuSyncProfile.CountChain(ChainDecision.Skipped); - return false; + GpuSyncProfile.CountChain(ChainDecision.Overlap); + Reset(); + return true; } public void Commit(bool deferred, long promotions) @@ -67,8 +97,19 @@ public void Commit(bool deferred, long promotions) return; } - _touched.AddRange(_recordTouched); - _written.AddRange(_recordWritten); + if (!_open) + { + _program = _recordProgram; + _oneProgram = true; + } + else if (_recordProgram != _program) + { + _oneProgram = false; + } + + AddMerged(_read, _recordRead); + AddMerged(_written, _recordWritten); + AddMerged(_atomic, _recordAtomic); _readImages |= _recordReadsImages; _wroteImages |= _recordWritesImages; _conservative |= _recordConservative; @@ -78,27 +119,32 @@ public void Commit(bool deferred, long promotions) private void Reset() { - _touched.Clear(); + _read.Clear(); _written.Clear(); + _atomic.Clear(); _open = false; _conservative = false; _readImages = false; _wroteImages = false; + _oneProgram = false; } private void Collect(ResolvedDispatch record, in ShaderStageResources stage) { - _recordTouched.Clear(); + _recordRead.Clear(); _recordWritten.Clear(); + _recordAtomic.Clear(); _recordConservative = false; _recordReadsImages = false; _recordWritesImages = false; + _recordProgram = 0; if (stage.Program is not { } program) { _recordConservative = true; return; } + _recordProgram = program.Hash; var resources = stage.Resources; // Runtime callees and heap accesses can touch resources outside the snapshot below. // Keep their barriers until the chain can account for that complete access set. @@ -135,9 +181,22 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) continue; } + // An atomic binding is its own kind. Otherwise only a buffer the program purely writes is not a read: + // scalar loads and anything not marked written count as reads. var span = new GuestSpan(descriptor.Address, footprint); - _recordTouched.Add(span); - if (program.Buffers[index].Written) + var access = program.Buffers[index]; + if (access.Atomic) + { + _recordAtomic.Add(span); + continue; + } + + if (!access.Written || access.Read || access.Scalar) + { + _recordRead.Add(span); + } + + if (access.Written) { _recordWritten.Add(span); } @@ -159,6 +218,7 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) } } + // Device-address ranges always count as reads; written ones as writes too. foreach (var range in resources.DeviceAddressRanges) { if (!range.Planned || range.Size == 0) @@ -168,7 +228,7 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) } var span = new GuestSpan(range.Base, range.Size); - _recordTouched.Add(span); + _recordRead.Add(span); if (range.Written) { _recordWritten.Add(span); @@ -182,7 +242,33 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) if (record.IndirectArgumentsAddress != 0) { - _recordTouched.Add(new GuestSpan(record.IndirectArgumentsAddress, IndirectArgumentBytes)); + _recordRead.Add(new GuestSpan(record.IndirectArgumentsAddress, IndirectArgumentBytes)); + } + } + + // Adds the spans, widening an overlapping or adjacent one instead of growing the list, so a long run of dispatches + // over the same or neighbouring bytes keeps a short list. + private static void AddMerged(List target, List spans) + { + foreach (var span in spans) + { + var merged = false; + for (var index = 0; index < target.Count; index++) + { + var existing = target[index]; + if (span.Address <= existing.End && existing.Address <= span.End) + { + var begin = Math.Min(span.Address, existing.Address); + target[index] = new GuestSpan(begin, Math.Max(span.End, existing.End) - begin); + merged = true; + break; + } + } + + if (!merged) + { + target.Add(span); + } } } @@ -210,5 +296,6 @@ internal enum ChainDecision Skipped, Overlap, Conservative, + SameProgramWrites, Count, } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index f15466269..8763a93ef 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -202,7 +202,9 @@ void SealDispatchReplay() { } - bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage) => false; + // replaceTable: the stage differs from the sealed dispatch only in its flattened resource table, which the replay + // uploads again and binds by pushing that one descriptor. + bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage, bool replaceTable) => false; void RebindBuffers(IPreparedBindings prepared) { diff --git a/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs b/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs index da20bc7d6..3adf9785c 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs @@ -346,12 +346,35 @@ public void MarkEverything(long sequence) public void Release(long sequence) { + // While a deferred dispatch run is open, its members' marks stay pending, so the in-order checks of later members and + // of the command thread's register tables see every write before them; the release lands when the run closes. + var held = Volatile.Read(ref _holdFrom); + if (sequence >= held) + { + RaiseTo(ref _heldRelease, sequence); + RaiseTo(ref _released, held - 1); + return; + } + if (sequence > Volatile.Read(ref _released)) { Volatile.Write(ref _released, sequence); } } + private long _holdFrom = long.MaxValue; + private long _heldRelease; + + // No release reaches the first member of the open deferred dispatch run, or anything after it, until EndHold. + public void HoldFrom(long sequence) => Volatile.Write(ref _holdFrom, sequence); + + public void EndHold() + { + Volatile.Write(ref _holdFrom, long.MaxValue); + Interlocked.MemoryBarrier(); + RaiseTo(ref _released, Interlocked.Exchange(ref _heldRelease, 0)); + } + private void Sweep() { var released = Volatile.Read(ref _released); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs index df76b3a6b..9b8d91d40 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs @@ -194,6 +194,99 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro Record(record); } + // Whether a direct dispatch runs no group (Dispatch records it skipped). + internal static bool IsEmptyDirectDispatch(ComputeStageRegisters compute, uint dispatchInitiator, uint groupsX, uint groupsY, uint groupsZ) => + IsEmptyDispatch(compute, (dispatchInitiator & DispatchInitiatorUseThreadDimensions) != 0, groupsX, groupsY, groupsZ); + + // The record of a deferred direct dispatch from its rebound program, built as Dispatch builds it after the program + // lookup. On a worker (serialOnly false), a program that is not plain, a decoded fill, copy or clear, or a linked program + // returns null: the member rolls back to the command thread. On the render thread (serialOnly true) every case is + // recorded as Dispatch records it, but a decoded word copy stays in the record instead of being posted. + internal ResolvedDispatch? ResolveDeferredDispatch(ulong submitId, ComputeStageRegisters compute, uint groupsX, uint groupsY, uint groupsZ, + uint dispatchInitiator, ComputeProgram computeProgram, bool serialOnly) + { + var record = _pool.RentDispatch(); + record.Debug = new DebugInformation(RecordedOperation.DispatchDirect, submitId, groupsX, groupsY, groupsZ, dispatchInitiator, compute.Address); + record.Skipped = true; + record.SubmitId = submitId; + record.ShaderAddress = compute.Address; + if (computeProgram.ImageCopy is not null || computeProgram.Consumed || !computeProgram.Available || computeProgram.KnownWrite is not null) + { + if (!serialOnly) + { + _pool.Return(record); + return null; + } + + if (computeProgram.ImageCopy is not null) + { + record.Program = computeProgram; + record.Skipped = false; + record.GroupsX = groupsX; + record.GroupsY = groupsY; + record.GroupsZ = groupsZ; + record.IndirectArgumentsAddress = 0; + return record; + } + + if (computeProgram.Consumed || !computeProgram.Available) + { + return record; + } + } + + var input = computeProgram.Input; + var program = input.Stage.Program ?? throw _host.Fatal($"The compute program is missing: shader=0x{compute.Address:X16}."); + if (program.Bindings is { CallTargetCount: not 0 }) + { + if (!serialOnly) + { + _pool.Return(record); + return null; + } + + if (SkipWhileLinkedModuleCompiles(input, computeProgram.Program, program)) + { + return record; + } + } + + record.MetadataClear = DecodeMetadataClear(input); + record.MetadataClearHasExclusiveOr = program.HasBitwiseExclusiveOr; + record.ConstantFill = DecodeConstantFill(input, groupsX, groupsY, groupsZ); + record.BoundedFill = DecodeBoundedFill(input, groupsX, groupsY, groupsZ, dispatchInitiator); + record.BoundedCopy = DecodeBoundedCopy(input, groupsX, groupsY, groupsZ, dispatchInitiator); + record.ImageClear = TryDecodeImageClear(input, groupsX, groupsY, groupsZ, dispatchInitiator); + if (!serialOnly && (record.ConstantFill is not null || record.BoundedFill is not null || record.BoundedCopy is not null || record.ImageClear is not null)) + { + _pool.Return(record); + return null; + } + + if ((dispatchInitiator & DispatchInitiatorUseThreadDimensions) != 0) + { + groupsX = GroupsFromThreads(groupsX, compute.ThreadsX); + groupsY = GroupsFromThreads(groupsY, compute.ThreadsY); + groupsZ = GroupsFromThreads(groupsZ, compute.ThreadsZ); + } + + var hasStorageWrites = HasBufferWrites(input.Stage); + foreach (var image in program.Images) + { + hasStorageWrites |= image.Written && image.Class == ImageResourceClass.Storage; + } + + record.Skipped = false; + record.Program = computeProgram; + record.GroupsX = groupsX; + record.GroupsY = groupsY; + record.GroupsZ = groupsZ; + record.IndirectArgumentsAddress = 0; + record.GpuThreadCounts = false; + record.HasStorageWrites = hasStorageWrites; + return record; + } + // A program linked with the callees of its hit-group tables can take the driver minutes to compile, and the game // adds callees as it streams. Such programs are ray-traced passes that run every frame, so their dispatches are left // out while the module compiles instead of holding every queue behind it: the pass's output is stale for those diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs index ff162ad4c..80d8a66f0 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs @@ -66,38 +66,54 @@ private void MarkPendingWrites(ResolvedDraw record) } } - private void MarkPendingWrites(ResolvedDispatch record) + private void MarkPendingWrites(ResolvedDispatch record) => MarkDispatchWrites(record, record.Sequence, null); + + // The marks a dispatch record would make, collected for a deferred dispatch's finalization. + internal void CollectDispatchWrites(ResolvedDispatch record, List into) => MarkDispatchWrites(record, 0, into); + + private void MarkDispatchWrites(ResolvedDispatch record, long sequence, List? into) { if (record.Skipped) { return; } - var sequence = record.Sequence; if (record.Program.ImageCopy is { } imageCopy) { - Mark(imageCopy.Destination.Description.Data, sequence, PendingWriteKind.Target); + MarkRange(imageCopy.Destination.Description.Data.Address, imageCopy.Destination.Description.Data.Size, sequence, PendingWriteKind.Target, into); return; } - MarkStageWrites(record.Program.Input.Stage, sequence); + MarkStageWrites(record.Program.Input.Stage, sequence, into); if (record.ConstantFill is { } fill) { - PendingWrites.Mark(fill.Address, fill.Size, sequence, PendingWriteKind.Fill); + MarkRange(fill.Address, fill.Size, sequence, PendingWriteKind.Fill, into); } if (record.BoundedFill is { } bounded) { - PendingWrites.Mark(bounded.Address, bounded.Size, sequence, PendingWriteKind.Fill); + MarkRange(bounded.Address, bounded.Size, sequence, PendingWriteKind.Fill, into); } if (record.BoundedCopy is { } copy) { - PendingWrites.Mark(copy.Destination, copy.Words * sizeof(uint), sequence, PendingWriteKind.Copy); + MarkRange(copy.Destination, copy.Words * sizeof(uint), sequence, PendingWriteKind.Copy, into); } if (record.ImageClear is { } clear) { - PendingWrites.Mark(clear.Descriptor.Address, clear.Size, sequence, PendingWriteKind.Fill); + MarkRange(clear.Descriptor.Address, clear.Size, sequence, PendingWriteKind.Fill, into); + } + } + + private void MarkRange(ulong address, ulong size, long sequence, PendingWriteKind kind, List? into) + { + if (into is null) + { + PendingWrites.Mark(address, size, sequence, kind); + } + else if (size != 0) + { + into.Add(new PendingMark(address, size, kind)); } } @@ -117,7 +133,7 @@ private void MarkTargets(ResolvedDraw record, long sequence) private void Mark(in GuestSpan data, long sequence, PendingWriteKind kind) => PendingWrites.Mark(data.Address, data.Size, sequence, kind); - private void MarkStageWrites(in ShaderStageResources stage, long sequence) + private void MarkStageWrites(in ShaderStageResources stage, long sequence, List? into = null) { if (stage.Program is not { } program) { @@ -136,7 +152,7 @@ private void MarkStageWrites(in ShaderStageResources stage, long sequence) var descriptor = BufferDescriptorWords.From(buffers[index]); if (descriptor.Address != 0 && descriptor.Footprint() is { } footprint) { - PendingWrites.Mark(descriptor.Address, footprint, sequence, PendingWriteKind.Buffer); + MarkRange(descriptor.Address, footprint, sequence, PendingWriteKind.Buffer, into); } } @@ -152,7 +168,7 @@ private void MarkStageWrites(in ShaderStageResources stage, long sequence) if (shapes is not null && index < shapes.Count && TryGetImageData(program, shapes[index], images[index], index, out var data)) { - Mark(data, sequence, PendingWriteKind.Image); + MarkRange(data.Address, data.Size, sequence, PendingWriteKind.Image, into); } } @@ -160,7 +176,7 @@ private void MarkStageWrites(in ShaderStageResources stage, long sequence) { if (range.Written) { - PendingWrites.Mark(range.Base, range.Size, sequence, PendingWriteKind.Range); + MarkRange(range.Base, range.Size, sequence, PendingWriteKind.Range, into); } } @@ -169,7 +185,7 @@ private void MarkStageWrites(in ShaderStageResources stage, long sequence) { if (range.Written) { - PendingWrites.Mark(range.Base, range.Size, sequence, PendingWriteKind.Range); + MarkRange(range.Base, range.Size, sequence, PendingWriteKind.Range, into); } } } @@ -190,3 +206,6 @@ private static bool TryGetImageData(ShaderProgramInfo program, ImageResource ima return data.Size != 0; } } + +// One write mark a deferred dispatch publishes when it is finalized. +public readonly record struct PendingMark(ulong Address, ulong Size, PendingWriteKind Kind); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs index 9fb20b774..6ea4eb0ca 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs @@ -195,7 +195,7 @@ private void RecordPreparedDispatch(ResolvedDispatch record, ComputeProgram comp } if (DispatchReplayEnabled && record.IndirectArgumentsAddress == 0 && !record.GpuThreadCounts && threadDispatch is null && imageSnapshot == 0 && - IsReplayable(program) && _host.CurrentItemSequence is var sequence and not 0) + IsDispatchReplayable(program) && _host.CurrentItemSequence is var sequence and not 0) { _dispatchReplayStage = stage; _dispatchReplayPipeline = pipeline; @@ -268,12 +268,24 @@ private bool TryReplayDispatch(ResolvedDispatch record, ComputeProgram computePr return DispatchMiss(7); } + var replaceTable = false; if (StageInputMismatch(in stage, in _dispatchReplayStage, compareThreadLimits: false) is var mismatch and >= 0) { - return DispatchMiss(2 + mismatch); + // Only the flattened table may differ: the host uploads it again and pushes its descriptor alone. + if (mismatch != 4) + { + return DispatchMiss(2 + mismatch); + } + + if (StageInputMismatchAfterTable(in stage, in _dispatchReplayStage) is var after and >= 0) + { + return DispatchMiss(2 + after); + } + + replaceTable = true; } - if (!_host.TryReplayDispatch(in pipeline, in stage)) + if (!_host.TryReplayDispatch(in pipeline, in stage, replaceTable)) { return DispatchMiss(11); } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index 931be0ee9..89108cfd6 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -36,6 +36,7 @@ internal sealed partial class RenderRecorder : IResolvedCommandSink private static readonly ThreadCounter _drawReplayMisses = new(); private static readonly bool DrawReplayEnabled = Environment.GetEnvironmentVariable("SHARPEMU_DRAW_REPLAY") != "0"; private readonly Dictionary _replayablePrograms = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary _tableReplayablePrograms = new(ReferenceEqualityComparer.Instance); private bool _replayValid; private long _replaySequence; private ShaderStageResources _replayVertex; @@ -818,28 +819,81 @@ private bool IsReplayable(ShaderProgramInfo? program) return known; } + var reason = UnreplayableReason(program); + var replayable = reason is null; + if (!replayable) + { + _unreplayablePrograms.AddOrUpdate(reason!, 1, static (_, count) => count + 1); + } + + _replayablePrograms[program] = replayable; + return replayable; + } + + // A compute program whose one replay refusal is its flattened table seals a replay basis too: a dispatch whose table + // alone differs replays with the table uploaded again and only that descriptor pushed. + private bool IsDispatchReplayable(ShaderProgramInfo? program) + { + if (IsReplayable(program)) + { + return true; + } + + if (program is null) + { + return false; + } + + if (_tableReplayablePrograms.TryGetValue(program, out var known)) + { + return known; + } + + var replayable = program.Bindings?.Find(ShaderCompiler.Resources.DescriptorBindingKind.FlattenedResourceTable) is not null && + UnreplayableReason(program, ignoreFlattenedTable: true) is null; + _tableReplayablePrograms[program] = replayable; + return replayable; + } + + // Why a program cannot seal a replay basis, or null. + private static string? UnreplayableReason(ShaderProgramInfo program, bool ignoreFlattenedTable = false) + { var layout = program.Bindings; - var reason = layout is null ? "no_layout" + return layout is null ? "no_layout" : layout.UsesBindlessHeap ? "bindless" : program.UsesDeviceAddresses ? "device_addresses" : program.CallRecordCallees.Count != 0 || layout.CallTargetCount != 0 || layout.CallArgumentCount != 0 ? "calls" : layout.UsesTessellationData ? "tessellation" : program.Frontend is { RequiresOrderedImagePreparation: true } ? "frontend" : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.ShaderData) is not null ? "shader_data" - : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.FlattenedResourceTable) is not null ? "flattened_table" + : !ignoreFlattenedTable && layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.FlattenedResourceTable) is not null ? "flattened_table" : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.CallRecords) is not null || layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.CallMarks) is not null ? "call_records" : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.GlobalDataShare) is not null ? "gds" : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.DeviceAddressFallback) is not null ? "device_address_fallback" : null; - var replayable = reason is null; - if (!replayable) + } + + // StageInputMismatch's checks after the flattened table, for a stage whose table differs. + private static int StageInputMismatchAfterTable(in ShaderStageResources current, in ShaderStageResources kept) + { + var resources = current.Resources; + var keptResources = kept.Resources; + if (!ReferenceEquals(resources.DeviceAddressRanges, keptResources.DeviceAddressRanges) && + !resources.DeviceAddressRanges.AsSpan().SequenceEqual(keptResources.DeviceAddressRanges)) { - _unreplayablePrograms.AddOrUpdate(reason!, 1, static (_, count) => count + 1); + return 6; } - _replayablePrograms[program] = replayable; - return replayable; + if (resources.Heaps.Length != 0 || keptResources.Heaps.Length != 0) + { + return 7; + } + + return ReferenceEquals(resources.MipStatistics, keptResources.MipStatistics) || + (resources.MipStatistics ?? []).AsSpan().SequenceEqual(keptResources.MipStatistics ?? []) + ? -1 + : 8; } private static bool SameWordSets(uint[][] current, uint[][] kept) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs index 6e38b5742..a5385bb87 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs @@ -59,6 +59,11 @@ public class ShaderProgramInfo public bool UsesDeviceAddresses { get; init; } public bool DeviceAddressReadsBounded { get; init; } + // See ShaderResourcePlan.DeviceAddressReadsWindowed. + public bool DeviceAddressReadsWindowed { get; init; } + + public ulong DeviceAddressWindowBytes { get; init; } + // The dword every invocation stores when the whole program is 'index, v_mov constant, one // buffer store, end' (AGC's constant fill kernels); null for any other program. public uint? ConstantStoreValue { get; init; } diff --git a/src/SharpEmu.Libs/Gpu/Vulkan/GpuSyncProfile.cs b/src/SharpEmu.Libs/Gpu/Vulkan/GpuSyncProfile.cs index 28b6e523d..5ac044e05 100644 --- a/src/SharpEmu.Libs/Gpu/Vulkan/GpuSyncProfile.cs +++ b/src/SharpEmu.Libs/Gpu/Vulkan/GpuSyncProfile.cs @@ -50,7 +50,7 @@ private static string TakeChainReport() => FormattableString.Invariant($"deferred={Interlocked.Exchange(ref _deferredBarriers, 0)} skipped={Interlocked.Exchange(ref _skippedBarriers, 0)} transfer_kept={Interlocked.Exchange(ref _transferKeptDeferred, 0)} ") + FormattableString.Invariant($"promoted_handle={Interlocked.Exchange(ref _deferredPromotions[(int)DeferredBarrierPromotion.Handle], 0)} promoted_request={Interlocked.Exchange(ref _deferredPromotions[(int)DeferredBarrierPromotion.Request], 0)} ") + FormattableString.Invariant($"chain_open={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Open], 0)} chain_start={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Start], 0)} ") + - FormattableString.Invariant($"chain_skipped={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Skipped], 0)} chain_overlap={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Overlap], 0)} chain_conservative={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Conservative], 0)}"); + FormattableString.Invariant($"chain_skipped={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Skipped], 0)} chain_overlap={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Overlap], 0)} chain_conservative={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.Conservative], 0)} chain_same_program={Interlocked.Exchange(ref _chainDecisions[(int)Rendering.ChainDecision.SameProgramWrites], 0)}"); private static readonly long[] _nativeStateRecorded = new long[(int)NativeStateKind.Count]; private static readonly long[] _nativeStateReused = new long[(int)NativeStateKind.Count]; diff --git a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs index 7492e7006..580619281 100644 --- a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs @@ -106,7 +106,9 @@ public static int KernelUsleep(CpuContext ctx) if (micros > UsleepSpinLimitMicroseconds) { - micros = Audio.AudioOut2Exports.ProducerSleepMicroseconds(micros); + // The audio producer pacing may shorten the sleep; a sleep that was above the spin limit stays above it, so a nap + // just over the limit remains a timer wait instead of becoming a spin. + micros = Math.Max(Audio.AudioOut2Exports.ProducerSleepMicroseconds(micros), UsleepSpinLimitMicroseconds + 1); } while (micros > 0) diff --git a/src/SharpEmu.Libs/VideoOut/PendingStorePages.cs b/src/SharpEmu.Libs/VideoOut/PendingStorePages.cs new file mode 100644 index 000000000..101ddd36e --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/PendingStorePages.cs @@ -0,0 +1,127 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; + +namespace SharpEmu.Libs.VideoOut; + +// The pages the command stream's queued stores land on, for lock-free tests from any thread. The owner adds a store under its +// lock when it queues the store and removes it under the same lock after the store landed, so a test that starts after a store +// was queued (on the queueing thread, or after a hand-off through the queue) sees it. A store longer than LargePages pages is +// kept as one range instead of page by page, and a count per bucket of pages answers most page tests before the dictionary. +internal sealed class PendingStorePages +{ + public const int PageShift = 12; + public const int LargePages = 16; + private const int BucketShift = 52; + + private readonly ConcurrentDictionary _pages = new(); + private readonly int[] _buckets = new int[1 << (64 - BucketShift)]; + private readonly List<(ulong Address, ulong End)> _large = new(); + private volatile (ulong Address, ulong End)[] _largeSnapshot = []; + + public static bool IsLarge(ulong address, ulong length) => + length != 0 && ((address + length - 1) >> PageShift) - (address >> PageShift) >= LargePages; + + private static int Bucket(ulong page) => (int)((page * 0x9E3779B97F4A7C15UL) >> BucketShift); + + public bool HasLarge => _largeSnapshot.Length != 0; + + internal bool IsEmpty => _pages.IsEmpty && _largeSnapshot.Length == 0 && Array.TrueForAll(_buckets, static count => count == 0); + + // The owner, under its lock; a store is removed with the large flag it was added with. + public void Add(ulong address, ulong length, bool large) => Note(address, length, large, 1); + + public void Remove(ulong address, ulong length, bool large) => Note(address, length, large, -1); + + // The owner, under its lock: whether a store kept as a range overlaps the bytes. + public bool OverlapsLarge(ulong address, ulong end) + { + foreach (var range in _large) + { + if (range.Address < end && address < range.End) + { + return true; + } + } + + return false; + } + + private void Note(ulong address, ulong length, bool large, int delta) + { + if (large) + { + var range = (address, address + length); + if (delta > 0) + { + _large.Add(range); + } + else if (!_large.Remove(range)) + { + throw new InvalidOperationException("The command stream removed a queued store range it does not hold."); + } + + _largeSnapshot = _large.ToArray(); + return; + } + + var last = (address + length - 1) >> PageShift; + for (var page = address >> PageShift; page <= last; page++) + { + var bucket = Bucket(page); + if (delta > 0) + { + Volatile.Write(ref _buckets[bucket], _buckets[bucket] + 1); + _pages.AddOrUpdate(page, 1, static (_, count) => count + 1); + } + else + { + if (_pages.AddOrUpdate(page, -1, static (_, count) => count - 1) == 0) + { + _pages.TryRemove(new KeyValuePair(page, 0)); + } + + Volatile.Write(ref _buckets[bucket], _buckets[bucket] - 1); + } + } + } + + // Any thread: whether a queued store lands on a page of the range. A store kept as a range is compared by page as well, + // so the answer is the one a page index alone would give. + public bool Overlaps(ulong address, ulong size) => Overlaps(address, size, prefilter: true); + + internal bool Overlaps(ulong address, ulong size, bool prefilter) + { + if (size == 0) + { + return false; + } + + var first = address >> PageShift; + var last = (address + size - 1) >> PageShift; + for (var page = first; page <= last; page++) + { + if ((!prefilter || Volatile.Read(ref _buckets[Bucket(page)]) != 0) && _pages.ContainsKey(page)) + { + return true; + } + } + + var large = _largeSnapshot; + if (large.Length != 0) + { + var start = first << PageShift; + var end = (last + 1) << PageShift; + foreach (var range in large) + { + if (range.Address < end && start < range.End) + { + return true; + } + } + } + + return false; + } +} diff --git a/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs b/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs index 8ea582d72..a778714be 100644 --- a/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs +++ b/src/SharpEmu.Libs/VideoOut/RenderPhaseProfile.cs @@ -588,6 +588,7 @@ public static void RecordFrame() Console.Error.WriteLine(SharpEmu.Libs.Agc.AgcExports.TakeResolvePoolReport()); SharpEmu.Libs.Agc.DcbParseProfile.TryReport(); Console.Error.WriteLine(SharpEmu.Libs.Diagnostics.PacketHandlerTally.TakeReport()); + Console.Error.WriteLine(SharpEmu.Libs.Gpu.Pipelines.ComputeTickets.TakeReport()); Console.Error.WriteLine(SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeKeptProgramsReport()); Console.Error.WriteLine(SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeFastPathReport()); Console.Error.WriteLine(SharpEmu.Libs.Gpu.Pipelines.ShaderPipelineCache.TakeCpuKernelReport()); diff --git a/src/SharpEmu.Libs/VideoOut/StoreBufferPool.cs b/src/SharpEmu.Libs/VideoOut/StoreBufferPool.cs new file mode 100644 index 000000000..43e0a64eb --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/StoreBufferPool.cs @@ -0,0 +1,84 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +// Buffers for posted word copies of 64 KiB or more, in 64 KiB size classes, with at most 48 MiB idle. The command stream +// rents one before it peeks the copy's source; the queued store returns it once it lands on the render thread, or the +// command stream returns it when the copy is refused. A buffer is never handed out again before it comes back. +internal sealed class StoreBufferPool(long maxIdleBytes = StoreBufferPool.DefaultMaxIdleBytes) +{ + public const int ClassBytes = 64 * 1024; + public const long DefaultMaxIdleBytes = 48L * 1024 * 1024; + + public static readonly StoreBufferPool Shared = new(); + + public enum ReturnResult : byte + { + Kept, + Dropped, + NotLeased, + } + + private readonly object _gate = new(); + private readonly Dictionary> _idle = new(); + private readonly HashSet _leases = new(ReferenceEqualityComparer.Instance); + private long _idleBytes; + + public byte[] Rent(int length) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length); + var size = checked((length + ClassBytes - 1) / ClassBytes * ClassBytes); + lock (_gate) + { + if (_idle.TryGetValue(size, out var stack) && stack.TryPop(out var idle)) + { + _idleBytes -= idle.Length; + _leases.Add(idle); + return idle; + } + } + + var array = GC.AllocateUninitializedArray(size); + lock (_gate) + { + _leases.Add(array); + } + + return array; + } + + public ReturnResult Return(byte[] array) + { + lock (_gate) + { + if (!_leases.Remove(array)) + { + return ReturnResult.NotLeased; + } + + if (_idleBytes + array.Length > maxIdleBytes) + { + return ReturnResult.Dropped; + } + + if (!_idle.TryGetValue(array.Length, out var stack)) + { + stack = new Stack(); + _idle.Add(array.Length, stack); + } + + stack.Push(array); + _idleBytes += array.Length; + return ReturnResult.Kept; + } + } + + internal (int Leases, long IdleBytes) Stats() + { + lock (_gate) + { + return (_leases.Count, _idleBytes); + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs index 0a0f76e60..e3b48fab9 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs @@ -219,6 +219,11 @@ private sealed class ResolveWorkerState { public Presenter? Owner; public long Sequence; + // A compute ticket's worker: it resolves ahead of every stream position, and the take checks again only the reads it + // logged. + public bool Ticket; + // A deferred dispatch member's worker: a read it cannot serve and log refuses the member. + public bool Strict; public ResolveReadLog Reads = null!; public CleanReadPages? CleanReads; public ulong DirectPage = ulong.MaxValue; @@ -231,6 +236,20 @@ private sealed class ResolveWorkerState private bool OnResolveWorker => _resolveWorker is { Sequence: not 0 } worker && ReferenceEquals(worker.Owner, this); + // A read a compute ticket's worker cannot serve and log (unreadable, GPU-owned, pending, or served from a known GPU write) + // refuses the ticket. The take checks again only the logged reads, and the serial rebind there may serve the same read + // once the GPU work is done, so a ticket resolved without those bytes could differ from it. A deferred dispatch member + // refuses the same reads. + private bool RefuseOnTicketWorker(string reason) + { + if (OnResolveWorker && (_resolveWorker!.Ticket || _resolveWorker.Strict)) + { + throw new SerialResolveRequiredException("ticket read " + reason); + } + + return false; + } + int ICommandStreamHost.ResolveWorkerCount => ResolveWorkerCount; PendingCommandSignal ICommandStreamHost.CommandSignal => _relay.CommandSignal; @@ -245,12 +264,22 @@ void ICommandStreamHost.BeginWorkerResolve(long sequence, ResolveReadLog reads) } worker.Sequence = sequence; + worker.Ticket = sequence == long.MaxValue; + worker.Strict = false; worker.Reads = reads; worker.DirectPage = ulong.MaxValue; reads.Version = _bufferCache.GpuModifiedVersion; reads.Publications = _guestPublications.Ordinal; } + void ICommandStreamHost.BeginStrictWorkerResolve(long sequence, ResolveReadLog reads) + { + ((ICommandStreamHost)this).BeginWorkerResolve(sequence, reads); + _resolveWorker!.Strict = true; + } + + IDeferredDispatchRuns? ICommandStreamHost.DispatchRuns => _translation.DispatchRuns; + void ICommandStreamHost.EndWorkerResolve() { var worker = _resolveWorker!; @@ -304,6 +333,53 @@ bool ICommandStreamHost.ValidateWorkerReads(ResolveReadLog reads) return true; } + SharpEmu.Libs.Gpu.Pipelines.ComputeTickets? ICommandStreamHost.ComputeTickets => _translation.ComputeTicketPool; + + // A ticket was requested before the dispatches between its request and its take posted their writes, so a pending GPU + // write, publication, store or GPU-dirty byte over any range it read refuses it, and every range must read the same now. + bool ICommandStreamHost.ValidateTicketReads(ResolveReadLog reads) + { + Span current = stackalloc byte[256]; + var thread = _commandThread; + for (var index = 0; index < reads.Count; index++) + { + var bytes = reads.Bytes(index, out var address); + var size = (ulong)bytes.Length; + // A queued fill or copy over the range, or a store, may have been queued after the ticket read and not run + // yet, so raw guest memory still matches: a fill refuses the ticket, and stores are read through the overlay, + // the view the serial rebind reads. The lock-free MayHavePending filters the locked pending-write query. A clean + // read is checked again with the command thread's clean test, which also refuses a page a GPU write may own and an + // image's GPU-modified bytes: the serial rebind would see that read refused and could take another branch. + if (HasPendingMemoryPublication(address, size) || _bufferCache.HasGpuDirtyBytes(address, size) || + (reads.IsClean(index) && IsGpuOwnedForCleanRead(address, size)) || + (_translation.PendingWrites is { } pending && pending.MayHavePending(address, size) && + pending.HasPendingBetween(address, size, pending.Released, long.MaxValue)) || + (thread is not null && (thread.HasShadowBefore(address, size, long.MaxValue) || thread.HasPendingRange(address, size)))) + { + return false; + } + + var rented = bytes.Length > current.Length ? ArrayPool.Shared.Rent(bytes.Length) : null; + try + { + var now = rented is null ? current[..bytes.Length] : rented.AsSpan(0, bytes.Length); + var read = thread is not null && thread.HasPendingStores(address, size) + ? thread.ReadOverlay(address, now) + : _guestMemory.TryRead(address, now); + if (!read || !now.SequenceEqual(bytes)) + { + return false; + } + } + finally + { + if (rented is not null) ArrayPool.Shared.Return(rented); + } + } + + return true; + } + // A read for a draw resolving ahead of the stream: a range earlier GPU work may still write // sends the draw to the stream thread; everything else reads with the stores before it applied. private bool ReadOnResolveWorker(ulong address, Span destination) @@ -323,11 +399,12 @@ private bool ReadOnResolveWorker(ulong address, Span destination) if (!_guestMemory.CanRead(address, size)) { - return false; + return RefuseOnTicketWorker("unreadable"); } if (TryReadShadowForWorker(address, destination)) { + RefuseOnTicketWorker("shadow"); return true; } @@ -343,7 +420,7 @@ private bool ReadOnResolveWorker(ulong address, Span destination) if (!_commandThread!.ReadOverlayBefore(address, destination, worker.Sequence)) { - return false; + return RefuseOnTicketWorker("overlay"); } worker.Reads.Add(address, destination); @@ -401,7 +478,8 @@ private bool IsGpuOwnedForWorkerCleanRead(ulong address, ulong size) => private bool IsPendingForWorker(ulong address, ulong size) { var sequence = _resolveWorker!.Sequence; - return (_translation.PendingWrites is { } pending && pending.HasPendingBetween(address, size, pending.Released, sequence)) || + return (_translation.PendingWrites is { } pending && pending.MayHavePending(address, size) && + pending.HasPendingBetween(address, size, pending.Released, sequence)) || _commandThread!.HasShadowBefore(address, size, sequence); } @@ -475,6 +553,7 @@ private void RunDeferredWork(AgcExports.DeferredWork work) private void RunRelayBetweenCommandItems() { + _bufferCache.PumpEagerReadbacks(); if (_relay.HasPendingCommands) { using var relayScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.QueueRelay); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index e2172cd8b..0c0dbf3ca 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -19,11 +19,16 @@ internal static partial class VulkanVideoPresenter // queued; a callback that returns a result waits for the render thread to run everything before it. private sealed class CommandThread : AgcExports.IDeferredWorkSink { - // The thread runs this far ahead of the render thread at most. Operand reads only drain the - // queue when a queued write targets them, so the depth mostly costs memory; too shallow and the - // two threads take turns waiting on each other (128 did, with draws resolving on the pool). + // The thread runs this far ahead of the render thread at most: 4,096 items, or a larger configured depth, so it keeps + // interpreting while the render side records and joins slices. Operand reads only drain the queue when a queued write + // targets them, so the depth mostly costs memory; too shallow and the two threads take turns waiting on each other + // (128 did, with draws resolving on the pool). private static readonly int MaxOutstanding = - int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_COMMAND_QUEUE_DEPTH"), out var depth) && depth >= 128 ? depth : 1024; + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_COMMAND_QUEUE_DEPTH"), out var depth) && depth > 4096 ? depth : 4096; + + // A producer waiting for room resumes once the queue is an eighth below its cap rather than half empty, so it + // keeps overlapping the render side instead of waiting for it to drain. + private static readonly int ResumeBelow = MaxOutstanding - MaxOutstanding / 8; private static readonly int SlicesAheadPerWorker = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_SLICES_AHEAD"), out var ahead) && ahead >= 1 ? ahead : 2; @@ -56,7 +61,13 @@ internal sealed class Item public Action? Action; public ulong Address; public byte[]? Data; + // The store's length; a pooled Data can be longer. + public int Length; public bool Kernel; + // A store over more than PendingStorePages.LargePages pages, kept as one range in the page index. + public bool Large; + // Data came from StoreBufferPool.Shared and returns there once the store lands. + public bool Pooled; // The guest range a queued fill or copy writes; zero for other items. public ulong RangeSize; public RangeKind Range; @@ -122,7 +133,7 @@ private sealed class Unit // this thread see them over guest memory. private readonly object _writeLock = new(); private readonly Queue _pendingWrites = new(); - private readonly ConcurrentDictionary _pendingStorePages = new(); + private readonly PendingStorePages _storePages = new(); private readonly Dictionary> _storesByPage = new(); private readonly Stack> _spareStoreQueues = new(); private volatile int _pendingWriteCount; @@ -134,6 +145,34 @@ private sealed class Unit private readonly List _shadows = new(); private volatile Shadow[] _shadowSnapshot = []; + // The newest sequence and the address bounds of the snapshot, published with it: a shadow test returns at once + // when no shadow can match. + private volatile ShadowBounds _shadowBounds = ShadowBounds.Empty; + + private sealed record ShadowBounds(long Newest, ulong Low, ulong High) + { + public static readonly ShadowBounds Empty = new(long.MinValue, ulong.MaxValue, 0); + } + + private static ShadowBounds BoundsOf(List shadows) + { + if (shadows.Count == 0) + { + return ShadowBounds.Empty; + } + + var newest = long.MinValue; + var low = ulong.MaxValue; + var high = 0UL; + foreach (var shadow in shadows) + { + newest = Math.Max(newest, shadow.Sequence); + low = Math.Min(low, shadow.Address); + high = Math.Max(high, shadow.Address + (ulong)shadow.Length); + } + + return new ShadowBounds(newest, low, high); + } private volatile Item[] _pendingRangeSnapshot = []; private long _shadowGeneration; @@ -162,29 +201,28 @@ public CommandThread(Presenter presenter, CommandStreamQueue queue, ICpuMemory m public long ShadowGeneration => Volatile.Read(ref _shadowGeneration); // Whether a queued store of the stream lands on a page of the range. - public bool HasPendingStores(ulong address, ulong size) + public bool HasPendingStores(ulong address, ulong size) => _pendingWriteCount != 0 && _storePages.Overlaps(address, size); + + // A large store has no page queues: a single-page overlay read it overlaps scans the ordered store queue instead. + private void NotePendingStorePages(Item item, int delta) { - if (_pendingWriteCount == 0) + var address = item.Address; + var length = (ulong)item.Length; + if (delta > 0) { - return false; + _storePages.Add(address, length, item.Large); } - - var last = (address + size - 1) >> StorePageShift; - for (var page = address >> StorePageShift; page <= last; page++) + else { - if (_pendingStorePages.ContainsKey(page)) - { - return true; - } + _storePages.Remove(address, length, item.Large); } - return false; - } + if (item.Large) + { + return; + } - private void NotePendingStorePages(Item item, int delta) - { - var address = item.Address; - var last = (address + (ulong)item.Data!.Length - 1) >> StorePageShift; + var last = (address + length - 1) >> StorePageShift; for (var page = address >> StorePageShift; page <= last; page++) { if (delta > 0) @@ -213,11 +251,6 @@ private void NotePendingStorePages(Item item, int delta) } } } - - if (_pendingStorePages.AddOrUpdate(page, delta, (_, count) => count + delta) == 0) - { - _pendingStorePages.TryRemove(new KeyValuePair(page, 0)); - } } } @@ -274,9 +307,18 @@ public T Run(Func function, [CallerMemberName] string caller = "") public void PostWrite(ulong address, ReadOnlySpan data, bool kernel = false) => PostOwnedWrite(address, data.ToArray(), kernel); - public void PostOwnedWrite(ulong address, byte[] data, bool kernel) + public void PostOwnedWrite(ulong address, byte[] data, bool kernel) => PostStore(address, data, data.Length, kernel, pooled: false); + + // The first length bytes of a buffer rented from StoreBufferPool.Shared, which takes it back once the store lands. + public void PostPooledWrite(ulong address, byte[] data, int length, bool kernel) => PostStore(address, data, length, kernel, pooled: true); + + private void PostStore(ulong address, byte[] data, int length, bool kernel, bool pooled) { - var item = new Item { Kind = Kind.Write, Address = address, Data = data, Kernel = kernel }; + var item = new Item + { + Kind = Kind.Write, Address = address, Data = data, Length = length, Kernel = kernel, Pooled = pooled, + Large = PendingStorePages.IsLarge(address, (ulong)length), + }; lock (_writeLock) { _pendingWrites.Enqueue(item); @@ -382,6 +424,7 @@ public void NoteKnownWrite(KnownGpuWrite known, long sequence, ShadowSource sour _shadows.Add(new Shadow { Address = known.Address, Length = known.ByteCount, Sequence = sequence, Known = known, Source = source }); _shadowSnapshot = _shadows.ToArray(); + _shadowBounds = BoundsOf(_shadows); } Interlocked.Increment(ref _shadowGeneration); @@ -404,6 +447,7 @@ private void SweepShadows() _shadows.RemoveRange(kept, _shadows.Count - kept); _shadowSnapshot = _shadows.ToArray(); + _shadowBounds = BoundsOf(_shadows); } public bool HasShadow(ulong address, ulong size) => HasShadowBefore(address, size, long.MaxValue); @@ -413,6 +457,12 @@ public bool HasShadowBefore(ulong address, ulong size, long sequence) { var executed = Volatile.Read(ref _executed); var end = address + size; + var bounds = _shadowBounds; + if (bounds.Newest <= executed || end <= bounds.Low || bounds.High <= address) + { + return false; + } + foreach (var shadow in _shadowSnapshot) { if (shadow.Sequence > executed && shadow.Sequence < sequence && address < shadow.Address + (ulong)shadow.Length && shadow.Address < end) @@ -488,6 +538,13 @@ public bool ReadOverlay(ulong address, Span destination) } } + // Tests: ReadOverlay into a new array. + internal byte[] ReadOverlayForTest(ulong address, int length) + { + var bytes = new byte[length]; + return ReadOverlay(address, bytes) ? bytes : throw new InvalidOperationException("The overlay read failed."); + } + // Guest memory as a draw at this stream position sees it: the queued stores before it applied, // none of the later ones. A queued fill or copy before it into the range cannot be read ahead. public bool ReadOverlayBefore(ulong address, Span destination, long sequence) @@ -536,7 +593,7 @@ private void ApplyPendingStoresLocked(ulong address, Span destination, lon { var end = address + (ulong)destination.Length; var page = address >> StorePageShift; - if (page == (end - 1) >> StorePageShift) + if (page == (end - 1) >> StorePageShift && (!_storePages.HasLarge || !_storePages.OverlapsLarge(address, end))) { if (_storesByPage.TryGetValue(page, out var queued)) { @@ -557,7 +614,7 @@ private void ApplyPendingStoresLocked(ulong address, Span destination, lon private static void ApplyPendingStore(Item write, ulong address, ulong end, Span destination, long afterSequence, long beforeSequence) { - var writeEnd = write.Address + (ulong)write.Data!.Length; + var writeEnd = write.Address + (ulong)write.Length; if (write.Sequence <= afterSequence || write.Address >= end || writeEnd <= address || (beforeSequence != long.MaxValue && (write.Sequence == 0 || write.Sequence >= beforeSequence))) { @@ -635,7 +692,7 @@ private void WaitForSpaceCore() { _waitingForSpace = true; Interlocked.MemoryBarrier(); - if (Volatile.Read(ref _outstanding) < MaxOutstanding / 2 || _failure is not null) + if (Volatile.Read(ref _outstanding) < ResumeBelow || _failure is not null) { break; } @@ -739,7 +796,7 @@ public int RunBatch(long deadline, int maxItems, Action betweenItems) var ran = 0; for (;;) { - FillUnits(maxItems); + FillUnits(); if (_unitHead == _units.Count) { _units.Clear(); @@ -787,7 +844,9 @@ public int RunBatch(long deadline, int maxItems, Action betweenItems) } } - private void FillUnits(int maxItems) + // A fill cuts slices up to the look-ahead limit rather than a fixed number of items, so the render workers keep + // recording while the render thread joins and the command thread runs ahead. + private void FillUnits() { var slicing = _presenter.SlicesEnabled; var slicesAhead = 0; @@ -800,8 +859,7 @@ private void FillUnits(int maxItems) } var limit = slicing ? SlicesAheadPerWorker * _presenter.WorkerCount : 0; - var pulled = 0; - while (slicesAhead <= limit && pulled < maxItems) + while (slicesAhead <= limit) { if (_drainIndex == _draining.Count && !RefillDraining()) { @@ -810,7 +868,6 @@ private void FillUnits(int maxItems) var item = _draining[_drainIndex]; _draining[_drainIndex++] = null!; - pulled++; if (slicing && item.Kind == Kind.Deferred) { (_cutting ??= new RenderSlice()).Items.Add(item); @@ -1025,7 +1082,7 @@ private void CompleteItem(Item item) var outstanding = Interlocked.Decrement(ref _outstanding); // One pulse per wait: the producer sets its flag again if it keeps waiting. var wakeForSync = item.Sync && _waitingForSync; - var wakeForSpace = _waitingForSpace && outstanding < MaxOutstanding / 2; + var wakeForSpace = _waitingForSpace && outstanding < ResumeBelow; var wakeForSequence = item.Sequence >= Volatile.Read(ref _waitingForSequence); if (wakeForSync || wakeForSpace || wakeForSequence) { @@ -1111,7 +1168,8 @@ private void ApplyWrite(Item item) { lock (_writeLock) { - var written = (item.Kernel && _presenter.TryApplyKernelWriteOverGpuBytes(item.Address, item.Data!)) || _memory.TryWrite(item.Address, item.Data); + var data = item.Data.AsSpan(0, item.Length); + var written = (item.Kernel && _presenter.TryApplyKernelWriteOverGpuBytes(item.Address, data)) || _memory.TryWrite(item.Address, data); if (!ReferenceEquals(_pendingWrites.Peek(), item)) { throw SubmissionScheduler.Fatal("The command stream stores ran out of order."); @@ -1123,7 +1181,14 @@ private void ApplyWrite(Item item) if (!written) { throw SubmissionScheduler.Fatal( - $"The command stream cannot write guest memory: address=0x{item.Address:X16} size={item.Data!.Length}."); + $"The command stream cannot write guest memory: address=0x{item.Address:X16} size={item.Length}."); + } + + // No reader reaches the store once it left the queue and the index under this lock. + if (item.Pooled) + { + StoreBufferPool.Shared.Return(item.Data!); + item.Data = null; } } } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index 4451f3a64..b0a2286f4 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -1371,6 +1371,7 @@ public void PrepareDeviceAddresses() GuestGpuMemoryHook.Trace(traceAddress, 1, $"device-address-mapping-check readable={_guestMemory.CanRead(traceAddress, 1)} backed={_guestBacking.IsBackedView(traceAddress)}"); var bounded = BoundedDeviceAddressReads && ReadsOnlyBoundedRanges(preparation); + var windowed = !bounded && ReadsOnlyWindowedRanges(preparation) && CollectWindows(preparation, _bdaWindows); if (_worker) { if (bounded) @@ -1380,6 +1381,14 @@ public void PrepareDeviceAddresses() else { Requests.NeedsBdaSweep = true; + if (windowed) + { + Requests.BdaWindows.AddRange(_bdaWindows); + } + else + { + Requests.BdaFullSweep = true; + } } Requests.BdaSpans = spans; @@ -1402,9 +1411,85 @@ public void PrepareDeviceAddresses() return; } + if (windowed) + { + GuestBufferCache.ClipSpansToWindows(spans, _bdaWindows, _bdaWindowSpans); + _bufferCache.PrepareWindowedBda(_bdaWindowSpans, GuestBufferCache.MappingKey(_bdaWindowSpans), _bdaSpanMapping); + return; + } + _bufferCache.PrepareBda(spans, _bdaSpanMapping); } + // Every device-address stage is bounded, with ranges that pass the bounded checks, or windowed, with planned read-only + // ranges, and at least one is windowed. + private bool ReadsOnlyWindowedRanges(RenderPreparation preparation) + { + var any = false; + foreach (var stage in preparation.Stages) + { + if (!stage.Program.UsesDeviceAddresses) + { + continue; + } + + var windowedStage = stage.Program.DeviceAddressReadsWindowed; + if (!windowedStage && !stage.Program.DeviceAddressReadsBounded) + { + return false; + } + + foreach (var range in DeviceAddressRangesOf(stage)) + { + if (!range.Planned || range.Written || (!windowedStage && range.Size > ShaderCompiler.Resources.DeviceAddressRangePlanner.MaxRangeBytes)) + { + return false; + } + } + + any |= windowedStage; + } + + return any; + } + + // The windows of the windowed stages' ranges that are not bounded exactly (an unbounded range evaluates to MaxRangeBytes): + // from each range base for the program's window bytes. False when one would wrap the 48-bit device address space. + private const ulong DeviceAddressSpaceEnd = 1UL << 48; + private readonly List<(ulong Start, ulong End)> _bdaWindows = []; + private readonly List _bdaWindowSpans = []; + + private bool CollectWindows(RenderPreparation preparation, List<(ulong Start, ulong End)> windows) + { + windows.Clear(); + foreach (var stage in preparation.Stages) + { + if (!stage.Program.UsesDeviceAddresses || !stage.Program.DeviceAddressReadsWindowed) + { + continue; + } + + var bytes = stage.Program.DeviceAddressWindowBytes; + foreach (var range in DeviceAddressRangesOf(stage)) + { + if (range.Size < ShaderCompiler.Resources.DeviceAddressRangePlanner.MaxRangeBytes) + { + continue; + } + + if (bytes == 0 || range.Base >= DeviceAddressSpaceEnd || DeviceAddressSpaceEnd - range.Base < bytes) + { + windows.Clear(); + return false; + } + + windows.Add((range.Base, range.Base + bytes)); + } + } + + return true; + } + private static readonly bool BoundedDeviceAddressReads = Environment.GetEnvironmentVariable("SHARPEMU_BOUNDED_BDA") != "0"; private bool ReadsOnlyBoundedRanges(RenderPreparation preparation) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs index f8413240b..3faa94f58 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs @@ -191,6 +191,9 @@ bool IRenderHost.TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan ve private readonly record struct HeldStorage(ulong Address, ulong Size, BufferResource Resource, GpuBuffer Buffer, ulong Offset); + // The open preparation bound a stream copy: a read-only range copied into the slice arena as it stood at this item. + private bool _preparationStreamCopied; + private readonly List _stageStorage = new(); private bool _holdingStorage; private HeldStorage[] _dispatchStorage = new HeldStorage[16]; @@ -210,7 +213,8 @@ bool IRenderHost.TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan ve private DrawScopeToken _dispatchScope; private long _dispatchOwners; private static readonly string[] DispatchHostMissNames = - ["unsealed", "recording", "generation", "epoch", "segment", "scope", "owners", "layout", "patch", "written", "dirty", "texel"]; + ["unsealed", "recording", "generation", "epoch", "segment", "scope", "owners", "layout", "patch", "written", "dirty", "texel", + "table_set", "table_layout", "table_shadow"]; private static readonly long[] _dispatchHostMisses = new long[DispatchHostMissNames.Length]; internal static string TakeDispatchHostMisses() @@ -281,6 +285,12 @@ private void CaptureDispatchReplay(PipelineBindPoint bindPoint, RenderPipelineEn _dispatchStorage[index] = held; } + // A replay keeps the sealed descriptors, so a later item would read this item's stream copy. + if (_preparationStreamCopied) + { + return; + } + _dispatchStorageCount = _stageStorage.Count; new ReadOnlySpan(pushData, (int)PushData.DwordCount).CopyTo(_dispatchPushData); _dispatchHasPush = hasPushData; @@ -309,7 +319,7 @@ void IRenderHost.SealDispatchReplay() _dispatchSealed = true; } - bool IRenderHost.TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage) + bool IRenderHost.TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage, bool replaceTable) { if (!_dispatchSealed) { @@ -382,23 +392,61 @@ bool IRenderHost.TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageRes } } - if (!_dispatchHasPush) + // Only a pushed set can take one binding again. When the native state is shadowed, the shadow must still hold the + // sealed set, so the new descriptor can replace its entry there. + var tableBinding = 0u; + var tableEntry = -1; + DescriptorShadow? tableShadow = null; + if (replaceTable) { - return true; + if (!entry.UsesPushDescriptors) + { + return DispatchHostMiss(12); + } + + if (stage.Program is not { } tableProgram || _dispatchStageLayout?.Find(DescriptorBindingKind.FlattenedResourceTable) is not { } table || + DescriptorWriter.DescriptorCount(table) != 1) + { + return DispatchHostMiss(13); + } + + tableBinding = BindingLayout.NativeBindingIndex(StageOf(tableProgram), DescriptorBindingKind.FlattenedResourceTable); + if (SyncNativeShadow(BeginBatchedGuestStateCommands())) + { + tableShadow = _computeDescriptorShadow; + if (tableShadow is not { Valid: true } || tableShadow.Layout.Handle != _dispatchLayout.Handle || + (tableEntry = FindShadowBufferEntry(tableShadow, tableBinding)) < 0) + { + return DispatchHostMiss(14); + } + } } var push = stackalloc uint[(int)PushData.DwordCount]; var data = new Span(push, (int)PushData.DwordCount); - _dispatchPushData.CopyTo(data); - var layout = _dispatchStageLayout; - if (!PatchReplayUserData(data, layout, _dispatchUserDataBase, stage.Resources.UserData)) + if (_dispatchHasPush) + { + _dispatchPushData.CopyTo(data); + var layout = _dispatchStageLayout; + if (!PatchReplayUserData(data, layout, _dispatchUserDataBase, stage.Resources.UserData)) + { + return DispatchHostMiss(8); + } + + if (layout is { UsesPushData: true, UsesDispatchThreadLimits: true } && !stage.GpuThreadLimits) + { + stage.WriteDispatchThreadLimits(data.Slice((int)layout.PushDataStartDword, (int)layout.ShaderDataDwordCount)); + } + } + + if (replaceTable) { - return DispatchHostMiss(8); + PushTableBinding(in stage, tableBinding, tableShadow, tableEntry); } - if (layout is { UsesPushData: true, UsesDispatchThreadLimits: true } && !stage.GpuThreadLimits) + if (!_dispatchHasPush) { - stage.WriteDispatchThreadLimits(data.Slice((int)layout.PushDataStartDword, (int)layout.ShaderDataDwordCount)); + return true; } data.CopyTo(_dispatchPushData); @@ -406,6 +454,56 @@ bool IRenderHost.TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageRes return true; } + // Uploads the table as the full path does and pushes only its descriptor; the other pushed descriptors of the sealed + // dispatch stay bound. The shadow's entry takes the new descriptor, so the next full commit compares against it. + private void PushTableBinding(in ShaderStageResources stage, uint binding, DescriptorShadow? shadow, int entry) + { + var view = UploadDwords(stage.Resources.FlattenedResourceTable, "flattened resource table", stage.Program!, byIdentity: true); + var info = new DescriptorBufferInfo { Buffer = view.Buffer, Offset = view.Offset, Range = view.Range }; + var write = new WriteDescriptorSet + { + SType = StructureType.WriteDescriptorSet, + DstBinding = binding, + DescriptorType = DescriptorWriter.DescriptorType(DescriptorBindingKind.FlattenedResourceTable), + DescriptorCount = 1, + PBufferInfo = &info, + }; + var command = BeginBatchedGuestStateCommands(); + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _presenter._pushDescriptorApi.CmdPushDescriptorSet(command, PipelineBindPoint.Compute, _dispatchLayout, 0, 1, &write); + } + + if (shadow is not null && entry >= 0) + { + shadow.Key[entry] = info.Buffer.Handle; + shadow.Key[entry + 1] = info.Offset; + shadow.Key[entry + 2] = info.Range; + } + } + + // The key index of a binding's one buffer descriptor in a shadow (DescriptorKey's layout), or -1. + private static int FindShadowBufferEntry(DescriptorShadow shadow, uint binding) + { + var key = shadow.Key; + var index = 0; + while (index + 2 <= shadow.Length) + { + var flags = key[index + 1]; + var count = (int)(uint)flags; + var hasBuffer = (flags & (1UL << 32)) != 0; + var described = hasBuffer || (flags & (1UL << 33)) != 0; + if ((uint)key[index] == binding) + { + return hasBuffer && count == 1 && index + 5 <= shadow.Length ? index + 2 : -1; + } + + index += 2 + (described ? count * 3 : 0); + } + + return -1; + } + private static bool PatchReplayUserData(Span push, BindingLayout? layout, uint userDataBase, ReadOnlySpan userData) { if (layout is not { UsesPushData: true }) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs index 3602b4ca4..313df3cf1 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs @@ -61,9 +61,17 @@ private KernelWriteRefusal PostWordCopy(ulong destination, ulong source, ulong s return refusal; } - var data = GC.AllocateUninitializedArray((int)size); + // A copy of 64 KiB or more uses a pooled buffer, returned when its store lands or here when the copy is refused. + var length = (int)size; + var pooled = length >= StoreBufferPool.ClassBytes; + var data = pooled ? StoreBufferPool.Shared.Rent(length) : GC.AllocateUninitializedArray(length); if (!TryPeekResidentGuestBytes(source, data.AsSpan(0, (int)sourceSize))) { + if (pooled) + { + StoreBufferPool.Shared.Return(data); + } + if (RenderPhaseProfile.Enabled) { ShaderPipelineCache.NoteWordCopyInput( @@ -78,19 +86,26 @@ private KernelWriteRefusal PostWordCopy(ulong destination, ulong source, ulong s return KernelWriteRefusal.Input; } - for (var filled = (int)sourceSize; filled < data.Length;) + for (var filled = (int)sourceSize; filled < length;) { - var count = Math.Min(filled, data.Length - filled); + var count = Math.Min(filled, length - filled); data.AsSpan(0, count).CopyTo(data.AsSpan(filled)); filled += count; } - _commandThread!.PostOwnedWrite(destination, data, kernel: true); + if (pooled) + { + _commandThread!.PostPooledWrite(destination, data, length, kernel: true); + } + else + { + _commandThread!.PostOwnedWrite(destination, data, kernel: true); + } return KernelWriteRefusal.None; } // On the render thread at the store's stream position: a store into GPU-dirty pages lands on both copies. - internal bool TryApplyKernelWriteOverGpuBytes(ulong address, byte[] data) + internal bool TryApplyKernelWriteOverGpuBytes(ulong address, ReadOnlySpan data) { var size = (ulong)data.Length; if (!_bufferCache.MayHaveGpuDirtyPages(address, size) || !_bufferCache.HasGpuDirtyPages(address, size) || diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs index 948e7b14f..4e28ad06d 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs @@ -290,23 +290,28 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) CompletePendingPublicationsForResourceRead(address, sizeof(uint)); if (!_guestMemory.CanRead(address, sizeof(uint))) { - return false; + return RefuseOnTicketWorker("unreadable"); } if (OnResolveWorker) { - if (IsGpuOwnedForWorkerCleanRead(address, sizeof(uint)) || IsPendingForWorker(address, sizeof(uint))) + if (IsGpuOwnedForWorkerCleanRead(address, sizeof(uint))) { - return false; + return RefuseOnTicketWorker("gpu owned"); + } + + if (IsPendingForWorker(address, sizeof(uint))) + { + return RefuseOnTicketWorker("pending"); } Span cleanBytes = stackalloc byte[sizeof(uint)]; if (!_commandThread!.ReadOverlayBefore(address, cleanBytes, _resolveWorker!.Sequence)) { - return false; + return RefuseOnTicketWorker("overlay"); } - _resolveWorker.Reads.Add(address, cleanBytes); + _resolveWorker.Reads.Add(address, cleanBytes, clean: true); word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(cleanBytes); return true; } @@ -387,7 +392,7 @@ private bool ReadResidentBytesOnResolveWorker(ulong address, Span destinat if (!_guestMemory.CanRead(address, size)) { - return false; + return RefuseOnTicketWorker("unreadable"); } if (!clean && _commandThread!.TryReadShadowBefore(address, destination, worker.Sequence, out var shadowSequence, out var shadowSource)) @@ -395,24 +400,30 @@ private bool ReadResidentBytesOnResolveWorker(ulong address, Span destinat if ((_translation.PendingWrites is { } pending && pending.HasPendingBetween(address, size, shadowSequence, worker.Sequence)) || _commandThread.HasPendingRangeBetween(address, size, shadowSequence, worker.Sequence)) { - return false; + return RefuseOnTicketWorker("shadowed pending"); } + RefuseOnTicketWorker("shadow"); SharpEmu.Libs.Agc.AgcExports.NoteWorkerShadowRead((int)shadowSource); return true; } - if ((clean ? IsGpuOwnedForWorkerCleanRead(address, size) : IsGpuOwnedForWorkerRead(address, size)) || IsPendingForWorker(address, size)) + if (clean ? IsGpuOwnedForWorkerCleanRead(address, size) : IsGpuOwnedForWorkerRead(address, size)) { - return false; + return RefuseOnTicketWorker("gpu owned"); + } + + if (IsPendingForWorker(address, size)) + { + return RefuseOnTicketWorker("pending"); } if (!_commandThread!.ReadOverlayBefore(address, destination, worker.Sequence)) { - return false; + return RefuseOnTicketWorker("overlay"); } - worker.Reads.Add(address, destination); + worker.Reads.Add(address, destination, clean); if (!clean) { NoteCleanReadPage(address, size); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs index aa4fc6429..cc552d939 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs @@ -289,11 +289,6 @@ public void RunPendingOperations() } _presenter.RunPendingCommands(); - if (_presenter._batchOpen && _preparation is null && _bufferCache?.HotWritePending == true && _presenter._batchDrawCount >= Presenter.MinimumFlushDraws) - { - EndRendering(); - FlushBatchedGuestCommands(); - } } public void SetDebugInformation(RecordedOperation operation, ulong submitId, uint argument0, uint argument1, uint argument2, uint argument3, ulong argument4) => @@ -634,6 +629,7 @@ public IResourcePreparation BeginPreparation() throw SubmissionScheduler.Fatal("A resource preparation is already open."); } + _preparationStreamCopied = false; if (_worker) { _preparation = (_sparePreparation ??= new RenderPreparation(this)).Open(null); @@ -1185,6 +1181,11 @@ internal static ColorComponentFlags ToVkColorWriteMask(uint mask) public void BeginRendering(in RenderingState state) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawRenderingSetup); + if (_worker && _segment is { Requests.DepthClears.Count: > 0 } segment) + { + NoteDepthClearArea(segment.Requests, in state); + } + if (_renderingActive && _renderingState == state) { _renderingWritesMemory |= _nextDrawWritesMemory; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index a0429dacf..0ee8865dd 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -283,6 +283,11 @@ private static bool SameBytes(in T left, in T right) where T : unmanaged => public long? ReadsVersion; public bool MixedReadsVersions; public readonly List<(ResourceSlotIdentifier Image, ImageRequest Request)> NativeColorUses = new(); + // Native color clears the worker passed because only their registration was not current; the join applies them. + public readonly List<(ResourceSlotIdentifier Image, ImageRequest Request)> NativeColorEntries = new(); + // One clear entry per depth view with HTILE first acquired in the segment, and their keys for the join's image check. + public readonly List DepthClears = new(); + public readonly List<(ResourceSlotIdentifier Image, ImageViewDescription View)> DepthClearKeys = new(); public bool WritesRange(GuestSpan range) { @@ -322,6 +327,28 @@ public bool WritesImageRange(GuestSpan range) public long MetadataGeneration; public IReadOnlyList? BdaSpans; public ulong BdaMapping; + // The windows of the segment's windowed device-address programs; one program that is not windowed sweeps every + // mapped span. + public readonly List<(ulong Start, ulong End)> BdaWindows = new(); + public bool BdaFullSweep; + } + + // A depth view with HTILE that a render worker acquired in a segment, and what the render thread's first acquisition of + // it would clear when its base layer's HTILE slice is clear at the join: the area of the segment's first rendering with + // the view, with the draw's clear value. + private sealed class SliceDepthClear + { + public ResourceSlotIdentifier Image; + public CachedImage Expected = null!; + public ImageViewDescription View; + public ImageView NativeView; + public ulong Htile; + public uint BaseLayer; + public uint ClearWord; + public bool HasArea; + public uint Width; + public uint Height; + public uint Layers; } // Items recorded into one command buffer; the item after them, if any, needs the render thread. @@ -713,7 +740,8 @@ private bool ValidateSegment(RenderSlice slice, SliceSegment segment) } var started = System.Diagnostics.Stopwatch.GetTimestamp(); - var valid = _imageCache.ValidateSliceImages(requests.Images, requests.LookupGeneration, requests.MetadataGeneration); + var valid = _imageCache.ValidateSliceImages(requests.Images, requests.LookupGeneration, requests.MetadataGeneration, + requests.DepthClearKeys.Count != 0 ? requests.DepthClearKeys : null); var imagesDone = System.Diagnostics.Stopwatch.GetTimestamp(); _validateImageTicks.Add(imagesDone - started); if (!valid) @@ -757,9 +785,71 @@ private bool ValidateSegment(RenderSlice slice, SliceSegment segment) } _validateDeferredTicks.Add(System.Diagnostics.Stopwatch.GetTimestamp() - buffersDone); + if (valid && requests.DepthClears.Count != 0 && !DepthClearsAppliable(requests)) + { + return false; + } + + // Last, so nothing refuses the segment after its entries are applied. + if (valid && requests.NativeColorEntries.Count != 0 && !ApplyNativeColorEntries(requests)) + { + return false; + } + return valid; } + // The native color clears the segment's worker passed with only their registration out of date. The segment is + // refused when one would now record a clear or its metadata is GPU-dirty; otherwise each serial apply runs in stream + // order, updating the registration without recording anything. + private bool ApplyNativeColorEntries(SliceRequests requests) + { + foreach (var (image, request) in requests.NativeColorEntries) + { + var range = request.Description.Metadata.Range; + if (_bufferCache.HasGpuDirtyBytes(range.Address, range.Size) || + _imageCache.PredictNativeColorClear(image, request) is NativeColorClearPrediction.ClearCode or NativeColorClearPrediction.BadView) + { + return false; + } + } + + foreach (var (image, request) in requests.NativeColorEntries) + { + _imageCache.ApplyNativeColorClear(image, request); + } + + return true; + } + + // A clear the join records ahead of the segment needs the area of its view's first rendering, and no other use of its + // image in the segment: a sampled use there would see the clear before its turn. + private bool DepthClearsAppliable(SliceRequests requests) + { + foreach (var entry in requests.DepthClears) + { + if (!_imageCache.IsMetadataCleared(entry.Htile, entry.BaseLayer)) + { + continue; + } + + if (!entry.HasArea) + { + return false; + } + + foreach (var use in requests.Images) + { + if (use.Image == entry.Image && use.Request.Role != ImageRole.DepthTarget) + { + return false; + } + } + } + + return true; + } + private bool ValidateDeferredItems(RenderSlice slice, SliceSegment segment) { var end = segment.First + segment.Count; @@ -817,6 +907,8 @@ private void RetireSliceDescriptorPools(RenderSlice slice) } } + private readonly List _prologueWindowSpans = []; + private void RecordSlicePrologue(SliceRequests requests) { Recording.EndRendering(); @@ -839,7 +931,15 @@ private void RecordSlicePrologue(SliceRequests requests) mapping = Recording.DeviceAddressSpanMapping; } - _bufferCache.PrepareBda(spans, mapping); + if (!requests.BdaFullSweep && requests.BdaWindows.Count != 0) + { + GuestBufferCache.ClipSpansToWindows(spans, requests.BdaWindows, _prologueWindowSpans); + _bufferCache.PrepareWindowedBda(_prologueWindowSpans, GuestBufferCache.MappingKey(_prologueWindowSpans), mapping); + } + else + { + _bufferCache.PrepareBda(spans, mapping); + } } else if (requests.NeedsBdaTouch && requests.BdaSpans is { } touched) { @@ -873,6 +973,12 @@ private void RecordSlicePrologue(SliceRequests requests) _imageCache.ApplySliceUse(use.Image, in request); } + // After the image uses, so a refresh from guest memory comes before the clear, as before a load-op clear. + if (requests.DepthClears.Count != 0) + { + Recording.ApplySliceDepthClears(requests.DepthClears); + } + foreach (var (address, words) in requests.KnownWrites) { _bufferCache.NoteKnownGpuContents(address, words); @@ -923,6 +1029,7 @@ internal void RecordSlice(RenderSlice slice) for (var index = 0; index < slice.Items.Count; index++) { var started = System.Diagnostics.Stopwatch.GetTimestamp(); + var depthClearMark = -1; try { if (!_presenter._translation.CanRecordDeferred(slice.Items[index].Work!)) @@ -945,6 +1052,7 @@ internal void RecordSlice(RenderSlice slice) } segment ??= BeginSegment(index); + depthClearMark = segment.Requests.DepthClears.Count; _itemSequence = slice.Items[index].Sequence; if (slice.Items[index].Work is SharpEmu.Libs.Agc.AgcExports.GlobalBarrierWork) { @@ -960,6 +1068,14 @@ internal void RecordSlice(RenderSlice slice) } catch (SerialRequiredException serial) { + // The item runs on the render thread, so the clear entries it made leave the segment. + if (depthClearMark >= 0 && segment!.Requests.DepthClears.Count > depthClearMark) + { + var dropped = segment.Requests.DepthClears.Count - depthClearMark; + segment.Requests.DepthClears.RemoveRange(depthClearMark, dropped); + segment.Requests.DepthClearKeys.RemoveRange(depthClearMark, dropped); + } + segment!.SerialReason = serial.Message; Interlocked.Increment(ref _serialReasons.GetOrAdd(serial.Message, static _ => new StrongBox()).Value); EndSegment(slice, segment); @@ -1010,16 +1126,26 @@ private void RecordGuestCacheFlush() private static void NoteReadsVersion(SliceRequests requests, SharpEmu.Libs.Agc.AgcExports.DeferredWork work) { - if (work is not SharpEmu.Libs.Agc.AgcExports.DeferredDraw draw) + long readsVersion; + if (work is SharpEmu.Libs.Agc.AgcExports.DeferredDraw draw) + { + readsVersion = draw.Reads.Version; + } + else if (work is SharpEmu.Libs.Agc.AgcExports.DeferredDispatch { Cancelled: false } dispatch) + { + // A deferred dispatch member's reads join the segment's check like a deferred draw's. + readsVersion = dispatch.Reads.Version; + } + else { return; } if (requests.ReadsVersion is not { } version) { - requests.ReadsVersion = draw.Reads.Version; + requests.ReadsVersion = readsVersion; } - else if (version != draw.Reads.Version) + else if (version != readsVersion) { requests.MixedReadsVersions = true; } @@ -1173,6 +1299,7 @@ private ResourceSlotIdentifier FindBuffer(ulong address, ulong size) { _arena.Commit(in reservation); _streamCopies.Increment(); + _preparationStreamCopied = true; return (reservation.Chunk.Buffer, reservation.Offset, (size + 3) & ~3UL); } } @@ -1223,12 +1350,19 @@ private void ApplyNativeColorClear(ResourceSlotIdentifier imageIdentifier, in Im } else if (request.Description.Metadata.NativeColorClear) { - if (!_imageCache.NativeColorClearSettled(imageIdentifier, request)) + // A clear whose only change would be its registration passes: no slice holds a clear code, so the serial + // apply records nothing, and the join runs it in stream order. Its use is not part of the join's settled check. + switch (_imageCache.PredictNativeColorClear(imageIdentifier, request)) { - throw Serial("native color clear", resumable: true); + case NativeColorClearPrediction.Settled: + Requests.NativeColorUses.Add((imageIdentifier, request)); + break; + case NativeColorClearPrediction.RegistrationOnly: + Requests.NativeColorEntries.Add((imageIdentifier, request)); + break; + default: + throw Serial("native color clear", resumable: true); } - - Requests.NativeColorUses.Add((imageIdentifier, request)); } } @@ -1366,14 +1500,27 @@ private DepthAttachmentAcquisition AcquireDepthAttachmentForSlice(in DepthAttach throw Serial("stale depth target"); } + // A pending HTILE clear passes when the segment holds a clear entry for the view: the join records the clear ahead + // of the segment. The draw's own depth clear, or an earlier use of the image other than as depth, stops the worker. var layer = resolution.Request.View.BaseLayer; + var pending = false; if (resolution.HasHtile && (resolution.DepthClearEnabled || _imageCache.IsMetadataCleared(resolution.HtileAddress, layer))) { - throw Serial("depth clear"); + if (resolution.DepthClearEnabled || HasNonDepthUse(depth.Image)) + { + throw Serial("depth clear"); + } + + pending = true; } if (TryKeptAttachment(depth.Image, resolution.Request, out var keptView, out var keptImage)) { + if (pending && !HasDepthClear(depth.Image, resolution.Request.View)) + { + throw Serial("depth clear"); + } + return new DepthAttachmentAcquisition(keptView, keptImage.Backing.Samples, false); } @@ -1385,9 +1532,121 @@ private DepthAttachmentAcquisition AcquireDepthAttachmentForSlice(in DepthAttach var image = Image(depth.Image); Requests.AddImage(new ImageSliceUse(depth.Image, image, resolution.Request)); _attachments.Add((depth.Image, resolution.Request, view, image)); + if (resolution.HasHtile && !HasDepthClear(depth.Image, resolution.Request.View)) + { + Requests.DepthClears.Add(new SliceDepthClear + { + Image = depth.Image, + Expected = image, + View = resolution.Request.View, + NativeView = view, + Htile = resolution.HtileAddress, + BaseLayer = layer, + ClearWord = BitConverter.SingleToUInt32Bits(depth.Target.State.DepthClearValue), + }); + Requests.DepthClearKeys.Add((depth.Image, resolution.Request.View)); + } + return new DepthAttachmentAcquisition(view, image.Backing.Samples, false); } + private bool HasDepthClear(ResourceSlotIdentifier image, in ImageViewDescription view) + { + foreach (var key in Requests.DepthClearKeys) + { + if (key.Image == image && key.View == view) + { + return true; + } + } + + return false; + } + + private bool HasNonDepthUse(ResourceSlotIdentifier image) + { + foreach (var use in Requests.Images) + { + if (use.Image == image && use.Request.Role != ImageRole.DepthTarget) + { + return true; + } + } + + return false; + } + + // A worker notes the area of the segment's first rendering with each clear entry's view. + private static void NoteDepthClearArea(SliceRequests requests, in RenderingState state) + { + if (!state.DepthStencilAttachment.HasDepth) + { + return; + } + + foreach (var entry in requests.DepthClears) + { + if (!entry.HasArea && entry.NativeView.Handle == state.DepthStencilAttachment.View.Handle) + { + entry.HasArea = true; + entry.Width = state.Width; + entry.Height = state.Height; + entry.Layers = state.Layers; + } + } + } + + // The render thread records a segment's pending depth clears ahead of it, as the first acquisition of each view would: + // it consumes the base layer's HTILE clear state and clears the area of the view's first rendering with the draw's + // value. Stencil is not touched. + internal void ApplySliceDepthClears(List clears) + { + foreach (var entry in clears) + { + if (!_imageCache.IsMetadataCleared(entry.Htile, entry.BaseLayer)) + { + continue; + } + + if (!entry.HasArea) + { + throw SubmissionScheduler.Fatal($"A slice depth clear has no rendering area: htile=0x{entry.Htile:X16}."); + } + + if (!_imageCache.SetMetadataSlice(entry.Htile, entry.BaseLayer, false)) + { + throw SubmissionScheduler.Fatal($"The HTile clear state could not be consumed: htile=0x{entry.Htile:X16} layer={entry.BaseLayer}."); + } + + EndRendering(); + var command = BeginBatchedGuestCommands(); + var view = entry.View; + TransitionImage(entry.Expected, AccessFlags.DepthStencilAttachmentReadBit | AccessFlags.DepthStencilAttachmentWriteBit, + new SubresourceRange(view.BaseLevel, view.LevelCount, view.BaseLayer, view.LayerCount), command); + var depth = new RenderingAttachmentInfo + { + SType = StructureType.RenderingAttachmentInfo, + ImageView = entry.NativeView, + ImageLayout = ImageLayout.General, + LoadOp = AttachmentLoadOp.Clear, + StoreOp = AttachmentStoreOp.Store, + ClearValue = new ClearValue { DepthStencil = new ClearDepthStencilValue(BitConverter.UInt32BitsToSingle(entry.ClearWord), 0) }, + }; + var rendering = new RenderingInfo + { + SType = StructureType.RenderingInfo, + RenderArea = new Rect2D(new Offset2D(0, 0), new Extent2D(entry.Width, entry.Height)), + LayerCount = entry.Layers, + PDepthAttachment = &depth, + }; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdBeginRendering(command, &rendering); + _vk.CmdEndRendering(command); + } + } + } + private ImageView AcquireTextureViewForSlice(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) { if (!_imageCache.TryPrepareTextureViewForSlice(imageIdentifier, in request, out var view)) diff --git a/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs b/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs index fc179c8fb..7ec535581 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs @@ -63,9 +63,23 @@ public static string TakeUnboundedReport() public static IReadOnlyList Plan(ShaderResourcePlan plan) => Plan(plan, out _); - public static IReadOnlyList Plan(ShaderResourcePlan plan, out bool readsBounded) + public static IReadOnlyList Plan(ShaderResourcePlan plan, out bool readsBounded) => + Plan(plan, out readsBounded, out _, out _); + + // A scalar address read, and a global read with a scalar base, address the handle's 64-bit base plus a zero-extended + // 32-bit offset (the translator widens it with UConvert) and a signed immediate, so such a handle reaches only + // [base + first byte, base + 2^32 + end byte). A program is windowed when every range it does not bound exactly is such + // a handle, read only, with a plannable base. windowBytes is the widest window measured from the host's range base + // (EvaluateRange: base + min(first byte, 0), dword-aligned for scalar reads), with a pad for that alignment. + public const ulong WindowOffsetBytes = 1UL << 32; + private const long WindowPadBytes = 16; + + public static IReadOnlyList Plan(ShaderResourcePlan plan, out bool readsBounded, out bool readsWindowed, + out ulong windowBytes) { readsBounded = true; + var windowable = true; + var windowSafe = new List(); var ranges = new List(); var handles = new List(); var slotsByHash = new Dictionary>(); @@ -75,6 +89,7 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan if (memory.DeviceDescriptor || memory.Opcode is "ImageBvhIntersectRay" or "ImageBvh64IntersectRay") { readsBounded = false; + windowable = false; } if (memory.Kind is not (MemoryResourceKind.Flat or MemoryResourceKind.Global or MemoryResourceKind.ScalarAddress)) @@ -85,12 +100,14 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan if (memory.PlanningOnly) { readsBounded &= memory.Kind == MemoryResourceKind.ScalarAddress; + windowable &= memory.Kind == MemoryResourceKind.ScalarAddress; continue; } if (plan.Accesses[index]?.Handle is not { Kind: ScalarValueKind.AddressHandle } handle || handle.Operands.Length != 2) { readsBounded = false; + windowable = false; continue; } @@ -128,12 +145,15 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan slot = handles.Count; hashSlots.Add(slot); handles.Add(handle); + windowSafe.Add(true); ranges.Add(new DeviceAddressRangePlan((uint)slot, handle.Operands[0], handle.Operands[1], [], false, true, long.MaxValue, long.MinValue, false) { AlignScalarReads = true }); } // The immediate offset is signed; the span keeps the lowest and highest byte. var written = memory.Access is MemoryAccess.Write or MemoryAccess.Atomic; + windowSafe[slot] = windowSafe[slot] && + (memory.Kind == MemoryResourceKind.ScalarAddress || (memory.Kind == MemoryResourceKind.Global && !memory.AddressIsFull)); readsBounded &= memory.Access == MemoryAccess.Read; var bytes = Math.Max((memory.DataBits + 7) / 8, 1u) * Math.Max(memory.DataDwords, 1u); var firstByte = (long)unchecked((int)memory.Offset); @@ -158,6 +178,8 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan }; } + var anyWindowed = false; + long margin = 0; for (var slot = 0; slot < ranges.Count; slot++) { ranges[slot] = ranges[slot] with @@ -165,10 +187,27 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan Plannable = plan.ValidateRuntimeValue(ranges[slot].BaseLow) && plan.ValidateRuntimeValue(ranges[slot].BaseHigh), }; var range = ranges[slot]; - readsBounded &= range.Bounded && range.Plannable && !range.Written && range.Extent <= MaxRangeBytes; + var exact = range.Bounded && range.Plannable && !range.Written && range.Extent <= MaxRangeBytes; + readsBounded &= exact; + if (exact) + { + continue; + } + + if (!range.Bounded && range.Plannable && !range.Written && windowSafe[slot] && range.EndByte >= range.FirstByte) + { + anyWindowed = true; + margin = Math.Max(margin, range.EndByte - Math.Min(range.FirstByte, 0)); + continue; + } + + windowable = false; } - readsBounded &= ranges.Count != 0 && plan.DeviceRecordCounts is null && plan.Graph.Program.FunctionBufferAccesses.Count == 0; + var plainProgram = ranges.Count != 0 && plan.DeviceRecordCounts is null && plan.Graph.Program.FunctionBufferAccesses.Count == 0; + readsBounded &= plainProgram; + readsWindowed = windowable && anyWindowed && plainProgram; + windowBytes = readsWindowed ? WindowOffsetBytes + (ulong)(margin + WindowPadBytes) : 0; return ranges; } diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs new file mode 100644 index 000000000..a47b71738 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs @@ -0,0 +1,420 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// The branch selection of a plan with resource branches (RuntimeValueEvaluator.EvaluateActiveSources) on registers lowered once +// per plan, so a draw builds no evaluators for it. Clean reads have effects (a resolve worker logs each word it reads, and a +// read can throw to resolve the draw in stream order), so the selection reads exactly what the evaluator reads, in its order: +// the conditions of the blocks it visits, evaluated on demand operand by operand (a failed operand ends its value, a success +// is kept for the call), then, for a plan that writes memory, the written buffers' descriptor words, buffer by buffer, which +// ResourceBranchWriteGuard tests against the words the conditions read. +internal sealed partial class MaterializationProgram +{ + private enum BranchNodeKind : byte + { + Constant, + Step, + Read, + } + + private readonly record struct BranchNode(BranchNodeKind Kind, ulong Constant, Step Step, ReadStep Read); + + [ThreadStatic] + private static BranchScratch? _branchScratch; + + private sealed class BranchScratch + { + public ulong[] Values = new ulong[128]; + public uint[] Stamps = new uint[128]; + public uint Generation; + // Whether a successful clean read is kept for the write guard. + public bool Recording; + public ulong[] Reads = new ulong[16]; + public int ReadCount; + public bool[] Visited = new bool[16]; + public int[] Pending = new int[32]; + + public void Begin(int registers, int blocks, int pending, bool recording) + { + if (Values.Length < registers) + { + var size = Math.Max(registers, Values.Length * 2); + Values = new ulong[size]; + Stamps = new uint[size]; + } + + if (Visited.Length < blocks) + { + Visited = new bool[Math.Max(blocks, Visited.Length * 2)]; + } + else + { + Array.Clear(Visited, 0, blocks); + } + + if (Pending.Length < pending) + { + Pending = new int[Math.Max(pending, Pending.Length * 2)]; + } + + if (++Generation == 0) + { + Array.Clear(Stamps); + Generation = 1; + } + + Recording = recording; + ReadCount = 0; + } + + public void Record(ulong address) + { + if (ReadCount == Reads.Length) + { + Array.Resize(ref Reads, ReadCount * 2); + } + + Reads[ReadCount++] = address; + } + } + + internal sealed class BranchSelection + { + private readonly BranchNode[] _nodes; + private readonly int[] _conditions; + private readonly int[][] _successors; + private readonly uint[][] _sources; + private readonly bool[] _initialActive; + private readonly bool _guarded; + // Four registers per written buffer, in ResourceBranchWrites order, up to the first whose descriptor is not four words. + private readonly int[] _writtenWords; + // The guard fails once it reaches a written descriptor that is not four words. + private readonly bool _guardFails; + private readonly int _pendingCapacity; + + private BranchSelection(BranchNode[] nodes, int[] conditions, int[][] successors, uint[][] sources, bool[] initialActive, bool guarded, + int[] writtenWords, bool guardFails, int pendingCapacity) + { + _nodes = nodes; + _conditions = conditions; + _successors = successors; + _sources = sources; + _initialActive = initialActive; + _guarded = guarded; + _writtenWords = writtenWords; + _guardFails = guardFails; + _pendingCapacity = pendingCapacity; + } + + internal int SourceCount => _initialActive.Length; + + // Null when a condition or a written descriptor word does not lower: the plan selects with the evaluator. + internal static BranchSelection? Build(ShaderResourcePlan plan) + { + var blocks = plan.ResourceBranches; + if (blocks.Count == 0) + { + return null; + } + + var builder = new Builder(plan); + var conditions = new int[blocks.Count]; + for (var index = 0; index < blocks.Count; index++) + { + conditions[index] = -1; + if (blocks[index].Condition is { } condition && !builder.Register(condition, out conditions[index])) + { + return null; + } + } + + var writtenWords = new List(); + var guardFails = false; + if (plan.ResourceBranchesWithWrites) + { + foreach (var buffer in plan.ResourceBranchWrites) + { + var source = plan.DescriptorSources[(int)plan.Info.Buffers[(int)buffer].Source]; + if (source.DwordCount != 4) + { + guardFails = true; + break; + } + + foreach (var word in source.Dwords) + { + if (!builder.Register(word, out var register)) + { + return null; + } + + writtenWords.Add(register); + } + } + } + + var successors = new int[blocks.Count][]; + var sources = new uint[blocks.Count][]; + var initialActive = new bool[plan.DescriptorSources.Count]; + Array.Fill(initialActive, true); + // A walk visits each block once and pushes each of its successors at most once. + var pendingCapacity = 1; + for (var index = 0; index < blocks.Count; index++) + { + successors[index] = blocks[index].Successors; + sources[index] = blocks[index].Sources; + pendingCapacity += successors[index].Length; + foreach (var source in sources[index]) + { + initialActive[source] = false; + } + } + + return new BranchSelection(builder.Nodes(), conditions, successors, sources, initialActive, plan.ResourceBranchesWithWrites, + [.. writtenWords], guardFails, pendingCapacity); + } + + // Fills `active` (SourceCount long) as EvaluateActiveSources does; false without a clean reader, which the evaluator + // handles. + internal bool TrySelect(ResourceRuntimeInputs inputs, bool[] active) + { + var clean = inputs.ReadCleanMemory; + if (clean is null) + { + return false; + } + + // Taken out of its slot while in use: a guest read can select another draw's sources on this thread. + var scratch = _branchScratch ?? new BranchScratch(); + _branchScratch = null; + try + { + Select(inputs, clean, scratch, active); + } + finally + { + _branchScratch = scratch; + } + + ResourceMaterializationProfile.RecordActivity(active); + return true; + } + + private void Select(ResourceRuntimeInputs inputs, GuestWordReader clean, BranchScratch scratch, bool[] active) + { + scratch.Begin(_nodes.Length, _conditions.Length, _pendingCapacity, _guarded); + Array.Copy(_initialActive, active, _initialActive.Length); + var visited = scratch.Visited; + var pending = scratch.Pending; + var count = 0; + pending[count++] = 0; + while (count != 0) + { + var block = pending[--count]; + if (visited[block]) + { + continue; + } + + visited[block] = true; + foreach (var source in _sources[block]) + { + active[source] = true; + } + + // An unreadable predicate keeps both paths. + var condition = _conditions[block]; + var successors = _successors[block]; + if (condition >= 0 && Evaluate(condition, inputs, clean, scratch)) + { + pending[count++] = successors[(uint)scratch.Values[condition] != 0 ? 0 : 1]; + continue; + } + + foreach (var successor in successors) + { + pending[count++] = successor; + } + } + + if (_guarded && !GuardHolds(inputs, clean, scratch)) + { + Array.Fill(active, true); + } + } + + // ResourceBranchWriteGuard.Holds: each written descriptor, read after every predicate, against the words the predicates + // read. + private bool GuardHolds(ResourceRuntimeInputs inputs, GuestWordReader clean, BranchScratch scratch) + { + var predicateReads = scratch.Reads.AsSpan(0, scratch.ReadCount); + scratch.Recording = false; + for (var at = 0; at < _writtenWords.Length; at += 4) + { + for (var word = at; word < at + 4; word++) + { + if (!Evaluate(_writtenWords[word], inputs, clean, scratch)) + { + return false; + } + } + + var values = scratch.Values; + if (ResourceBranchWriteGuard.Reaches((uint)values[_writtenWords[at]], (uint)values[_writtenWords[at + 1]], + (uint)values[_writtenWords[at + 2]], (uint)values[_writtenWords[at + 3]], predicateReads)) + { + return false; + } + } + + return !_guardFails; + } + + // The evaluator's value of a register: its operands in the evaluator's order, where the first failure ends it and a + // success is kept for the rest of the call. + private bool Evaluate(int register, ResourceRuntimeInputs inputs, GuestWordReader clean, BranchScratch scratch) + { + if (scratch.Stamps[register] == scratch.Generation) + { + return true; + } + + ref readonly var node = ref _nodes[register]; + ulong value; + switch (node.Kind) + { + case BranchNodeKind.Constant: + value = node.Constant; + break; + case BranchNodeKind.Step: + if (!EvaluateStep(node.Step, inputs, clean, scratch, out value)) + { + return false; + } + + break; + default: + if (!ReadClean(node.Read, inputs, clean, scratch, out value)) + { + return false; + } + + break; + } + + scratch.Values[register] = value; + scratch.Stamps[register] = scratch.Generation; + return true; + } + + private bool EvaluateStep(in Step step, ResourceRuntimeInputs inputs, GuestWordReader clean, BranchScratch scratch, out ulong value) + { + value = 0; + switch (step.Kind) + { + case StepKind.UserData: + if ((uint)step.First >= (uint)inputs.UserData.Count) + { + return false; + } + + value = inputs.UserData[step.First]; + return true; + case StepKind.ShaderBase: + value = inputs.ShaderBase; + return true; + case StepKind.Select: + { + // A select reads both arms, as the evaluator's does. + if (!Evaluate(step.First, inputs, clean, scratch) || !Evaluate(step.Second, inputs, clean, scratch) || + !Evaluate(step.Third, inputs, clean, scratch)) + { + return false; + } + + var values = scratch.Values; + value = values[step.First] != 0 ? values[step.Second] : values[step.Third]; + return true; + } + default: + { + var registers = step.Operands!; + foreach (var operand in registers) + { + if (!Evaluate(operand, inputs, clean, scratch)) + { + return false; + } + } + + Span operands = registers.Length <= 8 ? stackalloc ulong[8] : new ulong[registers.Length]; + operands = operands[..registers.Length]; + for (var index = 0; index < registers.Length; index++) + { + operands[index] = scratch.Values[registers[index]]; + } + + return ScalarOperationSemantics.TryEvaluate(step.Operation, operands, out value); + } + } + } + + // RuntimeValueEvaluator.EvaluateRawRead and ReadRawWord: the handle's low and high words, the offset, then a buffer's + // records and word 3, and one aligned dword. Every predicate reader is clean, so a refused word reads as zero only + // through a null base. + private bool ReadClean(in ReadStep read, ResourceRuntimeInputs inputs, GuestWordReader clean, BranchScratch scratch, out ulong value) + { + value = 0; + var buffer = read.Kind == ScalarValueKind.ScalarBufferWord; + if (!Evaluate(read.Low, inputs, clean, scratch) || !Evaluate(read.High, inputs, clean, scratch) || + (read.Offset >= 0 && !Evaluate(read.Offset, inputs, clean, scratch)) || + (buffer && (!Evaluate(read.Records, inputs, clean, scratch) || !Evaluate(read.Word3, inputs, clean, scratch)))) + { + return false; + } + + var values = scratch.Values; + var high = values[read.High]; + var records = buffer ? values[read.Records] : 0; + var offset = read.Offset >= 0 ? (uint)values[read.Offset] : read.ConstantOffset; + var baseAddress = ((high << 32) | (uint)values[read.Low]) & AddressMask; + switch (RuntimeValueEvaluator.ResolveRawAddress(read.Kind, baseAddress, high, records, read.Immediate, offset, out var address)) + { + case RuntimeValueEvaluator.RawAddress.Failed: + return false; + case RuntimeValueEvaluator.RawAddress.Zero: + return true; + } + + if (!clean(address, out var word)) + { + return (baseAddress & ~3ul) == 0; + } + + if (scratch.Recording) + { + scratch.Record(address); + } + + value = word; + return true; + } + } + + // The active sources of TryRun and TryRunInto: the plan's compiled selection when it lowers and the draw has a clean reader, + // else EvaluateActiveSources. With `reuse`, the array is that scratch's. + private static bool[] SelectActiveSources(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, Scratch? reuse) + { + if (plan.BranchSelection is { } selection) + { + var active = reuse?.ActiveSources(selection.SourceCount) ?? new bool[selection.SourceCount]; + if (selection.TrySelect(inputs, active)) + { + return active; + } + } + + return RuntimeValueEvaluator.EvaluateActiveSources(plan, inputs); + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index c0b223f63..c2bd024fc 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -5,7 +5,7 @@ namespace SharpEmu.ShaderCompiler.Resources; -internal sealed class MaterializationProgram +internal sealed partial class MaterializationProgram { private const ulong AddressMask = 0x0000_FFFF_FFFF_FFFFul; private const int MinimumRunWords = 2; @@ -54,6 +54,11 @@ private sealed class Scratch public byte[] Bytes = new byte[1024]; public int Count; + // Active-source arrays by length: TryRunInto reads its array before the scratch goes back to the thread. + private readonly bool[]?[] _activeSources = new bool[]?[65]; + + public bool[] ActiveSources(int count) => count < _activeSources.Length ? _activeSources[count] ??= new bool[count] : new bool[count]; + public void Ensure(int registers) { if (Values.Length < registers) @@ -211,6 +216,28 @@ private int NewRegister(int level, ulong constant = 0, bool constantValid = fals private int LevelOf(int register) => _registerLevels[register]; + // Every register as a node a branch selection evaluates on demand: its constant, step or read. + public BranchNode[] Nodes() + { + var nodes = new BranchNode[_constants.Count]; + for (var register = 0; register < nodes.Length; register++) + { + nodes[register] = new BranchNode(BranchNodeKind.Constant, _constants[register], default, default); + } + + foreach (var (_, step) in _steps) + { + nodes[step.Target] = new BranchNode(BranchNodeKind.Step, 0, step, default); + } + + foreach (var (_, read) in _reads) + { + nodes[read.Target] = new BranchNode(BranchNodeKind.Read, 0, default, read); + } + + return nodes; + } + public bool Register(ScalarValue value, out int register) { if (_registers.TryGetValue(value, out register)) @@ -401,7 +428,7 @@ public MaterializationProgram Finish(int[][] sourceWords, int[] tableWords, uint internal bool TryRun(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int additionalTableWords, out List sources, out uint[] table, out DeviceAddressRange[] ranges, out bool[] activeSources) { - activeSources = plan.ResourceBranches.Count != 0 ? RuntimeValueEvaluator.EvaluateActiveSources(plan, inputs) : []; + activeSources = plan.ResourceBranches.Count != 0 ? SelectActiveSources(plan, inputs, reuse: null) : []; var scratch = _scratch ?? new Scratch(); _scratch = null; try @@ -433,11 +460,11 @@ internal sealed class Output internal bool TryRunInto(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int additionalTableWords, Output output) { - var activeSources = plan.ResourceBranches.Count != 0 ? RuntimeValueEvaluator.EvaluateActiveSources(plan, inputs) : []; var scratch = _scratch ?? new Scratch(); _scratch = null; try { + var activeSources = plan.ResourceBranches.Count != 0 ? SelectActiveSources(plan, inputs, reuse: scratch) : []; Evaluate(inputs, scratch); return Emit(plan, additionalTableWords, scratch, activeSources, output); } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs index 289c4e5b8..2d915de86 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs @@ -1,6 +1,8 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Runtime.InteropServices; + namespace SharpEmu.ShaderCompiler.Resources; // SHARPEMU_BRANCHES_WITH_WRITES (on by default, =0 off): the branch selection of a plan that writes memory @@ -52,22 +54,31 @@ internal bool Holds() if (!Evaluator.Evaluate(source.Dwords[index], out words[index])) return false; } - // A descriptor that is not a buffer is bound as null (ResourceMaterializer.BuildSpecialization): nothing is written. - if ((words[3] >> 30) != 0) continue; - if ((words[1] >> 31) != 0 || ((words[3] >> 23) & 1) != 0) return false; - var stride = (words[1] >> 16) & 0x3FFFu; - var size = stride == 0 ? words[2] : (ulong)stride * words[2]; - var start = words[0] | ((ulong)(words[1] & 0xFFFF) << 32); - var low = start > Margin ? start - Margin : 0; - var high = start + size + Margin; - for (var index = 0; index < predicateReads; index++) - { - if (_reads[index] + sizeof(uint) > low && _reads[index] < high) return false; - } + if (Reaches(words[0], words[1], words[2], words[3], CollectionsMarshal.AsSpan(_reads)[..predicateReads])) return false; } return true; } + // Whether a written V# may reach one of the words the predicates read: one that swizzles or adds the thread id may, and + // so may one whose records, Margin bytes wider on each side, cover such a word. + internal static bool Reaches(uint word0, uint word1, uint word2, uint word3, ReadOnlySpan predicateReads) + { + // A descriptor that is not a buffer is bound as null (ResourceMaterializer.BuildSpecialization): nothing is written. + if ((word3 >> 30) != 0) return false; + if ((word1 >> 31) != 0 || ((word3 >> 23) & 1) != 0) return true; + var stride = (word1 >> 16) & 0x3FFFu; + var size = stride == 0 ? word2 : (ulong)stride * word2; + var start = word0 | ((ulong)(word1 & 0xFFFF) << 32); + var low = start > Margin ? start - Margin : 0; + var high = start + size + Margin; + foreach (var read in predicateReads) + { + if (read + sizeof(uint) > low && read < high) return true; + } + + return false; + } + public void Dispose() => _scratch.Dispose(); } diff --git a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs index 6e615f9c1..323026d4e 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs @@ -632,6 +632,8 @@ internal static bool[] EvaluateActiveSources(ShaderResourcePlan plan, ResourceRu return EvaluateActiveSources(plan, inputs, cleanEvaluator, cleanScratch); } + // MaterializationProgram.BranchSelection makes this walk, with the same reads in the same order, on registers lowered once + // per plan. private static bool[] EvaluateActiveSources(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, RuntimeValueEvaluator cleanEvaluator, RuntimeEvaluationScratch scratch) { diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs index b02574577..5b793d4d4 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs @@ -86,6 +86,20 @@ private ProgramBox InitializeMaterializationProgram() return Interlocked.CompareExchange(ref _materializationProgram, built, null) ?? built; } + private sealed record BranchSelectionBox(MaterializationProgram.BranchSelection? Selection); + + private BranchSelectionBox? _branchSelection; + + // The materialization program's branch selection, built on first use; null leaves the selection to the evaluator. + internal MaterializationProgram.BranchSelection? BranchSelection => + (Volatile.Read(ref _branchSelection) ?? InitializeBranchSelection()).Selection; + + private BranchSelectionBox InitializeBranchSelection() + { + var built = new BranchSelectionBox(Resources.MaterializationProgram.BranchSelection.Build(this)); + return Interlocked.CompareExchange(ref _branchSelection, built, null) ?? built; + } + internal object?[]? SpecializationMemos; internal int NextSpecializationMemo; @@ -365,9 +379,11 @@ ScalarValue RewriteRead(ScalarValue read) plan.ResourceBranches = ResourceBranchBlock.Build(plan, Rewrite); plan.ResourceBranchesWithWrites = plan.ResourceBranches.Count != 0 && ResourceBranchBlock.Writes(plan); plan.ResourceBranchWrites = plan.ResourceBranchesWithWrites ? ResourceBranchBlock.WrittenBuffers(plan) ?? [] : []; - plan.DeviceAddressRanges = DeviceAddressRangePlanner.Plan(plan, out var readsBounded); + plan.DeviceAddressRanges = DeviceAddressRangePlanner.Plan(plan, out var readsBounded, out var readsWindowed, out var windowBytes); plan.CallRecordCallees = CallRecordPlanner.Plan(plan); plan.DeviceAddressReadsBounded = readsBounded && plan.CallRecordCallees.Count == 0; + plan.DeviceAddressReadsWindowed = !plan.DeviceAddressReadsBounded && readsWindowed && plan.CallRecordCallees.Count == 0; + plan.DeviceAddressWindowBytes = plan.DeviceAddressReadsWindowed ? windowBytes : 0; // Each written handle owns three flattened slots after the table reads: base // low, base high and size, which the shader checks every store against. @@ -393,6 +409,12 @@ ScalarValue RewriteRead(ScalarValue read) public bool DeviceAddressReadsBounded { get; private set; } + // Every device-address read the plan does not bound exactly is a handle base plus a 32-bit offset, and + // DeviceAddressWindowBytes from each evaluated range base covers what it reaches. + public bool DeviceAddressReadsWindowed { get; private set; } + + public ulong DeviceAddressWindowBytes { get; private set; } + public IReadOnlyDictionary WrittenRangeSlotByHandle { get; private set; } = new Dictionary(); public int WrittenRangeCount => WrittenRangeSlotByHandle.Count; diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs new file mode 100644 index 000000000..7729c15bf --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs @@ -0,0 +1,371 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.HLE; +using SharpEmu.Libs.Agc; +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Libs.Tests.Agc; + +// The register and draw packet exports build each packet in full and write it at once. They leave the same guest bytes, +// cursor and result as a reference emitter that allocates every packet on its own and writes it a dword at a time, in +// roomy buffers and in buffers too full for their packets (no buffer-full callback is installed). +[Collection(AgcCommandBufferChainCollection.Name)] +public sealed class AgcPackedRegisterPacketTests +{ + private const ulong BaseAddress = 0x2_7000_0000; + private const ulong CommandBufferAddress = BaseAddress + 0x100; + private const ulong CursorAddress = CommandBufferAddress + 0x10; + private const ulong PacketAddress = BaseAddress + 0x1000; + private const ulong SourceAddress = BaseAddress + 0x8000; + private const int MemorySize = 0x10000; + private const uint RangeMarker = 0x6875000D; + + [Theory] + [InlineData(1, 0x2000u)] + [InlineData(2, 0x2000u)] + [InlineData(3, 0x40u)] + [InlineData(4, 0x18u)] + public void ShRegisterRangeDirectMatchesTheReferenceEmitter(int seed, uint availableBytes) + { + var random = new System.Random(seed); + for (var trial = 0; trial < 32; trial++) + { + var offset = (uint)random.Next(1, 0x3FF); + var values = new uint[random.Next(1, 24)]; + for (var index = 0; index < values.Length; index++) + { + values[index] = (uint)random.Next(); + } + + AssertMatchesReference( + availableBytes, + memory => + { + for (var index = 0; index < values.Length; index++) + { + WriteUInt32(memory, SourceAddress + ((ulong)index * 4), values[index]); + } + }, + memory => + { + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = offset, + [CpuRegister.Rdx] = SourceAddress, + [CpuRegister.Rcx] = (ulong)values.Length, + }; + AgcExports.CbSetShRegisterRangeDirect(context); + return context[CpuRegister.Rax]; + }, + buffer => + buffer.TryEmit([PacketHeader.Make(2, PacketOpcode.Nop), RangeMarker], out _) && + buffer.TryEmit([PacketHeader.Make((uint)values.Length + 2, PacketOpcode.SetShaderRegister), offset, .. values], + out var commandAddress) + ? commandAddress + : 0); + } + } + + [Theory] + [InlineData(5, 0x4000u)] + [InlineData(6, 0x4000u)] + [InlineData(7, 0x30u)] + public void ShRegistersDirectMatchesTheReferenceEmitter(int seed, uint availableBytes) + { + var random = new System.Random(seed); + for (var trial = 0; trial < 32; trial++) + { + var entries = new (uint Offset, uint Value)[random.Next(1, 40)]; + var next = (uint)random.Next(0, 0x200); + for (var index = 0; index < entries.Length; index++) + { + // Runs of consecutive registers with gaps, shuffled below; a repeated register now and then. + next += random.Next(4) == 0 ? (uint)random.Next(2, 9) : random.Next(10) == 0 ? 0u : 1u; + entries[index] = (next, (uint)random.Next()); + } + + random.Shuffle(entries); + AssertMatchesReference( + availableBytes, + memory => WriteEntries(memory, entries), + memory => EmitShRegisters(memory, entries.Length), + buffer => ReferenceShRegisters(buffer, entries)); + } + } + + [Theory] + [InlineData(8, 0x40000000UL, 0x280u, 0x280u, 2u)] + [InlineData(9, 0x60180707UL, 0x10Fu, 0x10Fu, 0x22u)] + [InlineData(10, 0x4F18060DUL, 0x8Fu, 0x8Fu, 2u)] + public void DrawIndexIndirectMatchesTheReferenceEmitter( + int seed, ulong modifier, uint vertexRegister, uint instanceRegister, uint initiator) + { + var random = new System.Random(seed); + foreach (var availableBytes in new uint[] { 0x100, 0x14, 0x10 }) + { + var dataOffset = (uint)random.Next(); + AssertMatchesReference( + availableBytes, + _ => { }, + memory => + { + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = dataOffset, + [CpuRegister.Rdx] = modifier, + }; + AgcExports.DcbDrawIndexIndirect(context); + return context[CpuRegister.Rax]; + }, + buffer => buffer.TryEmit( + [PacketHeader.Make(5, PacketOpcode.DrawIndexIndirect), dataOffset, vertexRegister, instanceRegister, initiator], + out var commandAddress) + ? commandAddress + : 0); + } + } + + [Fact] + public void EachPacketTakesOneAllocationAndOneWrite() + { + (uint Offset, uint Value)[] entries = [(0x12, 3), (0x10, 1), (0x20, 4), (0x11, 2)]; + var memory = new CountingMemory(Prepare(0x1000)); + WriteEntries(memory.Inner, entries); + + Assert.Equal(PacketAddress, EmitShRegisters(memory, entries.Length)); + + // One read of the entries; each of the two packets (registers 0x10-0x12, then 0x20) reads the buffer state, moves + // the cursor and is written. + Assert.Equal((3, 4, 2), (memory.Reads, memory.Writes, memory.CursorWrites)); + Assert.Equal(PacketAddress + 32, ReadUInt64(memory.Inner, CursorAddress)); + + memory.ResetCounts(); + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = 0x1F4, + [CpuRegister.Rdx] = 0x40000000UL, + }; + AgcExports.DcbDrawIndexIndirect(context); + + Assert.Equal(PacketAddress + 32, context[CpuRegister.Rax]); + Assert.Equal((1, 2, 1), (memory.Reads, memory.Writes, memory.CursorWrites)); + } + + [Fact] + public void ShRegistersDirectWithAnUnreadableEntryWritesNothing() + { + // The last entry's value lies past the end of guest memory. + var registersAddress = BaseAddress + MemorySize - 20; + var memory = new CountingMemory(Prepare(0x1000)); + WriteUInt32(memory.Inner, registersAddress, 0x10); + WriteUInt32(memory.Inner, registersAddress + 4, 1); + WriteUInt32(memory.Inner, registersAddress + 8, 0x11); + WriteUInt32(memory.Inner, registersAddress + 12, 2); + WriteUInt32(memory.Inner, registersAddress + 16, 0x12); + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = registersAddress, + [CpuRegister.Rdx] = 3, + }; + + Assert.Equal(0, AgcExports.CbSetShRegistersDirect(context)); + + Assert.Equal(0UL, context[CpuRegister.Rax]); + Assert.Equal(0, memory.Writes); + Assert.Equal(PacketAddress, ReadUInt64(memory.Inner, CursorAddress)); + } + + [Theory] + [InlineData(0)] + [InlineData(8)] + public void ARangeWhoseMarkerOrHeaderCannotBeWrittenKeepsItsOneAllocation(int failedByte) + { + // The marker and packet share one allocation: a failed marker or header write returns null without moving the + // cursor back or allocating again. + var memory = new CountingMemory(Prepare(0x1000)) { FailedWriteAddress = PacketAddress + (ulong)failedByte }; + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = 0x40, + [CpuRegister.Rdx] = SourceAddress, + [CpuRegister.Rcx] = 3, + }; + + Assert.Equal(0, AgcExports.CbSetShRegisterRangeDirect(context)); + + Assert.Equal(0UL, context[CpuRegister.Rax]); + Assert.Equal(1, memory.CursorWrites); + Assert.Equal(PacketAddress + 28, ReadUInt64(memory.Inner, CursorAddress)); + } + + // Runs the export and the reference emitter from the same starting memory and compares the result and every byte. + private static void AssertMatchesReference( + uint availableBytes, + Action writeInputs, + Func export, + Func reference) + { + var memory = Prepare(availableBytes); + writeInputs(memory); + var result = export(memory); + + var expected = Prepare(availableBytes); + writeInputs(expected); + var expectedResult = reference(new ReferenceBuffer(expected, availableBytes)); + + Assert.Equal(expectedResult, result); + Assert.Equal(Snapshot(expected), Snapshot(memory)); + } + + // SET_SH_REG packets for (offset, value) entries: sorted by offset, one packet per run of consecutive offsets (a + // repeated offset starts a new packet), in order; the result is the first packet's address. + private static ulong ReferenceShRegisters(ReferenceBuffer buffer, (uint Offset, uint Value)[] entries) + { + var sorted = entries.ToArray(); + Array.Sort(sorted, static (left, right) => left.Offset.CompareTo(right.Offset)); + ulong firstCommandAddress = 0; + for (var start = 0; start < sorted.Length;) + { + var end = start + 1; + while (end < sorted.Length && sorted[end].Offset == sorted[end - 1].Offset + 1) + { + end++; + } + + var packet = new uint[end - start + 2]; + packet[0] = PacketHeader.Make((uint)packet.Length, PacketOpcode.SetShaderRegister); + packet[1] = sorted[start].Offset & 0xFFFFu; + for (var index = start; index < end; index++) + { + packet[2 + index - start] = sorted[index].Value; + } + + if (!buffer.TryEmit(packet, out var commandAddress)) + { + return 0; + } + + firstCommandAddress = firstCommandAddress == 0 ? commandAddress : firstCommandAddress; + start = end; + } + + return firstCommandAddress; + } + + // A packet goes at the cursor when it fits below the down cursor; the cursor is stored, then the packet is written a + // dword at a time. Nothing is reserved and no buffer-full callback is installed, so a packet that does not fit fails. + private sealed class ReferenceBuffer(FakeCpuMemory memory, uint availableBytes) + { + private ulong _cursor = PacketAddress; + + public bool TryEmit(ReadOnlySpan packet, out ulong commandAddress) + { + var bytes = (ulong)packet.Length * sizeof(uint); + if (bytes > PacketAddress + availableBytes - _cursor) + { + commandAddress = 0; + return false; + } + + commandAddress = _cursor; + _cursor += bytes; + WriteUInt64(memory, CursorAddress, _cursor); + for (var index = 0; index < packet.Length; index++) + { + WriteUInt32(memory, commandAddress + ((ulong)index * sizeof(uint)), packet[index]); + } + + return true; + } + } + + private sealed class CountingMemory(FakeCpuMemory inner) : ICpuMemory + { + public FakeCpuMemory Inner => inner; + public ulong FailedWriteAddress { get; init; } + public int Reads { get; private set; } + public int Writes { get; private set; } + public int CursorWrites { get; private set; } + + public void ResetCounts() => (Reads, Writes, CursorWrites) = (0, 0, 0); + + public bool TryRead(ulong virtualAddress, Span destination) + { + Reads++; + return inner.TryRead(virtualAddress, destination); + } + + public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) + { + Writes++; + CursorWrites += virtualAddress == CursorAddress && source.Length == sizeof(ulong) ? 1 : 0; + var fails = FailedWriteAddress != 0 && FailedWriteAddress >= virtualAddress && + FailedWriteAddress - virtualAddress < (ulong)source.Length; + return !fails && inner.TryWrite(virtualAddress, source); + } + } + + private static ulong EmitShRegisters(ICpuMemory memory, int count) + { + var context = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = SourceAddress, + [CpuRegister.Rdx] = (ulong)count, + }; + AgcExports.CbSetShRegistersDirect(context); + return context[CpuRegister.Rax]; + } + + private static void WriteEntries(FakeCpuMemory memory, (uint Offset, uint Value)[] entries) + { + for (var index = 0; index < entries.Length; index++) + { + WriteUInt32(memory, SourceAddress + ((ulong)index * 8), entries[index].Offset); + WriteUInt32(memory, SourceAddress + ((ulong)index * 8) + 4, entries[index].Value); + } + } + + private static FakeCpuMemory Prepare(uint availableBytes) + { + var memory = new FakeCpuMemory(BaseAddress, MemorySize); + WriteUInt64(memory, CursorAddress, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, PacketAddress + availableBytes); + return memory; + } + + private static byte[] Snapshot(FakeCpuMemory memory) + { + var bytes = new byte[MemorySize]; + Assert.True(memory.TryRead(BaseAddress, bytes)); + return bytes; + } + + private static ulong ReadUInt64(FakeCpuMemory memory, ulong address) + { + Span bytes = stackalloc byte[sizeof(ulong)]; + Assert.True(memory.TryRead(address, bytes)); + return BinaryPrimitives.ReadUInt64LittleEndian(bytes); + } + + private static void WriteUInt32(FakeCpuMemory memory, ulong address, uint value) + { + Span bytes = stackalloc byte[sizeof(uint)]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, value); + Assert.True(memory.TryWrite(address, bytes)); + } + + private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value) + { + Span bytes = stackalloc byte[sizeof(ulong)]; + BinaryPrimitives.WriteUInt64LittleEndian(bytes, value); + Assert.True(memory.TryWrite(address, bytes)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs index ffdc0e531..9685f39ce 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs @@ -110,8 +110,9 @@ public void Emit_UsesOneBulkCopyAndPreservesPacket(uint valueCount) Assert.Equal(PacketAddress + 8, context[CpuRegister.Rax]); Assert.Equal(1, memory.CopyCalls); Assert.Equal((PacketAddress + 16, sourceAddress, (ulong)valueCount * 4), memory.LastCopy); - Assert.Equal(2, memory.ReadCalls); - Assert.Equal(4, memory.WriteCalls); + // One read of the buffer state, then the cursor and the marker with its header in one write each. + Assert.Equal(1, memory.ReadCalls); + Assert.Equal(2, memory.WriteCalls); Assert.Equal(0xC0001000u, ReadUInt32(memory, PacketAddress)); Assert.Equal(0x6875000Du, ReadUInt32(memory, PacketAddress + 4)); Assert.Equal(0xC0007600u | (valueCount << 16), ReadUInt32(memory, PacketAddress + 8)); @@ -155,8 +156,9 @@ public void Emit_NullValuesReservePayloadWithoutAccessingIt(uint valueCount) Assert.Equal(PacketAddress + 8, context[CpuRegister.Rax]); Assert.Equal(0, memory.CopyCalls); - Assert.Equal(2, memory.ReadCalls); - Assert.Equal(4, memory.WriteCalls); + // One read of the buffer state, then the cursor and the marker with its header in one write each. + Assert.Equal(1, memory.ReadCalls); + Assert.Equal(2, memory.WriteCalls); Assert.Equal(0xC0001000u, ReadUInt32(memory, PacketAddress)); Assert.Equal(0x6875000Du, ReadUInt32(memory, PacketAddress + 4)); Assert.Equal(0xC0007600u | (valueCount << 16), ReadUInt32(memory, PacketAddress + 8)); diff --git a/tests/SharpEmu.Libs.Tests/Cpu/ImportLeafTierTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/ImportLeafTierTests.cs new file mode 100644 index 000000000..a03eb5e49 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Cpu/ImportLeafTierTests.cs @@ -0,0 +1,50 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using System.Runtime.CompilerServices; +using SharpEmu.Core.Cpu.Native; +using SharpEmu.HLE; +using SharpEmu.Libs.Agc; +using Xunit; + +namespace SharpEmu.Libs.Tests.Cpu; + +// AGC exports that only touch guest memory through their pointer arguments take the cheaper import dispatch tiers. +public sealed class ImportLeafTierTests +{ + [Theory] + [InlineData("sceAgcSetCxRegIndirectPatchAddRegisters", "d-6uF9sZDIU")] + [InlineData("sceAgcSetShRegIndirectPatchAddRegisters", "z2duB-hHQSM")] + [InlineData("sceAgcSetUcRegIndirectPatchAddRegisters", "vRoArM9zaIk")] + [InlineData("sceAgcCreatePrimState", "D9sr1xGUriE")] + public void RegisterPatchesAndPrimitiveStateTakeTheTrivialLeafTier(string exportName, string nid) + { + Assert.Equal(nid, FindAgcNid(exportName)); + Assert.True(Classify("IsTrivialLeafImport", null, nid)); + } + + [Theory] + [InlineData("sceAgcCbSetShRegisterRangeDirect", "n2fD4A+pb+g")] + [InlineData("sceAgcDcbDrawIndexIndirect", "t1vNu082-jM")] + public void PacketWritersTakeTheLeafTier(string exportName, string nid) + { + Assert.Equal(nid, FindAgcNid(exportName)); + // Both can call the guest's buffer-full callback, so they keep the leaf tier's import call frame. + Assert.False(Classify("IsTrivialLeafImport", null, nid)); + Assert.True(Classify("IsLeafImport", RuntimeHelpers.GetUninitializedObject(typeof(DirectExecutionBackend)), nid)); + } + + private static string FindAgcNid(string exportName) => + Assert.Single(typeof(AgcExports).GetMethods(BindingFlags.Public | BindingFlags.Static) + .SelectMany(method => method.GetCustomAttributes()), + attribute => attribute.ExportName == exportName).Nid; + + private static bool Classify(string methodName, object? backend, string nid) + { + var method = typeof(DirectExecutionBackend).GetMethod(methodName, + BindingFlags.NonPublic | (backend is null ? BindingFlags.Static : BindingFlags.Instance)); + Assert.NotNull(method); + return Assert.IsType(method.Invoke(backend, [nid])); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs index e2a4495b9..db3de4e3a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs @@ -120,9 +120,10 @@ private static void GpuWrite(CacheHarness harness, ulong address, uint value) => private static void QueueRead(CacheHarness harness, ulong address) => harness.Worker.Run(() => Assert.True(harness.Cache.TrySynchronizeCpuRead(address, 4, SharpEmu.HLE.GuestMemory.GuestMemoryProfile.ReadbackSource.ShaderResourceRead))); + // The batch's GPU work completes before the hook runs: a read-ahead starts only once its writer has finished. private static void SubmitBatch(CacheHarness harness) => harness.Worker.Run(() => { - harness.Scheduler.Flush(); + harness.Scheduler.Finish(); harness.Cache.OnBatchSubmitted(); }); @@ -149,15 +150,15 @@ public void AHotWindowIsReadAheadAfterTheNextGpuWrite() harness.Shutdown(); } - // Eager readbacks are off by default: a GPU write into a hot window starts none, and the next read still lands the - // newest bytes through its own download. + // Eager readbacks are on by default. Disabled, a GPU write into a hot window starts none, and the next read still lands + // the newest bytes through its own download. [Fact] - public void AHotWindowIsNotReadAheadUnlessEagerReadbacksAreEnabled() + public void AHotWindowIsNotReadAheadWhenEagerReadbacksAreDisabled() { if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; using var harness = new CacheHarness(_vulkan); using var fatal = new FatalScope(); - Assert.False(harness.Cache.EagerReadbacksEnabled); + Assert.True(harness.Cache.EagerReadbacksEnabled); Attach(harness, _vulkan, eagerReadbacks: false); var address = harness.MapBacked(0x10000, ReadWrite); GpuWrite(harness, address, 0x01010101); @@ -210,7 +211,6 @@ public void AWindowWhoseReadAheadsKeepGoingStaleStopsBeingReadAhead() QueueRead(harness, address); GpuWrite(harness, address, 0x02020202); - Assert.True(harness.Cache.HotWritePending); var value = 0x03030303u; var deadline = DateTime.UtcNow.AddSeconds(20); while (harness.Cache.EagerReadbacksWasted < 3 && DateTime.UtcNow < deadline) @@ -223,7 +223,6 @@ public void AWindowWhoseReadAheadsKeepGoingStaleStopsBeingReadAhead() SubmitBatch(harness); var started = harness.Cache.EagerReadbacksStarted; GpuWrite(harness, address, 0x07070707); - Assert.False(harness.Cache.HotWritePending); SubmitBatch(harness); SubmitBatch(harness); @@ -317,6 +316,7 @@ public void AGuestReadOffTheQueueIsReadAheadToo() harness.Shutdown(); } + // Sixteen read-aheads run at a time; one more waits for a landing. [Fact] public void AReadAheadDeferredForASlotStartsLater() { @@ -325,7 +325,8 @@ public void AReadAheadDeferredForASlotStartsLater() using var fatal = new FatalScope(); Attach(harness, _vulkan); const ulong window = 0x80000; - const int windows = 5; + const int inFlight = 16; + const int windows = inFlight + 1; var address = harness.MapBacked(window * windows, ReadWrite); for (var index = 0; index < windows; index++) { @@ -339,7 +340,7 @@ public void AReadAheadDeferredForASlotStartsLater() } SubmitBatch(harness); - Assert.Equal(4, harness.Cache.EagerReadbacksStarted); + Assert.Equal(inFlight, harness.Cache.EagerReadbacksStarted); var deadline = DateTime.UtcNow.AddSeconds(10); while (harness.Cache.EagerReadbacksStarted < windows && DateTime.UtcNow < deadline) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferEagerReadbackTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferEagerReadbackTests.cs new file mode 100644 index 000000000..a1359f8ff --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferEagerReadbackTests.cs @@ -0,0 +1,152 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GuestMemory; +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; +using static SharpEmu.Libs.Tests.Gpu.Scheduling.SchedulingTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +[Collection(SchedulingStateCollection.Name)] +public sealed class GuestBufferEagerReadbackTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan = fixture.Vulkan; + + // The pump leaves a read-ahead alone until its writer's tick completes, then starts it and lands it without a guest read. + [Fact] + public void AReadAheadWaitsForItsWriterAndLandsWithoutAGuestRead() + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + using var fatal = new FatalScope(); + Attach(harness, _vulkan); + try + { + var address = harness.MapBacked(0x10000, ReadWrite); + GpuWrite(harness, address, 0x01010101); + QueueRead(harness, address); + + GpuWrite(harness, address, 0x02020202); + harness.Worker.Run(() => harness.Cache.PumpEagerReadbacks()); + Assert.Equal(0, harness.Cache.EagerReadbacksStarted); + + harness.Worker.Run(() => harness.Scheduler.Finish()); + Assert.True(WaitUntil(() => + { + harness.Worker.Run(() => harness.Cache.PumpEagerReadbacks()); + return harness.Cache.EagerReadbacksStarted == 1; + })); + Assert.True(WaitUntil(() => + { + harness.Worker.Run(() => harness.Cache.PumpEagerReadbacks()); + return !harness.Cache.HasGpuDirtyBytes(address, 0x100); + })); + + Assert.Equal(0x02020202u, BitConverter.ToUInt32(harness.Read(address + 0x40, 4))); + } + finally + { + Detach(harness); + harness.Shutdown(); + } + } + + // A small buffer has one hot entry: a write in another readback window of the same buffer still reads it ahead. + [Fact] + public void AWriteAnywhereInASmallHotBufferReadsItAhead() + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + using var fatal = new FatalScope(); + Attach(harness, _vulkan); + try + { + const ulong window = 0x80000; + var mapping = harness.MapBacked(0x100000, ReadWrite); + var boundary = (mapping + 0x4000 + window - 1) & ~(window - 1); + var start = boundary - 0x4000; + harness.Worker.Run(() => _ = harness.Cache.ObtainBuffer(start, 0x8000, isWritten: false)); + GpuWrite(harness, start, 0x01010101); + QueueRead(harness, start); + + GpuWrite(harness, boundary, 0x02020202); + SubmitBatchAfterItsWork(harness); + Assert.Equal(1, harness.Cache.EagerReadbacksStarted); + QueueRead(harness, boundary); + + Assert.Equal(1, harness.Cache.EagerReadbacksUsed); + Assert.Equal(0x02020202u, BitConverter.ToUInt32(harness.Read(boundary + 0x40, 4))); + } + finally + { + Detach(harness); + harness.Shutdown(); + } + } + + // A hot entry outlives a thousand batches without a read. + [Fact] + public void AHotWindowStaysHotAcrossManyBatches() + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + using var fatal = new FatalScope(); + Attach(harness, _vulkan); + try + { + var address = harness.MapBacked(0x10000, ReadWrite); + GpuWrite(harness, address, 0x01010101); + QueueRead(harness, address); + harness.Worker.Run(() => + { + for (var batch = 0; batch < 1000; batch++) + { + harness.Cache.OnBatchSubmitted(); + } + }); + + GpuWrite(harness, address, 0x02020202); + SubmitBatchAfterItsWork(harness); + Assert.Equal(1, harness.Cache.EagerReadbacksStarted); + QueueRead(harness, address); + + Assert.Equal(1, harness.Cache.EagerReadbacksUsed); + Assert.Equal(0x02020202u, BitConverter.ToUInt32(harness.Read(address + 0x40, 4))); + } + finally + { + Detach(harness); + harness.Shutdown(); + } + } + + private static void Attach(CacheHarness harness, HeadlessVulkan vulkan) => + harness.Cache.AsyncReadback = new VulkanAsyncReadback(vulkan.DeviceInfo, harness.Scheduler, vulkan.Queue, vulkan.QueueFamily); + + private static void Detach(CacheHarness harness) => harness.Worker.Run(() => + { + harness.Cache.Shutdown(); + harness.Cache.AsyncReadback?.Dispose(); + harness.Cache.AsyncReadback = null; + }); + + private static void GpuWrite(CacheHarness harness, ulong address, uint value) => harness.Worker.Run(() => + { + var (buffer, offset) = harness.Cache.ObtainBuffer(address, 0x100, isWritten: true); + buffer.Fill(offset, 0x100, value); + }); + + private static void QueueRead(CacheHarness harness, ulong address) => harness.Worker.Run(() => + Assert.True(harness.Cache.TrySynchronizeCpuRead(address, 4, GuestMemoryProfile.ReadbackSource.ShaderResourceRead))); + + private static void SubmitBatchAfterItsWork(CacheHarness harness) => harness.Worker.Run(() => + { + harness.Scheduler.Finish(); + harness.Cache.OnBatchSubmitted(); + }); +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferWindowSweepTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferWindowSweepTests.cs new file mode 100644 index 000000000..8a33bcd62 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferWindowSweepTests.cs @@ -0,0 +1,102 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +// A device-address program that reaches only its handles' windows sweeps the mapped spans inside them. +[Collection(SchedulingStateCollection.Name)] +public sealed class GuestBufferWindowSweepTests : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan; + + public GuestBufferWindowSweepTests(HeadlessVulkanFixture fixture) => _vulkan = fixture.Vulkan; + + [Fact] + public void TheMappedSpansAreCutToTheMergedWindows() + { + var spans = new List { new(0x1000, 0x3000), new(0x10000, 0x2000), new(0x20000, 0x1000) }; + var windows = new List<(ulong Start, ulong End)> { (0x11000, 0x18000), (0x2000, 0x3000), (0x2800, 0x11800) }; + var clipped = new List(); + + GuestBufferCache.ClipSpansToWindows(spans, windows, clipped); + + Assert.Equal([new GuestSpan(0x2000, 0x2000), new GuestSpan(0x10000, 0x2000)], clipped); + Assert.Equal([(0x2000ul, 0x18000ul)], windows); + } + + [Fact] + public void NoWindowsLeaveNothingToSweep() + { + var clipped = new List { new(1, 1) }; + + GuestBufferCache.ClipSpansToWindows([new GuestSpan(0x1000, 0x1000)], [], clipped); + + Assert.Empty(clipped); + } + + // A windowed preparation uploads the dirty pages inside its windows and leaves the others dirty for a later sweep. + [Fact] + public void AWindowedPreparationSweepsOnlyItsWindows() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x40000, ReadWrite); + var (first, firstOffset) = harness.Worker.Run(() => harness.Cache.ObtainBuffer(address, 0x8000, isWritten: false)); + var (second, secondOffset) = harness.Worker.Run(() => harness.Cache.ObtainBuffer(address + 0x20000, 0x8000, isWritten: false)); + var spans = new List { new(address, 0x40000) }; + var mapping = GuestBufferCache.MappingKey(spans); + harness.Worker.Run(() => harness.Cache.PrepareBda(spans, mapping)); + + Assert.True(harness.Store.MarkCpuWrite(address + 0x1000, 8)); + harness.Write(address + 0x1000, Pattern(0x20, 1)); + Assert.True(harness.Store.MarkCpuWrite(address + 0x21000, 8)); + harness.Write(address + 0x21000, Pattern(0x20, 2)); + var window = new List { new(address, 0x10000) }; + harness.Worker.Run(() => harness.Cache.PrepareWindowedBda(window, GuestBufferCache.MappingKey(window), mapping)); + + Assert.Equal(Pattern(0x20, 1), harness.ReadBack(first, firstOffset + 0x1000, 0x20)); + Assert.False(harness.Cache.HasCpuDirtyPages(address + 0x1000, 0x20)); + Assert.True(harness.Cache.HasCpuDirtyPages(address + 0x21000, 0x20)); + Assert.NotEqual(Pattern(0x20, 2), harness.ReadBack(second, secondOffset + 0x1000, 0x20)); + + harness.Worker.Run(() => harness.Cache.PrepareBda(spans, mapping)); + Assert.Equal(Pattern(0x20, 2), harness.ReadBack(second, secondOffset + 0x1000, 0x20)); + Assert.False(harness.Cache.HasCpuDirtyPages(address + 0x21000, 0x20)); + harness.Shutdown(); + } + + // The window's own state: a second windowed preparation with nothing new written sweeps nothing, and a write inside the + // window is taken by the next one. + [Fact] + public void AWindowKeepsItsOwnSweepState() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x40000, ReadWrite); + var (first, firstOffset) = harness.Worker.Run(() => harness.Cache.ObtainBuffer(address, 0x8000, isWritten: false)); + var spans = new List { new(address, 0x40000) }; + var mapping = GuestBufferCache.MappingKey(spans); + var window = new List { new(address, 0x10000) }; + var windowMapping = GuestBufferCache.MappingKey(window); + harness.Worker.Run(() => harness.Cache.PrepareWindowedBda(window, windowMapping, mapping)); + var sweeps = Interlocked.Read(ref GuestBufferCache.BdaSweeps); + harness.Worker.Run(() => harness.Cache.PrepareWindowedBda(window, windowMapping, mapping)); + Assert.Equal(sweeps, Interlocked.Read(ref GuestBufferCache.BdaSweeps)); + + Assert.True(harness.Store.MarkCpuWrite(address + 0x2000, 8)); + harness.Write(address + 0x2000, Pattern(0x20, 3)); + harness.Worker.Run(() => harness.Cache.PrepareWindowedBda(window, windowMapping, mapping)); + Assert.Equal(Pattern(0x20, 3), harness.ReadBack(first, firstOffset + 0x2000, 0x20)); + harness.Shutdown(); + } + + private static byte[] Pattern(int size, byte seed) => Enumerable.Range(0, size).Select(index => (byte)(seed * 37 + index)).ToArray(); +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs index ef75f538b..cc746add9 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs @@ -29,6 +29,10 @@ public RecordingCommandStreamHost() public Func? ReadOcclusionSamples { get; set; } + public SharpEmu.Libs.Gpu.Pipelines.ComputeTickets? ComputeTickets { get; set; } + + public IDeferredDispatchRuns? DispatchRuns { get; set; } + public Func? PendingPublications { get; set; } public Func? GpuWrittenCommandData { get; set; } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs new file mode 100644 index 000000000..0f7e8d2bc --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs @@ -0,0 +1,179 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; + +// The interpreter's side of a deferred dispatch run, with an engine that issues every dispatch and can roll the run back +// once at its barrier. +public sealed class DeferredDispatchRunTests +{ + private const uint ComputeUserData0 = 0x240; + private const uint PixelProgramLow = 0x008; + private const uint CacheFlushEvent = 0x07; + + private sealed class FakeRuns(GpuCommandInterpreter interpreter) : IDeferredDispatchRuns + { + private bool _open; + private bool _suppressed; + + public List<(DeferredIssueSite Site, ComputeStageRegisters Compute)> Issued { get; } = new(); + + public int RewindTo { get; set; } = -1; + + public int Barriers { get; private set; } + + public int Tables { get; private set; } + + public bool IsOpen => _open; + + public bool Active => _open || _suppressed; + + public bool StopsTicketScan => false; + + public bool WouldDefer(ComputeStageRegisters compute, uint initiator) => false; + + public DeferredIssue TryIssue(in DeferredIssueSite site, uint groupsX, uint groupsY, uint groupsZ, uint initiator) + { + if (_suppressed) + { + return DeferredIssue.NotEligible; + } + + Issued.Add((site, interpreter.TypedRegisters.Shader.Compute.Copy())); + _open = true; + return DeferredIssue.Issued; + } + + public DeferredRewind? Barrier() + { + Barriers++; + if (!_open) + { + _suppressed = false; + return null; + } + + _open = false; + if (RewindTo < 1) + { + return null; + } + + // A poisoned table of member RewindTo: the state at the issue of the member before it. + var (site, compute) = Issued[RewindTo - 1]; + RewindTo = -1; + _suppressed = true; + return new DeferredRewind + { + Depth = site.Depth, + CursorAddress = site.CursorAddress, + Offset = site.PacketOffset + 5, + Compute = compute, + RawUndoMark = site.RawUndoMark, + UserDataMarker = site.UserDataMarker, + }; + } + + public bool NoteTable(ulong address, ulong size) + { + Tables++; + return true; + } + + public void BreakChain() + { + } + } + + private static uint[] UserData(uint value) => StreamRunner.Packet(PacketOpcode.SetShaderRegister, ComputeUserData0, value); + + private static uint[] Dispatch(uint groups) => StreamRunner.Packet(PacketOpcode.DispatchDirect, groups, 1, 1, 0x41); + + [Fact] + public void RollbackRunsThePacketsAgainFromThePoisonedMemberWithItsRegisters() + { + var runner = new StreamRunner(); + var runs = new FakeRuns(runner.Interpreter) { RewindTo = 1 }; + runner.Host.DispatchRuns = runs; + + runner.Run( + UserData(0xA), Dispatch(1), + UserData(0xB), Dispatch(2), + UserData(0xC), Dispatch(3), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, PixelProgramLow, 0x1234)); + + // The three members went to the engine; the barrier at the pixel register rolled the run back to member 1, whose + // packets ran again on the stream with the registers member 0 was issued under. + Assert.Equal(3, runs.Issued.Count); + Assert.Equal(new[] { 0xAu, 0xBu, 0xCu }, runs.Issued.Select(static entry => entry.Compute.UserScalars.ValueSpan(1)[0])); + Assert.Equal(new[] { "dispatch 0 2 1 1 41", "dispatch 0 3 1 1 41" }, runner.Host.Calls); + Assert.Equal(0xCu, runner.Interpreter.Registers.Shader[ComputeUserData0]); + Assert.Equal(0xCu, runner.Interpreter.TypedRegisters.Shader.Compute.UserScalars.ValueSpan(1)[0]); + Assert.Equal(0x1234u, runner.Interpreter.Registers.Shader[PixelProgramLow]); + Assert.False(runs.Active); + } + + [Fact] + public void RunCloseAtTheBufferEndKeepsEveryMember() + { + var runner = new StreamRunner(); + var runs = new FakeRuns(runner.Interpreter); + runner.Host.DispatchRuns = runs; + + runner.Run(UserData(0xA), Dispatch(1), UserData(0xB), Dispatch(2)); + + Assert.Equal(2, runs.Issued.Count); + Assert.Empty(runner.Host.Calls); + Assert.Equal(1, runs.Barriers); + Assert.False(runs.Active); + Assert.Equal(0xBu, runner.Interpreter.Registers.Shader[ComputeUserData0]); + } + + [Fact] + public void ACacheFlushEventStaysInsideTheRun() + { + var runner = new StreamRunner(); + var runs = new FakeRuns(runner.Interpreter); + runner.Host.DispatchRuns = runs; + + runner.Run(UserData(0xA), Dispatch(1), StreamRunner.Packet(PacketOpcode.EventWrite, CacheFlushEvent), UserData(0xB), Dispatch(2)); + + // The event queued its barrier in stream order without closing the run; only the buffer end did. + Assert.Equal(2, runs.Issued.Count); + Assert.Equal(new[] { "barrier" }, runner.Host.Calls); + Assert.Equal(1, runs.Barriers); + } + + [Fact] + public void AGraphicsShaderRegisterClosesTheRunBeforeItApplies() + { + var runner = new StreamRunner(); + var runs = new FakeRuns(runner.Interpreter); + runner.Host.DispatchRuns = runs; + + runner.Run(UserData(0xA), Dispatch(1), StreamRunner.Packet(PacketOpcode.SetShaderRegister, PixelProgramLow, 0x1234), UserData(0xB), Dispatch(2)); + + // The pixel register is no run packet: the first run closed before it, and the second dispatch opened another run. + Assert.Equal(2, runs.Issued.Count); + Assert.Equal(2, runs.Barriers); + Assert.Equal(0x1234u, runner.Interpreter.Registers.Shader[PixelProgramLow]); + } + + [Fact] + public void MirrorRestorePutsBackAnUnwrittenRegister() + { + var mirror = new ShaderRegisterMirror(); + mirror[0x241] = 5; + var before = mirror.Peek(0x242); + mirror[0x242] = 7; + mirror.Restore(0x242, before.Value, before.Written); + + Assert.False(mirror.ContainsKey(0x242)); + Assert.Single(mirror); + Assert.Equal(5u, mirror[0x241]); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ResolveReadLogTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ResolveReadLogTests.cs index 7fc14fe67..4c0b4f427 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ResolveReadLogTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ResolveReadLogTests.cs @@ -35,6 +35,26 @@ public void KeepsEveryReadWithItsAddressAndGrowsPastItsInitialCapacity() Assert.Equal(new byte[] { 0x44, 0x33, 0x22, 0x11 }, word.ToArray()); } + // A clean read is checked again at the take with the command thread's clean test, so it never merges with a plain read + // next to it; reads of one class still merge. + [Fact] + public void AdjacentReadsMergeOnlyWithinTheirClass() + { + var log = new ResolveReadLog(); + log.Add(0x1000, new byte[] { 1, 2, 3, 4 }, clean: true); + log.Add(0x1004, new byte[] { 5, 6, 7, 8 }, clean: true); + log.Add(0x1008, new byte[] { 9, 10, 11, 12 }); + log.Add(0x100C, new byte[] { 13, 14, 15, 16 }); + + Assert.Equal(2, log.Count); + Assert.True(log.IsClean(0)); + Assert.False(log.IsClean(1)); + Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, log.Bytes(0, out var clean).ToArray()); + Assert.Equal(0x1000UL, clean); + Assert.Equal(new byte[] { 9, 10, 11, 12, 13, 14, 15, 16 }, log.Bytes(1, out var plain).ToArray()); + Assert.Equal(0x1008UL, plain); + } + [Fact] public void AdjacentReadsMergeIntoOneRange() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs index e578f790d..4b8f7580d 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs @@ -36,9 +36,9 @@ private static ImageRequest BlockAliasArray(ulong address, uint viewLayers) return request; } - // An image the guest has not touched for more than the removal window, nor since the frame ended, may be deleted - // by an overlapping request. - private static void AgeBeyondTheRemovalWindow(CacheHarness harness, ResourceSlotIdentifier imageIdentifier, bool endFrame = true) + // An image the guest has not touched for more than the removal window, nor since the frame ended, may be deleted by an + // overlapping request (an image used in each of the two frames before still counts as used this frame). + private static void AgeBeyondTheRemovalWindow(CacheHarness harness, ResourceSlotIdentifier imageIdentifier, int framesEnded = 2) { for (var pass = 0; pass < 100 && harness.Scheduler.CurrentTick <= 40; pass++) { @@ -47,7 +47,7 @@ private static void AgeBeyondTheRemovalWindow(CacheHarness harness, ResourceSlot Assert.True(harness.Scheduler.CurrentTick > 40); harness.Image(imageIdentifier).LastAccessTick = 0; - if (endFrame) + for (var frame = 0; frame < framesEnded; frame++) { harness.Worker.Run(() => harness.Images.RunGarbageCollector()); } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Lookup.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Lookup.cs index 8c500d2a5..980770c28 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Lookup.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Lookup.cs @@ -74,11 +74,12 @@ public void FindImage_ADifferentViewIsNotReused() // A title submits dozens of command buffers per frame. An image it writes early in a frame and reads late in it // is past the removal window of submissions in between, and an unrelated image the frame requested inside its // memory deleted it with its contents: its next use uploaded stale guest memory. An image used this frame stays; - // after the frame ends, the overlapping request parks it with its contents. + // once its frame has ended, the overlapping request parks it with its contents. [Theory] - [InlineData(false)] - [InlineData(true)] - public void FindImage_AnUnrelatedImageInsideAnImageUsedThisFrameKeepsItsContents(bool frameEnded) + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void FindImage_AnUnrelatedImageInsideAnImageUsedThisFrameKeepsItsContents(int framesEnded) { if (!GatePrerequisites.Ready(_vulkan)) return; using var harness = new CacheHarness(_vulkan); @@ -89,20 +90,49 @@ public void FindImage_AnUnrelatedImageInsideAnImageUsedThisFrameKeepsItsContents new Extent3D(width, width, 1), 1, 4, 1); var writtenId = harness.Acquire(ref written); Assert.True(harness.Worker.Run(() => harness.Images.TryClearImageFromBuffer(address, width * width * 4, deviceValue))); - AgeBeyondTheRemovalWindow(harness, writtenId, endFrame: frameEnded); + AgeBeyondTheRemovalWindow(harness, writtenId, framesEnded); var inside = LinearRequest(address + 0x8000, 0x4000, Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, new Extent3D(64, 64, 1), 1, 4, 1); harness.Acquire(ref inside); Assert.True(harness.Images.Contains(writtenId)); - Assert.Equal(frameEnded, harness.Image(writtenId).Parked); + Assert.Equal(framesEnded != 0, harness.Image(writtenId).Parked); Assert.True(harness.Image(writtenId).IsGpuModified); Assert.Equal(Bytes(Enumerable.Repeat(deviceValue, (int)(width * width)).ToArray()), harness.ReadImageBytes(harness.Image(writtenId))); harness.Shutdown(); } + // Two aliases of the same memory that a title uses every frame swapped at each one's first use in a frame, each + // request parking the other. An image used in each of the two frames before is a recurring alias and stays + // registered; an image used in one frame only is parked after it, as above. + [Fact] + public void FindImage_AnImageUsedInEachOfTheTwoFramesBeforeStaysRegistered() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + const uint width = 128; + var address = harness.MapBacked(0x20000, ReadWrite); + var first = LinearRequest(address, width * width * 4, Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, + new Extent3D(width, width, 1), 1, 4, 1); + var recurringId = harness.Acquire(ref first); + harness.Worker.Run(() => harness.Images.RunGarbageCollector()); + var second = LinearRequest(address, width * width * 4, Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, + new Extent3D(width, width, 1), 1, 4, 1); + Assert.Equal(recurringId, harness.Acquire(ref second)); + AgeBeyondTheRemovalWindow(harness, recurringId, framesEnded: 1); + + var inside = LinearRequest(address + 0x8000, 0x4000, Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, + new Extent3D(64, 64, 1), 1, 4, 1); + harness.Acquire(ref inside); + + Assert.True(harness.Images.Contains(recurringId)); + Assert.False(harness.Image(recurringId).Parked); + + harness.Shutdown(); + } + [Fact] public void FindImage_AnImageFilledFromGuestMemoryIsParkedAndReusedWithTheNewerBytes() { @@ -115,7 +145,7 @@ public void FindImage_AnImageFilledFromGuestMemoryIsParkedAndReusedWithTheNewerB new Extent3D(width, width, 1), 1, 4, 1); var filledId = harness.Acquire(ref filled); Assert.False(harness.Image(filledId).IsGpuModified); - AgeBeyondTheRemovalWindow(harness, filledId, endFrame: true); + AgeBeyondTheRemovalWindow(harness, filledId); var inside = LinearRequest(address + 0x8000, 0x4000, Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, new Extent3D(64, 64, 1), 1, 4, 1); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs index 1847896df..449f1e630 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs @@ -851,4 +851,79 @@ public void Unregister_DropsMetadataInTheRange() Assert.True(harness.Images.IsMetadata(address + 0x3000)); harness.Shutdown(); } + + private static ImageViewDescription LayerView(uint baseLayer, uint layerCount, ImageViewType type = ImageViewType.Type2D) => + ImageViewDescription.Default with { Type = type, BaseLayer = baseLayer, LayerCount = layerCount }; + + [Fact] + public void ConsumedClears_PassOnlyTheLayersTheyLeft() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x10000, ReadWrite); + var metadata = address + 0x1000; + harness.Images.RegisterHtileMetadataForTest(metadata); + var generation = harness.Images.MetadataGeneration; + + Assert.True(harness.Images.ClearMetadata(metadata)); + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, metadata, LayerView(0, 1))); + + Assert.True(harness.Images.SetMetadataSlice(metadata, 0, false)); + Assert.True(harness.Images.ConsumedClearsOnlyForTest(generation, metadata, LayerView(0, 1))); + // Layer 1 still waits on its clear: a view that covers it, or a 3D view, does not pass. + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, metadata, LayerView(0, 2))); + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, metadata, LayerView(0, 1, ImageViewType.Type3D))); + harness.Shutdown(); + } + + [Fact] + public void ConsumedClears_IncludeATrackedDccFill() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x10000, ReadWrite); + var metadata = address + 0x4000; + harness.Images.RegisterDccMetadataForTest(metadata, 0x1000); + var generation = harness.Images.MetadataGeneration; + Assert.True(harness.Images.TryAbsorbDccFill(metadata, 0x1000, 0x00000000u)); + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, metadata, LayerView(0, 1))); + + Assert.True(harness.Images.SetMetadataSlice(metadata, 0, false)); + Assert.True(harness.Images.ConsumedClearsOnlyForTest(generation, metadata, LayerView(0, 1))); + harness.Shutdown(); + } + + [Fact] + public void ConsumedClears_ExcludeRegistrationsInvalidationsAndAnOverflowedRing() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x10000, ReadWrite); + + // A fill seen before its target registers a pending entry. + var pending = address + 0x1000; + var generation = harness.Images.MetadataGeneration; + Assert.False(harness.Images.TryAbsorbDccFill(pending, 0x100, 0xc0c0c0c0u)); + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, pending, LayerView(0, 1))); + + // A CPU write over registered DCC metadata invalidates it. + var dcc = address + 0x4000; + harness.Images.RegisterDccMetadataForTest(dcc, 0x1000); + generation = harness.Images.MetadataGeneration; + harness.ImageStore.MarkCpuWrite(dcc + 0x10, 8); + Assert.False(harness.Images.IsMetadata(dcc)); + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, dcc, LayerView(0, 1))); + + // More events than the ring holds since the segment began. + var htile = address + 0x8000; + harness.Images.RegisterHtileMetadataForTest(htile); + generation = harness.Images.MetadataGeneration; + for (var index = 0; index < 1100; index++) + { + Assert.True(harness.Images.SetMetadataSlice(htile, 0, index % 2 == 0)); + } + + Assert.False(harness.Images.ConsumedClearsOnlyForTest(generation, htile, LayerView(1, 1))); + harness.Shutdown(); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.NativeColorClear.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.NativeColorClear.cs index b49bb3c2b..140708a63 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.NativeColorClear.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.NativeColorClear.cs @@ -111,6 +111,37 @@ public void NativeColorClearIsSettledOnlyWhileTheRegistrationIsCurrentAndNoSlice harness.Shutdown(); } + [Fact] + public void NativeColorClearPredictionSeparatesARegistrationUpdateFromAClear() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x20000, ReadWrite); + var metadataAddress = address + 0x10000; + var target = AsColorTarget(LinearRequest(address, 8, Format.R16G16B16A16Sfloat, + GuestPixelFormat.Bits16_16_16_16Float, GuestImageType.Color2D, new Extent3D(1, 1, 1), 1, 8, 1)); + target.Description.Metadata.Kind = MetadataKind.Dcc; + target.Description.Metadata.Range = new GuestSpan(metadataAddress, 4096); + target.Description.Metadata.NativeColorClear = true; + target.Description.Metadata.PackedColorClearSupported = true; + target.Description.Metadata.PackedColorClear = new ClearColorValue(0f, 0f, 1f, 1f); + harness.Write(metadataAddress, Enumerable.Repeat((byte)0xFF, 4096).ToArray()); + var identifier = harness.Find(ref target); + + // No slice holds a clear code: the apply would only register the metadata. + Assert.Equal(NativeColorClearPrediction.RegistrationOnly, harness.Images.PredictNativeColorClear(identifier, target)); + harness.Worker.Run(() => harness.Images.ApplyNativeColorClear(identifier, target)); + Assert.Equal(NativeColorClearPrediction.Settled, harness.Images.PredictNativeColorClear(identifier, target)); + + harness.Write(metadataAddress, Enumerable.Repeat((byte)0x20, 4096).ToArray()); + Assert.Equal(NativeColorClearPrediction.ClearCode, harness.Images.PredictNativeColorClear(identifier, target)); + + var outside = target; + outside.Description.Metadata.ColorMetadataBaseLayer = 1; + Assert.Equal(NativeColorClearPrediction.BadView, harness.Images.PredictNativeColorClear(identifier, outside)); + harness.Shutdown(); + } + [Theory] [InlineData(0u, false, true)] [InlineData(0u, true, false)] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SliceDepthClears.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SliceDepthClears.cs new file mode 100644 index 000000000..277ca28df --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SliceDepthClears.cs @@ -0,0 +1,46 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Silk.NET.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +// A slice segment whose join applies a depth view's pending HTILE clear itself. +public sealed partial class GuestImageCacheTests +{ + [Fact] + public void SliceJoin_ADepthUseWithAClearEntryPassesAPendingClear() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x20000, ReadWrite); + var metadataAddress = address + 0x10000; + var depth = AsDepthTarget(LinearRequest(address + 0x8000, 4, Format.D32Sfloat, + GuestPixelFormat.Bits32Float, GuestImageType.Color2D, new Extent3D(1, 1, 1), 1, 4, 1), Format.D32Sfloat); + depth.Description.Metadata.Kind = MetadataKind.Htile; + depth.Description.Metadata.Range = new GuestSpan(metadataAddress, 0x100); + var identifier = harness.Acquire(ref depth); + Assert.True(harness.Images.SetMetadataSlice(metadataAddress, 0, false)); + List uses = [new ImageSliceUse(identifier, harness.Image(identifier), depth)]; + var lookup = harness.Images.LookupGeneration; + var metadata = harness.Images.MetadataGeneration; + Assert.True(harness.Images.ClearMetadata(metadataAddress)); + + // The clear still waits on the view's slice: only an entry for the same view lets the use pass. + Assert.False(harness.Images.ValidateSliceImages(uses, lookup, metadata)); + Assert.True(harness.Images.ValidateSliceImages(uses, lookup, metadata, [(identifier, depth.View)])); + Assert.False(harness.Images.ValidateSliceImages(uses, lookup, metadata, [(identifier, depth.View with { BaseLayer = 1 })])); + + // An event other than a clear-state change fails the use with an entry too. + harness.ImageStore.MarkCpuWrite(metadataAddress + 0x10, 8); + Assert.False(harness.Images.ValidateSliceImages(uses, lookup, metadata, [(identifier, depth.View)])); + harness.Shutdown(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs new file mode 100644 index 000000000..3b44046d9 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs @@ -0,0 +1,284 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.GpuCommands; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// SHARPEMU_COMPUTE_TICKETS: worker rebinds a direct dispatch takes in place of its own. +[Collection(SchedulingStateCollection.Name)] +public sealed class ComputeTicketTests +{ + private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong HeaderAddress = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong PacketAddress = 0x100; + private const uint Initiator = 0x8001; + private static readonly object Owner = new(); + + [Fact] + public void ATicketServesTheRebindTheCommandThreadWouldMake() + { + using var fatal = new FatalScope(); + var (cache, tickets) = CreateCache(workers: 0); + var banks = KeptBanks(cache, out var first); + banks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + + var taken = Dispatch(cache, tickets, banks, PacketAddress); + + Assert.Equal(1, tickets.Served); + Assert.Equal(first.Program, taken.Program); + Assert.Equal(0x1234u, taken.Input.Stage.Resources.UserData[0]); + var (serialCache, _) = CreateCache(workers: 0); + serialCache.Tickets = null; + var serialBanks = KeptBanks(serialCache, out _); + serialBanks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + var serial = serialCache.GetComputeProgram(serialBanks, Initiator, 1, 1, 1); + Assert.Equal(serial.Input.Stage.Resources.UserData, taken.Input.Stage.Resources.UserData); + } + + [Fact] + public void ChangedRegistersRefuseTheTicket() + { + using var fatal = new FatalScope(); + var (cache, tickets) = CreateCache(workers: 0); + var banks = KeptBanks(cache, out _); + banks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + banks.Shader.Compute.UserScalars.Set(0, 0x5678, UserScalarKind.Unknown); + + var program = Dispatch(cache, tickets, banks, PacketAddress); + + Assert.Equal(0, tickets.Served); + Assert.Equal(0x5678u, program.Input.Stage.Resources.UserData[0]); + } + + [Fact] + public void ChangedReadsRefuseTheTicket() + { + using var fatal = new FatalScope(); + var (cache, tickets) = CreateCache(workers: 0, validate: static _ => false); + var banks = KeptBanks(cache, out _); + banks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + + var program = Dispatch(cache, tickets, banks, PacketAddress); + + Assert.Equal(0, tickets.Served); + Assert.Equal(0x1234u, program.Input.Stage.Resources.UserData[0]); + } + + [Fact] + public void AnUnfinishedTicketIsNotTaken() + { + using var fatal = new FatalScope(); + var (cache, tickets) = CreateCache(workers: -1); + var banks = KeptBanks(cache, out _); + banks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + + var program = Dispatch(cache, tickets, banks, PacketAddress); + tickets.RunManual(); + + Assert.Equal(0, tickets.Served); + Assert.Equal(1, tickets.NotReady); + Assert.Equal(0x1234u, program.Input.Stage.Resources.UserData[0]); + } + + [Fact] + public void ATicketForAnEarlierPacketIsDropped() + { + using var fatal = new FatalScope(); + var (cache, tickets) = CreateCache(workers: 0); + var banks = KeptBanks(cache, out _); + banks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + + Dispatch(cache, tickets, banks, PacketAddress + 0x20); + + Assert.Equal(0, tickets.Served); + Assert.Equal(1, tickets.Unused); + Assert.Equal(0, tickets.LeadCount); + } + + [Fact] + public void ADispatchWithoutAKeptProgramRequestsNoTicket() + { + using var fatal = new FatalScope(); + var (_, tickets) = CreateCache(workers: 0); + var banks = Banks(); + + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + + Assert.Equal(0, tickets.Requested); + Assert.Equal(0, tickets.LeadCount); + } + + [Fact] + public void VerifyComparesEveryTakenTicketWithTheSerialRebind() + { + using var fatal = new FatalScope(); + var (cache, tickets) = CreateCache(workers: 0, verify: true); + var banks = KeptBanks(cache, out _); + banks.Shader.Compute.UserScalars.Set(0, 0x1234, UserScalarKind.Unknown); + tickets.Request(Owner, PacketAddress, banks.Shader.Compute, 1, 1, 1, Initiator); + + var program = Dispatch(cache, tickets, banks, PacketAddress); + + Assert.Equal(1, tickets.Served); + Assert.Equal(1, tickets.Verified); + Assert.Equal(0, tickets.Mismatches); + Assert.Equal(0x1234u, program.Input.Stage.Resources.UserData[0]); + } + + [Fact] + public void ADispatchScansTheDispatchesThatFollowItUntilAnotherPacket() + { + var (_, tickets) = CreateCache(workers: 0); + var requested = new List(); + tickets.RequestObserver = (_, compute, x, y, z, initiator) => + requested.Add($"{compute.UserScalars.ValueSpan(1)[0]:X} {x} {y} {z} {initiator:X}"); + var runner = new StreamRunner(); + runner.Host.ComputeTickets = tickets; + + runner.Run( + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeUserData0, 0x11), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 1, 1, 1, 0x41), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeUserData0, 0x22), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 2, 1, 1, 0x41), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeUserData0, 0x33), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 3, 1, 1, 0x41), + StreamRunner.Packet(PacketOpcode.SetContextRegister, RegisterBankLayout.ContextNop, 0), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeUserData0, 0x44), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 4, 1, 1, 0x41)); + + Assert.Equal(new[] { "22 2 1 1 41", "33 3 1 1 41" }, requested); + Assert.Equal(4, runner.Host.Calls.Count(call => call.StartsWith("dispatch", StringComparison.Ordinal))); + } + + // Guests set a dispatch's user data through register tables as often as through register writes; events and annotation + // markers change no register. + [Fact] + public void TheScanFollowsShaderRegisterTablesAndPassesEventsAndMarkers() + { + var (_, tickets) = CreateCache(workers: 0); + var requested = new List(); + tickets.RequestObserver = (_, compute, x, _, _, _) => requested.Add($"{compute.UserScalars.ValueSpan(1)[0]:X} {x}"); + var runner = new StreamRunner(); + runner.Host.ComputeTickets = tickets; + const ulong nopTable = StreamRunner.TableAddress; + const ulong indirectTable = StreamRunner.TableAddress + 0x100; + runner.Host.WriteWords(nopTable, new uint[] { ShaderRegisterOffset.ComputeUserData0, 0x22 }); + runner.Host.WriteWords(indirectTable, new uint[] { ShaderRegisterOffset.ComputeUserData0, 0x33 }); + + runner.Run( + StreamRunner.Packet(PacketOpcode.DispatchDirect, 1, 1, 1, 0x41), + StreamRunner.CustomPacket(PacketOpcode.Nop, PacketCustomCode.ShaderRegisterTable, 1, StreamRunner.Low(nopTable), StreamRunner.High(nopTable)), + StreamRunner.Packet(PacketOpcode.EventWrite, 0x0E), + StreamRunner.Packet(PacketOpcode.Nop, 0x6875_06ECu), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 2, 1, 1, 0x41), + StreamRunner.Packet(PacketOpcode.SetShaderRegisterIndirect, StreamRunner.Low(indirectTable), StreamRunner.High(indirectTable), 0, 1), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 3, 1, 1, 0x41)); + + Assert.Equal(new[] { "22 2", "33 3" }, requested); + Assert.Equal(0x33u, runner.Interpreter.TypedRegisters.Shader.Compute.UserScalars.ValueSpan(1)[0]); + } + + // A ticket worker never compiles: a missing permutation asks for the serial resolve. + [Fact] + public void ASpeculativeResolveNeverCompilesAPermutation() + { + using var fatal = new FatalScope(); + var guest = new PipelineTestGuest(); + guest.RegisterProgram(CodeAddress, HeaderAddress, PipelineTestGuest.EndProgram); + var source = guest.Source(CodeAddress, SharpEmu.ShaderCompiler.Resources.ShaderStage.Compute, []); + var cursor = 0u; + ShaderProgramCache.SpeculativeResolve = true; + try + { + Assert.Throws(() => guest.Programs.TryGetProgram( + source, PipelineTestGuest.ComputeOptions(32), false, ref cursor, out _, out _, out _)); + } + finally + { + ShaderProgramCache.SpeculativeResolve = false; + } + + Assert.Empty(guest.Compiler.Requests); + Assert.Empty(guest.Host.Modules); + } + + // A ticket worker never raises a fatal: a strict rejection asks for the serial resolve, which rejects it for real. + [Fact] + public void ASpeculativeResolveTurnsAStrictRejectionIntoASerialResolve() + { + using var fatal = new FatalScope(); + var guest = new PipelineTestGuest(); + guest.Compiler.LinkedShaderCallsSupported = false; + guest.RegisterProgram(CodeAddress, HeaderAddress, [0xBE8E2100, 0xBF810000]); + var source = guest.Source(CodeAddress, SharpEmu.ShaderCompiler.Resources.ShaderStage.Compute, []); + var cursor = 0u; + ShaderProgramCache.SpeculativeResolve = true; + try + { + Assert.Throws(() => guest.Programs.TryGetProgram( + source, PipelineTestGuest.ComputeOptions(32), true, ref cursor, out _, out _, out _)); + } + finally + { + ShaderProgramCache.SpeculativeResolve = false; + } + + Assert.Empty(guest.Compiler.Requests); + } + + private static (ShaderPipelineCache Cache, ComputeTickets Tickets) CreateCache(int workers, Func? validate = null, bool verify = false) + { + var guest = new PipelineTestGuest(); + guest.RegisterProgram(CodeAddress, HeaderAddress, PipelineTestGuest.EndProgram); + var cache = new ShaderPipelineCache(guest.Context, guest.Host, guest.Compiler, guest.Registry); + var tickets = new ComputeTickets(cache, static _ => { }, static () => { }, validate ?? (static _ => true), workers, verify); + cache.Tickets = tickets; + return (cache, tickets); + } + + private static RegisterBanks Banks() + { + var banks = new RegisterBanks(static message => new InvalidOperationException(message)); + var compute = banks.Shader.Compute; + compute.Address = CodeAddress; + compute.ThreadsX = 1; + compute.ThreadsY = 1; + compute.ThreadsZ = 1; + compute.UserScalarCount = 8; + return banks; + } + + // The banks of a dispatch whose program the cache keeps (resolved once, outside any ticket). + private static RegisterBanks KeptBanks(ShaderPipelineCache cache, out ComputeProgram first) + { + var banks = Banks(); + first = cache.GetComputeProgram(banks, Initiator, 1, 1, 1); + Assert.True(first.Available); + return banks; + } + + private static ComputeProgram Dispatch(ShaderPipelineCache cache, ComputeTickets tickets, RegisterBanks banks, ulong packetAddress) + { + tickets.BeginDispatch(Owner, packetAddress); + try + { + return cache.GetComputeProgram(banks, Initiator, 1, 1, 1); + } + finally + { + tickets.EndDispatch(); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs index 21e82b5c0..e72c1f029 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs @@ -18,15 +18,23 @@ public sealed class DispatchChainTests : IDisposable private readonly FakePipelineProvider _pipelines = new(); private readonly RenderExecutor _executor; private readonly FatalScope _fatal = new(); + private readonly bool _sameProgramWrites = DispatchChain.SameProgramWrites; public DispatchChainTests() => _executor = new RenderExecutor(_host, _pipelines); - public void Dispose() => _fatal.Dispose(); + public void Dispose() + { + DispatchChain.SameProgramWrites = _sameProgramWrites; + _fatal.Dispose(); + } private static BufferResourceInfo Written => new(false, true, false, false, false, 4); private static BufferResourceInfo Read => new(true, false, false, false, false, 4); + // As the shader tracker records an atomic binding: read, written and atomic. + private static BufferResourceInfo Atomic => new(true, true, true, false, false, 4); + private void Dispatch(ulong submitId, BufferResourceInfo[] buffers, uint[][] descriptors) { _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: buffers), buffers: descriptors)); @@ -35,6 +43,107 @@ private void Dispatch(ulong submitId, BufferResourceInfo[] buffers, uint[][] des private int HazardBarriers => _host.Calls.Count(call => call == "write_hazard_barrier"); + private void DispatchStage(ulong submitId, ShaderStageResources stage) + { + _pipelines.Compute = ComputeProgram(stage); + _executor.Dispatch(submitId, Banks(), 1, 1, 1, 0x41); + } + + // SHARPEMU_CHAIN_SAME_PROGRAM_WRITES: dispatches of one program the guest left unordered may write the same span. + [Theory] + [InlineData(true, 1)] + [InlineData(false, 2)] + public void SameProgramWritesOverOneSpanShareTheChain(bool sameProgramWrites, int barriers) + { + DispatchChain.SameProgramWrites = sameProgramWrites; + Dispatch(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(2, [Written], [BufferDescriptor(BufferA, 4, 16)]); + + Assert.Equal(barriers, HazardBarriers); + } + + [Fact] + public void WritesOverOneSpanByTwoProgramsKeepTheBarrier() + { + DispatchChain.SameProgramWrites = true; + Dispatch(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + var other = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x0BAD_C0DE, Buffers = [Written] }; + DispatchStage(2, Stage(other, [BufferDescriptor(BufferA, 4, 16)])); + + Assert.Equal(2, HazardBarriers); + } + + [Fact] + public void SameProgramAtomicsOverOneSpanShareTheChain() + { + DispatchChain.SameProgramWrites = true; + Dispatch(1, [Atomic], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(2, [Atomic], [BufferDescriptor(BufferA, 4, 16)]); + + Assert.Equal(1, HazardBarriers); + } + + [Fact] + public void AnAtomicOverAPlainWriteKeepsTheBarrier() + { + DispatchChain.SameProgramWrites = true; + Dispatch(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(2, [Atomic], [BufferDescriptor(BufferA, 4, 16)]); + + Assert.Equal(2, HazardBarriers); + } + + [Fact] + public void APlainReadOfAnAtomicSpanKeepsTheBarrier() + { + DispatchChain.SameProgramWrites = true; + Dispatch(1, [Atomic], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(2, [Read], [BufferDescriptor(BufferA + 0x20, 4, 4)]); + + Assert.Equal(2, HazardBarriers); + } + + [Fact] + public void SameProgramWritersShareTheChainUntilAReaderOfTheirBytes() + { + DispatchChain.SameProgramWrites = true; + Dispatch(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(2, [Written], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(3, [Written], [BufferDescriptor(BufferA, 4, 16)]); + Dispatch(4, [Read], [BufferDescriptor(BufferA + 0x20, 4, 4)]); + + Assert.Equal(2, HazardBarriers); + } + + [Fact] + public void APromotionBetweenSameProgramWritersStartsANewChain() + { + DispatchChain.SameProgramWrites = true; + Dispatch(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + _host.Promotions++; + Dispatch(2, [Written], [BufferDescriptor(BufferA, 4, 16)]); + + Assert.Equal(2, HazardBarriers); + } + + [Fact] + public void ALongSameProgramRunOverOneSpanKeepsOneBarrierAndShortLists() + { + DispatchChain.SameProgramWrites = true; + var chain = new DispatchChain(); + var stage = Stage(Program(ShaderStageKind.Compute, buffers: [Written]), [BufferDescriptor(BufferA, 4, 16)]); + var record = new ResolvedDispatch { HasStorageWrites = true }; + var barriers = 0; + for (var index = 0; index < 2000; index++) + { + barriers += chain.NeedsHazardBarrier(record, in stage, promotions: 0) ? 1 : 0; + chain.Commit(deferred: true, promotions: 0); + } + + Assert.Equal(1, barriers); + Assert.True(chain.SpanCount <= 2, $"spans {chain.SpanCount}"); + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchTableReplayTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchTableReplayTests.cs new file mode 100644 index 000000000..a0d4441ad --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchTableReplayTests.cs @@ -0,0 +1,97 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; +using ResourceSnapshot = SharpEmu.ShaderCompiler.Resources.ResourceSnapshot; + +namespace SharpEmu.Libs.Tests.Gpu.Rendering; + +[Collection(SchedulingStateCollection.Name)] +public sealed class DispatchTableReplayTests : IDisposable +{ + private readonly FatalScope _fatal = new(); + + public void Dispose() => _fatal.Dispose(); + + // A compute program whose only binding is its flattened resource table; device addresses are a second replay refusal. + private static ShaderProgramInfo TableProgram(bool usesDeviceAddresses = false) + { + var info = new ShaderResourceInfo(); + return new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, + Hash = 0x7AB1_E000, + UsesDeviceAddresses = usesDeviceAddresses, + Resources = new SpecializedResourceInfo { Info = info }, + Bindings = BindingLayout.Allocate(info, [], usesGlobalDataShare: false, usesFlattenedTable: true, usesShaderBase: false), + }; + } + + private static ResolvedDispatch Dispatch(ShaderProgramInfo program, uint[] table, uint[][]? buffers = null) => new() + { + Program = ComputeProgram(new ShaderStageResources(program, new ResourceSnapshot { FlattenedResourceTable = table, Buffers = buffers ?? [] })), + GroupsX = 1, + GroupsY = 1, + GroupsZ = 1, + }; + + private static List RecordTwo(ResolvedDispatch first, ResolvedDispatch second) + { + var host = new RecordingRenderHost(); + var recorder = new RenderRecorder(host, new FakePipelineProvider(), strictDrawResources: true, returnsRecords: false); + host.ItemSequence = 1; + recorder.Record(first); + host.ItemSequence = 2; + recorder.Record(second); + return host.Calls; + } + + private static int Count(List calls, string prefix) => calls.Count(call => call.StartsWith(prefix, StringComparison.Ordinal)); + + [Fact] + public void ADispatchWhoseTableAloneDiffersReplaysWithItsTableReplaced() + { + var program = TableProgram(); + var calls = RecordTwo(Dispatch(program, [1, 2, 3]), Dispatch(program, [4, 5, 6])); + + Assert.Equal(1, Count(calls, "commit Compute")); + Assert.Contains("replay_dispatch table=True", calls); + Assert.Equal(2, Count(calls, "dispatch 1 1 1")); + Assert.Equal(2, Count(calls, "seal_dispatch")); + } + + [Fact] + public void ADispatchWithTheSameTableReplaysWithoutReplacingIt() + { + var program = TableProgram(); + var calls = RecordTwo(Dispatch(program, [1, 2, 3]), Dispatch(program, [1, 2, 3])); + + Assert.Equal(1, Count(calls, "commit Compute")); + Assert.Contains("replay_dispatch table=False", calls); + } + + [Fact] + public void ATableThatDiffersBesideOtherBindingsTakesTheFullPath() + { + var program = TableProgram(); + var calls = RecordTwo(Dispatch(program, [1, 2, 3], [BufferDescriptor(VertexBase, 4, 16)]), + Dispatch(program, [4, 5, 6], [BufferDescriptor(VertexBase + 0x100, 4, 16)])); + + Assert.Equal(2, Count(calls, "commit Compute")); + Assert.DoesNotContain(calls, call => call.StartsWith("replay_dispatch", StringComparison.Ordinal)); + } + + [Fact] + public void AProgramWithAnotherReplayRefusalBesideItsTableSealsNothing() + { + var program = TableProgram(usesDeviceAddresses: true); + var calls = RecordTwo(Dispatch(program, [1, 2, 3]), Dispatch(program, [4, 5, 6])); + + Assert.Equal(2, Count(calls, "commit Compute")); + Assert.Equal(0, Count(calls, "seal_dispatch")); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/PendingGpuWritesTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/PendingGpuWritesTests.cs index 6bd3b1d0c..2f2a6f0ca 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/PendingGpuWritesTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/PendingGpuWritesTests.cs @@ -43,6 +43,29 @@ public void ReleasingASequenceDropsEveryMarkUpToIt() Assert.Equal(3, pending.Released); } + [Fact] + public void AHoldKeepsReleasesBelowItsFirstSequenceUntilItEnds() + { + var pending = new PendingGpuWrites(); + pending.Mark(0x1000, 0x10, sequence: 4); + pending.Mark(0x2000, 0x10, sequence: 6); + pending.HoldFrom(5); + + pending.Release(3); + Assert.Equal(3, pending.Released); + pending.Release(7); + Assert.Equal(4, pending.Released); + Assert.False(pending.TryGetPending(0x1000, 4, out _)); + Assert.True(pending.TryGetPending(0x2000, 4, out var sequence)); + Assert.Equal(6, sequence); + + pending.EndHold(); + Assert.Equal(7, pending.Released); + Assert.False(pending.TryGetPending(0x2000, 4, out _)); + pending.Release(8); + Assert.Equal(8, pending.Released); + } + [Fact] public void AMarkOfEverythingMakesEveryReadPendingUntilItIsReleased() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index 23c6afae3..dbb62568c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -427,6 +427,21 @@ void IRenderHost.EndCheckedDispatch() long IRenderHost.DeferredBarrierPromotions => Promotions; + // The stream position of the item being recorded; zero keeps dispatches from sealing a replay basis. + public long ItemSequence { get; set; } + + long IRenderHost.CurrentItemSequence => ItemSequence; + + public bool AcceptDispatchReplay { get; set; } = true; + + void IRenderHost.SealDispatchReplay() => Calls.Add("seal_dispatch"); + + bool IRenderHost.TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage, bool replaceTable) + { + Calls.Add($"replay_dispatch table={replaceTable}"); + return AcceptDispatchReplay; + } + public bool RetainTargetlessDraws { get; set; } public List<(RegisterBanks Banks, GraphicsPrograms Programs, TargetlessDrawArguments Arguments)> RetainedDraws { get; } = new(); diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreIndexTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreIndexTests.cs new file mode 100644 index 000000000..983acb89a --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreIndexTests.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.Reflection; +using SharpEmu.HLE; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +[Collection(SchedulingStateCollection.Name)] +public sealed class CommandStreamStoreIndexTests : IClassFixture +{ + private static readonly Type CommandThreadType = typeof(VulkanVideoPresenter).GetNestedType("CommandThread", BindingFlags.NonPublic)!; + private readonly HeadlessVulkan? _vulkan; + + public CommandStreamStoreIndexTests(HeadlessVulkanFixture fixture) => _vulkan = fixture.Vulkan; + + internal static object NewThread(PresenterUnderTest presenter) => + Activator.CreateInstance(CommandThreadType, PresenterUnderTest.InstanceMembers, null, + [presenter.Instance, null, presenter.Harness.Memory, null, null], null)!; + + internal static object[] Stores(object thread) => + ((IEnumerable)CommandThreadType.GetField("_pendingWrites", PresenterUnderTest.InstanceMembers)!.GetValue(thread)!).Cast().ToArray(); + + internal static void Land(PresenterUnderTest presenter, object thread) + { + var execute = CommandThreadType.GetMethod("Execute", PresenterUnderTest.InstanceMembers)!; + foreach (var store in Stores(thread)) + { + presenter.Harness.Worker.Run(() => execute.Invoke(thread, [store])); + } + } + + // A small store before a large one and a small store after it on one page: the overlay applies the three in order, and + // the index is empty once they land. + [Fact] + public void TheOverlayAppliesSmallAndLargeStoresOnOnePageInOrder() + { + if (_vulkan is null || !OperatingSystem.IsWindows()) + return; + + using var presenter = new PresenterUnderTest(_vulkan); + var address = presenter.Harness.MapBacked(0x40000, GuestPageProtection.Read | GuestPageProtection.Write); + var thread = NewThread(presenter); + var post = CommandThreadType.GetMethod("PostOwnedWrite")!; + var large = new byte[20 * 0x1000]; + Array.Fill(large, (byte)2); + post.Invoke(thread, [address + 0x100, new byte[] { 1, 1, 1, 1 }, false]); + post.Invoke(thread, [address, large, false]); + post.Invoke(thread, [address + 0x104, new byte[] { 3, 3, 3, 3 }, false]); + + var expected = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3 }; + var read = (byte[])CommandThreadType.GetMethod("ReadOverlayForTest", PresenterUnderTest.InstanceMembers)! + .Invoke(thread, [address + 0xFC, expected.Length])!; + Assert.Equal(expected, read); + + Land(presenter, thread); + var index = (PendingStorePages)CommandThreadType.GetField("_storePages", PresenterUnderTest.InstanceMembers)!.GetValue(thread)!; + Assert.True(index.IsEmpty); + Assert.Empty(Stores(thread)); + Assert.Equal(expected, presenter.Harness.Read(address + 0xFC, expected.Length)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PendingStorePagesTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PendingStorePagesTests.cs new file mode 100644 index 000000000..2b09b705c --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PendingStorePagesTests.cs @@ -0,0 +1,97 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed class PendingStorePagesTests +{ + private const ulong Page = 0x1000; + + // A store kept as one range answers as the page index would: every page from its first byte to its last, and no other. + [Fact] + public void ALargeStoreCoversThePagesOfItsFirstAndLastBytesAndNoOthers() + { + var pages = new PendingStorePages(); + var address = 0x40000UL + 0x10; + var length = (PendingStorePages.LargePages + 1) * Page; + Assert.True(PendingStorePages.IsLarge(address, length)); + Assert.False(PendingStorePages.IsLarge(0x40000, PendingStorePages.LargePages * Page)); + pages.Add(address, length, large: true); + var firstPage = address & ~(Page - 1); + var lastByte = address + length - 1; + var lastPage = lastByte & ~(Page - 1); + + Assert.True(pages.Overlaps(address, 1)); + Assert.True(pages.Overlaps(firstPage, 1)); + Assert.True(pages.Overlaps(lastByte, 1)); + Assert.True(pages.Overlaps(lastPage + Page - 1, 1)); + Assert.False(pages.Overlaps(firstPage - 1, 1)); + Assert.False(pages.Overlaps(lastPage + Page, 1)); + + Assert.True(pages.OverlapsLarge(lastByte, lastByte + 1)); + Assert.False(pages.OverlapsLarge(lastByte + 1, lastByte + 2)); + Assert.False(pages.OverlapsLarge(address - 1, address)); + } + + // Small stores before and after a large one on its first page stay in the page index; once all of them leave in order, + // nothing is left. + [Fact] + public void SmallStoresOnALargeStoresPageStayAfterItLeaves() + { + var pages = new PendingStorePages(); + var page = 0x80000UL; + pages.Add(page + 0x100, 4, large: false); + pages.Add(page, 20 * Page, large: true); + pages.Add(page + 0x200, 8, large: false); + Assert.True(pages.HasLarge); + + pages.Remove(page + 0x100, 4, large: false); + pages.Remove(page, 20 * Page, large: true); + Assert.False(pages.HasLarge); + Assert.True(pages.Overlaps(page + 0x200, 8)); + Assert.True(pages.Overlaps(page + 0x100, 4)); + Assert.False(pages.Overlaps(page + 5 * Page, 4)); + + pages.Remove(page + 0x200, 8, large: false); + Assert.True(pages.IsEmpty); + Assert.False(pages.Overlaps(page, Page)); + } + + // The bucket counts never hide a page the dictionary holds. + [Fact] + public void TheBucketCountsAgreeWithTheDictionary() + { + var pages = new PendingStorePages(); + var random = new System.Random(22); + var queued = new Queue<(ulong Address, ulong Length)>(); + for (var step = 0; step < 4000; step++) + { + if (queued.Count < 64 && random.Next(3) != 0) + { + var store = ((ulong)random.Next(0, 1 << 20) * 4, (ulong)random.Next(1, 3 * (int)Page)); + pages.Add(store.Item1, store.Item2, large: false); + queued.Enqueue(store); + } + else if (queued.Count != 0) + { + var store = queued.Dequeue(); + pages.Remove(store.Address, store.Length, large: false); + } + + var address = (ulong)random.Next(0, 1 << 22); + var size = (ulong)random.Next(1, 2 * (int)Page); + Assert.Equal(pages.Overlaps(address, size, prefilter: false), pages.Overlaps(address, size, prefilter: true)); + } + + while (queued.Count != 0) + { + var store = queued.Dequeue(); + pages.Remove(store.Address, store.Length, large: false); + } + + Assert.True(pages.IsEmpty); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/ResolveWorkerReadTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/ResolveWorkerReadTests.cs new file mode 100644 index 000000000..03722beae --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/ResolveWorkerReadTests.cs @@ -0,0 +1,59 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +[Collection(SchedulingStateCollection.Name)] +public sealed class ResolveWorkerReadTests : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan; + + public ResolveWorkerReadTests(HeadlessVulkanFixture fixture) => _vulkan = fixture.Vulkan; + + // A compute ticket's take checks again only the reads its worker logged, so a read the worker cannot serve refuses the + // ticket; a draw's worker still reports the failed read to the resource materializer. + [Fact] + public void AReadAWorkerCannotServeRefusesATicketButNotADraw() + { + if (_vulkan is null || !OperatingSystem.IsWindows()) + return; + + using var presenter = new PresenterUnderTest(_vulkan); + var (first, granule, _) = presenter.Harness.MapBackedSandwich(); + var hole = first + granule; + var host = (ICommandStreamHost)presenter.Instance; + var reader = (IShaderPipelineHost)presenter.Instance; + + var drawReads = new ResolveReadLog(); + host.BeginWorkerResolve(5, drawReads); + try + { + Assert.False(reader.TryReadGuestWord(hole, out _)); + } + finally + { + host.EndWorkerResolve(); + } + + var ticketReads = new ResolveReadLog(); + host.BeginWorkerResolve(long.MaxValue, ticketReads); + try + { + var refusal = Assert.Throws(() => reader.TryReadGuestWord(hole, out _)); + Assert.Equal("ticket read unreadable", refusal.Message); + } + finally + { + host.EndWorkerResolve(); + } + + Assert.Equal(0, drawReads.Count); + Assert.Equal(0, ticketReads.Count); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs index 41bfe0e54..2b63139e0 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs @@ -450,6 +450,47 @@ public void WorkerBufferUseCacheNeverHandsOutABufferAMergeRetired() harness.Shutdown(); } + // A worker passes a native color clear whose only change would be its registration; the join applies it after every + // other check, unless the apply would now record a clear. + [Fact] + public void JoinAppliesARegistrationOnlyNativeColorClearUnlessItWouldNowClear() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var presenter = new PresenterUnderTest(_vulkan!); + var harness = presenter.Harness; + var address = harness.MapBacked(0x20000, ImageCacheTestSupport.ReadWrite); + var metadataAddress = address + 0x10000; + var target = ImageCacheTestSupport.AsColorTarget(ImageCacheTestSupport.LinearRequest(address, 8, Format.R16G16B16A16Sfloat, + GuestPixelFormat.Bits16_16_16_16Float, GuestImageType.Color2D, new Extent3D(1, 1, 1), 1, 8, 1)); + target.Description.Metadata.Kind = MetadataKind.Dcc; + target.Description.Metadata.Range = new GuestSpan(metadataAddress, 4096); + target.Description.Metadata.NativeColorClear = true; + target.Description.Metadata.PackedColorClearSupported = true; + target.Description.Metadata.PackedColorClear = new ClearColorValue(0f, 0f, 1f, 1f); + harness.Write(metadataAddress, Enumerable.Repeat((byte)0x20, 4096).ToArray()); + var identifier = harness.Find(ref target); + presenter.Run(() => + { + var slice = Activator.CreateInstance(SliceType, nonPublic: true)!; + var segment = Activator.CreateInstance(SegmentType, nonPublic: true)!; + var requests = SegmentType.GetField("Requests")!.GetValue(segment)!; + var requestsType = requests.GetType(); + requestsType.GetField("BufferSerial")!.SetValue(requests, harness.Cache.RefreshSnapshot().Serial); + requestsType.GetField("LookupGeneration")!.SetValue(requests, harness.Images.LookupGeneration); + requestsType.GetField("MetadataGeneration")!.SetValue(requests, harness.Images.MetadataGeneration); + ((List<(ResourceSlotIdentifier, ImageRequest)>)requestsType.GetField("NativeColorEntries")!.GetValue(requests)!).Add((identifier, target)); + + // The slice holds a clear code by the join: the segment is refused and the registration stays as it was. + Assert.False(ValidateSegment(presenter, slice, segment)); + harness.Write(metadataAddress, Enumerable.Repeat((byte)0xFF, 4096).ToArray()); + Assert.Equal(NativeColorClearPrediction.RegistrationOnly, harness.Images.PredictNativeColorClear(identifier, target)); + + Assert.True(ValidateSegment(presenter, slice, segment)); + Assert.Equal(NativeColorClearPrediction.Settled, harness.Images.PredictNativeColorClear(identifier, target)); + }); + harness.Shutdown(); + } + [Fact] public void ReadyPresentationYieldsQueuedWorkButShutdownStillDrainsIt() { diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/StoreBufferPoolTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/StoreBufferPoolTests.cs new file mode 100644 index 000000000..96a450b04 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/StoreBufferPoolTests.cs @@ -0,0 +1,75 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +[Collection(SchedulingStateCollection.Name)] +public sealed class StoreBufferPoolTests : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan; + + public StoreBufferPoolTests(HeadlessVulkanFixture fixture) => _vulkan = fixture.Vulkan; + + // Buffers come in 64 KiB classes and come back once: a second return of one is refused, and an idle buffer is reused. + [Fact] + public void BuffersComeIn64KiBClassesAndComeBackOnce() + { + var pool = new StoreBufferPool(); + var buffer = pool.Rent(StoreBufferPool.ClassBytes + 1); + Assert.Equal(2 * StoreBufferPool.ClassBytes, buffer.Length); + Assert.Equal((1, 0L), pool.Stats()); + + Assert.Equal(StoreBufferPool.ReturnResult.Kept, pool.Return(buffer)); + Assert.Equal(StoreBufferPool.ReturnResult.NotLeased, pool.Return(buffer)); + Assert.Equal((0, (long)buffer.Length), pool.Stats()); + Assert.Same(buffer, pool.Rent(2 * StoreBufferPool.ClassBytes)); + } + + // A leased buffer is never handed out again before it comes back; returns past the idle budget are dropped. + [Fact] + public void ALeasedBufferIsNotHandedOutAgainAndTheIdleBudgetHolds() + { + var pool = new StoreBufferPool(maxIdleBytes: 3 * StoreBufferPool.ClassBytes); + var first = pool.Rent(2 * StoreBufferPool.ClassBytes); + var second = pool.Rent(2 * StoreBufferPool.ClassBytes); + Assert.NotSame(first, second); + + Assert.Equal(StoreBufferPool.ReturnResult.Kept, pool.Return(first)); + Assert.Equal(StoreBufferPool.ReturnResult.Dropped, pool.Return(second)); + Assert.Equal((0, 2L * StoreBufferPool.ClassBytes), pool.Stats()); + Assert.Equal(StoreBufferPool.ReturnResult.NotLeased, pool.Return(new byte[StoreBufferPool.ClassBytes])); + } + + // A pooled store keeps its buffer until it lands, writes only its own length, then returns the buffer to the pool. + [Fact] + public void APooledStoreReturnsItsBufferWhenItLands() + { + if (_vulkan is null || !OperatingSystem.IsWindows()) + return; + + using var presenter = new PresenterUnderTest(_vulkan); + var address = presenter.Harness.MapBacked(0x20000, GuestPageProtection.Read | GuestPageProtection.Write); + var thread = CommandStreamStoreIndexTests.NewThread(presenter); + var buffer = StoreBufferPool.Shared.Rent(StoreBufferPool.ClassBytes); + Array.Fill(buffer, (byte)7); + thread.GetType().GetMethod("PostPooledWrite")!.Invoke(thread, [address, buffer, StoreBufferPool.ClassBytes - 16, false]); + + var store = Assert.Single(CommandStreamStoreIndexTests.Stores(thread)); + var data = store.GetType().GetField("Data")!; + Assert.Same(buffer, data.GetValue(store)); + + CommandStreamStoreIndexTests.Land(presenter, thread); + Assert.Null(data.GetValue(store)); + Assert.Equal(7, presenter.Harness.Read(address + StoreBufferPool.ClassBytes - 17, 1)[0]); + Assert.Equal(0, presenter.Harness.Read(address + StoreBufferPool.ClassBytes - 16, 1)[0]); + var again = StoreBufferPool.Shared.Rent(StoreBufferPool.ClassBytes); + Assert.Same(buffer, again); + StoreBufferPool.Shared.Return(again); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceAddressWindowTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceAddressWindowTests.cs new file mode 100644 index 000000000..9c5e6788b --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceAddressWindowTests.cs @@ -0,0 +1,99 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +// Which programs reach only their handles' 4 GiB windows. +public sealed class DeviceAddressWindowTests +{ + private const ulong Window = DeviceAddressRangePlanner.WindowOffsetBytes; + + // global_load through s[0:1] with a vector offset: base + zext(v0) + 8, four bytes, ends before base + 2^32 + 12. + [Fact] + public void AGlobalReadWithAScalarBaseIsWindowed() + { + var plan = Extract(Program(GlobalAccess(0, "GlobalLoadDword", 0, offset: 8, vectorAddress: 0), EndProgram(8))); + + Assert.False(plan.DeviceAddressReadsBounded); + Assert.True(plan.DeviceAddressReadsWindowed); + var range = Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x1000, 0]))); + Assert.True(range.Planned); + Assert.Equal(0x1000ul, range.Base); + Assert.True(range.Base + plan.DeviceAddressWindowBytes >= 0x1000ul + Window - 1 + 8 + 4); + } + + // A negative immediate reaches below the base; the host's range base starts there and the window still covers the top. + [Fact] + public void ANegativeImmediateStartsTheWindowBelowTheBase() + { + var plan = Extract(Program( + GlobalAccess(0, "GlobalLoadDword", 0, offset: -16, vectorAddress: 0), + GlobalAccess(8, "GlobalLoadDwordx2", 0, offset: 24, vectorAddress: 0, dwords: 2), + EndProgram(16))); + + Assert.True(plan.DeviceAddressReadsWindowed); + var range = Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x1000, 0]))); + Assert.Equal(0x1000ul - 16, range.Base); + Assert.True(range.Base + plan.DeviceAddressWindowBytes >= 0x1000ul + Window - 1 + 24 + 8); + } + + // s_load through s[0:1] plus a run-time s4: the offset is zero-extended, so the read stays in the window. + [Fact] + public void AScalarReadWithARunTimeOffsetIsWindowed() + { + var plan = Extract(Program(ScalarLoad(0, 0, 8, count: 2, immediateOffset: 4, dynamicOffsetRegister: 4), EndProgram(8))); + + Assert.True(plan.DeviceAddressReadsWindowed); + var range = Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x2000, 0]))); + Assert.True(range.Base <= 0x2000ul + 4); + Assert.True(range.Base + plan.DeviceAddressWindowBytes >= 0x2000ul + Window - 1 + 4 + 8); + } + + // A flat read addresses the whole 64-bit vector pair: no window holds it. + [Fact] + public void AFlatReadIsNotWindowed() + { + var plan = Extract(Program(GlobalAccess(0, "FlatLoadDword", 0, vectorAddress: 2), EndProgram(8))); + + Assert.False(plan.DeviceAddressReadsWindowed); + Assert.Equal(0ul, plan.DeviceAddressWindowBytes); + } + + // A windowed read beside a flat read: the program keeps the full sweep. + [Fact] + public void AFlatReadBesideAWindowedReadKeepsTheFullSweep() + { + var plan = Extract(Program( + GlobalAccess(0, "GlobalLoadDword", 0, offset: 8, vectorAddress: 0), + GlobalAccess(8, "FlatLoadDword", 0, vectorAddress: 2), + EndProgram(16))); + + Assert.False(plan.DeviceAddressReadsWindowed); + } + + // A store through the handle: the written range keeps the full sweep. + [Fact] + public void AWrittenRangeIsNotWindowed() + { + var plan = Extract(Program(GlobalAccess(0, "GlobalStoreDword", 0, vectorAddress: 0), EndProgram(8))); + + Assert.False(plan.DeviceAddressReadsWindowed); + } + + // Exactly bounded reads stay in the bounded class. + [Fact] + public void ABoundedProgramIsNotWindowed() + { + var plan = Extract(Program( + Vop1(0, "VMovB32", 0, Operand(0)), + GlobalAccess(4, "GlobalLoadDword", 0, offset: 8), + EndProgram(12))); + + Assert.True(plan.DeviceAddressReadsBounded); + Assert.False(plan.DeviceAddressReadsWindowed); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs index 4f915ed73..89c8bc9e7 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs @@ -13,12 +13,16 @@ public class ResourceBranchTests // case through the compiled branch transaction. internal virtual RuntimeValueEvaluator.CompiledBranchMode? BranchMode => null; - private static Gen5ShaderProgram ConditionalBuffers(string branch = "SCbranchScc1", bool shared = false) => Program( + // True compares the materialization program's compiled branch selection with the evaluator's walk before every case's + // materialization (the derived class). + internal virtual bool CompareSelection => false; + + private protected static Gen5ShaderProgram ConditionalBuffers(string branch = "SCbranchScc1", bool shared = false) => Program( Sopc(0, "SCmpEqU32", Gen5Operand.Scalar(8), Operand(1)), Branch(4, branch, 3), BufferLoad(8, 0), Branch(16, "SBranch", 2), BufferLoad(20, shared ? 0u : 4u), EndProgram(28)); - private static uint[] UserData(uint condition) => [0x1000, 0, 256, 0, 0x2000, 0, 256, 0, condition]; + private protected static uint[] UserData(uint condition) => [0x1000, 0, 256, 0, 0x2000, 0, 256, 0, condition]; [Theory] [InlineData(0u)] @@ -38,15 +42,20 @@ public void EmptySourceEvaluationPreservesBranchActivity(uint condition) Assert.Equal(table, refreshed); } - private static bool CleanRead(ulong address, out uint word) { word = 0; return false; } + private protected static bool CleanRead(ulong address, out uint word) { word = 0; return false; } private ResourceSnapshot Materialize(ShaderResourcePlan plan, uint[] userData, GuestWordReader? cleanReader) => Materialize(plan, Inputs(userData, readCleanMemory: cleanReader)); - private ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) => Materialize(plan, inputs, out _); + private protected ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) => Materialize(plan, inputs, out _); private ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, out ResourceSpecialization specialization) { + if (CompareSelection && plan.ResourceBranches.Count != 0) + { + AssertSelectionMatchesEvaluator(plan, inputs); + } + var snapshot = new ResourceSnapshot(); specialization = new ResourceSpecialization(); var mode = BranchMode; @@ -88,6 +97,52 @@ private ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInp ReadsClean = inputs.ReadsClean, }; + // The compiled branch selection against the evaluator's walk on one draw: the same active sources, and the same words + // read through each reader in the same order with the same results. Returns the evaluator's active sources. + private protected static bool[] AssertSelectionMatchesEvaluator(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, string draw = "") + { + var selection = plan.BranchSelection; + Assert.NotNull(selection); + var expectedReads = new List(); + var expected = RuntimeValueEvaluator.EvaluateActiveSources(plan, Traced(inputs, expectedReads)); + var reads = new List(); + var active = new bool[selection.SourceCount]; + if (!selection.TrySelect(Traced(inputs, reads), active)) + { + Assert.True(inputs.ReadCleanMemory is null, $"The compiled selection refused a draw with a clean reader. {draw}"); + Assert.Empty(reads); + Assert.Empty(expectedReads); + return expected; + } + + Assert.True(expected.AsSpan().SequenceEqual(active), + $"The active sources differ. {draw} evaluator=[{string.Join(",", expected)}] compiled=[{string.Join(",", active)}]"); + Assert.True(expectedReads.SequenceEqual(reads), + $"The reads differ. {draw} evaluator=[{string.Join(" ", expectedReads)}] compiled=[{string.Join(" ", reads)}]"); + return expected; + } + + private static ResourceRuntimeInputs Traced(ResourceRuntimeInputs inputs, List trace) + { + GuestWordReader? Trace(GuestWordReader? reader, string name) => reader is null ? null : (ulong address, out uint word) => + { + var read = reader(address, out word); + trace.Add($"{name}:{address:X}:{read}:{word:X}"); + return read; + }; + + return new ResourceRuntimeInputs + { + UserData = inputs.UserData, + ShaderBase = inputs.ShaderBase, + ReadMemory = Trace(inputs.ReadMemory, "general"), + ReadCleanMemory = Trace(inputs.ReadCleanMemory, "clean"), + ComputeState = inputs.ComputeState, + IsRangeMapped = inputs.IsRangeMapped, + ReadsClean = inputs.ReadsClean, + }; + } + [Theory] [InlineData("SCbranchScc1", 0u, 0)] [InlineData("SCbranchScc1", 1u, 1)] @@ -147,14 +202,14 @@ public void ShaderWritesAndAtomicsDisablePruning(bool atomic) // A count read from the buffer at s[0:3] guards a 2D-array sample of the T# at s[8:15]; the shader then stores // through the buffer at s[4:7]. The count is the first word of the guest memory at 0x1000. - private static Gen5ShaderProgram CountedSampleThenStore() => Program( + private protected static Gen5ShaderProgram CountedSampleThenStore() => Program( ScalarBufferLoad(0, 0, 24), Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(24), Operand(0)), Branch(12, "SCbranchScc1", 2), Image(16, "ImageSample", 8, 16, dimension: 5), BufferStore(24, 4), EndProgram(32)); - private static readonly uint[] VolumeImage = [.. ResourceTrackerTests.ImageDescriptor()[..3], + private protected static readonly uint[] VolumeImage = [.. ResourceTrackerTests.ImageDescriptor()[..3], (ResourceTrackerTests.ImageDescriptor()[3] & 0x0FFFFFFFu) | (GuestImageFormat.ImageType3D << 28), 0, 0, 0, 0]; - private static ShaderResourcePlan ExtractWithWrites(Gen5ShaderProgram program, bool allowed) + private protected static ShaderResourcePlan ExtractWithWrites(Gen5ShaderProgram program, bool allowed) { ResourceBranchBlock.WritesOverride = allowed; try @@ -339,3 +394,340 @@ public sealed class CompiledResourceBranchTests : ResourceBranchTests { internal override RuntimeValueEvaluator.CompiledBranchMode? BranchMode => RuntimeValueEvaluator.CompiledBranchMode.On; } + +// Every case above with the materialization program's compiled branch selection compared against the evaluator's walk, then +// draws with varied register and memory states over the value shapes a selection evaluates. +public sealed class CompiledBranchSelectionTests : ResourceBranchTests +{ + internal override bool CompareSelection => true; + + // Guest words by address; a missing or refused word fails its read. + private sealed class WordMemory + { + public Dictionary Words { get; } = []; + public HashSet Refused { get; } = []; + + public bool Read(ulong address, out uint word) + { + word = 0; + return !Refused.Contains(address) && Words.TryGetValue(address, out word); + } + } + + // A selection never reads through the general reader: it answers words no clean read returns. + private static bool GeneralRead(ulong address, out uint word) + { + word = 0xDEAD_0000u | (uint)(address & 0xFFFF); + return true; + } + + private static uint Pick(System.Random random, params uint[] values) => + random.Next(5) == 0 ? (uint)random.NextInt64(0, 1L << 32) : values[random.Next(values.Length)]; + + // Most draws have a clean reader; a few have none, which keeps every reachable path. + private static ResourceRuntimeInputs Draw(System.Random random, uint[] userData, WordMemory memory) => new() + { + UserData = userData, + ReadMemory = GeneralRead, + ReadCleanMemory = random.Next(16) == 0 ? null : memory.Read, + }; + + private static uint[] FourBuffers(params uint[] tail) => + [0x1000, 0, 256, 0, 0x2000, 0, 256, 0, 0x3000, 0, 256, 0, 0x4000, 0, 256, 0, .. tail]; + + // The predicate is the dword at s[12:13]. + private static Gen5ShaderProgram LoadedPredicate() => Program(ScalarLoad(0, 12, 8), + Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(8), Operand(1)), Branch(12, "SCbranchScc1", 3), + BufferLoad(16, 0), Branch(24, "SBranch", 2), BufferLoad(28, 4), EndProgram(36)); + + // Two dwords read through s[18:19]: the first decides two branches and is read once for both; the second, against user + // data s16, decides a third. + private static Gen5ShaderProgram NestedLoads() => Program( + ScalarLoad(0, 18, 20, count: 2), + Sopc(8, "SCmpLtU32", Gen5Operand.Scalar(20), Operand(4)), Branch(12, "SCbranchScc1", 8), + Sopc(16, "SCmpEqU32", Gen5Operand.Scalar(20), Operand(9)), Branch(20, "SCbranchScc0", 3), + BufferLoad(24, 0), Branch(32, "SBranch", 10), + BufferLoad(36, 4), Branch(44, "SBranch", 7), + Sopc(48, "SCmpLtU32", Gen5Operand.Scalar(21), Gen5Operand.Scalar(16)), Branch(52, "SCbranchScc1", 3), + BufferLoad(56, 8), Branch(64, "SBranch", 2), + BufferLoad(68, 12), EndProgram(76)); + + // s_cselect picks one of two loaded dwords by user data s16; both are read, whichever it picks. + private static Gen5ShaderProgram SelectedLoad() => Program( + ScalarLoad(0, 18, 20, count: 2), + Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(16), Operand(0)), + Sop2(12, "SCselectB32", 22, Gen5Operand.Scalar(20), Gen5Operand.Scalar(21)), + Sopc(16, "SCmpLtU32", Gen5Operand.Scalar(22), Operand(5)), Branch(20, "SCbranchScc1", 3), + BufferLoad(24, 0), Branch(32, "SBranch", 2), + BufferLoad(36, 4), EndProgram(44)); + + // s_brev_b64 of user data s[16:17] compares its halves. + private static Gen5ShaderProgram ReversedPair() => Program( + Sop1(0, "SBrevB64", 20, Gen5Operand.Scalar(16)), + Sopc(4, "SCmpLtU32", Gen5Operand.Scalar(20), Gen5Operand.Scalar(21)), Branch(8, "SCbranchScc1", 3), + BufferLoad(12, 0), Branch(20, "SBranch", 2), + BufferLoad(24, 4), EndProgram(32)); + + // The predicate is record s16 of the buffer at s[0:3], read with a dynamic offset and checked against its records. + private static Gen5ShaderProgram IndexedRecord() => Program( + Sop2(0, "SLshlB32", 20, Gen5Operand.Scalar(16), Operand(2)), + ScalarBufferLoad(4, 0, 24, dynamicOffsetRegister: 20), + Sopc(12, "SCmpLtU32", Gen5Operand.Scalar(24), Operand(5)), Branch(16, "SCbranchScc1", 3), + BufferLoad(20, 4), Branch(28, "SBranch", 2), + BufferLoad(32, 8), EndProgram(40)); + + // The predicate is read through a V# and an offset that are themselves read from s[18:19], so every operand of its read + // reads memory. + private static Gen5ShaderProgram ChasedDescriptor() => Program( + ScalarLoad(0, 18, 20, count: 4), + ScalarLoad(8, 18, 26, immediateOffset: 16), + ScalarBufferLoad(16, 20, 24, dynamicOffsetRegister: 26), + Sopc(24, "SCmpLtU32", Gen5Operand.Scalar(24), Operand(5)), Branch(28, "SCbranchScc1", 3), + BufferLoad(32, 0), Branch(40, "SBranch", 2), + BufferLoad(44, 4), EndProgram(52)); + + // User data s5 chooses between a buffer and an image whose T# halves are scalar buffer reads 80 bytes apart in record s4 + // of the table at s[16:19]. + private static Gen5ShaderProgram RecordImageOrBuffer() => Program( + Sopc(0, "SCmpEqU32", Gen5Operand.Scalar(5), Operand(0)), Branch(4, "SCbranchScc1", 8), + Sop2(8, "SLshlB32", 106, Gen5Operand.Scalar(4), Operand(7)), + ScalarBufferLoad(12, 16, destination: 20, count: 4, immediateOffset: 16, dynamicOffsetRegister: 106), + ScalarBufferLoad(20, 16, destination: 24, count: 4, immediateOffset: 96, dynamicOffsetRegister: 106), + Image(28, "ImageLoad", 20), Branch(36, "SBranch", 2), + BufferLoad(40, 8), EndProgram(48)); + + private static uint[] RecordUserData(uint record, uint condition) => + [0, 0, 0, 0, record, condition, 0, 0, 0x2000, 0, 256, 0, 0, 0, 0, 0, 0x1000, 0, 0x200, 0]; + + private delegate ResourceRuntimeInputs DrawState(System.Random random); + + private sealed record Shape(string Name, ShaderResourcePlan Plan, DrawState Draw); + + private static Shape[] Shapes() => + [ + new("uniform scc1", Extract(ConditionalBuffers()), random => + Draw(random, UserData(Pick(random, 0, 1, 2, 0x8000_0000, uint.MaxValue)), new WordMemory())), + new("uniform scc0", Extract(ConditionalBuffers("SCbranchScc0")), random => + Draw(random, UserData(Pick(random, 0, 1, 2, 0x8000_0000, uint.MaxValue)), new WordMemory())), + new("loaded predicate", Extract(LoadedPredicate()), random => + { + var memory = new WordMemory(); + memory.Words[0x3000] = Pick(random, 0, 1, 2); + memory.Words[0x3004] = Pick(random, 0, 1); + if (random.Next(4) == 0) memory.Refused.Add(0x3000); + return Draw(random, [.. UserData(0), 0, 0, 0, Pick(random, 0x3000, 0x3004, 0, 2, 0x9000), Pick(random, 0, 0, 0, 1)], memory); + }), + new("write guard", ExtractWithWrites(CountedSampleThenStore(), true), random => + { + // The stored V# lies around the count's word at 0x1000, within and past the guard's margin. + var memory = new WordMemory(); + memory.Words[0x1000] = Pick(random, 0, 0, 1); + if (random.Next(6) == 0) memory.Refused.Add(0x1000); + uint[] userData = + [ + Pick(random, 0x1000, 0x1000, 0x1000, 0, 0x2000), Pick(random, 0, 0, 0, 4 << 16), Pick(random, 16, 16, 16, 0, 3, 4), 0, + Pick(random, 0x1800, 0x1000, 0x0F00, 0x0EFC, 0x1104, 0x1103, 0), + Pick(random, 0, 0, 0, 0x8000_0000, 16 << 16, 1), + Pick(random, 64, 64, 0, 1, uint.MaxValue), + Pick(random, 0, 0, 0, 0, 1u << 23, 1u << 30, 3u << 30), + .. VolumeImage, 0, 0, 0, 0, + ]; + return Draw(random, userData, memory); + }), + new("nested loads", Extract(NestedLoads()), random => NestedDraw(random)), + new("selected load", Extract(SelectedLoad()), random => NestedDraw(random)), + new("reversed pair", Extract(ReversedPair()), random => + Draw(random, FourBuffers(Pick(random, 0, 1, 0x8000_0000, 0x0F0F_0F0F), Pick(random, 0, 1, 0x8000_0000, 2)), new WordMemory())), + new("indexed record", Extract(IndexedRecord()), random => + { + var memory = new WordMemory(); + for (var record = 0u; record < 16; record++) + { + memory.Words[0x6000 + record * 4] = Pick(random, 0, 4, 5, 6); + } + + if (random.Next(5) == 0) memory.Refused.Add(0x6000 + (ulong)random.Next(16) * 4); + uint[] userData = + [ + Pick(random, 0x6000, 0x6000, 0, 0x6002), Pick(random, 0, 0, 4 << 16, 16 << 16), Pick(random, 16, 64, 0, 1, 4, 1000), 0, + 0x2000, 0, 256, 0, 0x3000, 0, 256, 0, 0, 0, 0, 0, Pick(random, 0, 1, 2, 3, 15, 0x4000_0000), + ]; + return Draw(random, userData, memory); + }), + new("chased descriptor", Extract(ChasedDescriptor()), random => + { + var memory = new WordMemory(); + uint[] words = [Pick(random, 0x8000, 0x8000, 0, 0x8002), Pick(random, 0, 0, 4 << 16, 1), Pick(random, 64, 64, 0, 1, 2), + Pick(random, 0, 0, 1u << 30), Pick(random, 0, 4, 8, 60, 64)]; + for (var word = 0; word < words.Length; word++) + { + memory.Words[0x7000 + (ulong)word * 4] = words[word]; + } + + for (var word = 0u; word < 16; word++) + { + memory.Words[0x8000 + word * 4] = Pick(random, 0, 4, 5, 6); + } + + if (random.Next(4) == 0) + { + memory.Refused.Add(random.Next(2) == 0 ? 0x7000 + (ulong)random.Next(5) * 4 : 0x8000 + (ulong)random.Next(16) * 4); + } + + return Draw(random, FourBuffers(0, 0, Pick(random, 0x7000, 0x7000, 0x7004, 0), 0), memory); + }), + new("record image", Extract(RecordImageOrBuffer(), stage: ShaderStage.Pixel), random => + Draw(random, RecordUserData(Pick(random, 0, 1, 2), Pick(random, 0, 1, 7)), new WordMemory())), + ]; + + private static ResourceRuntimeInputs NestedDraw(System.Random random) + { + var memory = new WordMemory(); + memory.Words[0x5000] = Pick(random, 0, 3, 4, 9, 10); + memory.Words[0x5004] = Pick(random, 0, 1, 5, uint.MaxValue); + if (random.Next(5) == 0) memory.Refused.Add(random.Next(2) == 0 ? 0x5000ul : 0x5004ul); + return Draw(random, FourBuffers(Pick(random, 0, 2, 6, uint.MaxValue), 0, Pick(random, 0x5000, 0x5000, 0, 0x5002, 0x9000), 0), memory); + } + + // The shapes take turns on one thread, so each selection starts from the scratch another plan left. The evaluator walks + // with the plan's compiled evaluator, or with its interpreter until the background compiler builds one. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void CompiledSelectionChoosesAndReadsWhatTheEvaluatorDoes(bool compiledEvaluator) + { + var shapes = Shapes(); + if (compiledEvaluator) + { + foreach (var shape in shapes) + { + shape.Plan.CompileEvaluatorNow(); + } + } + + var outcomes = shapes.Select(_ => new HashSet()).ToArray(); + var random = new System.Random(compiledEvaluator ? 0x5E1EC7 : 0x7A11); + for (var draw = 0; draw < 1024; draw++) + { + for (var index = 0; index < shapes.Length; index++) + { + var shape = shapes[index]; + Assert.NotEmpty(shape.Plan.ResourceBranches); + var active = AssertSelectionMatchesEvaluator(shape.Plan, shape.Draw(random), $"shape={shape.Name} draw={draw}"); + outcomes[index].Add(string.Concat(active.Select(source => source ? '1' : '0'))); + } + } + + // Every shape took more than one selection; the write guard both pruned and kept every source. + for (var index = 0; index < shapes.Length; index++) + { + Assert.True(outcomes[index].Count > 1, $"shape={shapes[index].Name} took one selection"); + } + + var guard = outcomes[Array.FindIndex(shapes, shape => shape.Name == "write guard")]; + Assert.Contains(guard, outcome => outcome.Contains('0')); + Assert.Contains(guard, outcome => !outcome.Contains('0')); + } + + // A condition the registers do not cover, here a first-lane read, leaves the program's selection to the evaluator. + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void AConditionThatDoesNotLowerIsSelectedByTheEvaluator(uint condition) + { + var plan = Extract(Program( + MoveVectorFromScalar(0, 1, 8), ReadFirstLane(4, 9, 1), + Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(9), Operand(1)), Branch(12, "SCbranchScc1", 3), + BufferLoad(16, 0), Branch(24, "SBranch", 2), BufferLoad(28, 4), EndProgram(36))); + Assert.NotEmpty(plan.ResourceBranches); + Assert.NotNull(plan.MaterializationProgram); + Assert.Null(plan.BranchSelection); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(UserData(condition), readCleanMemory: CleanRead), ref snapshot, + ref specialization)); + Assert.Equal(condition == 0 ? 0x1000u : 0u, snapshot.Buffers[0][0]); + Assert.Equal(condition == 1 ? 0x2000u : 0u, snapshot.Buffers[1][0]); + } + + // The selection reads through the clean reader only; a draw without one is left to the evaluator. + [Fact] + public void ADrawWithoutACleanReaderIsLeftToTheEvaluator() + { + var plan = Extract(LoadedPredicate()); + var selection = Assert.IsType(plan.BranchSelection); + var active = new bool[selection.SourceCount]; + Assert.False(selection.TrySelect(Inputs([.. UserData(0), 0, 0, 0, 0x3000, 0], GeneralRead), active)); + Assert.All(active, Assert.False); + } + + // A guest read can select another draw's sources on the same thread: the outer selection keeps its values, its pending + // blocks and the reads its write guard checks. + [Fact] + public void ASelectionInsideAGuestReadLeavesTheOuterSelectionIntact() + { + var inner = Extract(NestedLoads()); + var innerMemory = new WordMemory(); + innerMemory.Words[0x5000] = 2; + innerMemory.Words[0x5004] = 1; + var innerInputs = Inputs(FourBuffers(6, 0, 0x5000, 0), GeneralRead, innerMemory.Read); + var innerExpected = RuntimeValueEvaluator.EvaluateActiveSources(inner, innerInputs); + var nested = 0; + var memory = new WordMemory(); + memory.Words[0x1000] = 0; + bool Reentering(ulong address, out uint word) + { + nested++; + var active = new bool[inner.BranchSelection!.SourceCount]; + Assert.True(inner.BranchSelection.TrySelect(innerInputs, active)); + Assert.Equal(innerExpected, active); + return memory.Read(address, out word); + } + + // The stored buffer covers the count, so the guard keeps every source; one that lost the count's read would prune. + var outer = ExtractWithWrites(CountedSampleThenStore(), true); + uint[] userData = [0x1000, 0, 16, 0, 0x1000, 0, 64, 0, .. VolumeImage, 0, 0, 0, 0]; + var expected = RuntimeValueEvaluator.EvaluateActiveSources(outer, Inputs(userData, GeneralRead, memory.Read)); + Assert.All(expected, Assert.True); + var selected = new bool[outer.BranchSelection!.SourceCount]; + Assert.True(outer.BranchSelection.TrySelect(Inputs(userData, GeneralRead, Reentering), selected)); + Assert.Equal(expected, selected); + Assert.Equal(1, nested); + } + + // A T# whose halves are scalar buffer reads at a uniform record offset is evaluated word by word; the arm that reads it + // is pruned like any other, through the program's full and fast paths. + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void AnImageReadWordByWordIsPrunedWithItsArm(uint condition) + { + var plan = Extract(RecordImageOrBuffer(), stage: ShaderStage.Pixel); + Assert.NotNull(plan.MaterializationProgram); + var image = Assert.Single(plan.Info.Images); + Assert.All(plan.DescriptorSources[(int)image.Source].Dwords, word => Assert.Equal(ScalarValueKind.ScalarBufferWord, word.Kind)); + var memory = ResourceTrackerTests.LinearMemory(); + var descriptor = ResourceTrackerTests.ImageDescriptor(); + // Record 2 starts at byte 256 of the table. + for (var word = 0; word < 4; word++) + { + memory.At(0x1000 + 256 + 16 + (ulong)word * 4) = descriptor[word]; + memory.At(0x1000 + 256 + 96 + (ulong)word * 4) = descriptor[4 + word]; + } + + var snapshot = Materialize(plan, Inputs(RecordUserData(2, condition), memory.Read, memory.Read)); + // The table the T# is read from is a buffer of the image's arm. + uint[] table = [0x1000, 0, 0x200, 0]; + uint[] buffer = [0x2000, 0, 256, 0]; + if (condition == 0) + { + Assert.Equal([new uint[4], buffer], snapshot.Buffers); + Assert.All(Assert.Single(snapshot.Images), word => Assert.Equal(0u, word)); + } + else + { + Assert.Equal([table, new uint[4]], snapshot.Buffers); + Assert.Equal(descriptor, Assert.Single(snapshot.Images)); + } + } +} From cf5d9596f6c0d7bf9c6fc98a2d52d6aedb2c1047 Mon Sep 17 00:00:00 2001 From: Foued Attar Date: Fri, 20 Nov 2026 17:33:29 +0100 Subject: [PATCH 02/64] fix(gpu): keep compute ticket scans to compute registers (#1154) The compute ticket scan replayed every shader register write of a run into its shadow banks and failed fatally on any it did not know. Gnm (PS4) titles write graphics stage registers in their own layout and the per-engine CU masks (COMPUTE_STATIC_THREAD_MGMT_SE0..3), so Bloodborne died on 0x216 right after boot. The scan now applies only compute registers (0x200..0x250), an unknown write there ends the prediction instead of the process, and the CU masks are accepted and ignored since the host GPU schedules compute work. --- .../GpuCommandInterpreter.ComputeTickets.cs | 40 +++++++++++-- .../GpuCommands/Registers/RegisterOffsets.cs | 4 ++ .../Registers/RegisterWriters.Shader.cs | 6 ++ .../Gpu/Pipelines/ComputeTicketTests.cs | 59 +++++++++++++++++++ 4 files changed, 103 insertions(+), 6 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs index a85bafbd3..7c701475a 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.ComputeTickets.cs @@ -13,6 +13,10 @@ public sealed partial class GpuCommandInterpreter private const int TicketScanChunkDwords = 256; private const uint TicketTableEntries = 512; + // The compute registers, through the last compute user scalar: the only ones a prediction reads. + private const uint FirstComputeRegister = 0x200; + private const uint ComputeRegisterEnd = 0x250; + private RegisterBanks? _ticketShadow; private uint[]? _ticketWords; private ulong[]? _ticketFound; @@ -27,7 +31,17 @@ private void ScanComputeTickets(ComputeTickets tickets, in PacketContext packet, { var found = _ticketFound ??= new ulong[ComputeTickets.MaxLead]; var count = 0; - var stopped = ScanComputeTicketsCore(tickets, in packet, requestedThrough, found, ref count); + bool stopped; + try + { + stopped = ScanComputeTicketsCore(tickets, in packet, requestedThrough, found, ref count); + } + catch (TicketScanStop) + { + // A register write the shadow cannot apply ends the prediction; the dispatch that makes it reports it. + stopped = true; + } + tickets.EndScan(this, packet.PacketAddress, found.AsSpan(0, count), stopped); } @@ -45,7 +59,7 @@ private bool ScanComputeTicketsCore(ComputeTickets tickets, in PacketContext pac var available = (int)Math.Min(remaining, (uint)ComputeTickets.MaxScanDwords); var words = _ticketWords ??= new uint[ComputeTickets.MaxScanDwords]; var read = 0; - var shadow = _ticketShadow ??= new RegisterBanks(_host.Fatal); + var shadow = _ticketShadow ??= new RegisterBanks(static message => new TicketScanStop(message)); shadow.Shader.Compute = TypedRegisters.Shader.Compute.Copy(); var position = 0; // The third dispatch of one shader in a row starts a deferred dispatch run, whose workers resolve it and the dispatches @@ -97,10 +111,18 @@ private bool ScanComputeTicketsCore(ComputeTickets tickets, in PacketContext pac return true; } - var context = new PacketContext(header & ~1u, address, (uint)position, (uint)(available - position), (uint)available); - if (RegisterWriteTable.WriteShaderPacket(shadow, in context, offset, payload.Slice(1, (int)values)) != values) + // Only the compute registers of the run reach the shadow: a graphics stage register cannot change a + // prediction, and a mode may write it in another layout (Gnm's PS4 stages) that its own packets translate. + var first = Math.Max(offset, FirstComputeRegister); + var end = Math.Min(offset + values, ComputeRegisterEnd); + if (first < end) { - return true; + var context = new PacketContext(header & ~1u, address, (uint)position, (uint)(available - position), (uint)available); + var written = payload.Slice(1 + (int)(first - offset), (int)(end - first)); + if (RegisterWriteTable.WriteShaderPacket(shadow, in context, first, written) != (uint)written.Length) + { + return true; + } } } } @@ -246,9 +268,15 @@ private bool ScanShaderRegisterTable(RegisterBanks shadow, ulong packetAddress, return false; } - RegisterWriteTable.WriteShaderEntry(shadow, offset, value, tableAddress); + if (offset is >= FirstComputeRegister and < ComputeRegisterEnd) + { + RegisterWriteTable.WriteShaderEntry(shadow, offset, value, tableAddress); + } } return true; } } + +// Ends a compute ticket scan at a register write the shadow cannot apply. +internal sealed class TicketScanStop(string message) : Exception(message); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterOffsets.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterOffsets.cs index 1533c44d8..543916234 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterOffsets.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterOffsets.cs @@ -220,7 +220,11 @@ public static class ShaderRegisterOffset public const uint ComputePgmRsrc1 = 0x212; public const uint ComputePgmRsrc2 = 0x213; public const uint ComputeResourceLimits = 0x215; + public const uint ComputeStaticThreadMgmtSe0 = 0x216; + public const uint ComputeStaticThreadMgmtSe1 = 0x217; public const uint ComputeTmpringSize = 0x218; + public const uint ComputeStaticThreadMgmtSe2 = 0x219; + public const uint ComputeStaticThreadMgmtSe3 = 0x21A; public const uint ComputeUserAccum0 = 0x224; public const uint ComputePgmRsrc3 = 0x228; public const uint ComputeShaderChecksum = 0x22A; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs index 0f2306323..70f76e6eb 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs @@ -17,6 +17,7 @@ internal static partial class RegisterWriters [ ComputePgmLo, ComputePgmHi, ComputePgmRsrc1, ComputePgmRsrc2, ComputeStartX, ComputeStartY, ComputeStartZ, ComputeNumThreadX, ComputeNumThreadY, ComputeNumThreadZ, ComputeResourceLimits, ComputeTmpringSize, ComputePgmRsrc3, ComputeShaderChecksum, + ComputeStaticThreadMgmtSe0, ComputeStaticThreadMgmtSe1, ComputeStaticThreadMgmtSe2, ComputeStaticThreadMgmtSe3, ]; private static readonly uint[] IgnoredShaderOffsets = @@ -233,6 +234,11 @@ private static void ComputeRegisterEntry(RegisterBanks banks, uint offset, uint case ComputeStartZ: case ComputeResourceLimits: case ComputeTmpringSize: + // The CU masks of each shader engine: the host GPU schedules compute work. + case ComputeStaticThreadMgmtSe0: + case ComputeStaticThreadMgmtSe1: + case ComputeStaticThreadMgmtSe2: + case ComputeStaticThreadMgmtSe3: break; default: throw banks.Fatal($"The compute shader register is not supported: offset=0x{offset:X4} value=0x{value:X8}."); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs index 3b44046d9..af20f0d33 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeTicketTests.cs @@ -190,6 +190,65 @@ public void TheScanFollowsShaderRegisterTablesAndPassesEventsAndMarkers() Assert.Equal(0x33u, runner.Interpreter.TypedRegisters.Shader.Compute.UserScalars.ValueSpan(1)[0]); } + // A PS4 title writes the compute CU masks and its own stage registers between dispatches (Bloodborne). The scan predicts + // through them: the masks are host-scheduled, and a graphics stage register cannot change a compute prediction. + [Fact] + public void TheScanPassesCuMasksAndStageRegistersOfAPs4Stream() + { + var (_, tickets) = CreateCache(workers: 0); + var requested = new List(); + tickets.RequestObserver = (_, compute, x, _, _, _) => requested.Add($"{compute.UserScalars.ValueSpan(1)[0]:X} {x}"); + var runner = new StreamRunner(); + runner.Host.ComputeTickets = tickets; + var packets = typeof(SharpEmu.GnmMode.GnmRuntime).Assembly.GetType("SharpEmu.GnmMode.Gpu.GnmCommandPackets")!; + runner.Interpreter.SetPacketHandlers((PacketHandler?[])packets.GetField("Handlers", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!.GetValue(null)!); + + runner.Run( + StreamRunner.Packet(PacketOpcode.DispatchDirect, 1, 1, 1, 0x41), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeStaticThreadMgmtSe0, 0xFFFF_FFFFu, 0xFFFF_FFFFu), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, 0x4C, 0x55), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeUserData0, 0x22), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 2, 1, 1, 0x41)); + + Assert.Equal(new[] { "22 2" }, requested); + Assert.Equal(2, runner.Host.Calls.Count(call => call.StartsWith("dispatch", StringComparison.Ordinal))); + } + + // The PS5 bank takes the CU masks too, in a run with the registers around them. + [Fact] + public void TheCuMasksAreHostScheduledComputeRegisters() + { + var runner = new StreamRunner(); + + runner.Run(StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.ComputeResourceLimits, 1, 2, 3, 4, 5, 6)); + + Assert.Equal(0, runner.Host.Calls.Count(call => call.StartsWith("dispatch", StringComparison.Ordinal))); + } + + // A compute register the shadow cannot apply ends the prediction; the packet that writes it reports it when it runs, + // after the dispatch that scanned it. + [Fact] + public void AnUnsupportedRegisterEndsTheScanWithoutAFatalError() + { + var (_, tickets) = CreateCache(workers: 0); + var requested = 0; + tickets.RequestObserver = (_, _, _, _, _, _) => requested++; + var runner = new StreamRunner(); + runner.Host.ComputeTickets = tickets; + + var fatal = runner.RunExpectingFatal( + StreamRunner.Packet(PacketOpcode.DispatchDirect, 1, 1, 1, 0x41), + StreamRunner.Packet(PacketOpcode.SetShaderRegister, UnsupportedComputeRegister, 1), + StreamRunner.Packet(PacketOpcode.DispatchDirect, 2, 1, 1, 0x41)); + + Assert.Contains($"unsupported=0x{UnsupportedComputeRegister:X4}", fatal.Message); + Assert.Equal(0, requested); + Assert.Equal(1, runner.Host.Calls.Count(call => call.StartsWith("dispatch", StringComparison.Ordinal))); + } + + private const uint UnsupportedComputeRegister = 0x21C; + // A ticket worker never compiles: a missing permutation asks for the serial resolve. [Fact] public void ASpeculativeResolveNeverCompilesAPermutation() From fc7b27301398295d80f8cd9e8256d2fe8ad1c79e Mon Sep 17 00:00:00 2001 From: Foued Attar Date: Fri, 20 Nov 2026 20:53:52 +0100 Subject: [PATCH 03/64] [HLE/FileSystem] Add PS4 PKG reader and installer * Add PKG reader and installer (fake PS4 packages) Parse the PKG header and entry table, decrypt the PFS image (XTS sectors, ekpfs/dk3 key derivation), read the PFSC/inode/dirent tree and extract it to a game folder block by block. Exposed as --install-pkg in the CLI and an Install PKG action in the library menu with a progress dialog. The RSA key tables (PkgKeys) are still empty placeholders. * Fill in the fake-PKG RSA key tables * [GUI] Install PKG files found in a folder added to the library * [GUI] Find PKG files recursively when adding a game folder * [GUI] Keep pre-existing folders when a PKG install fails * [PKG] Reject corrupt headers, entry sizes and inode tables * [Tests] Cover end-to-end PKG extraction and corrupt inputs * [PKG] Extract nptitle.dat and npbind.dat into sce_sys * [PKG] Make PFS stream Seek reject negative positions * [PKG] Read the package category from param.sfo and flag non-game packages * [PKG] Report progress inside large files and check free disk space before extracting * [CLI] Refuse patch and DLC packages in --install-pkg * [GUI] Translate the PKG install strings to French and add the new PKG prompts * [GUI] Skip patch and DLC packages and confirm folder PKG installs with the needed disk space * [PKG] Read the PFS block count at 0x38 like retail images Retail fake PKGs store the image's total block count at 0x38 (it equals the PFSC block count); the field at 0x28 holds 1. Reading 0x28 rejected every real package as having an implausible inode table. * [GUI] Close the PKG install sheet by itself once the install succeeds A folder of packages no longer needs a click per game; a failed install still stays open so its error can be read. * [GUI] Skip folder PKGs whose game is already extracted under the root The scan only looked at /, so a game installed next to its package (or by an earlier manual install) was extracted a second time and showed up as two versions. Games are now matched by the TITLE_ID of their param.sfo anywhere under the root, and two packages of one title in the same batch install once. * [PKG] Name install folders after the game's title A folder named CUSA33851 says nothing in a file browser. Installs from the GUI and the CLI now use the param.sfo TITLE, with characters Windows refuses replaced by spaces, and fall back to the title id, then the package file name. * [GUI] Translate the PKG install strings to every language * [PKG] Check file names against the Windows set on every host Path.GetInvalidFileNameChars() is only '/' and NUL on Linux, so a title like "Part I: Remastered" kept its ':' and a package entry holding '\' was accepted there. Folder names and the path-component check now use one fixed set, so extraction behaves the same on Windows and Linux. * [Tests] Retry splash test deletes while a virus scanner holds the image The win-x64 runner failed PrepareKeepsTheOriginalPngAndSurvivesSourceRemoval when an external process briefly kept the freshly written 4K PNG open; the splash cache itself closes its handles. --- src/SharpEmu.CLI/Program.cs | 65 ++ src/SharpEmu.GUI/Languages/ar.json | 16 + src/SharpEmu.GUI/Languages/az.json | 16 + src/SharpEmu.GUI/Languages/br.json | 16 + src/SharpEmu.GUI/Languages/de.json | 16 + src/SharpEmu.GUI/Languages/dk.json | 16 + src/SharpEmu.GUI/Languages/ee.json | 16 + src/SharpEmu.GUI/Languages/en.json | 16 + src/SharpEmu.GUI/Languages/es.json | 16 + src/SharpEmu.GUI/Languages/fr.json | 16 + src/SharpEmu.GUI/Languages/hu.json | 16 + src/SharpEmu.GUI/Languages/it.json | 16 + src/SharpEmu.GUI/Languages/ja.json | 16 + src/SharpEmu.GUI/Languages/ko.json | 16 + src/SharpEmu.GUI/Languages/nl.json | 16 + src/SharpEmu.GUI/Languages/pl.json | 16 + src/SharpEmu.GUI/Languages/pt.json | 16 + src/SharpEmu.GUI/Languages/ru.json | 16 + src/SharpEmu.GUI/Languages/tr.json | 16 + src/SharpEmu.GUI/Languages/zh.json | 16 + src/SharpEmu.GUI/LibraryMenu.axaml | 7 + src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs | 244 ++++++ src/SharpEmu.GUI/MainWindow.axaml.cs | 2 + src/SharpEmu.GUI/PkgConfirmDialog.axaml | 30 + src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs | 26 + src/SharpEmu.GUI/PkgInstallDialog.axaml | 45 ++ src/SharpEmu.GUI/PkgInstallDialog.axaml.cs | 149 ++++ src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs | 339 ++++++++ src/SharpEmu.HLE/FileSystem/Pkg/PkgCrypto.cs | 149 ++++ src/SharpEmu.HLE/FileSystem/Pkg/PkgFile.cs | 180 +++++ src/SharpEmu.HLE/FileSystem/Pkg/PkgKeys.cs | 21 + src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs | 386 ++++++++++ .../FileSystem/Pkg/PkgParamSfo.cs | 81 ++ .../FileSystem/Pkg/PkgPfsStream.cs | 141 ++++ .../FileSystem/PkgTests.cs | 721 ++++++++++++++++++ .../GUI/ShortcutSplashTests.cs | 22 +- 36 files changed, 2910 insertions(+), 2 deletions(-) create mode 100644 src/SharpEmu.GUI/PkgConfirmDialog.axaml create mode 100644 src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs create mode 100644 src/SharpEmu.GUI/PkgInstallDialog.axaml create mode 100644 src/SharpEmu.GUI/PkgInstallDialog.axaml.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgCrypto.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgFile.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgKeys.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgParamSfo.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs create mode 100644 tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs index 0bd544a8e..f836612e1 100644 --- a/src/SharpEmu.CLI/Program.cs +++ b/src/SharpEmu.CLI/Program.cs @@ -162,6 +162,11 @@ private static int Run(string[] args) TryEnableConsoleFileMirror(earlyLogFilePath); } + if (args.Length > 0 && string.Equals(args[0], "--install-pkg", StringComparison.OrdinalIgnoreCase)) + { + return InstallPkg(args); + } + if (!CheckHostArchitecture()) { return 5; @@ -989,9 +994,69 @@ private static string QuoteArgument(string argument) return builder.ToString(); } + // --install-pkg <file.pkg> [destination]: unpacks a fake PS4 package into a game folder (by + // default <pkg folder>/<game title>) that can then be launched through its eboot.bin. + private static int InstallPkg(string[] args) + { + if (args.Length is < 2 or > 3) + { + Log.Error("Usage: SharpEmu.CLI --install-pkg <path-to-game.pkg> [destination-folder]"); + return 2; + } + + var pkgPath = Path.GetFullPath(args[1]); + if (!File.Exists(pkgPath)) + { + Log.Error($"Package not found: {pkgPath}"); + return 2; + } + + try + { + using var package = SharpEmu.HLE.FileSystem.Pkg.PkgPackage.Open(pkgPath); + if (!package.IsGameApplication) + { + Log.Error($"{Path.GetFileName(pkgPath)} is not a base game (category '{package.Category}'). Patches and DLC packages are not supported yet."); + return 2; + } + + var destination = args.Length == 3 + ? Path.GetFullPath(args[2]) + : Path.Combine( + Path.GetDirectoryName(pkgPath)!, + package.GetFolderName(Path.GetFileNameWithoutExtension(pkgPath))); + Log.Info($"Installing {Path.GetFileName(pkgPath)} ({package.Header.ContentId}) into {destination}"); + + var lastPercent = -1; + var progress = new SynchronousProgress<SharpEmu.HLE.FileSystem.Pkg.PkgExtractProgress>(report => + { + var percent = report.BytesTotal == 0 ? 100 : (int)(report.BytesDone * 100 / report.BytesTotal); + if (percent != lastPercent) + { + lastPercent = percent; + Log.Info($"{percent,3}% {report.BytesDone / (1024.0 * 1024 * 1024):0.00} / {report.BytesTotal / (1024.0 * 1024 * 1024):0.00} GB {report.CurrentFile}"); + } + }); + package.Extract(destination, progress); + Log.Info($"Done. Launch it with: SharpEmu.CLI \"{Path.Combine(destination, "eboot.bin")}\""); + return 0; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException) + { + Log.Error($"Installing the package failed: {exception.Message}"); + return 1; + } + } + + private sealed class SynchronousProgress<T>(Action<T> handler) : IProgress<T> + { + public void Report(T value) => handler(value); + } + private static void PrintUsage() { Log.Info("Usage: SharpEmu.CLI [--strict[=on|off]] [--trace-imports[=N]] [--cpu-engine=<native>] [--console=<ps5>] [--console-language=<language>] [--log-level=<level>] [--log-file[=<path>]] [--no-log-file] [--window-mode=<windowed|borderless|exclusive>] [--resolution=<WIDTHxHEIGHT>] [--display=<N>] [--refresh-rate=<HZ>] [--scaling=<fit|cover|stretch|integer>] [--vsync=<on|off>] [--hdr=<auto|on|off>] [--overlay=<on|off>] [--overlay-mode=<full|minimal|titlebar>] [--overlay-corner=<topleft|topright|bottomright|bottomleft>] [--debug-server[=host:port]] <path-to-eboot.bin|path-to-game.zar>"); + Log.Info("Install a fake PS4 package: SharpEmu.CLI --install-pkg <path-to-game.pkg> [destination-folder]"); Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin"""); Log.Info("Debug server: --debug-server starts a live debug listener (default 127.0.0.1:5714); connect with SharpEmu.DebugClient."); } diff --git a/src/SharpEmu.GUI/Languages/ar.json b/src/SharpEmu.GUI/Languages/ar.json index 4eb901b60..c2a4a254d 100644 --- a/src/SharpEmu.GUI/Languages/ar.json +++ b/src/SharpEmu.GUI/Languages/ar.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "مستوى الصوت", "LibraryMenu.AddGames": "إضافة ألعاب", "LibraryMenu.AddFolder": "إضافة مجلد…", + "Library.Pkg.Install": "تثبيت PKG…", + "Library.Pkg.Heading": "جارٍ تثبيت {0}", + "Library.Pkg.Explanation": "يفك هذا الإجراء ضغط ملف PKG المزيف في مجلد لعبة يشغّله SharpEmu مثل أي لعبة أخرى. تستغرق الحزم الكبيرة وقتاً وتحتاج إلى مساحة قرص خالية للعبة بأكملها.", + "Library.Pkg.Preparing": "جارٍ قراءة الحزمة…", + "Library.Pkg.Progress": "{0} / {1} غيغابايت ({2}%)", + "Library.Pkg.Cancelling": "جارٍ الإلغاء…", + "Library.Pkg.Failed": "فشل التثبيت: {0}", + "Library.Pkg.SkippedNotGame": "تم تخطي {0}: حزم التحديثات والمحتوى الإضافي (DLC) غير مدعومة بعد ({1}).", + "Library.Pkg.AlreadyInstalled": "تم تخطي {0}: مثبّتة بالفعل في {1}.", + "Library.Pkg.ConfirmTitle": "تثبيت ملفات PKG؟", + "Library.Pkg.ConfirmMessage": "تم العثور على {0} من ملفات PKG في هذا المجلد. هل تريد تثبيتها الآن؟ يتطلب ذلك {1} غيغابايت من المساحة الخالية.", + "Library.Pkg.ConfirmInstall": "تثبيت", + "Library.Pkg.ConfirmSkip": "ليس الآن", + "Dialog.OpenPkg": "اختر ملف PKG لتثبيته", + "Dialog.PkgFiles": "حزم PS4", + "Dialog.ChoosePkgInstallFolder": "اختر مكان تثبيت اللعبة", "Hero.GameSettings": "إعدادات اللعبة", "Hero.Console": "وحدة التحكم", "Hint.LibraryMenu": "قائمة المكتبة", diff --git a/src/SharpEmu.GUI/Languages/az.json b/src/SharpEmu.GUI/Languages/az.json index 68bc0231b..881799123 100644 --- a/src/SharpEmu.GUI/Languages/az.json +++ b/src/SharpEmu.GUI/Languages/az.json @@ -41,6 +41,22 @@ "LibraryMenu.Volume": "Səs səviyyəsi", "LibraryMenu.AddGames": "Oyun əlavə et", "LibraryMenu.AddFolder": "Qovluq əlavə et…", + "Library.Pkg.Install": "PKG quraşdır…", + "Library.Pkg.Heading": "{0} quraşdırılır", + "Library.Pkg.Explanation": "Bu əməliyyat saxta PKG-ni SharpEmu-nun digərləri kimi işlətdiyi oyun qovluğuna açır. Böyük paketlər xeyli vaxt aparır və bütün oyun üçün boş disk sahəsi tələb edir.", + "Library.Pkg.Preparing": "Paket oxunur…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Ləğv edilir…", + "Library.Pkg.Failed": "Quraşdırma uğursuz oldu: {0}", + "Library.Pkg.SkippedNotGame": "{0} atlandı: yamaq və DLC paketləri hələ dəstəklənmir ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} atlandı: artıq {1} qovluğunda quraşdırılıb.", + "Library.Pkg.ConfirmTitle": "PKG faylları quraşdırılsın?", + "Library.Pkg.ConfirmMessage": "Bu qovluqda {0} PKG faylı tapıldı. İndi quraşdırılsın? Bunun üçün {1} GB boş yer lazımdır.", + "Library.Pkg.ConfirmInstall": "Quraşdır", + "Library.Pkg.ConfirmSkip": "İndi yox", + "Dialog.OpenPkg": "Quraşdırılacaq PKG-ni seçin", + "Dialog.PkgFiles": "PS4 paketləri", + "Dialog.ChoosePkgInstallFolder": "Oyunun quraşdırılacağı yeri seçin", "Hero.GameSettings": "Oyun ayarları", "Hero.Console": "Konsol", "Hint.LibraryMenu": "Kitabxana menyusu", diff --git a/src/SharpEmu.GUI/Languages/br.json b/src/SharpEmu.GUI/Languages/br.json index edc1151fe..8519aeb93 100644 --- a/src/SharpEmu.GUI/Languages/br.json +++ b/src/SharpEmu.GUI/Languages/br.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Volume", "LibraryMenu.AddGames": "Adicionar jogos", "LibraryMenu.AddFolder": "Adicionar pasta…", + "Library.Pkg.Install": "Instalar PKG…", + "Library.Pkg.Heading": "Instalando {0}", + "Library.Pkg.Explanation": "Isso extrai o PKG falso para uma pasta de jogo que o SharpEmu executa como qualquer outra. Pacotes grandes demoram e precisam de espaço livre em disco para o jogo inteiro.", + "Library.Pkg.Preparing": "Lendo o pacote…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Cancelando…", + "Library.Pkg.Failed": "Falha na instalação: {0}", + "Library.Pkg.SkippedNotGame": "{0} ignorado: pacotes de patch e DLC ainda não são suportados ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} ignorado: já instalado em {1}.", + "Library.Pkg.ConfirmTitle": "Instalar arquivos PKG?", + "Library.Pkg.ConfirmMessage": "{0} arquivo(s) PKG encontrado(s) nesta pasta. Instalar agora? Isso exige {1} GB de espaço livre.", + "Library.Pkg.ConfirmInstall": "Instalar", + "Library.Pkg.ConfirmSkip": "Agora não", + "Dialog.OpenPkg": "Escolha um PKG para instalar", + "Dialog.PkgFiles": "Pacotes de PS4", + "Dialog.ChoosePkgInstallFolder": "Escolha onde instalar o jogo", "Hero.GameSettings": "Configurações do jogo", "Hero.Console": "Console", "Hint.LibraryMenu": "Menu da biblioteca", diff --git a/src/SharpEmu.GUI/Languages/de.json b/src/SharpEmu.GUI/Languages/de.json index dbd7dae4c..a0c0f5d6d 100644 --- a/src/SharpEmu.GUI/Languages/de.json +++ b/src/SharpEmu.GUI/Languages/de.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Lautstärke", "LibraryMenu.AddGames": "Spiele hinzufügen", "LibraryMenu.AddFolder": "Ordner hinzufügen…", + "Library.Pkg.Install": "PKG installieren…", + "Library.Pkg.Heading": "{0} wird installiert", + "Library.Pkg.Explanation": "Dadurch wird das gefälschte PKG in einen Spielordner entpackt, den SharpEmu wie jeden anderen startet. Große Pakete brauchen etwas Zeit und freien Speicherplatz für das gesamte Spiel.", + "Library.Pkg.Preparing": "Paket wird gelesen…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Wird abgebrochen…", + "Library.Pkg.Failed": "Installation fehlgeschlagen: {0}", + "Library.Pkg.SkippedNotGame": "{0} übersprungen: Patches und DLC-Pakete werden noch nicht unterstützt ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} übersprungen: bereits in {1} installiert.", + "Library.Pkg.ConfirmTitle": "PKG-Dateien installieren?", + "Library.Pkg.ConfirmMessage": "{0} PKG-Datei(en) in diesem Ordner gefunden. Jetzt installieren? Dafür werden {1} GB freier Speicherplatz benötigt.", + "Library.Pkg.ConfirmInstall": "Installieren", + "Library.Pkg.ConfirmSkip": "Nicht jetzt", + "Dialog.OpenPkg": "PKG zum Installieren auswählen", + "Dialog.PkgFiles": "PS4-Pakete", + "Dialog.ChoosePkgInstallFolder": "Wähle, wo das Spiel installiert werden soll", "Hero.GameSettings": "Spieleinstellungen", "Hero.Console": "Konsole", "Hint.LibraryMenu": "Bibliotheksmenü", diff --git a/src/SharpEmu.GUI/Languages/dk.json b/src/SharpEmu.GUI/Languages/dk.json index 02c7afc40..e9aaed451 100644 --- a/src/SharpEmu.GUI/Languages/dk.json +++ b/src/SharpEmu.GUI/Languages/dk.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Lydstyrke", "LibraryMenu.AddGames": "Tilføj spil", "LibraryMenu.AddFolder": "Tilføj mappe…", + "Library.Pkg.Install": "Installer PKG…", + "Library.Pkg.Heading": "Installerer {0}", + "Library.Pkg.Explanation": "Dette udpakker den falske PKG til en spilmappe, som SharpEmu kører som alle andre. Store pakker tager tid og kræver ledig diskplads til hele spillet.", + "Library.Pkg.Preparing": "Læser pakken…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Annullerer…", + "Library.Pkg.Failed": "Installationen mislykkedes: {0}", + "Library.Pkg.SkippedNotGame": "{0} sprunget over: patch- og DLC-pakker understøttes endnu ikke ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} sprunget over: allerede installeret i {1}.", + "Library.Pkg.ConfirmTitle": "Installer PKG-filer?", + "Library.Pkg.ConfirmMessage": "Fandt {0} PKG-fil(er) i denne mappe. Vil du installere dem nu? Det kræver {1} GB ledig plads.", + "Library.Pkg.ConfirmInstall": "Installer", + "Library.Pkg.ConfirmSkip": "Ikke nu", + "Dialog.OpenPkg": "Vælg en PKG der skal installeres", + "Dialog.PkgFiles": "PS4-pakker", + "Dialog.ChoosePkgInstallFolder": "Vælg hvor spillet skal installeres", "Hero.GameSettings": "Spilindstillinger", "Hero.Console": "Konsol", "Hint.LibraryMenu": "Biblioteksmenu", diff --git a/src/SharpEmu.GUI/Languages/ee.json b/src/SharpEmu.GUI/Languages/ee.json index 8d364db77..b12d89ee3 100644 --- a/src/SharpEmu.GUI/Languages/ee.json +++ b/src/SharpEmu.GUI/Languages/ee.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Helitugevus", "LibraryMenu.AddGames": "Lisa mänge", "LibraryMenu.AddFolder": "Lisa kaust…", + "Library.Pkg.Install": "Installi PKG…", + "Library.Pkg.Heading": "Installin {0}", + "Library.Pkg.Explanation": "See pakib võlts-PKG lahti mängukausta, mida SharpEmu käivitab nagu iga teist. Suured paketid võtavad aega ja vajavad vaba kettaruumi kogu mängu jaoks.", + "Library.Pkg.Preparing": "Paketi lugemine…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Tühistamine…", + "Library.Pkg.Failed": "Installimine ebaõnnestus: {0}", + "Library.Pkg.SkippedNotGame": "{0} jäeti vahele: paigad ja DLC-paketid ei ole veel toetatud ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} jäeti vahele: juba installitud kausta {1}.", + "Library.Pkg.ConfirmTitle": "Kas installida PKG-failid?", + "Library.Pkg.ConfirmMessage": "Sellest kaustast leiti {0} PKG-faili. Kas installida need nüüd? See vajab {1} GB vaba ruumi.", + "Library.Pkg.ConfirmInstall": "Installi", + "Library.Pkg.ConfirmSkip": "Mitte praegu", + "Dialog.OpenPkg": "Vali installitav PKG", + "Dialog.PkgFiles": "PS4 paketid", + "Dialog.ChoosePkgInstallFolder": "Vali, kuhu mäng installida", "Hero.GameSettings": "Mängu seaded", "Hero.Console": "Konsool", "Hint.LibraryMenu": "Teegi menüü", diff --git a/src/SharpEmu.GUI/Languages/en.json b/src/SharpEmu.GUI/Languages/en.json index f4bcc4400..3e06bdff7 100644 --- a/src/SharpEmu.GUI/Languages/en.json +++ b/src/SharpEmu.GUI/Languages/en.json @@ -56,6 +56,22 @@ "LibraryMenu.Volume": "Volume", "LibraryMenu.AddGames": "Add games", "LibraryMenu.AddFolder": "Add folder…", + "Library.Pkg.Install": "Install PKG…", + "Library.Pkg.Heading": "Installing {0}", + "Library.Pkg.Explanation": "This unpacks the fake PKG into a game folder that SharpEmu runs like any other. Large packages take a while and need free disk space for the whole game.", + "Library.Pkg.Preparing": "Reading the package…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Cancelling…", + "Library.Pkg.Failed": "Installing failed: {0}", + "Library.Pkg.SkippedNotGame": "Skipped {0}: patches and DLC packages are not supported yet ({1}).", + "Library.Pkg.AlreadyInstalled": "Skipped {0}: already installed in {1}.", + "Library.Pkg.ConfirmTitle": "Install PKG files?", + "Library.Pkg.ConfirmMessage": "Found {0} PKG file(s) in this folder. Install them now? This needs {1} GB of free space.", + "Library.Pkg.ConfirmInstall": "Install", + "Library.Pkg.ConfirmSkip": "Not now", + "Dialog.OpenPkg": "Choose a PKG to install", + "Dialog.PkgFiles": "PS4 packages", + "Dialog.ChoosePkgInstallFolder": "Choose where to install the game", "Hero.GameSettings": "Game settings", "Hero.Console": "Console", "Hint.LibraryMenu": "Library menu", diff --git a/src/SharpEmu.GUI/Languages/es.json b/src/SharpEmu.GUI/Languages/es.json index 7d431316a..8fe293054 100644 --- a/src/SharpEmu.GUI/Languages/es.json +++ b/src/SharpEmu.GUI/Languages/es.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Volumen", "LibraryMenu.AddGames": "Añadir juegos", "LibraryMenu.AddFolder": "Añadir carpeta…", + "Library.Pkg.Install": "Instalar PKG…", + "Library.Pkg.Heading": "Instalando {0}", + "Library.Pkg.Explanation": "Esto descomprime el PKG falso en una carpeta de juego que SharpEmu ejecuta como cualquier otra. Los paquetes grandes tardan y necesitan espacio libre en disco para todo el juego.", + "Library.Pkg.Preparing": "Leyendo el paquete…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Cancelando…", + "Library.Pkg.Failed": "Error al instalar: {0}", + "Library.Pkg.SkippedNotGame": "{0} omitido: los paquetes de parches y DLC aún no son compatibles ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} omitido: ya está instalado en {1}.", + "Library.Pkg.ConfirmTitle": "¿Instalar archivos PKG?", + "Library.Pkg.ConfirmMessage": "Se encontraron {0} archivo(s) PKG en esta carpeta. ¿Instalarlos ahora? Esto requiere {1} GB de espacio libre.", + "Library.Pkg.ConfirmInstall": "Instalar", + "Library.Pkg.ConfirmSkip": "Ahora no", + "Dialog.OpenPkg": "Elige un PKG para instalar", + "Dialog.PkgFiles": "Paquetes de PS4", + "Dialog.ChoosePkgInstallFolder": "Elige dónde instalar el juego", "Hero.GameSettings": "Ajustes del juego", "Hero.Console": "Consola", "Hint.LibraryMenu": "Menú de la biblioteca", diff --git a/src/SharpEmu.GUI/Languages/fr.json b/src/SharpEmu.GUI/Languages/fr.json index 150e730eb..6cb94938f 100644 --- a/src/SharpEmu.GUI/Languages/fr.json +++ b/src/SharpEmu.GUI/Languages/fr.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Volume", "LibraryMenu.AddGames": "Ajouter des jeux", "LibraryMenu.AddFolder": "Ajouter un dossier…", + "Library.Pkg.Install": "Installer un PKG…", + "Library.Pkg.Heading": "Installation de {0}", + "Library.Pkg.Explanation": "Cette action décompresse le faux PKG dans un dossier de jeu que SharpEmu lance comme n’importe quel autre. Les gros paquets prennent du temps et nécessitent assez d’espace disque pour tout le jeu.", + "Library.Pkg.Preparing": "Lecture du paquet…", + "Library.Pkg.Progress": "{0} / {1} Go ({2} %)", + "Library.Pkg.Cancelling": "Annulation…", + "Library.Pkg.Failed": "Échec de l’installation : {0}", + "Library.Pkg.SkippedNotGame": "{0} ignoré : les paquets de correctif et de DLC ne sont pas encore pris en charge ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} ignoré : déjà installé dans {1}.", + "Library.Pkg.ConfirmTitle": "Installer les fichiers PKG ?", + "Library.Pkg.ConfirmMessage": "{0} fichier(s) PKG trouvé(s) dans ce dossier. Les installer maintenant ? Cela nécessite {1} Go d’espace libre.", + "Library.Pkg.ConfirmInstall": "Installer", + "Library.Pkg.ConfirmSkip": "Pas maintenant", + "Dialog.OpenPkg": "Choisir un PKG à installer", + "Dialog.PkgFiles": "Paquets PS4", + "Dialog.ChoosePkgInstallFolder": "Choisir où installer le jeu", "Hero.GameSettings": "Paramètres du jeu", "Hero.Console": "Console", "Hint.LibraryMenu": "Menu de la bibliothèque", diff --git a/src/SharpEmu.GUI/Languages/hu.json b/src/SharpEmu.GUI/Languages/hu.json index c6fad4972..bc58905b9 100644 --- a/src/SharpEmu.GUI/Languages/hu.json +++ b/src/SharpEmu.GUI/Languages/hu.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Hangerő", "LibraryMenu.AddGames": "Játékok hozzáadása", "LibraryMenu.AddFolder": "Mappa hozzáadása…", + "Library.Pkg.Install": "PKG telepítése…", + "Library.Pkg.Heading": "{0} telepítése", + "Library.Pkg.Explanation": "Ez kicsomagolja a hamis PKG-t egy játékmappába, amelyet a SharpEmu úgy futtat, mint bármelyik másikat. A nagy csomagok sokáig tartanak, és a teljes játékhoz elegendő szabad lemezterület kell.", + "Library.Pkg.Preparing": "Csomag olvasása…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Megszakítás…", + "Library.Pkg.Failed": "A telepítés sikertelen: {0}", + "Library.Pkg.SkippedNotGame": "{0} kihagyva: a javítócsomagok és a DLC-csomagok még nem támogatottak ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} kihagyva: már telepítve van ide: {1}.", + "Library.Pkg.ConfirmTitle": "Telepíti a PKG-fájlokat?", + "Library.Pkg.ConfirmMessage": "{0} PKG-fájl található ebben a mappában. Telepíti őket most? Ehhez {1} GB szabad hely szükséges.", + "Library.Pkg.ConfirmInstall": "Telepítés", + "Library.Pkg.ConfirmSkip": "Most nem", + "Dialog.OpenPkg": "Válassza ki a telepítendő PKG-t", + "Dialog.PkgFiles": "PS4-csomagok", + "Dialog.ChoosePkgInstallFolder": "Válassza ki, hová települjön a játék", "Hero.GameSettings": "Játékbeállítások", "Hero.Console": "Konzol", "Hint.LibraryMenu": "Könyvtár menü", diff --git a/src/SharpEmu.GUI/Languages/it.json b/src/SharpEmu.GUI/Languages/it.json index 30e7b0120..d52620838 100644 --- a/src/SharpEmu.GUI/Languages/it.json +++ b/src/SharpEmu.GUI/Languages/it.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Volume", "LibraryMenu.AddGames": "Aggiungi giochi", "LibraryMenu.AddFolder": "Aggiungi cartella…", + "Library.Pkg.Install": "Installa PKG…", + "Library.Pkg.Heading": "Installazione di {0}", + "Library.Pkg.Explanation": "Questa operazione estrae il PKG fittizio in una cartella di gioco che SharpEmu esegue come qualsiasi altra. I pacchetti grandi richiedono tempo e spazio libero su disco per l'intero gioco.", + "Library.Pkg.Preparing": "Lettura del pacchetto…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Annullamento…", + "Library.Pkg.Failed": "Installazione non riuscita: {0}", + "Library.Pkg.SkippedNotGame": "{0} ignorato: i pacchetti di patch e DLC non sono ancora supportati ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} ignorato: già installato in {1}.", + "Library.Pkg.ConfirmTitle": "Installare i file PKG?", + "Library.Pkg.ConfirmMessage": "Trovati {0} file PKG in questa cartella. Installarli ora? Servono {1} GB di spazio libero.", + "Library.Pkg.ConfirmInstall": "Installa", + "Library.Pkg.ConfirmSkip": "Non ora", + "Dialog.OpenPkg": "Scegli un PKG da installare", + "Dialog.PkgFiles": "Pacchetti PS4", + "Dialog.ChoosePkgInstallFolder": "Scegli dove installare il gioco", "Hero.GameSettings": "Impostazioni del gioco", "Hero.Console": "Console", "Hint.LibraryMenu": "Menu della libreria", diff --git a/src/SharpEmu.GUI/Languages/ja.json b/src/SharpEmu.GUI/Languages/ja.json index 98a56c804..509de7e93 100644 --- a/src/SharpEmu.GUI/Languages/ja.json +++ b/src/SharpEmu.GUI/Languages/ja.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "音量", "LibraryMenu.AddGames": "ゲームを追加", "LibraryMenu.AddFolder": "フォルダーを追加…", + "Library.Pkg.Install": "PKGをインストール…", + "Library.Pkg.Heading": "{0} をインストール中", + "Library.Pkg.Explanation": "偽のPKGをゲームフォルダーに展開します。SharpEmu は他のゲームと同じように実行できます。大きなパッケージは時間がかかり、ゲーム全体のための空きディスク容量が必要です。", + "Library.Pkg.Preparing": "パッケージを読み込み中…", + "Library.Pkg.Progress": "{0} / {1} GB({2}%)", + "Library.Pkg.Cancelling": "キャンセル中…", + "Library.Pkg.Failed": "インストールに失敗しました: {0}", + "Library.Pkg.SkippedNotGame": "{0} をスキップしました: パッチと DLC のパッケージにはまだ対応していません({1})。", + "Library.Pkg.AlreadyInstalled": "{0} をスキップしました: {1} にインストール済みです。", + "Library.Pkg.ConfirmTitle": "PKGファイルをインストールしますか?", + "Library.Pkg.ConfirmMessage": "このフォルダーに PKG ファイルが {0} 個見つかりました。今すぐインストールしますか? {1} GB の空き容量が必要です。", + "Library.Pkg.ConfirmInstall": "インストール", + "Library.Pkg.ConfirmSkip": "今はしない", + "Dialog.OpenPkg": "インストールする PKG を選択", + "Dialog.PkgFiles": "PS4 パッケージ", + "Dialog.ChoosePkgInstallFolder": "ゲームのインストール先を選択", "Hero.GameSettings": "ゲーム設定", "Hero.Console": "コンソール", "Hint.LibraryMenu": "ライブラリメニュー", diff --git a/src/SharpEmu.GUI/Languages/ko.json b/src/SharpEmu.GUI/Languages/ko.json index cabe542b1..aef6daeed 100644 --- a/src/SharpEmu.GUI/Languages/ko.json +++ b/src/SharpEmu.GUI/Languages/ko.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "볼륨", "LibraryMenu.AddGames": "게임 추가", "LibraryMenu.AddFolder": "폴더 추가…", + "Library.Pkg.Install": "PKG 설치…", + "Library.Pkg.Heading": "{0} 설치 중", + "Library.Pkg.Explanation": "가짜 PKG를 게임 폴더에 풀어 SharpEmu가 다른 게임과 똑같이 실행할 수 있게 합니다. 큰 패키지는 시간이 걸리며 게임 전체를 위한 여유 디스크 공간이 필요합니다.", + "Library.Pkg.Preparing": "패키지 읽는 중…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "취소 중…", + "Library.Pkg.Failed": "설치 실패: {0}", + "Library.Pkg.SkippedNotGame": "{0} 건너뜀: 패치 및 DLC 패키지는 아직 지원되지 않습니다({1}).", + "Library.Pkg.AlreadyInstalled": "{0} 건너뜀: 이미 {1}에 설치되어 있습니다.", + "Library.Pkg.ConfirmTitle": "PKG 파일을 설치할까요?", + "Library.Pkg.ConfirmMessage": "이 폴더에서 PKG 파일 {0}개를 찾았습니다. 지금 설치할까요? {1} GB의 여유 공간이 필요합니다.", + "Library.Pkg.ConfirmInstall": "설치", + "Library.Pkg.ConfirmSkip": "나중에", + "Dialog.OpenPkg": "설치할 PKG 선택", + "Dialog.PkgFiles": "PS4 패키지", + "Dialog.ChoosePkgInstallFolder": "게임을 설치할 위치 선택", "Hero.GameSettings": "게임 설정", "Hero.Console": "콘솔", "Hint.LibraryMenu": "라이브러리 메뉴", diff --git a/src/SharpEmu.GUI/Languages/nl.json b/src/SharpEmu.GUI/Languages/nl.json index ca1264472..f3aa27dbc 100644 --- a/src/SharpEmu.GUI/Languages/nl.json +++ b/src/SharpEmu.GUI/Languages/nl.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Volume", "LibraryMenu.AddGames": "Games toevoegen", "LibraryMenu.AddFolder": "Map toevoegen…", + "Library.Pkg.Install": "PKG installeren…", + "Library.Pkg.Heading": "{0} wordt geïnstalleerd", + "Library.Pkg.Explanation": "Hiermee wordt de nep-PKG uitgepakt in een gamemap die SharpEmu net als elke andere uitvoert. Grote pakketten duren even en hebben vrije schijfruimte nodig voor de hele game.", + "Library.Pkg.Preparing": "Pakket lezen…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Annuleren…", + "Library.Pkg.Failed": "Installeren mislukt: {0}", + "Library.Pkg.SkippedNotGame": "{0} overgeslagen: patch- en DLC-pakketten worden nog niet ondersteund ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} overgeslagen: al geïnstalleerd in {1}.", + "Library.Pkg.ConfirmTitle": "PKG-bestanden installeren?", + "Library.Pkg.ConfirmMessage": "{0} PKG-bestand(en) gevonden in deze map. Nu installeren? Hiervoor is {1} GB vrije ruimte nodig.", + "Library.Pkg.ConfirmInstall": "Installeren", + "Library.Pkg.ConfirmSkip": "Niet nu", + "Dialog.OpenPkg": "Kies een PKG om te installeren", + "Dialog.PkgFiles": "PS4-pakketten", + "Dialog.ChoosePkgInstallFolder": "Kies waar de game moet worden geïnstalleerd", "Hero.GameSettings": "Game-instellingen", "Hero.Console": "Console", "Hint.LibraryMenu": "Bibliotheekmenu", diff --git a/src/SharpEmu.GUI/Languages/pl.json b/src/SharpEmu.GUI/Languages/pl.json index badbab94b..a2267ac24 100644 --- a/src/SharpEmu.GUI/Languages/pl.json +++ b/src/SharpEmu.GUI/Languages/pl.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Głośność", "LibraryMenu.AddGames": "Dodaj gry", "LibraryMenu.AddFolder": "Dodaj folder…", + "Library.Pkg.Install": "Zainstaluj PKG…", + "Library.Pkg.Heading": "Instalowanie {0}", + "Library.Pkg.Explanation": "To rozpakowuje fałszywy PKG do folderu z grą, który SharpEmu uruchamia jak każdy inny. Duże pakiety trwają dłużej i wymagają wolnego miejsca na dysku na całą grę.", + "Library.Pkg.Preparing": "Odczytywanie pakietu…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "Anulowanie…", + "Library.Pkg.Failed": "Instalacja nie powiodła się: {0}", + "Library.Pkg.SkippedNotGame": "Pominięto {0}: pakiety poprawek i DLC nie są jeszcze obsługiwane ({1}).", + "Library.Pkg.AlreadyInstalled": "Pominięto {0}: już zainstalowano w {1}.", + "Library.Pkg.ConfirmTitle": "Zainstalować pliki PKG?", + "Library.Pkg.ConfirmMessage": "Znaleziono plików PKG w tym folderze: {0}. Zainstalować je teraz? Wymaga to {1} GB wolnego miejsca.", + "Library.Pkg.ConfirmInstall": "Zainstaluj", + "Library.Pkg.ConfirmSkip": "Nie teraz", + "Dialog.OpenPkg": "Wybierz PKG do zainstalowania", + "Dialog.PkgFiles": "Pakiety PS4", + "Dialog.ChoosePkgInstallFolder": "Wybierz, gdzie zainstalować grę", "Hero.GameSettings": "Ustawienia gry", "Hero.Console": "Konsola", "Hint.LibraryMenu": "Menu biblioteki", diff --git a/src/SharpEmu.GUI/Languages/pt.json b/src/SharpEmu.GUI/Languages/pt.json index 8cedb24cd..223e86778 100644 --- a/src/SharpEmu.GUI/Languages/pt.json +++ b/src/SharpEmu.GUI/Languages/pt.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Volume", "LibraryMenu.AddGames": "Adicionar jogos", "LibraryMenu.AddFolder": "Adicionar pasta…", + "Library.Pkg.Install": "Instalar PKG…", + "Library.Pkg.Heading": "A instalar {0}", + "Library.Pkg.Explanation": "Isto extrai o PKG falso para uma pasta de jogo que o SharpEmu executa como qualquer outra. Pacotes grandes demoram e precisam de espaço livre em disco para o jogo todo.", + "Library.Pkg.Preparing": "A ler o pacote…", + "Library.Pkg.Progress": "{0} / {1} GB ({2}%)", + "Library.Pkg.Cancelling": "A cancelar…", + "Library.Pkg.Failed": "Falha na instalação: {0}", + "Library.Pkg.SkippedNotGame": "{0} ignorado: os pacotes de patches e DLC ainda não são suportados ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} ignorado: já instalado em {1}.", + "Library.Pkg.ConfirmTitle": "Instalar ficheiros PKG?", + "Library.Pkg.ConfirmMessage": "Foram encontrados {0} ficheiro(s) PKG nesta pasta. Instalar agora? Isto requer {1} GB de espaço livre.", + "Library.Pkg.ConfirmInstall": "Instalar", + "Library.Pkg.ConfirmSkip": "Agora não", + "Dialog.OpenPkg": "Escolha um PKG para instalar", + "Dialog.PkgFiles": "Pacotes de PS4", + "Dialog.ChoosePkgInstallFolder": "Escolha onde instalar o jogo", "Hero.GameSettings": "Definições do jogo", "Hero.Console": "Consola", "Hint.LibraryMenu": "Menu da biblioteca", diff --git a/src/SharpEmu.GUI/Languages/ru.json b/src/SharpEmu.GUI/Languages/ru.json index fb3d32f93..42bd38cb4 100644 --- a/src/SharpEmu.GUI/Languages/ru.json +++ b/src/SharpEmu.GUI/Languages/ru.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Громкость", "LibraryMenu.AddGames": "Добавить игры", "LibraryMenu.AddFolder": "Добавить папку…", + "Library.Pkg.Install": "Установить PKG…", + "Library.Pkg.Heading": "Установка {0}", + "Library.Pkg.Explanation": "Поддельный PKG будет распакован в папку игры, которую SharpEmu запускает как любую другую. Большие пакеты распаковываются долго и требуют свободного места на диске для всей игры.", + "Library.Pkg.Preparing": "Чтение пакета…", + "Library.Pkg.Progress": "{0} / {1} ГБ ({2}%)", + "Library.Pkg.Cancelling": "Отмена…", + "Library.Pkg.Failed": "Не удалось установить: {0}", + "Library.Pkg.SkippedNotGame": "{0} пропущен: пакеты патчей и DLC пока не поддерживаются ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} пропущен: уже установлен в {1}.", + "Library.Pkg.ConfirmTitle": "Установить файлы PKG?", + "Library.Pkg.ConfirmMessage": "В этой папке найдено файлов PKG: {0}. Установить их сейчас? Потребуется {1} ГБ свободного места.", + "Library.Pkg.ConfirmInstall": "Установить", + "Library.Pkg.ConfirmSkip": "Не сейчас", + "Dialog.OpenPkg": "Выберите PKG для установки", + "Dialog.PkgFiles": "Пакеты PS4", + "Dialog.ChoosePkgInstallFolder": "Выберите, куда установить игру", "Hero.GameSettings": "Настройки игры", "Hero.Console": "Консоль", "Hint.LibraryMenu": "Меню библиотеки", diff --git a/src/SharpEmu.GUI/Languages/tr.json b/src/SharpEmu.GUI/Languages/tr.json index 5ed7a5cd0..a40cbd347 100644 --- a/src/SharpEmu.GUI/Languages/tr.json +++ b/src/SharpEmu.GUI/Languages/tr.json @@ -57,6 +57,22 @@ "LibraryMenu.Volume": "Ses düzeyi", "LibraryMenu.AddGames": "Oyun ekle", "LibraryMenu.AddFolder": "Klasör ekle…", + "Library.Pkg.Install": "PKG yükle…", + "Library.Pkg.Heading": "{0} yükleniyor", + "Library.Pkg.Explanation": "Bu işlem sahte PKG'yi, SharpEmu'nun diğerleri gibi çalıştırdığı bir oyun klasörüne açar. Büyük paketler zaman alır ve tüm oyun için boş disk alanı gerektirir.", + "Library.Pkg.Preparing": "Paket okunuyor…", + "Library.Pkg.Progress": "{0} / {1} GB (%{2})", + "Library.Pkg.Cancelling": "İptal ediliyor…", + "Library.Pkg.Failed": "Yükleme başarısız oldu: {0}", + "Library.Pkg.SkippedNotGame": "{0} atlandı: yama ve DLC paketleri henüz desteklenmiyor ({1}).", + "Library.Pkg.AlreadyInstalled": "{0} atlandı: zaten {1} içinde yüklü.", + "Library.Pkg.ConfirmTitle": "PKG dosyaları yüklensin mi?", + "Library.Pkg.ConfirmMessage": "Bu klasörde {0} PKG dosyası bulundu. Şimdi yüklensin mi? Bunun için {1} GB boş alan gerekir.", + "Library.Pkg.ConfirmInstall": "Yükle", + "Library.Pkg.ConfirmSkip": "Şimdi değil", + "Dialog.OpenPkg": "Yüklenecek PKG'yi seç", + "Dialog.PkgFiles": "PS4 paketleri", + "Dialog.ChoosePkgInstallFolder": "Oyunun yükleneceği yeri seç", "Hero.GameSettings": "Oyun ayarları", "Hero.Console": "Konsol", "Hint.LibraryMenu": "Kütüphane menüsü", diff --git a/src/SharpEmu.GUI/Languages/zh.json b/src/SharpEmu.GUI/Languages/zh.json index 1ce591a62..a3b878f6b 100644 --- a/src/SharpEmu.GUI/Languages/zh.json +++ b/src/SharpEmu.GUI/Languages/zh.json @@ -56,6 +56,22 @@ "LibraryMenu.Volume": "音量", "LibraryMenu.AddGames": "添加游戏", "LibraryMenu.AddFolder": "添加文件夹…", + "Library.Pkg.Install": "安装 PKG…", + "Library.Pkg.Heading": "正在安装 {0}", + "Library.Pkg.Explanation": "这会把伪造的 PKG 解压到一个游戏文件夹中,SharpEmu 会像运行其他游戏一样运行它。大型包需要较长时间,并且需要足够容纳整个游戏的可用磁盘空间。", + "Library.Pkg.Preparing": "正在读取包…", + "Library.Pkg.Progress": "{0} / {1} GB({2}%)", + "Library.Pkg.Cancelling": "正在取消…", + "Library.Pkg.Failed": "安装失败:{0}", + "Library.Pkg.SkippedNotGame": "已跳过 {0}:暂不支持补丁和 DLC 包({1})。", + "Library.Pkg.AlreadyInstalled": "已跳过 {0}:已安装在 {1}。", + "Library.Pkg.ConfirmTitle": "安装 PKG 文件?", + "Library.Pkg.ConfirmMessage": "在此文件夹中找到 {0} 个 PKG 文件。现在安装吗?这需要 {1} GB 的可用空间。", + "Library.Pkg.ConfirmInstall": "安装", + "Library.Pkg.ConfirmSkip": "暂不", + "Dialog.OpenPkg": "选择要安装的 PKG", + "Dialog.PkgFiles": "PS4 包", + "Dialog.ChoosePkgInstallFolder": "选择游戏的安装位置", "Hero.GameSettings": "游戏设置", "Hero.Console": "控制台", "Hint.LibraryMenu": "游戏库菜单", diff --git a/src/SharpEmu.GUI/LibraryMenu.axaml b/src/SharpEmu.GUI/LibraryMenu.axaml index 4748bae50..e2b428368 100644 --- a/src/SharpEmu.GUI/LibraryMenu.axaml +++ b/src/SharpEmu.GUI/LibraryMenu.axaml @@ -89,5 +89,12 @@ SPDX-License-Identifier: GPL-2.0-or-later Text="{Binding [Library.OpenFile], Source={x:Static local:Localization.Instance}}" /> </StackPanel> </Button> + <Button x:Name="InstallPkgButton" Classes="menuItem"> + <StackPanel Orientation="Horizontal" Spacing="12"> + <TextBlock Classes="materialSymbol compact menuIcon" Text="download" /> + <TextBlock Classes="menuLabel" + Text="{Binding [Library.Pkg.Install], Source={x:Static local:Localization.Instance}}" /> + </StackPanel> + </Button> </StackPanel> </local:SheetView> diff --git a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs index ed477feb6..4bf3f9e40 100644 --- a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs +++ b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs @@ -5,6 +5,8 @@ using Avalonia.Animation; using Avalonia.Input; using Avalonia.Media.Transformation; +using Avalonia.Platform.Storage; +using SharpEmu.HLE.FileSystem.Pkg; namespace SharpEmu.GUI; @@ -83,10 +85,252 @@ private void InitializeLibraryToolbar() await OpenFileAsync(); }; + _libraryMenu.InstallPkgButton.Click += async (_, _) => + { + _libraryMenu.Close(); + await InstallPkgAsync(); + }; + PageTabStrip.SizeChanged += (_, _) => MovePageTabThumb(animate: false); UpdateSearchExpanded(); } + // Unpacks a fake .pkg into <chosen folder>/<game title>, then adds the chosen folder to the library. + private async Task InstallPkgAsync() + { + var loc = Localization.Instance; + var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + { + Title = loc.Get("Dialog.OpenPkg"), + AllowMultiple = false, + FileTypeFilter = + [ + new FilePickerFileType(loc.Get("Dialog.PkgFiles")) { Patterns = ["*.pkg"] }, + FilePickerFileTypes.All, + ], + }); + var pkgPath = files.FirstOrDefault()?.TryGetLocalPath(); + if (string.IsNullOrEmpty(pkgPath)) + { + return; + } + + if (!TryReadPackageInfo(pkgPath, out var titleId, out var folderName, out var isGame, out var category)) + { + return; + } + + if (!isGame) + { + ReportSkippedNotGame(pkgPath, category); + return; + } + + var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + { + Title = loc.Get("Dialog.ChoosePkgInstallFolder"), + AllowMultiple = false, + }); + var parent = folders.FirstOrDefault()?.TryGetLocalPath(); + if (string.IsNullOrEmpty(parent)) + { + return; + } + + if (!await InstallPackageIntoAsync(pkgPath, parent, folderName)) + { + return; + } + + await RescanLibraryAsync(addingFolder: true); + } + + // A folder picked by "Add folder" may hold downloaded .pkg files instead of extracted games. + // Walk it recursively with the same depth limit as the library scan, install every package + // under the chosen root (named after the game's title) and let the caller's rescan pick them all + // up. Packages whose game is already extracted anywhere under the root are left alone. + private async Task InstallPackagesInFolderAsync(string folder) + { + string[] packages; + try + { + packages = Directory.EnumerateFiles(folder, "*.pkg", new EnumerationOptions + { + IgnoreInaccessible = true, + RecurseSubdirectories = true, + MaxRecursionDepth = 8, + MatchCasing = MatchCasing.CaseInsensitive, + }).ToArray(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + AppendConsoleLine(Localization.Instance.Format("Library.Pkg.Failed", exception.Message), ErrorLineBrush); + return; + } + + var installed = await Task.Run(() => FindInstalledTitles(folder)); + + // Patches and DLC share the base game's title id and the emulator cannot overlay them, so + // only base games are installed. + var installable = new List<(string Path, string FolderName)>(); + foreach (var pkgPath in packages) + { + if (!TryReadPackageInfo(pkgPath, out var titleId, out var folderName, out var isGame, out var category)) + { + continue; + } + + if (!isGame) + { + ReportSkippedNotGame(pkgPath, category); + continue; + } + + // The game may already sit elsewhere under the root (next to its package, or from an + // earlier manual install): installing it again would show two versions. + var key = string.IsNullOrWhiteSpace(titleId) ? Path.GetFileNameWithoutExtension(pkgPath) : titleId; + if (installed.TryGetValue(key, out var existing)) + { + AppendConsoleLine(Localization.Instance.Format("Library.Pkg.AlreadyInstalled", Path.GetFileName(pkgPath), existing), DimLineBrush); + continue; + } + + if (!File.Exists(Path.Combine(Path.Combine(folder, folderName), "eboot.bin"))) + { + installable.Add((pkgPath, folderName)); + installed[key] = Path.Combine(folder, folderName); + } + } + + if (installable.Count == 0) + { + return; + } + + long neededBytes = 0; + await Task.Run(() => + { + foreach (var (pkgPath, _) in installable) + { + try + { + using var package = PkgPackage.Open(pkgPath); + neededBytes += package.GetInstalledSize(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException) + { + // The install itself reports the problem; the estimate just misses this package. + } + } + }); + + var confirm = new PkgConfirmDialog( + Localization.Instance.Format( + "Library.Pkg.ConfirmMessage", + installable.Count, + (neededBytes / (1024.0 * 1024 * 1024)).ToString("0.0", System.Globalization.CultureInfo.CurrentCulture))); + if (await Sheets.ShowAsync(confirm) is not true) + { + return; + } + + foreach (var (pkgPath, folderName) in installable) + { + // Cancelling one package stops the batch; later packages stay untouched. + if (!await InstallPackageIntoAsync(pkgPath, folder, folderName)) + { + return; + } + } + } + + // Title id -> folder of every game already extracted under `root` (a folder with eboot.bin and + // sce_sys/param.sfo), searched as deep as the package scan. + private static Dictionary<string, string> FindInstalledTitles(string root) + { + var titles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + try + { + foreach (var eboot in Directory.EnumerateFiles(root, "eboot.bin", new EnumerationOptions + { + IgnoreInaccessible = true, + RecurseSubdirectories = true, + MaxRecursionDepth = 8, + MatchCasing = MatchCasing.CaseInsensitive, + })) + { + var directory = Path.GetDirectoryName(eboot)!; + try + { + var sfo = File.ReadAllBytes(Path.Combine(directory, "sce_sys", "param.sfo")); + if (PkgParamSfo.ReadString(sfo, "TITLE_ID") is { Length: > 0 } titleId) + { + titles.TryAdd(titleId, directory); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + + return titles; + } + + private void ReportSkippedNotGame(string pkgPath, string? category) => + AppendConsoleLine( + Localization.Instance.Format("Library.Pkg.SkippedNotGame", Path.GetFileName(pkgPath), category ?? string.Empty), + ErrorLineBrush); + + private bool TryReadPackageInfo(string pkgPath, out string titleId, out string folderName, out bool isGame, out string? category) + { + try + { + using var package = PkgPackage.Open(pkgPath); + titleId = package.TitleId; + folderName = package.GetFolderName(Path.GetFileNameWithoutExtension(pkgPath)); + category = package.Category; + isGame = package.IsGameApplication; + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException) + { + AppendConsoleLine(Localization.Instance.Format("Library.Pkg.Failed", exception.Message), ErrorLineBrush); + titleId = string.Empty; + folderName = string.Empty; + category = null; + isGame = false; + return false; + } + } + + // Shows the install sheet for one package. The caller owns the library rescan. + private async Task<bool> InstallPackageIntoAsync(string pkgPath, string parent, string folderName) + { + var destination = Path.Combine(parent, folderName); + if (File.Exists(Path.Combine(destination, "eboot.bin"))) + { + return true; // Already installed; the folder scan will pick it up. + } + + var dialog = new PkgInstallDialog(Path.GetFileName(pkgPath), pkgPath, destination); + if (await Sheets.ShowAsync(dialog) is not true) + { + return false; + } + + if (!_settings.GameFolders.Contains(parent, GameLibraryPath.Comparer)) + { + _settings.GameFolders.Add(parent); + _settings.Save(); + } + + return true; + } + private void OpenLibraryMenu() { if (_libraryMenu.IsOpen) diff --git a/src/SharpEmu.GUI/MainWindow.axaml.cs b/src/SharpEmu.GUI/MainWindow.axaml.cs index 1a4983a62..b6397580a 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml.cs +++ b/src/SharpEmu.GUI/MainWindow.axaml.cs @@ -1800,6 +1800,8 @@ private async Task AddFolderAsync() _settings.Save(); } + // A downloaded folder often holds .pkg files rather than an extracted game. + await InstallPackagesInFolderAsync(path); await RescanLibraryAsync(addingFolder: true); } diff --git a/src/SharpEmu.GUI/PkgConfirmDialog.axaml b/src/SharpEmu.GUI/PkgConfirmDialog.axaml new file mode 100644 index 000000000..5fcc368c6 --- /dev/null +++ b/src/SharpEmu.GUI/PkgConfirmDialog.axaml @@ -0,0 +1,30 @@ +<!-- +Copyright (C) 2026 SharpEmu Emulator Project +SPDX-License-Identifier: GPL-2.0-or-later +--> + +<local:SheetView xmlns="https://github.com/avaloniaui" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:local="clr-namespace:SharpEmu.GUI" + x:Class="SharpEmu.GUI.PkgConfirmDialog" + SheetWidth="520"> + <StackPanel Margin="28" Spacing="14"> + <TextBlock Classes="sheetTitle" + Text="{Binding [Library.Pkg.ConfirmTitle], Source={x:Static local:Localization.Instance}}" + TextWrapping="Wrap" /> + + <TextBlock x:Name="MessageText" + TextWrapping="Wrap" /> + + <StackPanel Margin="0,8,0,0" + Orientation="Horizontal" + HorizontalAlignment="Right" + Spacing="10"> + <Button x:Name="SkipButton" + Classes="ghost" + Content="{Binding [Library.Pkg.ConfirmSkip], Source={x:Static local:Localization.Instance}}" /> + <Button x:Name="InstallButton" + Content="{Binding [Library.Pkg.ConfirmInstall], Source={x:Static local:Localization.Instance}}" /> + </StackPanel> + </StackPanel> +</local:SheetView> diff --git a/src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs b/src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs new file mode 100644 index 000000000..f62821c79 --- /dev/null +++ b/src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Avalonia.Controls; + +namespace SharpEmu.GUI; + +// Asks whether the PKG files found in an added folder should be installed now. Returns true to +// install; anything else (the other button, Escape) skips the installs. +public partial class PkgConfirmDialog : SheetView +{ + public PkgConfirmDialog() + { + InitializeComponent(); + SkipButton.Click += (_, _) => Close(false); + InstallButton.Click += (_, _) => Close(true); + } + + public PkgConfirmDialog(string message) + : this() + { + MessageText.Text = message; + } + + public override Control? InitialFocus => InstallButton; +} diff --git a/src/SharpEmu.GUI/PkgInstallDialog.axaml b/src/SharpEmu.GUI/PkgInstallDialog.axaml new file mode 100644 index 000000000..1be3d1852 --- /dev/null +++ b/src/SharpEmu.GUI/PkgInstallDialog.axaml @@ -0,0 +1,45 @@ +<!-- +Copyright (C) 2026 SharpEmu Emulator Project +SPDX-License-Identifier: GPL-2.0-or-later +--> + +<local:SheetView xmlns="https://github.com/avaloniaui" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:local="clr-namespace:SharpEmu.GUI" + x:Class="SharpEmu.GUI.PkgInstallDialog" + SheetWidth="560"> + <StackPanel Margin="28" Spacing="12"> + <TextBlock x:Name="HeadingText" + FontSize="20" + FontWeight="Bold" + TextWrapping="Wrap" /> + + <TextBlock TextWrapping="Wrap" + Text="{Binding [Library.Pkg.Explanation], Source={x:Static local:Localization.Instance}}" /> + + <TextBlock x:Name="DestinationText" + Foreground="{StaticResource MutedBrush}" + TextWrapping="Wrap" /> + + <ProgressBar x:Name="InstallProgress" + Minimum="0" + Maximum="1" + Height="8" + Margin="0,8,0,0" /> + + <TextBlock x:Name="StatusText" + Foreground="{StaticResource MutedBrush}" + TextWrapping="Wrap" /> + + <TextBlock x:Name="FileText" + Foreground="{StaticResource MutedBrush}" + TextTrimming="CharacterEllipsis" /> + + <Grid Margin="0,8,0,0" ColumnDefinitions="*,Auto"> + <Button x:Name="CloseButton" + Grid.Column="1" + Classes="ghost" + Content="{Binding [Common.Cancel], Source={x:Static local:Localization.Instance}}" /> + </Grid> + </StackPanel> +</local:SheetView> diff --git a/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs b/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs new file mode 100644 index 000000000..881fbc82d --- /dev/null +++ b/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs @@ -0,0 +1,149 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Avalonia.Controls; +using SharpEmu.HLE.FileSystem.Pkg; + +namespace SharpEmu.GUI; + +// Extracts a .pkg into a game folder on a worker thread and shows its progress. The button cancels +// while installing. The sheet closes itself on success (returning true) and stays open on a +// failure. A cancelled or failed install removes the partial folder, unless it was there before. +public partial class PkgInstallDialog : SheetView +{ + private readonly CancellationTokenSource _cancellation = new(); + private readonly string _pkgPath = string.Empty; + private readonly string _destination = string.Empty; + private readonly bool _destinationExisted; + private bool _finished; + private bool _succeeded; + + public PkgInstallDialog() + { + InitializeComponent(); + } + + public PkgInstallDialog(string gameName, string pkgPath, string destination) + : this() + { + _pkgPath = pkgPath; + _destination = destination; + _destinationExisted = Directory.Exists(destination); + HeadingText.Text = Localization.Instance.Format("Library.Pkg.Heading", gameName); + DestinationText.Text = destination; + StatusText.Text = Localization.Instance.Get("Library.Pkg.Preparing"); + CloseButton.Click += (_, _) => OnCloseClicked(); + Opened += async (_, _) => await InstallAsync(); + Closed += (_, _) => + { + if (!_finished) + { + _cancellation.Cancel(); + } + }; + } + + public override void RequestCancel() + { + if (CloseButton.IsEnabled) + { + OnCloseClicked(); + } + } + + private void OnCloseClicked() + { + if (_finished) + { + Close(_succeeded); + return; + } + + CloseButton.IsEnabled = false; + StatusText.Text = Localization.Instance.Get("Library.Pkg.Cancelling"); + _cancellation.Cancel(); + } + + private async Task InstallAsync() + { + // Progress<T> captures the UI context, so reports arrive on the UI thread. + var progress = new Progress<PkgExtractProgress>(report => + { + var fraction = report.BytesTotal == 0 ? 1 : (double)report.BytesDone / report.BytesTotal; + InstallProgress.Value = fraction; + FileText.Text = report.CurrentFile; + StatusText.Text = Localization.Instance.Format( + "Library.Pkg.Progress", + FormatGigabytes(report.BytesDone), + FormatGigabytes(report.BytesTotal), + (int)(fraction * 100)); + }); + + string? error = null; + var cancelled = false; + try + { + await Task.Run(() => + { + using var package = PkgPackage.Open(_pkgPath); + package.Extract(_destination, progress, _cancellation.Token); + }); + _succeeded = true; + } + catch (OperationCanceledException) + { + cancelled = true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException) + { + error = exception.Message; + } + + if (!_succeeded && !_destinationExisted) + { + // A partial game folder would look installed yet not boot. Never delete a folder the + // user already had: the title id can collide with their own directory. + try + { + if (Directory.Exists(_destination)) + { + await Task.Run(() => Directory.Delete(_destination, recursive: true)); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + error ??= exception.Message; + } + } + + _finished = true; + if (cancelled && !IsOpen) + { + return; + } + + if (cancelled) + { + Close(false); + return; + } + + // A finished install closes by itself, so a batch of packages runs without a click per + // game; only a failure waits for the user to read it. + if (_succeeded) + { + if (IsOpen) + { + Close(true); + } + + return; + } + + StatusText.Text = Localization.Instance.Format("Library.Pkg.Failed", error ?? string.Empty); + CloseButton.Content = Localization.Instance.Get("Library.Pack.Close"); + CloseButton.IsEnabled = true; + } + + private static string FormatGigabytes(long bytes) => (bytes / (1024.0 * 1024 * 1024)).ToString("0.00"); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs new file mode 100644 index 000000000..59d655f9b --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs @@ -0,0 +1,339 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// The superblock at the start of the logical PFS image. Layout from shadPS4 (pfs.h), checked +// against a retail fake PKG: the image's total block count is at 0x38 (it equals the PFSC block +// count); the 64-bit field at 0x28 holds 1 there and is not a size. +public readonly record struct PfsHeader( + long Version, + long Magic, + ushort Mode, + int BlockSize, + long BlockCount, + long DinodeCount, + long DinodeBlockCount, + long SuperrootInode) +{ + public static PfsHeader Parse(ReadOnlySpan<byte> block) + { + if (block.Length < 0x50) + { + throw new InvalidDataException("PFS header is truncated."); + } + + return new PfsHeader( + BinaryPrimitives.ReadInt64LittleEndian(block), + BinaryPrimitives.ReadInt64LittleEndian(block[0x08..]), + BinaryPrimitives.ReadUInt16LittleEndian(block[0x1C..]), + BinaryPrimitives.ReadInt32LittleEndian(block[0x20..]), + BinaryPrimitives.ReadInt64LittleEndian(block[0x38..]), + BinaryPrimitives.ReadInt64LittleEndian(block[0x30..]), + BinaryPrimitives.ReadInt64LittleEndian(block[0x40..]), + BinaryPrimitives.ReadInt64LittleEndian(block[0x48..])); + } +} + +// A dinode of the unsigned PFS layout (0xA8 bytes; only the leading fields are used). +public readonly record struct PfsInode(ushort Mode, ushort Nlink, uint Flags, long Size, long SizeCompressed, uint Blocks, uint Location) +{ + public const int Stride = 0xA8; + + public const ushort ModeDirectory = 0x4000; + public const ushort ModeFile = 0x8000; + + public bool IsDirectory => (Mode & ModeDirectory) != 0; + public bool IsFile => (Mode & ModeFile) != 0; + public bool IsEmpty => Mode == 0; + + public static PfsInode Parse(ReadOnlySpan<byte> data) + { + if (data.Length < 0x68) + { + throw new InvalidDataException("PFS inode is truncated."); + } + + return new PfsInode( + BinaryPrimitives.ReadUInt16LittleEndian(data), + BinaryPrimitives.ReadUInt16LittleEndian(data[2..]), + BinaryPrimitives.ReadUInt32LittleEndian(data[4..]), + BinaryPrimitives.ReadInt64LittleEndian(data[8..]), + BinaryPrimitives.ReadInt64LittleEndian(data[16..]), + BinaryPrimitives.ReadUInt32LittleEndian(data[0x60..]), + BinaryPrimitives.ReadUInt32LittleEndian(data[0x64..])); + } +} + +public enum PfsDirentType +{ + File = 2, + Directory = 3, + CurrentDirectory = 4, + ParentDirectory = 5, +} + +public readonly record struct PfsDirent(int Inode, int Type, string Name) +{ + // Sequential directory entries: ino, type, namelen, entsize (all int32), then the name. + // Entries never cross a block; a zero inode or entry size ends the block. + public static List<PfsDirent> ParseBlock(ReadOnlySpan<byte> block) + { + var entries = new List<PfsDirent>(); + var offset = 0; + while (offset + 16 <= block.Length) + { + var inode = BinaryPrimitives.ReadInt32LittleEndian(block[offset..]); + var type = BinaryPrimitives.ReadInt32LittleEndian(block[(offset + 4)..]); + var nameLength = BinaryPrimitives.ReadInt32LittleEndian(block[(offset + 8)..]); + var entrySize = BinaryPrimitives.ReadInt32LittleEndian(block[(offset + 12)..]); + if (inode == 0 || entrySize < 16 || nameLength < 0 || offset + 16 + nameLength > block.Length) + { + break; + } + + var name = Encoding.UTF8.GetString(block.Slice(offset + 16, nameLength)); + entries.Add(new PfsDirent(inode, type, name)); + offset += entrySize; + } + + return entries; + } +} + +// The compressed container around the inner file system: a header, a table of block offsets and +// the 64 KiB blocks, each stored raw or zlib compressed. +public sealed class PfscImage +{ + public const uint Magic = 0x43534650; // "PFSC" + public const int BlockSize = 0x10000; + + private readonly Stream _source; + private readonly long _offset; + private readonly long[] _blockOffsets; + private byte[] _compressed = new byte[BlockSize]; + + public PfscImage(Stream source, long pfscOffset) + { + _source = source; + _offset = pfscOffset; + Span<byte> header = stackalloc byte[0x30]; + ReadExactly(pfscOffset, header); + if (BinaryPrimitives.ReadUInt32LittleEndian(header) != Magic) + { + throw new InvalidDataException("PFSC header not found."); + } + + var blockSize = BinaryPrimitives.ReadInt64LittleEndian(header[0x10..]); + var tableOffset = BinaryPrimitives.ReadInt64LittleEndian(header[0x18..]); + DataLength = BinaryPrimitives.ReadInt64LittleEndian(header[0x28..]); + if (blockSize != BlockSize || DataLength < 0 || tableOffset < 0x30) + { + throw new InvalidDataException("Unsupported PFSC layout."); + } + + BlockCount = (int)((DataLength + BlockSize - 1) / BlockSize); + var table = new byte[(BlockCount + 1) * 8]; + ReadExactly(pfscOffset + tableOffset, table); + _blockOffsets = new long[BlockCount + 1]; + for (var i = 0; i < _blockOffsets.Length; i++) + { + _blockOffsets[i] = BinaryPrimitives.ReadInt64LittleEndian(table.AsSpan(i * 8)); + } + } + + public long DataLength { get; } + + public int BlockCount { get; } + + // Finds the PFSC inside a decrypted PFS image: it starts on a 64 KiB boundary after the + // image's own header blocks. + public static long FindOffset(Stream image, int maxCandidates = 4096) + { + Span<byte> probe = stackalloc byte[4]; + for (var i = 0; i < maxCandidates; i++) + { + var offset = 0x20000L + i * 0x10000L; + if (offset + 4 > image.Length) + { + break; + } + + image.Position = offset; + image.ReadExactly(probe); + if (BinaryPrimitives.ReadUInt32LittleEndian(probe) == Magic) + { + return offset; + } + } + + throw new InvalidDataException("No PFSC container found in the PFS image."); + } + + // Decompresses block `index` into `destination` (64 KiB). Missing data reads as zeros. + public void ReadBlock(long index, Span<byte> destination) + { + if (index < 0 || index >= BlockCount) + { + throw new InvalidDataException($"PFSC block {index} is out of range."); + } + + var start = _blockOffsets[index]; + var size = _blockOffsets[index + 1] - start; + if (size < 0 || size > BlockSize) + { + throw new InvalidDataException($"PFSC block {index} has an invalid size {size}."); + } + + destination[..BlockSize].Clear(); + if (size == 0) + { + return; + } + + if (_compressed.Length < size) + { + _compressed = new byte[BlockSize]; + } + + var data = _compressed.AsSpan(0, (int)size); + ReadExactly(_offset + start, data); + if (size == BlockSize) + { + data.CopyTo(destination); + return; + } + + using var inflater = new ZLibStream(new MemoryStream(_compressed, 0, (int)size, writable: false), CompressionMode.Decompress); + var filled = 0; + while (filled < BlockSize) + { + var read = inflater.Read(destination[filled..BlockSize]); + if (read == 0) + { + break; + } + + filled += read; + } + } + + private void ReadExactly(long position, Span<byte> destination) + { + _source.Position = position; + _source.ReadExactly(destination); + } +} + +// The inner file system: superblock, inode table and directories on top of a PFSC. +public sealed class PfsImage +{ + private readonly PfscImage _pfsc; + private readonly byte[] _block = new byte[PfscImage.BlockSize]; + private PfsInode[]? _inodes; + + public PfsImage(PfscImage pfsc) + { + _pfsc = pfsc; + _pfsc.ReadBlock(0, _block); + Header = PfsHeader.Parse(_block); + if (Header.BlockSize != PfscImage.BlockSize) + { + throw new InvalidDataException($"Unsupported PFS block size {Header.BlockSize}."); + } + + if (Header.BlockCount <= 0 || Header.BlockCount > _pfsc.BlockCount) + { + throw new InvalidDataException("PFS block count does not fit its PFSC container."); + } + } + + public PfsHeader Header { get; } + + public PfsInode GetInode(long number) + { + _inodes ??= ReadInodes(); + if (number < 0 || number >= _inodes.Length) + { + throw new InvalidDataException($"PFS inode {number} is out of range."); + } + + return _inodes[number]; + } + + // Inodes are packed per block (a block holds 390 of them); the table starts at block 1. + private PfsInode[] ReadInodes() + { + var perBlock = PfscImage.BlockSize / PfsInode.Stride; + if (Header.DinodeBlockCount <= 0 || Header.DinodeBlockCount > Header.BlockCount || + Header.DinodeCount > Header.DinodeBlockCount * perBlock) + { + throw new InvalidDataException("PFS inode table is implausibly large."); + } + + var count = checked((int)Header.DinodeCount); + var inodes = new PfsInode[count]; + for (var i = 0; i < count; i++) + { + var slot = i % perBlock; + if (slot == 0) + { + _pfsc.ReadBlock(1 + i / perBlock, _block); + } + + inodes[i] = PfsInode.Parse(_block.AsSpan(slot * PfsInode.Stride, PfsInode.Stride)); + } + + return inodes; + } + + public List<PfsDirent> ReadDirectory(PfsInode directory) + { + var entries = new List<PfsDirent>(); + for (uint i = 0; i < directory.Blocks; i++) + { + _pfsc.ReadBlock((long)directory.Location + i, _block); + entries.AddRange(PfsDirent.ParseBlock(_block)); + } + + return entries; + } + + // The game's root directory: "uroot" inside the super root. + public PfsInode GetUserRoot() + { + var superRoot = GetInode(Header.SuperrootInode); + foreach (var entry in ReadDirectory(superRoot)) + { + if (entry.Name == "uroot") + { + return GetInode(entry.Inode); + } + } + + throw new InvalidDataException("PFS image has no uroot directory."); + } + + // Streams a file's blocks to `destination`; the last block is cut to the file size. + public void CopyFile(PfsInode file, Stream destination, Action<long>? onBytes = null) + { + if (file.Size < 0 || file.Blocks * (long)PfscImage.BlockSize < file.Size) + { + throw new InvalidDataException("PFS file claims more data than its blocks hold."); + } + + var remaining = file.Size; + for (uint i = 0; i < file.Blocks && remaining > 0; i++) + { + _pfsc.ReadBlock((long)file.Location + i, _block); + var chunk = (int)Math.Min(remaining, PfscImage.BlockSize); + destination.Write(_block, 0, chunk); + remaining -= chunk; + onBytes?.Invoke(chunk); + } + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgCrypto.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgCrypto.cs new file mode 100644 index 000000000..531fe173a --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgCrypto.cs @@ -0,0 +1,149 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Numerics; +using System.Security.Cryptography; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// Key derivation and the sector cipher of the PFS image. Ported from shadPS4 +// (src/core/crypto/crypto.cpp). +public static class PkgCrypto +{ + public const int SectorSize = 0x1000; + + // The first 16 sectors of the PFS image (its header block) are stored in the clear. + public const long FirstEncryptedSector = 16; + + // Raw RSA with PKCS#1 v1.5 (type 2) unpadding, which is what RSAES_PKCS1v15 does. + public static byte[] RsaDecrypt(ReadOnlySpan<byte> ciphertext, string modulusHex, string privateExponentHex) + { + var n = new BigInteger(Convert.FromHexString(modulusHex), isUnsigned: true, isBigEndian: true); + var d = new BigInteger(Convert.FromHexString(privateExponentHex), isUnsigned: true, isBigEndian: true); + var c = new BigInteger(ciphertext, isUnsigned: true, isBigEndian: true); + var length = (int)((n.GetBitLength() + 7) / 8); + var plain = BigInteger.ModPow(c, d, n); + var block = new byte[length]; + plain.TryWriteBytes(block.AsSpan(length - plain.GetByteCount(isUnsigned: true)), + out _, isUnsigned: true, isBigEndian: true); + return UnpadPkcs1(block); + } + + internal static byte[] UnpadPkcs1(byte[] block) + { + if (block.Length < 11 || block[0] != 0 || block[1] != 2) + { + throw new InvalidDataException("RSA block has invalid PKCS#1 padding."); + } + + var index = 2; + while (index < block.Length && block[index] != 0) + { + index++; + } + + if (index >= block.Length || index < 10) + { + throw new InvalidDataException("RSA block has invalid PKCS#1 padding."); + } + + return block[(index + 1)..]; + } + + // dk3 = RSA(PkgDerivedKey3)(entry key #3) + public static byte[] DeriveDk3(ReadOnlySpan<byte> entryKey3) => + Truncate(RsaDecrypt(entryKey3, PkgKeys.DerivedKey3Modulus, PkgKeys.DerivedKey3PrivateExponent), 32); + + // ekpfs = RSA(Fake)(AES-CBC(SHA256(imageKeyEntryRow || dk3))(image key)) + public static byte[] DeriveEkpfs(ReadOnlySpan<byte> imageKeyEntryRow, ReadOnlySpan<byte> dk3, ReadOnlySpan<byte> imageKey) + { + if (imageKey.Length % 16 != 0) + { + throw new InvalidDataException("PKG image key is not a whole number of AES blocks."); + } + + Span<byte> ivKeyInput = stackalloc byte[64]; + imageKeyEntryRow[..PkgEntry.Size_].CopyTo(ivKeyInput); + dk3[..32].CopyTo(ivKeyInput[32..]); + var ivKey = SHA256.HashData(ivKeyInput); + + using var aes = Aes.Create(); + aes.Key = ivKey[16..32]; + byte[] decrypted; + try + { + decrypted = aes.DecryptCbc(imageKey, ivKey.AsSpan(0, 16), PaddingMode.None); + } + catch (CryptographicException exception) + { + throw new InvalidDataException("Could not decrypt the PKG image key.", exception); + } + return Truncate(RsaDecrypt(decrypted, PkgKeys.FakeModulus, PkgKeys.FakePrivateExponent), 32); + } + + // The PFS data and tweak keys: HMAC-SHA256(ekpfs, le32(1) || seed), tweak first, data second. + public static (byte[] DataKey, byte[] TweakKey) DerivePfsKeys(ReadOnlySpan<byte> ekpfs, ReadOnlySpan<byte> seed) + { + Span<byte> input = stackalloc byte[20]; + BinaryPrimitives.WriteUInt32LittleEndian(input, 1); + seed[..16].CopyTo(input[4..]); + var hash = HMACSHA256.HashData(ekpfs, input); + return (hash[16..32], hash[..16]); + } + + // AES-128-XTS over `data` (a whole number of 16-byte blocks), in place. `sector` is the + // tweak: the sector number of the first byte. + public static void XtsDecrypt(Aes dataCipher, Aes tweakCipher, Span<byte> data, ulong sector) + { + if (data.Length % 16 != 0) + { + throw new ArgumentException("XTS data must be a multiple of 16 bytes.", nameof(data)); + } + + Span<byte> tweak = stackalloc byte[16]; + BinaryPrimitives.WriteUInt64LittleEndian(tweak, sector); + tweakCipher.EncryptEcb(tweak, tweak, PaddingMode.None); + + var blocks = data.Length / 16; + var tweaks = blocks <= 256 ? stackalloc byte[blocks * 16] : new byte[blocks * 16]; + for (var i = 0; i < blocks; i++) + { + tweak.CopyTo(tweaks.Slice(i * 16, 16)); + MultiplyTweak(tweak); + } + + Xor(data, tweaks); + dataCipher.DecryptEcb(data, data, PaddingMode.None); + Xor(data, tweaks); + } + + // Multiplication by x in GF(2^128), little-endian bit order. + internal static void MultiplyTweak(Span<byte> tweak) + { + byte carry = 0; + for (var i = 0; i < 16; i++) + { + var next = (byte)(tweak[i] >> 7); + tweak[i] = (byte)((tweak[i] << 1) | carry); + carry = next; + } + + if (carry != 0) + { + tweak[0] ^= 0x87; + } + } + + private static void Xor(Span<byte> data, ReadOnlySpan<byte> mask) + { + for (var i = 0; i < data.Length; i += 8) + { + var value = BinaryPrimitives.ReadUInt64LittleEndian(data[i..]) ^ BinaryPrimitives.ReadUInt64LittleEndian(mask[i..]); + BinaryPrimitives.WriteUInt64LittleEndian(data[i..], value); + } + } + + private static byte[] Truncate(byte[] value, int length) => + value.Length >= length ? value[..length] : throw new InvalidDataException("Decrypted key is too short."); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgFile.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgFile.cs new file mode 100644 index 000000000..941ef0f5f --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgFile.cs @@ -0,0 +1,180 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// The PS4 package container header (all fields big-endian). Layout ported from shadPS4 +// (src/core/file_format/pkg.h). +public sealed record PkgHeader( + uint PkgType, + uint FileCount, + uint TableEntryCount, + uint TableEntryOffset, + ulong BodyOffset, + ulong BodySize, + ulong ContentOffset, + ulong ContentSize, + string ContentId, + uint DrmType, + uint ContentType, + uint ContentFlags, + uint PfsImageCount, + ulong PfsImageFlags, + ulong PfsImageOffset, + ulong PfsImageSize, + ulong MountImageOffset, + ulong MountImageSize, + ulong PkgSize, + uint PfsSignedSize, + uint PfsCacheSize) +{ + public const int Size = 0x480; + public const uint Magic = 0x7F434E54; // "\x7FCNT" + + // The nine character title id (CUSA00900) is the tail of the content id UP9000-CUSA00900_00-... + public string TitleId => ContentId.Length >= 16 ? ContentId.Substring(7, 9) : string.Empty; + + public static bool HasMagic(ReadOnlySpan<byte> data) => + data.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(data) == Magic; + + public static PkgHeader Parse(ReadOnlySpan<byte> data) + { + if (data.Length < Size) + { + throw new InvalidDataException("PKG header is truncated."); + } + + if (!HasMagic(data)) + { + throw new InvalidDataException("Not a PKG file (bad magic)."); + } + + var contentId = Encoding.ASCII.GetString(data.Slice(0x40, 0x24)).TrimEnd('\0'); + return new PkgHeader( + PkgType: BinaryPrimitives.ReadUInt32BigEndian(data[0x04..]), + FileCount: BinaryPrimitives.ReadUInt32BigEndian(data[0x0C..]), + TableEntryCount: BinaryPrimitives.ReadUInt32BigEndian(data[0x10..]), + TableEntryOffset: BinaryPrimitives.ReadUInt32BigEndian(data[0x18..]), + BodyOffset: BinaryPrimitives.ReadUInt64BigEndian(data[0x20..]), + BodySize: BinaryPrimitives.ReadUInt64BigEndian(data[0x28..]), + ContentOffset: BinaryPrimitives.ReadUInt64BigEndian(data[0x30..]), + ContentSize: BinaryPrimitives.ReadUInt64BigEndian(data[0x38..]), + ContentId: contentId, + DrmType: BinaryPrimitives.ReadUInt32BigEndian(data[0x70..]), + ContentType: BinaryPrimitives.ReadUInt32BigEndian(data[0x74..]), + ContentFlags: BinaryPrimitives.ReadUInt32BigEndian(data[0x78..]), + PfsImageCount: BinaryPrimitives.ReadUInt32BigEndian(data[0x404..]), + PfsImageFlags: BinaryPrimitives.ReadUInt64BigEndian(data[0x408..]), + PfsImageOffset: BinaryPrimitives.ReadUInt64BigEndian(data[0x410..]), + PfsImageSize: BinaryPrimitives.ReadUInt64BigEndian(data[0x418..]), + MountImageOffset: BinaryPrimitives.ReadUInt64BigEndian(data[0x420..]), + MountImageSize: BinaryPrimitives.ReadUInt64BigEndian(data[0x428..]), + PkgSize: BinaryPrimitives.ReadUInt64BigEndian(data[0x430..]), + PfsSignedSize: BinaryPrimitives.ReadUInt32BigEndian(data[0x438..]), + PfsCacheSize: BinaryPrimitives.ReadUInt32BigEndian(data[0x43C..])); + } +} + +// One 32-byte row of the entry table: small metadata files (param.sfo, icons, keys) stored in the +// package body. +public readonly record struct PkgEntry( + uint Id, + uint FilenameOffset, + uint Flags1, + uint Flags2, + uint Offset, + uint Size) +{ + public const int Size_ = 32; + + public const uint EntryKeysId = 0x10; + public const uint ImageKeyId = 0x20; + + public static PkgEntry Parse(ReadOnlySpan<byte> row) + { + if (row.Length < Size_) + { + throw new InvalidDataException("PKG entry is truncated."); + } + + return new PkgEntry( + BinaryPrimitives.ReadUInt32BigEndian(row), + BinaryPrimitives.ReadUInt32BigEndian(row[4..]), + BinaryPrimitives.ReadUInt32BigEndian(row[8..]), + BinaryPrimitives.ReadUInt32BigEndian(row[12..]), + BinaryPrimitives.ReadUInt32BigEndian(row[16..]), + BinaryPrimitives.ReadUInt32BigEndian(row[20..])); + } + + public static PkgEntry[] ParseTable(ReadOnlySpan<byte> table, int count) + { + if (count < 0 || (long)count * Size_ > table.Length) + { + throw new InvalidDataException("PKG entry table is truncated."); + } + + var entries = new PkgEntry[count]; + for (var i = 0; i < count; i++) + { + entries[i] = Parse(table.Slice(i * Size_, Size_)); + } + + return entries; + } + + // Name of a well-known entry id relative to sce_sys, or null for ids that are not metadata + // files (digests, keys, licence data). + public string? Name => PkgEntryNames.Get(Id); +} + +internal static class PkgEntryNames +{ + private static readonly Dictionary<uint, string> Fixed = new() + { + [0x0402] = "nptitle.dat", + [0x0403] = "npbind.dat", + [0x1000] = "param.sfo", + [0x1001] = "playgo-chunk.dat", + [0x1002] = "playgo-chunk.sha", + [0x1003] = "playgo-manifest.xml", + [0x1004] = "pronunciation.xml", + [0x1005] = "pronunciation.sig", + [0x1006] = "pic1.png", + [0x1007] = "pubtoolinfo.dat", + [0x1008] = "app/playgo-chunk.dat", + [0x1009] = "app/playgo-chunk.sha", + [0x100A] = "app/playgo-manifest.xml", + [0x100B] = "shareparam.json", + [0x100C] = "shareoverlayimage.png", + [0x100D] = "save_data.png", + [0x100E] = "shareprivacyguardimage.png", + [0x1200] = "icon0.png", + [0x1220] = "pic0.png", + [0x1240] = "snd0.at9", + [0x1260] = "changeinfo/changeinfo.xml", + [0x1280] = "icon0.dds", + [0x12A0] = "pic0.dds", + [0x12C0] = "pic1.dds", + }; + + public static string? Get(uint id) + { + if (Fixed.TryGetValue(id, out var name)) + { + return name; + } + + // Numbered families: icon0_NN.png, pic1_NN.png, changeinfo_NN.xml, icon0_NN.dds, + // pic1_NN.dds (31 variants each) and trophyNN.trp (100 variants). + if (id is >= 0x1201 and <= 0x121F) return $"icon0_{id - 0x1200:00}.png"; + if (id is >= 0x1241 and <= 0x125F) return $"pic1_{id - 0x1240:00}.png"; + if (id is >= 0x1261 and <= 0x127F) return $"changeinfo/changeinfo_{id - 0x1260:00}.xml"; + if (id is >= 0x1281 and <= 0x129F) return $"icon0_{id - 0x1280:00}.dds"; + if (id is >= 0x12C1 and <= 0x12DF) return $"pic1_{id - 0x12C0:00}.dds"; + if (id is >= 0x1400 and <= 0x1463) return $"trophy/trophy{id - 0x1400:00}.trp"; + return null; + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgKeys.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgKeys.cs new file mode 100644 index 000000000..da668eba2 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgKeys.cs @@ -0,0 +1,21 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// The publicly known RSA keys used by fake (fpkg) packages. Ported from the shadPS4 key tables +// (src/core/crypto/keys.h): only the modulus and private exponent are needed for raw RSA. +internal static class PkgKeys +{ + public const string FakeModulus = + "C6CF71E7E59AF0D12A2C458BF92A0EC143058BC37117801DCD497DDE359D259BA0D7A0F27D6C087EAA5502682B23C644B84418EB56CF16A24803C9E74F87EB3D30C31588BF20E79DFF770CDE1D241E63A94F8ABF5BBE601968333BFCED9F474E5FF8EACB3D00BD6701F92C6DC6AC1364E76714F3DC52696AB9832C4230131BB2D8A5020D79ED96B10DF8CC0CDF81954F035809570E80692EFEFF5277EA7528A8FBC9BEBF9FBBB7798E1805E180BD50349481D353C269A2D24CCF6CF4572C104A3FFB22FD8B97E2C95BA62BCDD61B6BDB687F4BC2A05034C005E58DEF2467FF9340CF2D62A2A050B1F13AA83DFD80D1F9B80522AFC8354590588EE33A7CBD3E27"; + + public const string FakePrivateExponent = + "7F76CD0EE2D4DE051CC6D9A80E8DFA7BCA1EAA271A40F8F1228735DDDBFDEEF8C2BCBD01FB8BE23E63B2B1225C56496E11BE07440B9A2666D1492C8FD31BCFA4A1B8D1FBA49ED2212883098AF6A00BA3D60F9B6368CCBC0C4E145B27A4A9F42BB9B87BC0E651AD1D77D46BB9CE20D126667E5E9EA2E96B90F373B8528F4411030C1397393D132258D5438249DA6E7CA1C58CA5B009E0CE3DDFF49D3C9715E26AC72B3C509323DBBA4A226644AC78BB0E1A2743B57167AFF4AB48469373D042AB9363E56C9ADE5024C0237D99793F2207E0C148561BDF830912B42D456BC9C06885999079961AD7F54D1F3783404AEC3937A680927DC580C7D66FFE8A7989C6B1"; + + public const string DerivedKey3Modulus = + "D212FC335F6DDB831609628B0356273782D477853529392D526B8C4C8CFB06C1845BE7D4F7BCD24E6245CD2ABBD77776453655273FB3F5F98EDA4BEFAA59AEB39BEA5498D206326A58312AE0D44F90B50A7DECF43A9C52672D99318E0C43E682FE0746E12E50D41F2D2F7ED908BA06B3BF2E203F4E3FFE44FFAA50435791699449158282E40F4C8D9D2CC95B1D64BF888BD4C594E76547841EE57910FB989347B97D8512A640982CF792BC951932EDE890560D65C1AA78C62E54FD5F54A1F67EE5E05F61C120B4B9B4330870E4DF8956ED012946775F8CB8A9F51E2EB3B9BFE009B78D28D4A6C3B81E1F07EBB4120B95B88530FDDC3913D07CDC8FEDF9C9A3C1"; + + public const string DerivedKey3PrivateExponent = + "32D903908FBDB08F572B285E0B8DB3EA5CD17EA890888CDD6A80BBB1DFC1F70DAA32F0B77CCB88800E8B64B0BE4CD60E9B8C1E2A64E1F35CD77601415E935C94FEDD4662C31B5AE2A0BC2DEBC3980AA7B7856970682B644AB31FCC7DDC7C26F477F65CF2AE5A442DD3AB16620419BAFB90FFE23050896ECB56B2EBC09116925E308EAEC7945DFD35E120F8AD3EBC08BFC036749FD5BB5208FD0666F37AB304F475295DE95FAA1030B20F5A1AC12AB3FECB21AD80EC8F20091CDBC55894C29CC6CE82653E5790BCA98B06B4F072F677DF9864F1ECFE372DBCAE8C08811FC3C9891AC742824B2EDC8E8D73CEB1CC01D90870873C4408EC498F815AE240FF77FC0D"; +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs new file mode 100644 index 000000000..cf577c0f0 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs @@ -0,0 +1,386 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.FileSystem.Pkg; + +public readonly record struct PkgExtractProgress(long BytesDone, long BytesTotal, string CurrentFile); + +// A fake (fpkg) PS4 package opened for reading. Extraction streams every file block by block, +// so a package of any size needs only a few hundred KiB of memory. +public sealed class PkgPackage : IDisposable +{ + private const int EntryKeysTableOffset = 32 + 7 * 32; // seed digest + 7 digests, then 7 RSA keys + private const int EntryKeySize = 256; + private const long PfsSeedOffset = 0x370; + + private readonly FileStream _file; + private readonly byte[] _entryTable; + private string? _category; + private bool _categoryRead; + + private PkgPackage(FileStream file, PkgHeader header, byte[] entryTable, PkgEntry[] entries) + { + _file = file; + Header = header; + _entryTable = entryTable; + Entries = entries; + } + + public PkgHeader Header { get; } + + public IReadOnlyList<PkgEntry> Entries { get; } + + public string TitleId => Header.TitleId; + + // param.sfo CATEGORY (gd = game, gp = patch, ac = DLC...), or null when absent. Read once. + public string? Category + { + get + { + if (!_categoryRead) + { + var sfo = ReadParamSfo(); + _category = sfo is null ? null : PkgParamSfo.ReadString(sfo, "CATEGORY"); + _categoryRead = true; + } + + return _category; + } + } + + // param.sfo TITLE (the game's name), or null when absent. + public string? Title => ReadParamSfo() is { } sfo ? PkgParamSfo.ReadString(sfo, "TITLE") : null; + + // Folder name for an install: the game's title made safe for a file name, else its title id, + // else `fallback` (usually the package file name). + public string GetFolderName(string fallback) => + ToFolderName(Title) ?? ToFolderName(TitleId) ?? fallback; + + // The characters Windows refuses in a file name. The host's own list is only '/' and NUL on + // Linux, so extracted trees and folder names would differ by platform, and a package entry + // holding '\' would pass there and become a nested path once copied to Windows. + private static readonly char[] PortableInvalidNameChars = + ['"', '<', '>', '|', ':', '*', '?', '\\', '/', .. Enumerable.Range(0, 32).Select(code => (char)code)]; + + internal static string? ToFolderName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } + + var builder = new System.Text.StringBuilder(name.Length); + foreach (var c in name) + { + // Titles may hold line breaks or characters Windows refuses (':' in "Part I: ..."). + builder.Append(char.IsControl(c) || Array.IndexOf(PortableInvalidNameChars, c) >= 0 ? ' ' : c); + } + + var cleaned = string.Join(' ', builder.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.', ' '); + return cleaned.Length == 0 || cleaned is "." or ".." ? null : cleaned; + } + + // Base games are "gd" (and variants such as "gde"). Packages without a category are treated as + // games; patches ("gp") and DLC ("ac") are not. + public bool IsGameApplication => Category is null || Category.StartsWith("gd", StringComparison.OrdinalIgnoreCase); + + public static bool IsPkgPath(string path) + { + if (!string.Equals(Path.GetExtension(path), ".pkg", StringComparison.OrdinalIgnoreCase) || !File.Exists(path)) + { + return false; + } + + try + { + Span<byte> magic = stackalloc byte[4]; + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + return stream.Read(magic) == 4 && PkgHeader.HasMagic(magic); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + } + + public static PkgPackage Open(string path) + { + var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.RandomAccess); + try + { + var headerBytes = new byte[PkgHeader.Size]; + file.ReadExactly(headerBytes); + var header = PkgHeader.Parse(headerBytes); + if (header.PkgSize > (ulong)file.Length) + { + throw new InvalidDataException("The PKG file is shorter than its header says (incomplete download?)."); + } + + if (header.TableEntryCount > 0x10000) + { + throw new InvalidDataException("PKG entry table is implausibly large."); + } + + if ((ulong)header.TableEntryOffset + (ulong)header.TableEntryCount * PkgEntry.Size_ > header.PkgSize || + (ulong)header.PfsImageOffset + header.PfsImageSize > header.PkgSize) + { + throw new InvalidDataException("PKG points outside its own bounds."); + } + + var table = new byte[checked((int)header.TableEntryCount * PkgEntry.Size_)]; + file.Position = header.TableEntryOffset; + file.ReadExactly(table); + return new PkgPackage(file, header, table, PkgEntry.ParseTable(table, (int)header.TableEntryCount)); + } + catch + { + file.Dispose(); + throw; + } + } + + public byte[] ReadEntry(PkgEntry entry) + { + // A corrupt table must never make us allocate gigabytes before we notice. + if ((ulong)entry.Offset + entry.Size > Header.PkgSize) + { + throw new InvalidDataException("PKG entry lies outside the package."); + } + + var data = new byte[entry.Size]; + _file.Position = entry.Offset; + _file.ReadExactly(data); + return data; + } + + public byte[]? ReadParamSfo() + { + foreach (var entry in Entries) + { + if (entry.Id == 0x1000) + { + return ReadEntry(entry); + } + } + + return null; + } + + // Bytes between progress reports while one large file is being written. + internal const long ProgressStepBytes = 16L * 1024 * 1024; + + // Size on disk of everything Extract writes (sce_sys metadata plus the PFS files), computed + // without extracting. It opens the PFS image to walk its tree. + public long GetInstalledSize() + { + using var image = OpenPfsImageStream(); + var pfs = new PfsImage(new PfscImage(image, PfscImage.FindOffset(image))); + var files = new List<(string Path, PfsInode Inode)>(); + long total = 0; + CollectTree(pfs, pfs.GetUserRoot(), string.Empty, files, ref total, new HashSet<int>(), 0); + return total + MetadataSize(); + } + + private long MetadataSize() + { + long size = 0; + foreach (var entry in Entries) + { + if (entry.Name is not null) + { + size += entry.Size; + } + } + + return size; + } + + // Free bytes on the drive that will hold `destination`, or null when it cannot be told. + internal static long? GetAvailableSpace(string destination) + { + try + { + var root = Path.GetPathRoot(Path.GetFullPath(destination)); + return string.IsNullOrEmpty(root) ? null : new DriveInfo(root).AvailableFreeSpace; + } + catch (Exception exception) when (exception is ArgumentException or IOException or UnauthorizedAccessException or NotSupportedException) + { + return null; + } + } + + // Writes sce_sys metadata and the whole PFS tree into `destination`, which then is a game + // folder (eboot.bin at its root). Throws IOException before writing anything when the drive + // is known to be too small. + public void Extract(string destination, IProgress<PkgExtractProgress>? progress = null, CancellationToken cancellation = default) => + Extract(destination, progress, cancellation, ProgressStepBytes, GetAvailableSpace(destination)); + + internal void Extract( + string destination, + IProgress<PkgExtractProgress>? progress, + CancellationToken cancellation, + long progressStepBytes, + long? availableBytes) + { + using var image = OpenPfsImageStream(); + var pfsc = new PfscImage(image, PfscImage.FindOffset(image)); + var pfs = new PfsImage(pfsc); + + var files = new List<(string Path, PfsInode Inode)>(); + long total = 0; + CollectTree(pfs, pfs.GetUserRoot(), destination, files, ref total, new HashSet<int>(), 0); + + var needed = total + MetadataSize(); + if (availableBytes is { } available && available < needed) + { + throw new IOException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Not enough free disk space: need {needed / (1024.0 * 1024 * 1024):0.00} GB, {available / (1024.0 * 1024 * 1024):0.00} GB free.")); + } + + Directory.CreateDirectory(destination); + foreach (var entry in Entries) + { + if (entry.Name is { } name) + { + var path = ResolveSafe(Path.Combine(destination, "sce_sys"), name.Split('/')); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, ReadEntry(entry)); + } + } + + long done = 0; + foreach (var (path, inode) in files) + { + cancellation.ThrowIfCancellationRequested(); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var relative = Path.GetRelativePath(destination, path); + progress?.Report(new PkgExtractProgress(done, total, relative)); + var sinceReport = 0L; + using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 20, FileOptions.SequentialScan); + pfs.CopyFile(inode, output, bytes => + { + done += bytes; + sinceReport += bytes; + cancellation.ThrowIfCancellationRequested(); + if (sinceReport >= progressStepBytes) + { + sinceReport = 0; + progress?.Report(new PkgExtractProgress(done, total, relative)); + } + }); + progress?.Report(new PkgExtractProgress(done, total, relative)); + } + + progress?.Report(new PkgExtractProgress(total, total, string.Empty)); + } + + private PkgPfsStream OpenPfsImageStream() + { + var imageKeyEntry = FindEntry(PkgEntry.ImageKeyId, out var imageKeyRow); + var keysEntry = FindEntry(PkgEntry.EntryKeysId, out _); + if (imageKeyEntry is null || keysEntry is null) + { + // No key material means the PFS image is stored in the clear. + return new PkgPfsStream(_file, (long)Header.PfsImageOffset, (long)Header.PfsImageSize, null, null); + } + + var keys = ReadEntry(keysEntry.Value); + var key3Offset = EntryKeysTableOffset + 3 * EntryKeySize; + if (keys.Length < key3Offset + EntryKeySize) + { + throw new InvalidDataException("PKG entry keys entry is truncated."); + } + + var dk3 = PkgCrypto.DeriveDk3(keys.AsSpan(key3Offset, EntryKeySize)); + var imageKey = ReadEntry(imageKeyEntry.Value); + if (imageKey.Length < EntryKeySize) + { + throw new InvalidDataException("PKG image key entry is truncated."); + } + + var ekpfs = PkgCrypto.DeriveEkpfs(imageKeyRow, dk3, imageKey.AsSpan(0, EntryKeySize)); + + var seed = new byte[16]; + _file.Position = (long)Header.PfsImageOffset + PfsSeedOffset; + _file.ReadExactly(seed); + var (dataKey, tweakKey) = PkgCrypto.DerivePfsKeys(ekpfs, seed); + return new PkgPfsStream(_file, (long)Header.PfsImageOffset, (long)Header.PfsImageSize, dataKey, tweakKey); + } + + private PkgEntry? FindEntry(uint id, out byte[] row) + { + for (var i = 0; i < Entries.Count; i++) + { + if (Entries[i].Id == id) + { + row = _entryTable.AsSpan(i * PkgEntry.Size_, PkgEntry.Size_).ToArray(); + return Entries[i]; + } + } + + row = []; + return null; + } + + private static void CollectTree( + PfsImage pfs, + PfsInode directory, + string path, + List<(string, PfsInode)> files, + ref long total, + HashSet<int> visiting, + int depth) + { + if (depth > 64) + { + throw new InvalidDataException("PFS directory tree is too deep."); + } + + foreach (var entry in pfs.ReadDirectory(directory)) + { + if (entry.Type is (int)PfsDirentType.CurrentDirectory or (int)PfsDirentType.ParentDirectory) + { + continue; + } + + var target = ResolveSafe(path, [entry.Name]); + var inode = pfs.GetInode(entry.Inode); + if (entry.Type == (int)PfsDirentType.Directory) + { + if (!visiting.Add(entry.Inode)) + { + throw new InvalidDataException("PFS directory tree has a cycle."); + } + + CollectTree(pfs, inode, target, files, ref total, visiting, depth + 1); + visiting.Remove(entry.Inode); + } + else if (entry.Type == (int)PfsDirentType.File) + { + files.Add((target, inode)); + total += inode.Size; + } + } + } + + // Joins path components below `root`, refusing anything that could leave it. + internal static string ResolveSafe(string root, string[] components) + { + var path = root; + foreach (var component in components) + { + if (component.Length == 0 || component is "." or ".." || + component.IndexOfAny(PortableInvalidNameChars) >= 0) + { + throw new InvalidDataException($"Unsafe path component '{component}' in package."); + } + + path = Path.Combine(path, component); + } + + return path; + } + + public void Dispose() => _file.Dispose(); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgParamSfo.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgParamSfo.cs new file mode 100644 index 000000000..368786f4b --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgParamSfo.cs @@ -0,0 +1,81 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// A tiny param.sfo reader for package metadata. HLE cannot reference the GnmMode loader, so this +// reads just enough to look up string values by key. Anything malformed yields null. +public static class PkgParamSfo +{ + private const uint Magic = 0x46535000; + private const int HeaderSize = 0x14; + private const int IndexEntrySize = 16; + + public static string? ReadString(ReadOnlySpan<byte> sfo, string key) + { + if (sfo.Length < HeaderSize || BinaryPrimitives.ReadUInt32LittleEndian(sfo) != Magic) + { + return null; + } + + var keyTable = BinaryPrimitives.ReadUInt32LittleEndian(sfo[8..]); + var dataTable = BinaryPrimitives.ReadUInt32LittleEndian(sfo[0xC..]); + var count = BinaryPrimitives.ReadUInt32LittleEndian(sfo[0x10..]); + if (keyTable > sfo.Length || dataTable > sfo.Length || count > (uint)((sfo.Length - HeaderSize) / IndexEntrySize)) + { + return null; + } + + for (var i = 0; i < count; i++) + { + var entry = sfo.Slice(HeaderSize + i * IndexEntrySize, IndexEntrySize); + var keyOffset = BinaryPrimitives.ReadUInt16LittleEndian(entry); + var format = BinaryPrimitives.ReadUInt16LittleEndian(entry[2..]); + var length = BinaryPrimitives.ReadUInt32LittleEndian(entry[4..]); + var dataOffset = BinaryPrimitives.ReadUInt32LittleEndian(entry[12..]); + + var keyStart = (long)keyTable + keyOffset; + if (keyStart >= sfo.Length) + { + return null; + } + + var keyBytes = sfo[(int)keyStart..]; + var keyEnd = keyBytes.IndexOf((byte)0); + if (keyEnd < 0) + { + return null; + } + + if (!Encoding.ASCII.GetString(keyBytes[..keyEnd]).Equals(key, StringComparison.Ordinal)) + { + continue; + } + + if (format is not (0x0204 or 0x0004)) + { + return null; + } + + var valueStart = (long)dataTable + dataOffset; + if (valueStart + length > sfo.Length) + { + return null; + } + + var value = sfo.Slice((int)valueStart, (int)length); + var nul = value.IndexOf((byte)0); + if (nul >= 0) + { + value = value[..nul]; + } + + return Encoding.UTF8.GetString(value); + } + + return null; + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs new file mode 100644 index 000000000..5766500c2 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs @@ -0,0 +1,141 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Security.Cryptography; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// A read-only, seekable view of a PKG's PFS image with the XTS sector encryption removed. The +// tweak of a sector is its absolute number in the image; sectors before +// PkgCrypto.FirstEncryptedSector are plain. +public sealed class PkgPfsStream : Stream +{ + private readonly Stream _inner; + private readonly long _start; + private readonly long _length; + private readonly Aes? _dataCipher; + private readonly Aes? _tweakCipher; + private long _position; + private byte[] _scratch = new byte[PkgCrypto.SectorSize]; + + // Pass null keys for an image that is not encrypted. + public PkgPfsStream(Stream inner, long imageOffset, long imageSize, byte[]? dataKey, byte[]? tweakKey) + { + _inner = inner; + _start = imageOffset; + _length = imageSize; + if (dataKey is not null && tweakKey is not null) + { + _dataCipher = Aes.Create(); + _dataCipher.Key = dataKey; + _tweakCipher = Aes.Create(); + _tweakCipher.Key = tweakKey; + } + } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => _length; + + public override long Position + { + get => _position; + set => _position = value < 0 ? throw new ArgumentOutOfRangeException(nameof(value)) : value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span<byte> destination) + { + var remaining = _length - _position; + if (remaining <= 0 || destination.IsEmpty) + { + return 0; + } + + if (destination.Length > remaining) + { + destination = destination[..(int)remaining]; + } + + var alignedStart = _position & ~(long)(PkgCrypto.SectorSize - 1); + var alignedEnd = (_position + destination.Length + PkgCrypto.SectorSize - 1) & ~(long)(PkgCrypto.SectorSize - 1); + var span = (int)(alignedEnd - alignedStart); + if (_scratch.Length < span) + { + _scratch = new byte[span]; + } + + var window = _scratch.AsSpan(0, span); + _inner.Position = _start + alignedStart; + var filled = 0; + while (filled < span) + { + var read = _inner.Read(window[filled..]); + if (read == 0) + { + break; + } + + filled += read; + } + + // Sectors cut short by the end of the file are zero padded: PFS images are sector sized. + window[filled..].Clear(); + + if (_dataCipher is not null && _tweakCipher is not null) + { + for (var offset = 0; offset < span; offset += PkgCrypto.SectorSize) + { + var sector = (alignedStart + offset) / PkgCrypto.SectorSize; + if (sector >= PkgCrypto.FirstEncryptedSector) + { + PkgCrypto.XtsDecrypt(_dataCipher, _tweakCipher, + window.Slice(offset, PkgCrypto.SectorSize), (ulong)sector); + } + } + } + + window.Slice((int)(_position - alignedStart), destination.Length).CopyTo(destination); + _position += destination.Length; + return destination.Length; + } + + public override long Seek(long offset, SeekOrigin origin) + { + var target = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => _length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + if (target < 0) + { + throw new IOException("An attempt was made to move the position before the beginning of the stream."); + } + + _position = target; + return _position; + } + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _dataCipher?.Dispose(); + _tweakCipher?.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs new file mode 100644 index 000000000..14a74dce5 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs @@ -0,0 +1,721 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using SharpEmu.HLE.FileSystem.Pkg; +using Xunit; + +namespace SharpEmu.Libs.Tests.FileSystem; + +// Synthetic data only: nothing here comes from a real package. +public sealed class PkgTests +{ + [Fact] + public void HeaderFieldsAreReadBigEndian() + { + var data = new byte[PkgHeader.Size]; + BinaryPrimitives.WriteUInt32BigEndian(data, PkgHeader.Magic); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(0x0C), 7); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(0x10), 12); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(0x18), 0x2000); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(0x20), 0x2000); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(0x30), 0x80000); + Encoding.ASCII.GetBytes("UP9000-CUSA00900_00-BLOODBORNE000000").CopyTo(data, 0x40); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(0x78), 0x0A000000); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(0x404), 1); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(0x408), 0x8000000000000004); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(0x410), 0x80000); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(0x418), 0x1234_5678_9ABC); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(0x430), 0x2_0000_0000); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(0x43C), 0x4000); + + var header = PkgHeader.Parse(data); + + Assert.Equal(7u, header.FileCount); + Assert.Equal(12u, header.TableEntryCount); + Assert.Equal(0x2000u, header.TableEntryOffset); + Assert.Equal(0x80000ul, header.ContentOffset); + Assert.Equal("UP9000-CUSA00900_00-BLOODBORNE000000", header.ContentId); + Assert.Equal("CUSA00900", header.TitleId); + Assert.Equal(0x0A000000u, header.ContentFlags); + Assert.Equal(0x8000000000000004ul, header.PfsImageFlags); + Assert.Equal(0x80000ul, header.PfsImageOffset); + Assert.Equal(0x1234_5678_9ABCul, header.PfsImageSize); + Assert.Equal(0x2_0000_0000ul, header.PkgSize); + Assert.Equal(0x4000u, header.PfsCacheSize); + } + + [Fact] + public void HeaderRejectsBadMagicAndTruncation() + { + Assert.Throws<InvalidDataException>(() => PkgHeader.Parse(new byte[PkgHeader.Size])); + var good = new byte[PkgHeader.Size]; + BinaryPrimitives.WriteUInt32BigEndian(good, PkgHeader.Magic); + Assert.Throws<InvalidDataException>(() => PkgHeader.Parse(good.AsSpan(0, 0x100))); + Assert.True(PkgHeader.HasMagic([0x7F, 0x43, 0x4E, 0x54])); + Assert.False(PkgHeader.HasMagic([0x50, 0x4B, 0x03, 0x04])); + } + + [Fact] + public void EntryTableRowsAreParsedAndNamed() + { + var table = new byte[64]; + WriteEntry(table.AsSpan(0, 32), id: 0x1000, nameOffset: 5, flags1: 0, flags2: 0, offset: 0x3000, size: 0x1C0); + WriteEntry(table.AsSpan(32, 32), id: 0x1200, nameOffset: 9, flags1: 0x80000000, flags2: 0x3000, offset: 0x3200, size: 0x4000); + + var entries = PkgEntry.ParseTable(table, 2); + + Assert.Equal(0x1000u, entries[0].Id); + Assert.Equal("param.sfo", entries[0].Name); + Assert.Equal(0x3000u, entries[0].Offset); + Assert.Equal(0x1C0u, entries[0].Size); + Assert.Equal("icon0.png", entries[1].Name); + Assert.Equal(0x80000000u, entries[1].Flags1); + Assert.Equal(0x3000u, entries[1].Flags2); + Assert.Throws<InvalidDataException>(() => PkgEntry.ParseTable(table, 3)); + } + + [Theory] + [InlineData(0x402u, "nptitle.dat")] + [InlineData(0x403u, "npbind.dat")] + public void TrophyBindingEntriesAreExtractedIntoSceSys(uint id, string expected) => + Assert.Equal(expected, PkgEntryNames.Get(id)); + + [Fact] + public void ParamSfoReaderFindsStringKeys() + { + var sfo = BuildSfo(("TITLE_ID", "CUSA99999"), ("CATEGORY", "gp")); + Assert.Equal("gp", PkgParamSfo.ReadString(sfo, "CATEGORY")); + Assert.Equal("CUSA99999", PkgParamSfo.ReadString(sfo, "TITLE_ID")); + Assert.Null(PkgParamSfo.ReadString(sfo, "APP_VER")); + } + + [Fact] + public void ParamSfoReaderReturnsNullForMalformedData() + { + var sfo = BuildSfo(("CATEGORY", "gd")); + Assert.Null(PkgParamSfo.ReadString([], "CATEGORY")); + Assert.Null(PkgParamSfo.ReadString(new byte[64], "CATEGORY")); + for (var length = 0; length < sfo.Length; length++) + { + // Truncation at any point must never throw; short of the value it must yield null. + var truncated = sfo.AsSpan(0, length).ToArray(); + var value = PkgParamSfo.ReadString(truncated, "CATEGORY"); + Assert.True(value is null || value == "gd"); + } + + Assert.Null(PkgParamSfo.ReadString(sfo.AsSpan(0, sfo.Length - 1), "CATEGORY")); + + var hugeCount = (byte[])sfo.Clone(); + BinaryPrimitives.WriteUInt32LittleEndian(hugeCount.AsSpan(0x10), uint.MaxValue); + Assert.Null(PkgParamSfo.ReadString(hugeCount, "CATEGORY")); + + var badOffset = (byte[])sfo.Clone(); + BinaryPrimitives.WriteUInt32LittleEndian(badOffset.AsSpan(0x14 + 12), 0x7FFFFFFF); + Assert.Null(PkgParamSfo.ReadString(badOffset, "CATEGORY")); + } + + [Theory] + [InlineData("gd", true)] + [InlineData("gde", true)] + [InlineData("gp", false)] + [InlineData("ac", false)] + [InlineData(null, true)] + public void PackageCategoryDecidesWhetherItIsAGame(string? category, bool isGame) + { + var pkg = BuildSyntheticPkg( + BuildSyntheticImage(Encoding.ASCII.GetBytes("EBOOT")), + (0x1000, category is null ? BuildSfo(("TITLE_ID", "CUSA99999")) : BuildSfo(("CATEGORY", category)))); + var packagePath = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-{Guid.NewGuid():N}.pkg"); + try + { + File.WriteAllBytes(packagePath, pkg); + using var package = PkgPackage.Open(packagePath); + Assert.Equal(category, package.Category); + Assert.Equal(isGame, package.IsGameApplication); + } + finally + { + File.Delete(packagePath); + } + } + + private static byte[] BuildSfo(params (string Key, string Value)[] values) + { + var keys = new MemoryStream(); + var data = new MemoryStream(); + var index = new MemoryStream(); + foreach (var (key, value) in values) + { + var entry = new byte[16]; + BinaryPrimitives.WriteUInt16LittleEndian(entry, (ushort)keys.Length); + BinaryPrimitives.WriteUInt16LittleEndian(entry.AsSpan(2), 0x0204); + var bytes = Encoding.UTF8.GetBytes(value + "\0"); + BinaryPrimitives.WriteUInt32LittleEndian(entry.AsSpan(4), (uint)bytes.Length); + BinaryPrimitives.WriteUInt32LittleEndian(entry.AsSpan(8), (uint)bytes.Length); + BinaryPrimitives.WriteUInt32LittleEndian(entry.AsSpan(12), (uint)data.Length); + index.Write(entry); + keys.Write(Encoding.ASCII.GetBytes(key + "\0")); + data.Write(bytes); + } + + var keyTable = 0x14 + (int)index.Length; + var dataTable = keyTable + (int)keys.Length; + var sfo = new byte[dataTable + (int)data.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(sfo, 0x46535000); + BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(4), 0x101); + BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(8), (uint)keyTable); + BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(0xC), (uint)dataTable); + BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(0x10), (uint)values.Length); + index.ToArray().CopyTo(sfo, 0x14); + keys.ToArray().CopyTo(sfo, keyTable); + data.ToArray().CopyTo(sfo, dataTable); + return sfo; + } + + [Fact] + public void PfsStreamSeekRejectsNegativePositions() + { + using var stream = new PkgPfsStream(new MemoryStream(new byte[PkgCrypto.SectorSize * 2]), 0, PkgCrypto.SectorSize * 2, null, null); + Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Begin)); + Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Current)); + Assert.Throws<IOException>(() => stream.Seek(-(PkgCrypto.SectorSize * 2 + 1), SeekOrigin.End)); + Assert.Equal(PkgCrypto.SectorSize * 2 - 4, stream.Seek(-4, SeekOrigin.End)); + } + + [Theory] + [InlineData(0x1201u, "icon0_01.png")] + [InlineData(0x1259u, "pic1_25.png")] + [InlineData(0x1400u, "trophy/trophy00.trp")] + [InlineData(0x1463u, "trophy/trophy99.trp")] + public void NumberedEntryNamesFollowTheirFamilies(uint id, string expected) => + Assert.Equal(expected, PkgEntryNames.Get(id)); + + [Theory] + [InlineData(0x1u)] + [InlineData(0x10u)] + [InlineData(0x20u)] + [InlineData(0x400u)] + public void KeyAndLicenceEntriesAreNotExtractedAsMetadata(uint id) => + Assert.Null(PkgEntryNames.Get(id)); + + // The first 0x50 bytes of the PFS superblock of a retail fake PKG (Bloodborne, CUSA00900). + [Fact] + public void RetailPfsHeaderReadsTheBlockCountAt0x38() + { + var block = Convert.FromHexString( + "0100000000000000" + "0B2A330100000000" + "0000000000000000" + "0000010008000000" + + "0000010000000000" + "0100000000000000" + "E942000000000000" + "DA53060000000000" + + "2C00000000000000" + "0000000000000000"); + var header = PfsHeader.Parse(block); + Assert.Equal(20130315, header.Magic); + Assert.Equal(0x10000, header.BlockSize); + Assert.Equal(414682, header.BlockCount); + Assert.Equal(17129, header.DinodeCount); + Assert.Equal(44, header.DinodeBlockCount); + Assert.Equal(0, header.SuperrootInode); + } + + [Theory] + [InlineData("SIGNALIS", "SIGNALIS")] + [InlineData("The Last of Us Part I: Remastered", "The Last of Us Part I Remastered")] + [InlineData("OMORI\nDeluxe ", "OMORI Deluxe")] + [InlineData("A/B\\C?*", "A B C")] + [InlineData("Trailing...", "Trailing")] + [InlineData(" ", null)] + [InlineData("..", null)] + [InlineData(null, null)] + public void TitlesBecomeSafeFolderNames(string? title, string? expected) => + Assert.Equal(expected, PkgPackage.ToFolderName(title)); + + [Fact] + public void InodeFieldsAreDecoded() + { + var data = new byte[PfsInode.Stride]; + BinaryPrimitives.WriteUInt16LittleEndian(data, 0x81ED); + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(2), 1); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(4), 0x11); + BinaryPrimitives.WriteInt64LittleEndian(data.AsSpan(8), 123_456); + BinaryPrimitives.WriteInt64LittleEndian(data.AsSpan(16), 50_000); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x60), 2); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x64), 77); + + var inode = PfsInode.Parse(data); + + Assert.True(inode.IsFile); + Assert.False(inode.IsDirectory); + Assert.Equal(0x11u, inode.Flags); + Assert.Equal(123_456, inode.Size); + Assert.Equal(50_000, inode.SizeCompressed); + Assert.Equal(2u, inode.Blocks); + Assert.Equal(77u, inode.Location); + Assert.True(PfsInode.Parse(new byte[PfsInode.Stride]).IsEmpty); + } + + [Fact] + public void DirentsAreDecodedUntilTheFirstEmptyEntry() + { + var block = new byte[PfscImage.BlockSize]; + var offset = 0; + offset = WriteDirent(block, offset, 5, PfsDirentType.CurrentDirectory, "."); + offset = WriteDirent(block, offset, 1, PfsDirentType.ParentDirectory, ".."); + offset = WriteDirent(block, offset, 6, PfsDirentType.File, "eboot.bin"); + WriteDirent(block, offset, 7, PfsDirentType.Directory, "sce_sys"); + + var entries = PfsDirent.ParseBlock(block); + + Assert.Equal(4, entries.Count); + Assert.Equal(new PfsDirent(6, 2, "eboot.bin"), entries[2]); + Assert.Equal(new PfsDirent(7, 3, "sce_sys"), entries[3]); + } + + [Fact] + public void ImageIsReadThroughPfscAndWalked() + { + var content = new byte[150_000]; + new System.Random(5).NextBytes(content); + for (var i = 0; i < 100_000; i++) + { + content[i] = (byte)(i % 7); // compressible head, random tail + } + + var pfsc = BuildSyntheticImage(content); + + var image = new PfsImage(new PfscImage(new MemoryStream(pfsc), 0)); + Assert.Equal(PfscImage.BlockSize, image.Header.BlockSize); + + var root = image.GetUserRoot(); + Assert.True(root.IsDirectory); + var entries = image.ReadDirectory(root); + var file = Assert.Single(entries, entry => entry.Type == (int)PfsDirentType.File); + Assert.Equal("eboot.bin", file.Name); + + var output = new MemoryStream(); + long reported = 0; + image.CopyFile(image.GetInode(file.Inode), output, bytes => reported += bytes); + + Assert.Equal(content, output.ToArray()); + Assert.Equal(content.Length, reported); + } + + [Fact] + public void PfscWithoutMagicIsRejected() => + Assert.Throws<InvalidDataException>(() => new PfscImage(new MemoryStream(new byte[0x100]), 0)); + + [Fact] + public void SectorStreamDecryptsAtAnyOffsetAndLeavesTheHeaderPlain() + { + var dataKey = RandomNumberGenerator.GetBytes(16); + var tweakKey = RandomNumberGenerator.GetBytes(16); + var plain = new byte[PkgCrypto.SectorSize * 20]; + new System.Random(11).NextBytes(plain); + + var encrypted = (byte[])plain.Clone(); + using (var data = Aes.Create()) + using (var tweak = Aes.Create()) + { + data.Key = dataKey; + tweak.Key = tweakKey; + for (var sector = 16; sector < 20; sector++) + { + XtsEncryptSector(data, tweak, encrypted.AsSpan(sector * PkgCrypto.SectorSize, PkgCrypto.SectorSize), (ulong)sector); + } + } + + // The image sits at a non-zero offset inside a larger container. + var container = new byte[100 + encrypted.Length + 50]; + encrypted.CopyTo(container, 100); + using var stream = new PkgPfsStream(new MemoryStream(container), 100, encrypted.Length, dataKey, tweakKey); + + var whole = new byte[plain.Length]; + stream.ReadExactly(whole); + Assert.Equal(plain, whole); + + var slice = new byte[9000]; + stream.Position = 16 * PkgCrypto.SectorSize + 4000; + stream.ReadExactly(slice); + Assert.Equal(plain.AsSpan(16 * PkgCrypto.SectorSize + 4000, 9000).ToArray(), slice); + + stream.Position = 5; + var header = new byte[10]; + stream.ReadExactly(header); + Assert.Equal(plain.AsSpan(5, 10).ToArray(), header); + Assert.Equal(0, stream.Read(new byte[4], 0, 0)); + } + + [Fact] + public void XtsMatchesTheIeee1619Vector() + { + using var data = Aes.Create(); + using var tweak = Aes.Create(); + data.Key = new byte[16]; + tweak.Key = new byte[16]; + var buffer = Convert.FromHexString("917cf69ebd68b2ec9b9fe9a3eadda692cd43d2f59598ed858c02c2652fbf922e"); + + PkgCrypto.XtsDecrypt(data, tweak, buffer, 0); + + Assert.Equal(new byte[32], buffer); + } + + [Fact] + public void PfsKeysSplitTheHmacIntoTweakThenData() + { + var ekpfs = new byte[32]; + var seed = new byte[16]; + var (dataKey, tweakKey) = PkgCrypto.DerivePfsKeys(ekpfs, seed); + + var input = new byte[20]; + input[0] = 1; + var hash = HMACSHA256.HashData(ekpfs, input); + Assert.Equal(hash[..16], tweakKey); + Assert.Equal(hash[16..], dataKey); + } + + [Fact] + public void Pkcs1UnpaddingReturnsTheMessageAndRejectsBadBlocks() + { + var block = new byte[64]; + block[1] = 2; + Array.Fill(block, (byte)0xAA, 2, 20); + block[22] = 0; + Encoding.ASCII.GetBytes("secret").CopyTo(block, 23); + Array.Resize(ref block, 29); + + Assert.Equal("secret", Encoding.ASCII.GetString(PkgCrypto.UnpadPkcs1(block))); + Assert.Throws<InvalidDataException>(() => PkgCrypto.UnpadPkcs1(new byte[64])); + } + + [Theory] + [InlineData("..")] + [InlineData(".")] + [InlineData("")] + [InlineData("a/b")] + [InlineData("a\\b")] + public void UnsafePathComponentsAreRefused(string component) => + Assert.Throws<InvalidDataException>(() => PkgPackage.ResolveSafe("root", [component])); + + [Fact] + public void SafePathComponentsStayBelowTheRoot() => + Assert.Equal(Path.Combine("root", "sce_sys", "param.sfo"), PkgPackage.ResolveSafe("root", ["sce_sys", "param.sfo"])); + + [Fact] + public void ExtractWritesMetadataAndPfsTreeWithProgress() + { + var eboot = Encoding.ASCII.GetBytes("FAKE EBOOT BIN"); + var pkg = BuildSyntheticPkg( + BuildSyntheticImage(eboot), + (0x1000, Encoding.ASCII.GetBytes("PARAM")), + (0x1200, Encoding.ASCII.GetBytes("PNG"))); + var packagePath = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-{Guid.NewGuid():N}.pkg"); + var destination = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-out-{Guid.NewGuid():N}"); + try + { + File.WriteAllBytes(packagePath, pkg); + using var package = PkgPackage.Open(packagePath); + Assert.Equal("CUSA99999", package.TitleId); + + var reports = new List<PkgExtractProgress>(); + package.Extract(destination, new CollectingProgress<PkgExtractProgress>(reports.Add)); + + Assert.Equal("PARAM", File.ReadAllText(Path.Combine(destination, "sce_sys", "param.sfo"))); + Assert.Equal("PNG", File.ReadAllText(Path.Combine(destination, "sce_sys", "icon0.png"))); + Assert.Equal(eboot, File.ReadAllBytes(Path.Combine(destination, "eboot.bin"))); + Assert.NotEmpty(reports); + Assert.Equal(reports[^1].BytesTotal, reports[^1].BytesDone); + Assert.Equal(eboot.Length, reports[^1].BytesTotal); + Assert.All(reports, report => Assert.True(report.BytesDone <= report.BytesTotal)); + } + finally + { + File.Delete(packagePath); + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + } + } + + [Fact] + public void ExtractReportsProgressInsideALargeFile() + { + var eboot = new byte[PfscImage.BlockSize * 4]; + System.Random.Shared.NextBytes(eboot); + WithSyntheticPackage(BuildSyntheticPkg(BuildSyntheticImage(eboot)), (package, destination) => + { + var reports = new List<PkgExtractProgress>(); + package.Extract(destination, new CollectingProgress<PkgExtractProgress>(reports.Add), default, PfscImage.BlockSize, null); + + var midFile = reports.Where(report => report.BytesDone > 0 && report.BytesDone < eboot.Length).Select(report => report.BytesDone).Distinct().ToList(); + Assert.True(midFile.Count >= 3, $"expected mid-file reports, got {midFile.Count}"); + Assert.Equal(eboot, File.ReadAllBytes(Path.Combine(destination, "eboot.bin"))); + }); + } + + [Fact] + public void ExtractThrottlesProgressWithTheDefaultStep() + { + var eboot = new byte[PfscImage.BlockSize * 4]; + WithSyntheticPackage(BuildSyntheticPkg(BuildSyntheticImage(eboot)), (package, destination) => + { + var reports = new List<PkgExtractProgress>(); + package.Extract(destination, new CollectingProgress<PkgExtractProgress>(reports.Add)); + Assert.DoesNotContain(reports, report => report.BytesDone > 0 && report.BytesDone < eboot.Length); + }); + } + + [Fact] + public void ExtractRefusesWhenTheDriveIsTooSmallAndWritesNothing() + { + var pkg = BuildSyntheticPkg(BuildSyntheticImage(new byte[1000]), (0x1000, Encoding.ASCII.GetBytes("PARAM"))); + WithSyntheticPackage(pkg, (package, destination) => + { + Assert.Equal(1005, package.GetInstalledSize()); + var exception = Assert.Throws<IOException>(() => + package.Extract(destination, null, default, PkgPackage.ProgressStepBytes, availableBytes: 1004)); + Assert.Contains("Not enough free disk space", exception.Message); + Assert.False(Directory.Exists(destination)); + + package.Extract(destination, null, default, PkgPackage.ProgressStepBytes, availableBytes: 1005); + Assert.True(File.Exists(Path.Combine(destination, "eboot.bin"))); + }); + } + + private static void WithSyntheticPackage(byte[] pkg, Action<PkgPackage, string> body) + { + var packagePath = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-{Guid.NewGuid():N}.pkg"); + var destination = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-out-{Guid.NewGuid():N}"); + try + { + File.WriteAllBytes(packagePath, pkg); + using var package = PkgPackage.Open(packagePath); + body(package, destination); + } + finally + { + File.Delete(packagePath); + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + } + } + + [Fact] + public void ExtractRefusesAnEntryLargerThanThePackage() + { + var pkg = BuildSyntheticPkg( + BuildSyntheticImage(Encoding.ASCII.GetBytes("EBOOT")), + (0x1000, Encoding.ASCII.GetBytes("PARAM"))); + BinaryPrimitives.WriteUInt32BigEndian(pkg.AsSpan(PkgHeader.Size + 20), uint.MaxValue); + var packagePath = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-{Guid.NewGuid():N}.pkg"); + var destination = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-out-{Guid.NewGuid():N}"); + try + { + File.WriteAllBytes(packagePath, pkg); + using var package = PkgPackage.Open(packagePath); + Assert.Throws<InvalidDataException>(() => package.Extract(destination)); + } + finally + { + File.Delete(packagePath); + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + } + } + + [Fact] + public void ExtractRefusesAnImplausibleInodeTable() + { + const int imageOffset = 0x20000; + var pkg = BuildSyntheticPkg(BuildSyntheticImage(Encoding.ASCII.GetBytes("EBOOT"))); + BinaryPrimitives.WriteInt64LittleEndian(pkg.AsSpan(imageOffset + 0x20000 + 0x30), 100_000); + var packagePath = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-{Guid.NewGuid():N}.pkg"); + var destination = Path.Combine(Path.GetTempPath(), $"sharpemu-pkg-out-{Guid.NewGuid():N}"); + try + { + File.WriteAllBytes(packagePath, pkg); + using var package = PkgPackage.Open(packagePath); + Assert.Throws<InvalidDataException>(() => package.Extract(destination)); + } + finally + { + File.Delete(packagePath); + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + } + } + + private sealed class CollectingProgress<T>(Action<T> handler) : IProgress<T> + { + public void Report(T value) => handler(value); + } + + // A minimal PKG with one unencrypted PFS image and a few sce_sys entries. No key entries: + // the reader falls back to reading the image as-is, which keeps this fixture self-contained. + private static byte[] BuildSyntheticPkg(byte[] image, params (uint Id, byte[] Data)[] entries) + { + const int imageOffset = 0x20000; + // FindOffset starts looking for PFSC after the image's own header blocks. + const int pfsPrefix = 0x20000; + var storedImage = new byte[pfsPrefix + image.Length]; + image.CopyTo(storedImage, pfsPrefix); + var tableOffset = PkgHeader.Size; + var bodyOffset = tableOffset + entries.Length * PkgEntry.Size_; + var package = new byte[imageOffset + storedImage.Length]; + + BinaryPrimitives.WriteUInt32BigEndian(package, PkgHeader.Magic); + BinaryPrimitives.WriteUInt32BigEndian(package.AsSpan(0x10), (uint)entries.Length); + BinaryPrimitives.WriteUInt32BigEndian(package.AsSpan(0x18), (uint)tableOffset); + BinaryPrimitives.WriteUInt64BigEndian(package.AsSpan(0x20), (ulong)bodyOffset); + Encoding.ASCII.GetBytes("UP9000-CUSA99999_00-SYNTHETIC000000").CopyTo(package, 0x40); + BinaryPrimitives.WriteUInt32BigEndian(package.AsSpan(0x404), 1); + BinaryPrimitives.WriteUInt64BigEndian(package.AsSpan(0x410), imageOffset); + BinaryPrimitives.WriteUInt64BigEndian(package.AsSpan(0x418), (ulong)storedImage.Length); + BinaryPrimitives.WriteUInt64BigEndian(package.AsSpan(0x430), (ulong)package.Length); + + var body = bodyOffset; + for (var i = 0; i < entries.Length; i++) + { + WriteEntry(package.AsSpan(tableOffset + i * PkgEntry.Size_, PkgEntry.Size_), + entries[i].Id, 0, 0, 0, (uint)body, (uint)entries[i].Data.Length); + entries[i].Data.CopyTo(package, body); + body += entries[i].Data.Length; + } + + storedImage.CopyTo(package, imageOffset); + return package; + } + + private static void WriteEntry(Span<byte> row, uint id, uint nameOffset, uint flags1, uint flags2, uint offset, uint size) + { + BinaryPrimitives.WriteUInt32BigEndian(row, id); + BinaryPrimitives.WriteUInt32BigEndian(row[4..], nameOffset); + BinaryPrimitives.WriteUInt32BigEndian(row[8..], flags1); + BinaryPrimitives.WriteUInt32BigEndian(row[12..], flags2); + BinaryPrimitives.WriteUInt32BigEndian(row[16..], offset); + BinaryPrimitives.WriteUInt32BigEndian(row[20..], size); + } + + private static int WriteDirent(byte[] block, int offset, int inode, PfsDirentType type, string name) + { + var nameBytes = Encoding.UTF8.GetBytes(name); + var entrySize = (16 + nameBytes.Length + 7) & ~7; + BinaryPrimitives.WriteInt32LittleEndian(block.AsSpan(offset), inode); + BinaryPrimitives.WriteInt32LittleEndian(block.AsSpan(offset + 4), (int)type); + BinaryPrimitives.WriteInt32LittleEndian(block.AsSpan(offset + 8), nameBytes.Length); + BinaryPrimitives.WriteInt32LittleEndian(block.AsSpan(offset + 12), entrySize); + nameBytes.CopyTo(block, offset + 16); + return offset + entrySize; + } + + private static void WriteInode(byte[] block, int slot, ushort mode, long size, uint blocks, uint location) + { + var span = block.AsSpan(slot * PfsInode.Stride, PfsInode.Stride); + BinaryPrimitives.WriteUInt16LittleEndian(span, mode); + BinaryPrimitives.WriteInt64LittleEndian(span[8..], size); + BinaryPrimitives.WriteUInt32LittleEndian(span[0x60..], blocks); + BinaryPrimitives.WriteUInt32LittleEndian(span[0x64..], location); + } + + // Logical blocks: 0 header, 1 inodes, 2 super root dir, 3 uroot dir, 4.. file data. + // Inodes: 0 super root, 1 uroot, 2 eboot.bin. Block 4 is stored compressed, the rest raw. + private static byte[] BuildSyntheticImage(byte[] content) + { + var fileBlocks = (content.Length + PfscImage.BlockSize - 1) / PfscImage.BlockSize; + var logical = new List<byte[]>(); + + var header = new byte[PfscImage.BlockSize]; + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(0x20), PfscImage.BlockSize); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x28), 1); // as in retail images + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x38), 4 + fileBlocks); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x30), 3); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x40), 1); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x48), 0); + logical.Add(header); + + var inodes = new byte[PfscImage.BlockSize]; + WriteInode(inodes, 0, PfsInode.ModeDirectory, PfscImage.BlockSize, 1, 2); + WriteInode(inodes, 1, PfsInode.ModeDirectory, PfscImage.BlockSize, 1, 3); + WriteInode(inodes, 2, PfsInode.ModeFile, content.Length, (uint)fileBlocks, 4); + logical.Add(inodes); + + var superRoot = new byte[PfscImage.BlockSize]; + var offset = WriteDirent(superRoot, 0, 1, PfsDirentType.File, "flat_path_table"); + WriteDirent(superRoot, offset, 1, PfsDirentType.Directory, "uroot"); + logical.Add(superRoot); + + var userRoot = new byte[PfscImage.BlockSize]; + offset = WriteDirent(userRoot, 0, 1, PfsDirentType.CurrentDirectory, "."); + offset = WriteDirent(userRoot, offset, 0x7FFF, PfsDirentType.ParentDirectory, ".."); + WriteDirent(userRoot, offset, 2, PfsDirentType.File, "eboot.bin"); + logical.Add(userRoot); + + for (var i = 0; i < fileBlocks; i++) + { + var block = new byte[PfscImage.BlockSize]; + Array.Copy(content, i * PfscImage.BlockSize, block, 0, Math.Min(PfscImage.BlockSize, content.Length - i * PfscImage.BlockSize)); + logical.Add(block); + } + + var stored = new List<byte[]>(); + foreach (var block in logical) + { + using var compressed = new MemoryStream(); + using (var zlib = new ZLibStream(compressed, CompressionLevel.SmallestSize, leaveOpen: true)) + { + zlib.Write(block); + } + + stored.Add(compressed.Length < PfscImage.BlockSize ? compressed.ToArray() : block); + } + + var tableOffset = 0x30; + var dataStart = tableOffset + (stored.Count + 1) * 8; + var image = new MemoryStream(); + var pfscHeader = new byte[dataStart]; + BinaryPrimitives.WriteUInt32LittleEndian(pfscHeader, PfscImage.Magic); + BinaryPrimitives.WriteInt32LittleEndian(pfscHeader.AsSpan(0x0C), PfscImage.BlockSize); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x10), PfscImage.BlockSize); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x18), tableOffset); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x20), dataStart); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x28), (long)stored.Count * PfscImage.BlockSize); + long position = dataStart; + for (var i = 0; i < stored.Count; i++) + { + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(tableOffset + i * 8), position); + position += stored[i].Length; + } + + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(tableOffset + stored.Count * 8), position); + image.Write(pfscHeader); + foreach (var block in stored) + { + image.Write(block); + } + + return image.ToArray(); + } + + private static void XtsEncryptSector(Aes data, Aes tweakCipher, Span<byte> sector, ulong number) + { + Span<byte> tweak = stackalloc byte[16]; + BinaryPrimitives.WriteUInt64LittleEndian(tweak, number); + tweakCipher.EncryptEcb(tweak, tweak, PaddingMode.None); + Span<byte> block = stackalloc byte[16]; + for (var offset = 0; offset < sector.Length; offset += 16) + { + var current = sector.Slice(offset, 16); + for (var i = 0; i < 16; i++) block[i] = (byte)(current[i] ^ tweak[i]); + data.EncryptEcb(block, block, PaddingMode.None); + for (var i = 0; i < 16; i++) current[i] = (byte)(block[i] ^ tweak[i]); + PkgCrypto.MultiplyTweak(tweak); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs b/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs index de1c7c2ea..e867c77db 100644 --- a/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs +++ b/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs @@ -36,7 +36,7 @@ public void PrepareKeepsTheOriginalPngAndSurvivesSourceRemoval(int width, int he Assert.NotNull(path); Assert.Equal(ShortcutSplashCache.PathForGame(game, cache), path); Assert.Equal(File.ReadAllBytes(source), File.ReadAllBytes(path)); - File.Delete(source); + RetryWhileLocked(() => File.Delete(source)); using var cached = SKBitmap.Decode(File.ReadAllBytes(path)); Assert.NotNull(cached); Assert.Equal(width, cached.Width); @@ -111,5 +111,23 @@ public void SplashClosesOnlyWhenTheGameWindowIsShown(string line, bool ready) Assert.Equal(ready, EmulatorProcess.IsWindowReadyMessage(line)); } - public void Dispose() => Directory.Delete(_root, recursive: true); + public void Dispose() => RetryWhileLocked(() => Directory.Delete(_root, recursive: true)); + + // A Windows virus scanner can briefly hold a freshly written image open; that is not the + // splash cache leaking a handle, so wait for it instead of failing. + private static void RetryWhileLocked(Action delete) + { + for (var attempt = 1; ; attempt++) + { + try + { + delete(); + return; + } + catch (IOException) when (attempt < 20) + { + Thread.Sleep(100); + } + } + } } From 99cfff94dd72110338fa8d6d5040b726a865a165 Mon Sep 17 00:00:00 2001 From: Foued Attar <attar.foued@gmail.com> Date: Fri, 20 Nov 2026 21:23:22 +0100 Subject: [PATCH 04/64] Feat/ps5 pkg (#1157) * [PKG] Read and extract fake/debug PS5 packages PS5 packages (\x7FFIH) wrap an embedded CNT container and a plain outer PFS (PPRPLAIN-NOAUTH! seed) holding pfs_image.dat and naps_pkg_layout.dat. The inner image is streamed through the NAPS block map (stored, sparse or Kraken-compressed 256 KiB blocks) and its flat PFS tree under uroot is written out next to the CNT metadata in sce_sys. Retail packages and encrypted outer images are refused with a clear message. GamePackage.Open picks the PS4 or PS5 reader from the magic. The Kraken decoder is ported from pkg-to-anyps5 and is GPL-3.0-or-later. * [CLI][GUI] Install PS5 packages through the format-detecting reader * [PKG] Skip PS5 self and parent directory records typed 4 and 5 Real fake PS5 packages type the "." and ".." records with the PFS self (4) and parent (5) kinds, so the inner walk treated them as names and refused the install. * [PKG] Ship the GPL-3.0 licence text for the Kraken decoder * [PKG] Refuse PS5 layouts with an implausible mount size Sparse regions cost no stored bytes, so a forged NAPS mount size made the reader build one 256 KiB block record per step of a huge image until memory ran out. --- LICENSES/GPL-3.0-or-later.txt | 232 +++ src/SharpEmu.CLI/Program.cs | 8 +- src/SharpEmu.GUI/Languages/ar.json | 2 +- src/SharpEmu.GUI/Languages/az.json | 2 +- src/SharpEmu.GUI/Languages/br.json | 2 +- src/SharpEmu.GUI/Languages/de.json | 2 +- src/SharpEmu.GUI/Languages/dk.json | 2 +- src/SharpEmu.GUI/Languages/ee.json | 2 +- src/SharpEmu.GUI/Languages/en.json | 2 +- src/SharpEmu.GUI/Languages/es.json | 2 +- src/SharpEmu.GUI/Languages/fr.json | 2 +- src/SharpEmu.GUI/Languages/hu.json | 2 +- src/SharpEmu.GUI/Languages/it.json | 2 +- src/SharpEmu.GUI/Languages/ja.json | 2 +- src/SharpEmu.GUI/Languages/ko.json | 2 +- src/SharpEmu.GUI/Languages/nl.json | 2 +- src/SharpEmu.GUI/Languages/pl.json | 2 +- src/SharpEmu.GUI/Languages/pt.json | 2 +- src/SharpEmu.GUI/Languages/ru.json | 2 +- src/SharpEmu.GUI/Languages/tr.json | 2 +- src/SharpEmu.GUI/Languages/zh.json | 2 +- src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs | 4 +- src/SharpEmu.GUI/PkgInstallDialog.axaml.cs | 2 +- .../FileSystem/Pkg/GamePackage.cs | 56 + .../FileSystem/Pkg/IGamePackage.cs | 31 + src/SharpEmu.HLE/FileSystem/Pkg/Kraken.cs | 1616 +++++++++++++++++ src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs | 4 +- src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs | 227 +++ .../FileSystem/Pkg/Ps5InnerImage.cs | 523 ++++++ src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs | 277 +++ .../FileSystem/Pkg/Ps5OuterPfs.cs | 390 ++++ src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs | 231 +++ src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs | 58 + .../FileSystem/Ps5PkgTests.cs | 956 ++++++++++ 34 files changed, 4626 insertions(+), 27 deletions(-) create mode 100644 LICENSES/GPL-3.0-or-later.txt create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/IGamePackage.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Kraken.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs create mode 100644 tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs diff --git a/LICENSES/GPL-3.0-or-later.txt b/LICENSES/GPL-3.0-or-later.txt new file mode 100644 index 000000000..f6cdd22a6 --- /dev/null +++ b/LICENSES/GPL-3.0-or-later.txt @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>. + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs index f836612e1..6d0756153 100644 --- a/src/SharpEmu.CLI/Program.cs +++ b/src/SharpEmu.CLI/Program.cs @@ -994,7 +994,7 @@ private static string QuoteArgument(string argument) return builder.ToString(); } - // --install-pkg <file.pkg> [destination]: unpacks a fake PS4 package into a game folder (by + // --install-pkg <file.pkg> [destination]: unpacks a fake PS4 or PS5 package into a game folder (by // default <pkg folder>/<game title>) that can then be launched through its eboot.bin. private static int InstallPkg(string[] args) { @@ -1013,7 +1013,7 @@ private static int InstallPkg(string[] args) try { - using var package = SharpEmu.HLE.FileSystem.Pkg.PkgPackage.Open(pkgPath); + using var package = SharpEmu.HLE.FileSystem.Pkg.GamePackage.Open(pkgPath); if (!package.IsGameApplication) { Log.Error($"{Path.GetFileName(pkgPath)} is not a base game (category '{package.Category}'). Patches and DLC packages are not supported yet."); @@ -1025,7 +1025,7 @@ private static int InstallPkg(string[] args) : Path.Combine( Path.GetDirectoryName(pkgPath)!, package.GetFolderName(Path.GetFileNameWithoutExtension(pkgPath))); - Log.Info($"Installing {Path.GetFileName(pkgPath)} ({package.Header.ContentId}) into {destination}"); + Log.Info($"Installing {Path.GetFileName(pkgPath)} ({package.ContentId}) into {destination}"); var lastPercent = -1; var progress = new SynchronousProgress<SharpEmu.HLE.FileSystem.Pkg.PkgExtractProgress>(report => @@ -1056,7 +1056,7 @@ private sealed class SynchronousProgress<T>(Action<T> handler) : IProgress<T> private static void PrintUsage() { Log.Info("Usage: SharpEmu.CLI [--strict[=on|off]] [--trace-imports[=N]] [--cpu-engine=<native>] [--console=<ps5>] [--console-language=<language>] [--log-level=<level>] [--log-file[=<path>]] [--no-log-file] [--window-mode=<windowed|borderless|exclusive>] [--resolution=<WIDTHxHEIGHT>] [--display=<N>] [--refresh-rate=<HZ>] [--scaling=<fit|cover|stretch|integer>] [--vsync=<on|off>] [--hdr=<auto|on|off>] [--overlay=<on|off>] [--overlay-mode=<full|minimal|titlebar>] [--overlay-corner=<topleft|topright|bottomright|bottomleft>] [--debug-server[=host:port]] <path-to-eboot.bin|path-to-game.zar>"); - Log.Info("Install a fake PS4 package: SharpEmu.CLI --install-pkg <path-to-game.pkg> [destination-folder]"); + Log.Info("Install a fake PS4 or PS5 package: SharpEmu.CLI --install-pkg <path-to-game.pkg> [destination-folder]"); Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin"""); Log.Info("Debug server: --debug-server starts a live debug listener (default 127.0.0.1:5714); connect with SharpEmu.DebugClient."); } diff --git a/src/SharpEmu.GUI/Languages/ar.json b/src/SharpEmu.GUI/Languages/ar.json index c2a4a254d..1647cace0 100644 --- a/src/SharpEmu.GUI/Languages/ar.json +++ b/src/SharpEmu.GUI/Languages/ar.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "تثبيت", "Library.Pkg.ConfirmSkip": "ليس الآن", "Dialog.OpenPkg": "اختر ملف PKG لتثبيته", - "Dialog.PkgFiles": "حزم PS4", + "Dialog.PkgFiles": "حزم PS4/PS5", "Dialog.ChoosePkgInstallFolder": "اختر مكان تثبيت اللعبة", "Hero.GameSettings": "إعدادات اللعبة", "Hero.Console": "وحدة التحكم", diff --git a/src/SharpEmu.GUI/Languages/az.json b/src/SharpEmu.GUI/Languages/az.json index 881799123..b4cc864c4 100644 --- a/src/SharpEmu.GUI/Languages/az.json +++ b/src/SharpEmu.GUI/Languages/az.json @@ -55,7 +55,7 @@ "Library.Pkg.ConfirmInstall": "Quraşdır", "Library.Pkg.ConfirmSkip": "İndi yox", "Dialog.OpenPkg": "Quraşdırılacaq PKG-ni seçin", - "Dialog.PkgFiles": "PS4 paketləri", + "Dialog.PkgFiles": "PS4/PS5 paketləri", "Dialog.ChoosePkgInstallFolder": "Oyunun quraşdırılacağı yeri seçin", "Hero.GameSettings": "Oyun ayarları", "Hero.Console": "Konsol", diff --git a/src/SharpEmu.GUI/Languages/br.json b/src/SharpEmu.GUI/Languages/br.json index 8519aeb93..cec2aaa7d 100644 --- a/src/SharpEmu.GUI/Languages/br.json +++ b/src/SharpEmu.GUI/Languages/br.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Instalar", "Library.Pkg.ConfirmSkip": "Agora não", "Dialog.OpenPkg": "Escolha um PKG para instalar", - "Dialog.PkgFiles": "Pacotes de PS4", + "Dialog.PkgFiles": "Pacotes de PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Escolha onde instalar o jogo", "Hero.GameSettings": "Configurações do jogo", "Hero.Console": "Console", diff --git a/src/SharpEmu.GUI/Languages/de.json b/src/SharpEmu.GUI/Languages/de.json index a0c0f5d6d..9d5f426b1 100644 --- a/src/SharpEmu.GUI/Languages/de.json +++ b/src/SharpEmu.GUI/Languages/de.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Installieren", "Library.Pkg.ConfirmSkip": "Nicht jetzt", "Dialog.OpenPkg": "PKG zum Installieren auswählen", - "Dialog.PkgFiles": "PS4-Pakete", + "Dialog.PkgFiles": "PS4/PS5-Pakete", "Dialog.ChoosePkgInstallFolder": "Wähle, wo das Spiel installiert werden soll", "Hero.GameSettings": "Spieleinstellungen", "Hero.Console": "Konsole", diff --git a/src/SharpEmu.GUI/Languages/dk.json b/src/SharpEmu.GUI/Languages/dk.json index e9aaed451..20edb35d1 100644 --- a/src/SharpEmu.GUI/Languages/dk.json +++ b/src/SharpEmu.GUI/Languages/dk.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Installer", "Library.Pkg.ConfirmSkip": "Ikke nu", "Dialog.OpenPkg": "Vælg en PKG der skal installeres", - "Dialog.PkgFiles": "PS4-pakker", + "Dialog.PkgFiles": "PS4/PS5-pakker", "Dialog.ChoosePkgInstallFolder": "Vælg hvor spillet skal installeres", "Hero.GameSettings": "Spilindstillinger", "Hero.Console": "Konsol", diff --git a/src/SharpEmu.GUI/Languages/ee.json b/src/SharpEmu.GUI/Languages/ee.json index b12d89ee3..057fe0f41 100644 --- a/src/SharpEmu.GUI/Languages/ee.json +++ b/src/SharpEmu.GUI/Languages/ee.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Installi", "Library.Pkg.ConfirmSkip": "Mitte praegu", "Dialog.OpenPkg": "Vali installitav PKG", - "Dialog.PkgFiles": "PS4 paketid", + "Dialog.PkgFiles": "PS4/PS5 paketid", "Dialog.ChoosePkgInstallFolder": "Vali, kuhu mäng installida", "Hero.GameSettings": "Mängu seaded", "Hero.Console": "Konsool", diff --git a/src/SharpEmu.GUI/Languages/en.json b/src/SharpEmu.GUI/Languages/en.json index 3e06bdff7..5624d3b6e 100644 --- a/src/SharpEmu.GUI/Languages/en.json +++ b/src/SharpEmu.GUI/Languages/en.json @@ -70,7 +70,7 @@ "Library.Pkg.ConfirmInstall": "Install", "Library.Pkg.ConfirmSkip": "Not now", "Dialog.OpenPkg": "Choose a PKG to install", - "Dialog.PkgFiles": "PS4 packages", + "Dialog.PkgFiles": "PS4 and PS5 packages", "Dialog.ChoosePkgInstallFolder": "Choose where to install the game", "Hero.GameSettings": "Game settings", "Hero.Console": "Console", diff --git a/src/SharpEmu.GUI/Languages/es.json b/src/SharpEmu.GUI/Languages/es.json index 8fe293054..dca27e5f8 100644 --- a/src/SharpEmu.GUI/Languages/es.json +++ b/src/SharpEmu.GUI/Languages/es.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Instalar", "Library.Pkg.ConfirmSkip": "Ahora no", "Dialog.OpenPkg": "Elige un PKG para instalar", - "Dialog.PkgFiles": "Paquetes de PS4", + "Dialog.PkgFiles": "Paquetes de PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Elige dónde instalar el juego", "Hero.GameSettings": "Ajustes del juego", "Hero.Console": "Consola", diff --git a/src/SharpEmu.GUI/Languages/fr.json b/src/SharpEmu.GUI/Languages/fr.json index 6cb94938f..25e35ed0f 100644 --- a/src/SharpEmu.GUI/Languages/fr.json +++ b/src/SharpEmu.GUI/Languages/fr.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Installer", "Library.Pkg.ConfirmSkip": "Pas maintenant", "Dialog.OpenPkg": "Choisir un PKG à installer", - "Dialog.PkgFiles": "Paquets PS4", + "Dialog.PkgFiles": "Paquets PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Choisir où installer le jeu", "Hero.GameSettings": "Paramètres du jeu", "Hero.Console": "Console", diff --git a/src/SharpEmu.GUI/Languages/hu.json b/src/SharpEmu.GUI/Languages/hu.json index bc58905b9..4a6f2ef6f 100644 --- a/src/SharpEmu.GUI/Languages/hu.json +++ b/src/SharpEmu.GUI/Languages/hu.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Telepítés", "Library.Pkg.ConfirmSkip": "Most nem", "Dialog.OpenPkg": "Válassza ki a telepítendő PKG-t", - "Dialog.PkgFiles": "PS4-csomagok", + "Dialog.PkgFiles": "PS4/PS5-csomagok", "Dialog.ChoosePkgInstallFolder": "Válassza ki, hová települjön a játék", "Hero.GameSettings": "Játékbeállítások", "Hero.Console": "Konzol", diff --git a/src/SharpEmu.GUI/Languages/it.json b/src/SharpEmu.GUI/Languages/it.json index d52620838..38cfe5bee 100644 --- a/src/SharpEmu.GUI/Languages/it.json +++ b/src/SharpEmu.GUI/Languages/it.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Installa", "Library.Pkg.ConfirmSkip": "Non ora", "Dialog.OpenPkg": "Scegli un PKG da installare", - "Dialog.PkgFiles": "Pacchetti PS4", + "Dialog.PkgFiles": "Pacchetti PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Scegli dove installare il gioco", "Hero.GameSettings": "Impostazioni del gioco", "Hero.Console": "Console", diff --git a/src/SharpEmu.GUI/Languages/ja.json b/src/SharpEmu.GUI/Languages/ja.json index 509de7e93..14fefaa4c 100644 --- a/src/SharpEmu.GUI/Languages/ja.json +++ b/src/SharpEmu.GUI/Languages/ja.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "インストール", "Library.Pkg.ConfirmSkip": "今はしない", "Dialog.OpenPkg": "インストールする PKG を選択", - "Dialog.PkgFiles": "PS4 パッケージ", + "Dialog.PkgFiles": "PS4/PS5 パッケージ", "Dialog.ChoosePkgInstallFolder": "ゲームのインストール先を選択", "Hero.GameSettings": "ゲーム設定", "Hero.Console": "コンソール", diff --git a/src/SharpEmu.GUI/Languages/ko.json b/src/SharpEmu.GUI/Languages/ko.json index aef6daeed..7d29b2c0b 100644 --- a/src/SharpEmu.GUI/Languages/ko.json +++ b/src/SharpEmu.GUI/Languages/ko.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "설치", "Library.Pkg.ConfirmSkip": "나중에", "Dialog.OpenPkg": "설치할 PKG 선택", - "Dialog.PkgFiles": "PS4 패키지", + "Dialog.PkgFiles": "PS4/PS5 패키지", "Dialog.ChoosePkgInstallFolder": "게임을 설치할 위치 선택", "Hero.GameSettings": "게임 설정", "Hero.Console": "콘솔", diff --git a/src/SharpEmu.GUI/Languages/nl.json b/src/SharpEmu.GUI/Languages/nl.json index f3aa27dbc..d6f92a784 100644 --- a/src/SharpEmu.GUI/Languages/nl.json +++ b/src/SharpEmu.GUI/Languages/nl.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Installeren", "Library.Pkg.ConfirmSkip": "Niet nu", "Dialog.OpenPkg": "Kies een PKG om te installeren", - "Dialog.PkgFiles": "PS4-pakketten", + "Dialog.PkgFiles": "PS4/PS5-pakketten", "Dialog.ChoosePkgInstallFolder": "Kies waar de game moet worden geïnstalleerd", "Hero.GameSettings": "Game-instellingen", "Hero.Console": "Console", diff --git a/src/SharpEmu.GUI/Languages/pl.json b/src/SharpEmu.GUI/Languages/pl.json index a2267ac24..aab32feca 100644 --- a/src/SharpEmu.GUI/Languages/pl.json +++ b/src/SharpEmu.GUI/Languages/pl.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Zainstaluj", "Library.Pkg.ConfirmSkip": "Nie teraz", "Dialog.OpenPkg": "Wybierz PKG do zainstalowania", - "Dialog.PkgFiles": "Pakiety PS4", + "Dialog.PkgFiles": "Pakiety PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Wybierz, gdzie zainstalować grę", "Hero.GameSettings": "Ustawienia gry", "Hero.Console": "Konsola", diff --git a/src/SharpEmu.GUI/Languages/pt.json b/src/SharpEmu.GUI/Languages/pt.json index 223e86778..8fabbaf59 100644 --- a/src/SharpEmu.GUI/Languages/pt.json +++ b/src/SharpEmu.GUI/Languages/pt.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Instalar", "Library.Pkg.ConfirmSkip": "Agora não", "Dialog.OpenPkg": "Escolha um PKG para instalar", - "Dialog.PkgFiles": "Pacotes de PS4", + "Dialog.PkgFiles": "Pacotes de PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Escolha onde instalar o jogo", "Hero.GameSettings": "Definições do jogo", "Hero.Console": "Consola", diff --git a/src/SharpEmu.GUI/Languages/ru.json b/src/SharpEmu.GUI/Languages/ru.json index 42bd38cb4..1f12689eb 100644 --- a/src/SharpEmu.GUI/Languages/ru.json +++ b/src/SharpEmu.GUI/Languages/ru.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Установить", "Library.Pkg.ConfirmSkip": "Не сейчас", "Dialog.OpenPkg": "Выберите PKG для установки", - "Dialog.PkgFiles": "Пакеты PS4", + "Dialog.PkgFiles": "Пакеты PS4/PS5", "Dialog.ChoosePkgInstallFolder": "Выберите, куда установить игру", "Hero.GameSettings": "Настройки игры", "Hero.Console": "Консоль", diff --git a/src/SharpEmu.GUI/Languages/tr.json b/src/SharpEmu.GUI/Languages/tr.json index a40cbd347..5555d42b9 100644 --- a/src/SharpEmu.GUI/Languages/tr.json +++ b/src/SharpEmu.GUI/Languages/tr.json @@ -71,7 +71,7 @@ "Library.Pkg.ConfirmInstall": "Yükle", "Library.Pkg.ConfirmSkip": "Şimdi değil", "Dialog.OpenPkg": "Yüklenecek PKG'yi seç", - "Dialog.PkgFiles": "PS4 paketleri", + "Dialog.PkgFiles": "PS4/PS5 paketleri", "Dialog.ChoosePkgInstallFolder": "Oyunun yükleneceği yeri seç", "Hero.GameSettings": "Oyun ayarları", "Hero.Console": "Konsol", diff --git a/src/SharpEmu.GUI/Languages/zh.json b/src/SharpEmu.GUI/Languages/zh.json index a3b878f6b..1ee11582c 100644 --- a/src/SharpEmu.GUI/Languages/zh.json +++ b/src/SharpEmu.GUI/Languages/zh.json @@ -70,7 +70,7 @@ "Library.Pkg.ConfirmInstall": "安装", "Library.Pkg.ConfirmSkip": "暂不", "Dialog.OpenPkg": "选择要安装的 PKG", - "Dialog.PkgFiles": "PS4 包", + "Dialog.PkgFiles": "PS4/PS5 包", "Dialog.ChoosePkgInstallFolder": "选择游戏的安装位置", "Hero.GameSettings": "游戏设置", "Hero.Console": "控制台", diff --git a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs index 4bf3f9e40..edaa5e0d6 100644 --- a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs +++ b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs @@ -214,7 +214,7 @@ await Task.Run(() => { try { - using var package = PkgPackage.Open(pkgPath); + using var package = GamePackage.Open(pkgPath); neededBytes += package.GetInstalledSize(); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException) @@ -289,7 +289,7 @@ private bool TryReadPackageInfo(string pkgPath, out string titleId, out string f { try { - using var package = PkgPackage.Open(pkgPath); + using var package = GamePackage.Open(pkgPath); titleId = package.TitleId; folderName = package.GetFolderName(Path.GetFileNameWithoutExtension(pkgPath)); category = package.Category; diff --git a/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs b/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs index 881fbc82d..def9f74c5 100644 --- a/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs +++ b/src/SharpEmu.GUI/PkgInstallDialog.axaml.cs @@ -85,7 +85,7 @@ private async Task InstallAsync() { await Task.Run(() => { - using var package = PkgPackage.Open(_pkgPath); + using var package = GamePackage.Open(_pkgPath); package.Extract(_destination, progress, _cancellation.Token); }); _succeeded = true; diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs new file mode 100644 index 000000000..7a9a5e4fa --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs @@ -0,0 +1,56 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// Picks the reader for a .pkg file from its magic: "\x7FCNT" is a PS4 package, "\x7FFIH" a PS5 one. +public static class GamePackage +{ + private static ReadOnlySpan<byte> CntMagic => [0x7F, 0x43, 0x4E, 0x54]; + + private static ReadOnlySpan<byte> FihMagic => [0x7F, 0x46, 0x49, 0x48]; + + public static IGamePackage Open(string path) + { + Span<byte> magic = stackalloc byte[4]; + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + if (stream.Read(magic) != 4) + { + throw new InvalidDataException("This file is too short to be a PKG package."); + } + } + + if (magic.SequenceEqual(CntMagic)) + { + return PkgPackage.Open(path); + } + + if (magic.SequenceEqual(FihMagic)) + { + return Ps5Package.Open(path); + } + + throw new InvalidDataException("Not a PS4 or PS5 package (unknown magic)."); + } + + // True for a readable .pkg file with either known magic. + public static bool IsPackagePath(string path) + { + if (!string.Equals(Path.GetExtension(path), ".pkg", StringComparison.OrdinalIgnoreCase) || !File.Exists(path)) + { + return false; + } + + try + { + Span<byte> magic = stackalloc byte[4]; + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + return stream.Read(magic) == 4 && (magic.SequenceEqual(CntMagic) || magic.SequenceEqual(FihMagic)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/IGamePackage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/IGamePackage.cs new file mode 100644 index 000000000..f60b85140 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/IGamePackage.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// What callers need from an installable package, whatever its format (PS4 CNT or PS5 FIH). +public interface IGamePackage : IDisposable +{ + string ContentId { get; } + + string TitleId { get; } + + // The game's name, or null when the package does not carry one. + string? Title { get; } + + // Package category when the format exposes one (PS4: param.sfo CATEGORY), else null. + string? Category { get; } + + // Base games are installable; patches and DLC are not. A package without a category counts as a game. + bool IsGameApplication { get; } + + // Folder name for an install: the title made safe for a file name, else the title id, else `fallback`. + string GetFolderName(string fallback); + + // Bytes on disk that Extract writes. + long GetInstalledSize(); + + // Writes the game folder (eboot.bin at its root) into `destination`. Throws IOException before + // writing anything when the drive is known to be too small. + void Extract(string destination, IProgress<PkgExtractProgress>? progress = null, CancellationToken cancellation = default); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Kraken.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Kraken.cs new file mode 100644 index 000000000..50c16c6f2 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Kraken.cs @@ -0,0 +1,1616 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Ported from pkg-to-anyps5 (src/kraken.rs), which follows PS5PCEM (src/pkg/kraken.zig) and the +// managed decoder of LibProsperoPKG. All three are GPL-3.0-or-later. + +using System.Buffers.Binary; +using System.Numerics; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// Kraken (Oodle newLZ) decoder for the header-stripped blocks of a PS5 inner image. A 256 KiB block +// is one or two 128 KiB chunks with no Oodle block headers; the NAPS record gives the codec flags +// and the compressed length of the first chunk. Supported entropy types: memcpy and Huffman (2- and +// 4-way). tANS, RLE and recursive entropy blocks throw instead of guessing. Every access is bounds +// checked: corrupt input throws InvalidDataException. +internal static class Kraken +{ + private const int ChunkMax = 0x20000; + private const int SeedSize = 8; + private const uint Chunk0SubLit = 0x01; + private const uint Chunk0NewLz = 0x02; + private const uint Chunk1SubLit = 0x10; + private const uint Chunk1NewLz = 0x20; + private const uint Chunk1Restart = 0x40; + + private static readonly uint[] CodePrefixOrg = [0x0, 0x0, 0x2, 0x6, 0xE, 0x1E, 0x3E, 0x7E, 0xFE, 0x1FE, 0x2FE, 0x3FE]; + + private static InvalidDataException Malformed() => new("Malformed Kraken data."); + + private static uint Shl(uint v, long n) => n is >= 0 and < 32 ? v << (int)n : 0; + + private static uint Shr(uint v, long n) => n is >= 0 and < 32 ? v >> (int)n : 0; + + // Decodes one stored block into `dst` (exactly its uncompressed size). + public static void DecodeBlock(ReadOnlySpan<byte> payload, uint flags, uint firstChunkComp, Span<byte> dst) + { + if (dst.IsEmpty) + { + if (!payload.IsEmpty) + { + throw Malformed(); + } + + return; + } + + var oneChunk = firstChunkComp == 0 || firstChunkComp >= payload.Length || dst.Length <= ChunkMax; + if (oneChunk) + { + DecodeSubChunk(payload, dst, 0, dst.Length, (flags & Chunk0NewLz) != 0, true, SubLit(flags, Chunk0SubLit)); + return; + } + + var chunk0Dst = Math.Min(dst.Length, ChunkMax); + var chunk1Dst = dst.Length - chunk0Dst; + var chunk0Comp = (int)firstChunkComp; + var chunk1Comp = payload.Length - chunk0Comp; + if (chunk1Dst == 0 && chunk1Comp != 0) + { + throw Malformed(); + } + + DecodeSubChunk(payload[..chunk0Comp], dst, 0, chunk0Dst, (flags & Chunk0NewLz) != 0, true, SubLit(flags, Chunk0SubLit)); + if (chunk1Dst > 0) + { + DecodeSubChunk( + payload[chunk0Comp..], + dst, + chunk0Dst, + chunk1Dst, + (flags & Chunk1NewLz) != 0, + (flags & Chunk1Restart) != 0, + SubLit(flags, Chunk1SubLit)); + } + } + + private static int SubLit(uint flags, uint bit) => (flags & bit) != 0 ? 0 : 1; + + private static void DecodeSubChunk(ReadOnlySpan<byte> src, Span<byte> dst, int dstStart, int dstLen, bool lz, bool restart, int literalMode) + { + if (dstStart + dstLen > dst.Length) + { + throw Malformed(); + } + + if (src.Length == dstLen) + { + src.CopyTo(dst.Slice(dstStart, dstLen)); + return; + } + + if (lz) + { + DecodeChunk(src, dst, dstStart, dstLen, restart, literalMode); + return; + } + + var (used, decoded) = DecodeBytes(src, dstLen); + if (used != src.Length || decoded.Length != dstLen) + { + throw Malformed(); + } + + decoded.CopyTo(dst.Slice(dstStart, dstLen)); + } + + private sealed class LzTable + { + public byte[] Lit = []; + public byte[] Cmd = []; + public int[] Offs = []; + public int[] Lens = []; + } + + private static void DecodeChunk(ReadOnlySpan<byte> src, Span<byte> dst, int dstStart, int dstLen, bool withSeed, int literalMode) + { + var sp = 0; + if (withSeed) + { + if (src.Length < SeedSize || dstLen < SeedSize) + { + throw Malformed(); + } + + src[..SeedSize].CopyTo(dst.Slice(dstStart, SeedSize)); + sp = SeedSize; + } + + var table = ReadLzTable(src, ref sp, dstLen); + var start = dstStart + (withSeed ? SeedSize : 0); + var end = dstStart + dstLen; + var ok = literalMode switch + { + 1 => ProcessType1(table, dst, start, end), + 0 => ProcessType0(table, dst, start, end), + _ => false, + }; + if (!ok) + { + throw Malformed(); + } + } + + private static ReadOnlySpan<byte> Region(ReadOnlySpan<byte> src, int sp, int srcEnd) => + sp >= 0 && sp <= srcEnd && srcEnd <= src.Length ? src[sp..srcEnd] : throw Malformed(); + + private static LzTable ReadLzTable(ReadOnlySpan<byte> src, ref int sp, int dstSize) + { + var srcEnd = src.Length; + var excessFlag = false; + var excessCount = 0; + if (sp < srcEnd && (src[sp] & 0x80) != 0) + { + var flag = src[sp]; + if ((flag & 0xC0) == 0x80) + { + sp++; + excessFlag = true; + excessCount = flag & 0x3F; + if (excessCount > 0x1F) + { + if (sp >= srcEnd) + { + throw Malformed(); + } + + excessCount += src[sp] * 0x20; + sp++; + } + + if (srcEnd < sp + excessCount) + { + throw Malformed(); + } + + srcEnd -= excessCount; + } + } + + var table = new LzTable(); + var (used, lit) = DecodeBytes(Region(src, sp, srcEnd), dstSize); + sp += used; + table.Lit = lit; + (used, var cmd) = DecodeBytes(Region(src, sp, srcEnd), dstSize); + sp += used; + table.Cmd = cmd; + + if (srcEnd - sp < 3) + { + throw Malformed(); + } + + var offsScaling = 0; + byte[] packedExtra = []; + byte[] packedOffs; + if ((src[sp] & 0x80) != 0) + { + offsScaling = src[sp] - 127; + sp++; + (used, packedOffs) = DecodeBytes(Region(src, sp, srcEnd), table.Cmd.Length); + sp += used; + if (offsScaling != 1) + { + (used, packedExtra) = DecodeBytes(Region(src, sp, srcEnd), packedOffs.Length); + if (packedExtra.Length != packedOffs.Length) + { + throw Malformed(); + } + + sp += used; + } + } + else + { + (used, packedOffs) = DecodeBytes(Region(src, sp, srcEnd), table.Cmd.Length); + sp += used; + } + + (used, var packedLen) = DecodeBytes(Region(src, sp, srcEnd), dstSize >> 2); + sp += used; + + table.Offs = new int[packedOffs.Length]; + table.Lens = new int[packedLen.Length]; + var ok = UnpackOffsets(src, sp, srcEnd, excessFlag, excessCount, packedOffs, offsScaling, packedExtra, packedLen, table.Offs, table.Lens); + return ok ? table : throw Malformed(); + } + + // Internal so the tests can pin down the excess-framing edge case. + internal static bool UnpackOffsets( + ReadOnlySpan<byte> src, + int bsBegin, + int bsEnd, + bool excessFlag, + int excessCount, + byte[] packedOffs, + int offsScaling, + byte[] packedExtra, + byte[] packedLen, + int[] offsOut, + int[] lenOut) + { + if (bsBegin < 0 || bsBegin > bsEnd) + { + return false; + } + + var a = BitReader.Forward(src, bsBegin, bsEnd); + var b = BitReader.Backward(src, bsBegin, bsEnd); + long u32Len; + if (!excessFlag) + { + if (b.Bits < 0x2000) + { + return false; + } + + var nn = 31 - Bsr(b.Bits); + b.BitPos += (int)nn; + b.Bits = Shl(b.Bits, nn); + b.Refill(); + nn++; + u32Len = Shr(b.Bits, 32 - nn) - 1u; + b.BitPos += (int)nn; + b.Bits = Shl(b.Bits, nn); + b.Refill(); + } + else + { + u32Len = 0; + foreach (var v in packedLen) + { + if (v == 255) + { + u32Len++; + } + } + } + + if (u32Len > 512) + { + return false; + } + + if (offsScaling == 0) + { + var i = 0; + while (i < packedOffs.Length) + { + offsOut[i] = -(int)a.ReadDistance(packedOffs[i]); + i++; + if (i >= packedOffs.Length) + { + break; + } + + offsOut[i] = -(int)b.ReadDistance(packedOffs[i]); + i++; + } + } + else + { + var i = 0; + while (i < packedOffs.Length) + { + uint cmd = packedOffs[i]; + if ((cmd >> 3) > 26) + { + return false; + } + + var off = ((8 + (cmd & 7)) << (int)(cmd >> 3)) | a.ReadMoreThan24(cmd >> 3); + offsOut[i] = 8 - (int)off; + i++; + if (i >= packedOffs.Length) + { + break; + } + + uint cmd2 = packedOffs[i]; + if ((cmd2 >> 3) > 26) + { + return false; + } + + var off2 = ((8 + (cmd2 & 7)) << (int)(cmd2 >> 3)) | b.ReadMoreThan24(cmd2 >> 3); + offsOut[i] = 8 - (int)off2; + i++; + } + + if (offsScaling != 1) + { + if (packedExtra.Length != packedOffs.Length) + { + return false; + } + + for (var k = 0; k < offsOut.Length; k++) + { + offsOut[k] = (sbyte)packedExtra[k] - offsOut[k] * offsScaling; + } + } + } + + var u32s = new uint[512]; + if (u32Len > 0) + { + BitReader ra; + BitReader rb; + if (excessFlag) + { + ra = BitReader.Forward(src, bsEnd, bsEnd + excessCount); + rb = BitReader.Backward(src, bsEnd, bsEnd + excessCount); + } + else + { + ra = a; + rb = b; + } + + var i = 0; + while (i + 1 < u32Len) + { + if (!ra.ReadLength(out u32s[i]) || !rb.ReadLength(out u32s[i + 1])) + { + return false; + } + + i += 2; + } + + if (i < u32Len && !ra.ReadLength(out u32s[i])) + { + return false; + } + } + + long u = 0; + for (var i = 0; i < packedLen.Length; i++) + { + uint v = packedLen[i]; + if (v == 255) + { + if (u >= u32Len) + { + return false; + } + + v = u32s[u] + 255; + u++; + } + + lenOut[i] = (int)(v + 3); + } + + return u == u32Len; + } + + private static int RecentAt(int[] values, int index) => index < values.Length ? values[index] : 0; + + private static bool ProcessType1(LzTable t, Span<byte> dst, int start, int dstEnd) + { + int cmdI = 0, lenI = 0, litI = 0, offsI = 0; + var dstPos = start; + Span<int> recent = [0, 0, 0, -8, -8, -8, 0]; + while (cmdI < t.Cmd.Length) + { + int f = t.Cmd[cmdI++]; + var litLen = f & 3; + var offsIndex = f >> 6; + var matchLen = (f >> 2) & 0xF; + if (litLen == 3) + { + if (lenI >= t.Lens.Length || t.Lens[lenI] < 0) + { + return false; + } + + litLen = t.Lens[lenI++]; + } + + recent[6] = RecentAt(t.Offs, offsI); + if (litLen != 0) + { + if (litI + litLen > t.Lit.Length || dstPos + litLen > dstEnd) + { + return false; + } + + t.Lit.AsSpan(litI, litLen).CopyTo(dst.Slice(dstPos, litLen)); + dstPos += litLen; + litI += litLen; + } + + var offset = recent[offsIndex + 3]; + recent[offsIndex + 3] = recent[offsIndex + 2]; + recent[offsIndex + 2] = recent[offsIndex + 1]; + recent[offsIndex + 1] = recent[offsIndex]; + recent[3] = offset; + offsI += ((offsIndex + 1) & 4) >> 2; + var from = (long)dstPos + offset; + // A match copies bytes already written in this block. + if (from < 0 || from >= dstPos) + { + return false; + } + + int actual; + if (matchLen != 15) + { + actual = matchLen + 2; + } + else + { + if (lenI >= t.Lens.Length || t.Lens[lenI] < 0) + { + return false; + } + + actual = 14 + t.Lens[lenI++]; + if (actual < 0) + { + return false; + } + } + + if (dstPos + actual > dstEnd || from + actual > dst.Length) + { + return false; + } + + CopyMatch(dst, (int)from, dstPos, actual); + dstPos += actual; + } + + if (offsI != t.Offs.Length || lenI != t.Lens.Length) + { + return false; + } + + var finalLen = dstEnd - dstPos; + if (finalLen != t.Lit.Length - litI) + { + return false; + } + + t.Lit.AsSpan(litI).CopyTo(dst.Slice(dstPos, finalLen)); + return true; + } + + private static void DeltaLiterals(Span<byte> dst, int at, ReadOnlySpan<byte> lit, int lastOffset) + { + for (var c = 0; c < lit.Length; c++) + { + var back = (long)at + c + lastOffset; + var prev = back >= 0 && back < dst.Length ? dst[(int)back] : (byte)0; + dst[at + c] = (byte)(lit[c] + prev); + } + } + + private static bool ProcessType0(LzTable t, Span<byte> dst, int start, int dstEnd) + { + int cmdI = 0, lenI = 0, litI = 0, offsI = 0; + var dstPos = start; + Span<int> recent = [0, 0, 0, -8, -8, -8, 0]; + var lastOffset = -8; + while (cmdI < t.Cmd.Length) + { + int f = t.Cmd[cmdI++]; + var litLen = f & 3; + var offsIndex = f >> 6; + var matchLen = (f >> 2) & 0xF; + if (litLen == 3) + { + if (lenI >= t.Lens.Length || t.Lens[lenI] < 0) + { + return false; + } + + litLen = t.Lens[lenI++]; + } + + recent[6] = RecentAt(t.Offs, offsI); + if (litLen != 0) + { + if (litI + litLen > t.Lit.Length || dstPos + litLen > dstEnd) + { + return false; + } + + DeltaLiterals(dst, dstPos, t.Lit.AsSpan(litI, litLen), lastOffset); + dstPos += litLen; + litI += litLen; + } + + var offset = recent[offsIndex + 3]; + recent[offsIndex + 3] = recent[offsIndex + 2]; + recent[offsIndex + 2] = recent[offsIndex + 1]; + recent[offsIndex + 1] = recent[offsIndex]; + recent[3] = offset; + lastOffset = offset; + offsI += ((offsIndex + 1) & 4) >> 2; + int actual; + if (matchLen != 15) + { + actual = matchLen + 2; + } + else + { + if (lenI >= t.Lens.Length || t.Lens[lenI] < 0) + { + return false; + } + + actual = 14 + t.Lens[lenI++]; + if (actual < 0) + { + return false; + } + } + + if (dstPos + actual > dstEnd) + { + return false; + } + + var from = (long)dstPos + offset; + // A match copies bytes already written in this block; one before the start or at or + // after the cursor is corrupt data. + if (from < 0 || from >= dstPos) + { + return false; + } + + CopyMatch(dst, (int)from, dstPos, actual); + dstPos += actual; + } + + if (offsI != t.Offs.Length || lenI != t.Lens.Length) + { + return false; + } + + // The remaining literals fill the block exactly; a short stream would leave stale bytes + // from the previous block in the reused buffer. + var rest = t.Lit.AsSpan(litI); + if (dstPos + rest.Length != dstEnd) + { + return false; + } + + DeltaLiterals(dst, dstPos, rest, lastOffset); + return true; + } + + // Byte by byte so overlapping matches repeat their pattern. + private static void CopyMatch(Span<byte> dst, int from, int to, int len) + { + for (var c = 0; c < len; c++) + { + dst[to + c] = dst[from + c]; + } + } + + // Decodes one entropy-coded byte array. Returns the bytes consumed from `src` and the output. + internal static (int Used, byte[] Data) DecodeBytes(ReadOnlySpan<byte> src, int outputCap) + { + if (src.Length < 2) + { + throw Malformed(); + } + + var chunkType = (src[0] >> 4) & 7; + if (chunkType == 0) + { + int size, sp; + if (src[0] >= 0x80) + { + size = ((src[0] << 8) | src[1]) & 0xFFF; + sp = 2; + } + else + { + if (src.Length < 3) + { + throw Malformed(); + } + + size = (src[0] << 16) | (src[1] << 8) | src[2]; + if ((size & ~0x3FFFF) != 0) + { + throw Malformed(); + } + + sp = 3; + } + + if (size > outputCap || src.Length - sp < size) + { + throw Malformed(); + } + + return (sp + size, src.Slice(sp, size).ToArray()); + } + + int srcSize, dstSize, headerSize; + if (src[0] >= 0x80) + { + if (src.Length < 3) + { + throw Malformed(); + } + + var bits = ((uint)src[0] << 16) | ((uint)src[1] << 8) | src[2]; + srcSize = (int)(bits & 0x3FF); + dstSize = srcSize + (int)((bits >> 10) & 0x3FF) + 1; + headerSize = 3; + } + else + { + if (src.Length < 5) + { + throw Malformed(); + } + + var bits = BinaryPrimitives.ReadUInt32BigEndian(src[1..]); + srcSize = (int)(bits & 0x3FFFF); + dstSize = (int)((((bits >> 18) | ((uint)src[0] << 14)) & 0x3FFFF) + 1); + if (srcSize >= dstSize) + { + throw Malformed(); + } + + headerSize = 5; + } + + if (src.Length - headerSize < srcSize || dstSize > outputCap) + { + throw Malformed(); + } + + var output = new byte[dstSize]; + switch (chunkType) + { + case 2: + case 4: + if (!DecodeHuff(src.Slice(headerSize, srcSize), output, chunkType >> 1)) + { + throw Malformed(); + } + + break; + default: + throw new InvalidDataException($"Unsupported Kraken entropy type {chunkType}."); + } + + return (headerSize + srcSize, output); + } + + private sealed class HuffLut + { + public readonly byte[] Bits2Len = new byte[2048 + 16]; + public readonly byte[] Bits2Sym = new byte[2048 + 16]; + } + + private static bool DecodeHuff(ReadOnlySpan<byte> src, byte[] output, int typeDiv) + { + var prefix = (uint[])CodePrefixOrg.Clone(); + var syms = new byte[1280]; + var bits = BitReader.Forward(src, 0, src.Length); + int numSyms; + if (bits.ReadBitNoRefill() == 0) + { + numSyms = HuffReadCodeLengthsOld(ref bits, syms, prefix); + } + else if (bits.ReadBitNoRefill() == 0) + { + numSyms = HuffReadCodeLengthsNew(ref bits, syms, prefix); + } + else + { + return false; + } + + if (numSyms < 1) + { + return false; + } + + var adj = (24 - bits.BitPos) / 8; + long spLong = bits.P - adj; + if (numSyms == 1) + { + Array.Fill(output, syms[0]); + return true; + } + + if (spLong < 0 || spLong > src.Length) + { + return false; + } + + var sp = (int)spLong; + var lut = new HuffLut(); + if (!HuffMakeLut(prefix, lut, syms)) + { + return false; + } + + var rev = new HuffLut(); + for (var i = 0; i < 2048; i++) + { + var r = Reverse11((uint)i); + rev.Bits2Len[i] = lut.Bits2Len[r]; + rev.Bits2Sym[i] = lut.Bits2Sym[r]; + } + + if (typeDiv == 1) + { + if (sp + 3 > src.Length) + { + return false; + } + + var splitMid1 = src[sp] | (src[sp + 1] << 8); + sp += 2; + return DecodeBytesCore(src, output, 0, output.Length, sp, src.Length, sp + splitMid1, rev); + } + + if (sp + 6 > src.Length) + { + return false; + } + + var half = (output.Length + 1) >> 1; + var splitMid = src[sp] | (src[sp + 1] << 8) | (src[sp + 2] << 16); + sp += 3; + if (splitMid > src.Length - sp) + { + return false; + } + + var srcMid = sp + splitMid; + var splitLeft = src[sp] | (src[sp + 1] << 8); + sp += 2; + if (srcMid < sp || srcMid - sp < splitLeft + 2 || src.Length - srcMid < 3) + { + return false; + } + + var splitRight = src[srcMid] | (src[srcMid + 1] << 8); + if (src.Length - (srcMid + 2) < splitRight + 2) + { + return false; + } + + return DecodeBytesCore(src, output, 0, half, sp, srcMid, sp + splitLeft, rev) + && DecodeBytesCore(src, output, half, output.Length, srcMid + 2, src.Length, srcMid + 2 + splitRight, rev); + } + + private static bool HuffMakeLut(uint[] prefixCur, HuffLut lut, byte[] syms) + { + var currSlot = 0; + for (var i = 1; i < 11; i++) + { + var start = (int)CodePrefixOrg[i]; + var count = (int)(prefixCur[i] - CodePrefixOrg[i]); + if (count == 0) + { + continue; + } + + var stepSize = 1 << (11 - i); + var numToSet = count << (11 - i); + if (currSlot + numToSet > 2048) + { + return false; + } + + Array.Fill(lut.Bits2Len, (byte)i, currSlot, numToSet); + var p = currSlot; + for (var j = 0; j < count; j++) + { + Array.Fill(lut.Bits2Sym, syms[start + j], p, stepSize); + p += stepSize; + } + + currSlot += numToSet; + } + + var numToSet11 = (int)(prefixCur[11] - CodePrefixOrg[11]); + if (numToSet11 != 0) + { + if (currSlot + numToSet11 > 2048) + { + return false; + } + + var start = (int)CodePrefixOrg[11]; + Array.Fill(lut.Bits2Len, (byte)11, currSlot, numToSet11); + Array.Copy(syms, start, lut.Bits2Sym, currSlot, numToSet11); + currSlot += numToSet11; + } + + return currSlot == 2048; + } + + private static int Reverse11(uint v) + { + uint r = 0; + for (var i = 0; i < 11; i++) + { + r = (r << 1) | (v & 1); + v >>= 1; + } + + return (int)r; + } + + private static int HuffReadCodeLengthsOld(ref BitReader bits, byte[] syms, uint[] codePrefix) + { + if (bits.ReadBitNoRefill() != 0) + { + var sym = 0; + var numSymbols = 0; + var avg = 32; + var forced = (int)bits.ReadBitsNoRefill(2); + var thres = 1u << (31 - (int)(20u >> forced)); + var skip = bits.ReadBit() != 0; + while (true) + { + if (!skip) + { + if ((bits.Bits & 0xFF00_0000) == 0) + { + return -1; + } + + sym += (int)bits.ReadBitsNoRefill(2 * (Clz(bits.Bits) + 1)) - 2 + 1; + if (sym >= 256) + { + break; + } + } + + skip = false; + bits.Refill(); + if ((bits.Bits & 0xFF00_0000) == 0) + { + return -1; + } + + var n = (int)bits.ReadBitsNoRefill(2 * (Clz(bits.Bits) + 1)) - 2 + 1; + if (sym + n > 256) + { + return -1; + } + + bits.Refill(); + numSymbols += n; + while (n != 0) + { + n--; + if (bits.Bits < thres) + { + return -1; + } + + var lz = Clz(bits.Bits); + var v = (int)bits.ReadBitsNoRefill(lz + (uint)forced + 1); + var vv = v + (((int)lz - 1) << forced); + var codeLen = (-(vv & 1) ^ (vv >> 1)) + ((avg + 2) >> 2); + if (codeLen is < 1 or > 11) + { + return -1; + } + + avg = codeLen + ((3 * avg + 2) >> 2); + bits.Refill(); + var cp = codePrefix[codeLen]; + codePrefix[codeLen] = cp + 1; + if (cp >= syms.Length) + { + return -1; + } + + syms[cp] = (byte)sym; + sym++; + } + + if (sym == 256) + { + break; + } + } + + return sym == 256 && numSymbols >= 2 ? numSymbols : -1; + } + + var count = (int)bits.ReadBitsNoRefill(8); + if (count == 0) + { + return -1; + } + + if (count == 1) + { + syms[0] = (byte)bits.ReadBitsNoRefill(8); + } + else + { + var codeLenBits = bits.ReadBitsNoRefill(3); + if (codeLenBits > 4) + { + return -1; + } + + for (var i = 0; i < count; i++) + { + bits.Refill(); + var sym = bits.ReadBitsNoRefill(8); + var codeLen = (int)bits.ReadBitsNoRefillZero(codeLenBits) + 1; + if (codeLen > 11) + { + return -1; + } + + var cp = codePrefix[codeLen]; + codePrefix[codeLen] = cp + 1; + if (cp >= syms.Length) + { + return -1; + } + + syms[cp] = (byte)sym; + } + } + + return count; + } + + private static int HuffReadCodeLengthsNew(ref BitReader bits, byte[] syms, uint[] codePrefix) + { + var forcedBits = (int)bits.ReadBitsNoRefill(2); + var numSymbols = (int)bits.ReadBitsNoRefill(8) + 1; + var fluff = bits.ReadFluff(numSymbols); + var codeLen = new byte[512 + 16]; + var adj = (24 - bits.BitPos + 7) >> 3; + var br2 = new BitReader2 { P = bits.P - adj, PEnd = bits.Bound, BitPos = (bits.BitPos - 24) & 7 }; + if (!DecodeGolombRiceLengths(bits.B, codeLen, numSymbols + fluff, ref br2)) + { + return -1; + } + + if (!DecodeGolombRiceBits(bits.B, codeLen, numSymbols, forcedBits, ref br2)) + { + return -1; + } + + bits.BitPos = 24; + bits.P = br2.P; + bits.Bits = 0; + bits.Refill(); + bits.Bits = Shl(bits.Bits, br2.BitPos); + bits.BitPos += br2.BitPos; + + uint runningSum = 0x1e; + for (var i = 0; i < numSymbols; i++) + { + int v = codeLen[i]; + v = -(v & 1) ^ (v >> 1); + var cl = v + (int)(runningSum >> 2) + 1; + if (cl is < 1 or > 11) + { + return -1; + } + + codeLen[i] = (byte)cl; + runningSum = (uint)((int)runningSum + v); + } + + var ranges = new (int Sym, int Count)[128]; + var nRanges = HuffConvertToRanges(ranges, numSymbols, fluff, codeLen, numSymbols, ref bits); + if (nRanges <= 0) + { + return -1; + } + + var cp = 0; + for (var r = 0; r < nRanges; r++) + { + var (sym, nn) = ranges[r]; + while (nn != 0) + { + nn--; + var clen = codeLen[cp++]; + var slot = codePrefix[clen]; + codePrefix[clen] = slot + 1; + if (slot >= syms.Length) + { + return -1; + } + + syms[slot] = (byte)sym; + sym++; + } + } + + return numSymbols; + } + + private static int HuffConvertToRanges( + (int Sym, int Count)[] range, + int numSymbols, + int p, + byte[] symLen, + int start, + ref BitReader bits) + { + var numRanges = p >> 1; + var symIdx = 0; + var off = start; + if ((p & 1) != 0) + { + bits.Refill(); + int v = symLen[off++]; + if (v >= 8) + { + return -1; + } + + var n = (uint)(v + 1); + symIdx = (int)(bits.ReadBitsNoRefill(n) + (1u << (int)n) - 1); + } + + if (numRanges >= range.Length) + { + return -1; + } + + var symsUsed = 0; + for (var i = 0; i < numRanges; i++) + { + bits.Refill(); + uint v = symLen[off]; + if (v >= 9) + { + return -1; + } + + var num = (int)(bits.ReadBitsNoRefillZero(v) + (1u << (int)v)); + uint v2 = symLen[off + 1]; + if (v2 >= 8) + { + return -1; + } + + var space = (int)(bits.ReadBitsNoRefill(v2 + 1) + (1u << (int)(v2 + 1)) - 1); + range[i] = (symIdx, num); + symsUsed += num; + symIdx += num + space; + off += 2; + } + + if (symIdx >= 256 || symsUsed >= numSymbols || symIdx + numSymbols - symsUsed > 256) + { + return -1; + } + + range[numRanges] = (symIdx, numSymbols - symsUsed); + return numRanges + 1; + } + + private struct BitReader2 + { + public int P; + public int PEnd; + public int BitPos; + } + + private static readonly uint[] RiceVal = + [ + 0x80000000, 0x00000007, 0x10000006, 0x00000006, 0x20000005, 0x00000105, 0x10000005, 0x00000005, 0x30000004, 0x00000204, 0x10000104, + 0x00000104, 0x20000004, 0x00010004, 0x10000004, 0x00000004, 0x40000003, 0x00000303, 0x10000203, 0x00000203, 0x20000103, 0x00010103, + 0x10000103, 0x00000103, 0x30000003, 0x00020003, 0x10010003, 0x00010003, 0x20000003, 0x01000003, 0x10000003, 0x00000003, 0x50000002, + 0x00000402, 0x10000302, 0x00000302, 0x20000202, 0x00010202, 0x10000202, 0x00000202, 0x30000102, 0x00020102, 0x10010102, 0x00010102, + 0x20000102, 0x01000102, 0x10000102, 0x00000102, 0x40000002, 0x00030002, 0x10020002, 0x00020002, 0x20010002, 0x01010002, 0x10010002, + 0x00010002, 0x30000002, 0x02000002, 0x11000002, 0x01000002, 0x20000002, 0x00000012, 0x10000002, 0x00000002, 0x60000001, 0x00000501, + 0x10000401, 0x00000401, 0x20000301, 0x00010301, 0x10000301, 0x00000301, 0x30000201, 0x00020201, 0x10010201, 0x00010201, 0x20000201, + 0x01000201, 0x10000201, 0x00000201, 0x40000101, 0x00030101, 0x10020101, 0x00020101, 0x20010101, 0x01010101, 0x10010101, 0x00010101, + 0x30000101, 0x02000101, 0x11000101, 0x01000101, 0x20000101, 0x00000111, 0x10000101, 0x00000101, 0x50000001, 0x00040001, 0x10030001, + 0x00030001, 0x20020001, 0x01020001, 0x10020001, 0x00020001, 0x30010001, 0x02010001, 0x11010001, 0x01010001, 0x20010001, 0x00010011, + 0x10010001, 0x00010001, 0x40000001, 0x03000001, 0x12000001, 0x02000001, 0x21000001, 0x01000011, 0x11000001, 0x01000001, 0x30000001, + 0x00000021, 0x10000011, 0x00000011, 0x20000001, 0x00001001, 0x10000001, 0x00000001, 0x70000000, 0x00000600, 0x10000500, 0x00000500, + 0x20000400, 0x00010400, 0x10000400, 0x00000400, 0x30000300, 0x00020300, 0x10010300, 0x00010300, 0x20000300, 0x01000300, 0x10000300, + 0x00000300, 0x40000200, 0x00030200, 0x10020200, 0x00020200, 0x20010200, 0x01010200, 0x10010200, 0x00010200, 0x30000200, 0x02000200, + 0x11000200, 0x01000200, 0x20000200, 0x00000210, 0x10000200, 0x00000200, 0x50000100, 0x00040100, 0x10030100, 0x00030100, 0x20020100, + 0x01020100, 0x10020100, 0x00020100, 0x30010100, 0x02010100, 0x11010100, 0x01010100, 0x20010100, 0x00010110, 0x10010100, 0x00010100, + 0x40000100, 0x03000100, 0x12000100, 0x02000100, 0x21000100, 0x01000110, 0x11000100, 0x01000100, 0x30000100, 0x00000120, 0x10000110, + 0x00000110, 0x20000100, 0x00001100, 0x10000100, 0x00000100, 0x60000000, 0x00050000, 0x10040000, 0x00040000, 0x20030000, 0x01030000, + 0x10030000, 0x00030000, 0x30020000, 0x02020000, 0x11020000, 0x01020000, 0x20020000, 0x00020010, 0x10020000, 0x00020000, 0x40010000, + 0x03010000, 0x12010000, 0x02010000, 0x21010000, 0x01010010, 0x11010000, 0x01010000, 0x30010000, 0x00010020, 0x10010010, 0x00010010, + 0x20010000, 0x00011000, 0x10010000, 0x00010000, 0x50000000, 0x04000000, 0x13000000, 0x03000000, 0x22000000, 0x02000010, 0x12000000, + 0x02000000, 0x31000000, 0x01000020, 0x11000010, 0x01000010, 0x21000000, 0x01001000, 0x11000000, 0x01000000, 0x40000000, 0x00000030, + 0x10000020, 0x00000020, 0x20000010, 0x00001010, 0x10000010, 0x00000010, 0x30000000, 0x00002000, 0x10001000, 0x00001000, 0x20000000, + 0x00100000, 0x10000000, 0x00000000, + ]; + + private static readonly byte[] RiceLen = + [ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, + 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, + 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, + 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, + 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, + 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, + ]; + + private static byte AtByte(ReadOnlySpan<byte> b, int i) => (uint)i < (uint)b.Length ? b[i] : (byte)0; + + private static uint ReadLe32(ReadOnlySpan<byte> b, int off) + { + uint r = 0; + for (var i = 0; i < 4; i++) + { + r |= (uint)AtByte(b, off + i) << (8 * i); + } + + return r; + } + + private static ulong ReadLe64(ReadOnlySpan<byte> b, int off) + { + ulong r = 0; + for (var i = 0; i < 8; i++) + { + r |= (ulong)AtByte(b, off + i) << (8 * i); + } + + return r; + } + + private static void WriteLe32(byte[] b, int off, uint v) + { + for (var i = 0; i < 4; i++) + { + if ((uint)(off + i) < (uint)b.Length) + { + b[off + i] = (byte)(v >> (8 * i)); + } + } + } + + private static void WriteLe64(byte[] b, int off, ulong v) + { + for (var i = 0; i < 8; i++) + { + if ((uint)(off + i) < (uint)b.Length) + { + b[off + i] = (byte)(v >> (8 * i)); + } + } + } + + private static bool DecodeGolombRiceLengths(ReadOnlySpan<byte> src, byte[] dst, int size, ref BitReader2 br) + { + var p = br.P; + var pEnd = br.PEnd; + var dstPos = 0; + if (p >= pEnd) + { + return false; + } + + var count = -br.BitPos; + var v = AtByte(src, p) & Shr(255, Math.Max(br.BitPos, 0)); + p++; + while (true) + { + if (v == 0) + { + count += 8; + } + else + { + var x = RiceVal[v]; + WriteLe32(dst, dstPos, (uint)count + (x & 0x0F0F0F0F)); + WriteLe32(dst, dstPos + 4, (x >> 4) & 0x0F0F0F0F); + dstPos += RiceLen[v]; + if (dstPos >= size) + { + break; + } + + count = (int)(x >> 28); + } + + if (p >= pEnd) + { + return false; + } + + v = AtByte(src, p); + p++; + } + + if (dstPos > size) + { + for (var i = 0; i < dstPos - size; i++) + { + v &= v - 1; + } + } + + var bitPos = 0; + if ((v & 1) == 0) + { + p--; + bitPos = 8 - (int)Bsf(v); + } + + br.P = p; + br.BitPos = bitPos; + return true; + } + + private static bool DecodeGolombRiceBits(ReadOnlySpan<byte> src, byte[] dst, int size, int bitCount, ref BitReader2 br) + { + if (bitCount == 0) + { + return true; + } + + var dstPos = 0; + var p = br.P; + var bitPos = br.BitPos; + var bitsRequired = (long)Math.Max(bitPos, 0) + (long)bitCount * size; + var bytesRequired = (bitsRequired + 7) / 8; + if (p < 0 || br.PEnd - p < 0 || bytesRequired > br.PEnd - p) + { + return false; + } + + br.P = p + (int)(bitsRequired >> 3); + br.BitPos = (int)(bitsRequired & 7); + var bak = ReadLe64(dst, size); + while (dstPos < size) + { + var cur = ReadLe64(dst, dstPos); + ulong spread; + switch (bitCount) + { + case 1: + { + var bits = (ulong)(byte)Shr(BinaryPrimitives.ReverseEndianness(ReadLe32(src, p)), 24 - bitPos); + p += 1; + bits = (bits | (bits << 28)) & 0xF0000000F; + bits = (bits | (bits << 14)) & 0x3000300030003; + bits = (bits | (bits << 7)) & 0x0101010101010101; + spread = cur * 2 + BinaryPrimitives.ReverseEndianness(bits); + break; + } + + case 2: + { + var bits = (ulong)(ushort)Shr(BinaryPrimitives.ReverseEndianness(ReadLe32(src, p)), 16 - bitPos); + p += 2; + bits = (bits | (bits << 24)) & 0xFF000000FF; + bits = (bits | (bits << 12)) & 0xF000F000F000F; + bits = (bits | (bits << 6)) & 0x0303030303030303; + spread = cur * 4 + BinaryPrimitives.ReverseEndianness(bits); + break; + } + + default: + { + var bits = (ulong)(Shr(BinaryPrimitives.ReverseEndianness(ReadLe32(src, p)), 8 - bitPos) & 0xFFFFFF); + p += 3; + bits = (bits | (bits << 20)) & 0xFFF00000FFF; + bits = (bits | (bits << 10)) & 0x3F003F003F003F; + bits = (bits | (bits << 5)) & 0x0707070707070707; + spread = cur * 8 + BinaryPrimitives.ReverseEndianness(bits); + break; + } + } + + WriteLe64(dst, dstPos, spread); + dstPos += 8; + } + + WriteLe64(dst, size, bak); + return true; + } + + private static bool DecodeBytesCore( + ReadOnlySpan<byte> src, + byte[] output, + int outOff, + int outEnd, + int srcOff, + int srcEnd0, + int srcMidOrg, + HuffLut lut) + { + var srcI = srcOff; + uint srcBits = 0; + var srcBitPos = 0; + var srcMid = srcMidOrg; + uint srcMidBits = 0; + var srcMidBitPos = 0; + var srcEnd = srcEnd0; + uint srcEndBits = 0; + var srcEndBitPos = 0; + var dst = outOff; + if (srcI > srcMid || srcMid > srcEnd || srcEnd > src.Length || outEnd > output.Length) + { + return false; + } + + while (dst < outEnd) + { + long bp = (uint)srcBitPos & 31; + if (srcMid - srcI <= 1) + { + if (srcMid - srcI == 1) + { + srcBits |= Shl(src[srcI], bp); + } + } + else + { + srcBits |= Shl((uint)(src[srcI] | (src[srcI + 1] << 8)), bp); + } + + var k = (int)(srcBits & 0x7FF); + int n = lut.Bits2Len[k]; + srcBitPos -= n; + srcBits = Shr(srcBits, n); + output[dst++] = lut.Bits2Sym[k]; + srcI += (7 - srcBitPos) >> 3; + srcBitPos &= 7; + if (dst < outEnd) + { + long ebp = (uint)srcEndBitPos & 31; + long mbp = (uint)srcMidBitPos & 31; + if (srcEnd - srcMid <= 1) + { + if (srcEnd - srcMid == 1) + { + srcEndBits |= Shl(src[srcMid], ebp); + srcMidBits |= Shl(src[srcMid], mbp); + } + } + else + { + var vv = (uint)(src[srcEnd - 2] | (src[srcEnd - 1] << 8)); + srcEndBits |= Shl(((vv >> 8) | (vv << 8)) & 0xFFFF, ebp); + srcMidBits |= Shl((uint)(src[srcMid] | (src[srcMid + 1] << 8)), mbp); + } + + k = (int)(srcEndBits & 0x7FF); + n = lut.Bits2Len[k]; + output[dst++] = lut.Bits2Sym[k]; + srcEndBitPos -= n; + srcEndBits = Shr(srcEndBits, n); + srcEnd -= (7 - srcEndBitPos) >> 3; + srcEndBitPos &= 7; + if (dst < outEnd) + { + k = (int)(srcMidBits & 0x7FF); + n = lut.Bits2Len[k]; + output[dst++] = lut.Bits2Sym[k]; + srcMidBitPos -= n; + srcMidBits = Shr(srcMidBits, n); + srcMid += (7 - srcMidBitPos) >> 3; + srcMidBitPos &= 7; + } + } + + if (srcI > srcMid || srcMid > srcEnd) + { + return false; + } + } + + return srcI == srcMidOrg && srcEnd == srcMid; + } + + // A 32-bit window with the next bits at the top, filled forwards from P or backwards from P + // down to Bound. + private ref struct BitReader + { + public ReadOnlySpan<byte> B; + public int P; + public int Bound; + public uint Bits; + public int BitPos; + private bool _backward; + + public static BitReader Forward(ReadOnlySpan<byte> b, int start, int end) + { + var r = new BitReader { B = b, P = start, Bound = end, Bits = 0, BitPos = 24, _backward = false }; + r.RefillForward(); + return r; + } + + public static BitReader Backward(ReadOnlySpan<byte> b, int low, int high) + { + var r = new BitReader { B = b, P = high, Bound = low, Bits = 0, BitPos = 24, _backward = true }; + r.RefillBackward(); + return r; + } + + public void Refill() + { + if (_backward) + { + RefillBackward(); + } + else + { + RefillForward(); + } + } + + private void RefillForward() + { + while (BitPos > 0) + { + uint value = P < Bound ? AtByte(B, P) : 0u; + Bits |= Shl(value, BitPos); + BitPos -= 8; + P++; + } + } + + private void RefillBackward() + { + while (BitPos > 0) + { + P--; + uint value = P >= 0 && P < B.Length && P >= Bound ? B[P] : 0u; + Bits |= Shl(value, BitPos); + BitPos -= 8; + } + } + + public uint ReadBit() + { + Refill(); + return ReadBitNoRefill(); + } + + public uint ReadBitNoRefill() + { + var r = Bits >> 31; + Bits <<= 1; + BitPos++; + return r; + } + + public uint ReadBitsNoRefill(uint n) + { + var r = Shr(Bits, 32 - (long)n); + Bits = Shl(Bits, n); + BitPos += (int)n; + return r; + } + + public uint ReadBitsNoRefillZero(uint n) + { + var r = Shr(Bits >> 1, 31 - (long)n); + Bits = Shl(Bits, n); + BitPos += (int)n; + return r; + } + + public int ReadFluff(int numSymbols) + { + if (numSymbols == 256) + { + return 0; + } + + var x = Math.Min(257 - numSymbols, numSymbols) * 2; + var y = (int)Bsr((uint)(x - 1)) + 1; + var v = Shr(Bits, 32 - y); + var z = (1u << y) - (uint)x; + if ((v >> 1) >= z) + { + Bits = Shl(Bits, y); + BitPos += y; + return (int)(v - z); + } + + Bits = Shl(Bits, y - 1); + BitPos += y - 1; + return (int)(v >> 1); + } + + public uint ReadMoreThan24(uint n) + { + uint rv; + if (n <= 24) + { + rv = ReadBitsNoRefillZero(n); + } + else + { + var hi = ReadBitsNoRefill(24) << (int)(n - 24); + Refill(); + rv = hi + ReadBitsNoRefill(n - 24); + } + + Refill(); + return rv; + } + + public uint ReadDistance(byte value) + { + uint v = value; + uint rv; + if (v < 0xF0) + { + var n = (int)(v >> 4) + 4; + var w = BitOperations.RotateLeft(Bits | 1, n); + BitPos += n; + var m = (2u << n) - 1; + Bits = w & ~m; + rv = ((w & m) << 4) + (v & 0xF) - 248; + } + else + { + var n = (int)(v - 0xF0) + 4; + var w = BitOperations.RotateLeft(Bits | 1, n); + BitPos += n; + var m = (2u << n) - 1; + Bits = w & ~m; + rv = 8322816u + ((w & m) << 12); + Refill(); + rv += Bits >> 20; + BitPos += 12; + Bits <<= 12; + } + + Refill(); + return rv; + } + + public bool ReadLength(out uint v) + { + var n = 31 - Bsr(Bits); + if (n > 12) + { + v = 0; + return false; + } + + BitPos += (int)n; + Bits = Shl(Bits, n); + Refill(); + n += 7; + BitPos += (int)n; + v = Shr(Bits, 32 - (long)n) - 64; + Bits = Shl(Bits, n); + Refill(); + return true; + } + } + + private static uint Bsr(uint x) => x == 0 ? 0 : 31u - (uint)BitOperations.LeadingZeroCount(x); + + private static uint Bsf(uint x) => x == 0 ? 0 : (uint)BitOperations.TrailingZeroCount(x); + + private static uint Clz(uint x) => x == 0 ? 31 : (uint)BitOperations.LeadingZeroCount(x); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs index cf577c0f0..15e01b215 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs @@ -7,7 +7,7 @@ namespace SharpEmu.HLE.FileSystem.Pkg; // A fake (fpkg) PS4 package opened for reading. Extraction streams every file block by block, // so a package of any size needs only a few hundred KiB of memory. -public sealed class PkgPackage : IDisposable +public sealed class PkgPackage : IGamePackage { private const int EntryKeysTableOffset = 32 + 7 * 32; // seed digest + 7 digests, then 7 RSA keys private const int EntryKeySize = 256; @@ -30,6 +30,8 @@ private PkgPackage(FileStream file, PkgHeader header, byte[] entryTable, PkgEntr public IReadOnlyList<PkgEntry> Entries { get; } + public string ContentId => Header.ContentId; + public string TitleId => Header.TitleId; // param.sfo CATEGORY (gd = game, gp = patch, ac = DLC...), or null when absent. Read once. diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs new file mode 100644 index 000000000..b9999acc1 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs @@ -0,0 +1,227 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// The finalized image header of a PS5 package ("\x7FFIH", little-endian) and the embedded CNT +// metadata container ("\x7FCNT", big-endian). Layouts follow the pkg-to-anyps5 reader. +internal sealed record Ps5Fih(ushort FormatVersion, long PfsOffset, long PfsSize, long SuperblockOffset, long CntOffset) +{ + public const int HeaderSize = 0x100; + + public const string RetailMessage = + "This is a retail PS5 package: its files are encrypted with console keys. Only fake/debug PS5 packages can be installed."; + + private static ReadOnlySpan<byte> Magic => [0x7F, 0x46, 0x49, 0x48]; + + public static Ps5Fih Read(Ps5Source source) + { + if (source.Length < HeaderSize) + { + throw new InvalidDataException("The PS5 package header is truncated."); + } + + var header = source.ReadBytes(HeaderSize, 0); + if (!header.AsSpan(0, 4).SequenceEqual(Magic)) + { + throw new InvalidDataException("Not a PS5 package (bad magic)."); + } + + // 0x00 marks a debug or fake-signed image; 0x80 marks a retail image. + if (header[5] != 0) + { + throw new InvalidDataException(RetailMessage); + } + + var pfsOffset = ReadOffset(header, 0x10); + var pfsSize = ReadOffset(header, 0x18); + var fih = new Ps5Fih( + BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(6)), + pfsOffset, + pfsSize, + ReadOffset(header, 0x20), + ReadOffset(header, 0x58)); + if (pfsOffset <= 0 || pfsSize < 0 || pfsOffset > source.Length || pfsSize > source.Length - pfsOffset) + { + throw new InvalidDataException("The PFS segment does not fit inside the PS5 package (incomplete download?)."); + } + + if (fih.CntOffset <= 0 || fih.CntOffset >= source.Length) + { + throw new InvalidDataException("The embedded CNT offset lies outside the PS5 package."); + } + + return fih; + } + + // A 64-bit field that must be a plausible file offset; anything above long.MaxValue is corrupt. + private static long ReadOffset(byte[] header, int at) + { + var value = BinaryPrimitives.ReadUInt64LittleEndian(header.AsSpan(at)); + return value > long.MaxValue ? -1 : (long)value; + } +} + +internal sealed record Ps5CntFile(string Name, byte[] Bytes); + +internal sealed class Ps5Cnt +{ + private const int EntrySize = 0x20; + private const uint EntryNamesId = 0x0200; + private const uint EncryptedFlag = 0x8000_0000; + + // Container bookkeeping: digests, entry keys, image key, general digests, metas, entry names. + private static readonly HashSet<uint> BookkeepingIds = [0x0001, 0x0010, 0x0020, 0x0080, 0x0100, 0x0200]; + + private Ps5Cnt(string contentId, List<Ps5CntFile> files, List<string> skippedEncrypted) + { + ContentId = contentId; + Files = files; + SkippedEncrypted = skippedEncrypted; + } + + public string ContentId { get; } + + // Plain entries to write below sce_sys, names relative to it. + public IReadOnlyList<Ps5CntFile> Files { get; } + + public IReadOnlyList<string> SkippedEncrypted { get; } + + public long FilesSize => Files.Sum(file => (long)file.Bytes.Length); + + public static Ps5Cnt Read(Ps5Source source, long cntOffset) + { + var header = source.ReadBytes(0x80, cntOffset); + if (!header.AsSpan(0, 4).SequenceEqual(new byte[] { 0x7F, 0x43, 0x4E, 0x54 })) + { + throw new InvalidDataException("No CNT container at the offset the PS5 header gives."); + } + + var entryCount = BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x10)); + var tableOffset = BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(0x18)); + var bodyOffset = BinaryPrimitives.ReadUInt64BigEndian(header.AsSpan(0x20)); + var bodySize = BinaryPrimitives.ReadUInt64BigEndian(header.AsSpan(0x28)); + var contentId = Encoding.ASCII.GetString(header, 0x40, 0x24).Split('\0')[0]; + if (entryCount is 0 or > 4096) + { + throw new InvalidDataException($"PS5 package CNT entry count {entryCount} is implausible."); + } + + // The body is the last region of the container. + var cntSize = bodyOffset > long.MaxValue || bodySize > long.MaxValue ? long.MaxValue : (long)bodyOffset + (long)bodySize; + var table = source.ReadBytes(entryCount * EntrySize, cntOffset + tableOffset); + var entries = new CntEntry[entryCount]; + for (var i = 0; i < entries.Length; i++) + { + var row = table.AsSpan(i * EntrySize, EntrySize); + entries[i] = new CntEntry( + BinaryPrimitives.ReadUInt32BigEndian(row), + BinaryPrimitives.ReadUInt32BigEndian(row[4..]), + BinaryPrimitives.ReadUInt32BigEndian(row[8..]), + BinaryPrimitives.ReadUInt32BigEndian(row[16..]), + BinaryPrimitives.ReadUInt32BigEndian(row[20..])); + } + + byte[] ReadEntry(CntEntry entry) + { + if ((long)entry.Offset + entry.Size > cntSize) + { + throw new InvalidDataException($"PS5 package CNT entry 0x{entry.Id:X4} runs past the container."); + } + + return source.ReadBytes(entry.Size, cntOffset + entry.Offset); + } + + var names = Array.Empty<byte>(); + foreach (var entry in entries) + { + if (entry.Id == EntryNamesId && !entry.Encrypted) + { + names = ReadEntry(entry); + break; + } + } + + var files = new List<Ps5CntFile>(); + var skippedEncrypted = new List<string>(); + foreach (var entry in entries) + { + if (entry.Size == 0) + { + continue; + } + + var name = EntryName(names, entry.Id, entry.NameOffset); + if (entry.Encrypted) + { + skippedEncrypted.Add(name ?? $"0x{entry.Id:X4}"); + continue; + } + + if (BookkeepingIds.Contains(entry.Id) || string.IsNullOrEmpty(name)) + { + continue; + } + + files.Add(new Ps5CntFile(name, ReadEntry(entry))); + } + + return new Ps5Cnt(contentId, files, skippedEncrypted); + } + + // Name relative to sce_sys: from the names table, else the well-known id list; null when neither + // knows the entry. + internal static string? EntryName(byte[] names, uint id, uint nameOffset) + { + string? raw = null; + if (nameOffset != 0 && nameOffset < names.Length) + { + var end = Array.IndexOf(names, (byte)0, (int)nameOffset); + var length = (end < 0 ? names.Length : end) - (int)nameOffset; + if (length > 0) + { + raw = Encoding.UTF8.GetString(names, (int)nameOffset, length); + } + } + + raw ??= WellKnownName(id); + if (raw is null) + { + return null; + } + + var name = raw.TrimStart('/', '\\'); + while (name.StartsWith("sce_sys/", StringComparison.Ordinal)) + { + name = name["sce_sys/".Length..]; + } + + return name; + } + + private static string? WellKnownName(uint id) => id switch + { + 0x0400 => "license.dat", + 0x0401 => "license.info", + 0x0402 => "nptitle.dat", + 0x040a => "imagedigs.dat", + 0x1001 => "playgo-chunk.dat", + 0x1200 => "icon0.png", + 0x1220 => "pic0.png", + 0x1240 => "snd0.at9", + 0x1280 => "icon0.dds", + 0x12a0 => "pic0.dds", + 0x2000 => "param.json", + 0x2010 => "playgo-hash-table.dat", + 0x2011 => "playgo-ficm.dat", + _ => null, + }; + + private readonly record struct CntEntry(uint Id, uint NameOffset, uint Flags1, uint Offset, uint Size) + { + public bool Encrypted => (Flags1 & EncryptedFlag) != 0; + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs new file mode 100644 index 000000000..10818d897 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs @@ -0,0 +1,523 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// A file of the inner image: path components below uroot, logical byte offset and size. +internal sealed record Ps5InnerFile(string[] Components, long Logical, long Size); + +// The inner image (pfs_image.dat): a PFS whose logical bytes are stored as 256 KiB blocks, each raw +// or Kraken-compressed, as NAPS describes. The inner superblock, inodes and directories sit after +// the last file in logical order, so they are found by decoding that tail and looking for a +// superblock whose size matches the NAPS mount size. Blocks are decoded one at a time (the last one +// is cached) so an image of any size needs a few hundred KiB of memory. +internal sealed class Ps5InnerImage +{ + private const int InnerInodeSize = 0xA8; + private const uint DirentFile = 2; + private const uint DirentDir = 3; + private const long MaxDirSize = 8 << 20; + // The superblock, inodes and directories after the last file. Real images keep a few MiB there; + // a larger tail means a corrupt layout. + private const long MaxMetaTail = 1L << 30; + private const int MaxDepth = 64; + + private readonly Ps5OuterFile _image; + private readonly UBlock[] _blocks; + // NAPS file-offset entries: logical offsets of file boundaries. + private readonly ulong[] _boundaries; + + private int _cachedIndex = -1; + private byte[] _decoded = []; + private byte[] _payload = []; + + internal readonly record struct UBlock(long Logical, long OnDisk, uint Compressed, uint Uncompressed, bool Kraken, uint EvenComp, uint Flags); + + private Ps5InnerImage(Ps5OuterFile image, UBlock[] blocks, ulong[] boundaries, long mount) + { + _image = image; + _blocks = blocks; + _boundaries = boundaries; + Mount = mount; + } + + // Logical size of the inner image. + public long Mount { get; } + + public static Ps5InnerImage Open(Ps5OuterFile image, byte[] napsBlob) + { + var layout = Ps5Naps.Parse(napsBlob); + var mount = layout.MountSize(); + if (mount == 0) + { + throw new InvalidDataException("The NAPS layout has no mount size entry."); + } + + // Keep the one table placement whose blocks cover the mount exactly. + var walks = new List<UBlock[]>(); + var problems = new List<string>(); + foreach (var candidate in layout.Candidates) + { + try + { + walks.Add(WalkBlocks(layout, candidate.Cblocks, mount)); + } + catch (InvalidDataException exception) + { + problems.Add($"table at 0x{candidate.Start:X}: {exception.Message}"); + } + } + + if (walks.Count > 1) + { + throw new InvalidDataException("Two NAPS CblockInfo placements both map the whole image; refusing to guess."); + } + + if (walks.Count == 0) + { + throw new InvalidDataException(string.Join("; ", problems)); + } + + var blocks = walks[0]; + foreach (var block in blocks) + { + if (block.OnDisk + block.Compressed > image.Size) + { + throw new InvalidDataException( + $"The block at logical 0x{block.Logical:X} is stored at 0x{block.OnDisk:X}+0x{block.Compressed:X}, past the 0x{image.Size:X}-byte image."); + } + } + + return new Ps5InnerImage(image, blocks, layout.FileOffsets.Select(entry => entry.UncompressedOffset).ToArray(), mount); + } + + // Lists the regular files under uroot, every name checked with PkgPackage.ResolveSafe. + public List<Ps5InnerFile> ListFiles() + { + // Metadata follows the last file boundary below the mount size. + long metaBase = 0; + foreach (var boundary in _boundaries) + { + if (boundary > 0 && boundary < (ulong)Mount && (long)boundary > metaBase) + { + metaBase = (long)boundary; + } + } + + var first = PartitionPoint(block => block.Logical + block.Uncompressed <= metaBase); + if (first >= _blocks.Length) + { + throw new InvalidDataException("There are no blocks after the last file."); + } + + var tailBase = _blocks[first].Logical; + var tailLength = Mount - tailBase; + if (tailLength > MaxMetaTail) + { + throw new InvalidDataException("The inner image metadata after the last file is implausibly large."); + } + + var tail = new byte[tailLength]; + ReadAt(tailBase, tail); + var superblockOffset = FindSuperblock(tail, Mount) + ?? throw new InvalidDataException("No inner PFS superblock covers the image (corrupt or unsupported layout)."); + var tree = Tree.Parse(tail, superblockOffset, tailBase); + var files = new List<Ps5InnerFile>(); + WalkDir(tree, 0, [], false, files, new bool[tree.Inodes.Length], 0); + if (files.Count == 0) + { + throw new InvalidDataException("The inner tree has no files under uroot."); + } + + return files; + } + + private void WalkDir(Tree tree, uint inode, string[] path, bool underUroot, List<Ps5InnerFile> files, bool[] seen, int depth) + { + if (depth > MaxDepth) + { + throw new InvalidDataException("The inner directory tree is too deep."); + } + + if (inode >= tree.Inodes.Length) + { + throw new InvalidDataException($"Inner inode {inode} is out of range."); + } + + if (seen[inode]) + { + // Already walked (a hard link or a cycle): nothing new below it. + return; + } + + seen[inode] = true; + var dir = tree.Inodes[inode]; + if (!dir.IsDirectory || dir.Size == 0 || dir.Size > MaxDirSize) + { + throw new InvalidDataException($"Inner inode {inode} is not a readable directory."); + } + + var bytes = tree.Local(dir.Logical, dir.Size); + if (bytes is null) + { + bytes = new byte[dir.Size]; + ReadAt(dir.Logical, bytes); + } + + foreach (var entry in Ps5Dirent.Parse(bytes, tree.BlockSize)) + { + if (entry.IsSelfOrParentDirectory) + { + continue; + } + + string name; + try + { + name = new UTF8Encoding(false, true).GetString(entry.Name); + } + catch (ArgumentException) + { + throw new InvalidDataException("An inner file name is not valid UTF-8."); + } + + if (entry.Inode >= tree.Inodes.Length) + { + throw new InvalidDataException($"{name}: inode {entry.Inode} is out of range."); + } + + var isUroot = !underUroot && path.Length == 0 && name == "uroot"; + if (!underUroot && !isUroot) + { + continue; + } + + // Refuses separators, "..", Windows-reserved characters. + PkgPackage.ResolveSafe(string.Empty, [name]); + var childPath = isUroot ? path : [.. path, name]; + if (entry.Kind == DirentDir) + { + WalkDir(tree, entry.Inode, childPath, true, files, seen, depth + 1); + } + else if (entry.Kind == DirentFile) + { + var child = tree.Inodes[entry.Inode]; + if (child.Logical < 0 || child.Size < 0 || child.Logical > Mount || child.Size > Mount - child.Logical) + { + throw new InvalidDataException($"{string.Join('/', childPath)} runs past the end of the inner image."); + } + + files.Add(new Ps5InnerFile(childPath, child.Logical, child.Size)); + } + } + } + + // Reads logical bytes of the inner image. + public void ReadAt(long logical, byte[] buffer) + { + var done = 0; + CopyTo(logical, buffer.Length, chunk => + { + chunk.CopyTo(buffer.AsSpan(done)); + done += chunk.Length; + }); + } + + // Streams logical bytes to `sink` one block at a time. + public void CopyTo(long logical, long size, SpanAction sink) + { + if (logical < 0 || size < 0 || size > long.MaxValue - logical) + { + throw new InvalidDataException("A logical range of the inner image overflows."); + } + + var position = logical; + var end = logical + size; + while (position < end) + { + var index = FindBlock(position); + var block = _blocks[index]; + var within = (int)(position - block.Logical); + var count = (int)Math.Min(block.Uncompressed - within, end - position); + LoadBlock(index); + sink(_decoded.AsSpan(within, count)); + position += count; + } + } + + public delegate void SpanAction(ReadOnlySpan<byte> chunk); + + private int PartitionPoint(Func<UBlock, bool> predicate) + { + int low = 0, high = _blocks.Length; + while (low < high) + { + var mid = low + (high - low) / 2; + if (predicate(_blocks[mid])) + { + low = mid + 1; + } + else + { + high = mid; + } + } + + return low; + } + + private int FindBlock(long logical) + { + var index = PartitionPoint(block => block.Logical + block.Uncompressed <= logical); + if (index >= _blocks.Length || _blocks[index].Logical > logical) + { + throw new InvalidDataException($"No block covers logical 0x{logical:X}."); + } + + return index; + } + + private void LoadBlock(int index) + { + if (_cachedIndex == index) + { + return; + } + + _cachedIndex = -1; + var block = _blocks[index]; + if (_decoded.Length != block.Uncompressed) + { + _decoded = new byte[block.Uncompressed]; + } + + if (block.Compressed == 0) + { + Array.Clear(_decoded); + } + else + { + if (_payload.Length != block.Compressed) + { + _payload = new byte[block.Compressed]; + } + + _image.ReadExactAt(_payload, block.OnDisk); + if (_payload.Length == _decoded.Length) + { + _payload.CopyTo(_decoded, 0); + } + else + { + try + { + Kraken.DecodeBlock(_payload, block.Flags, block.EvenComp, _decoded); + } + catch (InvalidDataException exception) + { + throw new InvalidDataException( + $"{exception.Message} (block at logical 0x{block.Logical:X}, stored at 0x{block.OnDisk:X}, {block.Compressed} -> {block.Uncompressed} bytes, flags 0x{block.Flags:X})."); + } + } + } + + _cachedIndex = index; + } + + // Builds the logical-to-stored block list from the CblockInfo records. + internal static UBlock[] WalkBlocks(Ps5Naps layout, NapsCblock[] records, long mount) + { + var output = new List<UBlock>((int)Math.Min(layout.Counts.NumUblocks + 16L, 1 << 20)); + long onDisk = 0; + long uncompressed = 0; + var i = 0; + while (i < records.Length) + { + var record = records[i]; + if (record.IsRunBase) + { + if (i + 1 >= records.Length || records[i + 1].IsRunBase) + { + throw new InvalidDataException($"NAPS run base {i} is not followed by a data record."); + } + + onDisk = record.RunOnDisk(records[i + 1]); + i++; + continue; + } + + AppendSparse(layout, mount, ref uncompressed, output); + if (uncompressed >= mount || i + 1 >= records.Length) + { + break; + } + + var fileEnd = layout.NextBoundary(uncompressed, mount); + var length = Math.Min(Ps5Naps.UblockSize, Math.Max(fileEnd - uncompressed, 0)); + if (length == 0) + { + break; + } + + // The next record's offset within its 256 KiB block marks where this block's stored + // bytes end, for stored and Kraken blocks alike. + long diff = (long)records[i + 1].CoffsetMod - record.CoffsetMod; + if (diff <= 0) + { + diff += Ps5Naps.UblockSize; + } + + output.Add(new UBlock( + uncompressed, + onDisk, + (uint)diff, + (uint)length, + record.IsKraken || diff != length, + record.EvenComp, + record.KrakenFlags)); + onDisk += diff; + uncompressed += length; + if (uncompressed >= mount) + { + break; + } + + i++; + } + + AppendSparse(layout, mount, ref uncompressed, output); + if (uncompressed != mount) + { + throw new InvalidDataException($"NAPS blocks cover 0x{uncompressed:X} bytes, but the mount size is 0x{mount:X}."); + } + + return [.. output]; + } + + // A mount-kind entry below the mount size opens a region with no stored records; it reads as zeros. + private static void AppendSparse(Ps5Naps layout, long mount, ref long uncompressed, List<UBlock> output) + { + while (uncompressed < mount) + { + var entry = layout.FirstAtOrAfter(uncompressed); + if (entry is not { Kind: Ps5Naps.KindMount } found || found.UncompressedOffset != (ulong)uncompressed) + { + return; + } + + var end = layout.NextBoundary(uncompressed, mount); + var length = Math.Min(Ps5Naps.UblockSize, end - uncompressed); + if (length <= 0) + { + throw new InvalidDataException($"Empty sparse region at 0x{uncompressed:X}."); + } + + output.Add(new UBlock(uncompressed, 0, 0, (uint)length, false, 0, 0)); + uncompressed += length; + } + } + + // Requires the superblock to cover exactly the NAPS mount size, so the outer image's superblock + // can never be taken for the inner one. + internal static int? FindSuperblock(byte[] buffer, long mount) + { + for (long offset = 0; offset + 0x40 <= buffer.Length; offset += 0x10000) + { + var span = buffer.AsSpan((int)offset); + long blockSize = BinaryPrimitives.ReadUInt32LittleEndian(span[0x20..]); + if (BinaryPrimitives.ReadUInt64LittleEndian(span) == 2 + && BinaryPrimitives.ReadUInt64LittleEndian(span[8..]) == Ps5OuterPfs.PfsMagic + && BinaryPrimitives.ReadUInt64LittleEndian(span[0x30..]) > 0 + && unchecked(BinaryPrimitives.ReadUInt64LittleEndian(span[0x38..]) * (ulong)blockSize) == (ulong)mount) + { + return (int)offset; + } + } + + return null; + } + + private readonly record struct InnerInode(ushort Mode, long Size, long Logical) + { + public bool IsDirectory => (Mode & 0xF000) == 0x4000; + } + + private sealed class Tree + { + private readonly byte[] _tail; + private readonly long _tailBase; + + private Tree(byte[] tail, long tailBase, int blockSize, InnerInode[] inodes) + { + _tail = tail; + _tailBase = tailBase; + BlockSize = blockSize; + Inodes = inodes; + } + + public int BlockSize { get; } + + public InnerInode[] Inodes { get; } + + public static Tree Parse(byte[] tail, int superblockOffset, long tailBase) + { + var sb = tail.AsSpan(superblockOffset); + if (sb.Length < 0x40) + { + throw new InvalidDataException("The inner superblock is truncated."); + } + + long blockSize = BinaryPrimitives.ReadUInt32LittleEndian(sb[0x20..]); + var count = BinaryPrimitives.ReadUInt64LittleEndian(sb[0x30..]); + var mode = BinaryPrimitives.ReadUInt16LittleEndian(sb[0x1C..]); + if (blockSize == 0 || blockSize % 0x1000 != 0 || blockSize > 1 << 20 || count == 0 || count > 1_000_000) + { + throw new InvalidDataException($"Inner superblock: block size 0x{blockSize:X}, {count} inodes."); + } + + // Mode 0x10 is the compact flat layout: an inode stores the byte address of its data at + // 0x60 instead of signed block pointers. + if ((mode & 0x13) != 0x10) + { + throw new InvalidDataException($"Unsupported inner PFS mode 0x{mode:X} (only the flat 0x10 layout is known)."); + } + + var perBlock = blockSize / InnerInodeSize; + var table = superblockOffset + blockSize; + var inodes = new InnerInode[count]; + for (var i = 0; i < inodes.Length; i++) + { + var at = table + i / perBlock * blockSize + i % perBlock * InnerInodeSize; + if (at + InnerInodeSize > tail.Length) + { + throw new InvalidDataException("The inner inode table is truncated."); + } + + var record = tail.AsSpan((int)at, InnerInodeSize); + var size = BinaryPrimitives.ReadUInt64LittleEndian(record[8..]); + var logical = BinaryPrimitives.ReadUInt64LittleEndian(record[0x60..]); + inodes[i] = new InnerInode( + BinaryPrimitives.ReadUInt16LittleEndian(record), + size > long.MaxValue ? long.MaxValue : (long)size, + logical > long.MaxValue ? long.MaxValue : (long)logical); + } + + return new Tree(tail, tailBase, (int)blockSize, inodes); + } + + // The bytes of [logical, logical+size) when they sit inside the decoded tail. + public byte[]? Local(long logical, long size) + { + var start = logical - _tailBase; + if (start < 0 || size < 0 || start > _tail.Length || size > _tail.Length - start) + { + return null; + } + + return _tail.AsSpan((int)start, (int)size).ToArray(); + } + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs new file mode 100644 index 000000000..14034a979 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs @@ -0,0 +1,277 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +internal sealed record NapsCounts( + uint NumFiles, + byte CompressionType, + uint NumKeys, + uint NumShuffle, + uint NumUblocks, + uint NumOuterBlocks, + uint NumCblockInfo) +{ + public long NumU2c => (NumUblocks + 8) >> 3; +} + +internal readonly record struct NapsFileOffset(byte Kind, ulong UncompressedOffset); + +internal readonly record struct NapsCblock( + bool IsRunBase, + uint CoffsetMod, + uint ClenEvenMinus1, + byte KdePredictor, + byte ShuffleIdx, + uint CoffsetStart256K) +{ + // Compressed length of the first Kraken chunk of a block. + public uint EvenComp => ClenEvenMinus1 + 1; + + public bool IsKraken => (KdePredictor & 2) != 0; + + public uint KrakenFlags => KdePredictor | ((uint)ShuffleIdx << 4); + + // A run base holds twice the 256 KiB block index; the next data record supplies the byte offset + // within that block. + public long RunOnDisk(NapsCblock first) => + (long)(CoffsetStart256K / 2) * Ps5Naps.UblockSize + first.CoffsetMod; +} + +// A placement of the CblockInfo table that passed the structural checks. Only a walk over all +// blocks can tell two such placements apart. +internal sealed record NapsCandidate(int Start, NapsCblock[] Cblocks); + +// naps_pkg_layout.dat: the map from the inner image's logical offsets to the stored (raw or +// Kraken-compressed) bytes of pfs_image.dat. Layout: a 16-byte packed header, outer-block digests +// (8 bytes each), shuffle patterns (8 bytes each), file-offset entries (6 bytes each, padded to +// 16), u2c entries (10 bytes each, padded to 8), then 9-byte CblockInfo records. The format follows +// the PS5PCEM and LibProsperoPKG readers via pkg-to-anyps5. +internal sealed class Ps5Naps +{ + public const long UblockSize = 0x40000; + // The header counts pfs_image.dat in 64 KiB outer blocks. + private const long OuterBlockSize = 0x10000; + private const int HeaderSize = 16; + private const int OuterStride = 8; + private const int ShuffleStride = 8; + private const int FileOffsetStride = 6; + private const int U2cStride = 10; + private const int CblockStride = 9; + // File-offset kind of the terminal mount-size entry and of sparse regions. + public const byte KindMount = 0x40; + + // Largest inner image accepted. Sparse regions cost no stored bytes, so a forged mount size + // would otherwise make the reader build one 256 KiB block record per step of a huge image. + public const long MaxMountSize = 512L << 30; + + private Ps5Naps(NapsCounts counts, NapsFileOffset[] fileOffsets, List<NapsCandidate> candidates) + { + Counts = counts; + FileOffsets = fileOffsets; + Candidates = candidates; + } + + public NapsCounts Counts { get; } + + // Sorted by offset. + public NapsFileOffset[] FileOffsets { get; } + + public IReadOnlyList<NapsCandidate> Candidates { get; } + + public static Ps5Naps Parse(byte[] blob) + { + var counts = DecodeHeader(blob); + var pos = HeaderSize + (long)counts.NumOuterBlocks * OuterStride + (long)counts.NumShuffle * ShuffleStride; + long fileCount = counts.NumFiles; + if (pos + fileCount * FileOffsetStride > blob.Length) + { + throw new InvalidDataException("The NAPS file-offset table is truncated."); + } + + var fileOffsets = new NapsFileOffset[fileCount]; + for (var i = 0; i < fileOffsets.Length; i++) + { + var at = (int)pos + i * FileOffsetStride; + ulong offset = 0; + for (var b = 0; b < 5; b++) + { + offset |= (ulong)blob[at + b] << (8 * b); + } + + fileOffsets[i] = new NapsFileOffset(blob[at + 5], offset); + if (fileOffsets[i].Kind == KindMount && offset > MaxMountSize) + { + throw new InvalidDataException($"The NAPS mount size 0x{offset:X} is implausibly large."); + } + } + + var fileOffsetsEnd = pos + fileCount * FileOffsetStride; + // The u2c table ends on an 8-byte boundary. Where it starts differs between packages: some + // pad the file-offset table to 16 bytes, others start u2c right after it. Both placements + // are tried; only one yields a valid record table. + var starts = new List<long>(); + foreach (var u2c in new[] { AlignUp(fileOffsetsEnd, 16), fileOffsetsEnd }) + { + var start = AlignUp(u2c + counts.NumU2c * U2cStride, 8); + if (starts.Count == 0 || starts[^1] != start) + { + starts.Add(start); + } + } + + var imageSize = (long)counts.NumOuterBlocks * OuterBlockSize; + var problems = new List<string>(); + var candidates = new List<NapsCandidate>(); + foreach (var start in starts) + { + try + { + candidates.Add(new NapsCandidate((int)start, ReadCblocks(blob, start, counts.NumCblockInfo, imageSize))); + } + catch (InvalidDataException exception) + { + problems.Add($"at 0x{start:X}: {exception.Message}"); + } + } + + if (candidates.Count == 0) + { + throw new InvalidDataException($"No valid NAPS CblockInfo table ({string.Join("; ", problems)})."); + } + + // Stable, so entries sharing an offset keep their table order. + var sorted = fileOffsets.Select((entry, index) => (entry, index)).OrderBy(pair => pair.entry.UncompressedOffset).ThenBy(pair => pair.index) + .Select(pair => pair.entry).ToArray(); + return new Ps5Naps(counts, sorted, candidates); + } + + // The logical size of the inner image: the last mount-kind entry. + public long MountSize() + { + for (var i = FileOffsets.Length - 1; i >= 0; i--) + { + if (FileOffsets[i].Kind == KindMount) + { + return FileOffsets[i].UncompressedOffset > long.MaxValue ? 0 : (long)FileOffsets[i].UncompressedOffset; + } + } + + return 0; + } + + // The first file boundary after `current`, or `mount` when there is none. + public long NextBoundary(long current, long mount) + { + var index = PartitionPoint(offset => offset <= (ulong)current); + return index < FileOffsets.Length ? Math.Min(Clamp(FileOffsets[index].UncompressedOffset), mount) : mount; + } + + // The first entry at or after `offset`, in table order among equal offsets. + public NapsFileOffset? FirstAtOrAfter(long offset) + { + var index = PartitionPoint(value => value < (ulong)offset); + return index < FileOffsets.Length ? FileOffsets[index] : null; + } + + private int PartitionPoint(Func<ulong, bool> predicate) + { + int low = 0, high = FileOffsets.Length; + while (low < high) + { + var mid = low + (high - low) / 2; + if (predicate(FileOffsets[mid].UncompressedOffset)) + { + low = mid + 1; + } + else + { + high = mid; + } + } + + return low; + } + + private static long Clamp(ulong value) => value > long.MaxValue ? long.MaxValue : (long)value; + + private static long AlignUp(long value, long alignment) => (value + alignment - 1) / alignment * alignment; + + // Reads the records and checks that every run base is followed by a data record and lands inside + // the stored image. + private static NapsCblock[] ReadCblocks(byte[] blob, long start, uint count, long imageSize) + { + var end = start + (long)count * CblockStride; + if (start < 0 || end > blob.Length) + { + throw new InvalidDataException($"{count} records end at 0x{end:X}, past the {blob.Length}-byte layout."); + } + + var records = new NapsCblock[count]; + for (var i = 0; i < records.Length; i++) + { + records[i] = DecodeCblock(blob.AsSpan((int)start + i * CblockStride, CblockStride)); + } + + for (var i = 0; i < records.Length; i++) + { + if (!records[i].IsRunBase) + { + continue; + } + + if (i + 1 >= records.Length || records[i + 1].IsRunBase) + { + throw new InvalidDataException($"Run base {i} is not followed by a data record."); + } + + var at = records[i].RunOnDisk(records[i + 1]); + if (at >= imageSize) + { + throw new InvalidDataException($"Run base {i} points at 0x{at:X}, past the 0x{imageSize:X}-byte image."); + } + } + + return records; + } + + public static NapsCounts DecodeHeader(ReadOnlySpan<byte> blob) + { + if (blob.Length < HeaderSize) + { + throw new InvalidDataException("The NAPS header is truncated."); + } + + var w0 = BinaryPrimitives.ReadUInt64LittleEndian(blob); + var w1 = BinaryPrimitives.ReadUInt64LittleEndian(blob[8..]); + return new NapsCounts( + (uint)(w0 & 0xFF_FFFF) + 1, + (byte)((w0 >> 24) & 3), + (uint)((w0 >> 26) & 3) + 1, + (uint)((w0 >> 28) & 0xF), + (uint)((w0 >> 32) & 0xFF_FFFF), + (uint)(w1 & 0xFF_FFFF), + (uint)((w1 >> 24) & 0xFF_FFFF) + 2); + } + + public static NapsCblock DecodeCblock(ReadOnlySpan<byte> raw) + { + var lo = BinaryPrimitives.ReadUInt64LittleEndian(raw); + ulong hi = raw[8]; + var coffsetMod = (uint)(lo & 0x3FFFF); + if (((lo >> 18) & 1) == 0) + { + return new NapsCblock( + false, + coffsetMod, + (uint)((lo >> 38) & 0x1FFFF), + (byte)((lo >> 56) & 7), + (byte)((lo >> 59) & 0xF), + 0); + } + + return new NapsCblock(true, coffsetMod, 0, 0, 0, (uint)(((lo >> 49) & 0x7FFF) | ((hi & 0x1FF) << 15))); + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs new file mode 100644 index 000000000..bcf5aa4ad --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs @@ -0,0 +1,390 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// The outer PFS of a finalized PS5 image. It holds two files: pfs_image.dat (the inner image, stored +// or Kraken-compressed) and naps_pkg_layout.dat (the map from inner logical offsets to stored +// bytes). Block numbers count blocks from the start of the PFS segment. Layouts follow pkg-to-anyps5. +internal sealed class Ps5OuterPfs +{ + public const ulong PfsMagic = 20130315; // 0x01332A0B + private const ushort ModeSigned = 0x1; + private const ushort Mode64Bit = 0x2; + private const ushort ModeEncrypted = 0x4; + private const int DirectBlocks = 12; + private const int IndirectLevels = 5; + private const uint DirentFile = 2; + private const uint DirentDir = 3; + private const long MaxBlockSize = 1 << 20; + // The outer tree holds a handful of entries; a larger directory is corrupt. + private const long MaxOuterDirSize = 8 << 20; + + private static readonly byte[] PlainNoAuthSeed = "PPRPLAIN-NOAUTH!"u8.ToArray(); + + private readonly Ps5Source _source; + private readonly long _base; + private readonly long _size; + private readonly InodeLayout _layout; + private readonly Inode[] _inodes; + + private Ps5OuterPfs(Ps5Source source, long pfsOffset, long pfsSize, Ps5PfsSuperblock superblock, InodeLayout layout, Inode[] inodes) + { + _source = source; + _base = pfsOffset; + _size = pfsSize; + Superblock = superblock; + _layout = layout; + _inodes = inodes; + } + + public Ps5PfsSuperblock Superblock { get; } + + internal sealed record Ps5PfsSuperblock(ushort Mode, long BlockSize, long InodeCount, long InodeBlockCount, long InodeTableBlock, byte[] Seed) + { + public static Ps5PfsSuperblock Parse(ReadOnlySpan<byte> buf) + { + if (buf.Length < 0x380) + { + throw new InvalidDataException("The PFS superblock is truncated."); + } + + var version = BinaryPrimitives.ReadUInt64LittleEndian(buf); + var magic = BinaryPrimitives.ReadUInt64LittleEndian(buf[8..]); + if (magic != PfsMagic || version is not (1 or 2)) + { + throw new InvalidDataException($"No PFS superblock (version {version}, magic 0x{magic:X})."); + } + + long blockSize = BinaryPrimitives.ReadUInt32LittleEndian(buf[0x20..]); + if (blockSize == 0 || blockSize > MaxBlockSize || blockSize % 0x1000 != 0) + { + throw new InvalidDataException($"Unsupported PFS block size 0x{blockSize:X}."); + } + + return new Ps5PfsSuperblock( + BinaryPrimitives.ReadUInt16LittleEndian(buf[0x1C..]), + blockSize, + ClampToLong(BinaryPrimitives.ReadUInt64LittleEndian(buf[0x30..])), + Math.Max(1, ClampToLong(BinaryPrimitives.ReadUInt64LittleEndian(buf[0x40..]))), + ClampToLong(BinaryPrimitives.ReadUInt64LittleEndian(buf[0xD8..])), + buf.Slice(0x370, 16).ToArray()); + } + + internal InodeLayout GetInodeLayout() => ((Mode & ModeSigned) != 0, (Mode & Mode64Bit) != 0) switch + { + (true, false) => new InodeLayout(0x2C8, 0x64, 36, 32, false), + (true, true) => new InodeLayout(0x310, 0x68, 40, 32, true), + (false, false) => new InodeLayout(0xA8, 0x64, 4, 0, false), + (false, true) => new InodeLayout(0x100, 0x68, 8, 0, true), + }; + + private static long ClampToLong(ulong value) => value > long.MaxValue ? long.MaxValue : (long)value; + } + + // Where block pointers sit in an inode and in indirect blocks. Signed images put a 32-byte hash + // before every pointer. + internal readonly record struct InodeLayout(int Size, int FirstPointer, int Stride, int PointerAt, bool Pointer64) + { + public long Pointer(ReadOnlySpan<byte> buf, int index) + { + var at = index * Stride + PointerAt; + if (at < 0 || at + (Pointer64 ? 8 : 4) > buf.Length) + { + throw new InvalidDataException("A PFS block pointer lies outside its block."); + } + + return Pointer64 + ? (long)Math.Min(BinaryPrimitives.ReadUInt64LittleEndian(buf[at..]), long.MaxValue) + : BinaryPrimitives.ReadUInt32LittleEndian(buf[at..]); + } + } + + internal sealed record Inode(long Size, long[] Direct, long[] Indirect); + + public static Ps5OuterPfs Open(Ps5Source source, long pfsOffset, long pfsSize, long superblockOffset) + { + // Data-first images keep the superblock near the end, where the header points; classic + // images keep it at the start of the segment. + var inSegment = superblockOffset >= pfsOffset && superblockOffset <= pfsOffset + pfsSize - 0x400; + var at = inSegment ? superblockOffset : pfsOffset; + var superblock = Ps5PfsSuperblock.Parse(source.ReadBytes(0x400, at)); + if ((superblock.Mode & ModeEncrypted) != 0 && !superblock.Seed.AsSpan().SequenceEqual(PlainNoAuthSeed)) + { + throw new InvalidDataException( + "The PS5 package's outer PFS is encrypted (its seed is not PPRPLAIN-NOAUTH!); only fake/debug packages can be installed."); + } + + if (superblock.InodeCount is 0 or > 1 << 20) + { + throw new InvalidDataException($"The outer PFS inode count {superblock.InodeCount} is implausible."); + } + + var layout = superblock.GetInodeLayout(); + var perBlock = (int)(superblock.BlockSize / layout.Size); + if (perBlock == 0) + { + throw new InvalidDataException("The outer PFS block is too small for its inodes."); + } + + if (superblock.InodeBlockCount > pfsSize / superblock.BlockSize || superblock.InodeTableBlock > pfsSize / superblock.BlockSize) + { + throw new InvalidDataException("The outer PFS inode table does not fit in the PFS segment."); + } + + var table = source.ReadBytes(superblock.InodeBlockCount * superblock.BlockSize, pfsOffset + superblock.InodeTableBlock * superblock.BlockSize); + var inodes = new Inode[superblock.InodeCount]; + for (var i = 0; i < inodes.Length; i++) + { + var offset = (long)(i / perBlock) * superblock.BlockSize + (long)(i % perBlock) * layout.Size; + if (offset + layout.Size > table.Length) + { + throw new InvalidDataException("The outer PFS inode table is short."); + } + + inodes[i] = ParseInode(table.AsSpan((int)offset, layout.Size), layout); + } + + return new Ps5OuterPfs(source, pfsOffset, pfsSize, superblock, layout, inodes); + } + + internal static Inode ParseInode(ReadOnlySpan<byte> record, InodeLayout layout) + { + var pointers = record[layout.FirstPointer..]; + var direct = new long[DirectBlocks]; + for (var i = 0; i < direct.Length; i++) + { + direct[i] = layout.Pointer(pointers, i); + } + + var indirect = new long[IndirectLevels]; + for (var i = 0; i < indirect.Length; i++) + { + indirect[i] = layout.Pointer(pointers, DirectBlocks + i); + } + + var size = BinaryPrimitives.ReadUInt64LittleEndian(record[8..]); + return new Inode(size > long.MaxValue ? long.MaxValue : (long)size, direct, indirect); + } + + public int InodeCount => _inodes.Length; + + public Ps5OuterFile OpenFile(uint inode) + { + if (inode >= _inodes.Length) + { + throw new InvalidDataException($"Outer PFS inode {inode} is out of range."); + } + + var node = _inodes[inode]; + if (node.Size > _size) + { + throw new InvalidDataException($"Outer PFS inode {inode} is larger than the PFS segment."); + } + + var blockSize = Superblock.BlockSize; + var count = (node.Size + blockSize - 1) / blockSize; + return new Ps5OuterFile(_source, _base, blockSize, BlockList(node, count), node.Size); + } + + // Finds a regular file by name anywhere in the outer tree. + public uint? Find(string name) + { + var target = System.Text.Encoding.UTF8.GetBytes(name); + var stack = new Stack<uint>(); + stack.Push(0); + var seen = new bool[_inodes.Length]; + while (stack.Count > 0) + { + var dir = stack.Pop(); + if (seen[dir]) + { + continue; + } + + seen[dir] = true; + var file = OpenFile(dir); + if (file.Size > MaxOuterDirSize) + { + throw new InvalidDataException($"Outer PFS directory inode {dir} is implausibly large."); + } + + foreach (var entry in Ps5Dirent.Parse(file.ReadAll(), (int)Superblock.BlockSize)) + { + if (entry.Inode >= _inodes.Length || entry.IsSelfOrParentDirectory) + { + continue; + } + + if (entry.Kind == DirentDir) + { + stack.Push(entry.Inode); + } + else if (entry.Kind == DirentFile && entry.Name.AsSpan().SequenceEqual(target)) + { + return entry.Inode; + } + } + } + + return null; + } + + private long[] BlockList(Inode node, long count) + { + var blocks = new List<long>((int)Math.Min(count, 1 << 20)); + for (var i = 0; i < DirectBlocks && blocks.Count < count; i++) + { + blocks.Add(node.Direct[i]); + } + + var perBlock = (int)(Superblock.BlockSize / _layout.Stride); + var level = 0; + while (blocks.Count < count) + { + if (level >= 3) + { + throw new InvalidDataException("An outer PFS file needs more than triple-indirect blocks."); + } + + WalkIndirect(node.Indirect[level], level, count, perBlock, blocks); + level++; + } + + return [.. blocks]; + } + + private void WalkIndirect(long block, int depth, long count, int perBlock, List<long> output) + { + var buffer = _source.ReadBytes(Superblock.BlockSize, BlockOffset(_base, block, Superblock.BlockSize)); + for (var i = 0; i < perBlock && output.Count < count; i++) + { + var pointer = _layout.Pointer(buffer, i); + if (depth == 0) + { + output.Add(pointer); + } + else + { + WalkIndirect(pointer, depth - 1, count, perBlock, output); + } + } + } + + // Package offset of a PFS block; an overflow means a corrupt pointer. + internal static long BlockOffset(long baseOffset, long block, long blockSize) + { + try + { + return checked(baseOffset + block * blockSize); + } + catch (OverflowException) + { + throw new InvalidDataException($"Outer PFS block pointer 0x{block:X} is out of range."); + } + } +} + +// A file of the outer PFS, read through its block list. +internal sealed class Ps5OuterFile(Ps5Source source, long baseOffset, long blockSize, long[] blocks, long size) +{ + public long Size { get; } = size; + + public void ReadExactAt(Span<byte> buffer, long offset) + { + if (offset < 0 || offset > Size || buffer.Length > Size - offset) + { + throw new InvalidDataException($"Read of {buffer.Length:N0} bytes at 0x{offset:X} is past the end of a {Size:N0}-byte outer file."); + } + + var done = 0; + while (done < buffer.Length) + { + var position = offset + done; + var index = (int)(position / blockSize); + var within = position % blockSize; + // Coalesce a run of consecutive blocks into one read. + var run = 1; + while (index + run < blocks.Length && blocks[index + run] == blocks[index] + run) + { + run++; + } + + var available = run * blockSize - within; + var n = (int)Math.Min(available, buffer.Length - done); + var at = Ps5OuterPfs.BlockOffset(baseOffset, blocks[index], blockSize) + within; + source.ReadExactAt(buffer.Slice(done, n), at); + done += n; + } + } + + public byte[] ReadAll() + { + var bytes = new byte[Size]; + ReadExactAt(bytes, 0); + return bytes; + } +} + +internal readonly record struct Ps5Dirent(uint Inode, uint Kind, byte[] Name) +{ + // The "." and ".." directory records: typed as directories (3) by some builders, or with the + // PFS self (4) and parent (5) types by others. A file that merely carries one of those names is not one. + public bool IsSelfOrParentDirectory => Kind is 3 or 4 or 5 && (Name.AsSpan().SequenceEqual("."u8) || Name.AsSpan().SequenceEqual(".."u8)); + + // Directory records: inode, type, name length, record size, then the name. An all-zero record + // pads to the end of its block. + public static List<Ps5Dirent> Parse(byte[] buffer, int blockSize) + { + var entries = new List<Ps5Dirent>(); + var position = 0; + while (position < buffer.Length) + { + var rest = buffer.AsSpan(position); + if (rest.Length < 16) + { + if (rest.IndexOfAnyExcept((byte)0) < 0) + { + break; + } + + throw new InvalidDataException("Truncated PFS directory record."); + } + + var inode = BinaryPrimitives.ReadUInt32LittleEndian(rest); + var kind = BinaryPrimitives.ReadUInt32LittleEndian(rest[4..]); + var nameLength = BinaryPrimitives.ReadUInt32LittleEndian(rest[8..]); + var recordSize = BinaryPrimitives.ReadUInt32LittleEndian(rest[12..]); + if (inode == 0 && kind == 0 && nameLength == 0 && recordSize == 0) + { + var skip = blockSize - position % blockSize; + position += Math.Min(skip, rest.Length); + continue; + } + + if (recordSize is < 16 or > 0x1000 || nameLength > recordSize - 16 || recordSize > rest.Length) + { + throw new InvalidDataException($"Bad PFS directory record at 0x{position:X} (name {nameLength} bytes, record {recordSize} bytes)."); + } + + var name = rest.Slice(16, (int)nameLength); + var end = name.IndexOf((byte)0); + if (end >= 0) + { + name = name[..end]; + } + + position += (int)recordSize; + if (name.IsEmpty) + { + throw new InvalidDataException("PFS directory record without a name."); + } + + entries.Add(new Ps5Dirent(inode, kind, name.ToArray())); + } + + return entries; + } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs new file mode 100644 index 000000000..342c6f048 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs @@ -0,0 +1,231 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text.Json; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// A fake/debug PS5 package ("\x7FFIH") opened for reading. Retail packages and packages whose outer +// PFS is encrypted are refused at Open: their files need console keys. Extraction streams every +// file block by block, so a package of any size needs only a few hundred KiB of memory. +public sealed class Ps5Package : IGamePackage +{ + private const string ImageFileName = "pfs_image.dat"; + private const string LayoutFileName = "naps_pkg_layout.dat"; + // A layout is a few MiB at most; anything larger is not a NAPS file. + private const long MaxLayoutSize = 256L << 20; + + private readonly Ps5Source _source; + private readonly Ps5Fih _fih; + private readonly Ps5Cnt _cnt; + private readonly Ps5OuterPfs _outer; + private readonly string? _paramTitle; + private readonly string? _paramTitleId; + + private Ps5InnerImage? _inner; + private List<Ps5InnerFile>? _files; + private long _filesSize; + + private Ps5Package(Ps5Source source, Ps5Fih fih, Ps5Cnt cnt, Ps5OuterPfs outer) + { + _source = source; + _fih = fih; + _cnt = cnt; + _outer = outer; + foreach (var file in cnt.Files) + { + if (file.Name == "param.json") + { + (_paramTitleId, _paramTitle) = ReadParamJson(file.Bytes); + break; + } + } + } + + public string ContentId => _cnt.ContentId; + + // param.json titleId, else the title id inside the content id (UP9000-PPSA01234_00-...). + public string TitleId => + !string.IsNullOrWhiteSpace(_paramTitleId) ? _paramTitleId : ContentId.Length >= 16 ? ContentId.Substring(7, 9) : string.Empty; + + // param.json localizedParameters[defaultLanguage].titleName, else the en-US one. + public string? Title => _paramTitle; + + // Nothing in the container reliably tells a game from a patch or DLC, so this stays null (a game). + public string? Category => null; + + public bool IsGameApplication => true; + + public string GetFolderName(string fallback) => + PkgPackage.ToFolderName(Title) ?? PkgPackage.ToFolderName(TitleId) ?? fallback; + + public static Ps5Package Open(string path) + { + var source = new Ps5Source(path); + try + { + var fih = Ps5Fih.Read(source); + var cnt = Ps5Cnt.Read(source, fih.CntOffset); + var outer = Ps5OuterPfs.Open(source, fih.PfsOffset, fih.PfsSize, fih.SuperblockOffset); + return new Ps5Package(source, fih, cnt, outer); + } + catch + { + source.Dispose(); + throw; + } + } + + // Size on disk of everything Extract writes (sce_sys metadata plus the game files), computed + // without extracting. It decodes the inner image's metadata tail to walk the tree. + public long GetInstalledSize() + { + LoadTree(); + return _filesSize + _cnt.FilesSize; + } + + public void Extract(string destination, IProgress<PkgExtractProgress>? progress = null, CancellationToken cancellation = default) => + Extract(destination, progress, cancellation, PkgPackage.ProgressStepBytes, PkgPackage.GetAvailableSpace(destination)); + + internal void Extract( + string destination, + IProgress<PkgExtractProgress>? progress, + CancellationToken cancellation, + long progressStepBytes, + long? availableBytes) + { + var (image, files) = LoadTree(); + var total = _filesSize; + + // Resolve every destination first: an unsafe name must fail before anything is written. + var metadataRoot = Path.Combine(destination, "sce_sys"); + var metadata = _cnt.Files + .Select(file => (Path: PkgPackage.ResolveSafe(metadataRoot, file.Name.Split('/')), file.Bytes)) + .ToList(); + var targets = files + .Select(file => (Path: PkgPackage.ResolveSafe(destination, file.Components), File: file)) + .ToList(); + + var needed = total + _cnt.FilesSize; + if (availableBytes is { } available && available < needed) + { + throw new IOException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Not enough free disk space: need {needed / (1024.0 * 1024 * 1024):0.00} GB, {available / (1024.0 * 1024 * 1024):0.00} GB free.")); + } + + Directory.CreateDirectory(destination); + foreach (var (path, bytes) in metadata) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, bytes); + } + + long done = 0; + foreach (var (path, file) in targets) + { + cancellation.ThrowIfCancellationRequested(); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var relative = Path.GetRelativePath(destination, path); + progress?.Report(new PkgExtractProgress(done, total, relative)); + var sinceReport = 0L; + using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 20, FileOptions.SequentialScan); + image.CopyTo(file.Logical, file.Size, chunk => + { + output.Write(chunk); + done += chunk.Length; + sinceReport += chunk.Length; + cancellation.ThrowIfCancellationRequested(); + if (sinceReport >= progressStepBytes) + { + sinceReport = 0; + progress?.Report(new PkgExtractProgress(done, total, relative)); + } + }); + progress?.Report(new PkgExtractProgress(done, total, relative)); + } + + progress?.Report(new PkgExtractProgress(total, total, string.Empty)); + } + + // Opens the inner image and lists its files once; both GetInstalledSize and Extract need them. + private (Ps5InnerImage Image, List<Ps5InnerFile> Files) LoadTree() + { + if (_inner is not null && _files is not null) + { + return (_inner, _files); + } + + var imageInode = _outer.Find(ImageFileName) + ?? throw new InvalidDataException($"The PS5 package's outer PFS has no {ImageFileName}."); + var layoutInode = _outer.Find(LayoutFileName) + ?? throw new InvalidDataException($"The PS5 package's outer PFS has no {LayoutFileName}; images without a NAPS layout are not supported."); + var layoutFile = _outer.OpenFile(layoutInode); + if (layoutFile.Size > MaxLayoutSize) + { + throw new InvalidDataException($"{LayoutFileName} is far larger than any layout."); + } + + var inner = Ps5InnerImage.Open(_outer.OpenFile(imageInode), layoutFile.ReadAll()); + var files = inner.ListFiles(); + long size = 0; + foreach (var file in files) + { + // Every name goes through ResolveSafe again at Extract; the size can be summed now. + size += file.Size; + } + + _inner = inner; + _files = files; + _filesSize = size; + return (inner, files); + } + + private static (string? TitleId, string? Title) ReadParamJson(byte[] json) + { + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return (null, null); + } + + var titleId = root.TryGetProperty("titleId", out var id) && id.ValueKind == JsonValueKind.String ? id.GetString() : null; + string? title = null; + if (root.TryGetProperty("localizedParameters", out var localized) && localized.ValueKind == JsonValueKind.Object) + { + var defaultLanguage = localized.TryGetProperty("defaultLanguage", out var language) && language.ValueKind == JsonValueKind.String + ? language.GetString() + : null; + // defaultLanguage sits inside localizedParameters; a copy at the top level is tolerated too. + if (defaultLanguage is null && root.TryGetProperty("defaultLanguage", out var rootLanguage) && rootLanguage.ValueKind == JsonValueKind.String) + { + defaultLanguage = rootLanguage.GetString(); + } + + foreach (var key in new[] { defaultLanguage, "en-US" }) + { + if (key is not null + && localized.TryGetProperty(key, out var entry) + && entry.ValueKind == JsonValueKind.Object + && entry.TryGetProperty("titleName", out var name) + && name.ValueKind == JsonValueKind.String) + { + title = name.GetString(); + break; + } + } + } + + return (titleId, title); + } + catch (JsonException) + { + return (null, null); + } + } + + public void Dispose() => _source.Dispose(); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs new file mode 100644 index 000000000..59a8c98c8 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs @@ -0,0 +1,58 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Microsoft.Win32.SafeHandles; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// Positional reads over the package file; every read is range checked. +internal sealed class Ps5Source : IDisposable +{ + private readonly SafeFileHandle _handle; + + public Ps5Source(string path) + { + _handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, FileOptions.RandomAccess); + Length = RandomAccess.GetLength(_handle); + } + + public long Length { get; } + + public void ReadExactAt(Span<byte> buffer, long offset) + { + if (offset < 0 || offset > Length || buffer.Length > Length - offset) + { + throw new InvalidDataException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Read of {buffer.Length:N0} bytes at 0x{offset:X} is past the end of the {Length:N0}-byte package.")); + } + + var done = 0; + while (done < buffer.Length) + { + var read = RandomAccess.Read(_handle, buffer[done..], offset + done); + if (read == 0) + { + throw new InvalidDataException("The package file ended unexpectedly."); + } + + done += read; + } + } + + public byte[] ReadBytes(long length, long offset) + { + if (length < 0 || length > int.MaxValue || offset < 0 || offset > Length || length > Length - offset) + { + throw new InvalidDataException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Read of {length:N0} bytes at 0x{offset:X} is past the end of the {Length:N0}-byte package.")); + } + + var bytes = new byte[length]; + ReadExactAt(bytes, offset); + return bytes; + } + + public void Dispose() => _handle.Dispose(); +} diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs new file mode 100644 index 000000000..d6a32ee11 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs @@ -0,0 +1,956 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; +using SharpEmu.HLE.FileSystem.Pkg; +using Xunit; + +namespace SharpEmu.Libs.Tests.FileSystem; + +// Synthetic data only: nothing here comes from a real package. The builder writes a tiny but +// complete FIH package: FIH header, a signed 32-bit outer PFS (plain seed, encrypted mode bit set) +// holding pfs_image.dat and naps_pkg_layout.dat, an inner flat PFS, and an embedded CNT. +public sealed class Ps5PkgTests +{ + private const string DefaultContentId = "UP9000-PPSA01234_00-TESTGAME00000000"; + + private const string DefaultParamJson = + """{"titleId":"PPSA01234","localizedParameters":{"defaultLanguage":"en-US","en-US":{"titleName":"Test: The Game"},"fr-FR":{"titleName":"Le Jeu"}}}"""; + + // ---- package level ------------------------------------------------------------------------- + + [Fact] + public void FormatDetectionSeparatesFihCntAndJunk() + { + var fih = BuildPackage(new Spec()); + WithFile(fih.Bytes, path => + { + Assert.True(GamePackage.IsPackagePath(path)); + using var package = GamePackage.Open(path); + Assert.IsType<Ps5Package>(package); + }); + + // A bare "\x7FCNT" header with nothing behind it is a (degenerate) PS4 package. + var cnt = new byte[PkgHeader.Size]; + BinaryPrimitives.WriteUInt32BigEndian(cnt, PkgHeader.Magic); + WithFile(cnt, path => + { + Assert.True(GamePackage.IsPackagePath(path)); + using var package = GamePackage.Open(path); + Assert.IsType<PkgPackage>(package); + }); + + WithFile("PK\u0003\u0004 not a package, just junk bytes"u8.ToArray(), path => + { + Assert.False(GamePackage.IsPackagePath(path)); + Assert.Throws<InvalidDataException>(() => GamePackage.Open(path)); + }); + + WithFile([0x7F, 0x46], path => Assert.Throws<InvalidDataException>(() => GamePackage.Open(path))); + WithFile(fih.Bytes, path => Assert.False(GamePackage.IsPackagePath(path)), extension: ".bin"); + Assert.False(GamePackage.IsPackagePath(Path.Combine(Path.GetTempPath(), $"sharpemu-missing-{Guid.NewGuid():N}.pkg"))); + } + + [Fact] + public void OpenReadsContentIdTitleIdAndTitle() + { + WithPackage(BuildPackage(new Spec()).Bytes, (package, _) => + { + Assert.Equal(DefaultContentId, package.ContentId); + Assert.Equal("PPSA01234", package.TitleId); + Assert.Equal("Test: The Game", package.Title); + Assert.Null(package.Category); + Assert.True(package.IsGameApplication); + // ':' is refused by Windows, so the folder name drops it on every host. + Assert.Equal("Test The Game", package.GetFolderName("fallback")); + }); + } + + [Fact] + public void TitleFollowsTheDefaultLanguage() + { + const string json = """{"titleId":"PPSA01234","localizedParameters":{"defaultLanguage":"fr-FR","en-US":{"titleName":"English"},"fr-FR":{"titleName":"Le Jeu"}}}"""; + WithPackage(BuildPackage(new Spec { ParamJson = json }).Bytes, (package, _) => Assert.Equal("Le Jeu", package.Title)); + } + + [Fact] + public void FolderNameFallsBackToTheTitleIdThenToTheCaller() + { + WithPackage(BuildPackage(new Spec { ParamJson = null }).Bytes, (package, _) => + { + Assert.Null(package.Title); + Assert.Equal("PPSA01234", package.TitleId); + Assert.Equal("PPSA01234", package.GetFolderName("fallback")); + }); + + WithPackage(BuildPackage(new Spec { ParamJson = null, ContentId = "SHORT" }).Bytes, (package, _) => + { + Assert.Equal(string.Empty, package.TitleId); + Assert.Equal("fallback", package.GetFolderName("fallback")); + }); + + WithPackage(BuildPackage(new Spec { ParamJson = "{ not json" }).Bytes, (package, _) => Assert.Null(package.Title)); + } + + [Fact] + public void ExtractWritesTheGameTreeAndSceSys() + { + var built = BuildPackage(new Spec()); + WithPackage(built.Bytes, (package, destination) => + { + var reports = new List<PkgExtractProgress>(); + package.Extract(destination, new CollectingProgress<PkgExtractProgress>(reports.Add)); + + var written = ReadTree(destination); + Assert.Equal(built.ExpectedFiles.Keys.OrderBy(k => k, StringComparer.Ordinal), written.Keys.OrderBy(k => k, StringComparer.Ordinal)); + foreach (var (name, bytes) in built.ExpectedFiles) + { + Assert.True(bytes.AsSpan().SequenceEqual(written[name]), name); + } + + // Licences (encrypted) and container bookkeeping never reach disk. + Assert.False(File.Exists(Path.Combine(destination, "sce_sys", "license.dat"))); + Assert.False(File.Exists(Path.Combine(destination, "sce_sys", "digests.bin"))); + Assert.False(File.Exists(Path.Combine(destination, "sce_sys", "metas.bin"))); + Assert.False(File.Exists(Path.Combine(destination, "sce_sys", "entry_names.bin"))); + Assert.False(File.Exists(Path.Combine(destination, "sce_sys", "unnamed.bin"))); + // The sparse region reads as zeros and a file outside uroot is ignored. + Assert.All(written["assets/sparse.bin"], b => Assert.Equal(0, b)); + Assert.False(written.ContainsKey("readme")); + + Assert.NotEmpty(reports); + Assert.Equal(reports[^1].BytesTotal, reports[^1].BytesDone); + Assert.Equal(built.GameBytes, reports[^1].BytesTotal); + Assert.All(reports, report => Assert.True(report.BytesDone <= report.BytesTotal)); + }); + } + + [Fact] + public void GetInstalledSizeMatchesWhatExtractWrites() + { + WithPackage(BuildPackage(new Spec()).Bytes, (package, destination) => + { + var size = package.GetInstalledSize(); + package.Extract(destination); + Assert.Equal(size, ReadTree(destination).Values.Sum(bytes => (long)bytes.Length)); + }); + } + + [Fact] + public void ExtractReportsProgressInsideAFile() + { + WithPackage(BuildPackage(new Spec()).Bytes, (package, destination) => + { + var reports = new List<PkgExtractProgress>(); + package.Extract(destination, new CollectingProgress<PkgExtractProgress>(reports.Add), default, 1, null); + Assert.True(reports.Select(r => r.BytesDone).Distinct().Count() > 5); + Assert.Equal(reports[^1].BytesTotal, reports[^1].BytesDone); + }); + } + + [Fact] + public void RetailPackagesAreRefused() + { + var exception = OpenFails(BuildPackage(new Spec { RetailByte = 0x80 }).Bytes); + Assert.Contains("retail", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void AnEncryptedOuterPfsWithoutThePlainSeedIsRefused() + { + var exception = OpenFails(BuildPackage(new Spec { Seed = "SOMETHING-ELSE!!" }).Bytes); + Assert.Contains("encrypted", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..")] + [InlineData("a\\b")] + [InlineData("x:y")] + [InlineData("a/b")] + public void UnsafeInnerNamesAreRefusedBeforeAnythingIsWritten(string name) + { + WithPackage(BuildPackage(new Spec { ModuleFileName = name }).Bytes, (package, destination) => + { + Assert.Throws<InvalidDataException>(() => package.GetInstalledSize()); + Assert.Throws<InvalidDataException>(() => package.Extract(destination)); + Assert.False(Directory.Exists(destination)); + }); + } + + [Fact] + public void UnsafeCntNamesAreRefusedBeforeAnythingIsWritten() + { + WithPackage(BuildPackage(new Spec { ExtraCntName = "../evil.bin" }).Bytes, (package, destination) => + { + Assert.Throws<InvalidDataException>(() => package.Extract(destination)); + Assert.False(Directory.Exists(destination)); + }); + } + + [Fact] + public void ExtractRefusesWhenTheDriveIsTooSmallAndWritesNothing() + { + WithPackage(BuildPackage(new Spec()).Bytes, (package, destination) => + { + var needed = package.GetInstalledSize(); + Assert.Throws<IOException>(() => package.Extract(destination, null, default, PkgPackage.ProgressStepBytes, needed - 1)); + Assert.False(Directory.Exists(destination)); + + package.Extract(destination, null, default, PkgPackage.ProgressStepBytes, needed); + Assert.True(File.Exists(Path.Combine(destination, "eboot.bin"))); + }); + } + + [Fact] + public void ExtractHonoursCancellation() + { + WithPackage(BuildPackage(new Spec()).Bytes, (package, destination) => + { + using var already = new CancellationTokenSource(); + already.Cancel(); + Assert.Throws<OperationCanceledException>(() => package.Extract(destination, null, already.Token)); + }); + + WithPackage(BuildPackage(new Spec()).Bytes, (package, destination) => + { + using var source = new CancellationTokenSource(); + var progress = new CollectingProgress<PkgExtractProgress>(report => + { + if (report.BytesDone > 0) + { + source.Cancel(); + } + }); + Assert.Throws<OperationCanceledException>(() => package.Extract(destination, progress, source.Token, 1, null)); + }); + } + + // ---- NAPS ---------------------------------------------------------------------------------- + + [Fact] + public void NapsHeaderFieldsUnpack() + { + var w0 = 63UL | (2UL << 24) | (40808UL << 32); + var w1 = 68506UL | (43579UL << 24); + var header = new byte[16]; + BinaryPrimitives.WriteUInt64LittleEndian(header, w0); + BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(8), w1); + var counts = Ps5Naps.DecodeHeader(header); + Assert.Equal((64u, (byte)2, 40808u), (counts.NumFiles, counts.CompressionType, counts.NumUblocks)); + Assert.Equal((68506u, 43581u), (counts.NumOuterBlocks, counts.NumCblockInfo)); + + // The header of a large real-world layout: 550661 blocks of 256 KiB. + var large = Ps5Naps.DecodeHeader([0xAE, 0, 0, 2, 5, 0x67, 8, 0, 0x7A, 0xAB, 0x15, 0xD6, 0xF6, 8, 0, 0]); + Assert.Equal(0x219C140000L, large.NumUblocks * Ps5Naps.UblockSize); + Assert.Equal(0x15AB7Au, large.NumOuterBlocks); + Assert.Equal(0xAFu, large.NumFiles); + Assert.Throws<InvalidDataException>(() => Ps5Naps.DecodeHeader(new byte[15])); + } + + [Fact] + public void CblockInfoKeepsTheHighBitOfTheFirstChunkLength() + { + var record = Ps5Naps.DecodeCblock([0x09, 0x72, 0xA1, 0x48, 0x0E, 0xE2, 0xC9, 0x12, 0x00]); + Assert.False(record.IsRunBase); + Assert.Equal(75657u, record.EvenComp); + Assert.Equal(0x22u, record.KrakenFlags); + Assert.True(record.IsKraken); + + var stored = Ps5Naps.DecodeCblock([0x0A, 0x00, 0xA2, 0x24, 0xC3, 0xFF, 0xFF, 0x04, 0x00]); + Assert.Equal(0x20000u, stored.EvenComp); + } + + [Fact] + public void CblockInfoTableStartsAfterTheEightByteU2cPadding() + { + var blob = new byte[96]; + BinaryPrimitives.WriteUInt64LittleEndian(blob, 1UL | (9UL << 32)); + BinaryPrimitives.WriteUInt64LittleEndian(blob.AsSpan(8), 1UL); + blob[32] = 0x24; // mount size 0x240000 + blob[35] = 0x40; + blob[74] = 4; // run base marker at the start of CblockInfo (72) + blob[81] = 10; + + var layout = Ps5Naps.Parse(blob[..90]); + Assert.Equal(0x240000, layout.MountSize()); + var first = layout.Candidates[0]; + Assert.Equal(72, first.Start); + Assert.True(first.Cblocks[0].IsRunBase); + Assert.False(first.Cblocks[1].IsRunBase); + Assert.Equal(10, first.Cblocks[0].RunOnDisk(first.Cblocks[1])); + + // Cut off at 89 bytes only the placement right after the file offsets (56) still fits. + Assert.Equal(new[] { 56 }, Ps5Naps.Parse(blob[..89]).Candidates.Select(c => c.Start).ToArray()); + } + + [Fact] + public void ImplausibleMountSizeIsRefused() + { + var blob = new byte[90]; + BinaryPrimitives.WriteUInt64LittleEndian(blob, 1UL | (9UL << 32)); + BinaryPrimitives.WriteUInt64LittleEndian(blob.AsSpan(8), 1UL); + blob[32] = 0x24; + blob[34] = 0xFF; // mount size 0xFF00240000, about 1 TiB + blob[35] = 0x40; + blob[74] = 4; + blob[81] = 10; + + var refused = Assert.Throws<InvalidDataException>(() => Ps5Naps.Parse(blob)); + Assert.Contains("mount size", refused.Message); + } + + [Fact] + public void U2cMayStartRightAfterTheFileOffsets() + { + var blob = new byte[74]; + BinaryPrimitives.WriteUInt64LittleEndian(blob, 1UL | (9UL << 32)); + BinaryPrimitives.WriteUInt64LittleEndian(blob.AsSpan(8), 1UL); + blob[32] = 0x24; + blob[35] = 0x40; + blob[58] = 4; // run base + blob[65] = 10; // data record, offset 10 + + var layout = Ps5Naps.Parse(blob); + var only = Assert.Single(layout.Candidates); + Assert.Equal(56, only.Start); + Assert.Equal(10, only.Cblocks[0].RunOnDisk(only.Cblocks[1])); + } + + [Fact] + public void RunBasesOutsideTheImageRejectAPlacement() + { + var blob = new byte[74]; + BinaryPrimitives.WriteUInt64LittleEndian(blob, 1UL | (9UL << 32)); + BinaryPrimitives.WriteUInt64LittleEndian(blob.AsSpan(8), 1UL); + blob[35] = 0x40; + blob[58] = 4; + blob[63] = 0x04; // run start 512: 256 KiB block 256, past the 0x10000-byte image + Assert.Throws<InvalidDataException>(() => Ps5Naps.Parse(blob)); + Assert.Throws<InvalidDataException>(() => Ps5Naps.Parse(new byte[8])); + } + + // ---- outer PFS ----------------------------------------------------------------------------- + + [Fact] + public void OuterPfsFollowsDirectSingleAndDoubleIndirectBlocks() + { + // 4 KiB blocks hold 113 signed pointers: 12 direct + 113 single + 200 through double indirect. + var data = Pattern(9, (12 + 113 + 200) * 0x1000 - 123); + var small = Pattern(10, 77); + var pfs = BuildOuterPfs(0x1000, "PPRPLAIN-NOAUTH!", [("big.bin", data), ("small.bin", small)], scramble: true); + WithFile(pfs, path => + { + using var source = new Ps5Source(path); + var outer = Ps5OuterPfs.Open(source, 0, pfs.Length, 0); + var big = outer.OpenFile(outer.Find("big.bin") ?? throw new InvalidOperationException()); + Assert.Equal(data.Length, big.Size); + Assert.True(data.AsSpan().SequenceEqual(big.ReadAll())); + + var window = new byte[5000]; + big.ReadExactAt(window, 12 * 0x1000 - 2500); + Assert.True(data.AsSpan(12 * 0x1000 - 2500, window.Length).SequenceEqual(window)); + Assert.True(small.AsSpan().SequenceEqual(outer.OpenFile(outer.Find("small.bin")!.Value).ReadAll())); + Assert.Null(outer.Find("missing.bin")); + Assert.Throws<InvalidDataException>(() => big.ReadExactAt(new byte[2], big.Size - 1)); + }, extension: ".dat"); + } + + [Fact] + public void SignedInodePointersFollowTheirHashes() + { + var layout = new Ps5OuterPfs.Ps5PfsSuperblock(0x0D, 0x10000, 1, 1, 0, []).GetInodeLayout(); + Assert.Equal(0x2C8, layout.Size); + var record = new byte[layout.Size]; + BinaryPrimitives.WriteUInt64LittleEndian(record.AsSpan(8), 0x60); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(0x64 + 32), 0x15AC86); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(0x64 + 36 + 32), 7); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(0x64 + 12 * 36 + 32), 0x15AC88); + var inode = Ps5OuterPfs.ParseInode(record, layout); + Assert.Equal(0x15AC86, inode.Direct[0]); + Assert.Equal(7, inode.Direct[1]); + Assert.Equal(0x15AC88, inode.Indirect[0]); + Assert.Equal(0x60, inode.Size); + } + + [Fact] + public void DirectoryRecordsAreValidated() + { + var good = Dirent(2, 3, ".", 24); + Array.Resize(ref good, 64); + good = [.. good, .. Dirent(3, 2, "pfs_image.dat", 32)]; + Array.Resize(ref good, 128); + var names = Ps5Dirent.Parse(good, 64).Select(e => Encoding.ASCII.GetString(e.Name)).ToArray(); + Assert.Equal([".", "pfs_image.dat"], names); + + var tooLong = Dirent(3, 2, "x", 24); + BinaryPrimitives.WriteUInt32LittleEndian(tooLong.AsSpan(8), 30); + Assert.Throws<InvalidDataException>(() => Ps5Dirent.Parse(tooLong, 64)); + } + + // ---- Kraken -------------------------------------------------------------------------------- + + [Fact] + public void KrakenCopiesAVerbatimBlock() + { + byte[] src = [1, 2, 3, 4, 5, 6, 7, 8]; + var dst = new byte[8]; + Kraken.DecodeBlock(src, 0x02, 8, dst); + Assert.Equal(src, dst); + } + + [Fact] + public void KrakenMemcpyEntropyArrayExpands() + { + var (used, output) = Kraken.DecodeBytes([0x80, 0x04, 9, 8, 7, 6], 4); + Assert.Equal(6, used); + Assert.Equal<byte[]>([9, 8, 7, 6], output); + } + + [Fact] + public void KrakenDecodesASingleSymbolHuffmanArray() + { + // Entropy type 2, 3-byte header: 3 payload bytes expand to 10. The payload is "00", a + // count of 1 symbol, then the symbol 0xAA. + var (used, output) = Kraken.DecodeBytes([0xA0, 0x18, 0x03, 0x00, 0x6A, 0x80], 10); + Assert.Equal(6, used); + Assert.Equal(Enumerable.Repeat((byte)0xAA, 10), output); + } + + [Fact] + public void KrakenDecodesAnLzChunkWhoseLiteralsUseMemcpyEntropy() + { + var block = Pattern(5, 200); + var payload = KrakenLiteralChunk(block); + var output = new byte[block.Length]; + Kraken.DecodeBlock(payload, 0x02, 0, output); + Assert.Equal(block, output); + + // The same chunk as the second half of a two-chunk block, restarting with a fresh seed. + var two = new byte[0x20000 + block.Length]; + var first = KrakenLiteralChunk(Pattern(6, 0x20000)); + var combined = new byte[first.Length + payload.Length]; + first.CopyTo(combined, 0); + payload.CopyTo(combined, first.Length); + Kraken.DecodeBlock(combined, 0x02 | 0x20 | 0x40, (uint)first.Length, two); + Assert.True(Pattern(6, 0x20000).AsSpan().SequenceEqual(two.AsSpan(0, 0x20000))); + Assert.True(block.AsSpan().SequenceEqual(two.AsSpan(0x20000))); + } + + [Fact] + public void KrakenReportsUnsupportedEntropyTypesWithTheirNumber() + { + // Type 1 (tANS), 3-byte header: 2 compressed bytes for 4 output bytes. + var exception = Assert.Throws<InvalidDataException>(() => Kraken.DecodeBytes([0x90, 0x04, 0x02, 0, 0], 16)); + Assert.Contains("entropy type 1", exception.Message); + } + + [Fact] + public void KrakenRejectsMalformedData() + { + var dst = new byte[64]; + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBlock([], 0x02, 0, dst)); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBlock([1, 2, 3], 0x02, 0, dst)); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBlock(new byte[100], 0x02, 0, dst)); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBlock([1], 0, 0, [])); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBytes([0x80], 8)); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBytes([0x80, 0x09, 1, 2], 8)); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBytes([0x80, 0x04, 1, 2, 3, 4], 2)); + + // A valid chunk cut short or with a corrupted command stream must not decode. + var good = KrakenLiteralChunk(Pattern(7, 64)); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBlock(good.AsSpan(0, good.Length - 1), 0x02, 0, new byte[64])); + Assert.Throws<InvalidDataException>(() => Kraken.DecodeBlock(good, 0x02, 0, new byte[65])); + } + + [Fact] + public void KrakenNeverThrowsAnythingButInvalidDataOnCorruptInput() + { + var random = new System.Random(12345); + var seeds = new List<byte[]> + { + KrakenLiteralChunk(Pattern(1, 64)), + KrakenLiteralChunk(Pattern(2, 1000)), + new byte[] { 0xA0, 0x18, 0x03, 0x00, 0x6A, 0x80 }, + new byte[] { 0x90, 0x04, 0x02, 0, 0 }, + }; + var lengths = new[] { 64, 1000, 4096, 10, 0x20040 }; + for (var iteration = 0; iteration < 4000; iteration++) + { + var payload = (byte[])seeds[random.Next(seeds.Count)].Clone(); + if (random.Next(4) == 0) + { + payload = new byte[random.Next(1, 300)]; + random.NextBytes(payload); + } + + for (var edits = random.Next(0, 4); edits > 0 && payload.Length > 0; edits--) + { + payload[random.Next(payload.Length)] = (byte)random.Next(256); + } + + if (random.Next(5) == 0 && payload.Length > 1) + { + payload = payload[..random.Next(1, payload.Length)]; + } + + var dst = new byte[lengths[random.Next(lengths.Length)]]; + try + { + Kraken.DecodeBlock(payload, (uint)random.Next(0x80), (uint)random.Next(0, 400), dst); + } + catch (InvalidDataException) + { + } + } + } + + // ---- helpers ------------------------------------------------------------------------------- + + private sealed record Spec + { + public byte RetailByte { get; init; } + + public string Seed { get; init; } = "PPRPLAIN-NOAUTH!"; + + public string ContentId { get; init; } = DefaultContentId; + + public string? ParamJson { get; init; } = DefaultParamJson; + + public string ModuleFileName { get; init; } = "libfoo.prx"; + + public string? ExtraCntName { get; init; } + } + + private sealed record Built(byte[] Bytes, Dictionary<string, byte[]> ExpectedFiles, long GameBytes); + + private static byte[] Pattern(int seed, int length) + { + var bytes = new byte[length]; + for (var i = 0; i < bytes.Length; i++) + { + bytes[i] = (byte)(i * 31 + seed * 7 + (i >> 8)); + } + + return bytes; + } + + private static byte[] Dirent(uint inode, uint kind, string name, int recordSize) + { + var record = new byte[recordSize]; + BinaryPrimitives.WriteUInt32LittleEndian(record, inode); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(4), kind); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(8), (uint)Encoding.UTF8.GetByteCount(name)); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(12), (uint)recordSize); + Encoding.UTF8.GetBytes(name).CopyTo(record, 16); + return record; + } + + private static byte[] DirectoryBlock(int blockSize, params (uint Inode, uint Kind, string Name)[] entries) + { + var block = new byte[blockSize]; + var at = 0; + foreach (var (inode, kind, name) in entries) + { + var size = (16 + Encoding.UTF8.GetByteCount(name) + 1 + 7) & ~7; + Dirent(inode, kind, name, size).CopyTo(block, at); + at += size; + } + + return block; + } + + // One LZ chunk (with seed) holding `block` as 8 seed bytes plus literals stored with the memcpy + // entropy type and no commands. Every array uses the 3-byte memcpy header: a first byte with the + // high bit set would read as the excess framing. + private static byte[] KrakenLiteralChunk(byte[] block) + { + var literals = block[8..]; + var payload = new List<byte>(); + payload.AddRange(block[..8]); + payload.AddRange([(byte)(literals.Length >> 16), (byte)(literals.Length >> 8), (byte)literals.Length]); + payload.AddRange(literals); + payload.AddRange([0, 0, 0]); // commands + payload.AddRange([0, 0, 0]); // packed offsets + payload.AddRange([0, 0, 0]); // packed lengths + payload.Add(0x80); // the bit stream holding the zero escape-length count + return [.. payload]; + } + + private static byte[] CblockRecord(uint coffsetMod, ulong kdePredictor) + { + var record = new byte[9]; + BinaryPrimitives.WriteUInt64LittleEndian(record, coffsetMod | (kdePredictor << 56)); + return record; + } + + // Signed 32-bit PFS with the encrypted mode bit set. Block 0 is the superblock, then the inode + // table, the root directory, then data (and indirect) blocks, optionally in scrambled order. + private static byte[] BuildOuterPfs(int blockSize, string seed, IReadOnlyList<(string Name, byte[] Data)> files, bool scramble) + { + const int InodeSize = 0x2C8; + const int Stride = 36; + var inodeCount = files.Count + 1; + var perInodeBlock = blockSize / InodeSize; + var tableBlocks = (inodeCount + perInodeBlock - 1) / perInodeBlock; + var pointersPerBlock = blockSize / Stride; + var dirBlock = 1 + tableBlocks; + var firstData = dirBlock + 1; + + var dataCounts = files.Select(file => (file.Data.Length + blockSize - 1) / blockSize).ToArray(); + var dataPool = Enumerable.Range(firstData, dataCounts.Sum()).ToList(); + if (scramble) + { + var random = new System.Random(77); + for (var i = dataPool.Count - 1; i > 0; i--) + { + var j = random.Next(i + 1); + (dataPool[i], dataPool[j]) = (dataPool[j], dataPool[i]); + } + } + + var next = firstData + dataPool.Count; + var extraBlocks = new List<(int Block, int[] Pointers)>(); + var inodePointers = new List<(int[] Direct, int[] Indirect)>(); + var poolAt = 0; + foreach (var (file, count) in files.Zip(dataCounts)) + { + var blocks = dataPool.GetRange(poolAt, count); + poolAt += count; + var direct = new int[12]; + var indirect = new int[5]; + for (var i = 0; i < Math.Min(12, count); i++) + { + direct[i] = blocks[i]; + } + + var rest = blocks.Skip(12).ToList(); + if (rest.Count > 0) + { + var single = rest.Take(pointersPerBlock).ToArray(); + indirect[0] = next++; + extraBlocks.Add((indirect[0], single)); + rest = rest.Skip(pointersPerBlock).ToList(); + } + + if (rest.Count > 0) + { + Assert.True(rest.Count <= pointersPerBlock * pointersPerBlock); + var leaves = new List<int>(); + for (var at = 0; at < rest.Count; at += pointersPerBlock) + { + var leaf = next++; + extraBlocks.Add((leaf, rest.Skip(at).Take(pointersPerBlock).ToArray())); + leaves.Add(leaf); + } + + indirect[1] = next++; + extraBlocks.Add((indirect[1], [.. leaves])); + } + + inodePointers.Add((direct, indirect)); + } + + var image = new byte[next * blockSize]; + // Superblock. + BinaryPrimitives.WriteUInt64LittleEndian(image, 2); + BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(8), Ps5OuterPfs.PfsMagic); + BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(0x1C), 0x5); // signed | encrypted + BinaryPrimitives.WriteUInt32LittleEndian(image.AsSpan(0x20), (uint)blockSize); + BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(0x30), (ulong)inodeCount); + BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(0x40), (ulong)tableBlocks); + BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(0xD8), 1); + Encoding.ASCII.GetBytes(seed).CopyTo(image, 0x370); + + void WriteInode(int index, long size, int[] direct, int[] indirect) + { + var at = blockSize + index / perInodeBlock * blockSize + index % perInodeBlock * InodeSize; + BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(at + 8), (ulong)size); + var pointers = direct.Concat(indirect).ToArray(); + for (var i = 0; i < pointers.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(image.AsSpan(at + 0x64 + i * Stride + 32), (uint)pointers[i]); + } + } + + WriteInode(0, blockSize, [dirBlock, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], new int[5]); + var entries = new List<(uint, uint, string)> { (0, 3, ".") }; + for (var i = 0; i < files.Count; i++) + { + WriteInode(i + 1, files[i].Data.Length, inodePointers[i].Direct, inodePointers[i].Indirect); + entries.Add(((uint)(i + 1), 2, files[i].Name)); + var blocks = dataPool.GetRange(dataCounts.Take(i).Sum(), dataCounts[i]); + var logicalBlocks = ResolveBlocks(inodePointers[i], extraBlocks, dataCounts[i], pointersPerBlock); + Assert.Equal(blocks, logicalBlocks); + for (var b = 0; b < logicalBlocks.Count; b++) + { + var length = Math.Min(blockSize, files[i].Data.Length - b * blockSize); + files[i].Data.AsSpan(b * blockSize, length).CopyTo(image.AsSpan(logicalBlocks[b] * blockSize)); + } + } + + DirectoryBlock(blockSize, [.. entries]).CopyTo(image, dirBlock * blockSize); + foreach (var (block, pointers) in extraBlocks) + { + for (var i = 0; i < pointers.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(image.AsSpan(block * blockSize + i * Stride + 32), (uint)pointers[i]); + } + } + + return image; + } + + // Reads the pointer structure back the way a reader would, so the builder checks itself. + private static List<int> ResolveBlocks((int[] Direct, int[] Indirect) inode, List<(int Block, int[] Pointers)> extra, int count, int perBlock) + { + var map = extra.ToDictionary(e => e.Block, e => e.Pointers); + var blocks = inode.Direct.Take(Math.Min(12, count)).ToList(); + if (blocks.Count < count) + { + blocks.AddRange(map[inode.Indirect[0]]); + } + + if (blocks.Count < count) + { + foreach (var leaf in map[inode.Indirect[1]]) + { + blocks.AddRange(map[leaf]); + } + } + + return blocks.Take(count).ToList(); + } + + private static Built BuildPackage(Spec spec) + { + const int Mount = 0x30000; + var logical = new byte[Mount]; + var expected = new Dictionary<string, byte[]>(StringComparer.Ordinal); + + void Place(string path, int offset, byte[] data) + { + data.CopyTo(logical, offset); + expected[path] = data; + } + + Place("eboot.bin", 0, Pattern(1, 0x2345)); + Place("sce_module/" + spec.ModuleFileName, 0x3000, Pattern(2, 0x123)); + // Crosses the boundary between the raw block and the Kraken block. + Place("assets/data.bin", 0x7F00, Pattern(3, 0x300)); + Place("assets/sub/deep.bin", 0x9000, Pattern(4, 0x10)); + expected["assets/sparse.bin"] = new byte[0x2000]; + expected["assets/empty.bin"] = []; + + // Inner metadata: superblock, one inode block, five directory blocks (0x1000 each). + var tail = new byte[0x10000]; + BinaryPrimitives.WriteUInt64LittleEndian(tail, 2); + BinaryPrimitives.WriteUInt64LittleEndian(tail.AsSpan(8), Ps5OuterPfs.PfsMagic); + BinaryPrimitives.WriteUInt16LittleEndian(tail.AsSpan(0x1C), 0x10); + BinaryPrimitives.WriteUInt32LittleEndian(tail.AsSpan(0x20), 0x1000); + BinaryPrimitives.WriteUInt64LittleEndian(tail.AsSpan(0x30), 11); + BinaryPrimitives.WriteUInt64LittleEndian(tail.AsSpan(0x38), Mount / 0x1000); + + const long TailBase = 0x20000; + void Inode(int index, ushort mode, long size, long where) + { + var at = 0x1000 + index * 0xA8; + BinaryPrimitives.WriteUInt16LittleEndian(tail.AsSpan(at), mode); + BinaryPrimitives.WriteUInt64LittleEndian(tail.AsSpan(at + 8), (ulong)size); + BinaryPrimitives.WriteUInt64LittleEndian(tail.AsSpan(at + 0x60), (ulong)where); + } + + const ushort DirMode = 0x41ED; + const ushort FileMode = 0x81A4; + Inode(0, DirMode, 0x1000, TailBase + 0x2000); + Inode(1, DirMode, 0x1000, TailBase + 0x3000); + Inode(2, FileMode, 0x2345, 0); + Inode(3, DirMode, 0x1000, TailBase + 0x4000); + Inode(4, FileMode, 0x123, 0x3000); + Inode(5, DirMode, 0x1000, TailBase + 0x5000); + Inode(6, FileMode, 0x300, 0x7F00); + Inode(7, DirMode, 0x1000, TailBase + 0x6000); + Inode(8, FileMode, 0x10, 0x9000); + Inode(9, FileMode, 0x2000, 0x10000); + Inode(10, FileMode, 0, 0); + DirectoryBlock(0x1000, (0, 3, "."), (0, 3, ".."), (1, 3, "uroot"), (2, 2, "readme")).CopyTo(tail, 0x2000); + // Real packages type "." and ".." as PFS self (4) and parent (5) records. + DirectoryBlock(0x1000, (1, 4, "."), (0, 5, ".."), (2, 2, "eboot.bin"), (3, 3, "sce_module"), (5, 3, "assets")).CopyTo(tail, 0x3000); + DirectoryBlock(0x1000, (3, 3, "."), (1, 3, ".."), (4, 2, spec.ModuleFileName)).CopyTo(tail, 0x4000); + DirectoryBlock(0x1000, (5, 3, "."), (1, 3, ".."), (6, 2, "data.bin"), (7, 3, "sub"), (9, 2, "sparse.bin"), (10, 2, "empty.bin")) + .CopyTo(tail, 0x5000); + DirectoryBlock(0x1000, (7, 3, "."), (5, 3, ".."), (8, 2, "deep.bin")).CopyTo(tail, 0x6000); + tail.CopyTo(logical, (int)TailBase); + + // Stored image: raw block [0, 0x8000), a Kraken block for [0x8000, 0x10000), a sparse hole + // for [0x10000, 0x20000) and the raw metadata tail. + var kraken = KrakenLiteralChunk(logical[0x8000..0x10000]); + var stored = new List<byte>(); + stored.AddRange(logical[..0x8000]); + stored.AddRange(kraken); + stored.AddRange(logical[0x20000..]); + var image = stored.ToArray(); + + // NAPS: header, one outer digest, five file-offset entries, u2c, four CblockInfo records. + var naps = new byte[100]; + BinaryPrimitives.WriteUInt64LittleEndian(naps, 4UL | (2UL << 24) | (3UL << 32)); + BinaryPrimitives.WriteUInt64LittleEndian(naps.AsSpan(8), 1UL | (2UL << 24)); + var boundaries = new (int Offset, byte Kind)[] { (0, 0), (0x8000, 0), (0x10000, 0x40), (0x20000, 0), (Mount, 0x40) }; + for (var i = 0; i < boundaries.Length; i++) + { + var at = 24 + i * 6; + for (var b = 0; b < 4; b++) + { + naps[at + b] = (byte)(boundaries[i].Offset >> (8 * b)); + } + + naps[at + 5] = boundaries[i].Kind; + } + + var krakenEnd = 0x8000 + kraken.Length; + CblockRecord(0, 0).CopyTo(naps, 64); + CblockRecord(0x8000, 2).CopyTo(naps, 73); + CblockRecord((uint)(krakenEnd & 0x3FFFF), 0).CopyTo(naps, 82); + CblockRecord((uint)((krakenEnd + 0x10000) & 0x3FFFF), 0).CopyTo(naps, 91); + + var pfs = BuildOuterPfs(0x10000, spec.Seed, [("pfs_image.dat", image), ("naps_pkg_layout.dat", naps)], scramble: true); + + // CNT: entries, then the names table, then the data they point at. + var cntFiles = new List<(uint Id, uint NameAt, uint Flags, byte[] Data)>(); + var names = new MemoryStream(); + names.WriteByte(0); + uint AddName(string name) + { + var at = (uint)names.Length; + names.Write(Encoding.UTF8.GetBytes(name)); + names.WriteByte(0); + return at; + } + + cntFiles.Add((0x0001, 0, 0, [1, 2, 3])); + cntFiles.Add((0x0100, 0, 0, [4, 5, 6])); + cntFiles.Add((0x0400, 0, 0x80000000, [7, 7, 7, 7])); + cntFiles.Add((0x1200, 0, 0, Pattern(20, 300))); + cntFiles.Add((0x1220, 0, 0, [])); + cntFiles.Add((0x7777, 0, 0, [9, 9])); + var sceSys = new Dictionary<string, byte[]> { ["icon0.png"] = cntFiles[3].Data }; + if (spec.ParamJson is { } json) + { + var bytes = Encoding.UTF8.GetBytes(json); + cntFiles.Add((0x2000, AddName("/sce_sys/param.json"), 0, bytes)); + sceSys["param.json"] = bytes; + } + + var playgo = Pattern(21, 40); + cntFiles.Add((0x1001, AddName("playgo-chunk.dat"), 0, playgo)); + sceSys["playgo-chunk.dat"] = playgo; + if (spec.ExtraCntName is { } extra) + { + cntFiles.Add((0x2011, AddName(extra), 0, [1, 2, 3])); + } + + cntFiles.Add((0x0200, 0, 0, names.ToArray())); + foreach (var (name, bytes) in sceSys) + { + expected["sce_sys/" + name] = bytes; + } + + const int TableAt = 0x100; + var dataAt = TableAt + cntFiles.Count * 0x20; + var cnt = new byte[dataAt + cntFiles.Sum(file => file.Data.Length)]; + BinaryPrimitives.WriteUInt32BigEndian(cnt, PkgHeader.Magic); + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(0x10), (uint)cntFiles.Count); + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(0x18), TableAt); + BinaryPrimitives.WriteUInt64BigEndian(cnt.AsSpan(0x28), (ulong)cnt.Length); + Encoding.ASCII.GetBytes(spec.ContentId).CopyTo(cnt, 0x40); + for (var i = 0; i < cntFiles.Count; i++) + { + var (id, nameAt, flags, data) = cntFiles[i]; + var row = TableAt + i * 0x20; + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(row), id); + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(row + 4), nameAt); + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(row + 8), flags); + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(row + 16), (uint)dataAt); + BinaryPrimitives.WriteUInt32BigEndian(cnt.AsSpan(row + 20), (uint)data.Length); + data.CopyTo(cnt, dataAt); + dataAt += data.Length; + } + + const int PfsAt = 0x10000; + var package = new byte[PfsAt + pfs.Length + cnt.Length]; + package[0] = 0x7F; + package[1] = 0x46; + package[2] = 0x49; + package[3] = 0x48; + package[5] = spec.RetailByte; + BinaryPrimitives.WriteUInt16LittleEndian(package.AsSpan(6), 1); + BinaryPrimitives.WriteUInt64LittleEndian(package.AsSpan(0x10), PfsAt); + BinaryPrimitives.WriteUInt64LittleEndian(package.AsSpan(0x18), (ulong)pfs.Length); + BinaryPrimitives.WriteUInt64LittleEndian(package.AsSpan(0x20), PfsAt); + BinaryPrimitives.WriteUInt64LittleEndian(package.AsSpan(0x58), (ulong)(PfsAt + pfs.Length)); + BinaryPrimitives.WriteUInt64LittleEndian(package.AsSpan(0xA0), (ulong)cnt.Length); + pfs.CopyTo(package, PfsAt); + cnt.CopyTo(package, PfsAt + pfs.Length); + + var gameBytes = expected.Where(pair => !pair.Key.StartsWith("sce_sys/", StringComparison.Ordinal)).Sum(pair => (long)pair.Value.Length); + return new Built(package, expected, gameBytes); + } + + private static Dictionary<string, byte[]> ReadTree(string root) + { + var tree = new Dictionary<string, byte[]>(StringComparer.Ordinal); + foreach (var path in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)) + { + tree[Path.GetRelativePath(root, path).Replace('\\', '/')] = File.ReadAllBytes(path); + } + + return tree; + } + + private static InvalidDataException OpenFails(byte[] bytes) + { + InvalidDataException? caught = null; + WithFile(bytes, path => caught = Assert.Throws<InvalidDataException>(() => Ps5Package.Open(path).Dispose())); + return caught!; + } + + private static void WithFile(byte[] bytes, Action<string> action, string extension = ".pkg", Action<string>? afterWrite = null) + { + var path = Path.Combine(Path.GetTempPath(), $"sharpemu-ps5pkg-{Guid.NewGuid():N}{extension}"); + try + { + File.WriteAllBytes(path, bytes); + afterWrite?.Invoke(path); + action(path); + } + finally + { + File.Delete(path); + } + } + + private static void WithPackage(byte[] bytes, Action<Ps5Package, string> action) + { + var destination = Path.Combine(Path.GetTempPath(), $"sharpemu-ps5pkg-out-{Guid.NewGuid():N}"); + try + { + WithFile(bytes, path => + { + using var package = Ps5Package.Open(path); + action(package, destination); + }); + } + finally + { + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + } + } + + private sealed class CollectingProgress<T>(Action<T> handler) : IProgress<T> + { + public void Report(T value) => handler(value); + } +} From 9a64b459893cb98fa1510b98c6941db625b6ddff Mon Sep 17 00:00:00 2001 From: Foued Attar <attar.foued@gmail.com> Date: Fri, 20 Nov 2026 23:16:39 +0100 Subject: [PATCH 05/64] Fix/pkg install adds only the game (#1158) * [GUI] Add only the installed game to the library after a PKG install Install PKG added the whole destination folder to the library, so every other game already in it showed up too. Add the game's own folder instead, unless a library folder already covers it. * [GUI] Recognise extracted PS5 games when installing a folder of PKGs The already-installed check only read sce_sys/param.sfo, which PS5 games do not have, so Add folder extracted their packages again. Fall back to the titleId of sce_sys/param.json. --- src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs | 88 ++++++++++++++----- .../GUI/PkgInstallLibraryFolderTests.cs | 47 ++++++++++ 2 files changed, 115 insertions(+), 20 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/GUI/PkgInstallLibraryFolderTests.cs diff --git a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs index edaa5e0d6..99dae602d 100644 --- a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs +++ b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs @@ -95,7 +95,7 @@ private void InitializeLibraryToolbar() UpdateSearchExpanded(); } - // Unpacks a fake .pkg into <chosen folder>/<game title>, then adds the chosen folder to the library. + // Unpacks a fake .pkg into <chosen folder>/<game title>, then adds that game folder to the library. private async Task InstallPkgAsync() { var loc = Localization.Instance; @@ -245,7 +245,7 @@ await Task.Run(() => } // Title id -> folder of every game already extracted under `root` (a folder with eboot.bin and - // sce_sys/param.sfo), searched as deep as the package scan. + // sce_sys/param.sfo or param.json), searched as deep as the package scan. private static Dictionary<string, string> FindInstalledTitles(string root) { var titles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); @@ -260,16 +260,9 @@ private static Dictionary<string, string> FindInstalledTitles(string root) })) { var directory = Path.GetDirectoryName(eboot)!; - try - { - var sfo = File.ReadAllBytes(Path.Combine(directory, "sce_sys", "param.sfo")); - if (PkgParamSfo.ReadString(sfo, "TITLE_ID") is { Length: > 0 } titleId) - { - titles.TryAdd(titleId, directory); - } - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + if (ReadInstalledTitleId(directory) is { } titleId) { + titles.TryAdd(titleId, directory); } } } @@ -280,6 +273,39 @@ private static Dictionary<string, string> FindInstalledTitles(string root) return titles; } + // TITLE_ID of an extracted game: sce_sys/param.sfo for PS4, sce_sys/param.json for PS5. + internal static string? ReadInstalledTitleId(string gameDirectory) + { + var sceSys = Path.Combine(gameDirectory, "sce_sys"); + try + { + var sfoPath = Path.Combine(sceSys, "param.sfo"); + if (File.Exists(sfoPath) && + PkgParamSfo.ReadString(File.ReadAllBytes(sfoPath), "TITLE_ID") is { Length: > 0 } sfoTitleId) + { + return sfoTitleId; + } + + var jsonPath = Path.Combine(sceSys, "param.json"); + if (File.Exists(jsonPath)) + { + using var document = System.Text.Json.JsonDocument.Parse(File.ReadAllBytes(jsonPath)); + if (document.RootElement.ValueKind == System.Text.Json.JsonValueKind.Object && + document.RootElement.TryGetProperty("titleId", out var titleId) && + titleId.ValueKind == System.Text.Json.JsonValueKind.String && + titleId.GetString() is { Length: > 0 } jsonTitleId) + { + return jsonTitleId; + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or System.Text.Json.JsonException) + { + } + + return null; + } + private void ReportSkippedNotGame(string pkgPath, string? category) => AppendConsoleLine( Localization.Instance.Format("Library.Pkg.SkippedNotGame", Path.GetFileName(pkgPath), category ?? string.Empty), @@ -311,24 +337,46 @@ private bool TryReadPackageInfo(string pkgPath, out string titleId, out string f private async Task<bool> InstallPackageIntoAsync(string pkgPath, string parent, string folderName) { var destination = Path.Combine(parent, folderName); - if (File.Exists(Path.Combine(destination, "eboot.bin"))) + if (!File.Exists(Path.Combine(destination, "eboot.bin"))) { - return true; // Already installed; the folder scan will pick it up. + var dialog = new PkgInstallDialog(Path.GetFileName(pkgPath), pkgPath, destination); + if (await Sheets.ShowAsync(dialog) is not true) + { + return false; + } } - var dialog = new PkgInstallDialog(Path.GetFileName(pkgPath), pkgPath, destination); - if (await Sheets.ShowAsync(dialog) is not true) + AddInstalledGameToLibrary(destination); + return true; + } + + // Adds only the installed game's folder, not its parent: the parent may hold other games the + // user never added. Nothing changes when a library folder already covers the game. + private void AddInstalledGameToLibrary(string gameFolder) + { + if (IsUnderLibraryFolder(_settings.GameFolders, gameFolder)) { - return false; + return; } - if (!_settings.GameFolders.Contains(parent, GameLibraryPath.Comparer)) + _settings.GameFolders.Add(Path.TrimEndingDirectorySeparator(Path.GetFullPath(gameFolder))); + _settings.Save(); + } + + internal static bool IsUnderLibraryFolder(IEnumerable<string> libraryFolders, string path) + { + var target = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + foreach (var folder in libraryFolders) { - _settings.GameFolders.Add(parent); - _settings.Save(); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + if (string.Equals(target, root, GameLibraryPath.Comparison) || + target.StartsWith(root + Path.DirectorySeparatorChar, GameLibraryPath.Comparison)) + { + return true; + } } - return true; + return false; } private void OpenLibraryMenu() diff --git a/tests/SharpEmu.Libs.Tests/GUI/PkgInstallLibraryFolderTests.cs b/tests/SharpEmu.Libs.Tests/GUI/PkgInstallLibraryFolderTests.cs new file mode 100644 index 000000000..220944c24 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/GUI/PkgInstallLibraryFolderTests.cs @@ -0,0 +1,47 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.GUI; +using Xunit; + +namespace SharpEmu.Libs.Tests.GUI; + +public sealed class PkgInstallLibraryFolderTests +{ + private static readonly string Root = Path.Combine(Path.GetTempPath(), "sharpemu-library"); + + [Fact] + public void AGameUnderALibraryFolderIsAlreadyCovered() + { + var game = Path.Combine(Root, "Games", "Some Game"); + Assert.True(MainWindow.IsUnderLibraryFolder([Path.Combine(Root, "Games")], game)); + Assert.True(MainWindow.IsUnderLibraryFolder([game + Path.DirectorySeparatorChar], game)); + } + + [Fact] + public void ASiblingFolderWithTheSamePrefixIsNotCovered() + { + var library = Path.Combine(Root, "Games"); + Assert.False(MainWindow.IsUnderLibraryFolder([library], Path.Combine(Root, "Games2", "Some Game"))); + Assert.False(MainWindow.IsUnderLibraryFolder([], Path.Combine(library, "Some Game"))); + } + + [Fact] + public void AnExtractedPs5GameIsFoundThroughItsParamJson() + { + var game = Path.Combine(Path.GetTempPath(), $"sharpemu-installed-{Guid.NewGuid():N}"); + try + { + Directory.CreateDirectory(Path.Combine(game, "sce_sys")); + File.WriteAllText(Path.Combine(game, "sce_sys", "param.json"), """{ "titleId": "PPSA37001" }"""); + Assert.Equal("PPSA37001", MainWindow.ReadInstalledTitleId(game)); + + File.WriteAllText(Path.Combine(game, "sce_sys", "param.json"), "not json"); + Assert.Null(MainWindow.ReadInstalledTitleId(game)); + } + finally + { + Directory.Delete(game, recursive: true); + } + } +} From 957d1dc905579b49940e82e51231de256f16076e Mon Sep 17 00:00:00 2001 From: Usif <19160089+Im-Usif@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:01:32 +0300 Subject: [PATCH 06/64] [GPU] Find a texture read as a volume again instead of making a new image each time (#1171) A program can read a two-dimensional texture as a volume. The lookup found the texture's image, set it aside because a volume view needs a 3D image, and made a new one from the texture's description, which is two-dimensional again. Each lookup made another image: a bindless heap that looks the texture up every frame filled video memory until the game crashed, out of device memory or at 127 write watches on a page. Only a volume request now replaces an image for a volume view. Any other request keeps the image it found, and the caller rejects the view as before. --- .../Gpu/Images/GuestImageCache.cs | 5 ++- .../Images/GuestImageCacheTests.ImageTypes.cs | 31 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs index 9c14dabca..1988b337a 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs @@ -324,7 +324,10 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF : InsertDimensionTwin(replacement, resolved) : GrowImage(replacement, result); } - else if (request.View.Type == ImageViewType.Type3D && resolved.Backing.ImageType != ImageType.Type3D) + // A volume view needs a 3D image, and only a volume request makes one: an image made from any other request + // would not be 3D either, so each lookup would make another image that never serves the view. + else if (request.View.Type == ImageViewType.Type3D && resolved.Backing.ImageType != ImageType.Type3D && + request.Description.IsVolume) { result = ResourceSlotIdentifier.Invalid; viewMip = -1; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs index 66b13cfbd..4b1d230c6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs @@ -215,6 +215,37 @@ public void SingletonVolumeKeepsItsCompatibleTwoDimensionalView() harness.Shutdown(); } + // A program can read a two-dimensional texture as a volume. Its image is not 3D, and an image made from the texture's + // description would not be either: the lookup finds the same image again instead of making a new one each time. + [Fact] + public void TwoDimensionalTextureReadAsVolumeIsFoundAgain() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x10000, ReadWrite); + var request = VolumeViewOfTexture(address); + var imageIdentifier = harness.Find(ref request); + var images = harness.Images.ImageCount; + + for (var lookup = 0; lookup < 3; lookup++) + { + var again = VolumeViewOfTexture(address); + Assert.Equal(imageIdentifier, harness.Find(ref again)); + } + + Assert.Equal(images, harness.Images.ImageCount); + Assert.False(harness.Image(imageIdentifier).SupportsViewType(request.View)); + harness.Shutdown(); + } + + private static ImageRequest VolumeViewOfTexture(ulong address) + { + var request = LinearRequest(address, 64 * 64 * sizeof(uint), Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, + new Extent3D(64, 64, 1), 1, sizeof(uint), 1); + request.View = request.View with { Type = ImageViewType.Type3D }; + return request; + } + private static ImageRequest SingletonRequest(ulong address, uint layers, bool twoDimensions) { var request = LinearRequest(address, layers * 256ul, Format.R32Uint, GuestPixelFormat.Bits32UInt, From 96a4c7de613c55187af98492eafcdb14d454e725 Mon Sep 17 00:00:00 2001 From: "Ainesh M." <236408161+Kuaryn@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:41:13 +0000 Subject: [PATCH 07/64] [GPU] Keep the stage preparation of programs that read the bindless heap (#1159) A stage that reads the bindless heap was never memoized, so every draw and dispatch of such a program resolved all of its own images, samplers and buffers again on the render thread, although they are found the same way as for any other stage. The heap and its views are prepared before the memo is looked up; a reuse now writes this draw's heap views into the shader data as the full path does. Stages with call records still prepare in full, since their records are made per draw. Ghost of Yotei on main: ~520 of the ~690 full preparations per frame on the render thread were heap stages (~13 us each). (cherry picked from commit bf84d8be2d7ebdea44ef39c267fabfe2ced0181b) --- .../VulkanVideoPresenter.Descriptors.cs | 10 +++- .../RenderHostDeviceTests.StagePreparation.cs | 57 +++++++++++++++++++ 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index b0a2286f4..5160ffa76 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -492,7 +492,7 @@ private uint[] AssembleShaderData(ShaderStageResources stage, ShaderProgramInfo } private PreparedStageBindings ReuseStagePreparation(RenderPreparation preparation, ShaderStageResources stage, ShaderProgramInfo program, - StagePreparationMemo memo) + StagePreparationMemo memo, ReadOnlySpan<uint> heapViews) { var prepared = RentStage(stage, program); prepared.Memoized = true; @@ -515,6 +515,7 @@ private PreparedStageBindings ReuseStagePreparation(RenderPreparation preparatio var layout = program.Bindings!; prepared.ShaderData = AssembleShaderData(stage, program, layout); + heapViews.CopyTo(prepared.ShaderData.AsSpan((int)layout.HeapViewsDword)); if (layout.Find(DescriptorBindingKind.GlobalDataShare) is not null) { descriptors.GlobalDataShare = new BufferView(_bufferCache.GdsBuffer.Handle, 0, Vk.WholeSize); @@ -1008,7 +1009,7 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) if (frontendReady && !movieActive && !Gpu.Images.ImageClearTrace.Enabled && !MeshDrawTrace.Active && TryFindStagePreparation(preparations, snapshot, stage.ShaderBase, out var memo)) { - return ReuseStagePreparation(preparation, stage, program, memo); + return ReuseStagePreparation(preparation, stage, program, memo, heapViews); } Interlocked.Increment(ref _stageMemoMisses); @@ -1070,7 +1071,10 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) FindBuffers(prepared); using (DescriptorStallProfile.Measure(DescriptorStallProfile.Operation.ValidateImages, program.Hash, info.Buffers.Count, info.Images.Count, info.Samplers.Count)) ValidateDrawImageTypes(prepared); - if (!movieActive && layout.CallTargetCount == 0 && layout.CallArgumentCount == 0 && !layout.UsesBindlessHeap) + // A stage that reads the bindless heap is kept like any other: the heap and its views were prepared above, before + // the memo is looked up, and a reuse writes this draw's views. Call records are made per draw, so their stages are not. + if (!movieActive && layout.CallTargetCount == 0 && layout.CallArgumentCount == 0 && + (!layout.UsesBindlessHeap || program.CallRecordCallees.Count == 0)) { if (frontendReady) NoteStagePreparation(preparations, prepared, snapshot, stage.ShaderBase); diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs index 7402a9175..935ba4775 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs @@ -47,4 +47,61 @@ public void StagePreparation_RecapturedBindingsSurviveSubmissionRecycling() Assert.Empty(fatal.Messages); presenter.Harness.Shutdown(); } + + // A stage that reads the bindless heap keeps its preparation like any other stage, and a reuse carries the heap views + // this draw named into the shader data. + [Fact] + public void StagePreparation_ABindlessHeapStageIsReusedWithItsHeapViews() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + // Stand-ins for the heap set (the test device has no descriptor indexing) and a feedback copy in flight, so preparing + // the heap only reads its views. + presenter.SetField("_heapSet", new Silk.NET.Vulkan.DescriptorSet(1)); + presenter.SetField("_heapFeedbackCopyPending", 1); + foreach (var name in new[] { "_heapChangedImages", "_heapRegionEntries", "_callRecordEntries" }) + { + presenter.SetField(name, Activator.CreateInstance(PresenterUnderTest.PresenterType.GetField(name, HostMembers)!.FieldType)!); + } + + presenter.SetField("_heapImageViews", new SharpEmu.Libs.VideoOut.BindlessHeapViewTable(BindlessHeap.CallRecordFirstIndex)); + try + { + var program = FixedProgramProvider.EmptyProgram(ShaderStageKind.Compute, 0xB7, + new ShaderResourceInfo { Images = [SampledImage], UsesBindlessHeap = true, HeapViewCount = 1 }); + var layout = program.Bindings!; + var snapshot = new ResourceSnapshot + { + Images = [new uint[8]], + Heaps = [new BindlessHeapDescriptor(false, 0x4000_0000, 64, BindlessHeap.ImageRecordBytes)], + }; + (bool Memoized, uint[] Views) Prepare() => presenter.Run(() => + { + presenter.RenderHost.ResetBindings(); + using var preparation = presenter.RenderHost.BeginPreparation(); + var prepared = presenter.RenderHost.PrepareBindings(new ShaderStageResources(program, snapshot, 0x1000)); + presenter.RenderHost.BindResources(prepared); + var shaderData = (uint[])prepared.GetType().GetProperty("ShaderData", HostMembers)!.GetValue(prepared)!; + return ((bool)prepared.GetType().GetProperty("Memoized", HostMembers)!.GetValue(prepared)!, + shaderData.AsSpan((int)layout.HeapViewsDword, (int)HeapView.DwordCount).ToArray()); + }); + + var first = Prepare(); + var second = Prepare(); + Assert.False(first.Memoized); + Assert.NotEqual([HeapView.None.Word0, HeapView.None.Word1], first.Views); + Assert.True(second.Memoized); + Assert.Equal(first.Views, second.Views); + Assert.Empty(fatal.Messages); + } + finally + { + presenter.SetField("_heapSet", default(Silk.NET.Vulkan.DescriptorSet)); + presenter.SetField("_heapFeedbackCopyPending", 0); + } + + presenter.Harness.Shutdown(); + } } From cb790c35e46b4abe83670ec77080d2290768a7fb Mon Sep 17 00:00:00 2001 From: Usif <19160089+Im-Usif@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:25:54 +0300 Subject: [PATCH 08/64] [GPU/Audio/Pad/Memory] Demon's Souls: performance, crash, audio and graphics fixes, DualSense speaker and vibration (#1172) * [GPU] Reuse the previous draw's record for a repeated indirect draw Games often issue indexed indirect draws back to back with no register written in between. In a heavy scene about half of the deferred draws are such repeats, and each still resolved in full on a resolve worker. Such a draw now goes to the worker that resolved the previous one and takes that record with its own arguments, read on the CPU when the previous draw's were. The previous draw's read log and image version go with it, so the stream position checks the same bytes, and it marks its own pending writes. It resolves in full when shader registrations moved or its arguments take another path. * [AJM] Count the gapless window from the last reset, so a new window set without a reset takes effect * [AJM] Restart the gapless window at a stream's RIFF header and report empty jobs as partial input A looping voice rewinds to its file header without initializing the instance. The header's fact chunk now restarts the window (its sample count and lead-in, with the codec and the decoded-sample count starting over), as when the hardware parses the header, and the header check comes before the stop on an exhausted window. Before, a window the previous pass used up kept the voice silent for good while the title kept feeding it. A job without input reports partial input. * [AJM] Take the codec configuration from a stream's RIFF header A title that has AJM parse ATRAC9 RIFF headers can feed the next file through the same instance without initializing it. The format chunk's codec configuration (the ATRAC9 subformat's four bytes at offset 44) now starts the codec fresh with that configuration, adopting it when it differs, and the decode loop takes the new superframe size and channel count from there. Before, a file with another configuration was decoded with the previous file's, and every superframe failed as invalid data. * [LibAtrac9] Clamp the fine precision at 15, the last entry of the step size table A quantization unit with a high scale factor plus the gradient boundary's boost reached a precision above 30, so its fine precision indexed past the 16-entry step size table and the superframe threw. The precision is now clamped to 30 before the fine part is taken. * [AJM] Conceal a superframe the ATRAC9 decoder rejects with silence A decode exception used to fail the job; the game then zeroes its counts and retries the same input forever, which leaves the voice stuck. For AJM the superframe now plays as silence, the codec state is rebuilt from the configuration, and the job goes on. Ngs2 and the codec library keep reporting the error, as their callers expect. * [AJM] Check the output room before an ATRAC9 superframe's bytes are taken A superframe the output had no room for was copied in and reported consumed with nothing produced for it, then decoded at the start of the next job. It now stays in the input, as the codec leaves it. * [AudioOut2] Decode first-order ambisonic objects with two virtual microphones facing 74 degrees The stereo decode used cardioids facing 90 degrees (W and Y alone): sources ahead played 3 dB below those at the sides, and a scene's diffuse sound (its room and reverb) came out about 2 dB louder against the direct sound than with X included. The weights W 0.85355339, Y 0.52100538 and X 0.14644661 keep a source ahead at full level on both sides, one behind at -3 dB and one at the side at the power it has ahead. FuMa W (MaxN) takes sqrt(2) times the SN3D weight. * [AudioOut2] Output the context mix as float when the host takes float streams The context mix was clipped to full scale and converted to 16-bit before the host applied its volume, so every peak above full scale was cut in our code (Demon's Souls' gameplay mix reaches +5 dBFS). A host that accepts float streams (SDL3, the Windows and Linux backend) now gets the mix as float, bounded only at +-4 (+12 dBFS), and its float mixer applies the volume before the device clips. The queue cap keeps the 16-bit stream's duration (256 KiB of float stereo). Hosts without float streams keep the 16-bit path. * [AudioOut2] Play the pad speaker and vibration ports on a wired DualSense A DualSense on USB is a four-channel output device: its speaker (or a headset in the pad) on the front pair, its two actuators on the back pair. The pad speaker port now plays on the front pair, with the pad's output report routing that pair to the speaker (restored on close), and the vibration port on the actuators. A pad speaker port that plays there reports the controller speaker as its output. Only one wired DualSense with one matching four-channel device is used, since SDL ties no gamepad to its audio device. The controller stream drops its oldest audio past 80 ms instead of blocking the guest. Without such a pad both ports stay silent, as before. * [Memory] A partial unmap keeps the page access of the view parts it maps again Unmapping part of a backed view unmaps the whole view and maps the parts on either side again with the view's protection. That dropped every access change made on their pages since: the GPU memory page watches and a guest mprotect. A guest store to a GPU-owned page then landed without a fault, and a later download wrote the GPU bytes over it. In Demon's Souls this corrupted resource tables and crashed the game's allocator. The view's page access is now read before the unmap (VirtualQuery on Windows, the region table on Posix). A part mapped again loses write in one change, so no store lands unseen, and then each run of pages gets its access back; a page the host cannot describe takes the view's protection. A part whose pages all had the view's protection is left as it was mapped. * [ShaderCompiler] V_CVT_PKRTZ_F16_F32 saturates finite overflow at 65504 and keeps NaN, as rounding toward zero does The pack cleared the mantissa bits a half cannot hold and then packed with round-to-nearest, which still turned a finite value of 65536 or more into infinity. Rounding toward zero gives the largest finite half for it, and a NaN keeps its bits. An infinity in packed lighting data never decays; a lighting pass that feeds back into itself spreads it frame after frame. * [AJM] Run batches on a host thread between sceAjmBatchStart and sceAjmBatchWait, as the decoder hardware does Demon's Souls starts each grain's ATRAC9 batch and waits for it a grain later. Decoding every job while it was added put all of it on the thread that renders the audio, which then fell behind the device. Jobs now run in order on one AJM thread after Start, and Wait collects them, or returns the in-progress error when its timeout passes first. Buffer descriptors and parameters are read when a job is added, and teardown waits for started batches. AJM tracing no longer formats strings or reads the environment per call when it is off. * [Kernel/AudioOut2] An audio producer that runs behind the device naps for the time it asks A usleep above the spin limit waits on the host timer, which rounds a 51 us nap (an idle job worker's nap) up to about 0.5 ms. A producer that naps between the jobs of each grain then falls behind the device. A thread that pushed into an AudioOut2 context within the last 20 ms, while the device holds less than its cushion less one grain, now spins for naps of up to 1 ms instead. Other threads, longer sleeps and a device at its cushion keep the timer wait. * [GPU] Land a release after the older compute submissions that can still run The GPU runs every queue at once, so by the time an end-of-pipe label lands, the compute work submitted before it has run as far as its own waits let it, and the CPU may reuse that work's memory as soon as it sees the label. The command stream runs one queue at a time and could land a graphics release before an earlier compute submission had read its resource tables or written its outputs. A game that frees a frame's transient memory on its frame label then had that compute work read reused memory as descriptor tables. A release the CPU can observe (a label write or an interrupt) now waits while an older submission of another compute queue can still run, and those run first without soft waits. Blocked work never holds the release. Only its first wait retries the blocked heads, so two waiting releases cannot hold each other, and it lands after 256 checks at the same packet at most. * [GPU] Read pages with a queued fill or copy through the ordered path On the command stream thread and the resolve workers, a read of a clean page takes its bytes straight from guest memory. A page with a queued store already reads through the ordered path, but a page under a queued fill or copy that had not landed yet still read its old bytes. Such a page now reads through the ordered path too, which refuses the bytes or waits for the range, as it does for a queued store. * [GPU] Apply every pending GPU-write protection before a command stream store A command stream store can be an end-of-pipe label that tells the guest that earlier GPU writes are done. Their pages block CPU reads only once their deferred protection is applied, and a store applied it only after a copy or fill; pages a shader wrote waited for the next submission. A guest that saw the label could read them in between and get the bytes from before the write. In Demon's Souls, objects went missing for single frames. A store now applies every pending protection first, shader writes included, and the flag that tracked copies is gone. * [ShaderCompiler] Programs before rasterization keep each float rounding A game can draw a mesh twice: a depth prepass, then a pass that tests for equal depth and writes the G-buffer and stencil. The two passes run different vertex programs that compute the same position, and the guest GPU rounds every multiply and add the same way in both. A Vulkan driver may fuse a multiply with an add, or split a fused multiply-add, and decide differently in each pipeline. A vertex then moves by an ulp in only one pass, its triangles fail the equal test, and the lighting pass skips the pixels they leave without stencil. In Demon's Souls, fern fronds flickered black as the wind moved them. Vertex, mesh and tessellation evaluation programs now decorate every float add, subtract, multiply and fused multiply-add with NoContraction. Pixel and compute programs keep the driver's freedom. * [Core] Guest code starts with the console's floating-point environment The console starts its threads with MXCSR 0x9FC0 (every exception masked, round to nearest, flush-to-zero and denormals-are-zero) and the x87 control word 0x037F, the values its libc keeps as the default environment; fibers that ask for fresh FPU registers already got them here. A guest thread was entered with the host thread's state instead: Windows' MXCSR 0x1F80 keeps denormals and its x87 0x027F rounds to 53 bits. Guest float code then kept values the console flushes to zero and differed from it in the last bits. The guest entry stubs now save the host's MXCSR and x87 control word in the host state block and load the guest context's; every way back to the host restores the host's, whose control bits are callee-saved. * [Pad] scePadRead returns every state since the last read A read returned only the state at that moment. A press and its release between two reads never reached a game that takes each state's presses and releases, as Demon's Souls does with up to 64 states a frame: at a low frame rate a quick tap was lost, and a gamepad tap inside one poll of the window was lost before the pad saw it. The window's key, focus and gamepad button events, with SDL's queued gamepad button and trigger events, now record the pad's state after each change of a button or a touch contact, keeping the last 64 as the console does. Each pad handle reads the states it has not read, oldest first, then the current state when room is left, so the last state is always the newest. With no change since the last read it gets the current state alone, as before. * [GPU] Sample a depth surface's pending HTile clear as the cleared value A compute pass that writes a depth surface's HTile leaves its clear pending until the surface is next bound as a depth target, whose load then clears it. A surface sampled before that bind kept its older contents, where the console's texture unit reads the cleared value through the HTile. A game that clears an occlusion depth this way each frame and builds its culling pyramid from it then culled with the occluders of the last frame that drew any. A sample of a one-layer, one-level depth surface with a pending clear now clears it first, with the clear value of the surface's last depth-target bind (the value that bind would load), and consumes the clear. A recording worker leaves such a sample to the render thread. A layered surface keeps its pending clear for its next bind, as its clear bits are not exact per layer. * [GPU] Don't view an image of the other block class whose levels lie elsewhere A lookup at the address of a cached image with the same block grid and block size returned that image when one side was block-compressed and the other not: viewed in the requested format, or copied across. That is right for a compressor's view of a texture's blocks, which has the same tiling and places every level the same. When the memory holds another resource instead, such as a one-level image where a mipmapped texture was, the texture's level 0 lies after its smaller levels, and the request read and wrote the old texture's bytes instead of its own. Such an overlap is now handled as any layout mismatch: the cached image is parked or released once it is stale, and the requested image is made from guest memory. * [UserService] Report the standard trigger effect intensity The trigger effect intensity setting returned 0, which tells a game that the user turned trigger effects off, so a game that honors the setting never sent its adaptive trigger effects. It now returns 1, the standard intensity a console starts with, as the vibration intensity already does. * [Pad] Report the trigger effect state from the effect the game set scePadGetTriggerEffectState always reported no effect, so a game that waits for a weapon or feedback state before it acts on L2 or R2 never saw the trigger engage. The pad now keeps each trigger's last effect and reports its state from that effect and the trigger's travel (standby, pushing, pulling, fired or firing), as a DualSense reports it. * [Pad] Accumulate the controller's orientation from its gyro, with reset and tilt correction The pad data always reported an identity orientation, and scePadResetOrientation and scePadSetTiltCorrectionState did nothing, so a game that reads the orientation for motion controls saw the controller lying still. Each gyro reading from SDL now turns the orientation over its own interval since the previous one, from when the controller connected or the game last reset it. With tilt correction on (off until the game enables it), gravity pulls pitch and roll back toward the measured down direction. * [AudioOut] Play the pad speaker and vibration ports on the controller, not the speakers sceAudioOutOpen opened every port on the main output, so a game that sends its controller speaker or haptics through these ports played them on the speakers. Pad speaker ports now play on a wired DualSense's speaker pair and vibration ports on its actuators, paced in real time because the controller stream drops instead of blocking. Without such a pad both stay silent. * [ShaderCompiler] Count NGG vertex lanes up to the highest active host lane * [GPU] Keep span set nodes immutable * [GPU] Publish the span set tree for lock-free overlap reads * [GPU] Read GPU-modified ranges from the published span tree * [GPU/AGC] Detect user data packets that repeat the current values * [GPU/AGC] Keep register snapshots on repeated user data packets * [GPU] Carry indexed run offsets on resolved draws * [GPU] Ask the render host whether indexed draws can share bindings * [Vulkan] Share indexed draw bindings when no bound image is a target or snapshot * [GPU] Record each draw of an indexed run the recorder did not issue together * [GPU] Obtain the indirect arguments of a whole indexed run * [GPU] Issue an indexed run as consecutive indirect draws * [GPU] Keep indexed runs out of draw replay * [GPU] Decide which indexed draws may group into runs * [GPU] Record run offsets on a resolved indexed draw that is safe to share * [GPU/AGC] Learn which shader pairs may draw as indexed runs * [GPU/AGC] Resolve an indexed run on one worker * [GPU/AGC] Resolve the draws of a refused indexed run one by one at the join * [GPU/AGC] Defer a run of indexed indirect draws as one draw * [GPU] Let the command stream host take indexed draw runs * [Vulkan] Take indexed draw runs on the command thread * [GPU] Find runs of matching indexed indirect draw packets * [GPU] Hand runs of indexed indirect draws to the host * [Tests] Cover indexed draw runs, repeated user data and published span trees * [ShaderCompiler] Take a half wave's mask lane from its subgroup lane * [ShaderCompiler] Test a half wave's lane bit at its mask lane * [ShaderCompiler] Count V_MBCNT lanes at the mask lane * [ShaderCompiler] Pick a mask's first active lane by the mask lane * [ShaderCompiler] Read DPP8 sources at the mask lane * [ShaderCompiler] Read DPP sources and row and bank masks at the mask lane * [ShaderCompiler] Read V_PERMLANE16 sources at the mask lane * [GPU/AGC] Keep indexed runs out of repeated draws * [GnmMode/AJM] Restart a gapless loop when its window query asks for input * [GnmMode/AJM] A run without input reports no partial input * [Tests] Cover the GNM mode gapless loop and runs without input * [Pad] Add support for DualSense Bluetooth connection Haptics, Audio, etc * [GPU] Replay GNM shaders during graphics prewarm Decode recorded graphics shaders with their registered frontend and restore the GCN vertex fetch program. Preserve compatibility with existing recordings and use the frontend binding layout when rebuilding pipeline libraries. * [ShaderCompiler] Map lane-local Wave64 through full host subgroups Derive guest lanes and coordinates from the same subgroup indices. Keep padded lanes out of guest execution, refuse workgroup barriers in the lane-local proof, and avoid division and remainder for power-of-two coordinates. * [GPU] Batch Vulkan submissions across command stream slices Use the scheduler deferred-submit path for ordinary slice boundaries. Preserve each slice timeline tick and submit pending work when a consumer waits. Verify that deferred slices publish and retire their resources on the same timeline path. --------- Co-authored-by: ParantezTech <12572227+par274@users.noreply.github.com> --- Directory.Packages.props | 1 + .../DirectExecutionBackend.StackBounds.cs | 5 +- .../Cpu/Native/DirectExecutionBackend.cs | 49 +- .../Libraries/Ajm/GnmAjmExports.cs | 12 +- src/SharpEmu.HLE/CpuContext.cs | 8 +- src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs | 79 +-- .../GuestMemory/SharedBackingViews.cs | 88 ++- src/SharpEmu.HLE/Host/HostGamepadState.cs | 6 +- src/SharpEmu.HLE/Host/HostViewMemory.cs | 44 ++ src/SharpEmu.HLE/Host/IHostPcmAudioOutput.cs | 20 + src/SharpEmu.HLE/Host/IHostViewMemory.cs | 7 + src/SharpEmu.HLE/Host/Posix/PosixHostViews.cs | 10 + .../Host/Sdl/SdlDualSenseBluetooth.cs | 660 ++++++++++++++++++ src/SharpEmu.HLE/Host/Sdl/SdlHostAudio.cs | 214 +++++- .../Host/Windows/WindowsHostViews.cs | 17 + src/SharpEmu.HLE/SharpEmu.HLE.csproj | 1 + src/SharpEmu.LibAtrac9/BitAllocation.cs | 4 +- .../Agc/AgcExports.CommandStream.cs | 20 + .../Agc/AgcExports.ResolvePool.cs | 174 ++++- src/SharpEmu.Libs/Audio/AjmExports.cs | 523 ++++++++++---- src/SharpEmu.Libs/Audio/AjmOpusDecoder.cs | 21 +- src/SharpEmu.Libs/Audio/Atrac9DecodeState.cs | 177 ++++- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 309 +++++++- src/SharpEmu.Libs/Audio/AudioOutExports.cs | 94 ++- .../Gpu/Buffers/GuestBufferCache.cs | 33 +- .../Gpu/GpuCommands/CommandStreamQueue.cs | 66 +- .../GpuCommandInterpreter.Draws.cs | 53 ++ .../GpuCommandInterpreter.Events.cs | 14 + .../GpuCommandInterpreter.Labels.cs | 54 ++ .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 6 +- .../Gpu/GpuCommands/ICommandStreamHost.cs | 5 + .../Registers/RegisterWriteTable.cs | 6 + .../Registers/RegisterWriters.Shader.cs | 25 + .../Gpu/GpuCommands/ResolveReadLog.cs | 27 + .../Images/GuestImageCache.MemoryDetile.cs | 1 - .../Gpu/Images/GuestImageCache.Metadata.cs | 53 ++ .../Gpu/Images/GuestImageCache.Overlap.cs | 20 +- .../Gpu/Images/GuestImageCache.Slices.cs | 6 + .../Gpu/Images/GuestImageCache.cs | 5 + .../Gpu/Images/SurfaceMetadata.cs | 3 + .../Gpu/Pipelines/ShaderPrewarmList.cs | 11 + .../Gpu/Pipelines/ShaderProgramCache.cs | 70 +- .../Gpu/Rendering/IRenderHost.cs | 2 + .../Gpu/Rendering/RenderExecutor.cs | 139 +++- .../Rendering/RenderRecorder.Tessellation.cs | 2 +- .../Gpu/Rendering/RenderRecorder.cs | 50 +- .../Gpu/Rendering/ResolvedCommands.cs | 56 ++ src/SharpEmu.Libs/HostHighResolutionSleep.cs | 12 + .../Kernel/KernelRuntimeCompatExports.cs | 8 + src/SharpEmu.Libs/Pad/HostWindowInput.cs | 107 ++- src/SharpEmu.Libs/Pad/MotionOrientation.cs | 73 ++ src/SharpEmu.Libs/Pad/PadExports.cs | 221 +++++- src/SharpEmu.Libs/Pad/PadSessionRegistry.cs | 4 + .../Pad/SdlGamepadStateReader.cs | 63 +- .../UserService/UserServiceExports.cs | 4 +- src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs | 63 ++ .../VulkanVideoPresenter.CommandStream.cs | 16 + .../VulkanVideoPresenter.CommandThread.cs | 2 +- .../VulkanVideoPresenter.Device.Setup.cs | 5 +- .../VulkanVideoPresenter.GraphicsPrewarm.cs | 5 +- .../VulkanVideoPresenter.GuestSubmissions.cs | 6 +- .../VulkanVideoPresenter.Pipelines.cs | 7 +- .../VulkanVideoPresenter.Rendering.cs | 19 + .../VideoOut/VulkanVideoPresenter.Slices.cs | 1 + .../Gen5SpirvTranslator.Alu.cs | 17 +- .../Gen5SpirvTranslator.HalfWave64Lowering.cs | 39 +- .../Gen5SpirvTranslator.PairedLanes.cs | 4 +- .../Gen5SpirvTranslator.Resources.cs | 1 + .../Gen5SpirvTranslator.cs | 46 +- .../SpirvModuleBuilder.cs | 38 +- .../Ir/Gen5WaveLaneLocalAnalysis.cs | 2 + .../Audio/AjmExportsTests.cs | 121 ++++ .../Audio/Atrac9GaplessTests.cs | 144 ++++ .../Audio/AudioOut2MixTests.cs | 78 ++- .../Audio/AudioOut2PacingTests.cs | 26 + .../Audio/AudioOut2PcmSnapshotTests.cs | 77 ++ .../Audio/AudioOutExportsTests.cs | 44 +- .../Cpu/Gen5NativeReturnSmokeTests.cs | 44 +- .../GpuCommands/CommandStreamTestSupport.cs | 8 + .../Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs | 3 +- .../GpuCommandInterpreterDrawTests.cs | 43 ++ .../Registers/RegisterStampsTests.cs | 20 + .../Gpu/GpuCommands/ReleaseOrderTests.cs | 167 +++++ .../Images/GuestImageCacheTests.BlockAlias.cs | 76 ++ .../GuestImageCacheTests.SampledDepthClear.cs | 76 ++ .../Gpu/Pipelines/VertexPrewarmTests.cs | 36 + .../Gpu/Rendering/RepeatDrawTests.cs | 293 ++++++++ .../Scheduling/PresenterSubmissionTests.cs | 6 + .../Gpu/Vulkan/HalfConversionDeviceTests.cs | 26 + .../Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs | 19 +- .../Gpu/Vulkan/Wave64Subgroup32DeviceTests.cs | 2 +- .../Kernel/KernelBackedMemoryTests.cs | 44 ++ .../Loader/GnmAjmGaplessLoopTests.cs | 160 +++++ .../Memory/GpuMemory/AvlSpanSetTests.cs | 19 + .../Memory/GuestMemory/FailingHostViews.cs | 2 + .../PhysicalVirtualMemoryBackedTests.cs | 44 ++ .../GuestMemory/SharedBackingViewsTests.cs | 55 ++ .../Memory/NativePageProtection.cs | 7 + .../Pad/HostWindowInputTests.cs | 44 ++ .../Pad/MotionOrientationTests.cs | 80 +++ .../Pad/PadExportsTests.cs | 50 ++ .../Pad/PadReadHistoryTests.cs | 127 ++++ .../UserService/UserServiceExportsTests.cs | 22 + .../CommandStreamStoreProtectionTests.cs | 8 +- .../Gen5FloatContractionTests.cs | 71 ++ .../Gen5WaveLaneLocalAnalysisTests.cs | 8 + 106 files changed, 5570 insertions(+), 493 deletions(-) create mode 100644 src/SharpEmu.HLE/Host/Sdl/SdlDualSenseBluetooth.cs create mode 100644 src/SharpEmu.Libs/Pad/MotionOrientation.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ReleaseOrderTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SampledDepthClear.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/RepeatDrawTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Loader/GnmAjmGaplessLoopTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Pad/MotionOrientationTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Pad/PadReadHistoryTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Gen5FloatContractionTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index a63b0ca7a..7736edfd0 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -11,6 +11,7 @@ SPDX-License-Identifier: GPL-2.0-or-later <PackageVersion Include="Avalonia.Desktop" Version="12.1.0" /> <PackageVersion Include="Avalonia.Fonts.Inter" Version="12.1.0" /> <PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.0" /> + <PackageVersion Include="Concentus" Version="2.2.2" /> <PackageVersion Include="FFmpeg.AutoGen" Version="7.1.1" /> <PackageVersion Include="Iced" Version="1.21.0" /> <PackageVersion Include="ZstdSharp.Port" Version="0.8.5" /> diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.StackBounds.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.StackBounds.cs index 3302c4b34..a824b4d63 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.StackBounds.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.StackBounds.cs @@ -7,7 +7,10 @@ namespace SharpEmu.Core.Cpu.Native; public sealed partial class DirectExecutionBackend { - private const int HostStackStateBytes = 3 * sizeof(ulong); + // The host's stack pointer, its two stack bounds, then its MXCSR and x87 control word. + private const int HostStackStateBytes = 4 * sizeof(ulong); + private const byte HostMxcsrOffset = 3 * sizeof(ulong); + private const byte HostFpuControlWordOffset = HostMxcsrOffset + sizeof(uint); internal static unsafe bool TryGetGuestStackBounds(ulong stackPointer, out ulong bottom, out ulong top) { diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs index 7986dc793..72a5dd5b0 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs @@ -2231,7 +2231,7 @@ private unsafe bool TryPrepareGuestContextTransfer( frame[14] = target.R13; frame[15] = target.R14; frame[16] = target.R15; - frame[17] = target.Mxcsr == 0 ? 0x1F80u : target.Mxcsr; + frame[17] = target.Mxcsr == 0 ? CpuContext.InitialMxcsr : target.Mxcsr; frame[18] = target.FpuControlWord == 0 ? 0x037Fu : target.FpuControlWord; frame[19] = target.RestoreFullFpuState ? 1u : 0u; // The TEB stores NT_TIB.StackBase (the high address) at +0x08 and @@ -2765,6 +2765,7 @@ private unsafe nint CreateGuestReturnStub() EmitByte(code, ref offset, 0x20); EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xC2); // mov r10,rax EmitHostStackBounds(code, ref offset, save: false); + EmitHostFloatingPointControlRestore(code, ref offset); EmitHostNonvolatileXmmRestore(code, ref offset); EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x5F); EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x5E); @@ -4849,7 +4850,7 @@ public bool TryCallGuestContinuation( FsBase = callerContext.FsBase != 0 ? callerContext.FsBase : (continuation.FsBase != 0 ? continuation.FsBase : fallbackTlsBase), GsBase = callerContext.GsBase != 0 ? callerContext.GsBase : (continuation.GsBase != 0 ? continuation.GsBase : fallbackTlsBase), FpuControlWord = continuation.FpuControlWord == 0 ? (ushort)0x037F : continuation.FpuControlWord, - Mxcsr = continuation.Mxcsr == 0 ? 0x1F80u : continuation.Mxcsr, + Mxcsr = continuation.Mxcsr == 0 ? CpuContext.InitialMxcsr : continuation.Mxcsr, }; context[CpuRegister.Rax] = continuation.Rax; @@ -6296,7 +6297,7 @@ private static void ApplyGuestContinuation(CpuContext context, GuestCpuContinuat context.FpuControlWord = continuation.FpuControlWord == 0 ? (ushort)0x037F : continuation.FpuControlWord; - context.Mxcsr = continuation.Mxcsr == 0 ? 0x1F80u : continuation.Mxcsr; + context.Mxcsr = continuation.Mxcsr == 0 ? CpuContext.InitialMxcsr : continuation.Mxcsr; } private unsafe GuestNativeCallExitReason ExecuteGuestThreadEntry(CpuContext context, ulong entryPoint, string name, out string? reason) @@ -6364,6 +6365,7 @@ private unsafe GuestNativeCallExitReason ExecuteGuestThreadEntry(CpuContext cont ptr2[offset++] = 73; ptr2[offset++] = 137; ptr2[offset++] = 34; + EmitFloatingPointControlSwitch(ptr2, ref offset, context.Mxcsr, context.FpuControlWord); EmitGuestStackBounds(ptr2, ref offset, context[CpuRegister.Rsp]); ptr2[offset++] = 72; ptr2[offset++] = 184; @@ -6427,6 +6429,7 @@ private unsafe GuestNativeCallExitReason ExecuteGuestThreadEntry(CpuContext cont ptr2[offset++] = 139; ptr2[offset++] = 34; EmitHostStackBounds(ptr2, ref offset, save: false); + EmitHostFloatingPointControlRestore(ptr2, ref offset); EmitHostNonvolatileXmmRestore(ptr2, ref offset); ptr2[offset++] = 65; ptr2[offset++] = 95; @@ -6576,19 +6579,12 @@ private unsafe GuestNativeCallExitReason ExecuteGuestContinuationEntry( emitter.Emit(0x41); emitter.Emit(0x56); // push r14 emitter.Emit(0x41); emitter.Emit(0x57); // push r15 EmitHostNonvolatileXmmSave(ptr2, ref emitter.Offset); + emitter.EmitMovR64Immediate(0x49, 0xBA, hostRspSlot); // mov r10, hostRspSlot + emitter.Emit(0x49); emitter.Emit(0x89); emitter.Emit(0x22); // mov [r10], rsp // Restore the fiber's floating-point control environment before // abandoning the host stack. This path is used when a blocked guest // continuation migrates to another managed worker. - emitter.Emit(0x48); emitter.Emit(0x83); emitter.Emit(0xEC); emitter.Emit(0x08); // sub rsp,8 - emitter.Emit(0xC7); emitter.Emit(0x04); emitter.Emit(0x24); // mov dword [rsp],imm32 - emitter.Emit(context.Mxcsr); - emitter.Emit(0x0F); emitter.Emit(0xAE); emitter.Emit(0x14); emitter.Emit(0x24); // ldmxcsr [rsp] - emitter.Emit(0x66); emitter.Emit(0xC7); emitter.Emit(0x04); emitter.Emit(0x24); // mov word [rsp],imm16 - emitter.Emit(context.FpuControlWord); - emitter.Emit(0xD9); emitter.Emit(0x2C); emitter.Emit(0x24); // fldcw [rsp] - emitter.Emit(0x48); emitter.Emit(0x83); emitter.Emit(0xC4); emitter.Emit(0x08); // add rsp,8 - emitter.EmitMovR64Immediate(0x49, 0xBA, hostRspSlot); // mov r10, hostRspSlot - emitter.Emit(0x49); emitter.Emit(0x89); emitter.Emit(0x22); // mov [r10], rsp + EmitFloatingPointControlSwitch(ptr2, ref emitter.Offset, context.Mxcsr, context.FpuControlWord); EmitGuestStackBounds(ptr2, ref emitter.Offset, context[CpuRegister.Rsp]); emitter.EmitMovR64Immediate(0x48, 0xB8, context[CpuRegister.Rsp]); // mov rax, guest rsp emitter.Emit(0x48); emitter.Emit(0x89); emitter.Emit(0xC4); // mov rsp, rax @@ -6742,6 +6738,31 @@ private static unsafe void EmitUInt32(byte* code, ref int offset, uint value) offset += sizeof(uint); } + // R10 holds the host state block. The guest starts with its context's MXCSR and x87 control word (a new thread gets + // the console's) instead of the host thread's, which the block keeps for every way back to the host: their control + // bits are callee-saved on the host. + private static unsafe void EmitFloatingPointControlSwitch(byte* code, ref int offset, uint mxcsr, ushort fpuControlWord) + { + ReadOnlySpan<byte> save = [0x41, 0x0F, 0xAE, 0x5A, HostMxcsrOffset, 0x41, 0xD9, 0x7A, HostFpuControlWordOffset]; // stmxcsr [r10+24]; fnstcw [r10+28] + foreach (var value in save) EmitByte(code, ref offset, value); + ReadOnlySpan<byte> storeMxcsr = [0x48, 0x83, 0xEC, 0x08, 0xC7, 0x04, 0x24]; // sub rsp,8; mov dword [rsp],imm32 + foreach (var value in storeMxcsr) EmitByte(code, ref offset, value); + EmitUInt32(code, ref offset, mxcsr); + ReadOnlySpan<byte> storeControlWord = [0x0F, 0xAE, 0x14, 0x24, 0x66, 0xC7, 0x04, 0x24]; // ldmxcsr [rsp]; mov word [rsp],imm16 + foreach (var value in storeControlWord) EmitByte(code, ref offset, value); + EmitByte(code, ref offset, (byte)fpuControlWord); + EmitByte(code, ref offset, (byte)(fpuControlWord >> 8)); + ReadOnlySpan<byte> load = [0xD9, 0x2C, 0x24, 0x48, 0x83, 0xC4, 0x08]; // fldcw [rsp]; add rsp,8 + foreach (var value in load) EmitByte(code, ref offset, value); + } + + // R10 holds the host state block. + private static unsafe void EmitHostFloatingPointControlRestore(byte* code, ref int offset) + { + ReadOnlySpan<byte> restore = [0x41, 0x0F, 0xAE, 0x52, HostMxcsrOffset, 0x41, 0xD9, 0x6A, HostFpuControlWordOffset]; // ldmxcsr [r10+24]; fldcw [r10+28] + foreach (var value in restore) EmitByte(code, ref offset, value); + } + private static unsafe void EmitHostNonvolatileXmmSave(byte* code, ref int offset) { EmitByte(code, ref offset, 0x48); @@ -6859,6 +6880,7 @@ private unsafe bool ExecuteEntry(CpuContext context, ulong entryPoint, out Orbis ptr2[num3++] = 73; ptr2[num3++] = 137; ptr2[num3++] = 34; + EmitFloatingPointControlSwitch(ptr2, ref num3, context.Mxcsr, context.FpuControlWord); EmitGuestStackBounds(ptr2, ref num3, context[CpuRegister.Rsp]); ptr2[num3++] = 72; ptr2[num3++] = 184; @@ -6922,6 +6944,7 @@ private unsafe bool ExecuteEntry(CpuContext context, ulong entryPoint, out Orbis ptr2[num3++] = 139; ptr2[num3++] = 34; EmitHostStackBounds(ptr2, ref num3, save: false); + EmitHostFloatingPointControlRestore(ptr2, ref num3); EmitHostNonvolatileXmmRestore(ptr2, ref num3); ptr2[num3++] = 65; ptr2[num3++] = 95; diff --git a/src/SharpEmu.GnmMode/Libraries/Ajm/GnmAjmExports.cs b/src/SharpEmu.GnmMode/Libraries/Ajm/GnmAjmExports.cs index 16afa2136..6e6048ab0 100644 --- a/src/SharpEmu.GnmMode/Libraries/Ajm/GnmAjmExports.cs +++ b/src/SharpEmu.GnmMode/Libraries/Ajm/GnmAjmExports.cs @@ -308,6 +308,8 @@ private static bool ExecuteJob(CpuContext ctx, uint context, uint instance, Read AjmExports.AjmBatchJobRunBufferRa(call); } Trace($"run instance=0x{instance:X} flags=0x{flags:X} buffers={inputs.Count}/{outputs.Count} result=0x{call[CpuRegister.Rax]:X}"); + if (inputs.TrueForAll(static input => input.Size == 0)) + ClearPartialInput(ctx, controlOutput); if (state is not null) FinishRun(ctx, scratch, state, instance, flags, inputs, controlOutput); return true; @@ -407,7 +409,7 @@ private static void FinishRun(CpuContext ctx, BatchScratch scratch, InstanceStat call[CpuRegister.R8] = 0; call[CpuRegister.R9] = 0; scratch.WriteStackArgs(0, scratch.Address(ScratchQuery), (ulong)query.End); - if (scratch.Call(AjmExports.AjmBatchJobRunBufferRa, ScratchQuery) != 0 || + if ((scratch.Call(AjmExports.AjmBatchJobRunBufferRa, ScratchQuery) & ~Atrac9DecodeState.ResultPartialInput) != 0 || scratch.ReadUInt32(ScratchQuery + query.Gapless) != 0) return; @@ -425,6 +427,14 @@ private static void FinishRun(CpuContext ctx, BatchScratch scratch, InstanceStat Trace($"gapless_loop instance=0x{instance:X} decoded={decoded} base={state.DecodedBase} consumed=0x{consumed:X}"); } + private static void ClearPartialInput(CpuContext ctx, Buffer sideband) + { + if (sideband.Address == 0 || sideband.Size < AjmExports.AjmSidebandResultBytes || + !ctx.TryReadUInt32(sideband.Address, out var status) || (status & Atrac9DecodeState.ResultPartialInput) == 0) + return; + ctx.TryWriteUInt32(sideband.Address, status & ~(uint)Atrac9DecodeState.ResultPartialInput); + } + private static Atrac9Config? ReadAtrac9Config(CpuContext ctx, InstanceState state, Buffer parameters) { Span<byte> data = stackalloc byte[4]; diff --git a/src/SharpEmu.HLE/CpuContext.cs b/src/SharpEmu.HLE/CpuContext.cs index 23c39b1d5..1115dc9fd 100644 --- a/src/SharpEmu.HLE/CpuContext.cs +++ b/src/SharpEmu.HLE/CpuContext.cs @@ -41,7 +41,13 @@ public sealed class CpuContext(ICpuMemory memory, Generation generation) public ushort FpuControlWord { get; set; } = 0x037F; /// <summary>MXCSR observed at the current guest boundary.</summary> - public uint Mxcsr { get; set; } = 0x1F80; + public uint Mxcsr { get; set; } = InitialMxcsr; + + /// <summary> + /// The MXCSR a guest thread starts with on the console, as its libc's default environment holds it: every + /// exception masked, round to nearest, flush-to-zero and denormals-are-zero. + /// </summary> + public const uint InitialMxcsr = 0x9FC0; public ulong this[CpuRegister register] { diff --git a/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs b/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs index 7e1d35187..90a3a72b0 100644 --- a/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs +++ b/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs @@ -6,14 +6,17 @@ namespace SharpEmu.HLE.GpuMemory; // Callers serialize access. The tree does not change range ownership or locking. public sealed class AvlSpanSet { - private sealed class Node(ulong start, ulong end) + private sealed class Node(ulong start, ulong end, Node? left = null, Node? right = null) { - public ulong Start = start; - public ulong End = end; - public Node? Left; - public Node? Right; - public int Height = 1; - public int Count = 1; + public readonly ulong Start = start; + public readonly ulong End = end; + public readonly Node? Left = left; + public readonly Node? Right = right; + public readonly int Height = Math.Max(left?.Height ?? 0, right?.Height ?? 0) + 1; + public readonly int Count = (left?.Count ?? 0) + (right?.Count ?? 0) + 1; + + public Node WithLeft(Node? child) => new(Start, End, child, Right); + public Node WithRight(Node? child) => new(Start, End, Left, child); } // A new snapshot copies the last one's spans outside the extent of every span removed or inserted since, and walks the @@ -21,6 +24,13 @@ private sealed class Node(ulong start, ulong end) private static readonly bool SpliceSnapshots = Environment.GetEnvironmentVariable("SHARPEMU_SPAN_SNAPSHOT_SPLICE") != "0"; private Node? _root; + private Node? _published; + + // A GPU write may edit several ranges before other threads are allowed to observe them. + public void PublishChanges() => Volatile.Write(ref _published, _root); + + public bool PublishedOverlaps(ulong address, ulong size) => Overlaps(Volatile.Read(ref _published), address, size); + private SpanSnapshot? _snapshot = SpanSnapshot.Empty; private SpanSnapshot _built = SpanSnapshot.Empty; private ulong _changedStart = ulong.MaxValue; @@ -91,11 +101,12 @@ public bool Contains(ulong address, ulong size) return node is not null && node.End >= address + size; } - public bool Overlaps(ulong address, ulong size) + public bool Overlaps(ulong address, ulong size) => Overlaps(_root, address, size); + + private static bool Overlaps(Node? node, ulong address, ulong size) { ValidateRange(address, size); var end = address + size; - var node = _root; while (node is not null) { if (node.Start >= end) node = node.Left; @@ -254,44 +265,29 @@ private static void Collect(Node? node, ulong[] starts, ulong[] ends, ref int in } private static int Height(Node? node) => node?.Height ?? 0; - private static void UpdateHeight(Node node) - { - node.Height = Math.Max(Height(node.Left), Height(node.Right)) + 1; - node.Count = (node.Left?.Count ?? 0) + (node.Right?.Count ?? 0) + 1; - } - private static Node RotateRight(Node node) { var left = node.Left!; - node.Left = left.Right; - left.Right = node; - UpdateHeight(node); - UpdateHeight(left); - return left; + return left.WithRight(node.WithLeft(left.Right)); } private static Node RotateLeft(Node node) { var right = node.Right!; - node.Right = right.Left; - right.Left = node; - UpdateHeight(node); - UpdateHeight(right); - return right; + return right.WithLeft(node.WithRight(right.Left)); } private static Node Balance(Node node) { - UpdateHeight(node); var difference = Height(node.Left) - Height(node.Right); if (difference > 1) { - if (Height(node.Left!.Left) < Height(node.Left.Right)) node.Left = RotateLeft(node.Left); + if (Height(node.Left!.Left) < Height(node.Left.Right)) node = node.WithLeft(RotateLeft(node.Left)); return RotateRight(node); } if (difference < -1) { - if (Height(node.Right!.Right) < Height(node.Right.Left)) node.Right = RotateRight(node.Right); + if (Height(node.Right!.Right) < Height(node.Right.Left)) node = node.WithRight(RotateRight(node.Right)); return RotateLeft(node); } return node; @@ -300,28 +296,21 @@ private static Node Balance(Node node) private static Node Insert(Node? node, ulong start, ulong end) { if (node is null) return new Node(start, end); - if (start < node.Start) node.Left = Insert(node.Left, start, end); - else if (start > node.Start) node.Right = Insert(node.Right, start, end); - else node.End = end; - return Balance(node); + if (start < node.Start) return Balance(node.WithLeft(Insert(node.Left, start, end))); + if (start > node.Start) return Balance(node.WithRight(Insert(node.Right, start, end))); + return new Node(start, end, node.Left, node.Right); } private static Node? Delete(Node? node, ulong start) { if (node is null) return null; - if (start < node.Start) node.Left = Delete(node.Left, start); - else if (start > node.Start) node.Right = Delete(node.Right, start); - else - { - if (node.Left is null) return node.Right; - if (node.Right is null) return node.Left; - var successor = node.Right; - while (successor.Left is not null) successor = successor.Left; - node.Start = successor.Start; - node.End = successor.End; - node.Right = Delete(node.Right, successor.Start); - } - return Balance(node); + if (start < node.Start) return Balance(node.WithLeft(Delete(node.Left, start))); + if (start > node.Start) return Balance(node.WithRight(Delete(node.Right, start))); + if (node.Left is null) return node.Right; + if (node.Right is null) return node.Left; + var successor = node.Right; + while (successor.Left is not null) successor = successor.Left; + return Balance(new Node(successor.Start, successor.End, node.Left, Delete(node.Right, successor.Start))); } private static void ValidateRange(ulong address, ulong size) diff --git a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs index 69733b291..b151380c6 100644 --- a/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs +++ b/src/SharpEmu.HLE/GuestMemory/SharedBackingViews.cs @@ -427,6 +427,11 @@ private bool TryUnmapSingleView(ulong address, ulong size, out bool holePreserve return false; } + // The rest of a partly unmapped view is mapped again, which would drop every access change made on its pages since + // the view was mapped (the GPU memory page watches, a guest mprotect): a write to a page whose GPU data is newer + // would then land without a fault, and the GPU bytes would later overwrite it. The access is read before the view + // goes and put back on each part right after it is mapped again (RestoreAccess). + var access = address != old.Address || size != old.Size ? _host.QueryAccess(old.Address, old.Size) : []; bool unmapped; GuestMemoryProfile.RecordUnmapSizes(size, old.Size, address - old.Address, old.Address + old.Size - address - size); @@ -463,12 +468,24 @@ private bool TryUnmapSingleView(ulong address, ulong size, out bool holePreserve if (leftSize != 0) { - ok = TryMapReservedRange(old.Address, leftSize, old.Offset, old.Protection, true, out _) && ok; + var mapped = TryMapReservedRange(old.Address, leftSize, old.Offset, old.Protection, true, out _); + if (mapped) + { + RestoreAccess(access, old.Address, leftSize, old.Protection); + } + + ok = mapped && ok; } if (rightSize != 0) { - ok = TryMapReservedRange(rightAddress, rightSize, old.Offset + (rightAddress - old.Address), old.Protection, true, out _) && ok; + var mapped = TryMapReservedRange(rightAddress, rightSize, old.Offset + (rightAddress - old.Address), old.Protection, true, out _); + if (mapped) + { + RestoreAccess(access, rightAddress, rightSize, old.Protection); + } + + ok = mapped && ok; } if (ok) @@ -493,9 +510,76 @@ private bool TryUnmapSingleView(ulong address, ulong size, out bool holePreserve } RestoreViewMapping(old); + RestoreAccess(access, old.Address, old.Size, old.Protection); return false; } + // A view's protection without write. + private static HostPageProtection WithoutWrite(HostPageProtection protection) => protection switch + { + HostPageProtection.ReadWrite => HostPageProtection.ReadOnly, + HostPageProtection.ReadWriteExecute or HostPageProtection.ExecuteWriteCopy => HostPageProtection.ReadExecute, + _ => protection, + }; + + // Gives each page of a part of a view just mapped again with the view's protection the access it had before: the access + // the host reported for it, or the view's protection where it reported none. The part first loses write in one change + // (a view mapped without write cannot gain it back), so no store lands unseen while the pages get their access one run + // at a time; only a read can see the bytes in that window. Nothing changes when every page already has the view's + // protection or the host reported nothing. + private void RestoreAccess(IReadOnlyList<HostPageAccess> access, ulong address, ulong size, HostPageProtection mapped) + { + var end = address + size; + var differs = false; + foreach (var run in access) + { + if (run.Address < end && address < run.Address + run.Size && run.Protection != mapped) + { + differs = true; + break; + } + } + + if (!differs) + { + return; + } + + var held = WithoutWrite(mapped); + Apply(address, size, held, mapped); + var cursor = address; + foreach (var run in access) + { + var start = Math.Max(run.Address, address); + var stop = Math.Min(run.Address + run.Size, end); + if (start >= stop) + { + continue; + } + + if (cursor < start) + { + Apply(cursor, start - cursor, mapped, held); + } + + Apply(start, stop - start, run.Protection, held); + cursor = stop; + } + + if (cursor < end) + { + Apply(cursor, end - cursor, mapped, held); + } + + void Apply(ulong start, ulong bytes, HostPageProtection protection, HostPageProtection current) + { + if (protection != current && !_host.ChangeAccess(start, bytes, protection)) + { + OnFatal($"Could not restore the page access at 0x{start:X16} after a partial unmap."); + } + } + } + internal bool IsRestoredView(ulong address) { lock (_lock) diff --git a/src/SharpEmu.HLE/Host/HostGamepadState.cs b/src/SharpEmu.HLE/Host/HostGamepadState.cs index 368633765..2babc2e21 100644 --- a/src/SharpEmu.HLE/Host/HostGamepadState.cs +++ b/src/SharpEmu.HLE/Host/HostGamepadState.cs @@ -54,7 +54,11 @@ public readonly record struct HostMotionState( float AccelerationZ, float AngularVelocityX, float AngularVelocityY, - float AngularVelocityZ); + float AngularVelocityZ, + float OrientationX = 0, + float OrientationY = 0, + float OrientationZ = 0, + float OrientationW = 1); public readonly record struct HostTouchPoint( bool Active, diff --git a/src/SharpEmu.HLE/Host/HostViewMemory.cs b/src/SharpEmu.HLE/Host/HostViewMemory.cs index 914391495..0be47ddb0 100644 --- a/src/SharpEmu.HLE/Host/HostViewMemory.cs +++ b/src/SharpEmu.HLE/Host/HostViewMemory.cs @@ -16,4 +16,48 @@ internal static bool IsValidRange(ulong address, ulong size) => internal static bool IsValidOffset(HostBackingObject backing, ulong offset, ulong size, ulong pageSize) => offset % pageSize == 0 && offset < backing.Size && size != 0 && size <= backing.Size - offset; + + // A page's access as the host reports it (the PAGE_* values; the Posix region table keeps the same values). False for an + // access with a modifier such as a guard page, or one HostPageProtection has no value for. + internal static bool TryGetProtection(uint raw, out HostPageProtection protection) + { + (var known, protection) = raw switch + { + HostMemory.PAGE_NOACCESS => (true, HostPageProtection.NoAccess), + HostMemory.PAGE_READONLY => (true, HostPageProtection.ReadOnly), + HostMemory.PAGE_READWRITE => (true, HostPageProtection.ReadWrite), + HostMemory.PAGE_EXECUTE => (true, HostPageProtection.Execute), + HostMemory.PAGE_EXECUTE_READ => (true, HostPageProtection.ReadExecute), + HostMemory.PAGE_EXECUTE_READWRITE => (true, HostPageProtection.ReadWriteExecute), + 0x80 => (true, HostPageProtection.ExecuteWriteCopy), + _ => (false, HostPageProtection.NoAccess), + }; + return known; + } + + // Walks the range with a host query that describes the run of equal access a page starts. A run it cannot describe (not + // committed, an access TryGetProtection does not know) is left out, and so is the rest of the range once the query fails. + internal static IReadOnlyList<HostPageAccess> CollectAccess(ulong address, ulong size, Func<ulong, (bool Found, HostMemory.BasicInfo Info)> query) + { + var runs = new List<HostPageAccess>(); + var end = address + size; + for (var current = address; current < end;) + { + var (found, info) = query(current); + if (!found || info.BaseAddress + info.RegionSize <= current) + { + break; + } + + var stop = Math.Min(end, info.BaseAddress + info.RegionSize); + if (info.State == HostMemory.MEM_COMMIT && TryGetProtection(info.Protect, out var protection)) + { + runs.Add(new HostPageAccess(current, stop - current, protection)); + } + + current = stop; + } + + return runs; + } } diff --git a/src/SharpEmu.HLE/Host/IHostPcmAudioOutput.cs b/src/SharpEmu.HLE/Host/IHostPcmAudioOutput.cs index 1b8c671f4..06653efb8 100644 --- a/src/SharpEmu.HLE/Host/IHostPcmAudioOutput.cs +++ b/src/SharpEmu.HLE/Host/IHostPcmAudioOutput.cs @@ -10,6 +10,26 @@ namespace SharpEmu.HLE.Host; public interface IHostPcmAudioOutput : IHostAudioOutput { IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmFormat format); + + /// <summary> + /// The same stream with a caller-chosen backpressure cap in bytes, for callers that pace the guest themselves and + /// need a deeper queue than the default. + /// </summary> + IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmFormat format, int maxQueuedBytes) => + OpenPcmStream(sampleRate, channels, format); + + /// <summary> + /// A float stream on the game controller's own output device, or null when the host has none. A DualSense on USB + /// lists one with four channels: its speaker (or a headset plugged into the controller) on the first two and its + /// two haptic actuators on the last two. <paramref name="channels"/> is 4 when the device takes all of them and 2 + /// when it takes only the speaker pair. The stream does not report the guest audio clock. Without + /// <paramref name="routeSpeaker"/> the controller's speaker routing is left alone (a stream for the actuators). + /// </summary> + IHostAudioStream? TryOpenControllerStream(uint sampleRate, int maxQueuedBytes, out int channels, bool routeSpeaker = true) + { + channels = 0; + return null; + } } public enum HostPcmFormat diff --git a/src/SharpEmu.HLE/Host/IHostViewMemory.cs b/src/SharpEmu.HLE/Host/IHostViewMemory.cs index 7f05f9622..fe08b4924 100644 --- a/src/SharpEmu.HLE/Host/IHostViewMemory.cs +++ b/src/SharpEmu.HLE/Host/IHostViewMemory.cs @@ -5,6 +5,8 @@ namespace SharpEmu.HLE.Host; public readonly record struct HostAddressRange(ulong Address, ulong Size); +public readonly record struct HostPageAccess(ulong Address, ulong Size, HostPageProtection Protection); + // The caller must own each range. The host does not check this on all platforms. public interface IHostViewMemory { @@ -34,6 +36,11 @@ public interface IHostViewMemory bool ChangeAccess(ulong address, ulong size, HostPageProtection protection); + // The access of the range's committed pages, one entry per run of equal access, in address order. A page the host cannot + // describe (not committed, or an access HostPageProtection has no value for) has no entry. No default: a wrapper that + // left it out would silently report nothing. + IReadOnlyList<HostPageAccess> QueryAccess(ulong address, ulong size); + // Releases every private commit and placeholder that remains inside an owned range. bool FreeOwnedRange(ulong address, ulong size); } diff --git a/src/SharpEmu.HLE/Host/Posix/PosixHostViews.cs b/src/SharpEmu.HLE/Host/Posix/PosixHostViews.cs index 7c4706289..9dd8e6eb0 100644 --- a/src/SharpEmu.HLE/Host/Posix/PosixHostViews.cs +++ b/src/SharpEmu.HLE/Host/Posix/PosixHostViews.cs @@ -233,6 +233,16 @@ public bool ChangeAccess(ulong address, ulong size, HostPageProtection protectio } } + // The region table keeps every page's access as ChangeAccess set it. + public IReadOnlyList<HostPageAccess> QueryAccess(ulong address, ulong size) + { + lock (PosixViewRegions.Gate) + { + return HostViewMemory.CollectAccess(address, size, static current => + PosixViewRegions.TryQuery(current, out var info) ? (true, info) : (false, default)); + } + } + public bool FreeOwnedRange(ulong address, ulong size) { lock (PosixViewRegions.Gate) diff --git a/src/SharpEmu.HLE/Host/Sdl/SdlDualSenseBluetooth.cs b/src/SharpEmu.HLE/Host/Sdl/SdlDualSenseBluetooth.cs new file mode 100644 index 000000000..0d3aaa6a9 --- /dev/null +++ b/src/SharpEmu.HLE/Host/Sdl/SdlDualSenseBluetooth.cs @@ -0,0 +1,660 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers; +using System.Buffers.Binary; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using Concentus; +using Concentus.Enums; +using SDL; +using static SDL.SDL3; + +namespace SharpEmu.HLE.Host.Sdl; + +internal sealed unsafe class SdlDualSenseBluetooth +{ + private const ushort SonyVendorId = 0x054C; + private const ushort DualSenseProductId = 0x0CE6; + private const ushort DualSenseEdgeProductId = 0x0DF2; + private const int InputChannels = 4; + private const int ReportLength = 547; + private const byte ReportId = 0x39; + private const int HapticRate = 3000; + private const int HapticFrames = 64; + private const int HapticBlockBytes = 64; + private const int HapticOffset = 12; + private const int SpeakerRate = 45000; + private const int OpusSampleRate = 48000; + private const int OpusFrames = 480; + private const int OpusPacketBytes = 200; + private const int SpeakerFrames = 2 * OpusFrames; + private const int SpeakerHeaderOffset = 140; + private const int SpeakerOffset = 142; + private const byte AudioBufferLength = 48; + private const int ReopenDelayMilliseconds = 1000; + private static readonly long PeriodTicks = Stopwatch.Frequency * HapticFrames / HapticRate; + + private static readonly object RegistryGate = new(); + private static SdlDualSenseBluetooth? _shared; + + private readonly object _gate = new(); + private readonly List<Client> _clients = []; + private readonly AutoResetEvent _signal = new(false); + private readonly byte[] _path; + private readonly Thread _sender; + private SDL_hid_device* _device; + private IOpusEncoder? _encoder; + private bool _stopping; + private byte _sequence; + private byte _counter; + private long _reopenAt; + private bool _writeFailureLogged; + private bool _encodeFailureLogged; + + private SdlDualSenseBluetooth(byte[] path, SDL_hid_device* device) + { + _path = path; + _device = device; + _sender = new Thread(Run) + { + IsBackground = true, + Name = "DualSense Bluetooth audio", + Priority = ThreadPriority.AboveNormal, + }; + _sender.Start(); + } + + public static IHostAudioStream? TryOpen(SDL_JoystickID pad, uint sampleRate, int maxQueuedBytes, bool speaker) + { + lock (RegistryGate) + { + var link = _shared ?? Create(pad); + if (link is null) + { + return null; + } + + _shared = link; + try + { + return link.Attach(sampleRate, maxQueuedBytes, speaker); + } + catch + { + if (link.ClientCount == 0) + { + link.Shutdown(); + } + + throw; + } + } + } + + private int ClientCount + { + get + { + lock (_gate) + { + return _clients.Count; + } + } + } + + private static SdlDualSenseBluetooth? Create(SDL_JoystickID pad) + { + if (SDL_hid_init() != 0) + { + return null; + } + + var path = FindPath(pad); + var device = path is null ? null : OpenPath(path); + if (device is null) + { + SDL_hid_exit(); + return null; + } + + return new SdlDualSenseBluetooth(path!, device); + } + + private static byte[]? FindPath(SDL_JoystickID pad) + { + string? gamepadPath = null; + SDL_LockJoysticks(); + try + { + var gamepad = SDL_GetGamepadFromID(pad); + if (gamepad is not null) + { + gamepadPath = SDL_GetGamepadPath(gamepad); + } + } + finally + { + SDL_UnlockJoysticks(); + } + + byte[]? match = null; + byte[]? only = null; + var count = 0; + var devices = SDL_hid_enumerate(SonyVendorId, 0); + try + { + for (var device = devices; device is not null; device = device->next) + { + if (device->bus_type != SDL_hid_bus_type.SDL_HID_API_BUS_BLUETOOTH || + device->product_id is not (DualSenseProductId or DualSenseEdgeProductId) || + device->path is null || + (device->usage_page != 0 && (device->usage_page != 1 || device->usage != 5))) + { + continue; + } + + var path = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(device->path); + var copy = new byte[path.Length + 1]; + path.CopyTo(copy); + if (gamepadPath is not null && + string.Equals(Encoding.UTF8.GetString(path), gamepadPath, StringComparison.OrdinalIgnoreCase)) + { + match = copy; + } + + only = copy; + count++; + } + } + finally + { + SDL_hid_free_enumeration(devices); + } + + return match ?? (count == 1 ? only : null); + } + + private static SDL_hid_device* OpenPath(byte[] path) + { + fixed (byte* data = path) + { + return SDL_hid_open_path(data); + } + } + + private Client Attach(uint sampleRate, int maxQueuedBytes, bool speaker) + { + var queueMilliseconds = maxQueuedBytes * 1000.0 / ((double)sampleRate * InputChannels * sizeof(float)); + var client = new Client(this, sampleRate, queueMilliseconds, speaker); + lock (_gate) + { + _clients.Add(client); + } + + return client; + } + + private void Detach(Client client) + { + lock (RegistryGate) + { + lock (_gate) + { + _clients.Remove(client); + client.Release(); + if (_clients.Count > 0) + { + return; + } + } + + Shutdown(); + } + } + + private void Shutdown() + { + lock (_gate) + { + _stopping = true; + } + + if (ReferenceEquals(_shared, this)) + { + _shared = null; + } + + _signal.Set(); + _sender.Join(); + if (_device is not null) + { + SDL_hid_close(_device); + _device = null; + } + + SDL_hid_exit(); + } + + private void Run() + { + var report = new byte[ReportLength]; + var haptics = new float[HapticFrames * 2]; + var speaker = new float[SpeakerFrames * 2]; + var next = 0L; + while (true) + { + bool active; + bool speakerOpen; + lock (_gate) + { + if (_stopping) + { + return; + } + + Array.Clear(haptics); + Array.Clear(speaker); + active = false; + speakerOpen = false; + foreach (var client in _clients) + { + active |= client.Haptics.MixInto(haptics); + if (client.Speaker is { } lane) + { + speakerOpen = true; + active |= lane.MixInto(speaker); + } + } + } + + if (!active) + { + next = 0; + _signal.WaitOne(250); + continue; + } + + BuildReport(report, haptics, speakerOpen ? speaker : null); + Send(report); + + var now = Stopwatch.GetTimestamp(); + next = (next == 0 ? now : next) + PeriodTicks; + if (now - next > PeriodTicks) + { + next = now; + } + + var wait = next - Stopwatch.GetTimestamp(); + if (wait > 0) + { + SDL_DelayNS((ulong)(wait * 1_000_000_000.0 / Stopwatch.Frequency)); + } + } + } + + private void BuildReport(byte[] report, float[] haptics, float[]? speaker) + { + Array.Clear(report); + report[0] = ReportId; + report[1] = (byte)(_sequence << 4); + _sequence = (byte)((_sequence + 1) & 0x0F); + report[2] = 0x91; + report[3] = 6; + report[4] = 0x7E; + report.AsSpan(5, 4).Fill(AudioBufferLength); + _counter += 2; + report[9] = _counter; + report[10] = 0xD2; + report[11] = HapticBlockBytes; + for (var index = 0; index < haptics.Length; index++) + { + report[HapticOffset + index] = (byte)(sbyte)ToHapticSample(haptics[index]); + } + + if (speaker is not null && EncodeSpeaker(speaker, report.AsSpan(SpeakerOffset, 2 * OpusPacketBytes))) + { + report[SpeakerHeaderOffset] = 0xD3; + report[SpeakerHeaderOffset + 1] = OpusPacketBytes; + } + + byte header = 0xA2; + var crc = SDL_crc32(0, (nint)(&header), 1); + fixed (byte* data = report) + { + crc = SDL_crc32(crc, (nint)data, (nuint)(report.Length - sizeof(uint))); + } + + BinaryPrimitives.WriteUInt32LittleEndian(report.AsSpan(report.Length - sizeof(uint)), crc); + } + + private static int ToHapticSample(float value) => + float.IsFinite(value) ? (int)MathF.Round(Math.Clamp(value, -1f, 1f) * 127f) : 0; + + private bool EncodeSpeaker(float[] speaker, Span<byte> destination) + { + for (var index = 0; index < speaker.Length; index++) + { + speaker[index] = float.IsFinite(speaker[index]) ? Math.Clamp(speaker[index], -1f, 1f) : 0f; + } + + try + { + if (_encoder is null) + { + OpusCodecFactory.AttemptToUseNativeLibrary = false; + var encoder = OpusCodecFactory.CreateEncoder(OpusSampleRate, 2, OpusApplication.OPUS_APPLICATION_RESTRICTED_LOWDELAY); + encoder.Bitrate = OpusPacketBytes * 8 * OpusSampleRate / OpusFrames; + encoder.UseVBR = false; + encoder.Complexity = 0; + _encoder = encoder; + } + + for (var packet = 0; packet < 2; packet++) + { + var encoded = _encoder.Encode( + speaker.AsSpan(packet * OpusFrames * 2, OpusFrames * 2), + OpusFrames, + destination.Slice(packet * OpusPacketBytes, OpusPacketBytes), + OpusPacketBytes); + if (encoded != OpusPacketBytes) + { + destination.Clear(); + return false; + } + } + + return true; + } + catch (Exception exception) + { + destination.Clear(); + if (!_encodeFailureLogged) + { + _encodeFailureLogged = true; + Console.Error.WriteLine($"[LOADER][WARN] DualSense Bluetooth speaker encoding failed: {exception.Message}"); + } + + return false; + } + } + + private void Send(byte[] report) + { + if (_device is null) + { + if (Stopwatch.GetTimestamp() < _reopenAt) + { + return; + } + + _device = OpenPath(_path); + if (_device is null) + { + _reopenAt = Stopwatch.GetTimestamp() + Stopwatch.Frequency * ReopenDelayMilliseconds / 1000; + return; + } + } + + int written; + fixed (byte* data = report) + { + written = SDL_hid_write(_device, data, (nuint)report.Length); + } + + if (written >= 0) + { + return; + } + + if (!_writeFailureLogged) + { + _writeFailureLogged = true; + Console.Error.WriteLine($"[LOADER][WARN] DualSense Bluetooth audio report refused: {SDL_GetError()}"); + } + + SDL_hid_close(_device); + _device = null; + _reopenAt = Stopwatch.GetTimestamp() + Stopwatch.Frequency * ReopenDelayMilliseconds / 1000; + } + + private sealed class Client : IHostAudioStream + { + private readonly SdlDualSenseBluetooth _link; + private int _disposed; + + public Client(SdlDualSenseBluetooth link, uint sampleRate, double queueMilliseconds, bool speaker) + { + _link = link; + Haptics = new Lane(sampleRate, HapticRate, HapticFrames, queueMilliseconds); + try + { + Speaker = speaker ? new Lane(sampleRate, SpeakerRate, SpeakerFrames, queueMilliseconds) : null; + } + catch + { + Haptics.Dispose(); + throw; + } + } + + public Lane Haptics { get; } + + public Lane? Speaker { get; } + + public int QueuedMilliseconds => Haptics.QueuedMilliseconds; + + public bool Submit(ReadOnlySpan<byte> pcm) + { + if (Volatile.Read(ref _disposed) != 0) + { + return false; + } + + var samples = MemoryMarshal.Cast<byte, float>(pcm); + var frames = samples.Length / InputChannels; + if (frames == 0) + { + return true; + } + + var pair = ArrayPool<float>.Shared.Rent(frames * 2); + try + { + var stereo = pair.AsSpan(0, frames * 2); + if (Speaker is not null) + { + CopyPair(samples, stereo, 0); + Speaker.Put(stereo); + } + + CopyPair(samples, stereo, 2); + Haptics.Put(stereo); + } + finally + { + ArrayPool<float>.Shared.Return(pair); + } + + _link._signal.Set(); + return true; + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + _link.Detach(this); + } + } + + public void Release() + { + Haptics.Dispose(); + Speaker?.Dispose(); + } + + private static void CopyPair(ReadOnlySpan<float> samples, Span<float> stereo, int firstChannel) + { + for (var frame = 0; frame < stereo.Length / 2; frame++) + { + stereo[2 * frame] = samples[(frame * InputChannels) + firstChannel]; + stereo[(2 * frame) + 1] = samples[(frame * InputChannels) + firstChannel + 1]; + } + } + } + + private sealed class Lane : IDisposable + { + private const int FrameBytes = 2 * sizeof(float); + private readonly object _gate = new(); + private readonly int _outputRate; + private readonly int _primeBytes; + private readonly int _capacityBytes; + private SDL_AudioStream* _stream; + private bool _primed; + + public Lane(uint inputRate, int outputRate, int reportFrames, double queueMilliseconds) + { + var source = new SDL_AudioSpec + { + format = SDL_AudioFormat.SDL_AUDIO_F32LE, + channels = 2, + freq = checked((int)inputRate), + }; + var target = new SDL_AudioSpec + { + format = SDL_AudioFormat.SDL_AUDIO_F32LE, + channels = 2, + freq = outputRate, + }; + _stream = SDL_CreateAudioStream(&source, &target); + if (_stream is null) + { + throw new InvalidOperationException($"SDL audio stream creation failed: {SDL_GetError()}"); + } + + _outputRate = outputRate; + _primeBytes = reportFrames * 3 / 2 * FrameBytes; + _capacityBytes = Math.Max(2 * reportFrames, (int)(outputRate * queueMilliseconds / 1000)) * FrameBytes; + } + + public int QueuedMilliseconds + { + get + { + lock (_gate) + { + if (_stream is null) + { + return -1; + } + + var available = SDL_GetAudioStreamAvailable(_stream); + return available < 0 ? -1 : (int)(available / FrameBytes * 1000L / _outputRate); + } + } + } + + public void Put(ReadOnlySpan<float> stereo) + { + lock (_gate) + { + if (_stream is null) + { + return; + } + + fixed (float* data = stereo) + { + SDL_PutAudioStreamData(_stream, (nint)data, stereo.Length * sizeof(float)); + } + + var excess = SDL_GetAudioStreamAvailable(_stream) - _capacityBytes; + if (excess > 0) + { + Discard(excess); + } + } + } + + public bool MixInto(Span<float> destination) + { + lock (_gate) + { + if (_stream is null) + { + return false; + } + + if (!_primed && SDL_GetAudioStreamAvailable(_stream) < _primeBytes) + { + return false; + } + + var wanted = destination.Length * sizeof(float); + var buffer = ArrayPool<float>.Shared.Rent(destination.Length); + try + { + int read; + fixed (float* data = buffer) + { + read = SDL_GetAudioStreamData(_stream, (nint)data, wanted); + } + + _primed = read == wanted; + if (read <= 0) + { + return false; + } + + var samples = read / sizeof(float); + for (var index = 0; index < samples; index++) + { + destination[index] += buffer[index]; + } + + return true; + } + finally + { + ArrayPool<float>.Shared.Return(buffer); + } + } + } + + public void Dispose() + { + lock (_gate) + { + if (_stream is null) + { + return; + } + + SDL_DestroyAudioStream(_stream); + _stream = null; + } + } + + private void Discard(int bytes) + { + Span<byte> scratch = stackalloc byte[4096]; + bytes = (bytes + FrameBytes - 1) / FrameBytes * FrameBytes; + fixed (byte* buffer = scratch) + { + while (bytes > 0) + { + var read = SDL_GetAudioStreamData(_stream, (nint)buffer, Math.Min(bytes, scratch.Length)); + if (read <= 0) + { + break; + } + + bytes -= read; + } + } + } + } +} diff --git a/src/SharpEmu.HLE/Host/Sdl/SdlHostAudio.cs b/src/SharpEmu.HLE/Host/Sdl/SdlHostAudio.cs index 396bcf1db..f1b853082 100644 --- a/src/SharpEmu.HLE/Host/Sdl/SdlHostAudio.cs +++ b/src/SharpEmu.HLE/Host/Sdl/SdlHostAudio.cs @@ -54,6 +54,164 @@ public IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmForm return OpenStream(sampleRate, channels, format, cap); } + public IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmFormat format, int maxQueuedBytes) => + maxQueuedBytes > 0 ? OpenStream(sampleRate, channels, format, maxQueuedBytes) : OpenPcmStream(sampleRate, channels, format); + + /// <summary> + /// The controller's output device: exactly one wired DualSense and exactly one four-channel playback device named for + /// it ("DualSense", or "Wireless Controller" as Linux lists it). SDL ties no gamepad to its audio device, so anything + /// else (no pad, two pads, two candidate devices) gives no stream rather than a guess. While the + /// stream is open the pad's speaker plays the front pair; the back pair drives its actuators. + /// </summary> + public IHostAudioStream? TryOpenControllerStream(uint sampleRate, int maxQueuedBytes, out int channels, bool routeSpeaker = true) + { + channels = 0; + EnsureInitialized(); + IHostAudioStream stream; + string outputName; + if (TryFindDualSense(SDL_JoystickConnectionState.SDL_JOYSTICK_CONNECTION_WIRED, out var pad) && + TryFindControllerDevice(out var device, out var deviceName)) + { + stream = new AudioStream(device, sampleRate, 4, HostPcmFormat.Float32, maxQueuedBytes, reportsClock: false, dropOldest: true); + outputName = $"\"{deviceName}\""; + } + else if (TryFindDualSense(SDL_JoystickConnectionState.SDL_JOYSTICK_CONNECTION_WIRELESS, out pad) && + SdlDualSenseBluetooth.TryOpen(pad, sampleRate, maxQueuedBytes, routeSpeaker) is { } bluetooth) + { + stream = bluetooth; + outputName = "DualSense over Bluetooth"; + } + else + { + return null; + } + + var routed = routeSpeaker && SendControllerEffect(pad, ControllerAudioRoute(speaker: true)); + channels = 4; + Console.Error.WriteLine( + $"[LOADER][INFO] Controller audio: {outputName} (speaker {(routed ? "routed" : "not routed")})"); + return new ControllerAudioStream(stream, pad, routed); + } + + private static bool TryFindDualSense(SDL_JoystickConnectionState connection, out SDL_JoystickID pad) + { + pad = default; + var found = 0; + SDL_LockJoysticks(); + try + { + using var gamepads = SDL_GetGamepads(); + for (var index = 0; gamepads is not null && index < gamepads.Count; index++) + { + var id = gamepads[index]; + var gamepad = SDL_GetGamepadFromID(id); + if (gamepad is not null && + SDL_GetGamepadTypeForID(id) == SDL_GamepadType.SDL_GAMEPAD_TYPE_PS5 && + SDL_GetGamepadConnectionState(gamepad) == connection) + { + pad = id; + found++; + } + } + } + finally + { + SDL_UnlockJoysticks(); + } + + return found == 1; + } + + private static bool TryFindControllerDevice(out SDL_AudioDeviceID device, out string? deviceName) + { + device = default; + deviceName = null; + var found = 0; + using var devices = SDL_GetAudioPlaybackDevices(); + for (var index = 0; devices is not null && index < devices.Count; index++) + { + var name = SDL_GetAudioDeviceName(devices[index]); + SDL_AudioSpec spec; + int frames; + if (name is not null && + (name.Contains("DualSense", StringComparison.OrdinalIgnoreCase) || + name.Contains("Wireless Controller", StringComparison.OrdinalIgnoreCase)) && + SDL_GetAudioDeviceFormat(devices[index], &spec, &frames) && + spec.channels == 4) + { + (device, deviceName) = (devices[index], name); + found++; + } + } + + return found == 1; + } + + // The pad's audio routing, in its output report: with the speaker, the right channel of the front pair plays on the + // speaker and the headphone jack is muted (audio control and speaker volume valid, speaker volume 0x64, output path + // 0x30, speaker preamp +6 dB: the values Linux's driver uses without headphones); without it, the front pair goes + // back to the headphone jack. Plugged-in headphones are not detected. + private static byte[] ControllerAudioRoute(bool speaker) + { + var report = new byte[38]; + report[0] = 0x80; + if (speaker) + { + report[0] |= 0x20; + report[1] = 0x80; + report[5] = 0x64; + report[7] = 0x30; + report[37] = 0x02; + } + + return report; + } + + private static bool SendControllerEffect(SDL_JoystickID pad, byte[] report) + { + SDL_LockJoysticks(); + try + { + var gamepad = SDL_GetGamepadFromID(pad); + if (gamepad is null) + { + return false; + } + + fixed (byte* data = report) + { + return SDL_SendGamepadEffect(gamepad, (nint)data, report.Length); + } + } + finally + { + SDL_UnlockJoysticks(); + } + } + + private sealed class ControllerAudioStream(IHostAudioStream inner, SDL_JoystickID pad, bool speakerRouted) : IHostAudioStream + { + private int _disposed; + + public int QueuedMilliseconds => inner.QueuedMilliseconds; + + public bool Submit(ReadOnlySpan<byte> pcm) => inner.Submit(pcm); + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + inner.Dispose(); + if (speakerRouted) + { + SendControllerEffect(pad, ControllerAudioRoute(speaker: false)); + } + } + } + private static IHostAudioStream OpenStream( uint sampleRate, int channels, @@ -67,7 +225,7 @@ private static IHostAudioStream OpenStream( } EnsureInitialized(); - return new AudioStream(sampleRate, channels, format, maximumQueuedBytes); + return new AudioStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, sampleRate, channels, format, maximumQueuedBytes, reportsClock: true, dropOldest: false); } private static void EnsureInitialized() @@ -109,6 +267,8 @@ private sealed class AudioStream : IHostAudioStream private readonly int _bytesPerFrame; private readonly uint _sampleRate; private readonly int _streamId = Interlocked.Increment(ref _nextStreamId); + private readonly bool _reportsClock; + private readonly bool _dropOldest; private SDL_AudioStream* _stream; private bool _disposed; private long _totalSubmittedBytes; @@ -125,14 +285,19 @@ private sealed class AudioStream : IHostAudioStream private long _queuedByteSum; public AudioStream( + SDL_AudioDeviceID device, uint sampleRate, int channels, HostPcmFormat format, - int maximumQueuedBytes) + int maximumQueuedBytes, + bool reportsClock, + bool dropOldest) { var bytesPerSample = format == HostPcmFormat.Float32 ? sizeof(float) : sizeof(short); _bytesPerFrame = channels * bytesPerSample; _sampleRate = sampleRate; + _reportsClock = reportsClock; + _dropOldest = dropOldest; var spec = new SDL_AudioSpec { format = format == HostPcmFormat.Float32 @@ -143,7 +308,7 @@ public AudioStream( }; _stream = SDL_OpenAudioDeviceStream( - SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, + device, &spec, null, IntPtr.Zero); @@ -203,9 +368,9 @@ public bool Submit(ReadOnlySpan<byte> pcm) var blockStart = Stopwatch.GetTimestamp(); var deadline = blockStart + (Stopwatch.Frequency * MaximumWaitMilliseconds / 1_000); - int queued; var overrun = false; - while ((queued = SDL_GetAudioStreamQueued(_stream)) > _maximumQueuedBytes) + var queued = _dropOldest ? DropOldest(pcm.Length, out overrun) : 0; + while (!_dropOldest && (queued = SDL_GetAudioStreamQueued(_stream)) > _maximumQueuedBytes) { if (Stopwatch.GetTimestamp() >= deadline) { @@ -241,7 +406,7 @@ public bool Submit(ReadOnlySpan<byte> pcm) // what the player has actually heard. _totalSubmittedBytes += pcm.Length; var bytesPerSecond = (double)_bytesPerFrame * _sampleRate; - if (bytesPerSecond > 0) + if (_reportsClock && bytesPerSecond > 0) { GuestAudioClock.Report( Math.Max(0, _totalSubmittedBytes - queued - pcm.Length) / bytesPerSecond); @@ -252,6 +417,43 @@ public bool Submit(ReadOnlySpan<byte> pcm) } } + /// <summary> + /// For a stream the guest is not paced by: when the new audio would take the queue past its cap, the oldest + /// queued audio goes, a chunk at a time, so the gap after a device stall stays near one block (clearing the + /// whole queue leaves a long one) and the caller never waits. Caller holds <see cref="_gate"/>. + /// </summary> + private int DropOldest(int incomingBytes, out bool dropped) + { + var queued = Math.Max(0, SDL_GetAudioStreamQueued(_stream)); + dropped = queued + incomingBytes > _maximumQueuedBytes; + if (!dropped) + { + return queued; + } + + Span<byte> discard = stackalloc byte[4096]; + fixed (byte* buffer = discard) + { + for (var chunk = 0; chunk < 64 && queued + incomingBytes > _maximumQueuedBytes; chunk++) + { + if (SDL_GetAudioStreamData(_stream, (nint)buffer, discard.Length) <= 0) + { + break; + } + + queued = Math.Max(0, SDL_GetAudioStreamQueued(_stream)); + } + } + + if (queued + incomingBytes > _maximumQueuedBytes) + { + SDL_ClearAudioStream(_stream); + queued = 0; + } + + return queued; + } + /// <summary> /// Samples the queue depth at the moment the guest was allowed to write. /// That depth is the playback latency the guest's audio is subject to, so diff --git a/src/SharpEmu.HLE/Host/Windows/WindowsHostViews.cs b/src/SharpEmu.HLE/Host/Windows/WindowsHostViews.cs index 6bbe6c569..3ae6b166d 100644 --- a/src/SharpEmu.HLE/Host/Windows/WindowsHostViews.cs +++ b/src/SharpEmu.HLE/Host/Windows/WindowsHostViews.cs @@ -245,6 +245,23 @@ public bool ReleasePrivate(ulong address, ulong size) => public bool ChangeAccess(ulong address, ulong size, HostPageProtection protection) => VirtualProtect((void*)address, (nuint)size, GetNativeProtection(protection), out _); + public IReadOnlyList<HostPageAccess> QueryAccess(ulong address, ulong size) => + HostViewMemory.CollectAccess(address, size, static current => + { + if (VirtualQuery((void*)current, out var info, (nuint)sizeof(MemoryBasicInformation)) == 0) + { + return (false, default); + } + + return (true, new HostMemory.BasicInfo + { + BaseAddress = info.BaseAddress, + RegionSize = info.RegionSize, + State = info.State, + Protect = info.Protect, + }); + }); + public bool FreeOwnedRange(ulong address, ulong size) { var end = address + size; diff --git a/src/SharpEmu.HLE/SharpEmu.HLE.csproj b/src/SharpEmu.HLE/SharpEmu.HLE.csproj index c6d26a89d..def14f2da 100644 --- a/src/SharpEmu.HLE/SharpEmu.HLE.csproj +++ b/src/SharpEmu.HLE/SharpEmu.HLE.csproj @@ -23,6 +23,7 @@ SPDX-License-Identifier: GPL-2.0-or-later </ItemGroup> <ItemGroup> + <PackageReference Include="Concentus" /> <PackageReference Include="ppy.SDL3-CS" /> <PackageReference Include="ZstdSharp.Port" /> </ItemGroup> diff --git a/src/SharpEmu.LibAtrac9/BitAllocation.cs b/src/SharpEmu.LibAtrac9/BitAllocation.cs index 40404a5c2..18ecd0cce 100644 --- a/src/SharpEmu.LibAtrac9/BitAllocation.cs +++ b/src/SharpEmu.LibAtrac9/BitAllocation.cs @@ -113,7 +113,9 @@ public static void CalculatePrecisions(Channel channel) channel.PrecisionsFine[i] = 0; if (channel.Precisions[i] > 15) { - channel.PrecisionsFine[i] = channel.Precisions[i] - 15; + // The fine precision tops out at 15 (precision 30), the last entry of the step size table: a unit with + // a high scale factor and the boundary boost reached 16 or more and indexed past the table. + channel.PrecisionsFine[i] = Math.Min(channel.Precisions[i], 30) - 15; channel.Precisions[i] = 15; } } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index 8fdb6a2df..24e832952 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -501,6 +501,26 @@ internal void RecordIndexedDrawState(in DrawIndexedArguments arguments) SelectSnapshots(state, arguments.PacketAddress, indexed: true, arguments.IndexAddress, arguments.IndexCount); } + internal bool TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) + { + var state = RequireCurrent(); + var banks = RequireTypedRegisters(state); + if (_resolvePool is not { } pool || _executor is null || !Producing || + state.ActiveVertexSnapshots is { Count: > 0 } || state.ActiveIndexSnapshots is { Count: > 0 } || + !_drawWrites.TryGetValue((banks.Shader.Vertex.ExportAddress, banks.Shader.Pixel.Address), out var known) || + !known.Group || known.Registrations != ShaderHeaderRegistry.Registrations || !_executor.CanGroupIndexed(banks, in first)) return false; + Diagnostics.DispatchRunTally.NoteDraw(); + RecordIndexedDrawState(in first); + RecordKnownColorTargets(state, banks); + var run = offsets.ToArray(); + DeferDraw(pool, submitId, banks, true, in first, default, run); + state.FrameDrawCount += (uint)run.Length; + state.SawIndexedDraw = true; + state.CurrentIndexSnapshot = null; + state.CurrentVertexSnapshot = null; + return true; + } + public void DrawAuto(ulong submitId, in DrawAutoArguments arguments) { RecordAutoDrawState(in arguments); diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs b/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs index b4afdd50a..6d721393e 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs @@ -23,9 +23,12 @@ internal sealed record DeferredDraw : DeferredWork public bool Indexed; public DrawIndexedArguments IndexedArguments; public DrawAutoArguments AutoArguments; + public uint[]? IndirectOffsets; public long Sequence; public long FrontendImageVersion; public ResolvedDraw? Record; + // The sequence of the deferred draw right before this one when no register was written between them, or 0. + public long RepeatOf; public string? SerialReason; public Exception? Failure; public readonly ResolveReadLog Reads = new(); @@ -39,8 +42,10 @@ internal sealed record DeferredDraw : DeferredWork public void Reset() { Record = null; + RepeatOf = 0; SerialReason = null; Failure = null; + IndirectOffsets = null; FrontendImageVersion = 0; Reads.Clear(); Done.Reset(); @@ -93,7 +98,7 @@ internal sealed partial class CommandStreamTranslation private CapturingSink? _joinSink; private readonly ConcurrentQueue<DeferredDraw> _spareDeferred = new(); - private readonly Dictionary<(ulong Vertex, ulong Pixel), (bool Writes, long Registrations)> _drawWrites = new(); + private readonly Dictionary<(ulong Vertex, ulong Pixel), (bool Writes, long Registrations, bool Group)> _drawWrites = new(); private (ulong Vertex, ulong Pixel) _learningKey; // Only a draw whose shaders are known not to write memory resolves ahead of the stream: its @@ -114,11 +119,13 @@ private void LearnDrawWrites(ResolvedDraw record) { if (record.Kind == ResolvedDrawKind.Draw && _learningKey != default) { - _drawWrites[_learningKey] = (record.WritesMemory, ShaderHeaderRegistry.Registrations); + _drawWrites[_learningKey] = (record.WritesMemory, ShaderHeaderRegistry.Registrations, + !record.WritesMemory && RenderExecutor.SafeForRun(record.State.Programs.VertexInput.Stage.Program) && + (!record.State.PixelActive || RenderExecutor.SafeForRun(record.State.Programs.PixelInput.Stage.Program))); } } - private void DeferDraw(ResolvePool pool, ulong submitId, RegisterBanks banks, bool indexed, in DrawIndexedArguments indexedArguments, in DrawAutoArguments autoArguments) + private void DeferDraw(ResolvePool pool, ulong submitId, RegisterBanks banks, bool indexed, in DrawIndexedArguments indexedArguments, in DrawAutoArguments autoArguments, uint[]? offsets = null) { var work = _spareDeferred.TryDequeue(out var spare) ? spare : new DeferredDraw(); work.Banks = banks.Snapshot(work.Banks); @@ -126,9 +133,63 @@ private void DeferDraw(ResolvePool pool, ulong submitId, RegisterBanks banks, bo work.Indexed = indexed; work.IndexedArguments = indexedArguments; work.AutoArguments = autoArguments; + work.IndirectOffsets = offsets; work.Sequence = Sink!.EnqueueDeferred(work, isDraw: true); Interlocked.Increment(ref _deferredDraws); - pool.Dispatch(work); + var repeatable = indexed && offsets is null && indexedArguments.OffsetSource == DrawOffsetSource.IndirectArguments; + var route = -1; + if (repeatable && _repeatPrevious && work.Sequence == _repeatSequence + 1 && submitId == _repeatSubmit && + SameRegistersAsRepeatPrevious(work.Banks)) + { + work.RepeatOf = _repeatSequence; + route = _repeatRoute; + } + + route = pool.Dispatch(work, route); + _repeatPrevious = repeatable; + if (repeatable) + { + NoteRepeatPrevious(work.Banks, work.Sequence, submitId, route); + } + } + + // The last deferred indexed indirect draw: its banks' write stamps (a group with no write since then is equal) and + // the draw-time markers, and the worker it went to. + private bool _repeatPrevious; + private long _repeatSequence; + private ulong _repeatSubmit; + private int _repeatRoute; + private RegisterStampSet _repeatStamps; + private uint _repeatIndexType; + private UserScalarKind _repeatMarker; + private uint? _repeatDepthSize; + + private void NoteRepeatPrevious(RegisterBanks banks, long sequence, ulong submitId, int route) + { + _repeatSequence = sequence; + _repeatSubmit = submitId; + _repeatRoute = route; + for (var group = 0; group < RegisterStamps.Count; group++) + { + _repeatStamps[group] = banks.Stamp((RegisterStamp)group); + } + + _repeatIndexType = banks.IndexTypeAndSize; + _repeatMarker = banks.UserDataMarker; + _repeatDepthSize = banks.CompositeDepthSizeXy; + } + + private bool SameRegistersAsRepeatPrevious(RegisterBanks banks) + { + for (var group = 0; group < RegisterStamps.Count; group++) + { + if (banks.Stamp((RegisterStamp)group) != _repeatStamps[group]) + { + return false; + } + } + + return banks.IndexTypeAndSize == _repeatIndexType && banks.UserDataMarker == _repeatMarker && banks.CompositeDepthSizeXy == _repeatDepthSize; } private static void WaitResolved(DeferredDraw deferred) @@ -169,7 +230,8 @@ internal bool CanRecordDeferred(DeferredWork work) throw new InvalidOperationException("A resolve worker failed.", failure); } - return deferred.SerialReason is null && deferred.Record is not null && ValidateDeferredReads(deferred); + return deferred.SerialReason is null && deferred.Record is not null && + (deferred.IndirectOffsets is null || deferred.Record.IndirectOffsets is not null) && ValidateDeferredReads(deferred); } // At the stream position of a slice segment: whether a worker-resolved draw or dispatch it recorded still holds. @@ -224,12 +286,24 @@ record = ResolveOnThisThread(deferred); Interlocked.Increment(ref _deferredValid); } + bool expand = deferred.IndirectOffsets is not null && record.IndirectOffsets is null; _recorder!.Record(record); + if (expand) + { + var first = deferred.IndexedArguments; + var offsets = deferred.IndirectOffsets!; + for (int i = 1; i < offsets.Length; i++) + { + var next = first with { PacketAddress = first.PacketAddress + (uint)i * 20, + IndirectArgumentsAddress = first.IndirectArgumentsAddress + offsets[i] }; + _recorder.Record(ResolveOnThisThread(deferred, next)); + } + } deferred.Reset(); _spareDeferred.Enqueue(deferred); } - private ResolvedDraw ResolveOnThisThread(DeferredDraw deferred) + private ResolvedDraw ResolveOnThisThread(DeferredDraw deferred, DrawIndexedArguments? next = null) { var started = Stopwatch.GetTimestamp(); var sink = _joinSink ??= new CapturingSink(); @@ -238,7 +312,11 @@ private ResolvedDraw ResolveOnThisThread(DeferredDraw deferred) sink.Draw = null; if (deferred.Indexed) { - executor.DrawIndexed(deferred.SubmitId, deferred.Banks, in deferred.IndexedArguments); + var args = next ?? deferred.IndexedArguments; + if (next is null && deferred.IndirectOffsets is { } offsets) + executor.DrawIndexedCore(deferred.SubmitId, deferred.Banks, in args, offsets); + else + executor.DrawIndexed(deferred.SubmitId, deferred.Banks, in args); } else { @@ -277,6 +355,14 @@ private sealed class Worker public readonly CapturingSink Sink = new(); public Thread Thread = null!; public RenderExecutor Executor = null!; + + // The worker's copy of its last repeatable record, with its reads, image version and shader registrations; + // a repeat of that draw starts from it. TemplateSequence is -1 when there is none. + public readonly ResolvedDraw Template = new(); + public readonly ResolveReadLog TemplateReads = new(); + public long TemplateFrontendVersion; + public long TemplateRegistrations; + public long TemplateSequence = -1; } public ResolvePool(CommandStreamTranslation owner, IRenderHost host, int count) @@ -296,12 +382,12 @@ public ResolvePool(CommandStreamTranslation owner, IRenderHost host, int count) private const int SpillQueueLength = 32; // One shader pair keeps one worker while that worker keeps up; a run of its draws spills to - // the least loaded worker rather than wait in line. - public void Dispatch(DeferredDraw work) + // the least loaded worker rather than wait in line. A repeat goes to the worker of the draw it repeats. + public int Dispatch(DeferredDraw work, int repeatRoute) { var shader = work.Banks.Shader; - var route = (int)((uint)HashCode.Combine(shader.Vertex.ExportAddress, shader.Pixel.Address) % (uint)_workers.Length); - if (_workers[route].Queue.Count > SpillQueueLength) + var route = repeatRoute >= 0 ? repeatRoute : (int)((uint)HashCode.Combine(shader.Vertex.ExportAddress, shader.Pixel.Address) % (uint)_workers.Length); + if (repeatRoute < 0 && _workers[route].Queue.Count > SpillQueueLength) { var preferred = route; for (var index = 0; index < _workers.Length; index++) @@ -320,6 +406,7 @@ public void Dispatch(DeferredDraw work) Interlocked.Increment(ref _pending); _workers[route].Queue.Add(work); + return route; } public void WaitAllResolved() @@ -370,6 +457,66 @@ private void Run(Worker worker) } private void Resolve(Worker worker, DeferredDraw work) + { + if (work.RepeatOf != 0 && work.RepeatOf == worker.TemplateSequence && + worker.TemplateRegistrations == ShaderHeaderRegistry.Registrations && TryRepeat(worker, work)) + { + worker.TemplateSequence = work.Sequence; + return; + } + + // Kept programs and program keys depend on the shader registrations a resolve began with. + var registrations = ShaderHeaderRegistry.Registrations; + ResolveInFull(worker, work); + if (work.Record is { RepeatableArguments: true } record && work.SerialReason is null && work.Failure is null) + { + worker.Template.CopyFrom(record); + worker.TemplateReads.CopyFrom(work.Reads); + worker.TemplateFrontendVersion = work.FrontendImageVersion; + worker.TemplateRegistrations = registrations; + worker.TemplateSequence = work.Sequence; + } + else + { + worker.TemplateSequence = -1; + } + } + + // The repeat's read log is the template's, with the template's versions, plus the reads of its own arguments when + // the CPU reads them: the stream position checks every byte the record came from. + private bool TryRepeat(Worker worker, DeferredDraw work) + { + var host = _owner._host; + var started = Stopwatch.GetTimestamp(); + work.Reads.CopyFrom(worker.TemplateReads); + host.BeginWorkerResolve(work.Sequence, work.Reads); + work.Reads.Version = worker.TemplateReads.Version; + work.Reads.Publications = worker.TemplateReads.Publications; + try + { + worker.Sink.Sequence = work.Sequence; + worker.Sink.Draw = null; + if (worker.Executor.TryRepeatIndexed(worker.Template, work.SubmitId, work.Banks, in work.IndexedArguments)) + { + work.Record = worker.Sink.Draw; + work.FrontendImageVersion = worker.TemplateFrontendVersion; + Diagnostics.ItemCostTally.Note(work.CostKind, Diagnostics.ItemCostTally.Resolve, Stopwatch.GetTimestamp() - started); + return true; + } + } + catch (SerialResolveRequiredException) + { + } + finally + { + host.EndWorkerResolve(); + } + + work.Reads.Clear(); + return false; + } + + private void ResolveInFull(Worker worker, DeferredDraw work) { var host = _owner._host; work.FrontendImageVersion = _owner._pipelines!.FrontendImageVersion; @@ -381,7 +528,10 @@ private void Resolve(Worker worker, DeferredDraw work) worker.Sink.Draw = null; if (work.Indexed) { - worker.Executor.DrawIndexed(work.SubmitId, work.Banks, in work.IndexedArguments); + if (work.IndirectOffsets is { } offsets) + worker.Executor.DrawIndexedCore(work.SubmitId, work.Banks, in work.IndexedArguments, offsets); + else + worker.Executor.DrawIndexed(work.SubmitId, work.Banks, in work.IndexedArguments); } else { diff --git a/src/SharpEmu.Libs/Audio/AjmExports.cs b/src/SharpEmu.Libs/Audio/AjmExports.cs index fca933aad..7ed495440 100644 --- a/src/SharpEmu.Libs/Audio/AjmExports.cs +++ b/src/SharpEmu.Libs/Audio/AjmExports.cs @@ -51,6 +51,84 @@ public static class AjmExports private static int _nextContextId; private static int _nextBatchId; + // A batch runs its jobs in order on one host thread after sceAjmBatchStart, and sceAjmBatchWait collects it, as with the + // decoder hardware: a title that starts a batch and waits for it later no longer decodes on the thread that queued it. + // What a job may read from memory the title reuses after adding it (buffer descriptors, parameters) is read when the job + // is added. Tests that read a job's result as soon as it is added turn this off; the job then runs when it is added. + internal static bool AsyncBatches = true; + private const int OrbisAjmErrorInProgress = unchecked((int)0x8093000F); + private static readonly bool TraceEnabled = + string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AJM"), "1", StringComparison.Ordinal); + + private sealed class RunningBatch(List<Action<CpuContext>> jobs, ICpuMemory memory, Generation generation) + { + public List<Action<CpuContext>> Jobs { get; } = jobs; + public ICpuMemory Memory { get; } = memory; + public Generation Generation { get; } = generation; + public ManualResetEventSlim Done { get; } = new(false); + } + + private static readonly ConcurrentDictionary<ulong, List<Action<CpuContext>>> BuildingBatches = new(); + private static readonly ConcurrentDictionary<uint, RunningBatch> RunningBatches = new(); + private static readonly BlockingCollection<RunningBatch> BatchQueue = new(new ConcurrentQueue<RunningBatch>()); + private static readonly Lazy<Thread> BatchThread = new(() => + { + var thread = new Thread(RunBatches) { IsBackground = true, Name = "SharpEmu AJM", Priority = ThreadPriority.AboveNormal }; + thread.Start(); + return thread; + }); + private static int _asyncJobFaults; + + // Runs a job's work now, or adds it to the batch being built when that batch runs on the AJM thread. + private static void RunOrDefer(CpuContext ctx, ulong infoAddress, Action<CpuContext> work) + { + if (BuildingBatches.TryGetValue(infoAddress, out var jobs)) + { + lock (jobs) + { + jobs.Add(work); + } + + return; + } + + work(ctx); + } + + private static void RunBatches() + { + foreach (var batch in BatchQueue.GetConsumingEnumerable()) + { + var context = new CpuContext(batch.Memory, batch.Generation); + foreach (var job in batch.Jobs) + { + try + { + job(context); + } + catch (Exception exception) + { + if (Interlocked.Increment(ref _asyncJobFaults) <= 8) + { + Console.Error.WriteLine( + $"[AJM][WARN] a batch job failed on the AJM thread: {exception.GetType().Name}: {exception.Message}"); + } + } + } + + batch.Done.Set(); + } + } + + // Instance, codec and memory teardown first waits for the started batches, which may still use them. + private static void WaitForStartedBatches() + { + foreach (var batch in RunningBatches.Values) + { + batch.Done.Wait(); + } + } + private const uint AjmCodecMp3 = 0; private sealed class AjmInstanceState @@ -139,6 +217,7 @@ public static int AjmInitialize(CpuContext ctx) LibraryName = "libSceAjm")] public static int AjmFinalize(CpuContext ctx) { + WaitForStartedBatches(); if (!Contexts.TryRemove(unchecked((uint)ctx[CpuRegister.Rdi]), out var state)) { return ctx.SetReturn(OrbisAjmErrorInvalidContext); @@ -190,6 +269,7 @@ public static int AjmMemoryRegister(CpuContext ctx) LibraryName = "libSceAjm")] public static int AjmMemoryUnregister(CpuContext ctx) { + WaitForStartedBatches(); var contextId = unchecked((uint)ctx[CpuRegister.Rdi]); var address = ctx[CpuRegister.Rsi]; if (!Contexts.TryGetValue(contextId, out var state)) @@ -319,7 +399,7 @@ public static int AjmInstanceCreate(CpuContext ctx) Flags = flags, MaxChannels = maxChannels, Encoding = encoding, - Atrac9 = codecType == Atrac9CodecType ? new Atrac9DecodeState() : null, + Atrac9 = codecType == Atrac9CodecType ? new Atrac9DecodeState { ConcealsUndecodableSuperframes = true } : null, Mp3 = codecType == AjmCodecMp3 ? new AjmMp3Decoder() : null, Opus = codecType == OpusCodecType ? new AjmOpusDecoder(maxChannels, encoding) : null, }); @@ -336,6 +416,7 @@ public static int AjmInstanceCreate(CpuContext ctx) LibraryName = "libSceAjm")] public static int AjmInstanceDestroy(CpuContext ctx) { + WaitForStartedBatches(); var contextId = unchecked((uint)ctx[CpuRegister.Rdi]); var instanceId = unchecked((uint)ctx[CpuRegister.Rsi]); if (!Contexts.TryGetValue(contextId, out var state)) @@ -364,6 +445,7 @@ public static int AjmInstanceDestroy(CpuContext ctx) LibraryName = "libSceAjm")] public static int AjmModuleUnregister(CpuContext ctx) { + WaitForStartedBatches(); var contextId = unchecked((uint)ctx[CpuRegister.Rdi]); var codecType = unchecked((uint)ctx[CpuRegister.Rsi]); if (!Contexts.TryGetValue(contextId, out var state)) @@ -405,7 +487,20 @@ public static int AjmBatchInitialize(CpuContext ctx) return ctx.SetReturn(OrbisAjmErrorInvalidParameter); } - Trace($"batch_initialize buffer=0x{bufferAddress:X16} size=0x{bufferSize:X} info=0x{infoAddress:X16}"); + if (AsyncBatches) + { + BuildingBatches[infoAddress] = new List<Action<CpuContext>>(); + } + else + { + BuildingBatches.TryRemove(infoAddress, out _); + } + + if (TraceEnabled) + { + Trace($"batch_initialize buffer=0x{bufferAddress:X16} size=0x{bufferSize:X} info=0x{infoAddress:X16}"); + } + return ctx.SetReturn(0); } @@ -467,36 +562,45 @@ public static int AjmBatchJobInitialize(CpuContext ctx) return ctx.SetReturn(OrbisAjmErrorJobCreation); } - var status = Atrac9DecodeState.ResultInvalidParameter; - if (TryGetInstance(instanceId, out var instance)) + byte[]? parameters = null; + if (parametersAddress != 0 && parametersSize >= 4) { - if (instance.Opus is not null) + var read = new byte[parametersSize >= 12 ? 12 : 4]; + if (ctx.Memory.TryRead(parametersAddress, read)) { - Span<byte> parameters = stackalloc byte[12]; - if (parametersAddress != 0 && parametersSize >= (ulong)parameters.Length && - ctx.Memory.TryRead(parametersAddress, parameters) && instance.Opus.TryInitialize(parameters)) - status = 0; + parameters = read; } - else if (instance.Codec != Atrac9CodecType) - { - status = 0; - } - else if (instance.Atrac9 is not null && - parametersAddress != 0 && - parametersSize >= 4) + } + + RunOrDefer(ctx, infoAddress, c => + { + var status = Atrac9DecodeState.ResultInvalidParameter; + if (TryGetInstance(instanceId, out var instance)) { - Span<byte> configData = stackalloc byte[4]; - if (ctx.Memory.TryRead(parametersAddress, configData) && - instance.Atrac9.TryInitialize(configData)) + if (instance.Opus is not null) + { + if (parameters is { Length: >= 12 } && instance.Opus.TryInitialize(parameters.AsSpan(0, 12))) + status = 0; + } + else if (instance.Codec != Atrac9CodecType) + { + status = 0; + } + else if (instance.Atrac9 is not null && + parameters is { Length: >= 4 } && + instance.Atrac9.TryInitialize(parameters.AsSpan(0, 4))) { status = 0; } } - } - WriteBasicResult(ctx, resultAddress, status); - Trace( - $"batch_job_initialize instance=0x{instanceId:X8} params=0x{parametersAddress:X16}+0x{parametersSize:X} status=0x{status:X8}"); + WriteBasicResult(c, resultAddress, status); + if (TraceEnabled) + { + Trace( + $"batch_job_initialize instance=0x{instanceId:X8} params=0x{parametersAddress:X16}+0x{parametersSize:X} status=0x{status:X8}"); + } + }); return ctx.SetReturn(0); } @@ -516,15 +620,18 @@ public static int AjmBatchJobClearContext(CpuContext ctx) return ctx.SetReturn(OrbisAjmErrorJobCreation); } - var status = Atrac9DecodeState.ResultInvalidParameter; - if (TryGetInstance(instanceId, out var instance)) + RunOrDefer(ctx, infoAddress, c => { - instance.Atrac9?.Reset(); - instance.Opus?.Reset(); - status = 0; - } + var status = Atrac9DecodeState.ResultInvalidParameter; + if (TryGetInstance(instanceId, out var instance)) + { + instance.Atrac9?.Reset(); + instance.Opus?.Reset(); + status = 0; + } - WriteBasicResult(ctx, resultAddress, status); + WriteBasicResult(c, resultAddress, status); + }); return ctx.SetReturn(0); } @@ -609,14 +716,19 @@ public static int AjmBatchJobDecodeSplit(CpuContext ctx) return ctx.SetReturn(OrbisAjmErrorJobCreation); } - var result = DecodeJob( - ctx, instanceId, split: true, inputAddress, inputCount, outputAddress, outputCount, multipleFrames: true, - out _, out _); - WriteDecodeStreamResult(ctx, resultAddress, result, multipleFrames: true); - Trace( - $"batch_job_decode_split instance=0x{instanceId:X8} in=0x{inputAddress:X16}#{inputCount} " + - $"out=0x{outputAddress:X16}#{outputCount} consumed={result.InputConsumed} " + - $"produced={result.OutputWritten} frames={result.Frames} status=0x{result.Status:X8}"); + var plan = PrepareDecode(ctx, instanceId, split: true, inputAddress, inputCount, outputAddress, outputCount); + RunOrDefer(ctx, infoAddress, c => + { + var result = ExecuteDecode(c, plan, multipleFrames: true, out _, out _); + WriteDecodeStreamResult(c, resultAddress, result, multipleFrames: true); + if (TraceEnabled) + { + Trace( + $"batch_job_decode_split instance=0x{instanceId:X8} in=0x{inputAddress:X16}#{inputCount} " + + $"out=0x{outputAddress:X16}#{outputCount} consumed={result.InputConsumed} " + + $"produced={result.OutputWritten} frames={result.Frames} status=0x{result.Status:X8}"); + } + }); return ctx.SetReturn(0); } @@ -654,24 +766,27 @@ public static int AjmBatchJobSetGaplessDecode(CpuContext ctx) return ctx.SetReturn(OrbisAjmErrorJobCreation); } - var status = TryGetInstance(instanceId, out var instance) ? 0 : Atrac9DecodeState.ResultInvalidParameter; Span<byte> gapless = stackalloc byte[AjmSidebandGaplessDecodeBytes]; - if (status == 0 && gaplessAddress != 0 && ctx.Memory.TryRead(gaplessAddress, gapless)) + var haveWindow = gaplessAddress != 0 && ctx.Memory.TryRead(gaplessAddress, gapless); + var totalSamples = haveWindow ? BinaryPrimitives.ReadUInt32LittleEndian(gapless) : 0u; + var skipSamples = haveWindow ? BinaryPrimitives.ReadUInt16LittleEndian(gapless[4..]) : (ushort)0; + RunOrDefer(ctx, infoAddress, c => { - instance!.Atrac9?.SetGapless( - BinaryPrimitives.ReadUInt32LittleEndian(gapless), - BinaryPrimitives.ReadUInt16LittleEndian(gapless[4..]), - reset != 0); - instance.Opus?.SetGapless( - BinaryPrimitives.ReadUInt32LittleEndian(gapless), - BinaryPrimitives.ReadUInt16LittleEndian(gapless[4..]), - reset != 0); - } + var status = TryGetInstance(instanceId, out var instance) ? 0 : Atrac9DecodeState.ResultInvalidParameter; + if (status == 0 && haveWindow) + { + instance!.Atrac9?.SetGapless(totalSamples, skipSamples, reset != 0); + instance.Opus?.SetGapless(totalSamples, skipSamples, reset != 0); + } - WriteBasicResult(ctx, resultAddress, status); - Trace( - $"batch_job_set_gapless_decode instance=0x{instanceId:X8} " + - $"gapless=0x{gaplessAddress:X16} reset={reset} status=0x{status:X8}"); + WriteBasicResult(c, resultAddress, status); + if (TraceEnabled) + { + Trace( + $"batch_job_set_gapless_decode instance=0x{instanceId:X8} " + + $"gapless=0x{gaplessAddress:X16} reset={reset} status=0x{status:X8}"); + } + }); return ctx.SetReturn(0); } @@ -701,13 +816,17 @@ public static int AjmBatchJobSetResampleParameters(CpuContext ctx) const uint ignoreRatio = 1u << 3; var validRatio = (flags & ignoreRatio) != 0 || (float.IsFinite(ratio) && ratio is >= 0 and <= 4); - var status = TryGetInstance(instanceId, out var instance) && validRatio - ? 0 - : Atrac9DecodeState.ResultInvalidParameter; - if (status == 0) - instance.Opus?.SetResampleParameters(ratio, flags); - WriteBasicResult(ctx, resultAddress, status); - Trace($"batch_job_set_resample_parameters instance=0x{instanceId:X8} ratio={ratio:R} flags=0x{flags:X8} status=0x{status:X8}"); + RunOrDefer(ctx, infoAddress, c => + { + var status = TryGetInstance(instanceId, out var instance) && validRatio + ? 0 + : Atrac9DecodeState.ResultInvalidParameter; + if (status == 0) + instance!.Opus?.SetResampleParameters(ratio, flags); + WriteBasicResult(c, resultAddress, status); + if (TraceEnabled) + Trace($"batch_job_set_resample_parameters instance=0x{instanceId:X8} ratio={ratio:R} flags=0x{flags:X8} status=0x{status:X8}"); + }); return ctx.SetReturn(0); } @@ -723,20 +842,29 @@ public static int AjmBatchJobGetResampleInfo(CpuContext ctx) if (!TryAppendBatchJob(ctx, ctx[CpuRegister.Rdi], AjmJobRunSize)) return ctx.SetReturn(OrbisAjmErrorJobCreation); - Span<byte> result = stackalloc byte[48]; - result.Clear(); - if (TryGetInstance(unchecked((uint)ctx[CpuRegister.Rsi]), out var instance)) - { - var info = instance.Opus?.ResampleInfo ?? (Ratio: 1f, RemainingSamples: 0); - BinaryPrimitives.WriteSingleLittleEndian(result[8..], info.Ratio); - BinaryPrimitives.WriteInt32LittleEndian(result[12..], info.RemainingSamples); - } - else - { - BinaryPrimitives.WriteInt32LittleEndian(result, Atrac9DecodeState.ResultInvalidParameter); - } + var instanceId = unchecked((uint)ctx[CpuRegister.Rsi]); var address = ctx[CpuRegister.Rdx]; - return ctx.SetReturn(address == 0 || ctx.Memory.TryWrite(address, result) ? 0 : OrbisAjmErrorInvalidParameter); + RunOrDefer(ctx, ctx[CpuRegister.Rdi], c => + { + Span<byte> result = stackalloc byte[48]; + result.Clear(); + if (TryGetInstance(instanceId, out var instance)) + { + var info = instance.Opus?.ResampleInfo ?? (Ratio: 1f, RemainingSamples: 0); + BinaryPrimitives.WriteSingleLittleEndian(result[8..], info.Ratio); + BinaryPrimitives.WriteInt32LittleEndian(result[12..], info.RemainingSamples); + } + else + { + BinaryPrimitives.WriteInt32LittleEndian(result, Atrac9DecodeState.ResultInvalidParameter); + } + + if (address != 0) + { + c.Memory.TryWrite(address, result); + } + }); + return ctx.SetReturn(0); } [SysAbiExport( @@ -756,12 +884,12 @@ public static int AjmBatchJobGetStatistics(CpuContext ctx) if (resultAddress != 0) { - Span<byte> result = stackalloc byte[AjmStatisticsResultBytes]; - result.Clear(); - if (!ctx.Memory.TryWrite(resultAddress, result)) + RunOrDefer(ctx, infoAddress, c => { - return ctx.SetReturn(OrbisAjmErrorInvalidParameter); - } + Span<byte> result = stackalloc byte[AjmStatisticsResultBytes]; + result.Clear(); + c.Memory.TryWrite(resultAddress, result); + }); } ctx.GetXmmRegister(0, out var intervalBits, out _); @@ -893,6 +1021,25 @@ public static int AjmBatchStart(CpuContext ctx) ClearAjmBatchError(ctx, errorAddress); var batchId = unchecked((uint)Interlocked.Increment(ref _nextBatchId)); + if (BuildingBatches.TryRemove(infoAddress, out var jobs)) + { + if (RunningBatches.Count > 256) + { + foreach (var (id, finished) in RunningBatches) + { + if (finished.Done.IsSet) + { + RunningBatches.TryRemove(id, out _); + } + } + } + + var running = new RunningBatch(jobs, ctx.Memory, ctx.TargetGeneration); + RunningBatches[batchId] = running; + _ = BatchThread.Value; + BatchQueue.Add(running); + } + Span<byte> batchValue = stackalloc byte[sizeof(uint)]; BinaryPrimitives.WriteUInt32LittleEndian(batchValue, batchId); if (!ctx.Memory.TryWrite(batchOutAddress, batchValue)) @@ -900,9 +1047,13 @@ public static int AjmBatchStart(CpuContext ctx) return ctx.SetReturn(OrbisAjmErrorInvalidParameter); } - Trace( - $"batch_start context={contextId} info=0x{infoAddress:X16} " + - $"priority={priority} batch={batchId} error=0x{errorAddress:X16}"); + if (TraceEnabled) + { + Trace( + $"batch_start context={contextId} info=0x{infoAddress:X16} " + + $"priority={priority} batch={batchId} error=0x{errorAddress:X16}"); + } + return ctx.SetReturn(0); } @@ -913,13 +1064,35 @@ public static int AjmBatchStart(CpuContext ctx) LibraryName = "libSceAjm")] public static int AjmBatchWait(CpuContext ctx) { - // Batches complete synchronously in Start; Wait is a no-op success. + // A batch that ran on the AJM thread is collected here (timeout in milliseconds, all ones waits forever); the others + // completed in Start. var errorAddress = ctx[CpuRegister.Rcx]; + var batchId = unchecked((uint)ctx[CpuRegister.Rsi]); + var timeout = unchecked((uint)ctx[CpuRegister.Rdx]); + if (RunningBatches.TryGetValue(batchId, out var running)) + { + if (!running.Done.IsSet) + { + var finished = timeout == uint.MaxValue + ? running.Done.Wait(Timeout.Infinite) + : running.Done.Wait((int)Math.Min(timeout, (uint)int.MaxValue)); + if (!finished) + { + return ctx.SetReturn(OrbisAjmErrorInProgress); + } + } + + RunningBatches.TryRemove(batchId, out _); + } + ClearAjmBatchError(ctx, errorAddress); - Trace( - $"batch_wait context={unchecked((uint)ctx[CpuRegister.Rdi])} " + - $"batch={unchecked((uint)ctx[CpuRegister.Rsi])} " + - $"timeout={unchecked((uint)ctx[CpuRegister.Rdx])}"); + if (TraceEnabled) + { + Trace( + $"batch_wait context={unchecked((uint)ctx[CpuRegister.Rdi])} " + + $"batch={batchId} timeout={timeout}"); + } + return ctx.SetReturn(0); } @@ -951,60 +1124,65 @@ private static int AjmBatchJobDecodeCore(CpuContext ctx, bool multipleFrames) return ctx.SetReturn(OrbisAjmErrorJobCreation); } - Atrac9DecodeResult result; - if (!TryGetInstance(instanceId, out var instance)) + RunOrDefer(ctx, infoAddress, c => { - result = new Atrac9DecodeResult( - Atrac9DecodeState.ResultInvalidParameter, - 0, - 0, - 0, - 0); - } - else if (instance.Mp3 is not null) - { - // GTA V Enhanced streams menu music through AJM MP3 (codec 0). - // Decoded eagerly here so BatchStart/Wait stay synchronous no-ops. - result = DecodeMp3( - ctx, - instance, - inputAddress, - inputSize, - outputAddress, - outputSize); - } - else if (instance.Opus is null && (instance.Codec != Atrac9CodecType || instance.Atrac9 is null)) - { - if (outputAddress != 0 && - outputSize is > 0 and <= MaxDecodeBufferBytes) + Atrac9DecodeResult result; + if (!TryGetInstance(instanceId, out var instance)) { - ClearGuestMemory(ctx, outputAddress, outputSize); + result = new Atrac9DecodeResult( + Atrac9DecodeState.ResultInvalidParameter, + 0, + 0, + 0, + 0); + } + else if (instance.Mp3 is not null) + { + // GTA V Enhanced streams menu music through AJM MP3 (codec 0). + result = DecodeMp3( + c, + instance, + inputAddress, + inputSize, + outputAddress, + outputSize); } + else if (instance.Opus is null && (instance.Codec != Atrac9CodecType || instance.Atrac9 is null)) + { + if (outputAddress != 0 && + outputSize is > 0 and <= MaxDecodeBufferBytes) + { + ClearGuestMemory(c, outputAddress, outputSize); + } - result = new Atrac9DecodeResult( - 0, - unchecked((int)Math.Min(inputSize, int.MaxValue)), - 0, - 0, - inputSize != 0 || outputSize != 0 ? 1u : 0u); - } - else - { - result = DecodeAudio( - ctx, - instance, - inputAddress, - inputSize, - outputAddress, - outputSize, - multipleFrames); - } + result = new Atrac9DecodeResult( + 0, + unchecked((int)Math.Min(inputSize, int.MaxValue)), + 0, + 0, + inputSize != 0 || outputSize != 0 ? 1u : 0u); + } + else + { + result = DecodeAudio( + c, + instance, + inputAddress, + inputSize, + outputAddress, + outputSize, + multipleFrames); + } - WriteDecodeStreamResult(ctx, resultAddress, result, multipleFrames); - Trace( - $"batch_job_decode instance=0x{instanceId:X8} in=0x{inputAddress:X16}+0x{inputSize:X} " + - $"out=0x{outputAddress:X16}+0x{outputSize:X} consumed={result.InputConsumed} " + - $"produced={result.OutputWritten} frames={result.Frames} status=0x{result.Status:X8}"); + WriteDecodeStreamResult(c, resultAddress, result, multipleFrames); + if (TraceEnabled) + { + Trace( + $"batch_job_decode instance=0x{instanceId:X8} in=0x{inputAddress:X16}+0x{inputSize:X} " + + $"out=0x{outputAddress:X16}+0x{outputSize:X} consumed={result.InputConsumed} " + + $"produced={result.OutputWritten} frames={result.Frames} status=0x{result.Status:X8}"); + } + }); return ctx.SetReturn(0); } @@ -1046,18 +1224,27 @@ private static int AjmBatchJobRunCore(CpuContext ctx, bool split) } var multipleFrames = (flags & AjmJobRunFlagMultipleFrames) != 0; - var result = DecodeJob( - ctx, instanceId, split, inputAddress, inputCountOrSize, outputAddress, outputCountOrSize, multipleFrames, - out var instance, out var config); + var plan = PrepareDecode(ctx, instanceId, split, inputAddress, inputCountOrSize, outputAddress, outputCountOrSize); + RunOrDefer(ctx, infoAddress, c => + { + var result = ExecuteDecode(c, plan, multipleFrames, out var instance, out var config); + WriteRunSideband(c, sidebandAddress, sidebandSize, flags, result, instance, config); + if (TraceEnabled) + { + Trace( + $"batch_job_run{(split ? "_split" : string.Empty)} instance=0x{instanceId:X8} flags=0x{flags:X} " + + $"in=0x{inputAddress:X16}#{inputCountOrSize} out=0x{outputAddress:X16}#{outputCountOrSize} " + + $"sideband=0x{sidebandAddress:X16}+0x{sidebandSize:X} consumed={result.InputConsumed} " + + $"produced={result.OutputWritten} frames={result.Frames} status=0x{result.Status:X8}"); + } + }); + + if (TraceEnabled) + { + TraceBufferDescriptors(ctx, split, "in", inputAddress, inputCountOrSize); + TraceBufferDescriptors(ctx, split, "out", outputAddress, outputCountOrSize); + } - WriteRunSideband(ctx, sidebandAddress, sidebandSize, flags, result, instance, config); - Trace( - $"batch_job_run{(split ? "_split" : string.Empty)} instance=0x{instanceId:X8} flags=0x{flags:X} " + - $"in=0x{inputAddress:X16}#{inputCountOrSize} out=0x{outputAddress:X16}#{outputCountOrSize} " + - $"sideband=0x{sidebandAddress:X16}+0x{sidebandSize:X} consumed={result.InputConsumed} " + - $"produced={result.OutputWritten} frames={result.Frames} status=0x{result.Status:X8}"); - TraceBufferDescriptors(ctx, split, "in", inputAddress, inputCountOrSize); - TraceBufferDescriptors(ctx, split, "out", outputAddress, outputCountOrSize); return ctx.SetReturn(0); } @@ -1070,32 +1257,58 @@ private static ulong SplitJobSize(ulong inputCount, ulong outputCount) => /// The decode body of the flag-driven jobs and of sceAjmBatchJobDecodeSplit: ATRAC9 and Opus instances decode, /// any other codec stays a silence stub that reports the input consumed. /// </summary> - private static Atrac9DecodeResult DecodeJob( + private sealed record DecodePlan( + uint InstanceId, + bool BuffersValid, + List<AjmGuestBuffer> Inputs, + int InputLength, + List<AjmGuestBuffer> Outputs, + int OutputLength); + + // Reads the job's buffer descriptors when the job is added: the title may build them in memory it reuses afterwards. + private static DecodePlan PrepareDecode( CpuContext ctx, uint instanceId, bool split, ulong inputAddress, ulong inputCountOrSize, ulong outputAddress, - ulong outputCountOrSize, + ulong outputCountOrSize) + { + if (TryCollectBuffers(ctx, split, inputAddress, inputCountOrSize, out var inputs, out var inputLength) && + TryCollectBuffers(ctx, split, outputAddress, outputCountOrSize, out var outputs, out var outputLength)) + { + return new DecodePlan(instanceId, true, inputs, inputLength, outputs, outputLength); + } + + return new DecodePlan(instanceId, false, [], 0, [], 0); + } + + private static Atrac9DecodeResult ExecuteDecode( + CpuContext ctx, + DecodePlan plan, bool multipleFrames, out AjmInstanceState? instance, out Atrac9Config? config) { config = null; - if (!TryGetInstance(instanceId, out var found)) + if (!TryGetInstance(plan.InstanceId, out var found)) { instance = null; return new Atrac9DecodeResult(Atrac9DecodeState.ResultInvalidParameter, 0, 0, 0, 0); } instance = found; - if (!TryCollectBuffers(ctx, split, inputAddress, inputCountOrSize, out var inputs, out var inputLength) || - !TryCollectBuffers(ctx, split, outputAddress, outputCountOrSize, out var outputs, out var outputLength)) + if (!plan.BuffersValid) { return new Atrac9DecodeResult(Atrac9DecodeState.ResultInvalidParameter, 0, 0, 0, 0); } + var inputs = plan.Inputs; + var inputLength = plan.InputLength; + var outputs = plan.Outputs; + var outputLength = plan.OutputLength; + if (found.Opus is null && (found.Codec != Atrac9CodecType || found.Atrac9 is null)) { foreach (var buffer in outputs) @@ -1128,7 +1341,7 @@ private static void TraceBufferDescriptors( address == 0 || countOrSize == 0 || countOrSize > MaxBufferDescriptors || - !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AJM"), "1", StringComparison.Ordinal)) + !TraceEnabled) { return; } @@ -1470,6 +1683,10 @@ private static Atrac9PcmEncoding GetPcmEncoding(ulong flags) => internal static void ResetForTests() { + WaitForStartedBatches(); + BuildingBatches.Clear(); + RunningBatches.Clear(); + AsyncBatches = false; foreach (var context in Contexts.Values) { lock (context.Gate) @@ -1638,7 +1855,7 @@ private static bool TryWriteUInt64(CpuContext ctx, ulong address, ulong value) private static void Trace(string message) { - if (string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AJM"), "1", StringComparison.Ordinal)) + if (TraceEnabled) { Console.Error.WriteLine($"[LOADER][TRACE] ajm.{message}"); } diff --git a/src/SharpEmu.Libs/Audio/AjmOpusDecoder.cs b/src/SharpEmu.Libs/Audio/AjmOpusDecoder.cs index 8b31ee575..e21ca635c 100644 --- a/src/SharpEmu.Libs/Audio/AjmOpusDecoder.cs +++ b/src/SharpEmu.Libs/Audio/AjmOpusDecoder.cs @@ -25,6 +25,10 @@ internal sealed unsafe class AjmOpusDecoder(int maxChannels, Atrac9PcmEncoding e private bool _disposed; private Atrac9Gapless _gaplessInitial; private Atrac9Gapless _gapless; + + // Samples written and lead-in samples discarded since the last reset: the gapless window counts from there. + private uint _producedSinceReset; + private uint _skippedSinceReset; private ulong _totalSamples; public int Channels { get; private set; } @@ -106,6 +110,8 @@ public void Reset() _totalSamples = 0; FramesPerPacket = 0; _gapless = _gaplessInitial; + _producedSinceReset = 0; + _skippedSinceReset = 0; _end = false; } } @@ -114,9 +120,18 @@ public void SetGapless(uint totalSamples, ushort skipSamples, bool reset) { lock (_gate) { + // As the ATRAC9 window: a set without a reset moves the limits and keeps the progress made against them. _gaplessInitial = new Atrac9Gapless(totalSamples, skipSamples, 0); - if (reset || _gapless == default) - _gapless = _gaplessInitial; + if (reset) + { + _producedSinceReset = 0; + _skippedSinceReset = 0; + } + + _gapless = new Atrac9Gapless( + totalSamples is not 0 and not uint.MaxValue ? totalSamples - Math.Min(totalSamples, _producedSinceReset) : totalSamples, + (ushort)(skipSamples - Math.Min(skipSamples, _skippedSinceReset)), + reset ? (ushort)0 : _gapless.SkippedSamples); } } @@ -205,6 +220,8 @@ public Atrac9DecodeResult Decode(ReadOnlySpan<byte> input, Span<byte> output, bo frames += packetFrames; FramesPerPacket = packetFrames; _totalSamples += (uint)count; + _producedSinceReset = unchecked(_producedSinceReset + (uint)count); + _skippedSinceReset = unchecked(_skippedSinceReset + (uint)skipped); _gapless = _gapless with { SkipSamples = (ushort)(_gapless.SkipSamples - skipped), diff --git a/src/SharpEmu.Libs/Audio/Atrac9DecodeState.cs b/src/SharpEmu.Libs/Audio/Atrac9DecodeState.cs index 92feeb755..b4b18b2e7 100644 --- a/src/SharpEmu.Libs/Audio/Atrac9DecodeState.cs +++ b/src/SharpEmu.Libs/Audio/Atrac9DecodeState.cs @@ -24,6 +24,9 @@ internal readonly record struct Atrac9DecodeResult( internal sealed class Atrac9DecodeState { + // Set by AJM, whose titles retry a failed job forever: an undecodable superframe plays as silence instead. + public bool ConcealsUndecodableSuperframes { get; init; } + internal const int ResultNotInitialized = 0x00000001; internal const int ResultInvalidData = 0x00000002; internal const int ResultInvalidParameter = 0x00000004; @@ -52,6 +55,10 @@ private enum ContainerScan private Atrac9Gapless _gaplessInit; private Atrac9Gapless _gapless; + // Samples written and lead-in samples discarded since the last reset: the gapless window counts from there. + private uint _producedSinceReset; + private uint _skippedSinceReset; + public Atrac9Gapless Gapless { get @@ -63,15 +70,24 @@ public Atrac9Gapless Gapless } } + // The window counts from the last reset. A set without a reset moves its limits and keeps the progress made against + // them: a title that sends the same window with every job keeps its place, and one that sends a new window after + // initializing the instance for the next sound gets that window. public void SetGapless(uint totalSamples, ushort skipSamples, bool reset) { lock (_gate) { _gaplessInit = new Atrac9Gapless(totalSamples, skipSamples, 0); - if (reset || _gapless == default) + if (reset) { - _gapless = _gaplessInit; + _producedSinceReset = 0; + _skippedSinceReset = 0; } + + _gapless = new Atrac9Gapless( + HasSampleLimit ? totalSamples - Math.Min(totalSamples, _producedSinceReset) : totalSamples, + (ushort)(skipSamples - Math.Min(skipSamples, _skippedSinceReset)), + reset ? (ushort)0 : _gapless.SkippedSamples); } } @@ -112,6 +128,8 @@ public bool TryInitialize(ReadOnlySpan<byte> configData) _totalDecodedSamples = 0; _containerHeaderLength = 0; _gapless = _gaplessInit; + _producedSinceReset = 0; + _skippedSinceReset = 0; Trace( $"initialized config={Convert.ToHexString(normalizedConfig)} channels={config.ChannelCount} " + $"rate={config.SampleRate} frame_samples={config.FrameSamples} " + @@ -145,6 +163,8 @@ public void Reset() _totalDecodedSamples = 0; _containerHeaderLength = 0; _gapless = _gaplessInit; + _producedSinceReset = 0; + _skippedSinceReset = 0; if (_compressed is not null) { Array.Clear(_compressed); @@ -192,18 +212,15 @@ public Atrac9DecodeResult Decode( while (_compressedLength == config.SuperframeBytes || consumed < input.Length) { - if (HasSampleLimit && _gapless.TotalSamples == 0) - { - break; - } - // Titles that stream whole .at9 files hand AJM the RIFF/WAVE // container rather than a pointer into its `data` chunk, so the // stream has to be advanced past the header before the first // superframe — otherwise every job fails with invalid data and // the title drops the voice. This is checked at every superframe // boundary, not just after initialize, because a looping voice - // rewinds to the file header without reinitialising. + // rewinds to the file header without reinitialising. It comes before + // the window check: the header of the next pass restarts a window the + // last pass used up. if (_compressedLength == 0 && (_containerHeaderLength != 0 || consumed < input.Length)) { var scan = ScanContainerHeader(input[consumed..], out var headerBytes); @@ -219,24 +236,20 @@ public Atrac9DecodeResult Decode( _containerHeader = null; _containerHeaderLength = 0; consumed += headerBytes; + // The header may have brought another stream's codec configuration. + config = _decoder!.Config; + channels = requestedChannels > 0 ? requestedChannels : config.ChannelCount; continue; } } - if (_compressedLength < config.SuperframeBytes) - { - var copied = Math.Min(config.SuperframeBytes - _compressedLength, input.Length - consumed); - input.Slice(consumed, copied).CopyTo(_compressed.AsSpan(_compressedLength)); - _compressedLength += copied; - consumed += copied; - } - - if (_compressedLength < config.SuperframeBytes) + if (HasSampleLimit && _gapless.TotalSamples == 0) { - status |= ResultPartialInput; break; } + // The room check comes before the superframe's bytes are taken: a superframe the output has no room for + // stays in the input, as the codec leaves it, instead of being reported consumed with nothing produced. var skip = Math.Min(config.SuperframeSamples, (int)_gapless.SkipSamples); var samples = config.SuperframeSamples - skip; if (HasSampleLimit) @@ -251,6 +264,20 @@ public Atrac9DecodeResult Decode( break; } + if (_compressedLength < config.SuperframeBytes) + { + var copied = Math.Min(config.SuperframeBytes - _compressedLength, input.Length - consumed); + input.Slice(consumed, copied).CopyTo(_compressed.AsSpan(_compressedLength)); + _compressedLength += copied; + consumed += copied; + } + + if (_compressedLength < config.SuperframeBytes) + { + status |= ResultPartialInput; + break; + } + try { _decoder.Decode(_compressed, _planarPcm); @@ -263,13 +290,30 @@ public Atrac9DecodeResult Decode( $"config={Convert.ToHexString(_configData ?? [])} " + $"head={Convert.ToHexString(_compressed.AsSpan(0, Math.Min(16, _compressed.Length)))} " + $"error={exception.GetType().Name}: {exception.Message}"); - _compressedLength = 0; - return new Atrac9DecodeResult( - status | ResultInvalidData | ResultCodecError, - consumed, - written, - _totalDecodedSamples, - frames); + + // AJM plays a superframe it cannot decode as silence and goes on: a title that expects its + // stream to decode retries a failed job without advancing, so an error left the voice stuck on + // that superframe for good. Superframes decode independently, so the codec starts fresh for the + // next one. Other users report the error. + if (!ConcealsUndecodableSuperframes) + { + _compressedLength = 0; + return new Atrac9DecodeResult( + status | ResultInvalidData | ResultCodecError, + consumed, + written, + _totalDecodedSamples, + frames); + } + + foreach (var plane in _planarPcm) + { + Array.Clear(plane); + } + + var fresh = new Atrac9Decoder(); + fresh.Initialize((byte[])_configData!.Clone()); + _decoder = fresh; } WriteInterleaved( @@ -287,6 +331,8 @@ public Atrac9DecodeResult Decode( written += outputBytes; _compressedLength = 0; _totalDecodedSamples += unchecked((uint)samples); + _producedSinceReset = unchecked(_producedSinceReset + (uint)samples); + _skippedSinceReset = unchecked(_skippedSinceReset + (uint)skip); frames += unchecked((uint)config.FramesPerSuperframe); if (!multipleFrames) @@ -295,6 +341,12 @@ public Atrac9DecodeResult Decode( } } + // A job without input reports that it needs some, as for a partial superframe. + if (input.IsEmpty && written == 0 && _compressedLength < config.SuperframeBytes) + { + status |= ResultPartialInput; + } + return new Atrac9DecodeResult( status, consumed, @@ -320,7 +372,7 @@ private ContainerScan ScanContainerHeader(ReadOnlySpan<byte> input, out int inpu input[..copied].CopyTo(_containerHeader.AsSpan(previousLength)); var totalLength = previousLength + copied; - if (!TryFindRiffDataOffset(_containerHeader.AsSpan(0, totalLength), out var dataOffset)) + if (!TryFindRiffDataOffset(_containerHeader.AsSpan(0, totalLength), out var dataOffset, out var fact, out var headerConfig)) { if (totalLength >= MaxContainerHeaderBytes) { @@ -339,13 +391,67 @@ private ContainerScan ScanContainerHeader(ReadOnlySpan<byte> input, out int inpu } inputHeaderBytes = dataOffset - previousLength; - Trace($"container_header_skipped bytes={dataOffset} from_this_input={inputHeaderBytes}"); + if (headerConfig is not null) + { + RestartCodec(headerConfig); + } + + if (fact is { } window) + { + RestartWindow(window.Total, window.Skip); + } + + Trace($"container_header_skipped bytes={dataOffset} from_this_input={inputHeaderBytes} fact={fact}"); return ContainerScan.Found; } - private static bool TryFindRiffDataOffset(ReadOnlySpan<byte> header, out int dataOffset) + // A stream that reaches a RIFF header starts over as the hardware's header parse does: a looping voice rewinds to its + // file header, and a title may feed the next file through the same instance, without initializing it. The format + // chunk's codec configuration starts the codec fresh (taking that stream's configuration), and the fact chunk's + // sample count and lead-in are the new window. Without it, a window the previous pass used up kept the voice silent + // for good while the title went on feeding it. + private void RestartCodec(byte[] headerConfig) + { + try + { + var decoder = new Atrac9Decoder(); + decoder.Initialize((byte[])headerConfig.Clone()); + var config = decoder.Config; + if (_configData is null || !_configData.AsSpan().SequenceEqual(headerConfig)) + { + _configData = headerConfig; + _compressed = new byte[config.SuperframeBytes]; + _planarPcm = CreatePcmBuffer(config.ChannelCount, config.SuperframeSamples); + } + + _decoder = decoder; + _compressedLength = 0; + _totalDecodedSamples = 0; + } + catch (Exception exception) when (exception is ArgumentException or InvalidDataException or InvalidOperationException) + { + Trace($"header_config_rejected config={Convert.ToHexString(headerConfig)} error={exception.Message}"); + } + } + + private void RestartWindow(uint totalSamples, uint skipSamples) + { + _gaplessInit = new Atrac9Gapless(totalSamples, (ushort)Math.Min(skipSamples, ushort.MaxValue), 0); + _gapless = _gaplessInit; + _producedSinceReset = 0; + _skippedSinceReset = 0; + } + + // The ATRAC9 subformat of a WAVE_FORMAT_EXTENSIBLE format chunk; the codec configuration follows at byte 44. + private static ReadOnlySpan<byte> Atrac9SubFormat => + [0xD2, 0x42, 0xE1, 0x47, 0xBA, 0x36, 0x8D, 0x4D, 0x88, 0xFC, 0x61, 0x65, 0x4F, 0x8C, 0x83, 0x6C]; + + private static bool TryFindRiffDataOffset( + ReadOnlySpan<byte> header, out int dataOffset, out (uint Total, uint Skip)? fact, out byte[]? config) { dataOffset = 0; + fact = null; + config = null; if (header.Length < 12 || !header[..4].SequenceEqual("RIFF"u8) || !header.Slice(8, 4).SequenceEqual("WAVE"u8)) @@ -365,6 +471,19 @@ private static bool TryFindRiffDataOffset(ReadOnlySpan<byte> header, out int dat return true; } + if (chunkId.SequenceEqual("fact"u8) && chunkSize >= 8 && offset + 8 <= header.Length) + { + fact = (BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset, 4)), + BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(offset + 4, 4))); + } + + if (chunkId.SequenceEqual("fmt "u8) && chunkSize >= 48 && offset + 48 <= header.Length && + BinaryPrimitives.ReadUInt16LittleEndian(header.Slice(offset, 2)) == 0xFFFE && + header.Slice(offset + 24, 16).SequenceEqual(Atrac9SubFormat)) + { + config = header.Slice(offset + 44, 4).ToArray(); + } + // RIFF chunks are word aligned. var advance = chunkSize + (chunkSize & 1); if (advance > (ulong)(int.MaxValue - offset)) @@ -454,5 +573,7 @@ private void Clear() _containerHeaderLength = 0; _compressedLength = 0; _totalDecodedSamples = 0; + _producedSinceReset = 0; + _skippedSinceReset = 0; } } diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index 4aa9e3426..bb35ab228 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -79,7 +79,23 @@ private static bool AllowStackOut(string which) => internal const uint PassthroughLeft = 1; internal const uint PassthroughRight = 2; private const float HalfPower = 0.70710677f; + // A first-order scene is decoded for stereo by two virtual microphones facing about 74 degrees + // left and right (ACN channels are SN3D; FuMa channels are MaxN, W at sqrt(0.5)): a source ahead + // plays at full level on both sides (W + X = 1), one behind at -3 dB, one at the side with the + // power it has ahead. Microphones facing 90 degrees (W and Y alone) played sources ahead 3 dB + // below those at the sides, and the room's diffuse sound louder than the direct sound. + private const float AmbisonicsW = 0.85355339f; + private const float AmbisonicsX = 0.14644661f; + private const float AmbisonicsY = 0.52100538f; + private const float FumaW = AmbisonicsW * 1.41421356f; private const ushort PortStateOutputConnectedPrimary = 0x01; + // The output a port reaches when it plays on the controller's speaker. + private const ushort PortStateOutputConnectedController = 0x04; + private const ushort AudioOut2PortTypePadSpeaker = 3; + // The controller stream holds at most this much audio (its oldest audio goes past it): the guest is paced by its + // main output, and the controller's device runs on a clock of its own. + private const int ControllerQueueLimitMilliseconds = 80; + private const int ControllerChannelCount = 4; // A host device that already holds this much audio is pacing the context; anything beyond the // cushion counts as queued grains. The cushion stays below the emulated queue so host @@ -246,10 +262,21 @@ public PortState( private static IHostAudioStream? SecondaryBackend; private static string PrimaryBackendName = "none"; private static string SecondaryBackendName = "none"; + private static bool PrimaryBackendFloat; + private static bool SecondaryBackendFloat; + // A runaway gain cannot reach the device: float output is bounded far above full scale (+12 dBFS). + private const float FloatOutputBound = 4f; private static ulong PrimaryContextHandle; private static readonly object HostSubmitGate = new(); private static Func<uint, IHostAudioStream?>? _streamFactoryForTests; + // The controller's own output device, opened once on first need: the pad speaker port plays on its first two + // channels and the vibration port on its actuators, the last two (when the device has them). Without it both ports + // stay silent, as before. + private static IHostAudioStream? ControllerBackend; + private static bool ControllerOpenTried; + private static Func<uint, IHostAudioStream?>? _controllerFactoryForTests; + [SysAbiExport( Nid = "g2tViFIohHE", ExportName = "sceAudioOut2Initialize", @@ -512,6 +539,8 @@ public static int AudioOut2ContextPush(CpuContext ctx) Producers[producer] = context; } + _lastPushTimestamp = Stopwatch.GetTimestamp(); + // Host Submit already blocks on the output queue; software pacing covers grains with nothing // queued, once per grain whichever of Advance and Push comes first. var submitted = TrySubmitContextAudio(ctx, context); @@ -743,7 +772,7 @@ public static int AudioOut2PortSetAttributes(CpuContext ctx) byte[]? pcmData = null; if (pcmAddress != 0 && TryDecodeDataFormat(port.DataFormat, out var channels, out var bytesPerSample, out _) && - IsSnapshotPcmPort(port.PortType, channels)) + IsSnapshotPcmPort(port, channels)) { int byteLength; try @@ -885,7 +914,12 @@ public static int AudioOut2PortGetState(CpuContext ctx) channels = (byte)Math.Clamp(decodedChannels, 1, SpeakerMax); } - BinaryPrimitives.WriteUInt16LittleEndian(state[0x00..], PortStateOutputConnectedPrimary); + // A pad speaker port that plays on the controller's speaker reports that output. + BinaryPrimitives.WriteUInt16LittleEndian( + state[0x00..], + port is not null && (port.PortType & 0xFF) == AudioOut2PortTypePadSpeaker && ControllerTakes(port) + ? PortStateOutputConnectedController + : PortStateOutputConnectedPrimary); state[0x02] = channels; BinaryPrimitives.WriteInt16LittleEndian(state[0x04..], 127); @@ -1217,6 +1251,31 @@ public static int AudioOut2UserGetSupportedAttributes(CpuContext ctx) return SetReturn(ctx, 0); } + // A float stream keeps the mix's headroom: the 16-bit stream clipped every peak above full scale before the host + // applied its volume, which the host's float mixer does not. The queue cap is the same duration as the 16-bit one. + private static IHostAudioStream OpenContextStream(uint frequency, out bool isFloat) + { + var audio = HostPlatform.Current.Audio; + if (audio is IHostPcmAudioOutput pcm) + { + isFloat = true; + return pcm.OpenPcmStream(frequency, channels: 2, HostPcmFormat.Float32, maxQueuedBytes: 256 * 1024); + } + + isFloat = false; + return audio.OpenStereoPcm16Stream(frequency, maxQueuedPcmBytes: 128 * 1024); + } + + private static bool IsFloatBackend(IHostAudioStream backend) + { + lock (HostBackendGate) + { + return ReferenceEquals(backend, PrimaryBackend) + ? PrimaryBackendFloat + : ReferenceEquals(backend, SecondaryBackend) && SecondaryBackendFloat; + } + } + private static IHostAudioStream? ResolveContextBackend(ContextState context, out string backendName) { lock (HostBackendGate) @@ -1240,11 +1299,8 @@ public static int AudioOut2UserGetSupportedAttributes(CpuContext ctx) } else { - var audio = HostPlatform.Current.Audio; - PrimaryBackend = audio.OpenStereoPcm16Stream( - context.Frequency, - maxQueuedPcmBytes: 128 * 1024); - PrimaryBackendName = audio.BackendName + "-primary"; + PrimaryBackend = OpenContextStream(context.Frequency, out PrimaryBackendFloat); + PrimaryBackendName = HostPlatform.Current.Audio.BackendName + (PrimaryBackendFloat ? "-primary-f32" : "-primary"); } } catch (Exception exception) @@ -1271,11 +1327,8 @@ public static int AudioOut2UserGetSupportedAttributes(CpuContext ctx) } else { - var audio = HostPlatform.Current.Audio; - SecondaryBackend = audio.OpenStereoPcm16Stream( - context.Frequency, - maxQueuedPcmBytes: 128 * 1024); - SecondaryBackendName = audio.BackendName + "-secondary"; + SecondaryBackend = OpenContextStream(context.Frequency, out SecondaryBackendFloat); + SecondaryBackendName = HostPlatform.Current.Audio.BackendName + (SecondaryBackendFloat ? "-secondary-f32" : "-secondary"); } } catch (Exception exception) @@ -1294,6 +1347,45 @@ public static int AudioOut2UserGetSupportedAttributes(CpuContext ctx) internal static double DeviceSlotFreeThreshold(uint grainSamples, uint frequency, uint queueDepth) => DeviceCushionMilliseconds + (grainSamples * 1000.0 / frequency * Math.Max((long)queueDepth - 1, 0)); + // The guest thread's last push: a thread that pushed within the last ActiveProducerMilliseconds feeds a context now. + [ThreadStatic] + private static long _lastPushTimestamp; + + private const double ActiveProducerMilliseconds = 20; + + // A nap at most this long is the one an idle job worker takes between jobs. + internal const ulong PreciseNapLimitMicroseconds = 1000; + + /// <summary> + /// True when a short usleep on this thread must take only the time it asks for: the thread pushed into an AudioOut2 + /// context within the last 20 ms and the device holds less than its cushion. A host timer wait rounds a nap of + /// 51 us up to about 0.5 ms, so a producer that naps between the jobs of each grain falls behind the device. + /// </summary> + public static bool ProducerNeedsPreciseNap(ulong microseconds) + { + if (microseconds > PreciseNapLimitMicroseconds || + _lastPushTimestamp == 0 || + !Producers.TryGetValue(GuestThreadExecution.CurrentGuestThreadHandle, out var context) || + !context.DevicePaced || + context.DeviceBackend is not { } backend) + { + return false; + } + + var sincePush = (Stopwatch.GetTimestamp() - _lastPushTimestamp) * 1000.0 / Stopwatch.Frequency; + return PreciseProducerNap(microseconds, sincePush, backend.QueuedMilliseconds, context.GrainSamples, context.Frequency); + } + + // A nap of at most PreciseNapLimitMicroseconds by a thread that pushed within the last ActiveProducerMilliseconds, while + // the device reports less than its cushion less one grain (-1: it cannot report). + internal static bool PreciseProducerNap(ulong microseconds, double millisecondsSincePush, int queuedMilliseconds, + uint grainSamples, uint frequency) => + microseconds <= PreciseNapLimitMicroseconds && + millisecondsSincePush >= 0 && + millisecondsSincePush < ActiveProducerMilliseconds && + queuedMilliseconds >= 0 && + queuedMilliseconds < DeviceCushionMilliseconds - (grainSamples * 1000.0 / frequency); + /// <summary> /// Halves a usleep taken by a thread that feeds an AudioOut2 context while the device runs short, /// so a producer paced by fixed sleeps (CRI's mixer: 5 ms per 5.33 ms grain) can catch up. @@ -1371,11 +1463,12 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) lock (HostSubmitGate) { var mix = ArrayPool<float>.Shared.Rent(frames * 2); - var output = ArrayPool<byte>.Shared.Rent(frames * AudioPcmConversion.OutputFrameSize); + var output = ArrayPool<byte>.Shared.Rent(frames * 2 * sizeof(float)); try { mix.AsSpan(0, frames * 2).Clear(); var mixedPorts = 0; + float[]? controllerMix = null; foreach (var port in Ports.Values) { if (port.ContextHandle != context.Handle || @@ -1384,6 +1477,31 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) continue; } + if (ControllerTakes(port)) + { + var padBytes = frames * ch * bps; + if (TakePortPcmSnapshot(port) is { } padPcm && padPcm.Length >= padBytes) + { + if (controllerMix is null) + { + controllerMix = ArrayPool<float>.Shared.Rent(frames * ControllerChannelCount); + controllerMix.AsSpan(0, frames * ControllerChannelCount).Clear(); + } + + MixPortIntoController( + padPcm.AsSpan(0, padBytes), + controllerMix, + frames, + ch, + bps, + isFloat, + port.Gain, + (port.PortType & 0xFF) == AudioOut2PortTypePadSpeaker ? 0 : 2); + } + + continue; + } + var pcmData = TakePortPcmSnapshot(port); if (pcmData is null) { @@ -1425,25 +1543,24 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) mixedPorts++; } - if (mixedPorts == 0) + if (controllerMix is not null && ControllerBackend is { } controller) { - TraceSubmitSkipped(context, frames, "no-ports"); - return false; + var controllerOutput = ArrayPool<byte>.Shared.Rent(frames * ControllerChannelCount * sizeof(float)); + try + { + controller.Submit(WriteFloatOutput(controllerMix.AsSpan(0, frames * ControllerChannelCount), controllerOutput, out _)); + } + finally + { + ArrayPool<byte>.Shared.Return(controllerOutput); + ArrayPool<float>.Shared.Return(controllerMix); + } } - var outputSpan = output.AsSpan(0, frames * AudioPcmConversion.OutputFrameSize); - var peak = 0f; - for (var frame = 0; frame < frames; frame++) + if (mixedPorts == 0) { - var left = Math.Clamp(mix[frame * 2], -1f, 1f); - var right = Math.Clamp(mix[(frame * 2) + 1], -1f, 1f); - peak = Math.Max(peak, Math.Max(Math.Abs(left), Math.Abs(right))); - BinaryPrimitives.WriteInt16LittleEndian( - outputSpan[(frame * AudioPcmConversion.OutputFrameSize)..], - FloatToPcm16(left)); - BinaryPrimitives.WriteInt16LittleEndian( - outputSpan[((frame * AudioPcmConversion.OutputFrameSize) + 2)..], - FloatToPcm16(right)); + TraceSubmitSkipped(context, frames, "no-ports"); + return false; } var backend = ResolveContextBackend(context, out var backendName); @@ -1453,6 +1570,10 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) return false; } + float peak; + var outputSpan = IsFloatBackend(backend) + ? WriteFloatOutput(mix.AsSpan(0, frames * 2), output, out peak) + : WritePcm16Output(mix.AsSpan(0, frames * 2), output, out peak); context.DeviceBackend = backend; var n = Interlocked.Increment(ref _submitTraceCount); @@ -1520,10 +1641,16 @@ internal static void ResetForTests() SecondaryBackend = null; PrimaryBackendName = "none"; SecondaryBackendName = "none"; + PrimaryBackendFloat = false; + SecondaryBackendFloat = false; PrimaryContextHandle = 0; + ControllerBackend?.Dispose(); + ControllerBackend = null; + ControllerOpenTried = false; } Volatile.Write(ref _streamFactoryForTests, null); + Volatile.Write(ref _controllerFactoryForTests, null); } private static bool IsMainOrBgmPort(ushort portType) @@ -1567,29 +1694,113 @@ internal static bool TryGetStereoGains( return true; } + // ACN orders the first order W, Y, Z, X; FuMa orders it W, X, Y, Z. Z and the higher orders + // add nothing to a horizontal pair. var acn = ambisonics >= AmbisonicsAcnBase; var component = acn ? ambisonics - AmbisonicsAcnBase : ambisonics; if (component == 0) { - left = acn ? gain * HalfPower : gain; + left = gain * (acn ? AmbisonicsW : FumaW); right = left; return true; } if (component == (acn ? 1u : 2u)) { - left = gain * HalfPower; + left = gain * AmbisonicsY; right = -left; return true; } + if (component == (acn ? 3u : 1u)) + { + left = gain * AmbisonicsX; + right = left; + return true; + } + return false; } - private static bool IsSnapshotPcmPort(ushort portType, int channels) => - RoutesToSpeakers(portType) && - (portType & 0xFF) != AudioOut2PortTypeVibration && - (!IsObjectPort(portType) || channels == 1); + private static bool IsSnapshotPcmPort(PortState port, int channels) => + (RoutesToSpeakers(port.PortType) && + (port.PortType & 0xFF) != AudioOut2PortTypeVibration && + (!IsObjectPort(port.PortType) || channels == 1)) || + ControllerTakes(port); + + private static bool IsControllerPort(ushort portType) => + !IsObjectPort(portType) && (portType & 0xFF) is AudioOut2PortTypePadSpeaker or AudioOut2PortTypeVibration; + + // A pad speaker or vibration port plays on the controller's own output device, when the host has one. + private static bool ControllerTakes(PortState port) => + IsControllerPort(port.PortType) && EnsureControllerBackend(port.SamplingFrequency) is not null; + + private static IHostAudioStream? EnsureControllerBackend(uint frequency) + { + lock (HostBackendGate) + { + if (ControllerOpenTried) + { + return ControllerBackend; + } + + ControllerOpenTried = true; + var maxQueuedBytes = (int)(frequency * ControllerChannelCount * sizeof(float) * (long)ControllerQueueLimitMilliseconds / 1000); + try + { + if (Volatile.Read(ref _streamFactoryForTests) is not null) + { + // Tests choose the controller; without one there is none. + ControllerBackend = Volatile.Read(ref _controllerFactoryForTests)?.Invoke(frequency); + } + else if (HostPlatform.Current.Audio is IHostPcmAudioOutput pcm && + pcm.TryOpenControllerStream(frequency, maxQueuedBytes, out var channels) is { } stream) + { + if (channels == ControllerChannelCount) + { + ControllerBackend = stream; + } + else + { + stream.Dispose(); + } + } + } + catch (Exception exception) + { + ControllerBackend = null; + Console.Error.WriteLine($"[LOADER][WARN] AudioOut2 controller output unavailable: {exception.Message}"); + } + + return ControllerBackend; + } + } + + // A port's first two channels onto a pair of the controller's four: the speaker pair at 0, the actuators at 2. A mono + // port plays on both channels of its pair. + internal static void MixPortIntoController( + ReadOnlySpan<byte> source, + Span<float> mix, + int frames, + int channels, + int bytesPerSample, + bool isFloat, + float gain, + int firstChannel) + { + var frameSize = channels * bytesPerSample; + for (var frame = 0; frame < frames; frame++) + { + var frameBytes = source.Slice(frame * frameSize, frameSize); + var first = ReadNormalizedSample(frameBytes, 0, bytesPerSample, isFloat); + var second = channels == 1 ? first : ReadNormalizedSample(frameBytes, 1, bytesPerSample, isFloat); + mix[(frame * ControllerChannelCount) + firstChannel] += first * gain; + mix[(frame * ControllerChannelCount) + firstChannel + 1] += second * gain; + } + } + + internal static void SetControllerFactoryForTests(Func<uint, IHostAudioStream?>? controllerFactory) => + Volatile.Write(ref _controllerFactoryForTests, controllerFactory); internal static void MixPortIntoStereo( ReadOnlySpan<byte> source, @@ -1650,6 +1861,36 @@ private static float ReadNormalizedSample( return BinaryPrimitives.ReadInt16LittleEndian(sample) / 32768f; } + // The mix as interleaved float samples, bounded far above full scale only. + internal static Span<byte> WriteFloatOutput(ReadOnlySpan<float> mix, Span<byte> output, out float peak) + { + peak = 0f; + var span = output[..(mix.Length * sizeof(float))]; + for (var i = 0; i < mix.Length; i++) + { + var value = Math.Clamp(mix[i], -FloatOutputBound, FloatOutputBound); + peak = Math.Max(peak, Math.Abs(value)); + BinaryPrimitives.WriteSingleLittleEndian(span[(i * sizeof(float))..], value); + } + + return span; + } + + // The mix as interleaved 16-bit samples, clipped at full scale. + internal static Span<byte> WritePcm16Output(ReadOnlySpan<float> mix, Span<byte> output, out float peak) + { + peak = 0f; + var span = output[..(mix.Length * sizeof(short))]; + for (var i = 0; i < mix.Length; i++) + { + var value = Math.Clamp(mix[i], -1f, 1f); + peak = Math.Max(peak, Math.Abs(value)); + BinaryPrimitives.WriteInt16LittleEndian(span[(i * sizeof(short))..], FloatToPcm16(value)); + } + + return span; + } + private static short FloatToPcm16(float value) { var scale = value < 0f ? 32768f : short.MaxValue; diff --git a/src/SharpEmu.Libs/Audio/AudioOutExports.cs b/src/SharpEmu.Libs/Audio/AudioOutExports.cs index eb7f017b1..2d22936e1 100644 --- a/src/SharpEmu.Libs/Audio/AudioOutExports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOutExports.cs @@ -7,6 +7,7 @@ using System.Buffers.Binary; using System.Collections.Concurrent; using System.Diagnostics; +using System.Runtime.InteropServices; namespace SharpEmu.Libs.Audio; @@ -25,10 +26,18 @@ public static class AudioOutExports internal const int AudioOutErrorPortFull = unchecked((int)0x80260005); internal const int AudioOutErrorInvalidSize = unchecked((int)0x80260006); + // The pad speaker and vibration ports play on the controller's own four channels: the speaker pair, then the + // actuators. + private const int PortTypePadSpeaker = 4; + private const int PortTypeVibration = 10; + private const int ControllerChannels = 4; + private const int ControllerQueueMilliseconds = 80; + private static readonly ConcurrentDictionary<int, PortState> Ports = new(); private static readonly ConcurrentDictionary<int, PortState> ShutdownPorts = new(); private static int _nextPortHandle; private static Func<uint, IHostAudioStream?>? _streamFactoryForTests; + private static Func<uint, IHostAudioStream?>? _controllerFactoryForTests; // Diagnostic: confirm sceAudioOutOutput is actually called and whether the // guest submits real samples or silence. Gated so it costs nothing when off. @@ -78,6 +87,8 @@ public PortState( public bool PreservesGuestFormat { get; } public IHostAudioStream? Backend { get; } public string BackendName { get; } + // The first of the two controller channels this port plays on, or -1 for the speakers. + public int ControllerPair { get; init; } = -1; public object SubmissionGate { get; } = new(); public volatile float Volume = 1.0f; public int BufferByteLength => @@ -153,11 +164,23 @@ public static int AudioOutOpen(CpuContext ctx) IHostAudioStream? backend = null; var preservesGuestFormat = false; + var controllerPair = type switch + { + PortTypePadSpeaker => 0, + PortTypeVibration => 2, + _ => -1, + }; string backendName; try { var streamFactory = Volatile.Read(ref _streamFactoryForTests); - if (streamFactory is not null) + if (controllerPair >= 0) + { + // A controller port plays on the controller or stays silent, never on the speakers. + backend = OpenControllerBackend(frequency, speaker: controllerPair == 0); + backendName = backend is null ? "silent" : "controller"; + } + else if (streamFactory is not null) { backend = streamFactory(frequency); backendName = "test"; @@ -199,7 +222,10 @@ public static int AudioOutOpen(CpuContext ctx) isFloat, preservesGuestFormat, backend, - backendName); + backendName) + { + ControllerPair = controllerPair, + }; Console.Error.WriteLine( $"[LOADER][INFO] AudioOut port {handle}: {frequency} Hz, " + $"{channels} ch, {(isFloat ? "float32" : "s16")}, " + @@ -348,14 +374,14 @@ public static int AudioOutOutput(CpuContext ctx) return ctx.SetReturn(0); } - var outputLength = port.PreservesGuestFormat - ? port.BufferByteLength - : checked((int)port.BufferLength * AudioPcmConversion.OutputFrameSize); + var outputLength = HostBufferLength(port); var output = ArrayPool<byte>.Shared.Rent(outputLength); try { ConvertForHost(port, source, output.AsSpan(0, outputLength)); - if (!port.Backend.Submit(output.AsSpan(0, outputLength))) + // The controller's stream drops its oldest audio instead of blocking, so a controller port keeps the + // real-time pace here. + if (!port.Backend.Submit(output.AsSpan(0, outputLength)) || port.ControllerPair >= 0) { port.PaceSilence(); } @@ -476,9 +502,7 @@ private static int SubmitOutputs(CpuContext ctx, ReadOnlySpan<OutputDescriptor> TraceOutput(output.Handle, output.Port, source); - output.HostBufferLength = output.Port.PreservesGuestFormat - ? output.Port.BufferByteLength - : checked((int)output.Port.BufferLength * AudioPcmConversion.OutputFrameSize); + output.HostBufferLength = HostBufferLength(output.Port); output.HostBuffer = ArrayPool<byte>.Shared.Rent(output.HostBufferLength); ConvertForHost(output.Port, source, output.HostBuffer.AsSpan(0, output.HostBufferLength)); } @@ -495,7 +519,8 @@ private static int SubmitOutputs(CpuContext ctx, ReadOnlySpan<OutputDescriptor> if (output.HostBuffer is null || output.Port.Backend is null || !output.Port.Backend.Submit( - output.HostBuffer.AsSpan(0, output.HostBufferLength))) + output.HostBuffer.AsSpan(0, output.HostBufferLength)) || + output.Port.ControllerPair >= 0) { if (pacingPort is null || HasLongerBufferDuration(output.Port, pacingPort)) @@ -572,8 +597,53 @@ private static int PaceShutdownPorts(ReadOnlySpan<OutputDescriptor> descriptors) return 0; } + private static int HostBufferLength(PortState port) => + port.ControllerPair >= 0 ? checked((int)port.BufferLength * ControllerChannels * sizeof(float)) + : port.PreservesGuestFormat ? port.BufferByteLength + : checked((int)port.BufferLength * AudioPcmConversion.OutputFrameSize); + + private static IHostAudioStream? OpenControllerBackend(uint frequency, bool speaker) + { + if (Volatile.Read(ref _streamFactoryForTests) is not null) + { + // Tests choose the controller; without one there is none. + return Volatile.Read(ref _controllerFactoryForTests)?.Invoke(frequency); + } + + if (HostPlatform.Current.Audio is not IHostPcmAudioOutput pcm) + { + return null; + } + + var maxQueuedBytes = (int)(frequency * ControllerChannels * sizeof(float) * (long)ControllerQueueMilliseconds / 1000); + var stream = pcm.TryOpenControllerStream(frequency, maxQueuedBytes, out var channels, speaker); + if (stream is not null && channels != ControllerChannels) + { + stream.Dispose(); + return null; + } + + return stream; + } + private static void ConvertForHost(PortState port, ReadOnlySpan<byte> source, Span<byte> destination) { + if (port.ControllerPair >= 0) + { + var mix = MemoryMarshal.Cast<byte, float>(destination); + mix.Clear(); + AudioOut2Exports.MixPortIntoController( + source, + mix, + checked((int)port.BufferLength), + port.Channels, + port.BytesPerSample, + port.IsFloat, + port.Volume, + port.ControllerPair); + return; + } + if (port.PreservesGuestFormat) { AudioPcmConversion.CopyWithVolume(source, destination, port.IsFloat, port.Volume); @@ -701,6 +771,9 @@ public static void ShutdownAllPorts() internal static void SetStreamFactoryForTests(Func<uint, IHostAudioStream?>? streamFactory) => Volatile.Write(ref _streamFactoryForTests, streamFactory); + internal static void SetControllerFactoryForTests(Func<uint, IHostAudioStream?>? controllerFactory) => + Volatile.Write(ref _controllerFactoryForTests, controllerFactory); + internal static void ResetForTests() { foreach (var handle in Ports.Keys) @@ -716,6 +789,7 @@ internal static void ResetForTests() _outputCount = 0; Volatile.Write(ref _shutdown, false); Volatile.Write(ref _streamFactoryForTests, null); + Volatile.Write(ref _controllerFactoryForTests, null); } private static bool _shutdown; diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index 66f0d64b8..95ff09a20 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -55,8 +55,6 @@ private enum ShutdownOutcome private readonly AvlSpanSet _gpuModifiedRanges = new(); private readonly ReaderWriterLockSlim _gpuModifiedGate = new(LockRecursionPolicy.NoRecursion); - private SpanSnapshot _gpuModifiedSnapshot = SpanSnapshot.Empty; - private GpuModifiedWrite WriteGpuModified() { _gpuModifiedGate.EnterWriteLock(); @@ -67,7 +65,7 @@ private readonly ref struct GpuModifiedWrite(GuestBufferCache cache) { public void Dispose() { - Volatile.Write(ref cache._gpuModifiedSnapshot, cache._gpuModifiedRanges.Snapshot()); + cache._gpuModifiedRanges.PublishChanges(); cache._gpuModifiedGate.ExitWriteLock(); } } @@ -142,17 +140,7 @@ public bool DefersGpuWriteProtection set => _tracker.DefersGpuWriteProtection = value; } - public void ApplyPendingGpuProtections() - { - Volatile.Write(ref _copyWritesPending, 0); - _tracker.ApplyPendingGpuProtections(); - } - - private int _copyWritesPending; - - public bool CopyWritesPending => Volatile.Read(ref _copyWritesPending) != 0; - - public void NoteCopyWrite() => Volatile.Write(ref _copyWritesPending, 1); + public void ApplyPendingGpuProtections() => _tracker.ApplyPendingGpuProtections(); public GpuBuffer GdsBuffer => _gds; @@ -462,7 +450,6 @@ public void PrepareBufferAllocations(ReadOnlySpan<GuestSpan> ranges) return null; } - NoteCopyWrite(); return ObtainBuffer(guestAddress, size, isWritten: true).Buffer; } @@ -607,12 +594,7 @@ public void FillBuffer(ulong guestAddress, ulong size, uint value, bool isGds) = private void FillBuffer(ulong guestAddress, ulong size, uint value, bool isGds, bool publishFill) { - if (!isGds) - { - CompleteGuestPublications?.Invoke(guestAddress, size, PublicationAccess.Write); - NoteCopyWrite(); - } - + if (!isGds) CompleteGuestPublications?.Invoke(guestAddress, size, PublicationAccess.Write); if ((guestAddress & 3) != 0 || size == 0 || (size & 3) != 0 || size > ulong.MaxValue - guestAddress) { throw SubmissionScheduler.Fatal("The fill range must be aligned to four bytes."); @@ -863,12 +845,7 @@ public bool TryCopyWordsOnHost(ulong destination, ulong source, ulong sourceWord public void CopyBuffer(ulong dstVaddr, ulong srcVaddr, ulong size, bool dstGds, bool srcGds) { - if (!dstGds) - { - CompleteGuestPublications?.Invoke(dstVaddr, size, PublicationAccess.Write); - NoteCopyWrite(); - } - + if (!dstGds) CompleteGuestPublications?.Invoke(dstVaddr, size, PublicationAccess.Write); if (!srcGds) CompleteGuestPublications?.Invoke(srcVaddr, size, PublicationAccess.Read); var dstMemory = !dstGds; var srcMemory = !srcGds; @@ -966,7 +943,7 @@ public bool HasGpuDirtyBytes(ulong guestAddress, ulong size) Environment.FailFast($"The address range is invalid: 0x{guestAddress:X16}, 0x{size:X16}."); } - return Volatile.Read(ref _gpuModifiedSnapshot).Overlaps(guestAddress, size); + return _gpuModifiedRanges.PublishedOverlaps(guestAddress, size); } public bool EverGpuWritten(ulong guestAddress, ulong size) => _tracker.MayHaveGpuWrittenPages(guestAddress, size); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index 74707a5f9..c938bee0d 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -40,6 +40,8 @@ private sealed record ControlBarrier(ulong CutoffOrdinal, Action Work, Action Ca private readonly LinkedList<CommandSubmission>[] _queues = new LinkedList<CommandSubmission>[QueueCount]; private readonly GpuCommandInterpreter?[] _interpreters = new GpuCommandInterpreter?[QueueCount]; private readonly Queue<ControlBarrier> _controlBarriers = new(); + // Per queue: the admission order of its head while that head's release waits for older compute work, or 0. + private readonly ulong[] _waitingReleases = new ulong[QueueCount]; private int _nextQueue; private int _submissionCount; private ulong _admissionOrdinal; @@ -433,6 +435,59 @@ public void RetryBlocked() } } + // For a release (GpuCommandInterpreter.YieldsToOlderWork): whether another compute queue's head was admitted before the + // given submission and, with runnableOnly, is not blocked on an unmet wait. If so, the release waits and the older heads + // run before it without soft waits. Its first wait retries the blocked heads once, so each re-reads its wait; later + // checks leave the blocked state alone, because a retry from one waiting release kept the heads another one checks + // runnable, and two such releases then waited for each other for good. + internal bool YieldToOlderWork(int queueId, ulong admissionOrdinal, bool runnableOnly) + { + lock (_gate) + { + var older = false; + for (var other = 1; other < QueueCount && !older; other++) + { + older = other != queueId && _queues[other].First is { } head && head.Value.AdmissionOrdinal < admissionOrdinal && + (!runnableOnly || !head.Value.Blocked); + } + + _waitingReleases[queueId] = older ? admissionOrdinal : 0; + if (!older) + { + return false; + } + + for (var other = 1; other < QueueCount; other++) + { + if (other != queueId && _queues[other].First is { } head && head.Value.AdmissionOrdinal < admissionOrdinal) + { + head.Value.Deferral = null; + } + } + + if (!runnableOnly) + { + RetryBlocked(); + } + + return true; + } + } + + // A younger release waits for this submission (YieldToOlderWork). + private bool ReleaseWaitsForLocked(CommandSubmission submission) + { + foreach (var ordinal in _waitingReleases) + { + if (ordinal > submission.AdmissionOrdinal) + { + return true; + } + } + + return false; + } + // Runs one slice of the next unblocked submission on the calling thread. public SliceResult ProcessOne() { @@ -466,9 +521,10 @@ public SliceResult ProcessOne() queue.RemoveFirst(); _submissionCount--; _nextQueue = (selected + 1) % QueueCount; + _waitingReleases[selected] = 0; if (_landings is not null) { - mayDeferForLanding = HasOtherRunnableLocked(selected); + mayDeferForLanding = HasOtherRunnableLocked(selected) && !ReleaseWaitsForLocked(submission); completedGpuTick = _lastCompletedGpuTick; } } @@ -541,7 +597,9 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi var deferral = _landings is null ? null : _interpreters[submission!.QueueId]?.TakeLandingDeferral(out deferredSince); submission!.Deferral = deferral; submission.DeferredSinceTicks = deferral is null ? 0 : deferredSince; - submission.Blocked = deferral is null && retryGeneration == _retryGeneration; + // A release that waits for older work stays runnable: it checks again on its next turn. + var yielded = _interpreters[submission.QueueId]?.TakeReleaseYield() == true; + submission.Blocked = deferral is null && !yielded && retryGeneration == _retryGeneration; submission.BlockedSinceTicks = System.Diagnostics.Stopwatch.GetTimestamp(); submission.BlockedPacketAddress = submission.Commands.CurrentPacketAddress; _queues[submission.QueueId].AddFirst(submission); @@ -612,6 +670,8 @@ private bool RunSlice(CommandSubmission submission, bool mayDeferForLanding = fa SlicesRun++; processor.MayDeferForLanding = mayDeferForLanding; processor.CompletedGpuTick = completedGpuTick; + processor.Queues = this; + processor.AdmissionOrdinal = submission.AdmissionOrdinal; _host.BeginSubmission(submission.QueueId, submission.SubmissionId, submission.GeometrySnapshots); processor.ConstantEngineComplete = true; var complete = processor.Process(submission.Commands, submission.Address, submission.DwordCount, @@ -624,7 +684,7 @@ private bool RunSlice(CommandSubmission submission, bool mayDeferForLanding = fa _host.RunGarbageCollector(); } - _host.Flush(); + _host.FlushSlice(); } else if (complete) { diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs index 293d139de..2310c184d 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs @@ -21,6 +21,59 @@ public sealed partial class GpuCommandInterpreter private const uint DrawIndirectArgumentsSize = 16; private const uint DrawIndexedIndirectArgumentsSize = 20; + private int TryDrawIndexedRun(in PacketContext packet, PacketWindow window) + { + if (!_host.ResolvesIndirectDrawOnGpu || packet.Remaining < 10 || !window.Holds(packet.PacketAddress, 10) || + IndexTypeAndSize > 1 || IndexBaseAddress == 0 || DrawIndirectArgumentsBase == 0 || + IndexedDrawTrace.Enabled || Rendering.RenderTrace.Enabled || Rendering.ScissorTrace.Instance is { Active: true } || + !Rendering.RenderExecutor.RunsPlainVertexProgram(TypedRegisters.Context.ShaderStages) || + TypedRegisters.UserConfig.PrimitiveType != (uint)Rendering.GuestPrimitiveType.TriangleList) + return 0; + + int start = window.IndexOf(packet.PacketAddress); + var words = window.Words.AsSpan(start, (int)Math.Min(window.DwordCount - (uint)start, packet.Remaining)); + if (words[5] != packet.Header || (words[4] & ~0x20u) != 2u) return 0; + var locations = DrawRegisterLocations.FromPacket(words[2], words[3]); + int vertex = VertexUserDataIndex(locations.BaseVertex); + int instance = VertexUserDataIndex(locations.StartInstance); + if (DrawRegisterLocations.Names(locations.DrawIndex) || + (DrawRegisterLocations.Names(locations.BaseVertex) && vertex < 0) || + (DrawRegisterLocations.Names(locations.StartInstance) && instance < 0)) return 0; + + int limit = Math.Min(32, words.Length / 5); + var indexCount = IndexBufferSize; + if (indexCount == 0) + { + // Leave the periodic CPU sample to TryGetGpuIndexRange. + limit = Math.Min(limit, 1023 - (int)(_indexExtentDraws & 1023)); + if (!_indexExtents.TryGetValue(IndexBaseAddress, out var extent)) return 0; + indexCount = (uint)(extent / IndexElementSize); + } + if (indexCount == 0 || (ulong)indexCount * IndexElementSize > 64ul << 20) return 0; + + Span<uint> offsets = stackalloc uint[32]; + ulong first = DrawIndirectArgumentsBase + words[1]; + if (first < DrawIndirectArgumentsBase) return 0; + int count = 0; + for (; count < limit; count++) + { + var next = words.Slice(count * 5, 5); + ulong address = DrawIndirectArgumentsBase + next[1]; + if (next[0] != packet.Header || !next[2..].SequenceEqual(words[2..5]) || + (address & 3) != 0 || address < first || address > ulong.MaxValue - DrawIndexedIndirectArgumentsSize || + (address + DrawIndexedIndirectArgumentsSize - 1) >> 12 != first >> 12) break; + offsets[count] = (uint)(address - first); + } + if (count < 2) return 0; + var args = new DrawIndexedArguments(packet.PacketAddress, packet.Opcode, indexCount, IndexBaseAddress, + IndexTypeAndSize, 1, 0, 0, DrawOffsetSource.IndirectArguments, first, IndexBufferSize == 0, instance, BaseVertexUserData: vertex); + if (!_host.TryDrawIndexedRun(SubmitId, in args, offsets[..count])) return 0; + if (IndexBufferSize == 0) _indexExtentDraws += (uint)count; + if (IndirectInstanceInherit == IndirectInstanceInheritance.All) + _deferredInstanceCountAddress = first + offsets[count - 1] + 4; + return count; + } + internal void SetIndexType(uint indexTypeAndSize) => IndexTypeAndSize = indexTypeAndSize & 0x3u; internal void SetIndexBaseAddress(ulong address) => IndexBaseAddress = address; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs index 9343966fc..3d04d7017 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Events.cs @@ -41,6 +41,11 @@ internal uint EventWriteEndOfPipePacket(in PacketContext packet, ReadOnlySpan<ui RequireHeader(packet, PacketHeader.Make(6, PacketOpcode.EventWriteEndOfPipe)); var control = payload[0]; var destination = payload[1] | ((ulong)(payload[2] & 0xFFFFu) << 32); + if (EndOfPipeIsObservable(destination, payload[2]) && YieldsToOlderWork()) + { + return 5; + } + WriteEndOfPipe( is64Bit: true, cachePolicy: (control >> 25) & 0x3u, @@ -62,6 +67,11 @@ internal uint EventWriteEndOfShaderPacket(in PacketContext packet, ReadOnlySpan< RequireHeader(packet, 0xC003_4802u); var control = payload[0]; var destination = payload[1] | ((ulong)(payload[2] & 0xFFFFu) << 32); + if (EndOfPipeIsObservable(destination, payload[2]) && YieldsToOlderWork()) + { + return 4; + } + WriteEndOfPipe( is64Bit: false, cachePolicy: (control >> 25) & 0x3u, @@ -77,6 +87,10 @@ internal uint EventWriteEndOfShaderPacket(in PacketContext packet, ReadOnlySpan< return 4; } + // An end-of-pipe event the CPU can observe: it writes a label (a data source and a destination) or raises an interrupt. + private static bool EndOfPipeIsObservable(ulong destination, uint selectors) => + ((selectors >> 24) & 0x7u) != 0 || (destination != 0 && ((selectors >> 29) & 0x7u) != 0); + // Native release-memory body: event control, then destination and selectors. internal uint ReleaseMemoryNativePacket(in PacketContext packet, ReadOnlySpan<uint> payload) { diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs index d342062e1..baf946480 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs @@ -27,6 +27,55 @@ private bool WaitForPublication() return true; } + // Set by the command stream queue for each slice: the queue table and the admission order of the submission. + internal CommandStreamQueue? Queues { get; set; } + + internal ulong AdmissionOrdinal { get; set; } + + // A release lands after this many checks at the same packet even if older work still looks runnable: work that keeps + // being unblocked by other completions must not hold a release for ever. + private const int MaxReleaseYields = 256; + + private PacketCursorStack? _yieldedExecution; + private ulong _yieldedPacket; + private int _yieldChecks; + private bool _suspendedForYield; + + // Whether the last slice suspended at a release waiting for older work, taken by the command stream queue. + internal bool TakeReleaseYield() + { + var yielded = _suspendedForYield; + _suspendedForYield = false; + return yielded; + } + + // The GPU runs every queue at once, so by the time a release lands, the compute work submitted before it has run as far + // as its own waits let it, and the CPU may reuse that work's memory as soon as it sees the label. The command stream + // runs one queue at a time and can reach the release first. A release the CPU can observe therefore lets the older + // submissions of the compute queues run first, without soft waits, and lands once none of them can. + private bool YieldsToOlderWork() + { + if (Queues is not { } queues || _execution is not { } execution) + { + return false; + } + + var again = ReferenceEquals(_yieldedExecution, execution) && _yieldedPacket == _packetAddress; + _yieldChecks = again ? _yieldChecks + 1 : 0; + if (_yieldChecks >= MaxReleaseYields || !queues.YieldToOlderWork(QueueId, AdmissionOrdinal, runnableOnly: again)) + { + _yieldedExecution = null; + _yieldChecks = 0; + return false; + } + + _yieldedExecution = execution; + _yieldedPacket = _packetAddress; + _suspendedForYield = true; + Suspend(); + return true; + } + // Labels stay immediate unless an earlier result must be published first. internal void WriteEndOfPipe( bool is64Bit, @@ -346,6 +395,11 @@ internal void ReleaseMemory( throw _host.Fatal($"The release-memory data selection is not supported: selection={dataSelection} address=0x{destination:X16}."); } + if ((interruptSelector != 0 || (dataSelection != 0 && destination != 0)) && YieldsToOlderWork()) + { + return; + } + WarnUnknownReleaseMemGcr(gcrControl); var gl2WriteBack = (gcrControl & GcrGl2Writeback) != 0; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index c2b658548..d134cc61f 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -485,7 +485,11 @@ 0 or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or var waitedBefore = SharpEmu.Libs.Diagnostics.PacketHandlerTally.WaitedTicks; using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.CommandPacketHandler)) { - consumed = handler(this, in packet, payload) + 1; + var run = header == PacketHeader.Make(5, PacketOpcode.DrawIndexIndirect) && window is not null + ? TryDrawIndexedRun(in packet, window) : 0; + consumed = run == 0 ? handler(this, in packet, payload) + 1 : (uint)run * 5; + if (run > 1) + _packetSerial += (uint)run - 1; } if (handlerStarted != 0) diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs index 3a3b1b557..1452ae4da 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs @@ -126,6 +126,9 @@ bool TryReadGuestWaitOperand(ulong address, Span<byte> destination, bool allowSt // Draws resolve ahead of the stream on this many worker threads; zero resolves them on the stream thread. int ResolveWorkerCount => 0; + // Accept the complete run or leave every packet for the normal draw handler. + bool TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) => false; + // Reads on this thread now serve a draw at this stream position: a range earlier work may still // write refuses with SerialResolveRequiredException, every other read lands in the log. void BeginWorkerResolve(long sequence, ResolveReadLog reads) @@ -163,6 +166,8 @@ void EndWorkerResolve() void Flush(); + void FlushSlice() => Flush(); + // A frame boundary: submits what the frame recorded. The submitter resumes once it returns, so a // host that runs the stream ahead of its recording returns only after the frame is recorded. void FlushFrame() => Flush(); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriteTable.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriteTable.cs index aa3679244..40e7bfb2a 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriteTable.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriteTable.cs @@ -45,6 +45,12 @@ public static uint WriteContextPacket(RegisterBanks banks, in PacketContext pack // A shader packet without values has no writer; the other banks accept it. public static uint WriteShaderPacket(RegisterBanks banks, in PacketContext packet, uint offset, ReadOnlySpan<uint> values) { + if (!Rendering.RenderTrace.Enabled && RegisterWriters.SameUserScalarPacket(banks, offset, values)) + { + banks.UserDataMarker = UserScalarKind.Unknown; + return (uint)values.Length; + } + banks.PrepareShaderWrite(offset, (uint)values.Length); var consumed = WritePacket(banks, in packet, offset, values, Shader, ShaderIndirect, "shader", emptyIsHandled: false); banks.MarkWritten(RegisterStamps.ShaderBitsFor(offset, consumed)); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs index 70f76e6eb..63173c2cb 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterWriters.Shader.cs @@ -114,6 +114,31 @@ public static void FillShader(RegisterPacketWriter?[] direct, RegisterWriter?[] indirect[SpiShaderPgmRsrc2Vs] = static (banks, _, value) => banks.Shader.Vertex.LegacyVertexResource2 = value; } + // A repeated user-data packet still consumes its marker, but leaves shared register snapshots valid. + internal static bool SameUserScalarPacket(RegisterBanks banks, uint offset, ReadOnlySpan<uint> values) + { + if (values.IsEmpty) return false; + if (offset - SpiShaderUserDataPs0 < GraphicsUserScalarCount) + return Matches(banks.Shader.Pixel.UserScalars, offset - SpiShaderUserDataPs0, values, banks.UserDataMarker); + if (offset - SpiShaderUserDataGs0 < GraphicsUserScalarCount) + return Matches(banks.Shader.Vertex.GeometryUserScalars, offset - SpiShaderUserDataGs0, values, banks.UserDataMarker); + if (offset - SpiShaderUserDataHs0 < GraphicsUserScalarCount) + return Matches(banks.Shader.Vertex.HullUserScalars, offset - SpiShaderUserDataHs0, values, banks.UserDataMarker); + if (offset - ComputeUserData0 < ComputeUserScalarCount && values.Length <= ComputeUserScalarCount - (offset - ComputeUserData0)) + return Matches(banks.Shader.Compute.UserScalars, offset - ComputeUserData0, values, banks.UserDataMarker); + return false; + } + + private static bool Matches(UserScalarRegisters target, uint slot, ReadOnlySpan<uint> values, UserScalarKind marker) + { + var end = (int)slot + values.Length; + if (end > target.Count || end > UserScalarRegisters.Capacity || + !target.ValueSpan(end)[(int)slot..].SequenceEqual(values)) return false; + foreach (var kind in target.KindSpan(end)[(int)slot..]) + if (kind != marker) return false; + return true; + } + private static uint PixelUserScalarsPacket(RegisterBanks banks, in PacketContext packet, uint offset, ReadOnlySpan<uint> values) => UserScalarsPacket(banks, in packet, offset, values, banks.Shader.Pixel.UserScalars, SpiShaderUserDataPs0, GraphicsUserScalarCount); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs index d9e3000f7..d371e75ac 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ResolveReadLog.cs @@ -73,6 +73,33 @@ public ReadOnlySpan<byte> Bytes(int index, out ulong address) return _bytes.AsSpan(_offsets[index], _lengths[index]); } + public void CopyFrom(ResolveReadLog source) + { + if (_addresses.Length < source.Count) + { + var capacity = source._addresses.Length; + _addresses = new ulong[capacity]; + _offsets = new int[capacity]; + _lengths = new int[capacity]; + _clean = new bool[capacity]; + } + + if (_bytes.Length < source._byteCount) + { + _bytes = new byte[source._bytes.Length]; + } + + source._addresses.AsSpan(0, source.Count).CopyTo(_addresses); + source._offsets.AsSpan(0, source.Count).CopyTo(_offsets); + source._lengths.AsSpan(0, source.Count).CopyTo(_lengths); + source._clean.AsSpan(0, source.Count).CopyTo(_clean); + source._bytes.AsSpan(0, source._byteCount).CopyTo(_bytes); + Count = source.Count; + _byteCount = source._byteCount; + Version = source.Version; + Publications = source.Publications; + } + public void Clear() { Count = 0; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs index c5ac724df..2b6cac64f 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs @@ -17,7 +17,6 @@ public bool TryDetileMemory(ulong tiledAddress, ulong tiledSize, ulong linearAdd PublishImagesUnderRead(tiledAddress, tiledSize); InvalidateMemoryFromGpu(linearAddress, linearSize); var (source, sourceOffset) = _bufferCache.ObtainBuffer(tiledAddress, tiledSize, isWritten: false, isTexelBuffer: true); - _bufferCache.NoteCopyWrite(); var (target, targetOffset) = _bufferCache.ObtainBuffer(linearAddress, linearSize, isWritten: true, isTexelBuffer: true); _tiler.Detile(source.Handle, sourceOffset, tiledSize, target.Handle, targetOffset, linearSize, transfers); return true; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs index be34d5c20..b91a17b5b 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs @@ -782,4 +782,57 @@ public bool SetMetadataSlice(ulong address, uint slice, bool isClear) return true; } + + // The depth clear value of a depth-target bind: what a pending HTile clear loads at the next bind, and what a sample + // reads before that bind (SampleClearsDepth). + public void NoteDepthClearValue(ulong htileAddress, float value) + { + if (SubmissionScheduler.ReadOnlyThread) + { + throw SubmissionScheduler.ReadOnlyViolation("depth clear value"); + } + + using var held = _lock.Hold(); + if (_surfaceMetadata.TryGetValue(htileAddress, out var found) && found.Kind == SurfaceMetadataKind.HTile) + { + found.DepthClearValue = value; + found.HasDepthClearValue = true; + } + } + + // A depth surface the guest cleared through its HTile and then samples before binding it again: the texture unit reads + // the cleared value through the HTile, so the clear the next depth-target bind would load is made before the sample. + // One layer and one level only: a layered surface's clear bits are not exact per slice. + private bool SampleClearsDepth(CachedImage image) + { + ref readonly var description = ref image.Description; + return description.IsDepth && description.Resources.Levels == 1 && description.Resources.Layers == 1 && + image.MetadataRegistration is { Kind: SurfaceMetadataKind.HTile, Invalidated: false, HasDepthClearValue: true } metadata && + metadata.IsSliceClear(0) && + _surfaceMetadata.TryGetValue(description.Metadata.Range.Address, out var registered) && ReferenceEquals(registered, metadata); + } + + private unsafe void ClearDepthBeforeSample(CachedImage image) + { + var command = _scheduler.Current; + if (command.IsInvalid) + { + throw SubmissionScheduler.Fatal($"A sampled depth clear needs a command buffer that is recording: address=0x{image.Description.Data.Address:X16}."); + } + + var metadata = image.MetadataRegistration!; + command.EndRendering(); + var native = new CommandBuffer(command.Handle); + image.Transition(AccessFlags.TransferWriteBit, null, native); + var range = new ImageSubresourceRange(ImageAspectFlags.DepthBit, 0, 1, 0, 1); + var clear = new ClearDepthStencilValue(metadata.DepthClearValue, 0); + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _device.Vk.CmdClearDepthStencilImage(native, image.Backing.Handle, ImageLayout.General, &clear, 1, &range); + } + + TakeGpuOwnership(image); + NoteMetadataChange(image.Description.Metadata.Range.Address, clearOnly: true); + metadata.SetSliceClear(0, false); + } } diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs index 147c524a9..59c97e71f 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs @@ -304,11 +304,11 @@ static bool TryStretch(ref GuestSpan range, uint currentLayers, uint newLayers) // A block-compressed image states its pitch and height in texels, and the uncompressed view of its blocks states them in blocks, // so a side that is compressed is compared in blocks. - private static bool SameMipLayout(in ImageDescription left, in ImageDescription right) + private static bool SameMipLayout(in ImageDescription left, in ImageDescription right, int levels = ImageDescription.MaxLevels) { var leftShift = left.IsBlock ? 2 : 0; var rightShift = right.IsBlock ? 2 : 0; - for (var level = 0; level < ImageDescription.MaxLevels; level++) + for (var level = 0; level < levels; level++) { var a = left.MipLayout[level]; var b = right.MipLayout[level]; @@ -516,6 +516,22 @@ private OverlapResolution ResolveOverlap(in ImageDescription requested, ImageRol return new OverlapResolution(depthImageIdentifier); } + // An image of the other block class holds the requested image's blocks (or texels) only in the same tiling with + // every level both hold in the same place, as a compressor's view of a texture's blocks is. Otherwise the memory + // now holds another resource: a texture's level 0 lies after its smaller levels, where a one-level image has its + // own bytes. The image is neither viewed in the other format nor copied across, as a layout mismatch is not. + if (requested.IsBlock != cachedInfo.IsBlock && + (requested.TileMode != cachedInfo.TileMode || + !SameMipLayout(requested, cachedInfo, (int)Math.Min(requested.Resources.Levels, cachedInfo.Resources.Levels)))) + { + if (safeToDelete) + { + ParkOrReleaseImage(cachedImageIdentifier); + } + + return new OverlapResolution(mergedImageIdentifier); + } + if (requested.IsBlock && !cachedInfo.IsBlock) { return new OverlapResolution(GrowImage(requested, cachedImageIdentifier)); diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs index bdefaf170..549808b66 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs @@ -520,6 +520,12 @@ public bool TryPrepareTextureViewForSlice(ResourceSlotIdentifier imageIdentifier return false; } + // A sample that would record the pending HTile clear first is the render thread's (AcquireTextureCore). + if (hasData && request.Role == ImageRole.Texture && SampleClearsDepth(image)) + { + return false; + } + view = image.GetOrCreateView(request.View); return true; } diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs index 1988b337a..152b73fc6 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs @@ -539,6 +539,11 @@ private void AcquireTextureCore(ResourceSlotIdentifier imageIdentifier, CachedIm switch (request.Role) { case ImageRole.Texture: + if (hasData && SampleClearsDepth(image)) + { + ClearDepthBeforeSample(image); + } + break; case ImageRole.StorageImage: if (hasData) diff --git a/src/SharpEmu.Libs/Gpu/Images/SurfaceMetadata.cs b/src/SharpEmu.Libs/Gpu/Images/SurfaceMetadata.cs index bd3512a80..837649405 100644 --- a/src/SharpEmu.Libs/Gpu/Images/SurfaceMetadata.cs +++ b/src/SharpEmu.Libs/Gpu/Images/SurfaceMetadata.cs @@ -59,4 +59,7 @@ internal void SetSliceClear(uint slice, bool clear) public ulong RangeSize; public bool NativeColorClear; public bool Invalidated; + // HTile: the depth clear value (DB_DEPTH_CLEAR) of the surface's last depth-target bind. + public float DepthClearValue; + public bool HasDepthClearValue; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs index 20854cac5..f31db2496 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs @@ -113,6 +113,7 @@ internal sealed class ShaderCodeCapture public ulong FrontendDomain { get; init; } public uint[] FrontendUserData { get; init; } = []; public ulong FrontendContinuationOffset { get; init; } + public uint FrontendEntryCodeSize { get; init; } public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) Key => (Hash, CodeSize, Address, Fused is { } fused ? unchecked(fused.ContinuationAddress - Address) : FrontendContinuationOffset); @@ -1232,6 +1233,10 @@ private static byte[] SerializeCode(ShaderCodeCapture code) } writer.Write(code.FrontendContinuationOffset); + if (code.FrontendEntryCodeSize != 0) + { + writer.Write(code.FrontendEntryCodeSize); + } } writer.Flush(); @@ -1259,6 +1264,7 @@ private static ShaderCodeCapture DeserializeCode(byte[] payload) var frontendDomain = 0UL; uint[] frontendUserData = []; var frontendContinuationOffset = 0UL; + var frontendEntryCodeSize = 0u; if (reader.BaseStream.Position < reader.BaseStream.Length) { frontendDomain = reader.ReadUInt64(); @@ -1269,6 +1275,10 @@ private static ShaderCodeCapture DeserializeCode(byte[] payload) } frontendContinuationOffset = reader.ReadUInt64(); + if (reader.BaseStream.Position < reader.BaseStream.Length) + { + frontendEntryCodeSize = reader.ReadUInt32(); + } } return new ShaderCodeCapture @@ -1282,6 +1292,7 @@ private static ShaderCodeCapture DeserializeCode(byte[] payload) FrontendDomain = frontendDomain, FrontendUserData = frontendUserData, FrontendContinuationOffset = frontendContinuationOffset, + FrontendEntryCodeSize = frontendEntryCodeSize, }; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 392f0ae7e..ba709ebd0 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -483,6 +483,7 @@ private Gen5ShaderProgram DecodeCore(ShaderSource source, (ulong Hash, uint Code FrontendDomain = external?.CacheDomain ?? 0, FrontendUserData = external is null ? [] : source.Registered.FrontendUserData.ToArray(), FrontendContinuationOffset = external is null ? 0 : source.ContinuationAddressOffset, + FrontendEntryCodeSize = external is not null && source.Registered.IsFused ? source.Registered.CodeSizeBytes : 0, }; } @@ -2434,16 +2435,65 @@ internal static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCa } } + private static bool TryDecodeGraphicsPrewarm(ShaderCodeCapture code, ShaderStage stage, Func<ulong, IShaderFrontend?>? frontendOf, + out Gen5ShaderProgram program, out IShaderFrontend? frontend, out string error) + { + frontend = null; + if (code.FrontendDomain == 0) + { + return Gen5ShaderTranslator.TryDecodeProgram(code.CreateContext(), code.Address, out program, out error); + } + + frontend = frontendOf?.Invoke(code.FrontendDomain); + if (frontend is null) + { + program = default!; + error = $"The shader frontend 0x{code.FrontendDomain:X16} is not registered."; + return false; + } + + var continuation = code.FrontendContinuationOffset == 0 ? 0 : unchecked(code.Address + code.FrontendContinuationOffset); + var entrySize = code.FrontendEntryCodeSize; + if (entrySize == 0) + { + entrySize = code.CodeSize; + if (continuation != 0) + { + foreach (var range in code.Ranges) + { + if (code.Address >= range.Address && code.Address - range.Address < (ulong)range.Bytes.Length) + { + entrySize = Math.Min(entrySize, (uint)((ulong)range.Bytes.Length - (code.Address - range.Address))); + break; + } + } + + if (continuation > code.Address) + { + entrySize = (uint)Math.Min(entrySize, continuation - code.Address); + } + } + } + + var shader = new RegisteredShader(code.Address, 0, entrySize, 0, 0, 0, 0, continuation, checked(code.CodeSize - entrySize)) + { + Frontend = frontend, + FrontendUserData = code.FrontendUserData, + }; + return frontend.TryDecode(code.CreateContext(), shader, stage, out program, out error); + } + // A recorded pixel program translated again as its session translated it (CreateEntry, then the specialized // translation through the translation cache); the caller compiles its pixel library. internal static bool TryCompilePixelPrewarm(PixelPrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, - IShaderPipelineHost host, out IGuestCompiledShader? compiled, out BindingLayout? layout, out string error) + IShaderPipelineHost host, out IGuestCompiledShader? compiled, out BindingLayout? layout, out string error, + Func<ulong, IShaderFrontend?>? frontendOf = null) { compiled = null; layout = null; try { - if (!Gen5ShaderTranslator.TryDecodeProgram(code.CreateContext(), code.Address, out var program, out error)) + if (!TryDecodeGraphicsPrewarm(code, ShaderStage.Pixel, frontendOf, out var program, out var frontend, out error)) { return false; } @@ -2458,11 +2508,15 @@ internal static bool TryCompilePixelPrewarm(PixelPrewarmRecord record, ShaderCod waveSize: 32, bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: host.SupportsBindlessHeap, stableImageLimits: host.GraphicsImageDescriptorLimits, deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts, + normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, + normalizeImageDescriptor: frontend?.NormalizeImageDescriptor, + imageNormalizationVersion: frontend?.ImageNormalizationVersion, preferHeapRecords: record.PreferHeapRecords); // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); var resources = ResourceMaterializer.ApplyTo(plan, specialization); layout = AllocateLayout(program, plan, resources, record.UserDataBase, record.UserDataCount, record.PushDataCursor, false, + usesBufferLengths: frontend?.RequiresExplicitBufferLengths ?? false, tableBlocks: UsesTableBlocks(host, ShaderStage.Pixel)); var options = new StageCompileOptions { @@ -2492,14 +2546,15 @@ internal static bool TryCompilePixelPrewarm(PixelPrewarmRecord record, ShaderCod // its pre-rasterization libraries. internal static bool TryCompileVertexPrewarm(VertexPrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, IShaderPipelineHost host, out IGuestCompiledShader? compiled, out BindingLayout? layout, out MeshTaskLaunchInfo? task, - out string error) + out string error, Func<ulong, IShaderFrontend?>? frontendOf = null) { compiled = null; layout = null; task = null; try { - if (!Gen5ShaderTranslator.TryDecodeProgram(code.CreateContext(), code.Address, out var program, out error)) + var stage = record.Mesh ? ShaderStage.Mesh : ShaderStage.Vertex; + if (!TryDecodeGraphicsPrewarm(code, stage, frontendOf, out var program, out var frontend, out error)) { return false; } @@ -2510,7 +2565,6 @@ internal static bool TryCompileVertexPrewarm(VertexPrewarmRecord record, ShaderC return false; } - var stage = record.Mesh ? ShaderStage.Mesh : ShaderStage.Vertex; var options = new StageCompileOptions { VertexInfo = record.VertexInfo, @@ -2532,12 +2586,16 @@ internal static bool TryCompileVertexPrewarm(VertexPrewarmRecord record, ShaderC bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: host.SupportsBindlessHeap, stableImageLimits: host.GraphicsImageDescriptorLimits, deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts, + normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, + normalizeImageDescriptor: frontend?.NormalizeImageDescriptor, + imageNormalizationVersion: frontend?.ImageNormalizationVersion, preferHeapRecords: record.PreferHeapRecords); // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); var resources = ResourceMaterializer.ApplyTo(plan, specialization); layout = AllocateLayout(program, plan, resources, record.UserDataBase, record.UserDataCount, record.PushDataCursor, false, - usesMeshDrawParameters: record.Mesh, pushDataAtTop: PushDataAtTop(stage), tableBlocks: UsesTableBlocks(host, stage)); + usesMeshDrawParameters: record.Mesh, pushDataAtTop: PushDataAtTop(stage), tableBlocks: UsesTableBlocks(host, stage), + usesBufferLengths: frontend?.RequiresExplicitBufferLengths ?? false); var request = record.Mesh ? BuildMeshRequest(host, plan, resources, layout, options) : BuildVertexRequest(host, plan, resources, layout, options, vertexInputs); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index 8763a93ef..352ced4a6 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -239,6 +239,8 @@ void PrepareMemoryWritingDraw() { } void DrawIndexed(uint indexCount, uint instanceCount, uint firstIndex, int vertexOffset, uint firstInstance); // One indexed draw whose counts the GPU reads from the buffer (VkDrawIndexedIndirectCommand layout). + bool CanShareIndexedBindings(IPreparedBindings stage, ReadOnlySpan<ColorTargetState> colors, in DepthAttachmentState depth) => false; + void DrawIndexedIndirect(BufferBinding arguments) => throw new NotSupportedException("The render host does not draw from indirect arguments."); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs index a3fcf14fc..1371fc4ce 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs @@ -168,11 +168,31 @@ arguments.IndexCount is 0 or > IndirectMeshDrawRequest.MaximumIndexCapacity || // Reads the indirect arguments now and draws from them, as the interpreter would have. private void DrawIndexedWithCpuArguments(ulong submitId, RegisterBanks banks, in DrawIndexedArguments arguments) + { + if (!TryReadCpuArguments(in arguments, out var resolved)) + { + throw _host.Fatal($"The indirect draw arguments are unreadable: address=0x{arguments.IndirectArgumentsAddress:X16}."); + } + + if (resolved.IndexCount == 0 || resolved.InstanceCount == 0) + { + var skipped = _pool.RentDraw(); + skipped.ResetBindings = true; + Record(skipped); + return; + } + + DrawIndexedCore(submitId, banks, in resolved); + } + + // The draw the indirect arguments in guest memory describe. + private bool TryReadCpuArguments(in DrawIndexedArguments arguments, out DrawIndexedArguments resolved) { Span<byte> bytes = stackalloc byte[(int)IndexedIndirectArgumentsSize]; if (!_host.TryReadGuest(arguments.IndirectArgumentsAddress, bytes)) { - throw _host.Fatal($"The indirect draw arguments are unreadable: address=0x{arguments.IndirectArgumentsAddress:X16}."); + resolved = default; + return false; } var words = System.Runtime.InteropServices.MemoryMarshal.Cast<byte, uint>(bytes); @@ -182,7 +202,7 @@ private void DrawIndexedWithCpuArguments(ulong submitId, RegisterBanks banks, in GuestIndexType.Index32 => 4ul, _ => 1ul, }; - var resolved = arguments with + resolved = arguments with { IndexCount = arguments.UnboundedIndexBuffer ? words[0] : Math.Min(words[0], arguments.IndexCount), InstanceCount = words[1], @@ -192,18 +212,19 @@ private void DrawIndexedWithCpuArguments(ulong submitId, RegisterBanks banks, in IndirectArgumentsAddress = 0, UnboundedIndexBuffer = false, }; - if (resolved.IndexCount == 0 || resolved.InstanceCount == 0) - { - var skipped = _pool.RentDraw(); - skipped.ResetBindings = true; - Record(skipped); - return; - } - - DrawIndexedCore(submitId, banks, in resolved); + return true; } - private void DrawIndexedCore(ulong submitId, RegisterBanks banks, in DrawIndexedArguments arguments) + internal bool CanGroupIndexed(RegisterBanks banks, in DrawIndexedArguments first) => + CanDrawIndirectOnGpu(banks, in first) && DrawHasTargets(banks) && !MeshDrawTrace.Active; + + internal static bool SafeForRun(ShaderProgramInfo? program) => + program is { UsesDeviceAddresses: false, CallRecordCallees.Count: 0 } && program.Frontend?.RequiresOrderedImagePreparation != true && + !Array.Exists(program.Buffers, static buffer => buffer.Written) && !WritesStorageImage(program) && + program.Bindings?.UsesBindlessHeap != true && + program.Bindings?.Find(SharpEmu.ShaderCompiler.Resources.DescriptorBindingKind.GlobalDataShare) is null; + + internal void DrawIndexedCore(ulong submitId, RegisterBanks banks, in DrawIndexedArguments arguments, uint[]? offsets = null) { if (MeshDrawTrace.Active) MeshDrawTrace.Write("selection", $"indexed=true count={arguments.IndexCount}"); using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawExecutor); @@ -375,10 +396,104 @@ void TraceDisposition(string disposition) record.IndexedTrace = traceSample; record.PacketAddress = tracePacket; FillDraw(record, banks, in draw, ref state, topology, in emission, in indexSource, primitiveRestart, setBindDebug: true, setAutoDebug: false); + // An indirect draw arrives here with its arguments address when the GPU reads them, and without it once + // DrawIndexedWithCpuArguments read them. + record.RepeatableArguments = indirect && expandedIndices is null && traceSample is null && !RenderTrace.Enabled && !MeshDrawTrace.Active && + state.Programs.MeshInput is null && state.Programs.VertexInput.Tessellation is null && + (GuestPrimitiveType)userConfig.PrimitiveType != GuestPrimitiveType.TriangleStrip && + (GuestIndexType)arguments.IndexTypeAndSize is GuestIndexType.Index16 or GuestIndexType.Index32; + record.RepeatsCpuArguments = record.RepeatableArguments && arguments.IndirectArgumentsAddress == 0; + if (offsets is not null && !record.WritesMemory && record.WriteStages == PipelineStageFlags.None && record.State.Programs.MeshInput is null && + SafeForRun(state.Programs.VertexInput.Stage.Program) && + (!state.PixelActive || SafeForRun(state.Programs.PixelInput.Stage.Program))) + { + record.IndirectOffsets = offsets; + foreach (uint offset in offsets) + record.IndirectBytes = Math.Max(record.IndirectBytes, offset + (uint)IndexedIndirectArgumentsSize); + } TraceDisposition("recorded"); Record(record); } + // A draw issued right after the template's draw under the same registers records the template's record with its own + // arguments: index range, counts, offsets and indirect arguments address. Everything else a resolve derives from the + // registers and from guest bytes the template's read log covers. False when the draw would leave the path the template + // took; the caller then resolves it in full. A draw whose arguments the CPU reads reads its own here, as + // DrawIndexedWithCpuArguments does, and records a skipped draw when they draw nothing. + internal bool TryRepeatIndexed(ResolvedDraw template, ulong submitId, RegisterBanks banks, in DrawIndexedArguments arguments) + { + if (!template.RepeatableArguments || template.Kind != ResolvedDrawKind.Draw || template.Index.HostData is not null || + arguments.IndirectArgumentsAddress == 0 || arguments.OffsetSource != DrawOffsetSource.IndirectArguments || + RenderTrace.Enabled || MeshDrawTrace.Active || IndexedDrawTrace.Enabled || + arguments.StartInstanceUserData != template.State.StartInstanceUserData || + arguments.BaseVertexUserData != template.State.BaseVertexUserData || UsesMeshExecution(banks)) + { + return false; + } + + IndexType indexType; + ulong elementSize; + switch ((GuestIndexType)arguments.IndexTypeAndSize) + { + case GuestIndexType.Index16: + indexType = IndexType.Uint16; + elementSize = 2; + break; + case GuestIndexType.Index32: + indexType = IndexType.Uint32; + elementSize = 4; + break; + default: + return false; + } + + if (indexType != template.Index.Type) + { + return false; + } + + var drawn = arguments; + if (CanDrawIndirectOnGpu(banks, in arguments)) + { + if (template.RepeatsCpuArguments || arguments.IndexCount == 0 || arguments.InstanceCount == 0) + { + return false; + } + } + else + { + if (!template.RepeatsCpuArguments || !TryReadCpuArguments(in arguments, out drawn)) + { + return false; + } + + if (drawn.IndexCount == 0 || drawn.InstanceCount == 0) + { + var skipped = _pool.RentDraw(); + skipped.ResetBindings = true; + Record(skipped); + return true; + } + } + + var vertexInput = template.State.Programs.VertexInput; + var record = _pool.RentDraw(); + record.CopyFrom(template); + record.Debug = new DebugInformation(RecordedOperation.DrawIndex, submitId, drawn.IndexCount, 0, 1, drawn.InstanceCount, drawn.IndexAddress); + record.SubmitId = submitId; + record.Draw = new DrawCall("DrawIndexed", RecordedOperation.DrawIndex, drawn.IndexCount, drawn.InstanceCount, drawn.FirstInstance); + record.Index = new IndexSource(true, drawn.IndexAddress, null, elementSize * drawn.IndexCount, indexType); + record.Emission = new DrawEmission( + true, + drawn.BaseVertex + (drawn.BaseVertexInRegister ? ResolveVertexOffset(0, vertexInput) : 0), + 0, + drawn.FirstInstance + (drawn.FirstInstanceInRegister ? ResolveInstanceOffset(vertexInput) : 0), + drawn.IndirectArgumentsAddress); + record.PacketAddress = drawn.PacketAddress; + Record(record); + return true; + } + public void DrawAuto(ulong submitId, RegisterBanks banks, in DrawAutoArguments arguments) { using var meshTrace = MeshDrawTrace.Begin(submitId, banks.Shader.Vertex.ExportAddress, banks.Context.ShaderStages); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs index 067c881a4..ffdb425b4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs @@ -132,7 +132,7 @@ void Address(uint word, ulong address) } state.Programs.VertexInput.Stage = originalDomainStage with { TessellationData = data }; record.Draw = draw with { Count = batchPatches * layout.InputControlPoints, InstanceCount = 1 }; - RecordDrawCommands(record, ref state, inPlace: false); + RecordDrawCommands(record, ref state, inPlace: false, out _); _host.EndRendering(); // The next batch reuses relative patch IDs in the guest rings. _host.ShaderWriteHazardBarrier(); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index 89108cfd6..5c9bc8742 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -333,6 +333,30 @@ public void Record(ResolvedDraw record) private void RecordDraw(ResolvedDraw record) { + var offsets = record.IndirectOffsets; + RecordDraw(record, out var issuedRun); + if (issuedRun || offsets is null) return; + + var first = record.Emission; + try + { + record.IndirectOffsets = null; + foreach (var offset in offsets.AsSpan(1)) + { + record.Emission = first with { IndirectArgumentsAddress = first.IndirectArgumentsAddress + offset }; + RecordDraw(record, out _); + } + } + finally + { + record.IndirectOffsets = offsets; + record.Emission = first; + } + } + + private void RecordDraw(ResolvedDraw record, out bool issuedRun) + { + issuedRun = false; if (record.Announce) { if (!_host.IsRecording) @@ -390,7 +414,7 @@ private void RecordDraw(ResolvedDraw record) NoteFoundTargets(ref state); } - RecordDrawCommands(record, ref state, inPlace); + RecordDrawCommands(record, ref state, inPlace, out issuedRun); break; } } @@ -505,8 +529,9 @@ private static void NoteSampledTextures(in ShaderStageResources stage) } } - private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool inPlace) + private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool inPlace, out bool issuedRun) { + issuedRun = false; using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawResourcePreparation); var submitId = record.SubmitId; ref readonly var draw = ref record.Draw; @@ -650,9 +675,11 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i var vertexBuffers = meshInput is null ? AcquireVertexBuffers(vertexInput) : default; var indexBuffer = meshInput is null ? AcquireIndexBuffer(in indexSource) : default; + var indirectBytes = record.IndirectOffsets is not null ? record.IndirectBytes : + emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize; var indirectArguments = meshInput is null && emission.IndirectArgumentsAddress != 0 ? _host.ObtainBuffer(emission.IndirectArgumentsAddress, - emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false) + indirectBytes, isWritten: false) : default; RenderExecutor.DropUnwrittenColorTargets(context, ref state, pixelProgram); var reusedAttachments = inPlace && TryRestoreAttachments(ref state); @@ -693,7 +720,7 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i if (emission.IndirectArgumentsAddress != 0) { indirectArguments = _host.ObtainBuffer(emission.IndirectArgumentsAddress, - emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false); + indirectBytes, isWritten: false); } } } @@ -763,7 +790,18 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i } else if (emission.IndirectArgumentsAddress != 0 && emission.Indexed) { - _host.DrawIndexedIndirect(indirectArguments); + var targets = DrawState.BoundColors(ref state); + issuedRun = imageSnapshot == 0 && record.IndirectOffsets is not null && _host.CanShareIndexedBindings(vertexBindings, targets, in state.Depth) && + (pixelBindings is null || _host.CanShareIndexedBindings(pixelBindings, targets, in state.Depth)); + if (issuedRun) + { + foreach (var offset in record.IndirectOffsets!) + _host.DrawIndexedIndirect(indirectArguments with { Offset = indirectArguments.Offset + offset }); + } + else + { + _host.DrawIndexedIndirect(indirectArguments); + } } else if (emission.IndirectArgumentsAddress != 0) { @@ -1023,7 +1061,7 @@ private void SealReplay(ResolvedDraw record, in DrawState state, VertexInputInfo private bool TryReplayDraw(ResolvedDraw record, ref DrawState state, bool inPlace, VertexInputInfo vertexInput, PixelInputInfo pixelInput, in IndexSource indexSource, in DrawEmission emission, in DrawCall draw) { - if (!DrawReplayEnabled || !_replayValid || !inPlace || record.Kind != ResolvedDrawKind.Draw || record.WritesMemory || + if (record.IndirectOffsets is not null || !DrawReplayEnabled || !_replayValid || !inPlace || record.Kind != ResolvedDrawKind.Draw || record.WritesMemory || record.WriteStages != PipelineStageFlags.None || record.IndexedTrace is not null || MeshDrawTrace.Active) { return false; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs index f6b0f8cdd..0b186c3f1 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs @@ -87,6 +87,8 @@ internal sealed class ResolvedDraw public bool PrimitiveRestart; public GuestPrimitiveType PrimitiveType; public DrawEmission Emission; + public uint[]? IndirectOffsets; + public uint IndirectBytes; public IndexSource Index; public ulong TessellationIndexAddress; public uint TessellationIndexSize; @@ -112,9 +114,61 @@ internal sealed class ResolvedDraw public Extent3D CopyExtent; public ImageAspectFlags CopyAspects; + // An indexed indirect draw resolved on the plain path (no host index data, no strip, mesh or tessellation): the next draw + // under the same registers can take this record with only its own arguments (RenderExecutor.TryRepeatIndexed). + public bool RepeatableArguments; + + // The arguments were read on the CPU (DrawIndexedWithCpuArguments); a repeat reads its own the same way. + public bool RepeatsCpuArguments; + + public void CopyFrom(ResolvedDraw source) + { + Sequence = source.Sequence; + Kind = source.Kind; + Announce = source.Announce; + Debug = source.Debug; + ResetBindings = source.ResetBindings; + TargetsResolved = source.TargetsResolved; + SubmitId = source.SubmitId; + Draw = source.Draw; + State = source.State; + Topology = source.Topology; + PrimitiveRestart = source.PrimitiveRestart; + PrimitiveType = source.PrimitiveType; + Emission = source.Emission; + Index = source.Index; + TessellationIndexAddress = source.TessellationIndexAddress; + TessellationIndexSize = source.TessellationIndexSize; + TessellationVertexOffset = source.TessellationVertexOffset; + Context = source.Context; + ContextStamp = source.ContextStamp; + DynamicStamp = source.DynamicStamp; + TargetVersion = source.TargetVersion; + Dynamic = source.Dynamic; + WritesMemory = source.WritesMemory; + WriteStages = source.WriteStages; + SetBindDebug = source.SetBindDebug; + SetAutoDebug = source.SetAutoDebug; + IndexedTrace = source.IndexedTrace; + PacketAddress = source.PacketAddress; + Clear = source.Clear; + ResolveSource = source.ResolveSource; + ResolveDestination = source.ResolveDestination; + CopyRead = source.CopyRead; + CopyWrite = source.CopyWrite; + CopyReadFormat = source.CopyReadFormat; + CopyWriteFormat = source.CopyWriteFormat; + CopyExtent = source.CopyExtent; + CopyAspects = source.CopyAspects; + RepeatableArguments = source.RepeatableArguments; + RepeatsCpuArguments = source.RepeatsCpuArguments; + } + public void Reset() { var previous = Kind; + RepeatableArguments = false; + RepeatsCpuArguments = false; Sequence = 0; Kind = ResolvedDrawKind.Skipped; Announce = false; @@ -128,6 +182,8 @@ public void Reset() PrimitiveRestart = false; PrimitiveType = default; Emission = default; + IndirectOffsets = null; + IndirectBytes = 0; Index = default; TessellationIndexAddress = 0; TessellationIndexSize = 0; diff --git a/src/SharpEmu.Libs/HostHighResolutionSleep.cs b/src/SharpEmu.Libs/HostHighResolutionSleep.cs index 3981bba93..7efc27a31 100644 --- a/src/SharpEmu.Libs/HostHighResolutionSleep.cs +++ b/src/SharpEmu.Libs/HostHighResolutionSleep.cs @@ -27,6 +27,18 @@ internal static unsafe partial class HostHighResolutionSleep private static int _posixClockState; + // Spins for the time asked, with pause hints: for a short wait the host timer would round up to its period. + public static void SpinMicroseconds(ulong microseconds) + { + var ticks = (long)Math.Min(microseconds, 1_000_000UL) * Stopwatch.Frequency / 1_000_000; + var deadline = Stopwatch.GetTimestamp() + Math.Max(ticks, 1); + do + { + Thread.SpinWait(8); + } + while (Stopwatch.GetTimestamp() < deadline); + } + public static void SleepMicroseconds(ulong microseconds) => Sleep100ns(microseconds > long.MaxValue / 10 ? long.MaxValue : (long)microseconds * 10, allowSpinning: true); diff --git a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs index 580619281..52b81b241 100644 --- a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs @@ -104,6 +104,14 @@ public static int KernelUsleep(CpuContext ctx) GuestThreadExecution.Scheduler?.Pump(ctx, "sceKernelUsleep"); + // An audio producer that runs behind the device naps for the time it asks (a timer wait takes about 0.5 ms). + if (micros > UsleepSpinLimitMicroseconds && Audio.AudioOut2Exports.ProducerNeedsPreciseNap(micros)) + { + HostHighResolutionSleep.SpinMicroseconds(micros); + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + if (micros > UsleepSpinLimitMicroseconds) { // The audio producer pacing may shorten the sleep; a sleep that was above the spin limit stays above it, so a nap diff --git a/src/SharpEmu.Libs/Pad/HostWindowInput.cs b/src/SharpEmu.Libs/Pad/HostWindowInput.cs index 116fad99d..be9a999d1 100644 --- a/src/SharpEmu.Libs/Pad/HostWindowInput.cs +++ b/src/SharpEmu.Libs/Pad/HostWindowInput.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Numerics; using SharpEmu.HLE.Host; namespace SharpEmu.Libs.Pad; @@ -16,6 +17,8 @@ public static class HostWindowInput private static HostGamepadState _gamepadState; private static IHostGamepadOutput? _gamepadOutput; private static readonly WindowInputSource Source = new(); + private static readonly MotionOrientation Orientation = new(); + private const float StandardGravity = 9.80665f; public static void Connect(IHostGamepadOutput? gamepadOutput = null) { @@ -27,6 +30,7 @@ public static void Connect(IHostGamepadOutput? gamepadOutput = null) } HostWindowInputSource.Set(Source); + Changed?.Invoke(); } public static void Disconnect() @@ -39,58 +43,145 @@ public static void Disconnect() _gamepadState = default; _gamepadOutput = null; PressedKeys.Clear(); + Orientation.Reset(); } HostWindowInputSource.Clear(Source); + Changed?.Invoke(); } + // Called after each change of the window, a key, the focus, or a gamepad's buttons or touch contacts, as it + // happens: the pad keeps the states between two reads of the game (PadExports.RecordInputChange), so a press and + // its release in between both reach it. + internal static Action? Changed; + public static void SetFocused(bool focused) { + bool changed; lock (Gate) { + changed = _focused != focused || (!focused && PressedKeys.Count != 0); _focused = focused; if (!focused) { PressedKeys.Clear(); } } + + if (changed) Changed?.Invoke(); } public static void SetKey(int virtualKey, bool down) { + bool changed; lock (Gate) { - if (down) - { - PressedKeys.Add(virtualKey); - } - else - { - PressedKeys.Remove(virtualKey); - } + changed = down ? PressedKeys.Add(virtualKey) : PressedKeys.Remove(virtualKey); } + + if (changed) Changed?.Invoke(); } public static void SetGamepad(string? name, HostGamepadState state) { + bool changed; lock (Gate) { + changed = _gamepadConnected != state.Connected || _gamepadState.Buttons != state.Buttons || + !SameContacts(_gamepadState.Touch, state.Touch); + if (state.Motion.Available) + { + var orientation = Orientation.Orientation; + state = state with + { + Motion = state.Motion with + { + OrientationX = orientation.X, + OrientationY = orientation.Y, + OrientationZ = orientation.Z, + OrientationW = orientation.W, + }, + }; + } + _gamepadConnected = state.Connected; _gamepadName = name; _gamepadState = state; } + + if (changed) Changed?.Invoke(); + } + + // One button event of the connected gamepad, applied as it comes: a poll sees only where the buttons ended up. + public static void SetGamepadButton(HostGamepadButtons button, bool down) + { + bool changed; + lock (Gate) + { + var buttons = down ? _gamepadState.Buttons | button : _gamepadState.Buttons & ~button; + changed = _gamepadConnected && buttons != _gamepadState.Buttons; + if (changed) + { + _gamepadState = _gamepadState with { Buttons = buttons }; + } + } + + if (changed) Changed?.Invoke(); } public static void ClearGamepad() { + bool changed; lock (Gate) { + changed = _gamepadConnected; _gamepadConnected = false; _gamepadName = null; _gamepadState = default; + Orientation.Reset(); } + + if (changed) Changed?.Invoke(); } + // One sensor reading of the connected gamepad as SDL reports it (acceleration in m/s^2, angular velocity in + // radians per second, the sensor's timestamp in nanoseconds). Each gyro reading turns the pad's orientation by its + // own interval, which a poll of the latest reading cannot do. + public static void ApplyGamepadMotion(bool angularVelocity, float x, float y, float z, ulong timestampNanoseconds) + { + lock (Gate) + { + if (angularVelocity) + { + Orientation.ApplyAngularVelocity(new Vector3(x, y, z), timestampNanoseconds); + } + else + { + Orientation.ApplyAcceleration(new Vector3(x, y, z) / StandardGravity); + } + } + } + + internal static void ResetMotionOrientation() + { + lock (Gate) + { + Orientation.Reset(); + } + } + + internal static void SetMotionTiltCorrection(bool enabled) + { + lock (Gate) + { + Orientation.TiltCorrection = enabled; + } + } + + private static bool SameContacts(HostTouchState left, HostTouchState right) => + left.First.Active == right.First.Active && left.First.Id == right.First.Id && + left.Second.Active == right.Second.Active && left.Second.Id == right.Second.Id; + internal static byte ToStickByte(short value) { var normalized = value + 32768; diff --git a/src/SharpEmu.Libs/Pad/MotionOrientation.cs b/src/SharpEmu.Libs/Pad/MotionOrientation.cs new file mode 100644 index 000000000..2e635d528 --- /dev/null +++ b/src/SharpEmu.Libs/Pad/MotionOrientation.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Numerics; + +namespace SharpEmu.Libs.Pad; + +/// <summary> +/// The pad's orientation: the gyro's rotation accumulated since the controller connected or the game last reset it, +/// in the pad's own axes. With tilt correction on, gravity pulls pitch and roll back toward the measured down +/// direction; heading has no such reference and keeps the gyro's drift. +/// </summary> +internal sealed class MotionOrientation +{ + // Readings further apart than this are a gap in the reports, not one long rotation. + private const ulong MaximumStepNanoseconds = 100_000_000; + + private Quaternion _orientation = Quaternion.Identity; + private Vector3 _gravity; + private Vector3 _up; + private bool _upKnown; + private ulong _lastGyroTimestamp; + + public bool TiltCorrection { get; set; } + + public Quaternion Orientation => _orientation; + + public void Reset() + { + _orientation = Quaternion.Identity; + _upKnown = false; + _lastGyroTimestamp = 0; + } + + // An accelerometer reading in G. The first one near 1 G after a reset fixes the up direction tilt correction + // returns to. + public void ApplyAcceleration(Vector3 gravity) + { + _gravity = gravity; + var magnitude = gravity.Length(); + if (!_upKnown && magnitude is > 0.9f and < 1.1f) + { + _up = Vector3.Transform(gravity / magnitude, _orientation); + _upKnown = true; + } + } + + // A gyro reading in radians per second, rotating the orientation over the time since the previous reading. + public void ApplyAngularVelocity(Vector3 rate, ulong timestampNanoseconds) + { + var last = _lastGyroTimestamp; + _lastGyroTimestamp = timestampNanoseconds; + if (last == 0 || timestampNanoseconds <= last || timestampNanoseconds - last > MaximumStepNanoseconds) + { + return; + } + + var magnitude = _gravity.Length(); + if (TiltCorrection && _upKnown && magnitude is > 0.8f and < 1.2f) + { + // Turn toward the measured gravity from where the orientation expects it, both in the pad's axes. Readings + // far from 1 G carry the pad's own acceleration and are left out. + var expected = Vector3.Transform(_up, Quaternion.Conjugate(_orientation)); + rate += Vector3.Cross(_gravity / magnitude, expected); + } + + var angle = rate.Length() * ((timestampNanoseconds - last) * 1e-9f); + if (angle > 0) + { + _orientation = Quaternion.Normalize(_orientation * Quaternion.CreateFromAxisAngle(Vector3.Normalize(rate), angle)); + } + } +} diff --git a/src/SharpEmu.Libs/Pad/PadExports.cs b/src/SharpEmu.Libs/Pad/PadExports.cs index d291170c1..ae494fd27 100644 --- a/src/SharpEmu.Libs/Pad/PadExports.cs +++ b/src/SharpEmu.Libs/Pad/PadExports.cs @@ -38,6 +38,18 @@ public static class PadExports [ThreadStatic] private static PadState _cachedInputState; + [ThreadStatic] + private static long _cachedInputHistory; + + // The history scePadRead returns (64 states, as the console keeps): the pad's state after each change of a button + // or a touch contact, in order, taken as the window's input events come (RecordInputChange). Each session reads + // the states it has not read yet, so a press and its release between two reads reach the game as two states + // instead of none. + private const int HistoryCapacity = 64; + private static readonly object HistoryGate = new(); + private static readonly (PadState State, ulong Timestamp)[] History = new (PadState, ulong)[HistoryCapacity]; + private static long _historyNext; + private static int _controlsAnnouncementLogged; private static readonly bool LogPadState = string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_PAD_STATE"), "1", StringComparison.Ordinal); @@ -65,10 +77,61 @@ private static bool TryGetSession(CpuContext context, int handle, out PadSession public static int PadInit(CpuContext ctx) { GetSessions(ctx).Initialize(); + HostWindowInput.Changed = RecordInputChange; HostPlatform.Current.Input.EnsureStarted(); return ctx.SetReturn(0); } + private static void RecordInputChange() + { + var state = ReadHostInputState(fresh: true); + var timestamp = TimestampMicroseconds(); + lock (HistoryGate) + { + if (_historyNext != 0 && SameButtonsAndContacts(History[(int)((_historyNext - 1) % HistoryCapacity)].State, state)) + { + return; + } + + History[(int)(_historyNext % HistoryCapacity)] = (state, timestamp); + _historyNext++; + } + } + + private static bool SameButtonsAndContacts(in PadState left, in PadState right) => + left.Buttons == right.Buttons && + left.Touch.First.Active == right.Touch.First.Active && left.Touch.First.Id == right.Touch.First.Id && + left.Touch.Second.Active == right.Touch.Second.Active && left.Touch.Second.Id == right.Touch.Second.Id; + + // The states the session has not read, oldest first, at most count; a session reads from its first read on. + private static (PadState State, ulong Timestamp)[] TakeUnreadStates(PadSession session, int count, out bool more) + { + lock (HistoryGate) + { + if (session.ReadSequence < 0) + { + session.ReadSequence = _historyNext; + } + + var first = Math.Max(session.ReadSequence, _historyNext - HistoryCapacity); + var take = (int)Math.Min(_historyNext - first, count); + more = _historyNext - first > take; + if (take == 0) + { + return []; + } + + var states = new (PadState State, ulong Timestamp)[take]; + for (var index = 0; index < take; index++) + { + states[index] = History[(int)((first + index) % HistoryCapacity)]; + } + + session.ReadSequence = first + take; + return states; + } + } + #pragma warning disable SHEM006 [SysAbiExport( Nid = "n3kSX62fgNo", @@ -259,9 +322,13 @@ public static int PadSetMotionSensorState(CpuContext ctx) public static int PadSetTiltCorrectionState(CpuContext ctx) { var handle = unchecked((int)ctx[CpuRegister.Rdi]); - return TryGetSession(ctx, handle, out _) - ? ctx.SetReturn(0) - : ctx.SetReturn(OrbisPadErrorInvalidHandle); + if (!TryGetSession(ctx, handle, out _)) + { + return ctx.SetReturn(OrbisPadErrorInvalidHandle); + } + + HostWindowInput.SetMotionTiltCorrection((byte)ctx[CpuRegister.Rsi] != 0); + return ctx.SetReturn(0); } [SysAbiExport( @@ -478,14 +545,44 @@ public static int PadRead(CpuContext ctx) return ctx.SetReturn(OrbisPadErrorInvalidHandle); } - if (dataAddress == 0 || count < 1 || count > 64) + if (dataAddress == 0 || count < 1 || count > HistoryCapacity) { return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); } - return WritePadData(ctx, dataAddress, handle, session, "scePadRead") - ? ctx.SetReturn(1) - : ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + if (!session.Connected) + { + return WritePadData(ctx, dataAddress, handle, session, "scePadRead") + ? ctx.SetReturn(1) + : ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + // The unread states, then the state now when room is left and none waits: a connected pad keeps reporting, so + // the last state a read returns is the current one (the sticks and sensors since the last change). + var states = TakeUnreadStates(session, count, out var more); + var written = 0; + foreach (var (state, timestamp) in states) + { + if (!WritePadState(ctx, dataAddress + (ulong)(written * PadDataSize), handle, session, state, timestamp, "scePadRead")) + { + return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + written++; + } + + if (!more && written < count) + { + if (!WritePadState(ctx, dataAddress + (ulong)(written * PadDataSize), handle, session, + ReadHostInputState(fresh: written != 0), TimestampMicroseconds(), "scePadRead")) + { + return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + written++; + } + + return ctx.SetReturn(written); } [SysAbiExport( @@ -535,6 +632,19 @@ public static int PadSetTriggerEffect(CpuContext ctx) } var triggerMask = parameter[0]; + lock (session.TriggerEffects) + { + if ((triggerMask & 0x01) != 0) + { + parameter[8..64].CopyTo(session.TriggerEffects); + } + + if ((triggerMask & 0x02) != 0) + { + parameter[64..120].CopyTo(session.TriggerEffects.AsSpan(56)); + } + } + HostPlatform.Current.Input.SetAdaptiveTriggerEffect( (triggerMask & 0x01) != 0 ? DecodeTriggerEffect(parameter[8..64]) : null, (triggerMask & 0x02) != 0 ? DecodeTriggerEffect(parameter[64..120]) : null); @@ -556,7 +666,7 @@ public static int PadGetTriggerEffectState(CpuContext ctx) { var handle = unchecked((int)ctx[CpuRegister.Rdi]); var stateAddress = ctx[CpuRegister.Rsi]; - if (!TryGetSession(ctx, handle, out _)) + if (!TryGetSession(ctx, handle, out var session)) { return ctx.SetReturn(OrbisPadErrorInvalidHandle); } @@ -566,17 +676,42 @@ public static int PadGetTriggerEffectState(CpuContext ctx) return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); } - // No host pad exposes DualSense adaptive-trigger feedback, so every - // trigger reports the neutral "no effect engaged" state. Reporting it - // as success is what lets the caller take its normal path instead of - // falling back to a cached button bitmask every poll. + // A DualSense reports where each trigger is against its running effect, but SDL does not expose that report + // and other pads have no trigger motors. The state follows from the game's last effect and the trigger's + // travel instead, so a game that waits for a weapon or feedback state before acting on L2 or R2 sees it. + var input = ReadHostInputState(); Span<byte> state = stackalloc byte[TriggerEffectStateSize]; - state.Clear(); + lock (session.TriggerEffects) + { + BinaryPrimitives.WriteInt32LittleEndian(state, TriggerEffectState(session.TriggerEffects.AsSpan(0, 56), input.L2)); + BinaryPrimitives.WriteInt32LittleEndian(state[4..], TriggerEffectState(session.TriggerEffects.AsSpan(56, 56), input.R2)); + } + return ctx.Memory.TryWrite(stateAddress, state) ? ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_OK) : ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } + // A trigger's state against a trigger effect command: 0 no effect, 1/2 feedback standby/pushing, 3/4/5 weapon + // standby/pulling/fired, 6/7 vibration standby/firing. The travel 0..255 maps to the effect's ten positions, and + // below 8 the trigger counts as released. + internal static int TriggerEffectState(ReadOnlySpan<byte> command, byte travel) + { + var data = command[8..]; + var position = travel * 10 / 256; + var pressed = travel >= 8; + return BinaryPrimitives.ReadUInt32LittleEndian(command) switch + { + 1 => pressed && data[1] != 0 && position >= data[0] ? 2 : 1, + 2 => position >= data[1] ? 5 : position >= data[0] ? 4 : 3, + 3 => pressed && data[1] != 0 && data[2] != 0 && position >= data[0] ? 7 : 6, + 4 => pressed && data[position] != 0 ? 2 : 1, + 5 => pressed && position >= data[0] ? 2 : 1, + 6 => pressed && data[0] != 0 && data[1 + position] != 0 ? 7 : 6, + _ => 0, + }; + } + private static HostAdaptiveTriggerEffect DecodeTriggerEffect(ReadOnlySpan<byte> command) { var mode = BinaryPrimitives.ReadUInt32LittleEndian(command); @@ -835,9 +970,13 @@ public static int PadResetLightBar(CpuContext ctx) public static int PadResetOrientation(CpuContext ctx) { var handle = unchecked((int)ctx[CpuRegister.Rdi]); - return TryGetSession(ctx, handle, out _) - ? ctx.SetReturn(0) - : ctx.SetReturn(OrbisPadErrorInvalidHandle); + if (!TryGetSession(ctx, handle, out _)) + { + return ctx.SetReturn(OrbisPadErrorInvalidHandle); + } + + HostWindowInput.ResetMotionOrientation(); + return ctx.SetReturn(0); } [SysAbiExport( @@ -867,19 +1006,26 @@ public static int PadIsRemoteController(CpuContext ctx) private static bool WritePadData(CpuContext ctx, ulong dataAddress, int handle, PadSession session, string exportName) { - Span<byte> data = stackalloc byte[PadDataSize]; - data.Clear(); - if (!session.Connected) + if (session.Connected) { - data[0x04] = 128; - data[0x05] = 128; - data[0x06] = 128; - data[0x07] = 128; - BinaryPrimitives.WriteSingleLittleEndian(data[0x18..], 1.0f); - return ctx.Memory.TryWrite(dataAddress, data); + return WritePadState(ctx, dataAddress, handle, session, ReadHostInputState(), TimestampMicroseconds(), exportName); } - var input = ReadHostInputState(); + Span<byte> data = stackalloc byte[PadDataSize]; + data.Clear(); + data[0x04] = 128; + data[0x05] = 128; + data[0x06] = 128; + data[0x07] = 128; + BinaryPrimitives.WriteSingleLittleEndian(data[0x18..], 1.0f); + return ctx.Memory.TryWrite(dataAddress, data); + } + + private static bool WritePadState(CpuContext ctx, ulong dataAddress, int handle, PadSession session, in PadState input, + ulong timestampMicroseconds, string exportName) + { + Span<byte> data = stackalloc byte[PadDataSize]; + data.Clear(); var buttons = input.Buttons; var leftX = input.LeftX; var leftY = input.LeftY; @@ -898,6 +1044,10 @@ private static bool WritePadData(CpuContext ctx, ulong dataAddress, int handle, BinaryPrimitives.WriteSingleLittleEndian(data[0x18..], 1.0f); if (Volatile.Read(ref session.MotionSensorEnabled) != 0 && input.Motion.Available) { + BinaryPrimitives.WriteSingleLittleEndian(data[0x0C..], input.Motion.OrientationX); + BinaryPrimitives.WriteSingleLittleEndian(data[0x10..], input.Motion.OrientationY); + BinaryPrimitives.WriteSingleLittleEndian(data[0x14..], input.Motion.OrientationZ); + BinaryPrimitives.WriteSingleLittleEndian(data[0x18..], input.Motion.OrientationW); // Host acceleration is m/s^2 (SDL); ScePadData.acceleration is in G. BinaryPrimitives.WriteSingleLittleEndian(data[0x1C..], input.Motion.AccelerationX / StandardGravity); BinaryPrimitives.WriteSingleLittleEndian(data[0x20..], input.Motion.AccelerationY / StandardGravity); @@ -909,10 +1059,6 @@ private static bool WritePadData(CpuContext ctx, ulong dataAddress, int handle, WriteTouchData(data, input.Touch); data[0x4C] = 1; - var timestampTicks = Stopwatch.GetTimestamp(); - var timestampMicroseconds = - ((ulong)(timestampTicks / Stopwatch.Frequency) * 1_000_000UL) + - ((ulong)(timestampTicks % Stopwatch.Frequency) * 1_000_000UL / (ulong)Stopwatch.Frequency); BinaryPrimitives.WriteUInt64LittleEndian( data[0x50..], timestampMicroseconds); @@ -923,10 +1069,20 @@ private static bool WritePadData(CpuContext ctx, ulong dataAddress, int handle, return guestWriteSucceeded; } - private static PadState ReadHostInputState() + private static ulong TimestampMicroseconds() + { + var ticks = Stopwatch.GetTimestamp(); + return ((ulong)(ticks / Stopwatch.Frequency) * 1_000_000UL) + + ((ulong)(ticks % Stopwatch.Frequency) * 1_000_000UL / (ulong)Stopwatch.Frequency); + } + + // A cached state serves only while no input change was recorded since; fresh: never the cached state. + private static PadState ReadHostInputState(bool fresh = false) { var now = Stopwatch.GetTimestamp(); - if (_lastInputSampleTicks != 0 && now - _lastInputSampleTicks < InputSampleIntervalTicks) + var history = Volatile.Read(ref _historyNext); + if (!fresh && _lastInputSampleTicks != 0 && now - _lastInputSampleTicks < InputSampleIntervalTicks && + history == _cachedInputHistory) { return _cachedInputState; } @@ -1012,6 +1168,7 @@ private static PadState ReadHostInputState() ControllerButtons = controllerButtons, }; _lastInputSampleTicks = now; + _cachedInputHistory = history; return _cachedInputState; } diff --git a/src/SharpEmu.Libs/Pad/PadSessionRegistry.cs b/src/SharpEmu.Libs/Pad/PadSessionRegistry.cs index 6d29b9cf3..c6ae0ce53 100644 --- a/src/SharpEmu.Libs/Pad/PadSessionRegistry.cs +++ b/src/SharpEmu.Libs/Pad/PadSessionRegistry.cs @@ -132,4 +132,8 @@ internal sealed class PadSession(int userId, int portType, int portIndex, bool c public int PortIndex { get; } = portIndex; public bool Connected { get; } = connected; public int MotionSensorEnabled = 1; + // The next pad history state this session reads, -1 before its first read (PadExports.HistoryGate). + public long ReadSequence = -1; + // The last trigger effect command the game set for L2 and R2, 56 bytes each (PadExports.TriggerEffectState). + public readonly byte[] TriggerEffects = new byte[112]; } diff --git a/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs b/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs index 95e45132d..74556cbed 100644 --- a/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs +++ b/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs @@ -42,36 +42,61 @@ public static void EnableSonyHidApi() return SDL_OpenGamepad(selected); } + // SDL's gamepad buttons and the pad buttons they are, for a state read and a button event alike. + private static readonly (SDL_GamepadButton Source, HostGamepadButtons Target)[] ButtonMap = + [ + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_SOUTH, HostGamepadButtons.Cross), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_EAST, HostGamepadButtons.Circle), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_WEST, HostGamepadButtons.Square), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_NORTH, HostGamepadButtons.Triangle), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, HostGamepadButtons.L1), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, HostGamepadButtons.R1), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_LEFT_STICK, HostGamepadButtons.L3), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_RIGHT_STICK, HostGamepadButtons.R3), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_BACK, HostGamepadButtons.Create), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_GUIDE, HostGamepadButtons.Ps), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_START, HostGamepadButtons.Options), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_MISC1, HostGamepadButtons.Mic), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_TOUCHPAD, HostGamepadButtons.TouchPad), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_UP, HostGamepadButtons.Up), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_RIGHT, HostGamepadButtons.Right), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_DOWN, HostGamepadButtons.Down), + (SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_LEFT, HostGamepadButtons.Left), + ]; + + public static HostGamepadButtons MapButton(byte button) + { + foreach (var (source, target) in ButtonMap) + { + if ((byte)source == button) + { + return target; + } + } + + return HostGamepadButtons.None; + } + + // A trigger past a quarter of its travel is also its digital button. + public static bool IsTriggerPressed(byte value) => value > 64; + public static HostGamepadState Read(SDL_Gamepad* gamepad) { var buttons = HostGamepadButtons.None; - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_SOUTH, HostGamepadButtons.Cross, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_EAST, HostGamepadButtons.Circle, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_WEST, HostGamepadButtons.Square, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_NORTH, HostGamepadButtons.Triangle, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, HostGamepadButtons.L1, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, HostGamepadButtons.R1, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_LEFT_STICK, HostGamepadButtons.L3, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_RIGHT_STICK, HostGamepadButtons.R3, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_BACK, HostGamepadButtons.Create, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_GUIDE, HostGamepadButtons.Ps, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_START, HostGamepadButtons.Options, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_MISC1, HostGamepadButtons.Mic, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_TOUCHPAD, HostGamepadButtons.TouchPad, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_UP, HostGamepadButtons.Up, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_RIGHT, HostGamepadButtons.Right, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_DOWN, HostGamepadButtons.Down, ref buttons); - AddButton(gamepad, SDL_GamepadButton.SDL_GAMEPAD_BUTTON_DPAD_LEFT, HostGamepadButtons.Left, ref buttons); + foreach (var (source, target) in ButtonMap) + { + AddButton(gamepad, source, target, ref buttons); + } var leftTrigger = HostWindowInput.ToTriggerByte( SDL_GetGamepadAxis(gamepad, SDL_GamepadAxis.SDL_GAMEPAD_AXIS_LEFT_TRIGGER)); var rightTrigger = HostWindowInput.ToTriggerByte( SDL_GetGamepadAxis(gamepad, SDL_GamepadAxis.SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)); - if (leftTrigger > 64) + if (IsTriggerPressed(leftTrigger)) { buttons |= HostGamepadButtons.L2; } - if (rightTrigger > 64) + if (IsTriggerPressed(rightTrigger)) { buttons |= HostGamepadButtons.R2; } diff --git a/src/SharpEmu.Libs/UserService/UserServiceExports.cs b/src/SharpEmu.Libs/UserService/UserServiceExports.cs index 2460424db..d86eb6920 100644 --- a/src/SharpEmu.Libs/UserService/UserServiceExports.cs +++ b/src/SharpEmu.Libs/UserService/UserServiceExports.cs @@ -268,8 +268,10 @@ public static int UserServiceGetAccessibilityPressAndHoldDelay(CpuContext ctx) = ExportName = "sceUserServiceGetAccessibilityTriggerEffect", Target = Generation.Gen5, LibraryName = "libSceUserService")] + // 1 is the standard (strongest) intensity a console starts with; 0 would tell the game that the user turned trigger + // effects off. public static int UserServiceGetAccessibilityTriggerEffect(CpuContext ctx) => - WriteUserSettingInt32(ctx, 0, "get_accessibility_trigger_effect"); + WriteUserSettingInt32(ctx, 1, "get_accessibility_trigger_effect"); [SysAbiExport( Nid = "qWYHOFwqCxY", diff --git a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs index bb2a22af8..0cb6aadb8 100644 --- a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs +++ b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs @@ -488,6 +488,69 @@ private void PumpEvents() OpenFirstGamepad(); } break; + case SDL_EventType.SDL_EVENT_GAMEPAD_BUTTON_DOWN: + case SDL_EventType.SDL_EVENT_GAMEPAD_BUTTON_UP: + case SDL_EventType.SDL_EVENT_GAMEPAD_AXIS_MOTION: + ApplyGamepadEvent(in windowEvent); + break; + case SDL_EventType.SDL_EVENT_GAMEPAD_SENSOR_UPDATE: + ApplySensorEvent(in windowEvent); + break; + } + } + } + + private void ApplySensorEvent(in SDL_Event windowEvent) + { + lock (_gamepadGate) + { + var sensor = (SDL_SensorType)windowEvent.gsensor.sensor; + if (_gamepad is null || windowEvent.gsensor.which != SDL_GetGamepadID(_gamepad) || + sensor is not (SDL_SensorType.SDL_SENSOR_GYRO or SDL_SensorType.SDL_SENSOR_ACCEL)) + { + return; + } + + HostWindowInput.ApplyGamepadMotion( + sensor == SDL_SensorType.SDL_SENSOR_GYRO, + windowEvent.gsensor.data[0], + windowEvent.gsensor.data[1], + windowEvent.gsensor.data[2], + windowEvent.gsensor.sensor_timestamp); + } + } + + // A button event of the open gamepad, or a trigger crossing its button threshold, applied in the order SDL queued + // it: the poll after the events sees only where the buttons ended up, so a press and its release between two polls + // would never reach the pad. + private void ApplyGamepadEvent(in SDL_Event windowEvent) + { + lock (_gamepadGate) + { + if (_gamepad is null) + { + return; + } + + var gamepad = SDL_GetGamepadID(_gamepad); + if (windowEvent.Type != SDL_EventType.SDL_EVENT_GAMEPAD_AXIS_MOTION) + { + var button = SdlGamepadStateReader.MapButton(windowEvent.gbutton.button); + if (windowEvent.gbutton.which == gamepad && button != HostGamepadButtons.None) + { + HostWindowInput.SetGamepadButton(button, windowEvent.gbutton.down); + } + + return; + } + + var axis = (SDL_GamepadAxis)windowEvent.gaxis.axis; + if (windowEvent.gaxis.which == gamepad && + axis is SDL_GamepadAxis.SDL_GAMEPAD_AXIS_LEFT_TRIGGER or SDL_GamepadAxis.SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) + { + HostWindowInput.SetGamepadButton( + axis == SDL_GamepadAxis.SDL_GAMEPAD_AXIS_LEFT_TRIGGER ? HostGamepadButtons.L2 : HostGamepadButtons.R2, + SdlGamepadStateReader.IsTriggerPressed(HostWindowInput.ToTriggerByte(windowEvent.gaxis.value))); } } } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs index e3b48fab9..7461e0a1d 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs @@ -590,6 +590,7 @@ public bool TryWrite(ulong virtualAddress, ReadOnlySpan<byte> source) presenter._commandThread!.PostWrite(virtualAddress, source); return true; } + presenter._bufferCache?.ApplyPendingGpuProtections(); return inner.TryWrite(virtualAddress, source); } @@ -837,6 +838,18 @@ public void Flush() FlushBatchedGuestCommands(); } + public void FlushSlice() + { + if (OnCommandThread) + { + _commandThread!.Post(FlushSlice); + return; + } + + using var flushScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.Flush); + FlushGuestBatch(deferSubmit: true); + } + // The guest reuses the frame's memory (descriptor tables, rings) once the boundary returns, // so the draws queued before it are recorded first. public void FlushFrame() @@ -1199,6 +1212,9 @@ public void DrawAuto(ulong submitId, in DrawAutoArguments arguments) // SHARPEMU_CPU_INDIRECT_DRAW=1 reads the arguments back on the CPU as before. public bool ResolvesIndirectDrawOnGpu => !_cpuIndirectDraw; + bool ICommandStreamHost.TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) => + OnCommandThread && _translation.TryDrawIndexedRun(submitId, in first, offsets); + private static readonly bool _cpuIndirectDraw = string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_CPU_INDIRECT_DRAW"), "1", StringComparison.Ordinal); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index 0c0dbf3ca..ecc4aa482 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -1131,7 +1131,7 @@ private void Execute(Item item) _presenter._bufferCache.NoteObservation(); // The store can be an end-of-pipe label that tells the guest earlier GPU writes are done. Their // pages must block CPU reads before it lands, not only at the next submission. - if (_presenter._bufferCache.CopyWritesPending) _presenter._bufferCache.ApplyPendingGpuProtections(); + _presenter._bufferCache.ApplyPendingGpuProtections(); ApplyWrite(item); break; } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs index 10c811828..684a6f04a 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs @@ -683,8 +683,11 @@ private void LoadComputeDeviceLimits() } SetNativeSubgroupCapabilities(subgroup.SubgroupSize, subgroup.SupportedStages); SetMipStatisticsCapabilities(true, subgroup.SupportedOperations, subgroup.SupportedStages); + _fixedComputeSubgroup32 = subgroup.SubgroupSize == RdnaSubgroupSize && + subgroupSizeControl.MinSubgroupSize == RdnaSubgroupSize && subgroupSizeControl.MaxSubgroupSize == RdnaSubgroupSize && + (subgroup.SupportedStages & ShaderStageFlags.ComputeBit) != 0; _canRequireComputeSubgroup32 = - subgroup.SubgroupSize != RdnaSubgroupSize && + !_fixedComputeSubgroup32 && subgroupSizeControl.MinSubgroupSize <= RdnaSubgroupSize && subgroupSizeControl.MaxSubgroupSize >= RdnaSubgroupSize && (subgroupSizeControl.RequiredSubgroupSizeStages & ShaderStageFlags.ComputeBit) != 0; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs index 5a63bff8d..74078d36b 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs @@ -146,7 +146,8 @@ private void FlushGraphicsPrewarmProgress(ShaderPrewarmList list, string stamp) private bool PrewarmPixelLibrary(PixelPrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler) { var name = $"ps=0x{record.Hash:X16} shader=0x{record.Address:X16}"; - if (!ShaderProgramCache.TryCompilePixelPrewarm(record, code, compiler, this, out var compiled, out var layout, out var error)) + if (!ShaderProgramCache.TryCompilePixelPrewarm(record, code, compiler, this, out var compiled, out var layout, out var error, + Agc.AgcExports.ShaderFrontendForDomain)) { NoteGraphicsPrewarmFailure(name, error); return false; @@ -195,7 +196,7 @@ private bool PrewarmPreRasterizationLibrary(VertexPrewarmRecord program, ShaderC { var name = $"{(program.Mesh ? "ms" : "vs")}=0x{program.Hash:X16} shader=0x{program.Address:X16}"; if (!ShaderProgramCache.TryCompileVertexPrewarm(program, code, compiler, this, out var compiled, out var layout, - out var task, out var error)) + out var task, out var error, Agc.AgcExports.ShaderFrontendForDomain)) { NoteGraphicsPrewarmFailure(name, error); return false; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestSubmissions.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestSubmissions.cs index e6267b80e..8d91c89d6 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestSubmissions.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestSubmissions.cs @@ -108,7 +108,9 @@ internal void OpenGuestBatch() // Returns the timeline tick that contains the commands this call submitted, so a // caller that must wait for its own recording does not read the shared // _submitTimeline field, which the presenter thread also writes. - internal ulong FlushBatchedGuestCommands() + internal ulong FlushBatchedGuestCommands() => FlushGuestBatch(deferSubmit: false); + + private ulong FlushGuestBatch(bool deferSubmit) { if (!_batchOpen) { @@ -116,7 +118,7 @@ internal ulong FlushBatchedGuestCommands() } using var profile = RenderPhaseProfile.Measure(RenderPhaseProfile.Phase.QueueSubmit); - var tick = _scheduler.Flush(); + var tick = deferSubmit ? _scheduler.FlushDeferred([]) : _scheduler.Flush(); _bufferCache?.OnBatchSubmitted(); return tick; } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs index 4e28ad06d..6c9509dae 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs @@ -130,13 +130,13 @@ private uint[] NormalizeImageOnRenderThread(IShaderFrontend frontend, uint[] wor bool IShaderPipelineHost.ComputeWave64Supported => Volatile.Read(ref _nativeSubgroupSize) >= 64; bool IShaderPipelineHost.ComputeRunsOn32LaneSubgroups(ComputeInputInfo input) => - RequiresComputeSubgroup32(input) || - (Volatile.Read(ref _nativeSubgroupSize) == RdnaSubgroupSize && !RequiresComputeSubgroup64(input)); + _fixedComputeSubgroup32 || RequiresComputeSubgroup32(input); // Wave32 compute maps a guest wave to 32-lane host subgroups, and a 64-lane host subgroup // (AMD's default) left lanes 32..63 inactive, so those pipelines are pinned to 32. Wave64 // compute is pinned to 64 instead when the host runs it natively. private const uint RdnaSubgroupSize = 32; + private bool _fixedComputeSubgroup32; private bool _canRequireComputeSubgroup32; private uint _maxComputeWorkgroupSubgroups; @@ -686,10 +686,13 @@ private bool IsCleanReadPage(ulong address, ulong size) return MayBeCleanReadPage(page); } + // A queued fill or copy that has not landed changes the page for every item after it in the stream, so the page reads + // through the ordered path, which refuses the bytes or waits for the range, as it does for a queued store. private bool MayBeCleanReadPage(ulong page) { var thread = _commandThread!; return !_bufferCache.MayHaveGpuDirtyPages(page, CleanReadPageBytes) && !thread.HasPendingStores(page, CleanReadPageBytes) && + !thread.HasPendingRange(page, CleanReadPageBytes) && (_translation.PendingWrites is not { } pending || !pending.MayHavePending(page, CleanReadPageBytes)) && !thread.HasShadow(page, CleanReadPageBytes); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs index cc552d939..4dfe6ec89 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs @@ -453,6 +453,11 @@ DepthAttachmentAcquisition IRenderHost.AcquireDepthAttachment(in DepthAttachment throw SubmissionScheduler.Fatal($"The HTile clear state could not be consumed: htile=0x{resolution.HtileAddress:X16} layer={layer}."); } + if (resolution.HasHtile) + { + _imageCache.NoteDepthClearValue(resolution.HtileAddress, depth.Target.State.DepthClearValue); + } + var image = _imageCache.GetImage(depth.Image); return new DepthAttachmentAcquisition(view, image.Backing.Samples, metadataClear); } @@ -1539,6 +1544,20 @@ void IRenderHost.DrawIndexed(uint indexCount, uint instanceCount, uint firstInde CountDraw(); } + bool IRenderHost.CanShareIndexedBindings(IPreparedBindings stage, ReadOnlySpan<ColorTargetState> colors, in DepthAttachmentState depth) + { + if (_preparation?.StencilStorageImages is not null || _preparation?.FeedbackSnapshots is not null || _snapshotPixelHash != 0) + return false; + foreach (var texture in ((PreparedStageBindings)stage).Textures) + { + if (texture.IsHostMovie || texture.IsFeedbackSnapshot || texture.IsStorage) return false; + if (depth.HasTarget && texture.ImageIdentifier == depth.Image) return false; + foreach (ref readonly var color in colors) + if (texture.ImageIdentifier == color.Image) return false; + } + return true; + } + void IRenderHost.DrawIndexedIndirect(BufferBinding arguments) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawRecording); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index 0ee8865dd..26cb2ad41 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -1603,6 +1603,7 @@ internal void ApplySliceDepthClears(List<SliceDepthClear> clears) { foreach (var entry in clears) { + _imageCache.NoteDepthClearValue(entry.Htile, BitConverter.UInt32BitsToSingle(entry.ClearWord)); if (!_imageCache.IsMetadataCleared(entry.Htile, entry.BaseLayer)) { continue; diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs index 90cc93803..f8cc4714c 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs @@ -6212,12 +6212,21 @@ private uint ApplyOutputModifiers( return value; } + // V_CVT_PKRTZ_F16_F32 rounds toward zero. Clearing the 13 mantissa bits a half cannot hold makes the + // round-to-nearest pack exact inside the half range, but a finite value of 65536 or more would still round + // to infinity, where rounding toward zero gives the largest finite half, 65504. A NaN keeps its bits, so a + // payload held only in the cleared bits does not become infinity either. private uint TruncateFloat32ForPack(uint value) { - var raw = BitwiseAnd( - Bitcast(_uintType, value), - UInt(0xFFFF_E000)); - return Bitcast(_floatType, raw); + var bits = Bitcast(_uintType, value); + var raw = BitwiseAnd(bits, UInt(0xFFFF_E000)); + var magnitude = BitwiseAnd(bits, UInt(0x7FFF_FFFF)); + var overflow = LogicalAnd( + UCmp(SpirvOp.UGreaterThanEqual, magnitude, UInt(0x4780_0000)), + UCmp(SpirvOp.ULessThan, magnitude, UInt(0x7F80_0000))); + var largest = BitwiseOr(BitwiseAnd(bits, UInt(0x8000_0000)), UInt(0x477F_E000)); + var nan = UCmp(SpirvOp.UGreaterThan, magnitude, UInt(0x7F80_0000)); + return Bitcast(_floatType, SelectU(nan, bits, SelectU(overflow, largest, raw))); } private uint Ext(uint operation, uint resultType, params uint[] operands) diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs index d164e8cdd..48d60f716 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Numerics; using SharpEmu.ShaderCompiler.Resources; namespace SharpEmu.ShaderCompiler.Vulkan; @@ -30,6 +31,38 @@ private static bool CanRunHalfWaves(ShaderCompileRequest request, int[] physical return Ir.Gen5WaveLaneLocalAnalysis.IsLaneLocal(request.Program, sharedFlatPcs, out _); } + private bool UsesHalfWaveSubgroups => _waveLowering is HalfWave64Lowering && UsesSubgroupOperations(); + + private uint HalfWaveThreadCount => checked(_localSizeX * _localSizeY * _localSizeZ); + + private uint HalfWaveLocalIndex() => + IAdd(ShiftLeftLogical(Load(_uintType, _subgroupIdInput), UInt(5)), Load(_uintType, _subgroupInvocationIdInput)); + + private uint HalfWaveLocalCoordinates(uint index) + { + if (_localSizeY == 1 && _localSizeZ == 1) + { + return _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec3Type, index, UInt(0), UInt(0)); + } + + var (x, row) = SplitHalfWaveIndex(index, _localSizeX); + var (y, z) = _localSizeZ == 1 ? (row, UInt(0)) : SplitHalfWaveIndex(row, _localSizeY); + return _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec3Type, x, y, z); + } + + private (uint Component, uint Remaining) SplitHalfWaveIndex(uint index, uint size) + { + if (size == 1) + { + return (UInt(0), index); + } + + return BitOperations.IsPow2(size) + ? (BitwiseAnd(index, UInt(size - 1)), ShiftRightLogical(index, UInt((uint)BitOperations.Log2(size)))) + : (_module.AddInstruction(SpirvOp.UMod, _uintType, index, UInt(size)), + _module.AddInstruction(SpirvOp.UDiv, _uintType, index, UInt(size))); + } + private sealed class HalfWave64Lowering : IWaveLowering { private readonly CompilationContext _context; @@ -87,10 +120,10 @@ public uint BooleanToWaveMask(uint condition) SpirvOp.Select, context._ulongType, context._module.AddInstruction( - SpirvOp.UGreaterThanEqual, + SpirvOp.INotEqual, context._boolType, - context.GuestWaveLane(), - context.UInt(32)), + context.BitwiseAnd(context.Load(context._uintType, context._subgroupIdInput), context.UInt(1)), + context.UInt(0)), context.ShiftLeftLogical64(widened, context._module.Constant64(context._ulongType, 32)), widened); } diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs index 1673ea8dc..8c859e5db 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs @@ -91,9 +91,9 @@ private void DeclarePairedScratch(uint arrayPointer, uint arrayType) _module.AddName(_upperScratch, "scratchUpperHalf"); } - private void DeclarePairedLaneInputs() + private void DeclareComputeSubgroupId() { - if (!_pairedLanes) + if (!_pairedLanes && !UsesHalfWaveSubgroups) { return; } diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs index 53354406e..7acf2a6af 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs @@ -238,6 +238,7 @@ instruction.Opcode is "BufferLoadDwordx2" or "BufferStoreDwordx2" && ShaderStage.TessellationEvaluation => Gen5SpirvStage.TessellationEvaluation, _ => Gen5SpirvStage.Compute, }; + _module.KeepsFloatRounding = _stage is not (Gen5SpirvStage.Pixel or Gen5SpirvStage.Compute); _pixelOutputBindings = request.PixelOutputs; _usesPixelValidMask = _stage == Gen5SpirvStage.Pixel && diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs index 658b60041..cdf194d84 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs @@ -562,6 +562,10 @@ uint EncodeBool(uint condition) => { _module.AddExecutionMode(main, SpirvExecutionMode.LocalSize, PairedHostThreadCount(), 1, 1); } + else if (UsesHalfWaveSubgroups && physicalSizes[0] % 32 != 0) + { + _module.AddExecutionMode(main, SpirvExecutionMode.LocalSize, 32, (HalfWaveThreadCount + 31) / 32, 1); + } else { _module.AddExecutionMode( @@ -587,7 +591,7 @@ uint EncodeBool(uint condition) => ? (uint)_vertexOutputs.Count : (uint)_pixelInputs.Count; profile.Switch(ShaderTranslationProfile.Part.Serialization); - shader = new Gen5SpirvShader(_module.Build(), attributeCount) + shader = new Gen5SpirvShader(_module.Build(spirv16: UsesHalfWaveSubgroups), attributeCount) { InputLocationMask = _stage == Gen5SpirvStage.Pixel ? _pixelInputLocationMask : null, }; @@ -902,7 +906,7 @@ private void DeclareStageInterface() // LocalInvocationIndex is a compute-stage built-in. Graphics // stages can still use native subgroup operations, but they // cannot combine two subgroup32 halves through a workgroup. - if ((_stage is Gen5SpirvStage.Compute or Gen5SpirvStage.Mesh) && _waveLaneCount == 64) + if ((_stage is Gen5SpirvStage.Compute or Gen5SpirvStage.Mesh) && _waveLaneCount == 64 && !UsesHalfWaveSubgroups) { _localInvocationIndexInput = _module.AddGlobalVariable( subgroupPointer, @@ -914,7 +918,7 @@ private void DeclareStageInterface() _interfaces.Add(_localInvocationIndexInput); } - DeclarePairedLaneInputs(); + DeclareComputeSubgroupId(); } if (HasVertexOutputs) @@ -1195,13 +1199,12 @@ bool IsFlatSlot(uint attribute) => { var inputPointer = _module.TypePointer(SpirvStorageClass.Input, _uvec3Type); - _localInvocationIdInput = _module.AddGlobalVariable( - inputPointer, - SpirvStorageClass.Input); - _module.AddDecoration( - _localInvocationIdInput, - SpirvDecoration.BuiltIn, - (uint)SpirvBuiltIn.LocalInvocationId); + if (!UsesHalfWaveSubgroups) + { + _localInvocationIdInput = _module.AddGlobalVariable(inputPointer, SpirvStorageClass.Input); + _module.AddDecoration(_localInvocationIdInput, SpirvDecoration.BuiltIn, (uint)SpirvBuiltIn.LocalInvocationId); + _interfaces.Add(_localInvocationIdInput); + } _workGroupIdInput = _module.AddGlobalVariable( inputPointer, SpirvStorageClass.Input); @@ -1209,7 +1212,6 @@ bool IsFlatSlot(uint attribute) => _workGroupIdInput, SpirvDecoration.BuiltIn, (uint)SpirvBuiltIn.WorkgroupId); - _interfaces.Add(_localInvocationIdInput); _interfaces.Add(_workGroupIdInput); if (_stage == Gen5SpirvStage.Mesh) { @@ -1320,9 +1322,14 @@ private void EmitInitialState() else { var lanes = BooleanToWaveMask(_module.ConstantBool(true)); - laneCount = IAdd( - _module.AddInstruction(SpirvOp.BitCount, _uintType, Narrow(lanes)), - _module.AddInstruction(SpirvOp.BitCount, _uintType, Narrow(ShiftRightLogical64(lanes, _module.Constant64(_ulongType, 32))))); + var lowLanes = Narrow(lanes); + var highLanes = Narrow(ShiftRightLogical64(lanes, _module.Constant64(_ulongType, 32))); + laneCount = _module.AddInstruction( + SpirvOp.Select, + _uintType, + IsNotZero(highLanes), + IAdd(Ext(75, _uintType, highLanes), UInt(33)), + IAdd(Ext(75, _uintType, lowLanes), UInt(1))); } StoreS(3, BitwiseOr(laneCount, ShiftLeftLogical(laneCount, UInt(8)))); @@ -1403,9 +1410,12 @@ private void EmitInitialState() } else { - var localId = Load(_uvec3Type, _localInvocationIdInput); + var halfWaveIndex = UsesHalfWaveSubgroups ? HalfWaveLocalIndex() : 0; + var localId = halfWaveIndex != 0 ? HalfWaveLocalCoordinates(halfWaveIndex) : Load(_uvec3Type, _localInvocationIdInput); var workGroupId = Load(_uvec3Type, _workGroupIdInput); - var invocationInBounds = _module.ConstantBool(true); + var invocationInBounds = halfWaveIndex != 0 && HalfWaveThreadCount % 32 != 0 + ? _module.AddInstruction(SpirvOp.ULessThan, _boolType, halfWaveIndex, UInt(HalfWaveThreadCount)) + : _module.ConstantBool(true); for (uint component = 0; component < 3; component++) { // gl_LocalInvocationId/gl_WorkGroupId are indexed by the physical SPIR-V @@ -10000,6 +10010,10 @@ private uint GuestWaveLane() { return PairedGuestLane(); } + if (_waveLowering is HalfWave64Lowering && _subgroupIdInput != 0) + { + return BitwiseAnd(HalfWaveLocalIndex(), UInt(63)); + } // A native wave64 is one host subgroup: its lane is the subgroup lane, the same one // ballot and shuffle address, whatever order the driver gave the invocations. diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs index bfdf69047..e0f5724ba 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs @@ -409,6 +409,7 @@ public sealed partial class SpirvModuleBuilder { private const uint Magic = 0x07230203; private const uint Version15 = 0x00010500; + private const uint Version16 = 0x00010600; private const uint Generator = 0x53504500; // "SPE" private readonly List<uint> _capabilities = []; @@ -1127,7 +1128,35 @@ public void EndFunction() CurrentFunction = 0; } - public byte[] Build() + // A driver may fuse a multiply with an add, or split a fused multiply-add, and decide differently in each pipeline. + // A depth prepass and the pass that tests its depth for equality run different programs that compute the same + // position, so a vertex that moves by one ulp in only one of them drops the triangle from the second pass. Set for + // the stages before rasterization: each such operation keeps its own rounding, as the guest's instructions do. + public bool KeepsFloatRounding { get; set; } + + private const uint GlslFma = 50; + + private List<uint> WithNoContraction(List<uint> functions, List<uint> annotations) + { + var decorated = new List<uint>(annotations); + var glsl = _extInstImports.GetValueOrDefault("GLSL.std.450"); + for (var offset = 0; offset < functions.Count; offset += Math.Max(1, (int)(functions[offset] >> 16))) + { + var opcode = (SpirvOp)(functions[offset] & 0xFFFF); + if ((opcode is SpirvOp.FAdd or SpirvOp.FSub or SpirvOp.FMul || + opcode == SpirvOp.ExtInst && glsl != 0 && functions[offset + 3] == glsl && functions[offset + 4] == GlslFma) && + !_plainDecorations.Contains((functions[offset + 2], SpirvDecoration.NoContraction))) + { + Emit(decorated, SpirvOp.Decorate, functions[offset + 2], (uint)SpirvDecoration.NoContraction); + } + } + + return decorated; + } + + public byte[] Build() => Build(spirv16: false); + + internal byte[] Build(bool spirv16) { if (_memoryModel.Count == 0) { @@ -1139,6 +1168,11 @@ public byte[] Build() var functions = CompactFunctions(removedIds, unreadPointers); var debug = WithoutTargets(_debug, removedIds); var annotations = WithoutTargets(_annotations, removedIds); + if (KeepsFloatRounding) + { + annotations = WithNoContraction(functions, annotations); + } + var entryPoints = WithoutInterfaces(_entryPoints, unreadVariables); var globals = WithoutVariables(_typesConstantsGlobals, unreadVariables); var wordCount = @@ -1156,7 +1190,7 @@ public byte[] Build() var words = new uint[wordCount]; var offset = 0; WriteWord(Magic); - WriteWord(Version15); + WriteWord(spirv16 ? Version16 : Version15); WriteWord(Generator); WriteWord(_nextId); WriteWord(0); diff --git a/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs b/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs index ab49d8546..fcd281289 100644 --- a/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs +++ b/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs @@ -636,6 +636,8 @@ private static bool UsesSampler(string opcode) => var opcode = instruction.Opcode; switch (opcode) { + case "SBarrier": + return "a barrier"; case "VReadlaneB32": return "V_READLANE"; case "VWritelaneB32": diff --git a/tests/SharpEmu.Libs.Tests/Audio/AjmExportsTests.cs b/tests/SharpEmu.Libs.Tests/Audio/AjmExportsTests.cs index 615e13de1..41b620b58 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/AjmExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/AjmExportsTests.cs @@ -257,6 +257,127 @@ public void BatchJobRunSplit_GathersDescriptorsAndWritesFlaggedSideband() Assert.Equal(80ul, ReadUInt64(BatchInfoAddress + 8)); } + /// <summary> + /// With asynchronous batches a job runs after sceAjmBatchStart, on the AJM thread, and sceAjmBatchWait collects it, as with + /// the decoder hardware. The job's buffer descriptors are read when it is added, so a title that reuses that memory before + /// the batch starts still gets the buffers it named. + /// </summary> + [Fact] + public void AnAsyncBatchRunsAfterStartWithTheDescriptorsItWasGiven() + { + const ulong inputDescriptors = MemoryBase + 0x600; + const ulong outputDescriptors = MemoryBase + 0x640; + const ulong inputData = MemoryBase + 0x700; + const ulong outputData = MemoryBase + 0x800; + const ulong sideband = MemoryBase + 0x900; + const ulong errorAddress = MemoryBase + 0x980; + const ulong batchOut = MemoryBase + 0x9C0; + const ulong streamSideband = 1ul << 47; + const ulong multipleFrames = 1ul << 12; + + AjmExports.AsyncBatches = true; + var contextId = Initialize(); + Assert.Equal(0, RegisterCodec(contextId, 2)); + Assert.Equal(0, CreateInstance(contextId, 2, 0x2_0000_0002, InstanceAddress)); + var instanceId = ReadUInt32(InstanceAddress); + InitializeBatch(BatchBufferAddress, 0x200, BatchInfoAddress); + + WriteUInt64(inputDescriptors, inputData); + WriteUInt64(inputDescriptors + 8, 0x20); + WriteUInt64(inputDescriptors + 16, inputData + 0x20); + WriteUInt64(inputDescriptors + 24, 0x10); + WriteUInt64(outputDescriptors, outputData); + WriteUInt64(outputDescriptors + 8, 0x40); + Span<byte> dirty = stackalloc byte[0x40]; + dirty.Fill(0xAB); + Assert.True(_memory.TryWrite(outputData, dirty)); + Assert.True(_memory.TryWrite(sideband, dirty[..0x20])); + + _ctx[CpuRegister.Rdi] = BatchInfoAddress; + _ctx[CpuRegister.Rsi] = instanceId; + _ctx[CpuRegister.Rdx] = streamSideband | multipleFrames; + _ctx[CpuRegister.Rcx] = inputDescriptors; + _ctx[CpuRegister.R8] = 2; + _ctx[CpuRegister.R9] = outputDescriptors; + WriteStackArgs(outputCount: 1, sidebandAddress: sideband, sidebandSize: 0x20); + Assert.Equal(0, AjmExports.AjmBatchJobRunSplit(_ctx)); + + // Nothing ran yet, and the job size is accounted for as before. + Assert.All(ReadBytes(outputData, 0x40), value => Assert.Equal(0xAB, value)); + Assert.Equal(80ul, ReadUInt64(BatchInfoAddress + 8)); + + // The title reuses the descriptor memory before starting the batch. + WriteUInt64(inputDescriptors, 0); + WriteUInt64(inputDescriptors + 8, 0); + WriteUInt64(outputDescriptors, MemoryBase + 0xF00); + WriteUInt64(outputDescriptors + 8, 0x10); + + _ctx[CpuRegister.Rdi] = contextId; + _ctx[CpuRegister.Rsi] = BatchInfoAddress; + _ctx[CpuRegister.Rdx] = 0; + _ctx[CpuRegister.Rcx] = errorAddress; + _ctx[CpuRegister.R8] = batchOut; + Assert.Equal(0, AjmExports.AjmBatchStart(_ctx)); + + _ctx[CpuRegister.Rdi] = contextId; + _ctx[CpuRegister.Rsi] = ReadUInt32(batchOut); + _ctx[CpuRegister.Rdx] = uint.MaxValue; + _ctx[CpuRegister.Rcx] = errorAddress; + Assert.Equal(0, AjmExports.AjmBatchWait(_ctx)); + + Assert.All(ReadBytes(outputData, 0x40), value => Assert.Equal(0, value)); + var result = ReadBytes(sideband, 0x20); + Assert.Equal(0, BinaryPrimitives.ReadInt32LittleEndian(result)); + Assert.Equal(0x30, BinaryPrimitives.ReadInt32LittleEndian(result.AsSpan(8))); + Assert.Equal(1u, BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(24))); + } + + /// <summary>Jobs of an asynchronous batch run in the order they were added, and a second wait on it succeeds.</summary> + [Fact] + public void AnAsyncBatchRunsItsJobsInOrder() + { + const ulong first = MemoryBase + 0x600; + const ulong second = MemoryBase + 0x700; + const ulong errorAddress = MemoryBase + 0x980; + const ulong batchOut = MemoryBase + 0x9C0; + + AjmExports.AsyncBatches = true; + var contextId = Initialize(); + InitializeBatch(BatchBufferAddress, 0x200, BatchInfoAddress); + Span<byte> sentinel = stackalloc byte[48]; + sentinel.Fill(0xCC); + Assert.True(_memory.TryWrite(first, sentinel)); + Assert.True(_memory.TryWrite(second, sentinel)); + + foreach (var address in new[] { first, second }) + { + _ctx[CpuRegister.Rdi] = BatchInfoAddress; + _ctx[CpuRegister.Rsi] = address; + Assert.Equal(0, AjmExports.AjmBatchJobGetStatistics(_ctx)); + } + + Assert.All(ReadBytes(first, 48), value => Assert.Equal(0xCC, value)); + + _ctx[CpuRegister.Rdi] = contextId; + _ctx[CpuRegister.Rsi] = BatchInfoAddress; + _ctx[CpuRegister.Rdx] = 0; + _ctx[CpuRegister.Rcx] = errorAddress; + _ctx[CpuRegister.R8] = batchOut; + Assert.Equal(0, AjmExports.AjmBatchStart(_ctx)); + + for (var wait = 0; wait < 2; wait++) + { + _ctx[CpuRegister.Rdi] = contextId; + _ctx[CpuRegister.Rsi] = ReadUInt32(batchOut); + _ctx[CpuRegister.Rdx] = uint.MaxValue; + _ctx[CpuRegister.Rcx] = errorAddress; + Assert.Equal(0, AjmExports.AjmBatchWait(_ctx)); + } + + Assert.All(ReadBytes(first, 48), value => Assert.Equal(0, value)); + Assert.All(ReadBytes(second, 48), value => Assert.Equal(0, value)); + } + [Fact] public void BatchJobSetGaplessDecode_UsesFifthArgumentForResult() { diff --git a/tests/SharpEmu.Libs.Tests/Audio/Atrac9GaplessTests.cs b/tests/SharpEmu.Libs.Tests/Audio/Atrac9GaplessTests.cs index 2004c99db..df500b838 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/Atrac9GaplessTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/Atrac9GaplessTests.cs @@ -32,6 +32,121 @@ private static Atrac9DecodeResult DecodeSuperframes(Atrac9DecodeState decoder, i return decoder.Decode(input, output, Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); } + // A RIFF/WAVE header as an .at9 file has it: a WAVE_FORMAT_EXTENSIBLE format chunk with the ATRAC9 subformat and codec + // configuration, a fact chunk (sample count, lead-in) and the data chunk header; the superframes follow. + private static byte[] RiffPass(uint totalSamples, uint skipSamples, int superframes, byte[]? config = null, int superframeBytes = SuperframeBytes) + { + byte[] subFormat = [0xD2, 0x42, 0xE1, 0x47, 0xBA, 0x36, 0x8D, 0x4D, 0x88, 0xFC, 0x61, 0x65, 0x4F, 0x8C, 0x83, 0x6C]; + const int Header = 12 + 8 + 52 + 8 + 12 + 8; + var pass = new byte[Header + superframeBytes * superframes]; + var span = pass.AsSpan(); + "RIFF"u8.CopyTo(span); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span[4..], (uint)pass.Length - 8); + "WAVE"u8.CopyTo(span[8..]); + "fmt "u8.CopyTo(span[12..]); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span[16..], 52); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(span[20..], 0xFFFE); + subFormat.CopyTo(span[(20 + 24)..]); + (config ?? MonoConfig).CopyTo(span[(20 + 44)..]); + "fact"u8.CopyTo(span[72..]); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span[76..], 12); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span[80..], totalSamples); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span[84..], skipSamples); + "data"u8.CopyTo(span[92..]); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(span[96..], (uint)(superframeBytes * superframes)); + for (var superframe = 0; superframe < superframes; superframe++) + { + SilentFrame.CopyTo(pass, Header + superframe * superframeBytes); + } + + return pass; + } + + [Fact] + public void AHeaderWithAnotherCodecConfigurationSwitchesTheDecoderToIt() + { + var decoder = CreateDecoder(); + byte[] smallFrames = [0xFE, 0x70, 0x0B, 0xE0]; + var pass = RiffPass(totalSamples: 0, skipSamples: 0, superframes: 2, smallFrames, superframeBytes: 96); + + var result = decoder.Decode(pass, new byte[SuperframeSamples * 4], Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); + + Assert.Equal(96, decoder.Config!.SuperframeBytes); + Assert.Equal((pass.Length, SuperframeSamples * 2 * sizeof(short)), (result.InputConsumed, result.OutputWritten)); + } + + [Fact] + public void AStreamBackAtItsHeaderRestartsTheWindowItsLastPassUsedUp() + { + var decoder = CreateDecoder(); + var pass = RiffPass(totalSamples: 300, skipSamples: 100, superframes: 2); + + var first = decoder.Decode(pass, new byte[SuperframeSamples * 4], Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); + Assert.Equal((pass.Length, 300 * sizeof(short), 300ul), (first.InputConsumed, first.OutputWritten, first.TotalDecodedSamples)); + + var spent = DecodeSuperframes(decoder, 1, SuperframeSamples); + Assert.Equal((0, 0), (spent.InputConsumed, spent.OutputWritten)); + + var again = decoder.Decode(pass, new byte[SuperframeSamples * 4], Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); + Assert.Equal((pass.Length, 300 * sizeof(short), 300ul), (again.InputConsumed, again.OutputWritten, again.TotalDecodedSamples)); + } + + [Fact] + public void AnAjmDecoderPlaysASuperframeItCannotDecodeAsSilenceAndGoesOn() + { + var decoder = new Atrac9DecodeState { ConcealsUndecodableSuperframes = true }; + Assert.True(decoder.TryInitialize(MonoConfig)); + var input = new byte[SuperframeBytes * 2]; + Array.Fill(input, (byte)0xFF, 0, SuperframeBytes); + SilentFrame.CopyTo(input, SuperframeBytes); + var output = new byte[SuperframeSamples * 2 * sizeof(short)]; + Array.Fill(output, (byte)0x55); + + var result = decoder.Decode(input, output, Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); + + Assert.Equal(0, result.Status & (Atrac9DecodeState.ResultCodecError | Atrac9DecodeState.ResultInvalidData)); + Assert.Equal((SuperframeBytes * 2, output.Length), (result.InputConsumed, result.OutputWritten)); + Assert.All(output.AsSpan(0, SuperframeSamples * sizeof(short)).ToArray(), sample => Assert.Equal(0, sample)); + } + + [Fact] + public void ADecoderThatDoesNotConcealReportsASuperframeItCannotDecode() + { + var decoder = CreateDecoder(); + var input = new byte[SuperframeBytes]; + Array.Fill(input, (byte)0xFF); + + var result = decoder.Decode(input, new byte[SuperframeSamples * sizeof(short)], Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); + + Assert.Equal( + Atrac9DecodeState.ResultCodecError | Atrac9DecodeState.ResultInvalidData, + result.Status & (Atrac9DecodeState.ResultCodecError | Atrac9DecodeState.ResultInvalidData)); + } + + [Fact] + public void ASuperframeWithoutRoomStaysInTheInput() + { + var decoder = CreateDecoder(); + + var first = DecodeSuperframes(decoder, 2, SuperframeSamples); + Assert.Equal((SuperframeBytes, SuperframeSamples * sizeof(short)), (first.InputConsumed, first.OutputWritten)); + Assert.NotEqual(0, first.Status & Atrac9DecodeState.ResultNotEnoughRoom); + + var second = DecodeSuperframes(decoder, 1, SuperframeSamples); + Assert.Equal((SuperframeBytes, SuperframeSamples * sizeof(short)), (second.InputConsumed, second.OutputWritten)); + Assert.Equal((ulong)(SuperframeSamples * 2), second.TotalDecodedSamples); + } + + [Fact] + public void AJobWithoutInputReportsPartialInput() + { + var decoder = CreateDecoder(); + + var result = decoder.Decode(ReadOnlySpan<byte>.Empty, new byte[SuperframeSamples * 2], Atrac9PcmEncoding.Signed16, requestedChannels: 0, multipleFrames: true); + + Assert.Equal((Atrac9DecodeState.ResultPartialInput, 0, 0), (result.Status, result.InputConsumed, result.OutputWritten)); + } + [Fact] public void WithoutAWindowEverySuperframeSampleIsWritten() { @@ -110,4 +225,33 @@ public void ResetRestoresTheWindowAndASetWithoutResetKeepsProgress() decoder.SetGapless(totalSamples: 2000, skipSamples: 10, reset: true); Assert.Equal(new Atrac9Gapless(2000, 10, 0), decoder.Gapless); } + + [Fact] + public void ANewWindowAfterInitializingForTheNextSoundTakesEffectWithoutAReset() + { + // The next sound on a voice: the instance is initialized again, then its window is sent without a reset. + var decoder = CreateDecoder(); + decoder.SetGapless(totalSamples: 300, skipSamples: 100, reset: false); + DecodeSuperframes(decoder, 2, 2 * SuperframeSamples); + Assert.Equal(new Atrac9Gapless(0, 0, 212), decoder.Gapless); + + Assert.True(decoder.TryInitialize(MonoConfig)); + decoder.SetGapless(totalSamples: 1000, skipSamples: 50, reset: false); + Assert.Equal(new Atrac9Gapless(1000, 50, 0), decoder.Gapless); + + var result = DecodeSuperframes(decoder, 1, SuperframeSamples); + Assert.Equal((SuperframeSamples - 50) * sizeof(short), result.OutputWritten); + Assert.Equal((ulong)(SuperframeSamples - 50), result.TotalDecodedSamples); + } + + [Fact] + public void ASetWithoutResetMovesTheLimitsAndKeepsTheProgress() + { + var decoder = CreateDecoder(); + decoder.SetGapless(totalSamples: 500, skipSamples: 100, reset: false); + DecodeSuperframes(decoder, 1, SuperframeSamples); + + decoder.SetGapless(totalSamples: 1000, skipSamples: 100, reset: false); + Assert.Equal(new Atrac9Gapless(1000 - 156, 0, 100), decoder.Gapless); + } } diff --git a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2MixTests.cs b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2MixTests.cs index a59626c89..d05838778 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2MixTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2MixTests.cs @@ -30,11 +30,13 @@ public void OnlyMainBgmAndVoicePortsReachTheSpeakers(ushort portType, bool expec } [Theory] - [InlineData(64u, HalfPower, HalfPower)] - [InlineData(65u, HalfPower, -HalfPower)] - [InlineData(0u, 1f, 1f)] - [InlineData(2u, HalfPower, -HalfPower)] - public void FirstOrderAmbisonicsDecodeToStereoCardioids(uint ambisonics, float left, float right) + [InlineData(64u, 0.85355339f, 0.85355339f)] + [InlineData(65u, 0.52100538f, -0.52100538f)] + [InlineData(67u, 0.14644661f, 0.14644661f)] + [InlineData(0u, 1.20710678f, 1.20710678f)] + [InlineData(2u, 0.52100538f, -0.52100538f)] + [InlineData(1u, 0.14644661f, 0.14644661f)] + public void FirstOrderAmbisonicsDecodeToTwoVirtualMicrophones(uint ambisonics, float left, float right) { Assert.True(AudioOut2Exports.TryGetStereoGains(ObjectMain, 1, 0.5f, ambisonics, 0, out var leftGain, out var rightGain)); Assert.Equal(left * 0.5f, leftGain, 5); @@ -43,10 +45,10 @@ public void FirstOrderAmbisonicsDecodeToStereoCardioids(uint ambisonics, float l [Theory] [InlineData(66u)] - [InlineData(67u)] + [InlineData(68u)] [InlineData(99u)] - [InlineData(1u)] [InlineData(3u)] + [InlineData(4u)] [InlineData(15u)] public void HigherAmbisonicComponentsDoNotFeedStereo(uint ambisonics) { @@ -67,16 +69,58 @@ public void PlainObjectsPlayCentredOrPassThroughToOneSide() } [Fact] - public void FifthOrderSceneDecodesASourceToItsSide() + public void FifthOrderSceneKeepsASourceAheadAtFullLevelAndOneAtTheSideOnItsSide() { const int frames = 4; - var leftSource = DecodeScene(frames, azimuthSine: 1f); - var centreSource = DecodeScene(frames, azimuthSine: 0f); + var ahead = DecodeScene(frames, azimuthSine: 0f, azimuthCosine: 1f); + var left = DecodeScene(frames, azimuthSine: 1f, azimuthCosine: 0f); + var behind = DecodeScene(frames, azimuthSine: 0f, azimuthCosine: -1f); + + Assert.Equal((1f, 1f), (MathF.Round(ahead[0], 4), MathF.Round(ahead[1], 4))); + Assert.Equal(1.3746f, left[0], 4); + Assert.Equal(0.3325f, left[1], 4); + Assert.Equal(2f, (left[0] * left[0]) + (left[1] * left[1]), 4); + Assert.Equal(HalfPower, behind[0], 4); + Assert.Equal(HalfPower, behind[1], 4); + } - Assert.Equal(2f * HalfPower, leftSource[0], 4); - Assert.Equal(0f, leftSource[1], 4); - Assert.Equal(HalfPower, centreSource[0], 4); - Assert.Equal(HalfPower, centreSource[1], 4); + [Fact] + public void ControllerMixPutsTheSpeakerPairInFrontAndTheActuatorsBehind() + { + var mix = new float[2 * 4]; + var mono = new byte[2 * sizeof(float)]; + BinaryPrimitives.WriteSingleLittleEndian(mono, 0.5f); + BinaryPrimitives.WriteSingleLittleEndian(mono.AsSpan(4), -0.25f); + var stereo = new byte[2 * 2 * sizeof(short)]; + BinaryPrimitives.WriteInt16LittleEndian(stereo, 8192); + BinaryPrimitives.WriteInt16LittleEndian(stereo.AsSpan(2), -16384); + BinaryPrimitives.WriteInt16LittleEndian(stereo.AsSpan(4), 16384); + BinaryPrimitives.WriteInt16LittleEndian(stereo.AsSpan(6), 0); + + AudioOut2Exports.MixPortIntoController(mono, mix, 2, 1, sizeof(float), true, 1f, firstChannel: 0); + AudioOut2Exports.MixPortIntoController(stereo, mix, 2, 2, sizeof(short), false, 0.5f, firstChannel: 2); + + Assert.Equal([0.5f, 0.5f, 0.125f, -0.25f, -0.25f, -0.25f, 0.25f, 0f], mix); + } + + [Fact] + public void FloatOutputKeepsPeaksAboveFullScaleAndSixteenBitOutputClipsThem() + { + float[] mix = [1.5f, -0.25f, -9f, 0.5f]; + var output = new byte[mix.Length * sizeof(float)]; + + var floats = AudioOut2Exports.WriteFloatOutput(mix, output, out var floatPeak); + Assert.Equal(mix.Length * sizeof(float), floats.Length); + Assert.Equal(1.5f, BinaryPrimitives.ReadSingleLittleEndian(floats)); + Assert.Equal(-0.25f, BinaryPrimitives.ReadSingleLittleEndian(floats[4..])); + Assert.Equal(-4f, BinaryPrimitives.ReadSingleLittleEndian(floats[8..])); + Assert.Equal(4f, floatPeak); + + var shorts = AudioOut2Exports.WritePcm16Output(mix, output, out var shortPeak); + Assert.Equal(mix.Length * sizeof(short), shorts.Length); + Assert.Equal(short.MaxValue, BinaryPrimitives.ReadInt16LittleEndian(shorts)); + Assert.Equal(short.MinValue, BinaryPrimitives.ReadInt16LittleEndian(shorts[4..])); + Assert.Equal(1f, shortPeak); } [Fact] @@ -115,7 +159,9 @@ public void SetAttributesStoresGainAmbisonicsAndPassthrough() AudioOut2Exports.AudioOut2PortDestroy(ctx); } - private static float[] DecodeScene(int frames, float azimuthSine) + // A horizontal source in an SN3D scene: W = 1, Y = sin(azimuth), Z = 0, X = cos(azimuth); the higher orders carry + // values the stereo decode must ignore. + private static float[] DecodeScene(int frames, float azimuthSine, float azimuthCosine) { var mix = new float[frames * 2]; var source = new byte[frames * sizeof(float)]; @@ -125,6 +171,8 @@ private static float[] DecodeScene(int frames, float azimuthSine) { 0 => 1f, 1 => azimuthSine, + 2 => 0f, + 3 => azimuthCosine, _ => 0.6f, }; for (var frame = 0; frame < frames; frame++) diff --git a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PacingTests.cs b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PacingTests.cs index 7c003cf39..3f03208ad 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PacingTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PacingTests.cs @@ -34,6 +34,32 @@ public void AProducerSleepBetweenGrainsIsHalvedOnlyWhileTheDeviceRunsShort( Assert.Equal(expected, AudioOut2Exports.ShortenedProducerSleep(microseconds, 256, 48000, queuedMilliseconds)); } + [Theory] + [InlineData(51ul, 3.0, 20, true)] + [InlineData(51ul, 3.0, 34, true)] + [InlineData(51ul, 3.0, 35, false)] + [InlineData(51ul, 3.0, -1, false)] + [InlineData(51ul, 19.9, 0, true)] + [InlineData(51ul, 20.0, 0, false)] + [InlineData(51ul, -1.0, 0, false)] + [InlineData(1000ul, 3.0, 0, true)] + [InlineData(1001ul, 3.0, 0, false)] + [InlineData(5000ul, 3.0, 0, false)] + public void AShortNapIsPreciseOnlyForARecentProducerWhileTheDeviceRunsShort( + ulong microseconds, double millisecondsSincePush, int queuedMilliseconds, bool expected) + { + Assert.Equal(expected, AudioOut2Exports.PreciseProducerNap(microseconds, millisecondsSincePush, queuedMilliseconds, 256, 48000)); + } + + [Fact] + public void APreciseSpinTakesAboutTheTimeAsked() + { + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + SharpEmu.Libs.HostHighResolutionSleep.SpinMicroseconds(200); + var elapsed = System.Diagnostics.Stopwatch.GetElapsedTime(started); + Assert.InRange(elapsed.TotalMicroseconds, 200, 100_000); + } + [Fact] public void TheThresholdStaysFarBelowTheHostQueueCap() { diff --git a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PcmSnapshotTests.cs b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PcmSnapshotTests.cs index 8a79ae773..ea643835d 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PcmSnapshotTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2PcmSnapshotTests.cs @@ -97,6 +97,60 @@ public void ContextPush_DoesNotSubmitObjectOrVibrationPorts(ushort portType) Assert.Null(AudioOut2Exports.GetPortPcmSnapshotForTests(port)); } + [Fact] + public void ContextPush_PlaysPadSpeakerAndVibrationPortsOnTheControllerOnly() + { + var main = new RecordingAudioStream(); + var controller = new RecordingAudioStream(); + AudioOut2Exports.SetStreamFactoryForTests(_ => main); + AudioOut2Exports.SetControllerFactoryForTests(_ => controller); + + var context = CreateContext(grainSamples: 64); + var mainPort = CreateSigned16StereoPort(context, FirstPortOutAddress); + var padSpeaker = CreateSigned16StereoPort(context, SecondPortOutAddress, portType: 3); + var vibration = CreateSigned16StereoPort(context, SecondPortOutAddress + 8, portType: 6); + WritePcmAttribute(); + Assert.True(_memory.TryWrite(SharedPcmAddress, new byte[64 * 2 * sizeof(short)])); + SetPcmAttribute(mainPort); + Assert.True(_memory.TryWrite(SharedPcmAddress, StereoPcm(16384, 16384))); + SetPcmAttribute(padSpeaker); + Assert.True(_memory.TryWrite(SharedPcmAddress, StereoPcm(8192, -24576))); + SetPcmAttribute(vibration); + + _ctx[CpuRegister.Rdi] = context; + _ctx[CpuRegister.Rsi] = 1; + Assert.Equal(0, AudioOut2Exports.AudioOut2ContextPush(_ctx)); + + Assert.All(Assert.Single(main.Submissions), value => Assert.Equal(0, value)); + var pad = Assert.Single(controller.Submissions); + Assert.Equal(64 * 4 * sizeof(float), pad.Length); + for (var frame = 0; frame < 64; frame++) + { + var samples = Enumerable.Range(0, 4) + .Select(channel => BinaryPrimitives.ReadSingleLittleEndian(pad.AsSpan(((frame * 4) + channel) * sizeof(float)))) + .ToArray(); + Assert.Equal([0.5f, 0.5f, 0.25f, -0.75f], samples); + } + } + + [Fact] + public void PortGetState_ReportsTheControllerSpeakerForAPadSpeakerPortItPlays() + { + AudioOut2Exports.SetStreamFactoryForTests(_ => new RecordingAudioStream()); + var context = CreateContext(grainSamples: 64); + var padSpeaker = CreateSigned16StereoPort(context, FirstPortOutAddress, portType: 3); + Assert.Equal(1, ReadPortStateOutput(padSpeaker)); + + AudioOut2Exports.ResetForTests(); + AudioOut2Exports.SetStreamFactoryForTests(_ => new RecordingAudioStream()); + AudioOut2Exports.SetControllerFactoryForTests(_ => new RecordingAudioStream()); + context = CreateContext(grainSamples: 64); + var mainPort = CreateSigned16StereoPort(context, FirstPortOutAddress); + padSpeaker = CreateSigned16StereoPort(context, SecondPortOutAddress, portType: 3); + Assert.Equal(1, ReadPortStateOutput(mainPort)); + Assert.Equal(4, ReadPortStateOutput(padSpeaker)); + } + [Fact] public void ContextPush_SubmitsDevicePortSnapshotOnlyOnce() { @@ -231,6 +285,29 @@ private void SetPcmAttribute(ulong port) Assert.Equal(0, AudioOut2Exports.AudioOut2PortSetAttributes(_ctx)); } + private static byte[] StereoPcm(short left, short right) + { + var pcm = new byte[64 * 2 * sizeof(short)]; + for (var frame = 0; frame < 64; frame++) + { + BinaryPrimitives.WriteInt16LittleEndian(pcm.AsSpan(frame * 4), left); + BinaryPrimitives.WriteInt16LittleEndian(pcm.AsSpan((frame * 4) + 2), right); + } + + return pcm; + } + + private ushort ReadPortStateOutput(ulong port) + { + const ulong stateAddress = MemoryBase + 0x700; + _ctx[CpuRegister.Rdi] = port; + _ctx[CpuRegister.Rsi] = stateAddress; + Assert.Equal(0, AudioOut2Exports.AudioOut2PortGetState(_ctx)); + Span<byte> state = stackalloc byte[2]; + Assert.True(_memory.TryRead(stateAddress, state)); + return BinaryPrimitives.ReadUInt16LittleEndian(state); + } + private ulong ReadUInt64(ulong address) { Span<byte> value = stackalloc byte[8]; diff --git a/tests/SharpEmu.Libs.Tests/Audio/AudioOutExportsTests.cs b/tests/SharpEmu.Libs.Tests/Audio/AudioOutExportsTests.cs index 955f659a3..8e3e1b0b7 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/AudioOutExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/AudioOutExportsTests.cs @@ -223,12 +223,52 @@ public void OutputExportSubmitsThroughTheSharedHostAudioPath(Generation generati Assert.Equal(samples, Assert.Single(Assert.Single(_streams).Submissions)); } + [Theory] + [InlineData(4, 0)] + [InlineData(10, 2)] + public void ControllerPortsPlayOnTheirControllerPairAndNotOnTheSpeakers(int portType, int pair) + { + var controller = new RecordingAudioStream(); + AudioOutExports.SetControllerFactoryForTests(_ => controller); + var handle = OpenPort(bufferLength: 2, portType); + Span<byte> source = stackalloc byte[8]; + BinaryPrimitives.WriteInt16LittleEndian(source, 16384); + BinaryPrimitives.WriteInt16LittleEndian(source[2..], -16384); + BinaryPrimitives.WriteInt16LittleEndian(source[4..], 8192); + BinaryPrimitives.WriteInt16LittleEndian(source[6..], -8192); + Assert.True(_memory.TryWrite(FirstSourceAddress, source)); + + Assert.Equal(0, SubmitSingle(handle, FirstSourceAddress)); + + Assert.Empty(_streams); + var expected = new float[8]; + expected[pair] = 0.5f; + expected[pair + 1] = -0.5f; + expected[4 + pair] = 0.25f; + expected[4 + pair + 1] = -0.25f; + var submitted = Assert.Single(controller.Submissions); + Assert.Equal(expected, System.Runtime.InteropServices.MemoryMarshal.Cast<byte, float>(submitted.AsSpan()).ToArray()); + } + + [Fact] + public void ControllerPortsWithoutAControllerStaySilent() + { + AudioOutExports.SetControllerFactoryForTests(_ => null); + var handle = OpenPort(bufferLength: 2, portType: 10); + Assert.True(handle > 0); + Assert.True(_memory.TryWrite(FirstSourceAddress, new byte[] { 1, 0, 2, 0, 3, 0, 4, 0 })); + + Assert.Equal(0, SubmitSingle(handle, FirstSourceAddress)); + + Assert.Empty(_streams); + } + public void Dispose() => AudioOutExports.ResetForTests(); - private int OpenPort(uint bufferLength) + private int OpenPort(uint bufferLength, int portType = 0) { _ctx[CpuRegister.Rdi] = 1; - _ctx[CpuRegister.Rsi] = 0; + _ctx[CpuRegister.Rsi] = (ulong)portType; _ctx[CpuRegister.Rdx] = 0; _ctx[CpuRegister.Rcx] = bufferLength; _ctx[CpuRegister.R8] = 48000; diff --git a/tests/SharpEmu.Libs.Tests/Cpu/Gen5NativeReturnSmokeTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/Gen5NativeReturnSmokeTests.cs index 5928e10d7..e5a704674 100644 --- a/tests/SharpEmu.Libs.Tests/Cpu/Gen5NativeReturnSmokeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Cpu/Gen5NativeReturnSmokeTests.cs @@ -82,6 +82,36 @@ public async Task ExtractAndBlendPreserveLivePointerThroughNativeExecution() ]); } + [Fact] + public async Task GuestCodeRunsWithTheConsoleFloatingPointControlAndTheHostGetsItsOwnBack() + { + if (!IsSupportedHost) + return; + + if (Environment.GetEnvironmentVariable(WorkerEnvironmentVariable) != "1") + { + var result = await RunIsolatedWorker(nameof(GuestCodeRunsWithTheConsoleFloatingPointControlAndTheHostGetsItsOwnBack)); + Assert.True(result.Completed, result.Output); + Assert.True(result.ExitCode == 0, result.Output); + return; + } + + var instructions = new List<byte> + { + 0x0F, 0xAE, 0x1F, // stmxcsr [rdi] + 0xD9, 0x7F, 0x04, // fnstcw [rdi+4] + 0x48, 0xB8 // mov rax,imm64 + }; + var returnValue = new byte[8]; + BinaryPrimitives.WriteUInt64LittleEndian(returnValue, CallbackReturnValue); + instructions.AddRange(returnValue); + instructions.Add(0xC3); + ExecuteSyntheticGuest(instructions.ToArray(), expectedExtracts: 0, checkFloatingPointControl: true); + } + + private static int _smallestDenormalBits = 1; + private static float _one = 1.0f; + [Fact] public async Task SyntheticGen5Continuation_PreservesFullReturnValue() { @@ -252,7 +282,8 @@ private static async Task CheckRedZoneSentinel(string method, bool extract, bool } private static void ExecuteSyntheticGuest(byte[]? callbackInstructions = null, bool continuation = false, - int expectedExtracts = 1, bool checkRedZone = false, bool checkExtractControls = false) + int expectedExtracts = 1, bool checkRedZone = false, bool checkExtractControls = false, + bool checkFloatingPointControl = false) { using var memory = new PhysicalVirtualMemory(); var image = new SelfLoader().Load(BuildSyntheticElf(callbackInstructions), memory); @@ -345,6 +376,17 @@ private static void ExecuteSyntheticGuest(byte[]? callbackInstructions = null, b } Assert.True(callbackReturn == CallbackReturnValue, $"Guest return value changed: expected 0x{CallbackReturnValue:X16}, actual 0x{callbackReturn:X16}."); + if (checkFloatingPointControl) + { + var control = new byte[8]; + Assert.True(memory.TryRead(dataAddress, control)); + // Flush-to-zero and denormals-are-zero with every exception masked; the status flags may be anything. + Assert.Equal(CpuContext.InitialMxcsr, BinaryPrimitives.ReadUInt32LittleEndian(control) & ~0x3Fu); + Assert.Equal((ushort)0x037F, BinaryPrimitives.ReadUInt16LittleEndian(control.AsSpan(4))); + // The host thread is back in its own environment: a denormal survives a multiply. + var denormal = BitConverter.Int32BitsToSingle(Volatile.Read(ref _smallestDenormalBits)); + Assert.Equal(1, BitConverter.SingleToInt32Bits(denormal * Volatile.Read(ref _one))); + } if (checkRedZone) { var snapshot = new byte[128]; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs index cc746add9..e0da18f5f 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs @@ -268,6 +268,14 @@ public void DispatchDirect(ulong submitId, uint groupsX, uint groupsY, uint grou public bool ResolvesIndirectThreadDispatchOnGpu { get; set; } public bool ResolvesIndirectDrawOnGpu { get; set; } + public List<uint[]>? IndexedRuns { get; set; } + + public bool TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) + { + if (IndexedRuns is null) return false; + IndexedRuns.Add(offsets.ToArray()); + return true; + } public void OnQueueReset(int queueId) => Calls.Add($"queue_reset {queueId}"); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs index 2483d316a..e011db727 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs @@ -258,8 +258,9 @@ public void AWaitMetThroughADeferredLabelTakesNoSoftWait() public void AQueuesOwnReleaseIsNoHint() { var setup = NewQueue(); - Compute(setup, FirstCompute + 1, ComputeB, 2, Instances(5)); + // The other head is admitted after the graphics stream, so the release does not yield to it. Graphics0(setup, 3, Release32(Label, 1), Wait32(3, Label, 1), Draw(7)); + Compute(setup, FirstCompute + 1, ComputeB, 2, Instances(5)); Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); Assert.Equal(1, Draws(setup)); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs index fe23f8d03..faf01c225 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs @@ -327,6 +327,49 @@ public void IndirectDraws_WithZeroInstancesDrawNothing() Assert.Empty(runner.Host.IndexedDraws); } + [Fact] + public void IndexedRunKeepsArgumentOrderAndStopsBeforeAnotherPageOrRegisterWrite() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + runner.Host.IndexedRuns = []; + var address = (Arguments + 4095) & ~4095ul; + runner.Host.WriteWords(address + 0x1000, new uint[] { 3, 1, 0, 0, 0 }); + + runner.Run( + SetBase(address, dispatch: false), + StreamRunner.Packet(PacketOpcode.SetUserConfigRegister, UserConfigRegisterOffset.VgtPrimitiveType, 4), + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 0, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 64, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 32, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 32, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 0xFF0, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 0x1000, ShaderRegisterOffset.SpiShaderUserDataGs0, 0, 2)); + + Assert.Equal(new uint[] { 0, 64, 32, 32 }, Assert.Single(runner.Host.IndexedRuns)); + Assert.Equal(new ulong[] { address + 0xFF0, 0 }, runner.Host.IndexedDraws.Select(draw => draw.IndirectArgumentsAddress)); + Assert.DoesNotContain(runner.Host.GuestReads, read => read >= address && read < address + 0xFF0); + } + + [Fact] + public void RefusedIndexedRunLeavesEachIndirectDrawForTheNormalHandler() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + runner.Run( + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.SetUserConfigRegister, UserConfigRegisterOffset.VgtPrimitiveType, 4), + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 48, 0, 0, 2)); + + Assert.Equal(new ulong[] { Arguments + 16, Arguments + 48 }, runner.Host.IndexedDraws.Select(draw => draw.IndirectArgumentsAddress)); + Assert.Equal(runner.Host.IndexedDraws[0].PacketAddress + 20, runner.Host.IndexedDraws[1].PacketAddress); + } + [Fact] public void UnsizedIndexedIndirectDraws_LearnTheIndexRangeBeforeUsingTheGpu() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/RegisterStampsTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/RegisterStampsTests.cs index abbff2fa1..bd342be9a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/RegisterStampsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/RegisterStampsTests.cs @@ -40,6 +40,26 @@ private static RegisterStamp StampOfContextMember(string member) => : ShaderInterfaceMembers.Contains(member) ? RegisterStamp.ShaderInterface : RegisterStamp.PipelineState; + [Fact] + public void RepeatedUserDataConsumesTheMarkerAndKeepsTheSnapshotUntilTheKindChanges() + { + var banks = NewBanks(); + var packet = Packet(PacketOpcode.SetShaderRegister, 2); + const uint offset = SpiShaderUserDataPs0 + 3; + banks.UserDataMarker = UserScalarKind.Region; + RegisterWriteTable.WriteShaderPacket(banks, packet, offset, [1, 2]); + var snapshot = banks.Snapshot(); + banks.UserDataMarker = UserScalarKind.Region; + Assert.Equal(2u, RegisterWriteTable.WriteShaderPacket(banks, packet, offset, [1, 2])); + Assert.Same(snapshot.Shader.Pixel, banks.Shader.Pixel); + Assert.Equal(UserScalarKind.Unknown, banks.UserDataMarker); + RegisterWriteTable.WriteShaderPacket(banks, packet, offset, [1, 2]); + Assert.NotSame(snapshot.Shader.Pixel, banks.Shader.Pixel); + Assert.NotEqual(snapshot.Stamp(RegisterStamp.PixelUserData), banks.Stamp(RegisterStamp.PixelUserData)); + Assert.Equal(UserScalarKind.Region, snapshot.Shader.Pixel.UserScalars.Kinds[3]); + Assert.Equal(UserScalarKind.Unknown, banks.Shader.Pixel.UserScalars.Kinds[3]); + } + [Fact] public void EachContextRegisterFamilyMovesOnlyItsConsumersStamp() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ReleaseOrderTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ReleaseOrderTests.cs new file mode 100644 index 000000000..6f690f566 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/ReleaseOrderTests.cs @@ -0,0 +1,167 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; + +// A release the CPU can observe lands after the older compute submissions that can still run, a soft wait included, and +// never waits for one that is blocked. +[Collection(CommandStreamQueueStateCollection.Name)] +public sealed class ReleaseOrderTests +{ + private const ulong Label = StreamRunner.LabelAddress; + private const ulong SecondLabel = StreamRunner.LabelAddress + 0x10; + private const ulong Graphics = StreamRunner.CommandAddress; + private const ulong SecondGraphics = StreamRunner.CommandAddress + 0x400; + private const ulong Compute = StreamRunner.DataAddress; + private const uint FirstCompute = 0x20; + + private static uint[] Release32(ulong label, uint value) => + StreamRunner.Packet(PacketOpcode.ReleaseMemory, 0x28u | (5u << 8), 1u << 29, + StreamRunner.Low(label), StreamRunner.High(label), value, 0, 0); + + private static uint[] Wait32(uint function, ulong address, uint reference) => + StreamRunner.Packet(PacketOpcode.WaitRegisterMemory, function | 0x10u, + StreamRunner.Low(address), StreamRunner.High(address), reference, 0xFFFF_FFFFu, 0); + + private static uint[] Instances(uint count) => StreamRunner.Packet(PacketOpcode.NumInstances, count); + + private static (RecordingCommandStreamHost Host, CommandStreamQueue Queue) NewQueue(bool softWaits = false) + { + var host = new RecordingCommandStreamHost(); + var queue = new CommandStreamQueue(host) + { + Landings = softWaits ? new EndOfPipeLandings { CapTicks = long.MaxValue } : null, + }; + return (host, queue); + } + + private static void Enqueue(RecordingCommandStreamHost host, CommandStreamQueue queue, uint? computeQueue, ulong address, + ulong submission, params uint[][] packets) + { + var words = StreamRunner.Concat(packets); + host.WriteWords(address, words); + if (computeQueue is { } compute) + { + queue.EnqueueCompute(compute, address, (uint)words.Length, submission, null); + } + else + { + queue.EnqueueGraphics(address, (uint)words.Length, submission, null); + } + } + + [Fact] + public void GraphicsReleaseLandsAfterAnOlderRunnableComputeSubmission() + { + var (host, queue) = NewQueue(); + Enqueue(host, queue, FirstCompute, Compute, 1, Instances(5)); + Enqueue(host, queue, null, Graphics, 2, Release32(Label, 1)); + + // The round robin reaches the graphics queue first; its release lets the older compute submission run. + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(0u, host.ReadDword(Label)); + + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(5u, queue.GetInterpreter(1).InstanceCount); + Assert.Equal(0u, host.ReadDword(Label)); + + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(1u, host.ReadDword(Label)); + Assert.Equal(SliceResult.NoWork, queue.ProcessOne()); + } + + [Fact] + public void ReleaseLandsWhileAnOlderComputeSubmissionWaitsForIt() + { + var (host, queue) = NewQueue(); + Enqueue(host, queue, FirstCompute, Compute, 1, Wait32(3, Label, 1), Instances(5)); + Enqueue(host, queue, null, Graphics, 2, Release32(Label, 1)); + + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + // The compute wait is unmet and blocks; the release then lands instead of waiting for it. + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(1u, queue.GetInterpreter(1).InstanceCount); + + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(1u, host.ReadDword(Label)); + + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(5u, queue.GetInterpreter(1).InstanceCount); + Assert.Equal(SliceResult.NoWork, queue.ProcessOne()); + } + + [Fact] + public void OlderComputeSubmissionStopsWaitingSoftlyForTheRelease() + { + var (host, queue) = NewQueue(softWaits: true); + Enqueue(host, queue, null, Graphics, 1, Release32(Label, 1)); + Enqueue(host, queue, FirstCompute, Compute, 2, Wait32(3, Label, 1), Instances(5)); + Enqueue(host, queue, null, SecondGraphics, 3, Release32(SecondLabel, 1)); + + // The first release lands; the compute wait it meets is soft while that release has not completed on the GPU and + // the graphics queue can run. + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(1u, host.ReadDword(Label)); + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(1u, queue.GetInterpreter(1).InstanceCount); + + // The second release waits for the older compute submission, which then runs without its soft wait. + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(0u, host.ReadDword(SecondLabel)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(5u, queue.GetInterpreter(1).InstanceCount); + Assert.Equal(0u, host.ReadDword(SecondLabel)); + + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(1u, host.ReadDword(SecondLabel)); + Assert.Equal(SliceResult.NoWork, queue.ProcessOne()); + } + + [Fact] + public void TwoReleasesWaitingForOlderBlockedWorkBothLand() + { + // Round-robin order: release, older blocked work, release, older blocked work. A retry from each waiting release + // used to unblock the work the other one checks next, so neither release ever landed. + var (host, queue) = NewQueue(); + const ulong neverWritten = Label + 0x40; + Enqueue(host, queue, FirstCompute + 1, Compute + 0x100, 1, Wait32(3, neverWritten, 1)); + Enqueue(host, queue, FirstCompute + 3, Compute + 0x200, 2, Wait32(3, neverWritten + 0x10, 1)); + Enqueue(host, queue, FirstCompute, Compute, 3, Release32(Label, 1)); + Enqueue(host, queue, FirstCompute + 2, Compute + 0x300, 4, Release32(SecondLabel, 1)); + + var slices = 0; + while ((host.ReadDword(Label) == 0 || host.ReadDword(SecondLabel) == 0) && slices < 24) + { + queue.ProcessOne(); + slices++; + } + + Assert.Equal((1u, 1u), (host.ReadDword(Label), host.ReadDword(SecondLabel))); + Assert.True(slices < 24, $"the releases took {slices} slices"); + + // The last completion retries the two waits once each; then the queue rests instead of spinning. + var settle = 0; + while (queue.ProcessOne() != SliceResult.AllBlocked && settle < 4) + { + settle++; + } + + Assert.True(settle < 4, $"the queue did not settle after {settle} slices"); + } + + [Fact] + public void ReleaseWithoutOlderComputeWorkLandsAtOnce() + { + var (host, queue) = NewQueue(); + Enqueue(host, queue, null, Graphics, 1, Release32(Label, 1)); + Enqueue(host, queue, FirstCompute, Compute, 2, Instances(5)); + + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(1u, host.ReadDword(Label)); + Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + Assert.Equal(SliceResult.NoWork, queue.ProcessOne()); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs index 4b8f7580d..20e3da6f2 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.BlockAlias.cs @@ -173,4 +173,80 @@ public void FindImage_ACompressedImageSurvivesABlockAliasRoundTrip() Assert.True(harness.Image(sampledId).Description.IsBlock); Assert.True(harness.Image(sampledId).IsGpuModified); } + + // 64x64 BC1 with its 32x32 level first, as tiled chains place the smaller levels: level 0 starts after it. Linear rows are + // 256 bytes (32 blocks, 16 used): level 0 takes 16 of them, level 1 8. + private const ulong PaddedLevelBytes = 0x1000; + private const ulong PaddedMipBytes = 0x800; + + private static ImageRequest MippedCompressedTexture(ulong address) + { + var request = LinearRequest(address, PaddedMipBytes + PaddedLevelBytes, Format.BC1RgbaSrgbBlock, GuestPixelFormat.Bc1Srgb, + GuestImageType.Color2D, new Extent3D(64, 64, 1), 1, 8, 1); + request.Description.Resources = new SubresourceCount(2, 1); + request.Description.MipLayout[0] = new MipLevelLayout { Offset = PaddedMipBytes, Size = PaddedLevelBytes, Pitch = 64, Height = 64 }; + request.Description.MipLayout[1] = new MipLevelLayout { Offset = 0, Size = PaddedMipBytes, Pitch = 32, Height = 32 }; + request.View = request.View with { LevelCount = 2 }; + return request; + } + + // The memory of a texture the guest gave up now holds a one-level image whose texels are as large as the texture's blocks + // (a 16x16 R32G32 state where a 64x64 BC1 chain was). Its bytes start where the chain's smaller level was, not where the + // chain's level 0 is, so the texture is no view of it: the image is its own, made from guest memory. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FindImage_AnImageOfTheOtherBlockClassWithItsLevelsElsewhereIsItsOwn(bool aged) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x20000, ReadWrite); + var texture = MippedCompressedTexture(address); + var textureId = harness.Acquire(ref texture); + harness.MarkGpuWritten(textureId); + if (aged) + { + AgeBeyondTheRemovalWindow(harness, textureId); + } + + var state = Enumerable.Range(0, (int)BlockImageBytes).Select(index => (byte)(index * 13 + 5)).ToArray(); + Assert.True(harness.WriteFault(address)); + harness.Write(address, state); + var image = LinearRequest(address, BlockImageBytes, Format.R32G32Uint, GuestPixelFormat.Bits32_32UInt, GuestImageType.Color2D, + new Extent3D(16, 16, 1), 1, 8, 1); + var imageId = harness.Acquire(ref image); + + Assert.NotEqual(textureId, imageId); + Assert.False(harness.Image(imageId).Description.IsBlock); + Assert.Equal(state, harness.ReadImageBytes(harness.Image(imageId))); + var owners = harness.Images.FindImagesInRangeForTest(address, BlockImageBytes, pageOverlap: false); + Assert.Contains(imageId, owners); + Assert.Equal(!aged, owners.Contains(textureId)); + harness.Shutdown(); + } + + // The other way: a compressed chain requested where a one-level image of its block size lies. The chain's level 0 holds the + // guest bytes after its smaller level, not the image's texels. + [Fact] + public void FindImage_ACompressedChainOverAnImageWithItsLevelsElsewhereIsMadeFromGuestMemory() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x20000, ReadWrite); + var image = LinearRequest(address, BlockImageBytes, Format.R32G32Uint, GuestPixelFormat.Bits32_32UInt, GuestImageType.Color2D, + new Extent3D(16, 16, 1), 1, 8, 1); + var imageId = harness.Acquire(ref image); + + var blocks = Enumerable.Range(0, (int)(PaddedMipBytes + PaddedLevelBytes)).Select(index => (byte)(index * 7 + 3)).ToArray(); + Assert.True(harness.WriteFault(address)); + harness.Write(address, blocks); + var texture = MippedCompressedTexture(address); + var textureId = harness.Acquire(ref texture); + + Assert.NotEqual(imageId, textureId); + Assert.True(harness.Image(textureId).Description.IsBlock); + var rows = Enumerable.Range(0, 16).SelectMany(row => blocks.Skip((int)PaddedMipBytes + row * 256).Take(16 * 8)).ToArray(); + Assert.Equal(rows, harness.ReadImageBytes(harness.Image(textureId))[..(int)BlockImageBytes]); + harness.Shutdown(); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SampledDepthClear.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SampledDepthClear.cs new file mode 100644 index 000000000..f8cb77203 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.SampledDepthClear.cs @@ -0,0 +1,76 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using Silk.NET.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +// A depth surface the guest clears through its HTile and then samples before binding it as a depth target again. +public sealed partial class GuestImageCacheTests +{ + private static ImageRequest HtileDepth(ulong address, ulong metadataAddress, uint layers) + { + var depth = AsDepthTarget(LinearRequest(address, 16 * 4 * layers, Format.D32Sfloat, GuestPixelFormat.Bits32Float, + GuestImageType.Color2D, new Extent3D(4, 4, 1), layers, 4, 1), Format.D32Sfloat); + depth.Description.Metadata.Kind = MetadataKind.Htile; + depth.Description.Metadata.Range = new GuestSpan(metadataAddress, 0x100); + return depth; + } + + private static ImageRequest SampledDepth(ImageRequest depth) + { + depth.Role = ImageRole.Texture; + depth.Description.Metadata = default; + depth.View = depth.View with { Usage = ImageUsageFlags.SampledBit }; + return depth; + } + + [Fact] + public void SampledDepth_TakesThePendingHtileClearWithTheValueOfItsLastBind() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x20000, ReadWrite); + var metadataAddress = address + 0x10000; + var depth = HtileDepth(address, metadataAddress, 1); + var depthId = harness.Acquire(ref depth); + harness.Images.NoteDepthClearValue(metadataAddress, 0.25f); + Assert.True(harness.Images.ClearMetadata(metadataAddress)); + + var sampled = SampledDepth(depth); + Assert.Equal(depthId, harness.Find(ref sampled)); + // The render thread records the clear: a recording worker leaves such a sample to it. + Assert.False(harness.Images.TryPrepareTextureViewForSlice(depthId, sampled, out _)); + Assert.Equal(depthId, harness.Acquire(ref sampled)); + + Assert.False(harness.Images.IsMetadataCleared(metadataAddress, 0)); + Assert.True(harness.Images.TryPrepareTextureViewForSlice(depthId, sampled, out _)); + Assert.Equal(Bytes(Enumerable.Repeat(0.25f, 16).ToArray()), harness.ReadImageBytes(harness.Image(depthId), ImageAspectFlags.DepthBit)); + harness.Shutdown(); + } + + // A layered surface's clear bits are not exact per slice: its pending clear stays for its next depth-target bind. + [Fact] + public void SampledDepth_LeavesALayeredSurfacesPendingClearToItsNextBind() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x20000, ReadWrite); + var metadataAddress = address + 0x10000; + var depth = HtileDepth(address, metadataAddress, 2); + var depthId = harness.Acquire(ref depth); + harness.Images.NoteDepthClearValue(metadataAddress, 0.25f); + Assert.True(harness.Images.ClearMetadata(metadataAddress)); + + var sampled = SampledDepth(depth); + Assert.Equal(depthId, harness.Acquire(ref sampled)); + + Assert.True(harness.Images.IsMetadataCleared(metadataAddress, 0)); + harness.Shutdown(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs index 503632f91..5ebeb7bbe 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.GnmMode.Shaders; using SharpEmu.HLE; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.Libs.Gpu.Rendering; @@ -288,6 +289,41 @@ public void ARecordedVertexProgramTranslatesToTheSameSpirvAfterReload() Assert.Equal(runtime, Assert.IsType<FakeCompiledShader>(compiled).Spirv); } + [Fact] + public void GcnVertexPrewarmReplaysTheRecordedFetchShader() + { + var frontend = new GcnShaderFrontend(); + var guest = new PipelineTestGuest(Compile); + const ulong fetchAddress = CodeAddress - 0x100; + guest.RegisterProgram(CodeAddress, HeaderAddress, [0xBE802100, 0xBF810000]); + guest.RegisterProgram(fetchAddress, HeaderAddress - 0x100, [0x7E0802F2, 0xBE802000]); + uint[] userData = [unchecked((uint)fetchAddress), (uint)(fetchAddress >> 32)]; + var registered = new RegisteredShader(CodeAddress, 0, 8, 0, 0, 0, 0, fetchAddress, 8) + { + Frontend = frontend, + FrontendUserData = userData, + }; + var context = new CpuContext(guest.Memory, Generation.Gen4); + using (var list = Open()) + { + guest.Host.ShaderPrewarm = list; + var programs = new ShaderProgramCache(context, guest.Compiler, guest.Host); + var cursor = 0u; + programs.GetOrCompile(new ShaderSource(registered, 0x1234, userData, 0, ShaderStage.Vertex), + new StageCompileOptions { VertexInfo = new VertexInputInfo() }, ref cursor, out _); + var (_, identity) = Assert.Single(guest.Host.RecordedVertexPrograms); + list.RecordPreRasterization(identity, new PreRasterizationState(0, 0, 0, false, false, true, false)); + } + + using var reloaded = Open(); + var part = Assert.IsType<PreRasterizationPrewarmItem>(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(registered.CodeSizeBytes, part.Code.FrontendEntryCodeSize); + var compiler = new FakeShaderCompiler(Compile); + Assert.True(ShaderProgramCache.TryCompileVertexPrewarm(part.Program, part.Code, compiler, guest.Host, + out var compiled, out _, out _, out var error, domain => domain == frontend.CacheDomain ? frontend : null), error); + Assert.Equal(Assert.Single(guest.Compiler.Shaders).Spirv, Assert.IsType<FakeCompiledShader>(compiled).Spirv); + } + // A vertex program compiled after pixel stages that end at different push cursors is one translation, whose push // data takes the top of the range above every one of them; after a pixel stage its data does not fit beside, it // reads the shader data block. The program reads a V# from user data, so it has shader data to place. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RepeatDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RepeatDrawTests.cs new file mode 100644 index 000000000..fce980c13 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RepeatDrawTests.cs @@ -0,0 +1,293 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; + +namespace SharpEmu.Libs.Tests.Gpu.Rendering; + +// A draw whose registers repeat the previous draw's takes that draw's record with only its own arguments; the result must be +// the record a full resolve of the same draw makes. +[Collection(SchedulingStateCollection.Name)] +public sealed class RepeatDrawTests : IDisposable +{ + private sealed class CapturingSink : IResolvedCommandSink + { + private long _sequence; + + public List<ResolvedDraw> Draws { get; } = []; + + public long NextSequence() => ++_sequence; + + public void Record(ResolvedDraw record) => Draws.Add(record); + + public void Record(ResolvedDispatch record) => throw new InvalidOperationException("no dispatches here"); + } + + private const ulong IndirectArguments = RecordingRenderHost.MemoryBase + 0x60_0000; + + private readonly RecordingRenderHost _host = new(); + private readonly FakePipelineProvider _pipelines = new(); + private readonly CapturingSink _sink = new(); + private readonly PendingGpuWrites _pending = new(); + private readonly RecordPool _pool = new(); + private readonly RenderExecutor _executor; + private readonly FatalScope _fatal = new(); + + public RepeatDrawTests() => _executor = new RenderExecutor(_host, _pipelines, _sink, _pending, _pool); + + public void Dispose() => _fatal.Dispose(); + + private static DrawIndexedArguments IndirectIndexed(uint count, uint indexType = 0, int baseVertex = 0, ulong indexOffset = 0, ulong argumentsOffset = 0) => + Indexed(count, indexType: indexType, baseVertex: baseVertex, source: DrawOffsetSource.IndirectArguments, indexAddress: IndexBase + indexOffset) with + { + IndirectArgumentsAddress = IndirectArguments + argumentsOffset, + }; + + // An unbounded index buffer is too large for the GPU to read the arguments against it, so the CPU reads them. + private static DrawIndexedArguments CpuArguments(ulong argumentsOffset) => + IndirectIndexed(0x7FFF_FFFF, argumentsOffset: argumentsOffset) with { UnboundedIndexBuffer = true }; + + private ResolvedDraw Template(RegisterBanks banks, in DrawIndexedArguments arguments) + { + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _executor.DrawIndexed(7, banks, arguments); + var template = Assert.Single(_sink.Draws); + Assert.Equal(ResolvedDrawKind.Draw, template.Kind); + Assert.True(template.RepeatableArguments); + return template; + } + + private void WriteArguments(ulong address, params uint[] words) + { + var bytes = new byte[words.Length * 4]; + for (var index = 0; index < words.Length; index++) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(index * 4), words[index]); + } + + _host.WriteGuest(address, bytes); + } + + // The repeat, then a full resolve of the same draw. + private (ResolvedDraw Repeat, ResolvedDraw Full) RepeatAndResolve(ResolvedDraw template, RegisterBanks banks, in DrawIndexedArguments arguments) + { + Assert.True(_executor.TryRepeatIndexed(template, 8, banks, arguments)); + var repeat = _sink.Draws[^1]; + _executor.DrawIndexed(8, banks, arguments); + var full = _sink.Draws[^1]; + Assert.NotSame(repeat, full); + Assert.Equal(full.Sequence - 1, repeat.Sequence); + return (repeat, full); + } + + [Fact] + public void ARepeatRecordsWhatAFullResolveOfItsArgumentsRecords() + { + var banks = Banks().Snapshot(); + var template = Template(banks, IndirectIndexed(40)); + + var (repeat, full) = RepeatAndResolve(template, banks, IndirectIndexed(24, baseVertex: 5, indexOffset: 0x40, argumentsOffset: 0x20)); + + Assert.Null(FirstDifference(repeat, full)); + Assert.Equal(IndexBase + 0x40, repeat.Index.Address); + Assert.Equal(48ul, repeat.Index.Size); + Assert.Equal(IndirectArguments + 0x20, repeat.Emission.IndirectArgumentsAddress); + Assert.Equal(8ul, repeat.SubmitId); + } + + [Fact] + public void ARepeatMarksItsTargetAtItsOwnSequence() + { + var banks = Banks().Snapshot(); + var template = Template(banks, IndirectIndexed(40)); + _pending.Release(template.Sequence); + Assert.False(_pending.TryGetPending(ColorBase, 4, out _)); + + Assert.True(_executor.TryRepeatIndexed(template, 8, banks, IndirectIndexed(24, argumentsOffset: 0x20))); + + Assert.True(_pending.TryGetPending(ColorBase, 4, out var sequence)); + Assert.Equal(_sink.Draws[^1].Sequence, sequence); + } + + [Fact] + public void ARepeatOfACpuArgumentsDrawReadsItsOwnArguments() + { + var banks = Banks().Snapshot(); + WriteArguments(IndirectArguments, 12, 1, 0, 0, 0); + WriteArguments(IndirectArguments + 0x20, 9, 2, 3, 4, 0); + var template = Template(banks, CpuArguments(0)); + Assert.True(template.RepeatsCpuArguments); + + var (repeat, full) = RepeatAndResolve(template, banks, CpuArguments(0x20)); + + Assert.Null(FirstDifference(repeat, full)); + Assert.Equal(9u, repeat.Draw.Count); + Assert.Equal(IndexBase + 6, repeat.Index.Address); + Assert.Equal(0ul, repeat.Emission.IndirectArgumentsAddress); + } + + [Fact] + public void ARepeatWhoseArgumentsDrawNothingIsASkippedRecord() + { + var banks = Banks().Snapshot(); + WriteArguments(IndirectArguments, 12, 1, 0, 0, 0); + WriteArguments(IndirectArguments + 0x20, 0, 1, 0, 0, 0); + var template = Template(banks, CpuArguments(0)); + + var (repeat, full) = RepeatAndResolve(template, banks, CpuArguments(0x20)); + + Assert.Equal(ResolvedDrawKind.Skipped, full.Kind); + Assert.Null(FirstDifference(repeat, full)); + } + + [Fact] + public void ARepeatOnTheOtherArgumentsPathResolvesInFull() + { + var banks = Banks().Snapshot(); + WriteArguments(IndirectArguments, 12, 1, 0, 0, 0); + var template = Template(banks, CpuArguments(0)); + + Assert.False(_executor.TryRepeatIndexed(template, 8, banks, IndirectIndexed(24, argumentsOffset: 0x20))); + Assert.Single(_sink.Draws); + } + + [Fact] + public void ARepeatWithAnotherIndexTypeResolvesInFull() + { + var banks = Banks().Snapshot(); + var template = Template(banks, IndirectIndexed(40, indexType: 0)); + + Assert.False(_executor.TryRepeatIndexed(template, 8, banks, IndirectIndexed(24, indexType: 1))); + Assert.Single(_sink.Draws); + } + + [Fact] + public void ARepeatWithoutCountsResolvesInFull() + { + var banks = Banks().Snapshot(); + var template = Template(banks, IndirectIndexed(40)); + + Assert.False(_executor.TryRepeatIndexed(template, 8, banks, IndirectIndexed(0))); + Assert.Single(_sink.Draws); + } + + [Fact] + public void APacketDrawIsNotRepeatable() + { + _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); + _executor.DrawIndexed(7, Banks(), Indexed(40)); + var record = Assert.Single(_sink.Draws); + + Assert.False(record.RepeatableArguments); + Assert.False(_executor.TryRepeatIndexed(record, 8, Banks(), IndirectIndexed(24))); + Assert.Single(_sink.Draws); + } + + [Fact] + public void ARecordCopyEqualsItsSource() + { + var banks = Banks().Snapshot(); + var template = Template(banks, IndirectIndexed(40)); + var copy = _pool.RentDraw(); + + copy.CopyFrom(template); + + Assert.Equal(template.Sequence, copy.Sequence); + Assert.Null(FirstDifference(copy, template)); + copy.Index = copy.Index with { Size = copy.Index.Size + 4 }; + Assert.Equal("index", FirstDifference(copy, template)); + } + + [Fact] + public void AReadLogCopyKeepsEveryRead() + { + var source = new ResolveReadLog { Version = 3, Publications = 4 }; + source.Add(0x1000, 0xAABBCCDDu); + source.Add(0x1004, 0x11223344u); + source.Add(0x2000, [1, 2, 3], clean: true); + for (var index = 0; index < 100; index++) + { + source.Add(0x10_0000 + ((ulong)index * 0x100), new byte[32]); + } + + var copy = new ResolveReadLog(); + copy.Add(0x9000, 7u); + + copy.CopyFrom(source); + + Assert.Equal(source.Count, copy.Count); + for (var index = 0; index < source.Count; index++) + { + var expected = source.Bytes(index, out var address).ToArray(); + Assert.Equal(expected, copy.Bytes(index, out var copied).ToArray()); + Assert.Equal(address, copied); + Assert.Equal(source.IsClean(index), copy.IsClean(index)); + } + + Assert.Equal(3, copy.Version); + Assert.Equal(4, copy.Publications); + copy.Add(0x3000, 9u); + Assert.Equal(source.Count + 1, copy.Count); + } + + // The first field in which two draw records differ (the sequence aside), or null. + private static string? FirstDifference(ResolvedDraw a, ResolvedDraw b) + { + if (a.Kind != b.Kind) return "kind"; + if (a.Announce != b.Announce) return "announce"; + if (a.Debug != b.Debug) return "debug"; + if (a.ResetBindings != b.ResetBindings) return "reset_bindings"; + if (a.TargetsResolved != b.TargetsResolved) return "targets_resolved"; + if (a.SubmitId != b.SubmitId) return "submit"; + if (a.Draw != b.Draw) return "draw"; + if (a.Topology != b.Topology) return "topology"; + if (a.PrimitiveRestart != b.PrimitiveRestart) return "primitive_restart"; + if (a.PrimitiveType != b.PrimitiveType) return "primitive_type"; + if (a.Emission != b.Emission) return "emission"; + if (a.Index != b.Index) return "index"; + if (a.TessellationIndexAddress != b.TessellationIndexAddress || a.TessellationIndexSize != b.TessellationIndexSize || + a.TessellationVertexOffset != b.TessellationVertexOffset) return "tessellation"; + if (!ReferenceEquals(a.Context, b.Context)) return "context"; + if (a.ContextStamp != b.ContextStamp) return "context_stamp"; + if (a.DynamicStamp != b.DynamicStamp) return "dynamic_stamp"; + if (a.TargetVersion != b.TargetVersion) return "target_version"; + if (a.Dynamic != b.Dynamic) return "dynamic"; + if (a.WritesMemory != b.WritesMemory) return "writes_memory"; + if (a.WriteStages != b.WriteStages) return "write_stages"; + if (a.SetBindDebug != b.SetBindDebug || a.SetAutoDebug != b.SetAutoDebug) return "debug_flags"; + if (!ReferenceEquals(a.IndexedTrace, b.IndexedTrace)) return "indexed_trace"; + if (a.PacketAddress != b.PacketAddress) return "packet"; + if (a.RepeatableArguments != b.RepeatableArguments || a.RepeatsCpuArguments != b.RepeatsCpuArguments) return "repeatable"; + ref var stateA = ref a.State; + ref var stateB = ref b.State; + if (!ReferenceEquals(stateA.Programs, stateB.Programs)) return "programs"; + if (stateA.ColorCount != stateB.ColorCount) return "color_count"; + for (var index = 0; index < (int)stateA.ColorCount; index++) + { + if (!SameValue(stateA.Colors[index], stateB.Colors[index])) return "color_target"; + } + + if (!SameValue(stateA.Depth, stateB.Depth)) return "depth"; + if (stateA.DepthResolved != stateB.DepthResolved) return "depth_resolved"; + if (stateA.PixelActive != stateB.PixelActive) return "pixel_active"; + if (!stateA.Rendering.Equals(stateB.Rendering)) return "rendering"; + if (stateA.StartInstanceUserData != stateB.StartInstanceUserData || stateA.BaseVertexUserData != stateB.BaseVertexUserData) + { + return "draw_user_data"; + } + + return null; + } + + // Raw bytes, references included: default equality throws on the inline arrays these states hold. + private static bool SameValue<T>(T a, T b) where T : struct => + MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<T, byte>(ref a), Unsafe.SizeOf<T>()) + .SequenceEqual(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<T, byte>(ref b), Unsafe.SizeOf<T>())); +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs index 6b3e13e6c..1c8f31df3 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs @@ -590,6 +590,7 @@ public void RenderProfile_SequentialPhasesRestoreTheParentAfterAnException() [InlineData("shutdown")] [InlineData("wait")] [InlineData("flush")] + [InlineData("slice")] public void EverySubmissionRoutePublishesAndRetiresTheExactBatch(string route) { // Use the presenter bookkeeping without creating a window or Vulkan resources. @@ -635,6 +636,11 @@ public void EverySubmissionRoutePublishesAndRetiresTheExactBatch(string route) case "shutdown": scheduler.Shutdown(); break; case "wait": scheduler.Wait(scheduler.CurrentTick); break; case "flush": Invoke(presenter, "FlushBatchedGuestCommands"); break; + case "slice": + ((ICommandStreamHost)presenter).FlushSlice(); + Assert.Empty(device.Submits); + scheduler.Wait(1); + break; } Assert.Equal(1UL, Assert.Single(device.Submits).Tick); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HalfConversionDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HalfConversionDeviceTests.cs index 327f9cc88..0014451ea 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HalfConversionDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HalfConversionDeviceTests.cs @@ -81,6 +81,32 @@ public void AConversionInPlaceLeavesTheHighHalfForTheNextRead() Assert.Equal("x 48A00005, y 00091234", $"x {actual[0]:X8}, y {actual[1]:X8}"); } + // V_CVT_PKRTZ_F16_F32 rounds toward zero, so a finite value beyond the half range packs to 65504 (0x7BFF) with its sign and + // never to infinity; infinity and NaN pass through. An infinity in packed lighting data never decays: a lighting pass that + // feeds back into itself spreads it frame after frame. + [Fact] + public void ARoundTowardZeroPackSaturatesOnlyFiniteOverflow() + { + var actual = Run(3, + MoveVector(0, 40, BitConverter.SingleToUInt32Bits(70000f)), + MoveVector(0, 41, BitConverter.SingleToUInt32Bits(-1e30f)), + Vop2(0, "VCvtPkrtzF16F32", 44, Gen5Operand.Vector(40), Gen5Operand.Vector(41)), + Store(44, 0), + MoveVector(0, 42, 0x7F800000), + MoveVector(0, 43, BitConverter.SingleToUInt32Bits(65519f)), + Vop2(0, "VCvtPkrtzF16F32", 45, Gen5Operand.Vector(42), Gen5Operand.Vector(43)), + Store(45, 1), + MoveVector(0, 46, 0x7FC00000), + MoveVector(0, 47, BitConverter.SingleToUInt32Bits(-2.5f)), + Vop2(0, "VCvtPkrtzF16F32", 48, Gen5Operand.Vector(46), Gen5Operand.Vector(47)), + Store(48, 2)); + if (actual is null) return; + var nan = actual[2] & 0xFFFF; + Assert.Equal( + "FBFF7BFF 7BFF7C00 C100 nan True", + $"{actual[0]:X8} {actual[1]:X8} {actual[2] >> 16:X4} nan {(nan & 0x7C00) == 0x7C00 && (nan & 0x3FF) != 0}"); + } + private uint[]? Run(int results, params Gen5ShaderInstruction[] body) { var vulkan = fixture.Vulkan; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs index 5451ea7a3..1866b77f6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs @@ -52,7 +52,7 @@ protected uint CompareTo(string opcode, uint destination, Gen5Operand left, Gen5 // fixedThreadsX and fixedThreadsY put a thread count that can end inside the group in the module. With // dispatchLimits the thread count comes with each dispatch instead, and the pipeline runs once per entry. protected uint[] Run(uint localDataShareDwords = 0, uint sizeX = 8, uint sizeY = 8, bool? laneLocal = null, - uint? fixedThreadsX = null, uint? fixedThreadsY = null, (uint X, uint Y)[]? dispatchLimits = null) + uint? fixedThreadsX = null, uint? fixedThreadsY = null, (uint X, uint Y)[]? dispatchLimits = null, bool needsHalfWaveSubgroups = false) { var threads = sizeX * sizeY; Add(Vop2(0, "VLshlrevB32", 5, Operand(2), Gen5Operand.Vector(2))); @@ -76,7 +76,16 @@ protected uint[] Run(uint localDataShareDwords = 0, uint sizeX = 8, uint sizeY = { var halfWavesEnabled = Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL") != "0"; var paired = Gen5SpirvTranslator.PairsWave64Lanes(Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_PAIRED"), threads); - Assert.Equal((oneLanePerInvocation && halfWavesEnabled) || !paired ? sizeX : (threads + 63) / 64 * 32, LocalSizeX(shader.Spirv)); + var fullSubgroups = BinaryPrimitives.ReadUInt32LittleEndian(shader.Spirv.AsSpan(sizeof(uint))) == 0x00010600; + if (needsHalfWaveSubgroups) + { + Assert.Equal(halfWavesEnabled, fullSubgroups); + } + + var expectedSize = fullSubgroups && sizeX % 32 != 0 ? (32u, (threads + 31) / 32, 1u) + : (oneLanePerInvocation && halfWavesEnabled) || !paired ? (sizeX, sizeY, 1u) + : ((threads + 63) / 64 * 32, 1u, 1u); + Assert.Equal(expectedSize, LocalSize(shader.Spirv)); } Assert.NotNull(fixture.Vulkan); @@ -147,7 +156,7 @@ public void InitialExecContainsEveryLane() Assert.All(Run(), x => Assert.Equal(uint.MaxValue, x)); } - private static uint LocalSizeX(byte[] spirv) + private static (uint X, uint Y, uint Z) LocalSize(byte[] spirv) { const uint ExecutionMode = 16; const uint LocalSize = 17; @@ -158,7 +167,9 @@ private static uint LocalSizeX(byte[] spirv) if ((word & 0xFFFF) == ExecutionMode && BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset + 2 * sizeof(uint))) == LocalSize) { - return BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset + 3 * sizeof(uint))); + return (BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset + 3 * sizeof(uint))), + BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset + 4 * sizeof(uint))), + BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset + 5 * sizeof(uint)))); } offset += Math.Max(count, 1) * sizeof(uint); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64Subgroup32DeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64Subgroup32DeviceTests.cs index e6f90960f..676e391e1 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64Subgroup32DeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64Subgroup32DeviceTests.cs @@ -128,7 +128,7 @@ public void APartialLastWave_SelectsOnlyItsThreads() Add(Vop3(0, "VCndmaskB32", 4, Operand(0), Operand(2000), Gen5Operand.Scalar(10))); Add(Vop2(0, "VAddU32", 4, Gen5Operand.Vector(2), Gen5Operand.Vector(4))); - var lanes = Run(sizeX: 16, sizeY: 5, laneLocal: true); + var lanes = Run(sizeX: 16, sizeY: 5, laneLocal: true, needsHalfWaveSubgroups: true); for (uint index = 0; index < 80; index++) { Assert.Equal(index >= 40 ? 2000 + index : index, lanes[index]); diff --git a/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs index c903cf3cc..8faa2c8b4 100644 --- a/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs @@ -187,6 +187,50 @@ public void MappingChangesLetPendingGpuReadsFinish(string operation) } } + // A guest munmap of a piece of a larger direct mapping maps the rest of its view again. The pages on both sides of the + // hole keep the protection the GPU memory gave them, so a CPU store to a page the GPU owns still faults. + [NativePageProtectionFact] + public void PartialMunmapKeepsTheGpuWatchesOfTheRestOfTheMapping() + { + using var test = new BackedKernelMemory(); + var address = SharpEmu.Libs.Tests.Memory.HostViews.HostViewTestSupport.ProbeGuestAddress(test.Host, 0x30000); + using var memory = new GuestGpuMemory(test.Memory); + GuestGpuMemoryHook.Attach(memory); + var below = address + 0xF000; + var above = address + 0x20000; + var watching = false; + try + { + test.Allocate(0, 0x30000); + Assert.Equal(address, test.Map(0, 0x30000, address)); + Assert.True(memory.Covers(address, 0x30000)); + memory.Pages.AddWatch(below, 0x1000, blockReads: false); + memory.Pages.AddWatch(above, 0x1000, blockReads: true); + watching = true; + ExpectAccess("before the munmap"); + Assert.Equal(0, test.Unmap(address + 0x10000, 0x10000)); + Assert.False(memory.Covers(address + 0x10000, 0x10000)); + ExpectAccess("after the munmap"); + } + finally + { + if (watching) + { + memory.Pages.RemoveWatch(below, 0x1000, blockReads: false); + memory.Pages.RemoveWatch(above, 0x1000, blockReads: true); + } + + GuestGpuMemoryHook.Attach(null); + } + + void ExpectAccess(string step) + { + SharpEmu.Libs.Tests.Memory.NativePageProtection.Expect(HostMemory.PAGE_READONLY, below, $"write-watched page below the hole {step}"); + SharpEmu.Libs.Tests.Memory.NativePageProtection.Expect(HostMemory.PAGE_NOACCESS, above, $"read-watched page above the hole {step}"); + SharpEmu.Libs.Tests.Memory.NativePageProtection.Expect(HostMemory.PAGE_READWRITE, address, $"unwatched page {step}"); + } + } + [Fact] public void SparseImageReadCopiesResidentRangesAndClearsReservedGaps() { diff --git a/tests/SharpEmu.Libs.Tests/Loader/GnmAjmGaplessLoopTests.cs b/tests/SharpEmu.Libs.Tests/Loader/GnmAjmGaplessLoopTests.cs new file mode 100644 index 000000000..286451e72 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Loader/GnmAjmGaplessLoopTests.cs @@ -0,0 +1,160 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.GnmMode.Libraries.Ajm; +using SharpEmu.HLE; +using SharpEmu.Libs.Audio; +using SharpEmu.Libs.Tests.Audio; +using Xunit; + +namespace SharpEmu.Libs.Tests.Loader; + +[Collection(AjmStateCollection.Name)] +public sealed class GnmAjmGaplessLoopTests +{ + private const ulong Base = 0x1_0000_0000; + private const ulong ControlReset = 1UL << 13; + private const ulong ControlInitialize = 1UL << 14; + private const ulong Stream = AjmExports.AjmJobSidebandFlagStream | AjmExports.AjmJobRunFlagMultipleFrames; + private const ulong Config = Base + 0x1000; + private const ulong Window = Base + 0x1010; + private const ulong Superframe = Base + 0x1100; + private const ulong Output = Base + 0x2000; + private const ulong Sideband = Base + 0x400; + + [Fact] + public void AGaplessLoopInstanceStartsItsWindowAgainOnceTheLastSampleIsOut() + { + var (context, contextId, instance) = Create(); + try + { + var next = Prepare(context, Base + 0x600, instance); + next = Run(context, next, instance, Stream, Superframe, 192, 32); + Start(context, contextId, Base + 0x600, next); + Assert.Equal(0u, Read32(context, Sideband)); + Assert.Equal(192u, Read32(context, Sideband + 8)); + Assert.Equal(504u, Read32(context, Sideband + 12)); + + next = Run(context, Base + 0x700, instance, Stream, Superframe, 192, 32); + Start(context, contextId, Base + 0x700, next); + Assert.Equal(0u, Read32(context, Sideband)); + Assert.Equal(192u, Read32(context, Sideband + 8)); + Assert.Equal(504u, Read32(context, Sideband + 12)); + } + finally + { + Destroy(context, contextId, instance); + } + } + + [Fact] + public void ARunWithoutInputReportsNoPartialInput() + { + var (context, contextId, instance) = Create(); + try + { + var next = Prepare(context, Base + 0x600, instance); + next = Run(context, next, instance, AjmExports.AjmJobRunFlagGetCodecInfo, 0, 0, 24); + Start(context, contextId, Base + 0x600, next); + Assert.Equal(0u, Read32(context, Sideband)); + Assert.Equal(192u, Read32(context, Sideband + 8)); + + next = Run(context, Base + 0x700, instance, Stream, 0, 0, 32); + Start(context, contextId, Base + 0x700, next); + Assert.Equal(0u, Read32(context, Sideband)); + Assert.Equal(0u, Read32(context, Sideband + 12)); + } + finally + { + Destroy(context, contextId, instance); + } + } + + private static (CpuContext Context, uint ContextId, uint Instance) Create() + { + AjmExports.ResetForTests(); + var context = new CpuContext(new FakeCpuMemory(Base, 0x10000), Generation.Gen4); + context[CpuRegister.Rsp] = Base + 0x800; + context[CpuRegister.Rsi] = Base; + Assert.Equal(0, AjmExports.AjmInitialize(context)); + var contextId = Read32(context, Base); + context[CpuRegister.Rdi] = contextId; + context[CpuRegister.Rsi] = 1; + Assert.Equal(0, AjmExports.AjmModuleRegister(context)); + context[CpuRegister.Rdi] = contextId; + context[CpuRegister.Rsi] = 1; + context[CpuRegister.Rdx] = 0x409; + context[CpuRegister.Rcx] = Base + 4; + Assert.Equal(0, GnmAjmExports.InstanceCreate(context)); + Assert.True(context.Memory.TryWrite(Config, new byte[] { 0xFE, 0x70, 0x17, 0xE0, 0, 0, 0, 0 })); + Assert.True(context.TryWriteUInt32(Window, 252)); + Assert.True(context.TryWriteUInt32(Window + 4, 4)); + var superframe = new byte[192]; + new byte[] { 0x00, 0x84, 0x00, 0x40 }.CopyTo(superframe, 0); + Assert.True(context.Memory.TryWrite(Superframe, superframe)); + return (context, contextId, Read32(context, Base + 4)); + } + + private static ulong Prepare(CpuContext context, ulong address, uint instance) + { + var next = Control(context, address, instance, ControlReset | ControlInitialize, Config, Base + 0x480); + return Control(context, next, instance, ControlReset | AjmExports.AjmJobSidebandFlagGaplessDecode, Window, Base + 0x488); + } + + private static void Destroy(CpuContext context, uint contextId, uint instance) + { + context[CpuRegister.Rdi] = contextId; + context[CpuRegister.Rsi] = instance; + GnmAjmExports.InstanceDestroy(context); + AjmExports.ResetForTests(); + } + + private static ulong Control(CpuContext context, ulong address, uint instance, ulong flags, ulong input, ulong output) + { + context[CpuRegister.Rdi] = address; + context[CpuRegister.Rsi] = instance; + context[CpuRegister.Rdx] = flags; + context[CpuRegister.Rcx] = input; + context[CpuRegister.R8] = 8; + context[CpuRegister.R9] = output; + Assert.True(context.TryWriteUInt64(Base + 0x808, 8)); + Assert.True(context.TryWriteUInt64(Base + 0x810, 0)); + Assert.Equal(0, GnmAjmExports.BatchJobControlBufferRa(context)); + return context[CpuRegister.Rax]; + } + + private static ulong Run(CpuContext context, ulong address, uint instance, ulong flags, ulong input, ulong inputSize, + ulong sidebandSize) + { + Assert.True(context.Memory.TryWrite(Sideband, new byte[32])); + context[CpuRegister.Rdi] = address; + context[CpuRegister.Rsi] = instance; + context[CpuRegister.Rdx] = flags; + context[CpuRegister.Rcx] = input; + context[CpuRegister.R8] = inputSize; + context[CpuRegister.R9] = inputSize == 0 ? 0 : Output; + Assert.True(context.TryWriteUInt64(Base + 0x808, inputSize == 0 ? 0 : 1024UL)); + Assert.True(context.TryWriteUInt64(Base + 0x810, Sideband)); + Assert.True(context.TryWriteUInt64(Base + 0x818, sidebandSize)); + Assert.True(context.TryWriteUInt64(Base + 0x820, 0)); + Assert.Equal(0, GnmAjmExports.BatchJobRunBufferRa(context)); + return context[CpuRegister.Rax]; + } + + private static void Start(CpuContext context, uint contextId, ulong address, ulong end) + { + context[CpuRegister.Rdi] = contextId; + context[CpuRegister.Rsi] = address; + context[CpuRegister.Rdx] = end - address; + context[CpuRegister.Rcx] = 40; + context[CpuRegister.R8] = 0; + context[CpuRegister.R9] = Base + 8; + Assert.Equal(0, GnmAjmExports.BatchStartBuffer(context)); + } + + private static uint Read32(CpuContext context, ulong address) + { + Assert.True(context.TryReadUInt32(address, out var value)); + return value; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs index 1e3ad7fd6..66704f37e 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs @@ -8,6 +8,25 @@ namespace SharpEmu.Libs.Tests.Memory.GpuMemory; public sealed class AvlSpanSetTests { + [Fact] + public void ReadersSeeThePublishedTreeUntilTheWholeEditIsPublished() + { + var set = new AvlSpanSet(); + set.Add(100, 24); + set.PublishChanges(); + set.Remove(102, 16); + for (ulong address = 200; address < 600; address += 10) set.Add(address, 4); + Assert.True(set.PublishedOverlaps(104, 1)); + Assert.False(set.PublishedOverlaps(220, 1)); + set.PublishChanges(); + Assert.False(set.PublishedOverlaps(104, 1)); + Assert.True(set.PublishedOverlaps(220, 1)); + set.Clear(); + Assert.True(set.PublishedOverlaps(220, 1)); + set.PublishChanges(); + Assert.False(set.PublishedOverlaps(220, 1)); + } + // A snapshot built from the last one's spans outside the changed extent holds exactly the set's spans, after single and // batched changes, merges, splits and clears. [Theory] diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/FailingHostViews.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/FailingHostViews.cs index 16923dc2f..89d06e69e 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/FailingHostViews.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/FailingHostViews.cs @@ -117,6 +117,8 @@ public bool ChangeAccess(ulong address, ulong size, HostPageProtection protectio return !ShouldFail(Op.ChangeAccess) && _inner.ChangeAccess(address, size, protection); } + public IReadOnlyList<HostPageAccess> QueryAccess(ulong address, ulong size) => _inner.QueryAccess(address, size); + public bool FreeOwnedRange(ulong address, ulong size) => !ShouldFail(Op.FreeOwnedRange) && _inner.FreeOwnedRange(address, size); diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs index 726e7cf1a..451b51104 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs @@ -602,6 +602,50 @@ public void PartialUnmapPreservesTheRemainingRegions() Assert.True(memory.TryRead(address, new byte[3 * Segment])); } + // Unmapping part of a backed view, through GuestSpaceOwner, maps the rest of the view again. Its pages must keep the + // protection the GPU memory derived for them (the guest's own protection and the watches): a CPU store to a page the GPU + // owns has to fault, or the store goes unseen and a later download or landing writes GPU bytes over it. + [NativePageProtectionFact] + public void PartialUnmapKeepsTheGpuProtectionOfTheRestOfTheView() + { + if (!Supported) return; + const GuestPageProtection readWrite = GuestPageProtection.Read | GuestPageProtection.Write; + var host = HostViewMemory.Create(); + using var memory = new PhysicalVirtualMemory(viewHost: host, backingBytes: BackingSize); + var view = Hold(memory, host); + Assert.True(memory.TryMapBacked(view, 3 * Segment, 0, readWrite, out _)); + using var gpu = new GuestGpuMemory(memory); + gpu.Register(view, 3 * Segment, readWrite); + GuestGpuMemoryHook.Attach(gpu); + var writeWatched = view + 0x1000; + var guestReadOnly = view + 2 * Segment; + var readWatched = view + 2 * Segment + 0x2000; + gpu.Pages.AddWatch(writeWatched, 0x1000, blockReads: false); + gpu.Pages.AddWatch(readWatched, 0x1000, blockReads: true); + try + { + Assert.True(gpu.NoteProtected(guestReadOnly, 0x1000, GuestPageProtection.Read)); + ExpectAccess("before the unmap"); + Assert.True(memory.TryUnmapBacked(view + Segment, Segment)); + ExpectAccess("after the unmap"); + } + finally + { + gpu.Pages.RemoveWatch(writeWatched, 0x1000, blockReads: false); + gpu.Pages.RemoveWatch(readWatched, 0x1000, blockReads: true); + GuestGpuMemoryHook.Attach(null); + } + + void ExpectAccess(string step) + { + NativePageProtection.Expect(HostMemory.PAGE_READONLY, writeWatched, $"write-watched page {step}"); + NativePageProtection.Expect(HostMemory.PAGE_READONLY, guestReadOnly, $"guest read-only page {step}"); + NativePageProtection.Expect(HostMemory.PAGE_NOACCESS, readWatched, $"read-watched page {step}"); + NativePageProtection.Expect(HostMemory.PAGE_READWRITE, view, $"left page {step}"); + NativePageProtection.Expect(HostMemory.PAGE_READWRITE, view + 3 * Segment - 0x1000, $"right page {step}"); + } + } + [Fact] public void SearchSkipsOccupiedMemoryWithoutChangingIt() { diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingViewsTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingViewsTests.cs index b113bf153..ec4e71b18 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingViewsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SharedBackingViewsTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.HLE; using SharpEmu.HLE.GuestMemory; using SharpEmu.HLE.Host; using Xunit; @@ -292,6 +293,60 @@ public unsafe void PartialUnmap_SplitsTheRecordAndTransfersNeverCopyAcrossTheGap Assert.True(host.FreeHole(baseAddress, hole)); } + // A partial unmap maps the rest of the view again. Every page of it keeps the access it had, as the GPU memory page + // watches set it: no access while the GPU data is newer, read-only while CPU writes must be seen. A page that comes + // back read-write takes guest stores without a fault. Case 0 leaves a right part, 1 a part on each side of the hole, + // 2 a left part. + [NativePageProtectionTheory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void PartialUnmap_KeepsThePageAccessOfTheRestOfTheView(int unmapped) + { + if (!Supported) + { + return; + } + + var host = HostViewMemory.Create(); + using var store = new SharedBackingViews(host, BackingSize); + var hole = HoleSize(host); + var baseAddress = ReserveFreeHole(host, hole); + Assert.True(host.SplitHole(baseAddress, 3 * Segment)); + Assert.True(store.TryMapReservedRange(baseAddress, 3 * Segment, 0, HostPageProtection.ReadWrite, out _)); + // In each segment: page 0 read-write, page 1 no access (a read watch), page 2 read-only (a write watch), the rest + // read-write. + for (var segment = 0UL; segment < 3; segment++) + { + Assert.True(host.ChangeAccess(baseAddress + segment * Segment + 0x1000, 0x1000, HostPageProtection.NoAccess)); + Assert.True(host.ChangeAccess(baseAddress + segment * Segment + 0x2000, 0x1000, HostPageProtection.ReadOnly)); + } + + var gone = baseAddress + (ulong)unmapped * Segment; + Assert.True(store.Unmap(gone, Segment, out var preserved)); + Assert.True(preserved); + + for (var segment = 0UL; segment < 3; segment++) + { + var start = baseAddress + segment * Segment; + if (start == gone) + { + continue; + } + + var step = $"segment {segment} after unmapping segment {unmapped}"; + NativePageProtection.Expect(HostMemory.PAGE_READWRITE, start, step); + NativePageProtection.Expect(HostMemory.PAGE_NOACCESS, start + 0x1000, step); + NativePageProtection.Expect(HostMemory.PAGE_READONLY, start + 0x2000, step); + NativePageProtection.Expect(HostMemory.PAGE_READWRITE, start + Segment - 0x1000, step); + } + + Assert.True(store.TryMapReservedRange(gone, Segment, (ulong)unmapped * Segment, HostPageProtection.ReadWrite, out _)); + Assert.True(store.Unmap(baseAddress, 3 * Segment, out _)); + Assert.True(host.JoinHoles(baseAddress, hole)); + Assert.True(host.FreeHole(baseAddress, hole)); + } + [Fact] public void Rejections_MakeNoHostCall() { diff --git a/tests/SharpEmu.Libs.Tests/Memory/NativePageProtection.cs b/tests/SharpEmu.Libs.Tests/Memory/NativePageProtection.cs index 3c4324d63..7e6e3e4d0 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/NativePageProtection.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/NativePageProtection.cs @@ -35,6 +35,13 @@ public static uint Query(ulong address) return 0; } + // Fails with the page and the step named, so a failure says which check it was. + public static void Expect(uint expected, ulong address, string step) + { + var actual = Query(address); + Assert.True(actual == expected, $"{step}: page 0x{address:X} has protection 0x{actual:X2}, expected 0x{expected:X2}."); + } + private static uint ConvertProtection(bool readable, bool writable, bool executable) => (readable, writable, executable) switch { diff --git a/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs b/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs index d9e54f5b2..129edbefd 100644 --- a/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs +++ b/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs @@ -7,6 +7,7 @@ namespace SharpEmu.Libs.Tests.Pad; +[Collection(HostWindowInputCollection.Name)] public sealed class HostWindowInputTests { [Theory] @@ -67,6 +68,49 @@ public void ConnectedGamepadStateIsExposedByWindowSource() } } + [Fact] + public void GyroReadingsTurnTheReportedOrientationUntilReset() + { + var state = new HostGamepadState( + true, + HostGamepadButtons.None, + 128, + 128, + 128, + 128, + 0, + 0, + Motion: new HostMotionState(true, 0, 9.80665f, 0, 0, 0, 0)); + HostWindowInput.Connect(); + try + { + HostWindowInput.ResetMotionOrientation(); + ulong timestamp = 0; + for (var reading = 0; reading <= 100; reading++) + { + timestamp += 10_000_000; + HostWindowInput.ApplyGamepadMotion(true, 0, MathF.PI / 2, 0, timestamp); + } + + HostWindowInput.SetGamepad("SDL test pad", state); + Span<HostGamepadState> states = stackalloc HostGamepadState[1]; + var source = Assert.IsAssignableFrom<IHostWindowInputSource>(HostWindowInputSource.Current); + Assert.Equal(1, source.GetGamepadStates(states)); + Assert.Equal(MathF.Sqrt(0.5f), states[0].Motion.OrientationY, 3); + Assert.Equal(MathF.Sqrt(0.5f), states[0].Motion.OrientationW, 3); + + HostWindowInput.ResetMotionOrientation(); + HostWindowInput.SetGamepad("SDL test pad", state); + Assert.Equal(1, source.GetGamepadStates(states)); + Assert.Equal(0f, states[0].Motion.OrientationY, 5); + Assert.Equal(1f, states[0].Motion.OrientationW, 5); + } + finally + { + HostWindowInput.Disconnect(); + } + } + [Fact] public void ControllerOutputIsForwardedToSdlOwner() { diff --git a/tests/SharpEmu.Libs.Tests/Pad/MotionOrientationTests.cs b/tests/SharpEmu.Libs.Tests/Pad/MotionOrientationTests.cs new file mode 100644 index 000000000..0b990aa68 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Pad/MotionOrientationTests.cs @@ -0,0 +1,80 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Numerics; +using SharpEmu.Libs.Pad; +using Xunit; + +namespace SharpEmu.Libs.Tests.Pad; + +public sealed class MotionOrientationTests +{ + private const ulong StepNanoseconds = 10_000_000; + + [Fact] + public void AccumulatesTheGyroRotation() + { + var motion = new MotionOrientation(); + Turn(motion, new Vector3(0, MathF.PI / 2, 0), 101, 0); + AssertSameRotation(Quaternion.CreateFromAxisAngle(Vector3.UnitY, MathF.PI / 2), motion.Orientation); + } + + [Fact] + public void ResetReturnsToIdentity() + { + var motion = new MotionOrientation(); + Turn(motion, new Vector3(1, 0, 0), 20, 0); + motion.Reset(); + AssertSameRotation(Quaternion.Identity, motion.Orientation); + } + + [Fact] + public void AGapBetweenReadingsIsNotIntegrated() + { + var motion = new MotionOrientation(); + motion.ApplyAngularVelocity(new Vector3(1, 0, 0), 1_000_000_000); + motion.ApplyAngularVelocity(new Vector3(1, 0, 0), 2_000_000_000); + AssertSameRotation(Quaternion.Identity, motion.Orientation); + } + + [Theory] + [InlineData(false, 0.25f)] + [InlineData(true, 0f)] + public void TiltCorrectionTurnsPitchDriftBackToGravity(bool correction, float expectedAngle) + { + var motion = new MotionOrientation(); + motion.ApplyAcceleration(new Vector3(0, 1, 0)); + var timestamp = Turn(motion, new Vector3(0.5f, 0, 0), 51, 0); + Assert.Equal(0.25f, Angle(motion.Orientation), 3); + + motion.TiltCorrection = correction; + Turn(motion, Vector3.Zero, 500, timestamp); + Assert.Equal(expectedAngle, Angle(motion.Orientation), 2); + } + + [Fact] + public void TiltCorrectionLeavesHeadingDrift() + { + var motion = new MotionOrientation { TiltCorrection = true }; + motion.ApplyAcceleration(new Vector3(0, 1, 0)); + var timestamp = Turn(motion, new Vector3(0, 0.5f, 0), 51, 0); + Turn(motion, Vector3.Zero, 500, timestamp); + Assert.Equal(0.25f, Angle(motion.Orientation), 3); + } + + private static ulong Turn(MotionOrientation motion, Vector3 rate, int readings, ulong timestamp) + { + for (var reading = 0; reading < readings; reading++) + { + timestamp += StepNanoseconds; + motion.ApplyAngularVelocity(rate, timestamp); + } + + return timestamp; + } + + private static float Angle(Quaternion orientation) => 2 * MathF.Acos(MathF.Min(1, MathF.Abs(orientation.W))); + + private static void AssertSameRotation(Quaternion expected, Quaternion actual) => + Assert.True(MathF.Abs(Quaternion.Dot(expected, actual)) > 0.99999f, $"expected {expected}, got {actual}"); +} diff --git a/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs b/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs index e228873bc..fc137e268 100644 --- a/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Buffers.Binary; using SharpEmu.HLE; using SharpEmu.Libs.Pad; using Xunit; @@ -233,6 +234,55 @@ public void GetTriggerEffectState_RejectsForeignHandles(int handle) Assert.Equal(InvalidHandle, PadExports.PadGetTriggerEffectState(_ctx)); } + [NativeX64Fact] + public void GetTriggerEffectState_ReportsTheEffectTheGameSet() + { + const ulong parameterAddress = Base + 0x200; + const ulong stateAddress = Base + 0x100; + var parameter = new byte[120]; + parameter[0] = 0x02; + BinaryPrimitives.WriteUInt32LittleEndian(parameter.AsSpan(64), 2); + parameter[72] = 2; + parameter[73] = 6; + parameter[74] = 8; + Assert.True(_memory.TryWrite(parameterAddress, parameter)); + _ctx[CpuRegister.Rdi] = 1; + _ctx[CpuRegister.Rsi] = parameterAddress; + Assert.Equal(0, PadExports.PadSetTriggerEffect(_ctx)); + + _ctx[CpuRegister.Rdi] = 1; + _ctx[CpuRegister.Rsi] = stateAddress; + Assert.Equal(0, PadExports.PadGetTriggerEffectState(_ctx)); + Span<byte> state = stackalloc byte[8]; + Assert.True(_memory.TryRead(stateAddress, state)); + Assert.Equal(0, BinaryPrimitives.ReadInt32LittleEndian(state)); + Assert.Equal(3, BinaryPrimitives.ReadInt32LittleEndian(state[4..])); + } + + [NativeX64Theory] + [InlineData(0, new byte[0], 255, 0)] + [InlineData(1, new byte[] { 3, 5 }, 0, 1)] + [InlineData(1, new byte[] { 3, 5 }, 128, 2)] + [InlineData(1, new byte[] { 7, 5 }, 128, 1)] + [InlineData(2, new byte[] { 2, 6, 8 }, 0, 3)] + [InlineData(2, new byte[] { 2, 6, 8 }, 100, 4)] + [InlineData(2, new byte[] { 2, 6, 8 }, 255, 5)] + [InlineData(3, new byte[] { 0, 4, 40 }, 200, 7)] + [InlineData(3, new byte[] { 0, 4, 0 }, 200, 6)] + [InlineData(4, new byte[] { 0, 0, 0, 0, 0, 6, 6, 6, 6, 6 }, 140, 2)] + [InlineData(4, new byte[] { 0, 0, 0, 0, 0, 6, 6, 6, 6, 6 }, 60, 1)] + [InlineData(5, new byte[] { 4, 8, 1, 8 }, 120, 2)] + [InlineData(5, new byte[] { 4, 8, 1, 8 }, 4, 1)] + [InlineData(6, new byte[] { 30, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5 }, 120, 7)] + [InlineData(6, new byte[] { 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }, 120, 6)] + public void TriggerEffectState_FollowsTheEffectAndTheTriggerTravel(int mode, byte[] data, int travel, int expected) + { + var command = new byte[56]; + BinaryPrimitives.WriteUInt32LittleEndian(command, (uint)mode); + data.CopyTo(command, 8); + Assert.Equal(expected, PadExports.TriggerEffectState(command, (byte)travel)); + } + [NativeX64Fact] public void ReadState_RejectsHandleZeroOnceAPadIsOpen() { diff --git a/tests/SharpEmu.Libs.Tests/Pad/PadReadHistoryTests.cs b/tests/SharpEmu.Libs.Tests/Pad/PadReadHistoryTests.cs new file mode 100644 index 000000000..dce34135c --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Pad/PadReadHistoryTests.cs @@ -0,0 +1,127 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.HLE; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Pad; +using Xunit; + +namespace SharpEmu.Libs.Tests.Pad; + +[CollectionDefinition(HostWindowInputCollection.Name, DisableParallelization = true)] +public sealed class HostWindowInputCollection +{ + public const string Name = "Host window input"; +} + +[Collection(HostWindowInputCollection.Name)] +public sealed class PadReadHistoryTests : IDisposable +{ + private const ulong Base = 0x1_0000_0000; + private const ulong DataAddress = Base + 0x100; + private const int PadDataSize = 0x78; + private const int PrimaryUserId = 0x10000000; + private const int EnterKey = 0x0D; + private const uint Cross = 0x4000; + + private readonly FakeCpuMemory _memory = new(Base, 0x2000); + private readonly CpuContext _ctx; + + public PadReadHistoryTests() + { + HostWindowInput.Connect(); + _ctx = new CpuContext(_memory, Generation.Gen5); + Assert.Equal(0, PadExports.PadInit(_ctx)); + _ctx[CpuRegister.Rdi] = PrimaryUserId; + _ctx[CpuRegister.Rsi] = 0; + _ctx[CpuRegister.Rdx] = 0; + _ctx[CpuRegister.Rcx] = 0; + Assert.Equal(1, PadExports.PadOpen(_ctx)); + } + + public void Dispose() => HostWindowInput.Disconnect(); + + [NativeX64Fact] + public void ATapBetweenTwoReadsReachesTheGameAsAPressAndARelease() + { + Assert.Equal(1, Read(64)); + Assert.Equal(0u, Buttons(0) & Cross); + + HostWindowInput.SetKey(EnterKey, true); + HostWindowInput.SetKey(EnterKey, false); + + Assert.Equal(3, Read(64)); + Assert.Equal(Cross, Buttons(0) & Cross); + Assert.Equal(0u, Buttons(1) & Cross); + Assert.Equal(0u, Buttons(2) & Cross); + Assert.True(Timestamp(0) <= Timestamp(1) && Timestamp(1) <= Timestamp(2)); + Assert.Equal(1, Read(64)); + Assert.Equal(0u, Buttons(0) & Cross); + } + + [NativeX64Fact] + public void ReadsOfOneStateTakeTheChangesInOrder() + { + Assert.Equal(1, Read(1)); + + HostWindowInput.SetKey(EnterKey, true); + HostWindowInput.SetKey(EnterKey, false); + + Assert.Equal(1, Read(1)); + Assert.Equal(Cross, Buttons(0) & Cross); + Assert.Equal(1, Read(1)); + Assert.Equal(0u, Buttons(0) & Cross); + Assert.Equal(1, Read(1)); + Assert.Equal(0u, Buttons(0) & Cross); + } + + [NativeX64Fact] + public void GamepadButtonEventsBetweenPollsReachTheGame() + { + HostWindowInput.SetGamepad("test pad", new HostGamepadState(true, HostGamepadButtons.None, 128, 128, 128, 128, 0, 0)); + Assert.Equal(1, Read(64)); + + HostWindowInput.SetGamepadButton(HostGamepadButtons.Cross, true); + HostWindowInput.SetGamepadButton(HostGamepadButtons.Cross, false); + HostWindowInput.SetGamepad("test pad", new HostGamepadState(true, HostGamepadButtons.None, 128, 128, 128, 128, 0, 0)); + + Assert.Equal(3, Read(64)); + Assert.Equal(Cross, Buttons(0) & Cross); + Assert.Equal(0u, Buttons(1) & Cross); + Assert.Equal(0u, Buttons(2) & Cross); + } + + [NativeX64Fact] + public void AHeldButtonStaysPressedInTheCurrentState() + { + Assert.Equal(1, Read(64)); + + HostWindowInput.SetKey(EnterKey, true); + + Assert.Equal(2, Read(64)); + Assert.Equal(Cross, Buttons(0) & Cross); + Assert.Equal(Cross, Buttons(1) & Cross); + Assert.Equal(1, Read(64)); + Assert.Equal(Cross, Buttons(0) & Cross); + } + + private int Read(int count) + { + _ctx[CpuRegister.Rdi] = 1; + _ctx[CpuRegister.Rsi] = DataAddress; + _ctx[CpuRegister.Rdx] = (ulong)count; + return PadExports.PadRead(_ctx); + } + + private uint Buttons(int index) => BinaryPrimitives.ReadUInt32LittleEndian(State(index)); + + private ulong Timestamp(int index) => BinaryPrimitives.ReadUInt64LittleEndian(State(index)[0x50..]); + + private byte[] State(int index) + { + var data = new byte[PadDataSize]; + Assert.True(_memory.TryRead(DataAddress + (ulong)(index * PadDataSize), data)); + return data; + } +} diff --git a/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs b/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs index 85f39a1dc..f70fcfec7 100644 --- a/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs @@ -38,6 +38,28 @@ public void GetUserNumberValidatesUserAndOutput(int userId, ulong address, int e Assert.Equal(expected, UserServiceExports.UserServiceGetUserNumber(ctx)); } + [Fact] + public void TriggerEffectAndVibrationIntensitiesReportTheStandardSetting() + { + const ulong address = 0x1_0000_0000; + var memory = new FakeCpuMemory(address, 0x100); + var ctx = new CpuContext(memory, Generation.Gen5); + Span<byte> value = stackalloc byte[4]; + foreach (var export in new Func<CpuContext, int>[] + { + UserServiceExports.UserServiceGetAccessibilityTriggerEffect, + UserServiceExports.UserServiceGetAccessibilityVibration, + }) + { + Assert.True(memory.TryWrite(address, new byte[] { 0xEE, 0xEE, 0xEE, 0xEE })); + ctx[CpuRegister.Rdi] = 0x10000000; + ctx[CpuRegister.Rsi] = address; + Assert.Equal(0, export(ctx)); + Assert.True(memory.TryRead(address, value)); + Assert.Equal(1, BitConverter.ToInt32(value)); + } + } + [Fact] public void TerminateResetsTheLoginEvent() { diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs index 66db3cbad..cdc585f1d 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs @@ -46,10 +46,10 @@ public void ACommandStreamStoreLandsAfterEarlierGpuCopiesBlockCpuReads() Assert.Equal(1, harness.Read(label, 1)[0]); } - // A shader write keeps its read protection deferred to the submission: applying it before every store stalled guests - // that read their GPU output right after a label. + // The same holds for a shader write: a guest that sees the label reads the shader's output next, and must not get the + // bytes from before the write. [Fact] - public void ACommandStreamStoreLeavesShaderWriteProtectionToTheSubmission() + public void ACommandStreamStoreLandsAfterEarlierShaderWritesBlockCpuReads() { if (_vulkan is null || !OperatingSystem.IsWindows()) return; @@ -64,7 +64,7 @@ public void ACommandStreamStoreLeavesShaderWriteProtectionToTheSubmission() var label = address + 0x8000; LandStore(presenter, label); - Assert.Equal(HostPageProtection.ReadOnly, harness.Protection(address)); + Assert.Equal(HostPageProtection.NoAccess, harness.Protection(address)); Assert.Equal(1, harness.Read(label, 1)[0]); } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5FloatContractionTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5FloatContractionTests.cs new file mode 100644 index 000000000..92098db81 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5FloatContractionTests.cs @@ -0,0 +1,71 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class Gen5FloatContractionTests +{ + // A depth prepass and the pass that tests its depth for equality compute one position in two programs. A driver + // that fuses a multiply with an add in only one of them moves a vertex by an ulp and the second pass drops the + // triangle, so programs before rasterization keep each operation's rounding; pixel and compute programs may fuse. + [Theory] + [InlineData(ShaderStage.Vertex, true)] + [InlineData(ShaderStage.Pixel, false)] + [InlineData(ShaderStage.Compute, false)] + public void ProgramsBeforeRasterizationKeepEachFloatRounding(ShaderStage stage, bool kept) + { + var request = Request(Program( + Vop2(0, "VMulF32", 2, Gen5Operand.Vector(0), Gen5Operand.Vector(1)), + Vop2(4, "VAddF32", 3, Gen5Operand.Vector(2), Gen5Operand.Vector(1)), + Vop2(8, "VSubF32", 4, Gen5Operand.Vector(3), Gen5Operand.Vector(0)), + Vop3(12, "VFmaF32", 5, Gen5Operand.Vector(0), Gen5Operand.Vector(1), Gen5Operand.Vector(4)), + EndProgram(20)), stage); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var module = ReadInstructions(shader.Spirv); + var glsl = Assert.Single(module, instruction => instruction.Opcode == SpirvOp.ExtInstImport && + Literal(instruction.Operands.AsSpan(1)) == "GLSL.std.450").Operands[0]; + var arithmetic = module.Where(instruction => instruction.Opcode is SpirvOp.FMul or SpirvOp.FAdd or SpirvOp.FSub || + instruction.Opcode == SpirvOp.ExtInst && instruction.Operands[2] == glsl && instruction.Operands[3] == 50) + .Select(instruction => (instruction.Opcode, Result: instruction.Operands[1])).ToArray(); + foreach (var opcode in new[] { SpirvOp.FMul, SpirvOp.FAdd, SpirvOp.FSub, SpirvOp.ExtInst }) + Assert.Contains(arithmetic, operation => operation.Opcode == opcode); + var decorated = module.Where(instruction => instruction.Opcode == SpirvOp.Decorate && instruction.Operands.Length == 2 && + instruction.Operands[1] == (uint)SpirvDecoration.NoContraction).Select(instruction => instruction.Operands[0]).ToList(); + Assert.Equal(decorated.Count, decorated.Distinct().Count()); + Assert.All(arithmetic, operation => Assert.Equal(kept, decorated.Contains(operation.Result))); + Assert.Equal(kept ? arithmetic.Length : 0, decorated.Count); + } + + private static string Literal(ReadOnlySpan<uint> words) + { + var bytes = new byte[words.Length * sizeof(uint)]; + for (var index = 0; index < words.Length; index++) + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint)), words[index]); + var length = Array.IndexOf(bytes, (byte)0); + return Encoding.ASCII.GetString(bytes, 0, length < 0 ? bytes.Length : length); + } + + private static List<(SpirvOp Opcode, uint[] Operands)> ReadInstructions(byte[] bytes) + { + var words = new uint[bytes.Length / sizeof(uint)]; + for (var index = 0; index < words.Length; index++) + words[index] = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint))); + var result = new List<(SpirvOp, uint[])>(); + for (var index = 5; index < words.Length;) + { + var count = (int)(words[index] >> 16); + Assert.InRange(count, 1, words.Length - index); + result.Add(((SpirvOp)(words[index] & 0xFFFF), words.AsSpan(index + 1, count - 1).ToArray())); + index += count; + } + return result; + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5WaveLaneLocalAnalysisTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5WaveLaneLocalAnalysisTests.cs index 959eb3243..8fa77942f 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5WaveLaneLocalAnalysisTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5WaveLaneLocalAnalysisTests.cs @@ -205,6 +205,14 @@ public void ABarrierInAnExecSkip_IsRefused() AssertRefused("a barrier"); } + [Fact] + public void AWorkgroupBarrier_IsRefusedEvenOutsideAnExecSkip() + { + Add(new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Sopp, "SBarrier", [0u], [], [], null)); + + AssertRefused("a barrier"); + } + [Fact] public void ReadFirstLaneOfAUniformValue_IsLaneLocal() { From 94d833daabd1b11f7f3ca49c593649e3bd4d8835 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:37:26 +0300 Subject: [PATCH 09/64] [GUI] Add Xbox controller glyphs and hints to the GUI --- src/SharpEmu.GUI/Controls/PadGlyph.cs | 34 ++++++++++++-- .../MainWindow.ControllerHints.cs | 27 ++++++++--- src/SharpEmu.GUI/MainWindow.axaml | 2 +- src/SharpEmu.GUI/MainWindow.axaml.cs | 2 +- src/SharpEmu.GUI/Themes/Styles/Surfaces.axaml | 2 +- src/SharpEmu.HLE/Host/HostGamepadState.cs | 1 + .../Pad/SdlGamepadStateReader.cs | 1 + .../GUI/ControllerHintsTests.cs | 46 +++++++++++++++++++ 8 files changed, 103 insertions(+), 12 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/GUI/ControllerHintsTests.cs diff --git a/src/SharpEmu.GUI/Controls/PadGlyph.cs b/src/SharpEmu.GUI/Controls/PadGlyph.cs index 0b19baf01..8fb1ca82c 100644 --- a/src/SharpEmu.GUI/Controls/PadGlyph.cs +++ b/src/SharpEmu.GUI/Controls/PadGlyph.cs @@ -1,9 +1,11 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Globalization; using Avalonia; using Avalonia.Controls; using Avalonia.Media; +using SharpEmu.HLE.Host; namespace SharpEmu.GUI.Controls; @@ -16,20 +18,22 @@ internal enum PadSymbol } /// <summary> -/// A monochrome PlayStation face-button glyph (cross, circle, triangle, square) drawn as -/// shapes inside a thin ring, so it needs no font and stays crisp at any scale. +/// A monochrome face-button glyph inside a thin ring, using the connected pad's layout. /// </summary> internal sealed class PadGlyph : Control { public static readonly StyledProperty<PadSymbol> SymbolProperty = AvaloniaProperty.Register<PadGlyph, PadSymbol>(nameof(Symbol)); + public static readonly StyledProperty<HostGamepadType> GamepadTypeProperty = + AvaloniaProperty.Register<PadGlyph, HostGamepadType>(nameof(GamepadType)); + public static readonly StyledProperty<IBrush?> ForegroundProperty = AvaloniaProperty.Register<PadGlyph, IBrush?>(nameof(Foreground), Brushes.White); static PadGlyph() { - AffectsRender<PadGlyph>(SymbolProperty, ForegroundProperty); + AffectsRender<PadGlyph>(SymbolProperty, GamepadTypeProperty, ForegroundProperty); AffectsMeasure<PadGlyph>(WidthProperty, HeightProperty); WidthProperty.OverrideDefaultValue<PadGlyph>(28); HeightProperty.OverrideDefaultValue<PadGlyph>(28); @@ -48,6 +52,22 @@ public IBrush? Foreground set => SetValue(ForegroundProperty, value); } + public HostGamepadType GamepadType + { + get => GetValue(GamepadTypeProperty); + set => SetValue(GamepadTypeProperty, value); + } + + internal static string? GetButtonLetter(PadSymbol symbol, HostGamepadType type) => + type == HostGamepadType.Xbox ? symbol switch + { + PadSymbol.Cross => "A", + PadSymbol.Circle => "B", + PadSymbol.Square => "X", + PadSymbol.Triangle => "Y", + _ => null, + } : null; + public override void Render(DrawingContext context) { var size = Math.Min(Bounds.Width, Bounds.Height); @@ -60,6 +80,14 @@ public override void Render(DrawingContext context) var ring = new Pen(brush, 1.5) { LineCap = PenLineCap.Round }; context.DrawEllipse(null, ring, centre, size / 2 - 1, size / 2 - 1); + if (GetButtonLetter(Symbol, GamepadType) is { } letter) + { + var text = new FormattedText(letter, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, + new Typeface(FontFamily.Default, weight: FontWeight.SemiBold), size * 0.6, brush); + context.DrawText(text, new Point(centre.X - text.Width / 2, centre.Y - text.Height / 2)); + return; + } + // Symbols sit in a box 0.34 of the ring size either side of the centre. var r = size * 0.19; var pen = new Pen(brush, 2) { LineCap = PenLineCap.Round, LineJoin = PenLineJoin.Round }; diff --git a/src/SharpEmu.GUI/MainWindow.ControllerHints.cs b/src/SharpEmu.GUI/MainWindow.ControllerHints.cs index 29dd9c6d0..f6cfce514 100644 --- a/src/SharpEmu.GUI/MainWindow.ControllerHints.cs +++ b/src/SharpEmu.GUI/MainWindow.ControllerHints.cs @@ -6,11 +6,12 @@ using Avalonia.Layout; using Avalonia.Media; using SharpEmu.GUI.Controls; +using SharpEmu.HLE.Host; namespace SharpEmu.GUI; /// <summary> -/// Controller connection state and the PlayStation-style button-hint bar. Hints are shown +/// Controller connection state and the button-hint bar. Hints are shown /// only while a pad is connected and list only the buttons that do something right now. /// </summary> public partial class MainWindow @@ -19,6 +20,7 @@ public partial class MainWindow private const double MainContentBottomMargin = 24; private bool _gamepadConnected; + private HostGamepadType _gamepadType; private string? _hintKey; private enum HintContext @@ -33,8 +35,17 @@ private enum HintContext Trophies, } - private void SetGamepadConnected(bool connected) + private void SetGamepadConnected(bool connected, HostGamepadType type = HostGamepadType.Generic) { + if (_gamepadType != type) + { + _gamepadType = type; + var (left, right) = ShoulderHintLabels(type); + ((TextBlock)PageHintL1.Child!).Text = left; + ((TextBlock)PageHintR1.Child!).Text = right; + _hintKey = null; + } + if (connected == _gamepadConnected) { return; @@ -158,18 +169,22 @@ private void RefreshControllerHints() } } - private static StackPanel HintItem(PadSymbol symbol, string label) + private StackPanel HintItem(PadSymbol symbol, string label) { var item = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; - item.Children.Add(new PadGlyph { Symbol = symbol, VerticalAlignment = VerticalAlignment.Center }); + item.Children.Add(new PadGlyph { Symbol = symbol, GamepadType = _gamepadType, VerticalAlignment = VerticalAlignment.Center }); item.Children.Add(HintLabel(label)); return item; } - private static StackPanel ShoulderHintItem(string label) + internal static (string Left, string Right) ShoulderHintLabels(HostGamepadType type) => + type == HostGamepadType.Xbox ? ("LB", "RB") : ("L1", "R1"); + + private StackPanel ShoulderHintItem(string label) { var item = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 }; - foreach (var text in new[] { "L1", "R1" }) + var (left, right) = ShoulderHintLabels(_gamepadType); + foreach (var text in new[] { left, right }) { item.Children.Add(new Border { diff --git a/src/SharpEmu.GUI/MainWindow.axaml b/src/SharpEmu.GUI/MainWindow.axaml index 3f518b95d..0e3ded972 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml +++ b/src/SharpEmu.GUI/MainWindow.axaml @@ -130,7 +130,7 @@ SPDX-License-Identifier: GPL-2.0-or-later <!-- Page titles with the library toolbar on the same row. Every child is centred on the one 56 pt row and every toolbar control is 44 pt tall. - Plain buttons (not TabItem) so there is no Fluent tab chrome; the L1/R1 + Plain buttons (not TabItem) so there is no Fluent tab chrome; the shoulder-button keycaps appear only while a controller is connected and the shoulder buttons switch pages from anywhere. --> <Grid x:Name="ContentToolbar" Grid.Row="0" ColumnDefinitions="Auto,*,Auto" Height="56" Margin="0,0,0,16"> diff --git a/src/SharpEmu.GUI/MainWindow.axaml.cs b/src/SharpEmu.GUI/MainWindow.axaml.cs index b6397580a..a43d71b18 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml.cs +++ b/src/SharpEmu.GUI/MainWindow.axaml.cs @@ -939,7 +939,7 @@ private void PollGamepad() return; } - SetGamepadConnected(true); + SetGamepadConnected(true, pad.Type); RefreshControllerHints(); if ((pad.Buttons & ~_previousPadButtons) != HostGamepadButtons.None) { diff --git a/src/SharpEmu.GUI/Themes/Styles/Surfaces.axaml b/src/SharpEmu.GUI/Themes/Styles/Surfaces.axaml index b4f838e69..b29ea0f7d 100644 --- a/src/SharpEmu.GUI/Themes/Styles/Surfaces.axaml +++ b/src/SharpEmu.GUI/Themes/Styles/Surfaces.axaml @@ -47,7 +47,7 @@ Shared card, badge, hint and cover surfaces. <Setter Property="BorderBrush" Value="{StaticResource InfoRimBrush}" /> </Style> - <!-- Gamepad shoulder-button keycap (L1/R1): shown only while a controller is connected. --> + <!-- Gamepad shoulder-button keycap: shown only while a controller is connected. --> <Style Selector="Border.padHint"> <Setter Property="Background" Value="{StaticResource FieldBrush}" /> <Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" /> diff --git a/src/SharpEmu.HLE/Host/HostGamepadState.cs b/src/SharpEmu.HLE/Host/HostGamepadState.cs index 2babc2e21..ce04a0e65 100644 --- a/src/SharpEmu.HLE/Host/HostGamepadState.cs +++ b/src/SharpEmu.HLE/Host/HostGamepadState.cs @@ -38,6 +38,7 @@ public enum HostGamepadType : byte Generic, DualShock4, DualSense, + Xbox, } public enum HostGamepadConnection : byte diff --git a/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs b/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs index 74556cbed..445bb8ca5 100644 --- a/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs +++ b/src/SharpEmu.Libs/Pad/SdlGamepadStateReader.cs @@ -121,6 +121,7 @@ public static HostGamepadState Read(SDL_Gamepad* gamepad) { SDL_GamepadType.SDL_GAMEPAD_TYPE_PS4 => HostGamepadType.DualShock4, SDL_GamepadType.SDL_GAMEPAD_TYPE_PS5 => HostGamepadType.DualSense, + SDL_GamepadType.SDL_GAMEPAD_TYPE_XBOX360 or SDL_GamepadType.SDL_GAMEPAD_TYPE_XBOXONE => HostGamepadType.Xbox, _ => HostGamepadType.Generic, }; diff --git a/tests/SharpEmu.Libs.Tests/GUI/ControllerHintsTests.cs b/tests/SharpEmu.Libs.Tests/GUI/ControllerHintsTests.cs new file mode 100644 index 000000000..04fdc4f30 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/GUI/ControllerHintsTests.cs @@ -0,0 +1,46 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.GUI; +using SharpEmu.GUI.Controls; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Pad; +using SDL; +using Xunit; + +namespace SharpEmu.Libs.Tests.GUI; + +public sealed class ControllerHintsTests +{ + [Theory] + [InlineData(SDL_GamepadType.SDL_GAMEPAD_TYPE_XBOX360)] + [InlineData(SDL_GamepadType.SDL_GAMEPAD_TYPE_XBOXONE)] + public void XboxPadsUseTheirOwnFaceAndShoulderLabels(SDL_GamepadType sdlType) + { + var type = SdlGamepadStateReader.MapGamepadType(sdlType); + + Assert.Equal(HostGamepadType.Xbox, type); + Assert.Equal("A", PadGlyph.GetButtonLetter(PadSymbol.Cross, type)); + Assert.Equal("B", PadGlyph.GetButtonLetter(PadSymbol.Circle, type)); + Assert.Equal("X", PadGlyph.GetButtonLetter(PadSymbol.Square, type)); + Assert.Equal("Y", PadGlyph.GetButtonLetter(PadSymbol.Triangle, type)); + Assert.Equal(("LB", "RB"), MainWindow.ShoulderHintLabels(type)); + } + + [Theory] + [InlineData(SDL_GamepadType.SDL_GAMEPAD_TYPE_PS4, HostGamepadType.DualShock4)] + [InlineData(SDL_GamepadType.SDL_GAMEPAD_TYPE_PS5, HostGamepadType.DualSense)] + [InlineData(SDL_GamepadType.SDL_GAMEPAD_TYPE_UNKNOWN, HostGamepadType.Generic)] + public void OtherPadsKeepTheExistingSymbols(SDL_GamepadType sdlType, HostGamepadType expectedType) + { + var type = SdlGamepadStateReader.MapGamepadType(sdlType); + + Assert.Equal(expectedType, type); + foreach (var symbol in Enum.GetValues<PadSymbol>()) + { + Assert.Null(PadGlyph.GetButtonLetter(symbol, type)); + } + + Assert.Equal(("L1", "R1"), MainWindow.ShoulderHintLabels(type)); + } +} From a5f6feb4111101e34eb0a397259ec3e9d8d6e3a8 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:41:13 +0300 Subject: [PATCH 10/64] [GUI] Add "launch with variables" option to game context menu --- src/SharpEmu.GUI/MainWindow.axaml | 6 ++++++ src/SharpEmu.GUI/MainWindow.axaml.cs | 2 ++ 2 files changed, 8 insertions(+) diff --git a/src/SharpEmu.GUI/MainWindow.axaml b/src/SharpEmu.GUI/MainWindow.axaml index 0e3ded972..4b95e30ce 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml +++ b/src/SharpEmu.GUI/MainWindow.axaml @@ -241,6 +241,12 @@ SPDX-License-Identifier: GPL-2.0-or-later <TextBlock Classes="materialSymbol compact" Text="play_arrow" /> </MenuItem.Icon> </MenuItem> + <MenuItem x:Name="CtxLaunchVariables" + Header="{Binding [Launch.Variables.Title], Source={x:Static local:Localization.Instance}}"> + <MenuItem.Icon> + <TextBlock Classes="materialSymbol compact" Text="data_object" /> + </MenuItem.Icon> + </MenuItem> <MenuItem x:Name="CtxCreateShortcut" Header="{Binding [Library.Context.CreateShortcut], Source={x:Static local:Localization.Instance}}"> <MenuItem.Icon> diff --git a/src/SharpEmu.GUI/MainWindow.axaml.cs b/src/SharpEmu.GUI/MainWindow.axaml.cs index a43d71b18..ac79aa626 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml.cs +++ b/src/SharpEmu.GUI/MainWindow.axaml.cs @@ -442,6 +442,7 @@ public MainWindow() GameList.AddHandler(ContextRequestedEvent, OnGameContextRequested, RoutingStrategies.Tunnel); AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); CtxLaunch.Click += (_, _) => LaunchSelected(); + CtxLaunchVariables.Click += async (_, _) => await LaunchWithVariablesAsync(); CtxCreateShortcut.Click += async (_, _) => await CreateSelectedGameShortcutAsync(); CtxOpenFolder.Click += (_, _) => OpenSelectedGameFolder(); CtxCopyPath.Click += async (_, _) => await CopySelectedGamePathAsync(); @@ -2569,6 +2570,7 @@ private void OnGameContextRequested(object? sender, ContextRequestedEventArgs e) GameList.SelectedItem = game; CtxLaunch.IsEnabled = !_isRunning; + CtxLaunchVariables.IsEnabled = !_isRunning; CtxCopyTitleId.IsEnabled = game.TitleId is not null; CtxGameSettings.IsEnabled = true; CtxPackZar.IsEnabled = GameVersions.PackableForGame(_allGames, game).Count > 0; From 062289e7a68a2a0c4e2c556d49ff2bbd6c8c8c49 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:36 +0300 Subject: [PATCH 11/64] [Kernel] Print each guest assertion message once and count its repeats --- src/SharpEmu.Libs/Kernel/KernelExports.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Kernel/KernelExports.cs b/src/SharpEmu.Libs/Kernel/KernelExports.cs index 9ab75576e..9bc8000b7 100644 --- a/src/SharpEmu.Libs/Kernel/KernelExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelExports.cs @@ -11,8 +11,8 @@ public static class KernelExports private static readonly object _cxaGate = new(); private static readonly List<CxaDestructorEntry> _cxaDestructors = new(); private static readonly object _coredumpGate = new(); - private const string RepeatedGuestAssertion = "Assertion failed: 0"; - private static int _repeatedGuestAssertionCount; + private const int GuestAssertionReportInterval = 1000; + private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, int> GuestAssertionCounts = new(); private static ulong _coredumpHandler; private static ulong _coredumpHandlerContext; @@ -442,20 +442,29 @@ public static int Printf(CpuContext ctx) // but printf must still report its original byte count to the guest. private static bool ShouldWriteGuestPrintf(string text) { - if (!string.Equals(text.TrimEnd('\r', '\n'), RepeatedGuestAssertion, StringComparison.Ordinal)) + var line = text.TrimEnd('\r', '\n'); + if (!IsGuestAssertion(line)) { return true; } - var count = Interlocked.Increment(ref _repeatedGuestAssertionCount); + var count = GuestAssertionCounts.AddOrUpdate(line, 1, static (_, value) => value + 1); if (count == 2) { - Console.WriteLine("[DEBUG][PRINF] Further repeated 'Assertion failed: 0' messages are suppressed."); + Console.WriteLine($"[DEBUG][PRINF] Further repeats of '{line}' are suppressed."); + } + else if (count % GuestAssertionReportInterval == 0) + { + Console.WriteLine($"[DEBUG][PRINF] '{line}' repeated {count} times."); } return count == 1; } + private static bool IsGuestAssertion(string line) => + line.StartsWith("Assertion failed", StringComparison.Ordinal) || + line.StartsWith("An assertion fired in:", StringComparison.Ordinal); + [SysAbiExport( Nid = "EMutwaQ34Jo", ExportName = "perror", From ad6cec39eec503982343088f807bd9ad5e9d2343 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:36 +0300 Subject: [PATCH 12/64] [AudioOut2] Take the device cushion as a parameter of the slot threshold and the producer nap --- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index bb35ab228..bd0904851 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -1345,7 +1345,10 @@ private static bool IsFloatBackend(IHostAudioStream backend) } internal static double DeviceSlotFreeThreshold(uint grainSamples, uint frequency, uint queueDepth) => - DeviceCushionMilliseconds + (grainSamples * 1000.0 / frequency * Math.Max((long)queueDepth - 1, 0)); + DeviceSlotFreeThreshold(grainSamples, frequency, queueDepth, DeviceCushionMilliseconds); + + internal static double DeviceSlotFreeThreshold(uint grainSamples, uint frequency, uint queueDepth, int cushionMilliseconds) => + cushionMilliseconds + (grainSamples * 1000.0 / frequency * Math.Max((long)queueDepth - 1, 0)); // The guest thread's last push: a thread that pushed within the last ActiveProducerMilliseconds feeds a context now. [ThreadStatic] @@ -1380,11 +1383,15 @@ public static bool ProducerNeedsPreciseNap(ulong microseconds) // the device reports less than its cushion less one grain (-1: it cannot report). internal static bool PreciseProducerNap(ulong microseconds, double millisecondsSincePush, int queuedMilliseconds, uint grainSamples, uint frequency) => + PreciseProducerNap(microseconds, millisecondsSincePush, queuedMilliseconds, grainSamples, frequency, DeviceCushionMilliseconds); + + internal static bool PreciseProducerNap(ulong microseconds, double millisecondsSincePush, int queuedMilliseconds, + uint grainSamples, uint frequency, int cushionMilliseconds) => microseconds <= PreciseNapLimitMicroseconds && millisecondsSincePush >= 0 && millisecondsSincePush < ActiveProducerMilliseconds && queuedMilliseconds >= 0 && - queuedMilliseconds < DeviceCushionMilliseconds - (grainSamples * 1000.0 / frequency); + queuedMilliseconds < cushionMilliseconds - (grainSamples * 1000.0 / frequency); /// <summary> /// Halves a usleep taken by a thread that feeds an AudioOut2 context while the device runs short, From 42660b6c2badf86d0f0d54db2edcf733632d2f35 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:36 +0300 Subject: [PATCH 13/64] [AudioOut2] Count a context's dropout reserve into its device cushion --- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 29 ++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index bd0904851..35bbfd71b 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -178,13 +178,30 @@ public uint ClockQueuedGrains() } public double DeviceSlotFreeMilliseconds => - DeviceSlotFreeThreshold(GrainSamples, Frequency, QueueDepth); + DeviceSlotFreeThreshold(GrainSamples, Frequency, QueueDepth, CushionMilliseconds); + + public long ReserveMicroseconds; + + public int CushionMilliseconds => + (int)Math.Max(DeviceCushionMilliseconds, Volatile.Read(ref ReserveMicroseconds) / 1000); + + public long CalmSince; + public long LastOutputTimestamp; + public float[] Recent = []; + public int RecentFrames; + public long StatsWindowStart; + public long StatsGrains; + public long StatsDropouts; + public long StatsStretches; + public long StatsStretchedFrames; + public long StatsSilentFills; + public long StatsTrims; // Grains the device holds beyond the cushion, at most QueueDepth. public uint DeviceQueuedGrains(int queuedMilliseconds) { var grainMilliseconds = GrainSamples * 1000.0 / Frequency; - var beyondCushion = queuedMilliseconds - DeviceCushionMilliseconds; + var beyondCushion = queuedMilliseconds - CushionMilliseconds; return beyondCushion <= 0 ? 0 : (uint)Math.Min(Math.Ceiling(beyondCushion / grainMilliseconds), QueueDepth); @@ -1376,7 +1393,13 @@ public static bool ProducerNeedsPreciseNap(ulong microseconds) } var sincePush = (Stopwatch.GetTimestamp() - _lastPushTimestamp) * 1000.0 / Stopwatch.Frequency; - return PreciseProducerNap(microseconds, sincePush, backend.QueuedMilliseconds, context.GrainSamples, context.Frequency); + return PreciseProducerNap( + microseconds, + sincePush, + backend.QueuedMilliseconds, + context.GrainSamples, + context.Frequency, + context.CushionMilliseconds); } // A nap of at most PreciseNapLimitMicroseconds by a thread that pushed within the last ActiveProducerMilliseconds, while From 6ded0bc9cae3cee7bac99d4ee94cfb9a62c1daa1 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:36 +0300 Subject: [PATCH 14/64] [AudioOut2] Queue a reserve of silence when the device runs dry and grow it on repeated dropouts --- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 165 +++++++++++++++++++- 1 file changed, 163 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index 35bbfd71b..5a92ab105 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -1601,7 +1601,8 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) } float peak; - var outputSpan = IsFloatBackend(backend) + var isFloatBackend = IsFloatBackend(backend); + var outputSpan = isFloatBackend ? WriteFloatOutput(mix.AsSpan(0, frames * 2), output, out peak) : WritePcm16Output(mix.AsSpan(0, frames * 2), output, out peak); context.DeviceBackend = backend; @@ -1614,7 +1615,7 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) $"ports={mixedPorts} peak={peak:F4} backend={backendName}"); } - return backend.Submit(outputSpan); + return SubmitWithReserve(context, backend, outputSpan, mix.AsSpan(0, frames * 2), frames, isFloatBackend); } finally { @@ -1624,6 +1625,166 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) } } + private static readonly long ReserveBaseMicroseconds = + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_AUDIO_RESERVE_MS"), out var reserveMilliseconds) + ? Math.Clamp(reserveMilliseconds, 0, 200) * 1000L + : 20_000L; + + private static readonly bool LogReserveStats = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_LOG_AUDIO_OUT2"), + "1", + StringComparison.Ordinal); + + private const long ReserveStepMicroseconds = 20_000; + private const long ReserveLimitMicroseconds = 200_000; + private const long ReserveRelaxMicroseconds = 10_000; + private const long ReserveRelaxAfterMicroseconds = 60_000_000; + private const long DropoutWindowMicroseconds = 300_000; + private const float QuietSampleLimit = 0.001f; + private const int MixChannels = 2; + + private static byte[] _silence = []; + + private static long TicksToMicroseconds(long ticks) => ticks * 1_000_000L / Stopwatch.Frequency; + + private static bool SubmitWithReserve( + ContextState context, + IHostAudioStream backend, + ReadOnlySpan<byte> output, + ReadOnlySpan<float> grain, + int frames, + bool isFloat) + { + var queuedMilliseconds = ReserveBaseMicroseconds == 0 ? -1 : backend.QueuedMilliseconds; + if (queuedMilliseconds < 0) + { + return backend.Submit(output); + } + + var now = Stopwatch.GetTimestamp(); + var grainMicroseconds = Math.Max(1L, frames * 1_000_000L / context.Frequency); + var first = context.LastOutputTimestamp == 0; + var ranDry = !first && queuedMilliseconds == 0; + var reserve = Volatile.Read(ref context.ReserveMicroseconds); + if (reserve == 0) + { + reserve = ReserveBaseMicroseconds; + context.CalmSince = now; + } + + if (ranDry && TicksToMicroseconds(now - context.LastOutputTimestamp) < DropoutWindowMicroseconds) + { + reserve = Math.Min(reserve + ReserveStepMicroseconds, ReserveLimitMicroseconds); + context.CalmSince = now; + context.StatsDropouts++; + } + else if (TicksToMicroseconds(now - context.CalmSince) >= ReserveRelaxAfterMicroseconds && + reserve > ReserveBaseMicroseconds) + { + reserve = Math.Max(ReserveBaseMicroseconds, reserve - ReserveRelaxMicroseconds); + context.CalmSince = now; + } + + Volatile.Write(ref context.ReserveMicroseconds, reserve); + context.LastOutputTimestamp = now; + + var payload = output; + if (first || ranDry) + { + var silentGrains = (reserve + grainMicroseconds - 1) / grainMicroseconds; + SubmitSilence(backend, checked((int)(output.Length * silentGrains))); + } + else + { + var queuedMicroseconds = queuedMilliseconds * 1000L; + var quiet = IsQuietMix(grain); + var high = (context.CushionMilliseconds * 1000L) + (context.QueueDepth * grainMicroseconds) + 10_000; + if ((queuedMicroseconds > high && quiet) || queuedMicroseconds > high + 90_000) + { + context.StatsTrims++; + RecordReserveStats(context, queuedMilliseconds); + return true; + } + + if (queuedMicroseconds * 2 < reserve && quiet) + { + SubmitSilence(backend, output.Length); + context.StatsSilentFills++; + } + } + + RecordReserveStats(context, queuedMilliseconds); + return backend.Submit(payload); + } + + private static void SubmitSilence(IHostAudioStream backend, int bytes) + { + if (bytes <= 0) + { + return; + } + + if (_silence.Length < bytes) + { + _silence = new byte[bytes]; + } + + _ = backend.Submit(_silence.AsSpan(0, bytes)); + } + + private static bool IsQuietMix(ReadOnlySpan<float> grain) + { + foreach (var sample in grain) + { + if (sample > QuietSampleLimit || sample < -QuietSampleLimit) + { + return false; + } + } + + return true; + } + + private static void RecordReserveStats(ContextState context, int queuedMilliseconds) + { + if (!LogReserveStats) + { + return; + } + + context.StatsGrains++; + var now = Stopwatch.GetTimestamp(); + if (context.StatsWindowStart == 0) + { + context.StatsWindowStart = now; + return; + } + + var elapsed = now - context.StatsWindowStart; + if (elapsed < Stopwatch.Frequency) + { + return; + } + + var seconds = elapsed / (double)Stopwatch.Frequency; + Console.Error.WriteLine( + $"[PERF][AUDIO_MIX] ctx=0x{context.Handle:X} {seconds:F1}s " + + $"grains/s={context.StatsGrains / seconds:F0} " + + $"expected/s={context.Frequency / (double)context.GrainSamples:F0} " + + $"queued_ms={queuedMilliseconds} " + + $"reserve_ms={Volatile.Read(ref context.ReserveMicroseconds) / 1000} dropouts={context.StatsDropouts} " + + $"stretches={context.StatsStretches} stretched_ms={context.StatsStretchedFrames * 1000.0 / context.Frequency:F0} " + + $"silent_fills={context.StatsSilentFills} trims={context.StatsTrims}"); + + context.StatsWindowStart = now; + context.StatsGrains = 0; + context.StatsDropouts = 0; + context.StatsStretches = 0; + context.StatsStretchedFrames = 0; + context.StatsSilentFills = 0; + context.StatsTrims = 0; + } + internal static byte[]? GetPortPcmSnapshotForTests(ulong portHandle) { if (!Ports.TryGetValue(portHandle, out var port)) From 96fa5d10dc504a09619b26f1cc51d4b71621532e Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:24:36 +0300 Subject: [PATCH 15/64] [AudioOut2] Stretch a late grain by a matched period while the queue is below half its reserve --- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 160 +++++++++++++++++++- 1 file changed, 157 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index 5a92ab105..7cf0aaa44 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -1630,6 +1630,9 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) ? Math.Clamp(reserveMilliseconds, 0, 200) * 1000L : 20_000L; + private static readonly bool GrainStretchEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_AUDIO_STRETCH") != "0"; + private static readonly bool LogReserveStats = string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_LOG_AUDIO_OUT2"), "1", @@ -1644,6 +1647,9 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) private const int MixChannels = 2; private static byte[] _silence = []; + private static byte[] _stretchedOutput = []; + private static float[] _stretchedMix = []; + private static float[] _stretchMono = []; private static long TicksToMicroseconds(long ticks) => ticks * 1_000_000L / Stopwatch.Frequency; @@ -1693,6 +1699,7 @@ private static bool SubmitWithReserve( { var silentGrains = (reserve + grainMicroseconds - 1) / grainMicroseconds; SubmitSilence(backend, checked((int)(output.Length * silentGrains))); + context.RecentFrames = 0; } else { @@ -1706,13 +1713,40 @@ private static bool SubmitWithReserve( return true; } - if (queuedMicroseconds * 2 < reserve && quiet) + if (queuedMicroseconds * 2 < reserve) { - SubmitSilence(backend, output.Length); - context.StatsSilentFills++; + if (quiet) + { + SubmitSilence(backend, output.Length); + context.StatsSilentFills++; + } + else if (GrainStretchEnabled) + { + var added = StretchMixGrain( + context.Recent.AsSpan(0, context.RecentFrames * MixChannels), + grain, + (int)context.Frequency, + ref _stretchedMix); + if (added > 0) + { + var stretchedSamples = (frames + added) * MixChannels; + var bytesPerSample = isFloat ? sizeof(float) : sizeof(short); + if (_stretchedOutput.Length < stretchedSamples * bytesPerSample) + { + _stretchedOutput = new byte[stretchedSamples * bytesPerSample]; + } + + payload = isFloat + ? WriteFloatOutput(_stretchedMix.AsSpan(0, stretchedSamples), _stretchedOutput, out _) + : WritePcm16Output(_stretchedMix.AsSpan(0, stretchedSamples), _stretchedOutput, out _); + context.StatsStretches++; + context.StatsStretchedFrames += added; + } + } } } + RememberRecentGrain(context, grain); RecordReserveStats(context, queuedMilliseconds); return backend.Submit(payload); } @@ -1745,6 +1779,126 @@ private static bool IsQuietMix(ReadOnlySpan<float> grain) return true; } + private static void RememberRecentGrain(ContextState context, ReadOnlySpan<float> grain) + { + var keepFrames = (int)(context.Frequency / 50); + var keep = keepFrames * MixChannels; + if (context.Recent.Length < keep) + { + var grown = new float[keep]; + context.Recent.AsSpan(0, context.RecentFrames * MixChannels).CopyTo(grown); + context.Recent = grown; + } + + if (grain.Length >= keep) + { + grain[^keep..].CopyTo(context.Recent); + context.RecentFrames = keepFrames; + return; + } + + var held = context.RecentFrames * MixChannels; + var overflow = held + grain.Length - keep; + if (overflow > 0) + { + context.Recent.AsSpan(overflow, held - overflow).CopyTo(context.Recent); + held -= overflow; + } + + grain.CopyTo(context.Recent.AsSpan(held)); + context.RecentFrames = (held + grain.Length) / MixChannels; + } + + internal static int StretchMixGrain(ReadOnlySpan<float> history, ReadOnlySpan<float> grain, int frequency, ref float[] output) + { + var historyFrames = history.Length / MixChannels; + var grainFrames = grain.Length / MixChannels; + var total = historyFrames + grainFrames; + var window = Math.Min(grainFrames, frequency / 200); + var fade = Math.Min(grainFrames, frequency * 3 / 1000); + var shortest = frequency / 400; + var longest = Math.Min(frequency * 15 / 1000, total > window ? total - window : 0); + if (window == 0 || fade == 0 || shortest == 0 || longest < shortest) + { + return 0; + } + + if (_stretchMono.Length < total) + { + _stretchMono = new float[total]; + } + + var mono = _stretchMono; + for (var frame = 0; frame < total; frame++) + { + mono[frame] = MixSample(history, grain, historyFrames, frame, 0) + + MixSample(history, grain, historyFrames, frame, 1); + } + + var end = total - window; + var endEnergy = 0f; + for (var k = 0; k < window; k++) + { + endEnergy += mono[end + k] * mono[end + k]; + } + + var lag = shortest; + var best = -2f; + for (var period = shortest; period <= longest; period++) + { + var earlier = end - period; + var dot = 0f; + var energy = 0f; + for (var k = 0; k < window; k++) + { + dot += mono[end + k] * mono[earlier + k]; + energy += mono[earlier + k] * mono[earlier + k]; + } + + var score = dot / MathF.Sqrt((energy * endEnergy) + 1e-20f); + if (score > best) + { + best = score; + lag = period; + } + } + + var outputSamples = (grainFrames + lag) * MixChannels; + if (output.Length < outputSamples) + { + output = new float[outputSamples]; + } + + grain[..((grainFrames - fade) * MixChannels)].CopyTo(output); + for (var frame = grainFrames - fade; frame < grainFrames; frame++) + { + var x = (frame - (grainFrames - fade) + 0.5f) / fade; + var weight = 0.5f - (0.5f * MathF.Cos(MathF.PI * x)); + for (var channel = 0; channel < MixChannels; channel++) + { + output[(frame * MixChannels) + channel] = + ((1f - weight) * MixSample(history, grain, historyFrames, historyFrames + frame, channel)) + + (weight * MixSample(history, grain, historyFrames, historyFrames + frame - lag, channel)); + } + } + + for (var frame = grainFrames; frame < grainFrames + lag; frame++) + { + for (var channel = 0; channel < MixChannels; channel++) + { + output[(frame * MixChannels) + channel] = + MixSample(history, grain, historyFrames, historyFrames + frame - lag, channel); + } + } + + return lag; + } + + private static float MixSample(ReadOnlySpan<float> history, ReadOnlySpan<float> grain, int historyFrames, int frame, int channel) => + frame < historyFrames + ? history[(frame * MixChannels) + channel] + : grain[((frame - historyFrames) * MixChannels) + channel]; + private static void RecordReserveStats(ContextState context, int queuedMilliseconds) { if (!LogReserveStats) From 86aec8128f7c3403172c6ab8cb801c51678ae114 Mon Sep 17 00:00:00 2001 From: Berk <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:47:01 +0300 Subject: [PATCH 16/64] chore: bump version to 0.0.8-ember (#1173) --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 5402f132c..b83fe7228 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -9,7 +9,7 @@ SPDX-License-Identifier: GPL-2.0-or-later <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <GenerateDocumentationFile>true</GenerateDocumentationFile> - <SharpEmuVersion>0.0.7-pulse</SharpEmuVersion> + <SharpEmuVersion>0.0.8-ember</SharpEmuVersion> <Version>$(SharpEmuVersion)</Version> <RepoRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)'))</RepoRoot> From 5036e2761078b4a0a329896a32b705cbffa25378 Mon Sep 17 00:00:00 2001 From: Foued Attar <attar.foued@gmail.com> Date: Tue, 24 Nov 2026 11:25:16 +0100 Subject: [PATCH 17/64] fix(shader): emit the integer reciprocal inline with a Newton step (#1174) VRcpIflagF32 ran through a shared DontInline helper. NVIDIA miscompiles Demon's Souls' half-wave culling compute whenever it contains a real function call, which stretched geometry with lane-local wave64 on. A plain inline 1/x is not enough either: on NVIDIA it is 1 ulp high for some integer inputs, and the AMD unsigned division sequence then returns wrong quotients (e.g. divisors 27012373 and 91382283). Emit 1/x inline and refine it with one fma Newton step, keeping the division result for inf, NaN and zero. Checked on the GPU for every u32 and every positive float: correctly rounded, never worse than the plain division, and every integer division exact. --- .../Gen5SpirvTranslator.Alu.cs | 41 ++++++++----------- .../Gen5SpirvTranslator.cs | 1 - .../Gen5IntegerReciprocalTests.cs | 30 ++++---------- 3 files changed, 24 insertions(+), 48 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs index f8cc4714c..6f94aed60 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs @@ -9,26 +9,6 @@ public static partial class Gen5SpirvTranslator { private sealed partial class CompilationContext { - private uint _integerReciprocalFunction; - - private void DeclareIntegerReciprocalFunction() - { - if (!_request.Program.Instructions.Any(instruction => instruction.Opcode == "VRcpIflagF32")) - { - return; - } - - // Keep integer reciprocal lowering outside the caller's optimization region. - const uint dontInline = 2; - var functionType = _module.TypeFunction(_floatType, _floatType); - _integerReciprocalFunction = _module.BeginFunction(_floatType, functionType, dontInline); - var source = _module.AddFunctionParameter(_floatType); - _module.AddLabel(); - var reciprocal = _module.AddInstruction(SpirvOp.FDiv, _floatType, Float(1), source); - _module.AddStatement(SpirvOp.ReturnValue, reciprocal); - _module.EndFunction(); - } - private bool TryEmitVectorAlu( Gen5ShaderInstruction instruction, out string error) @@ -615,15 +595,26 @@ private bool TryEmitVectorAlu( EmitFlushF32DenormToSignedZero( GetFloatSource(instruction, 0)))); break; + // Inline: NVIDIA miscompiled a shader holding a real call (Demon's Souls half-wave culling compute). + // The fma Newton step keeps the reciprocal within the ~1 ulp the AMD integer division needs, which + // OpFDiv alone does not guarantee; inf/NaN/zero keep the division result. case "VRcpIflagF32": + { + var x = GetFloatSource(instruction, 0); + var r = _module.AddInstruction(SpirvOp.FDiv, _floatType, Float(1), x); + var negX = _module.AddInstruction(SpirvOp.FNegate, _floatType, x); + var e = Ext(50, _floatType, negX, r, Float(1)); + var r1 = Ext(50, _floatType, r, e, r); + var keep = LogicalOr( + LogicalOr( + _module.AddInstruction(SpirvOp.IsInf, _boolType, r), + _module.AddInstruction(SpirvOp.IsNan, _boolType, r)), + _module.AddInstruction(SpirvOp.FOrdEqual, _boolType, r, Float(0))); result = EmitFloatResult( instruction, - _module.AddInstruction( - SpirvOp.FunctionCall, - _floatType, - _integerReciprocalFunction, - GetFloatSource(instruction, 0))); + _module.AddInstruction(SpirvOp.Select, _floatType, keep, r, r1)); break; + } case "VLogF32": result = EmitFloatResult( instruction, diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs index cdf194d84..ff0b0186f 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs @@ -339,7 +339,6 @@ _request.Program.Address is 0x0000000500780000ul or FindLocalComparisonPredicates(blocks); profile.Switch(ShaderTranslationProfile.Part.Declarations); DeclareModule(); - DeclareIntegerReciprocalFunction(); var functionType = _module.TypeFunction(_voidType); var main = _module.BeginFunction(_voidType, functionType); _module.AddName(main, "main"); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5IntegerReciprocalTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5IntegerReciprocalTests.cs index 5d4439c28..da1da3102 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5IntegerReciprocalTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5IntegerReciprocalTests.cs @@ -19,36 +19,22 @@ public sealed class Gen5IntegerReciprocalTests [InlineData(ShaderStage.Compute, 1, true)] [InlineData(ShaderStage.Pixel, 1, false)] [InlineData(ShaderStage.Vertex, 1, false)] - public void IntegerReciprocalUsesOneHelperAndPreservesDivision(ShaderStage stage, int integerCalls, bool ordinary) + public void IntegerReciprocalIsInlineWithNewtonStep(ShaderStage stage, int integerCalls, bool ordinary) { var instructions = new List<Gen5ShaderInstruction>(); for (var index = 0; index < integerCalls; index++) - instructions.Add(Vop1((uint)instructions.Count * 4, "VRcpIflagF32", 2, Gen5Operand.Vector(0))); + instructions.Add(Vop1((uint)instructions.Count * 4, "VRcpIflagF32", (uint)(2 + index), Gen5Operand.Vector((uint)index))); if (ordinary) - instructions.Add(Vop1((uint)instructions.Count * 4, "VRcpF32", 2, Gen5Operand.Vector(0))); + instructions.Add(Vop1((uint)instructions.Count * 4, "VRcpF32", (uint)(2 + integerCalls), Gen5Operand.Vector((uint)integerCalls))); instructions.Add(EndProgram((uint)instructions.Count * 4)); var request = Request(Program([.. instructions]), stage); Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); var module = ReadInstructions(shader.Spirv); - var helpers = module.Where(instruction => instruction.Opcode == SpirvOp.Function && instruction.Operands[2] == 2).ToArray(); - var calls = module.Where(instruction => instruction.Opcode == SpirvOp.FunctionCall).ToArray(); - Assert.Equal(integerCalls == 0 ? 0 : 1, helpers.Length); - Assert.Equal(integerCalls, calls.Length); - Assert.Equal((integerCalls == 0 ? 0 : 1) + (ordinary ? 1 : 0), module.Count(instruction => instruction.Opcode == SpirvOp.FDiv)); - if (integerCalls == 0) return; - - var helper = Assert.Single(helpers).Operands[1]; - Assert.All(calls, call => Assert.Equal(helper, call.Operands[2])); - var start = module.FindIndex(instruction => instruction.Opcode == SpirvOp.Function && instruction.Operands[1] == helper); - var end = module.FindIndex(start + 1, instruction => instruction.Opcode == SpirvOp.FunctionEnd); - Assert.True(end > start); - var body = module.GetRange(start + 1, end - start - 1); - Assert.Equal(new[] { SpirvOp.FunctionParameter, SpirvOp.Label, SpirvOp.FDiv, SpirvOp.ReturnValue }, body.Select(instruction => instruction.Opcode)); - var divide = body[2].Operands; - Assert.Equal(body[0].Operands[1], divide[3]); - Assert.Equal(divide[1], body[3].Operands[0]); - Assert.Contains(module, instruction => instruction.Opcode == SpirvOp.Constant && - instruction.Operands[1] == divide[2] && instruction.Operands[2] == 0x3F800000); + Assert.DoesNotContain(module, instruction => instruction.Opcode == SpirvOp.FunctionCall); + Assert.Single(module, instruction => instruction.Opcode == SpirvOp.Function); + Assert.Equal(integerCalls + (ordinary ? 1 : 0), module.Count(instruction => instruction.Opcode == SpirvOp.FDiv)); + Assert.Equal(2 * integerCalls, module.Count(instruction => instruction.Opcode == SpirvOp.ExtInst && instruction.Operands[3] == 50)); + Assert.True(module.Count(instruction => instruction.Opcode == SpirvOp.Select) >= integerCalls); } private static List<(SpirvOp Opcode, uint[] Operands)> ReadInstructions(byte[] bytes) From 667439fa48fa7015ccdffbef2384db8cf92c0e7e Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:09:04 +0300 Subject: [PATCH 18/64] [AudioOut2] Compare the producer nap against the fixed device cushion instead of the dropout reserve --- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index 7cf0aaa44..06b382613 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -1398,8 +1398,7 @@ public static bool ProducerNeedsPreciseNap(ulong microseconds) sincePush, backend.QueuedMilliseconds, context.GrainSamples, - context.Frequency, - context.CushionMilliseconds); + context.Frequency); } // A nap of at most PreciseNapLimitMicroseconds by a thread that pushed within the last ActiveProducerMilliseconds, while From 111d753a4e8fc45b8da836f69df106991e9301a6 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:09:04 +0300 Subject: [PATCH 19/64] [AudioOut2] Bound spinning producer naps to one thread at a time --- src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index 06b382613..508eb1293 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -1401,6 +1401,28 @@ public static bool ProducerNeedsPreciseNap(ulong microseconds) context.Frequency); } + private static int _preciseNappers; + + internal const int MaxPreciseNappers = 1; + + public static bool TryBeginPreciseNap(ulong microseconds) + { + if (!ProducerNeedsPreciseNap(microseconds)) + { + return false; + } + + if (Interlocked.Increment(ref _preciseNappers) <= MaxPreciseNappers) + { + return true; + } + + Interlocked.Decrement(ref _preciseNappers); + return false; + } + + public static void EndPreciseNap() => Interlocked.Decrement(ref _preciseNappers); + // A nap of at most PreciseNapLimitMicroseconds by a thread that pushed within the last ActiveProducerMilliseconds, while // the device reports less than its cushion less one grain (-1: it cannot report). internal static bool PreciseProducerNap(ulong microseconds, double millisecondsSincePush, int queuedMilliseconds, From 914a40983e38283dd3116ed396af0343895d2705 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:09:04 +0300 Subject: [PATCH 20/64] [Kernel] Spin a usleep only when it claims the producer nap slot --- .../Kernel/KernelRuntimeCompatExports.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs index 52b81b241..160430a02 100644 --- a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs @@ -105,9 +105,17 @@ public static int KernelUsleep(CpuContext ctx) GuestThreadExecution.Scheduler?.Pump(ctx, "sceKernelUsleep"); // An audio producer that runs behind the device naps for the time it asks (a timer wait takes about 0.5 ms). - if (micros > UsleepSpinLimitMicroseconds && Audio.AudioOut2Exports.ProducerNeedsPreciseNap(micros)) + if (micros > UsleepSpinLimitMicroseconds && Audio.AudioOut2Exports.TryBeginPreciseNap(micros)) { - HostHighResolutionSleep.SpinMicroseconds(micros); + try + { + HostHighResolutionSleep.SpinMicroseconds(micros); + } + finally + { + Audio.AudioOut2Exports.EndPreciseNap(); + } + ctx[CpuRegister.Rax] = 0; return (int)OrbisGen2Result.ORBIS_GEN2_OK; } From 482b013dd58702d00d9bc614c7a69baf9766d861 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:50:47 +0300 Subject: [PATCH 21/64] [Pad] Turn vibration port audio into gamepad rumble when no controller output takes it --- src/SharpEmu.HLE/Host/IHostInput.cs | 2 + .../Host/IHostWindowInputSource.cs | 2 + src/SharpEmu.HLE/Host/WindowHostInput.cs | 3 + src/SharpEmu.Libs/Audio/AudioOut2Exports.cs | 41 ++++- src/SharpEmu.Libs/Audio/AudioOutExports.cs | 31 ++++ src/SharpEmu.Libs/Audio/HapticRumble.cs | 140 ++++++++++++++++++ src/SharpEmu.Libs/Pad/HostWindowInput.cs | 13 ++ src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs | 53 ++++++- .../Pad/HostWindowInputTests.cs | 3 + 9 files changed, 278 insertions(+), 10 deletions(-) create mode 100644 src/SharpEmu.Libs/Audio/HapticRumble.cs diff --git a/src/SharpEmu.HLE/Host/IHostInput.cs b/src/SharpEmu.HLE/Host/IHostInput.cs index 853f9abbf..b29d91033 100644 --- a/src/SharpEmu.HLE/Host/IHostInput.cs +++ b/src/SharpEmu.HLE/Host/IHostInput.cs @@ -26,6 +26,8 @@ public interface IHostInput /// <summary>Sets rumble on all connected gamepads; large = strong/left motor.</summary> void SetRumble(byte largeMotor, byte smallMotor); + void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs); + /// <summary> /// Approximates per-trigger vibration on gamepads without independent trigger /// actuators; null leaves that trigger's current value unchanged. diff --git a/src/SharpEmu.HLE/Host/IHostWindowInputSource.cs b/src/SharpEmu.HLE/Host/IHostWindowInputSource.cs index d33329fa5..eee1ef276 100644 --- a/src/SharpEmu.HLE/Host/IHostWindowInputSource.cs +++ b/src/SharpEmu.HLE/Host/IHostWindowInputSource.cs @@ -16,6 +16,8 @@ public interface IHostWindowInputSource void SetRumble(byte largeMotor, byte smallMotor); + void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs); + void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger); void SetAdaptiveTriggerEffect( diff --git a/src/SharpEmu.HLE/Host/WindowHostInput.cs b/src/SharpEmu.HLE/Host/WindowHostInput.cs index d3d5a8f2b..8ca0008d0 100644 --- a/src/SharpEmu.HLE/Host/WindowHostInput.cs +++ b/src/SharpEmu.HLE/Host/WindowHostInput.cs @@ -22,6 +22,9 @@ public int GetGamepadStates(Span<HostGamepadState> destination) => public void SetRumble(byte largeMotor, byte smallMotor) => HostWindowInputSource.Current?.SetRumble(largeMotor, smallMotor); + public void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs) => + HostWindowInputSource.Current?.SetHapticRumble(largeMotor, smallMotor, durationMs); + public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger) => HostWindowInputSource.Current?.SetTriggerRumble(leftTrigger, rightTrigger); diff --git a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs index 508eb1293..9528caefe 100644 --- a/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOut2Exports.cs @@ -1183,6 +1183,11 @@ public static int AudioOut2PortDestroy(CpuContext ctx) { var portHandle = ctx[CpuRegister.Rdi]; var removed = Ports.TryRemove(portHandle, out var port); + if (port is not null && IsVibrationPort(port.PortType) && !ControllerTakes(port)) + { + HapticRumble.Stop(); + } + var n = Interlocked.Increment(ref _portDestroyTraceCount); if (n <= 8 || n % 500 == 0) { @@ -1519,6 +1524,9 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) { mix.AsSpan(0, frames * 2).Clear(); var mixedPorts = 0; + var hapticPorts = 0; + var hapticLeft = 0f; + var hapticRight = 0f; float[]? controllerMix = null; foreach (var port in Ports.Values) { @@ -1553,6 +1561,26 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) continue; } + if (IsVibrationPort(port.PortType)) + { + hapticPorts++; + var hapticBytes = frames * ch * bps; + if (TakePortPcmSnapshot(port) is { } hapticPcm && hapticPcm.Length >= hapticBytes) + { + HapticRumble.MeasurePeaks( + hapticPcm.AsSpan(0, hapticBytes), + frames, + ch, + bps, + isFloat, + port.Gain, + ref hapticLeft, + ref hapticRight); + } + + continue; + } + var pcmData = TakePortPcmSnapshot(port); if (pcmData is null) { @@ -1608,6 +1636,11 @@ private static bool TrySubmitContextAudio(CpuContext ctx, ContextState context) } } + if (hapticPorts > 0) + { + HapticRumble.Update(hapticLeft, hapticRight, frames / (double)context.Frequency); + } + if (mixedPorts == 0) { TraceSubmitSkipped(context, frames, "no-ports"); @@ -2092,11 +2125,15 @@ private static bool IsSnapshotPcmPort(PortState port, int channels) => (RoutesToSpeakers(port.PortType) && (port.PortType & 0xFF) != AudioOut2PortTypeVibration && (!IsObjectPort(port.PortType) || channels == 1)) || - ControllerTakes(port); + ControllerTakes(port) || + (HapticRumble.Enabled && IsVibrationPort(port.PortType)); private static bool IsControllerPort(ushort portType) => !IsObjectPort(portType) && (portType & 0xFF) is AudioOut2PortTypePadSpeaker or AudioOut2PortTypeVibration; + private static bool IsVibrationPort(ushort portType) => + !IsObjectPort(portType) && (portType & 0xFF) == AudioOut2PortTypeVibration; + // A pad speaker or vibration port plays on the controller's own output device, when the host has one. private static bool ControllerTakes(PortState port) => IsControllerPort(port.PortType) && EnsureControllerBackend(port.SamplingFrequency) is not null; @@ -2210,7 +2247,7 @@ internal static void MixPortIntoStereo( } } - private static float ReadNormalizedSample( + internal static float ReadNormalizedSample( ReadOnlySpan<byte> frame, int channel, int bytesPerSample, diff --git a/src/SharpEmu.Libs/Audio/AudioOutExports.cs b/src/SharpEmu.Libs/Audio/AudioOutExports.cs index 2d22936e1..63c7809f7 100644 --- a/src/SharpEmu.Libs/Audio/AudioOutExports.cs +++ b/src/SharpEmu.Libs/Audio/AudioOutExports.cs @@ -246,6 +246,11 @@ public static int AudioOutClose(CpuContext ctx) return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); } + if (port.Type == PortTypeVibration && port.Backend is null) + { + HapticRumble.Stop(); + } + port.Dispose(); return ctx.SetReturn(0); } @@ -370,6 +375,7 @@ public static int AudioOutOutput(CpuContext ctx) if (port.Backend is null) { + FeedHapticRumble(port, source); port.PaceSilence(); return ctx.SetReturn(0); } @@ -501,6 +507,10 @@ private static int SubmitOutputs(CpuContext ctx, ReadOnlySpan<OutputDescriptor> } TraceOutput(output.Handle, output.Port, source); + if (output.Port.Backend is null) + { + FeedHapticRumble(output.Port, source); + } output.HostBufferLength = HostBufferLength(output.Port); output.HostBuffer = ArrayPool<byte>.Shared.Rent(output.HostBufferLength); @@ -597,6 +607,27 @@ private static int PaceShutdownPorts(ReadOnlySpan<OutputDescriptor> descriptors) return 0; } + private static void FeedHapticRumble(PortState port, ReadOnlySpan<byte> source) + { + if (port.Type != PortTypeVibration || !HapticRumble.Enabled) + { + return; + } + + var left = 0f; + var right = 0f; + HapticRumble.MeasurePeaks( + source, + checked((int)port.BufferLength), + port.Channels, + port.BytesPerSample, + port.IsFloat, + port.Volume, + ref left, + ref right); + HapticRumble.Update(left, right, port.BufferLength / (double)port.Frequency); + } + private static int HostBufferLength(PortState port) => port.ControllerPair >= 0 ? checked((int)port.BufferLength * ControllerChannels * sizeof(float)) : port.PreservesGuestFormat ? port.BufferByteLength diff --git a/src/SharpEmu.Libs/Audio/HapticRumble.cs b/src/SharpEmu.Libs/Audio/HapticRumble.cs new file mode 100644 index 000000000..9cf7bc5c4 --- /dev/null +++ b/src/SharpEmu.Libs/Audio/HapticRumble.cs @@ -0,0 +1,140 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using SharpEmu.HLE.Host; + +namespace SharpEmu.Libs.Audio; + +internal static class HapticRumble +{ + private const float NoiseFloor = 0.02f; + private const float FullScale = 0.7f; + private const float Curve = 0.75f; + private const double ReleaseSeconds = 0.08; + private const long MinimumIntervalMs = 16; + private const long RefreshIntervalMs = 100; + private const uint DurationMs = 250; + private const int ChangeThreshold = 6; + + private static readonly float Gain = ReadGain(); + private static readonly object Gate = new(); + private static float _left; + private static float _right; + private static byte _sentLarge; + private static byte _sentSmall; + private static long _sentAt; + + internal static bool Enabled => Gain > 0f; + + internal static void MeasurePeaks( + ReadOnlySpan<byte> source, + int frames, + int channels, + int bytesPerSample, + bool isFloat, + float gain, + ref float left, + ref float right) + { + var frameSize = channels * bytesPerSample; + if (frameSize <= 0) + { + return; + } + + frames = Math.Min(frames, source.Length / frameSize); + for (var frame = 0; frame < frames; frame++) + { + var frameBytes = source.Slice(frame * frameSize, frameSize); + var first = MathF.Abs(AudioOut2Exports.ReadNormalizedSample(frameBytes, 0, bytesPerSample, isFloat) * gain); + var second = channels == 1 + ? first + : MathF.Abs(AudioOut2Exports.ReadNormalizedSample(frameBytes, 1, bytesPerSample, isFloat) * gain); + left = MathF.Max(left, first); + right = MathF.Max(right, second); + } + } + + internal static void Update(float leftPeak, float rightPeak, double seconds) + { + if (!Enabled) + { + return; + } + + lock (Gate) + { + var decay = (float)Math.Exp(-Math.Max(0, seconds) / ReleaseSeconds); + _left = MathF.Max(leftPeak, _left * decay); + _right = MathF.Max(rightPeak, _right * decay); + var large = ToMotor(_left); + var small = ToMotor(_right); + var now = Environment.TickCount64; + if (!ShouldSend(large, small, now - _sentAt)) + { + return; + } + + _sentLarge = large; + _sentSmall = small; + _sentAt = now; + HostPlatform.Current.Input.SetHapticRumble(large, small, DurationMs); + } + } + + internal static void Stop() + { + lock (Gate) + { + _left = 0f; + _right = 0f; + if ((_sentLarge | _sentSmall) == 0) + { + return; + } + + _sentLarge = 0; + _sentSmall = 0; + _sentAt = Environment.TickCount64; + HostPlatform.Current.Input.SetHapticRumble(0, 0, DurationMs); + } + } + + internal static byte ToMotor(float level) + { + var scaled = level * Gain; + if (scaled <= NoiseFloor) + { + return 0; + } + + var normalized = MathF.Min(1f, (scaled - NoiseFloor) / (FullScale - NoiseFloor)); + return (byte)MathF.Round(MathF.Pow(normalized, Curve) * 255f); + } + + private static bool ShouldSend(byte large, byte small, long elapsedMs) + { + var wasRunning = (_sentLarge | _sentSmall) != 0; + if ((large | small) == 0) + { + return wasRunning; + } + + if (!wasRunning || elapsedMs >= RefreshIntervalMs) + { + return true; + } + + return elapsedMs >= MinimumIntervalMs && + (Math.Abs(large - _sentLarge) >= ChangeThreshold || Math.Abs(small - _sentSmall) >= ChangeThreshold); + } + + private static float ReadGain() + { + var value = Environment.GetEnvironmentVariable("SHARPEMU_HAPTIC_RUMBLE_GAIN"); + return float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var gain) && float.IsFinite(gain) + ? Math.Max(0f, gain) + : 0.5f; + } +} diff --git a/src/SharpEmu.Libs/Pad/HostWindowInput.cs b/src/SharpEmu.Libs/Pad/HostWindowInput.cs index be9a999d1..060c68bd6 100644 --- a/src/SharpEmu.Libs/Pad/HostWindowInput.cs +++ b/src/SharpEmu.Libs/Pad/HostWindowInput.cs @@ -245,6 +245,17 @@ public void SetRumble(byte largeMotor, byte smallMotor) output?.SetRumble(largeMotor, smallMotor); } + public void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs) + { + IHostGamepadOutput? output; + lock (Gate) + { + output = _gamepadOutput; + } + + output?.SetHapticRumble(largeMotor, smallMotor, durationMs); + } + public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger) { IHostGamepadOutput? output; @@ -297,6 +308,8 @@ public interface IHostGamepadOutput { void SetRumble(byte largeMotor, byte smallMotor); + void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs); + void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger); void SetAdaptiveTriggerEffect( diff --git a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs index 0cb6aadb8..0e3d3bdd0 100644 --- a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs +++ b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs @@ -32,6 +32,11 @@ internal sealed unsafe class SdlHostWindow : IDisposable, IHostGamepadOutput private HostGamepadType _gamepadType; private byte _leftTriggerRumble; private byte _rightTriggerRumble; + private byte _padLargeRumble; + private byte _padSmallRumble; + private byte _hapticLargeRumble; + private byte _hapticSmallRumble; + private long _hapticRumbleExpires; private int _closeRequested; private bool _closedByUser; private bool _fullscreen; @@ -218,17 +223,44 @@ public void SetRumble(byte largeMotor, byte smallMotor) { lock (_gamepadGate) { - if (IsGamepadConnected()) - { - SDL_RumbleGamepad( - _gamepad, - ExpandByte(largeMotor), - ExpandByte(smallMotor), - OutputDurationMs); - } + _padLargeRumble = largeMotor; + _padSmallRumble = smallMotor; + ApplyRumble(); + } + } + + public void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs) + { + lock (_gamepadGate) + { + _hapticLargeRumble = largeMotor; + _hapticSmallRumble = smallMotor; + _hapticRumbleExpires = Environment.TickCount64 + durationMs; + ApplyRumble(); } } + private void ApplyRumble() + { + if (!IsGamepadConnected()) + { + return; + } + + var hapticRemaining = _hapticRumbleExpires - Environment.TickCount64; + var hapticActive = hapticRemaining > 0; + var large = Math.Max(_padLargeRumble, hapticActive ? _hapticLargeRumble : (byte)0); + var small = Math.Max(_padSmallRumble, hapticActive ? _hapticSmallRumble : (byte)0); + var duration = (_padLargeRumble | _padSmallRumble) == 0 && hapticActive + ? (uint)hapticRemaining + : OutputDurationMs; + SDL_RumbleGamepad( + _gamepad, + ExpandByte(large), + ExpandByte(small), + duration); + } + public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger) { lock (_gamepadGate) @@ -774,6 +806,11 @@ private void CloseGamepad() _gamepadType = HostGamepadType.Generic; _leftTriggerRumble = 0; _rightTriggerRumble = 0; + _padLargeRumble = 0; + _padSmallRumble = 0; + _hapticLargeRumble = 0; + _hapticSmallRumble = 0; + _hapticRumbleExpires = 0; } HostWindowInput.ClearGamepad(); diff --git a/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs b/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs index 129edbefd..7d0e3d9e7 100644 --- a/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs +++ b/tests/SharpEmu.Libs.Tests/Pad/HostWindowInputTests.cs @@ -195,6 +195,9 @@ private sealed class RecordingGamepadOutput : IHostGamepadOutput public void SetRumble(byte largeMotor, byte smallMotor) => Rumble = (largeMotor, smallMotor); + public void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs) => + Rumble = (largeMotor, smallMotor); + public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger) => TriggerRumble = (leftTrigger, rightTrigger); From c88d6b0b2f75df087562627b16ada568334c1437 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:22:35 +0300 Subject: [PATCH 22/64] [Overlay] Add a shared in-game overlay design kit and draw its layers over presented frames --- Directory.Packages.props | 1 + src/SharpEmu.GUI/EmulatorOverlayText.cs | 26 ++ src/SharpEmu.GUI/LaunchConfiguration.cs | 3 + src/SharpEmu.GUI/LauncherThemes.cs | 27 +- src/SharpEmu.GUI/Localization.cs | 17 + src/SharpEmu.Libs/Overlay/OverlayFonts.cs | 135 +++++++ src/SharpEmu.Libs/Overlay/OverlayImages.cs | 55 +++ src/SharpEmu.Libs/Overlay/OverlayLayer.cs | 42 +++ src/SharpEmu.Libs/Overlay/OverlayPainter.cs | 343 ++++++++++++++++++ src/SharpEmu.Libs/Overlay/OverlayPalette.cs | 68 ++++ src/SharpEmu.Libs/Overlay/OverlayPrompts.cs | 22 ++ src/SharpEmu.Libs/Overlay/OverlayStyle.cs | 51 +++ src/SharpEmu.Libs/Overlay/OverlayText.cs | 121 ++++++ src/SharpEmu.Libs/SharpEmu.Libs.csproj | 1 + ...kanVideoPresenter.Present.OverlayLayers.cs | 287 +++++++++++++++ .../VulkanVideoPresenter.Present.Swapchain.cs | 1 + .../VulkanVideoPresenter.RenderLoop.cs | 2 + 17 files changed, 1197 insertions(+), 5 deletions(-) create mode 100644 src/SharpEmu.GUI/EmulatorOverlayText.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayFonts.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayImages.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayLayer.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayPainter.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayPalette.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayPrompts.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayStyle.cs create mode 100644 src/SharpEmu.Libs/Overlay/OverlayText.cs create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.OverlayLayers.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 7736edfd0..98def3495 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -27,6 +27,7 @@ SPDX-License-Identifier: GPL-2.0-or-later <!-- Reuse the font rasterizer already shipped with Avalonia.Skia. --> <PackageVersion Include="SkiaSharp" Version="3.119.4" /> <PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="3.119.4" /> + <PackageVersion Include="SkiaSharp.HarfBuzz" Version="3.119.4" /> <PackageVersion Include="System.IO.Hashing" Version="10.0.0" /> <!-- Transitive of Avalonia.Desktop; pinned. Avalonia 12 requires 0.94.1+. --> <PackageVersion Include="Tmds.DBus.Protocol" Version="0.94.1" /> diff --git a/src/SharpEmu.GUI/EmulatorOverlayText.cs b/src/SharpEmu.GUI/EmulatorOverlayText.cs new file mode 100644 index 000000000..dbbd295f0 --- /dev/null +++ b/src/SharpEmu.GUI/EmulatorOverlayText.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text.Json; +using SharpEmu.Libs.Overlay; + +namespace SharpEmu.GUI; + +internal static class EmulatorOverlayText +{ + public static string Language(GuiSettings settings) => + string.IsNullOrWhiteSpace(settings.Language) ? "en" : settings.Language.Trim(); + + public static string Strings(GuiSettings settings) + { + var localization = new Localization(Localization.LanguagesDirectory); + localization.Load(Language(settings)); + var strings = new Dictionary<string, string>(localization.WithPrefix(OverlayText.KeyPrefix), StringComparer.Ordinal); + return JsonSerializer.Serialize(strings, EmulatorOverlayTextContext.Default.DictionaryStringString); + } +} + +[System.Text.Json.Serialization.JsonSerializable(typeof(Dictionary<string, string>))] +internal sealed partial class EmulatorOverlayTextContext : System.Text.Json.Serialization.JsonSerializerContext +{ +} diff --git a/src/SharpEmu.GUI/LaunchConfiguration.cs b/src/SharpEmu.GUI/LaunchConfiguration.cs index e24912e5e..c4ad33830 100644 --- a/src/SharpEmu.GUI/LaunchConfiguration.cs +++ b/src/SharpEmu.GUI/LaunchConfiguration.cs @@ -82,6 +82,9 @@ public LaunchConfiguration WithOneOff(IReadOnlyList<string>? oneOff) => values["SHARPEMU_GPU_READBACKS"] = string.Equals(Settings.GpuReadbacks, "Off", StringComparison.OrdinalIgnoreCase) ? "off" : "full"; values[DefaultProfileVariable] = GuiSettings.NormalizeDefaultProfile(launcher.DefaultProfile); + values[SharpEmu.Libs.Overlay.OverlayPalette.EnvironmentVariable] = LauncherThemes.EmulatorPalette(launcher); + values[SharpEmu.Libs.Overlay.OverlayText.LanguageVariable] = EmulatorOverlayText.Language(launcher); + values[SharpEmu.Libs.Overlay.OverlayText.StringsVariable] = EmulatorOverlayText.Strings(launcher); values[GnmTrophyPackageReader.KeyEnvironmentName] = string.IsNullOrEmpty(launcher.GnmTrophyKey) ? null : launcher.GnmTrophyKey; values["SHARPEMU_BINK_MODE"] = Settings.BinkPlaybackMode.ToLowerInvariant() switch diff --git a/src/SharpEmu.GUI/LauncherThemes.cs b/src/SharpEmu.GUI/LauncherThemes.cs index 7bf1936e3..3cf1b61b2 100644 --- a/src/SharpEmu.GUI/LauncherThemes.cs +++ b/src/SharpEmu.GUI/LauncherThemes.cs @@ -326,6 +326,27 @@ public static IBrush Brush(string key) => ? brush : Brushes.Transparent; + public static LauncherPalette Resolve(LauncherAppearance appearance) => + AdjustContrast( + IsCustom(appearance.Theme) + ? Derive(appearance.CustomBackground, appearance.CustomAccent) + : Find(appearance.Theme), + appearance.Contrast); + + public static string EmulatorPalette(GuiSettings settings) + { + var palette = Resolve(new LauncherAppearance( + settings.LauncherTheme, + settings.CustomThemeBackground, + settings.CustomThemeAccent, + settings.GlassOpacity, + settings.ThemeContrast)); + return string.Join(',', + palette.Background, palette.Menu, palette.Card, palette.Elevated, palette.RaisedHover, + palette.Text, palette.SecondaryText, palette.Muted, palette.Faint, + palette.Accent, palette.AccentForeground); + } + public static void Apply(LauncherAppearance appearance) { if (Avalonia.Application.Current is not { } app) @@ -333,11 +354,7 @@ public static void Apply(LauncherAppearance appearance) return; } - var palette = AdjustContrast( - IsCustom(appearance.Theme) - ? Derive(appearance.CustomBackground, appearance.CustomAccent) - : Find(appearance.Theme), - appearance.Contrast); + var palette = Resolve(appearance); var background = Color.Parse(palette.Background); var overlay = Color.Parse(palette.Overlay); var field = Color.Parse(palette.Field); diff --git a/src/SharpEmu.GUI/Localization.cs b/src/SharpEmu.GUI/Localization.cs index 1e37aa645..96bd3d8ba 100644 --- a/src/SharpEmu.GUI/Localization.cs +++ b/src/SharpEmu.GUI/Localization.cs @@ -74,6 +74,23 @@ public string Get(string key) public string Format(string key, params object?[] args) => string.Format(Get(key), args); + public IReadOnlyDictionary<string, string> WithPrefix(string prefix) + { + var result = new Dictionary<string, string>(StringComparer.Ordinal); + foreach (var source in new[] { _fallbackStrings, _strings }) + { + foreach (var (key, value) in source) + { + if (key.StartsWith(prefix, StringComparison.Ordinal)) + { + result[key] = value; + } + } + } + + return result; + } + /// <summary> /// Languages available either embedded in the binary or as a loose /// override file, sorted by code. A loose file's declared name wins when diff --git a/src/SharpEmu.Libs/Overlay/OverlayFonts.cs b/src/SharpEmu.Libs/Overlay/OverlayFonts.cs new file mode 100644 index 000000000..29816c2c4 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayFonts.cs @@ -0,0 +1,135 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; +using SkiaSharp; +using SkiaSharp.HarfBuzz; + +namespace SharpEmu.Libs.Overlay; + +internal static class OverlayFonts +{ + private const string Ellipsis = "…"; + + private static readonly object Gate = new(); + private static readonly Dictionary<int, SKTypeface?> Fallbacks = new(); + private static readonly Dictionary<SKTypeface, SKShaper> Shapers = new(); + private static SKTypeface? _light; + private static SKTypeface? _regular; + private static SKTypeface? _bold; + + internal static float Measure(string text, float size, OverlayWeight weight) + { + if (string.IsNullOrEmpty(text)) + { + return 0; + } + + lock (Gate) + { + var typeface = Resolve(text, weight); + using var font = Create(typeface, size); + return Shaper(typeface).Shape(text, font).Width; + } + } + + internal static void Draw(SKCanvas canvas, SKPaint paint, string text, float x, float baseline, float size, + OverlayWeight weight, float maxWidth, SKTextAlign align) + { + if (string.IsNullOrEmpty(text) || maxWidth <= 0) + { + return; + } + + lock (Gate) + { + var typeface = Resolve(text, weight); + using var font = Create(typeface, size); + var shaper = Shaper(typeface); + var fitted = Fit(shaper, font, text, maxWidth); + if (fitted.Length != 0) + { + canvas.DrawShapedText(shaper, fitted, x, baseline, align, font, paint); + } + } + } + + private static string Fit(SKShaper shaper, SKFont font, string text, float maxWidth) + { + if (shaper.Shape(text, font).Width <= maxWidth) + { + return text; + } + + var runes = text.EnumerateRunes().ToArray(); + var low = 0; + var high = runes.Length; + while (low < high) + { + var middle = (low + high + 1) / 2; + if (shaper.Shape(Join(runes, middle) + Ellipsis, font).Width <= maxWidth) + { + low = middle; + } + else + { + high = middle - 1; + } + } + + return low == 0 ? string.Empty : Join(runes, low).TrimEnd() + Ellipsis; + } + + private static string Join(Rune[] runes, int count) + { + var builder = new StringBuilder(); + for (var index = 0; index < count; index++) + { + builder.Append(runes[index].ToString()); + } + + return builder.ToString(); + } + + private static SKFont Create(SKTypeface typeface, float size) => + new(typeface, size) { Edging = SKFontEdging.Antialias, Subpixel = true }; + + private static SKShaper Shaper(SKTypeface typeface) + { + if (!Shapers.TryGetValue(typeface, out var shaper)) + { + shaper = new SKShaper(typeface); + Shapers[typeface] = shaper; + } + + return shaper; + } + + private static SKTypeface Resolve(string text, OverlayWeight weight) + { + var primary = weight switch + { + OverlayWeight.Light => _light ??= SKTypeface.FromFamilyName(null, SKFontStyleWeight.Light, + SKFontStyleWidth.Normal, SKFontStyleSlant.Upright) ?? SKTypeface.Default, + OverlayWeight.Bold => _bold ??= SKTypeface.FromFamilyName(null, SKFontStyle.Bold) ?? SKTypeface.Default, + _ => _regular ??= SKTypeface.FromFamilyName(null) ?? SKTypeface.Default, + }; + foreach (var rune in text.EnumerateRunes()) + { + if (rune.Value < 0x20 || primary.ContainsGlyph(rune.Value)) + { + continue; + } + + if (!Fallbacks.TryGetValue(rune.Value, out var fallback)) + { + fallback = SKFontManager.Default.MatchCharacter(rune.Value); + Fallbacks[rune.Value] = fallback; + } + + return fallback ?? primary; + } + + return primary; + } +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayImages.cs b/src/SharpEmu.Libs/Overlay/OverlayImages.cs new file mode 100644 index 000000000..2fc6b0870 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayImages.cs @@ -0,0 +1,55 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SkiaSharp; + +namespace SharpEmu.Libs.Overlay; + +public sealed class OverlayImages : IDisposable +{ + private readonly object _gate = new(); + private readonly Dictionary<string, SKImage?> _images = new(StringComparer.OrdinalIgnoreCase); + + public SKImage? FromFile(string? path) + { + if (string.IsNullOrEmpty(path)) + { + return null; + } + + lock (_gate) + { + if (!_images.TryGetValue(path, out var image)) + { + try + { + using var data = SKData.Create(path); + image = data is null ? null : SKImage.FromEncodedData(data); + } + catch (IOException) + { + image = null; + } + + _images[path] = image; + } + + return image; + } + } + + public void Clear() + { + lock (_gate) + { + foreach (var image in _images.Values) + { + image?.Dispose(); + } + + _images.Clear(); + } + } + + public void Dispose() => Clear(); +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayLayer.cs b/src/SharpEmu.Libs/Overlay/OverlayLayer.cs new file mode 100644 index 000000000..d3b168e59 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayLayer.cs @@ -0,0 +1,42 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SkiaSharp; + +namespace SharpEmu.Libs.Overlay; + +public abstract class OverlayLayer +{ + private long _revision; + + public long Revision => Interlocked.Read(ref _revision); + + public abstract bool IsVisible { get; } + + public abstract SKRectI Bounds(int surfaceWidth, int surfaceHeight); + + public abstract int Render(SKCanvas canvas, int width, int height, float unit); + + protected void Invalidate() => Interlocked.Increment(ref _revision); + + protected static SKRectI Centered(int surfaceWidth, int surfaceHeight, int width, int height) => + SKRectI.Create((surfaceWidth - width) / 2, (surfaceHeight - height) / 2, width, height); +} + +public static class OverlayLayers +{ + private static readonly object Gate = new(); + private static OverlayLayer[] _layers = []; + + public static T Register<T>(T layer) where T : OverlayLayer + { + lock (Gate) + { + _layers = [.. _layers, layer]; + } + + return layer; + } + + public static OverlayLayer[] Snapshot() => Volatile.Read(ref _layers); +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayPainter.cs b/src/SharpEmu.Libs/Overlay/OverlayPainter.cs new file mode 100644 index 000000000..1eae51904 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayPainter.cs @@ -0,0 +1,343 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SkiaSharp; + +namespace SharpEmu.Libs.Overlay; + +public sealed class OverlayPainter : IDisposable +{ + private static readonly SKColor XboxA = new(0x3F, 0xB9, 0x50); + private static readonly SKColor XboxB = new(0xE5, 0x48, 0x4D); + private static readonly SKColor XboxX = new(0x3B, 0x8E, 0xEA); + private static readonly SKColor XboxY = new(0xF2, 0xB7, 0x05); + + private readonly SKPaint _paint = new() { IsAntialias = true, Style = SKPaintStyle.Fill }; + + public OverlayPainter(SKCanvas canvas, OverlayPalette palette, float unit) + { + Canvas = canvas; + Palette = palette; + Unit = unit; + } + + public SKCanvas Canvas { get; } + + public OverlayPalette Palette { get; } + + public float Unit { get; } + + public float U(float value) => value * Unit; + + public static unsafe int RenderInto(Span<byte> bgra, int width, int height, Func<SKCanvas, int> render) + { + if (width <= 0 || height <= 0 || bgra.Length != checked(width * height * 4)) + { + throw new ArgumentException("The overlay pixel buffer must match its dimensions.", nameof(bgra)); + } + + fixed (byte* address = bgra) + { + using var bitmap = new SKBitmap(); + if (!bitmap.InstallPixels( + new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul), + (nint)address, + width * 4)) + { + throw new InvalidOperationException("The overlay pixel buffer cannot be drawn."); + } + + using var canvas = new SKCanvas(bitmap); + var used = render(canvas); + canvas.Flush(); + return Math.Clamp(used, 1, height); + } + } + + public void Surface(float width, float height) + { + Canvas.Clear(Palette.Background); + Outline(new SKRect(0, 0, width, height), 0, Palette.Raised); + } + + public void Band(SKRect rect, bool lineAbove) + { + Rect(rect, Palette.Menu); + var line = Math.Max(1, Unit); + Rect(lineAbove + ? new SKRect(rect.Left, rect.Top, rect.Right, rect.Top + line) + : new SKRect(rect.Left, rect.Bottom - line, rect.Right, rect.Bottom), Palette.Raised); + } + + public void Rect(SKRect rect, SKColor color) + { + _paint.Style = SKPaintStyle.Fill; + _paint.Color = color; + Canvas.DrawRect(rect, _paint); + } + + public void RoundRect(SKRect rect, float radius, SKColor color) + { + _paint.Style = SKPaintStyle.Fill; + _paint.Color = color; + Canvas.DrawRoundRect(rect, radius, radius, _paint); + } + + public void Outline(SKRect rect, float radius, SKColor color, float width = 1) + { + _paint.Style = SKPaintStyle.Stroke; + _paint.StrokeWidth = Math.Max(1, U(width)); + _paint.Color = color; + var inner = rect; + inner.Inflate(-_paint.StrokeWidth / 2, -_paint.StrokeWidth / 2); + if (radius > 0) + { + Canvas.DrawRoundRect(inner, radius, radius, _paint); + } + else + { + Canvas.DrawRect(inner, _paint); + } + + _paint.Style = SKPaintStyle.Fill; + } + + public void Divider(float x, float y, float width) => + Rect(new SKRect(x, y, x + width, y + Math.Max(1, Unit)), Palette.Raised.WithAlpha(0xB0)); + + public float Measure(string text, OverlayFont font) => OverlayFonts.Measure(text, U(font.Size), font.Weight); + + public void Text(string? text, float x, float baseline, OverlayFont font, SKColor color, float maxWidth, + SKTextAlign align = SKTextAlign.Left) + { + if (string.IsNullOrEmpty(text)) + { + return; + } + + _paint.Style = SKPaintStyle.Fill; + _paint.Color = color; + OverlayFonts.Draw(Canvas, _paint, text, x, baseline, U(font.Size), font.Weight, maxWidth, align); + } + + public void Card(SKRect bounds, bool focused) + { + var radius = U(OverlayStyle.CardRadius); + if (focused) + { + using var glow = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, U(OverlayStyle.FocusGlow)); + _paint.MaskFilter = glow; + _paint.Color = Palette.Accent.WithAlpha(0x55); + Canvas.DrawRoundRect(bounds, radius, radius, _paint); + _paint.MaskFilter = null; + } + + RoundRect(bounds, radius, focused ? Palette.Elevated : Palette.Card.WithAlpha(0xD8)); + if (focused) + { + Outline(bounds, radius, Palette.Accent, OverlayStyle.FocusRingWidth); + } + } + + public void Image(SKImage? image, SKRect rect, float radius, string? placeholder = null, bool plus = false) + { + Canvas.Save(); + Canvas.ClipRoundRect(new SKRoundRect(rect, radius, radius), antialias: true); + if (image is not null) + { + var scale = Math.Max(rect.Width / image.Width, rect.Height / image.Height); + var sourceWidth = rect.Width / scale; + var sourceHeight = rect.Height / scale; + var source = SKRect.Create((image.Width - sourceWidth) / 2, (image.Height - sourceHeight) / 2, + sourceWidth, sourceHeight); + Canvas.DrawImage(image, source, rect, new SKSamplingOptions(SKCubicResampler.Mitchell)); + } + else + { + Rect(rect, Palette.Raised); + if (plus) + { + var arm = Math.Min(rect.Width, rect.Height) * 0.18f; + _paint.Style = SKPaintStyle.Stroke; + _paint.StrokeWidth = Math.Max(2, Math.Min(rect.Width, rect.Height) * 0.05f); + _paint.StrokeCap = SKStrokeCap.Round; + _paint.Color = Palette.Muted; + Canvas.DrawLine(rect.MidX - arm, rect.MidY, rect.MidX + arm, rect.MidY, _paint); + Canvas.DrawLine(rect.MidX, rect.MidY - arm, rect.MidX, rect.MidY + arm, _paint); + _paint.Style = SKPaintStyle.Fill; + } + else if (!string.IsNullOrEmpty(placeholder)) + { + var initial = placeholder.EnumerateRunes().First().ToString().ToUpperInvariant(); + var size = rect.Height * 0.5f; + _paint.Color = Palette.Muted; + OverlayFonts.Draw(Canvas, _paint, initial, rect.MidX, rect.MidY + size * 0.36f, size, + OverlayWeight.Light, rect.Width, SKTextAlign.Center); + } + } + + Canvas.Restore(); + } + + public void ScrollBar(SKRect track, int first, int visible, int total) + { + if (total <= visible) + { + return; + } + + var radius = track.Width / 2; + RoundRect(track, radius, Palette.Raised.WithAlpha(0xC0)); + var thumbHeight = Math.Max(U(28), track.Height * visible / total); + var thumbTop = track.Top + (track.Height - thumbHeight) * first / Math.Max(1, total - visible); + RoundRect(new SKRect(track.Left, thumbTop, track.Right, thumbTop + thumbHeight), radius, Palette.Muted); + } + + public void Dim(SKRect rect, byte alpha = 0xA8) => Rect(rect, new SKColor(0, 0, 0, alpha)); + + public void Modal(SKRect box) + { + var radius = U(OverlayStyle.ModalRadius); + using (var shadow = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, U(18))) + { + _paint.MaskFilter = shadow; + _paint.Color = new SKColor(0, 0, 0, 0x90); + Canvas.DrawRoundRect(box, radius, radius, _paint); + _paint.MaskFilter = null; + } + + RoundRect(box, radius, Palette.Menu); + Outline(box, radius, Palette.Raised); + } + + public float PromptsWidth(IReadOnlyList<OverlayPrompt> prompts, OverlayInputScheme scheme) + { + var width = 0f; + foreach (var prompt in prompts) + { + width += GlyphWidth(prompt, scheme) + U(9) + Measure(prompt.Label, OverlayStyle.Label); + } + + return width + Math.Max(0, prompts.Count - 1) * U(OverlayStyle.PromptSpacing); + } + + public void Prompts(IReadOnlyList<OverlayPrompt> prompts, OverlayInputScheme scheme, float x, float middle) + { + foreach (var prompt in prompts) + { + x += Glyph(prompt, scheme, x, middle) + U(9); + var labelWidth = Measure(prompt.Label, OverlayStyle.Label); + Text(prompt.Label, x, middle + U(6), OverlayStyle.Label, Palette.Secondary, labelWidth + 1); + x += labelWidth + U(OverlayStyle.PromptSpacing); + } + } + + public void Dispose() => _paint.Dispose(); + + private float GlyphWidth(OverlayPrompt prompt, OverlayInputScheme scheme) => + scheme == OverlayInputScheme.Keyboard + ? Measure(prompt.KeyLabel, OverlayStyle.KeyCap) + U(18) + : U(OverlayStyle.PromptGlyphRadius * 2); + + private float Glyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, float middle) + { + var width = GlyphWidth(prompt, scheme); + var radius = U(OverlayStyle.PromptGlyphRadius); + var cx = x + width / 2; + if (scheme == OverlayInputScheme.Keyboard) + { + var key = SKRect.Create(x, middle - U(14), width, U(28)); + RoundRect(key, U(6), Palette.Elevated); + Outline(key, U(6), Palette.Faint); + Rect(new SKRect(key.Left + U(5), key.Bottom - U(2.5f), key.Right - U(5), key.Bottom - U(2.5f) + Math.Max(1, Unit)), + Palette.Faint); + Text(prompt.KeyLabel, cx, middle + U(5), OverlayStyle.KeyCap, Palette.Text, width, SKTextAlign.Center); + return width; + } + + if (scheme == OverlayInputScheme.Xbox && prompt.Button != OverlayButton.DirectionalPad) + { + var (fill, letter, ink) = prompt.Button switch + { + OverlayButton.Confirm => (XboxA, "A", SKColors.White), + OverlayButton.Cancel => (XboxB, "B", SKColors.White), + OverlayButton.Square => (XboxX, "X", SKColors.White), + _ => (XboxY, "Y", new SKColor(0x1A, 0x1A, 0x1A)), + }; + _paint.Style = SKPaintStyle.Fill; + _paint.Color = fill; + Canvas.DrawCircle(cx, middle, radius, _paint); + Text(letter, cx, middle + U(6), new OverlayFont(17, OverlayWeight.Bold), ink, width, SKTextAlign.Center); + return width; + } + + _paint.Style = SKPaintStyle.Fill; + _paint.Color = Palette.Elevated; + Canvas.DrawCircle(cx, middle, radius, _paint); + _paint.Style = SKPaintStyle.Stroke; + _paint.StrokeWidth = Math.Max(1, U(1.2f)); + _paint.Color = Palette.Faint; + Canvas.DrawCircle(cx, middle, radius, _paint); + Symbol(prompt.Button, scheme, cx, middle, radius); + _paint.Style = SKPaintStyle.Fill; + return width; + } + + private void Symbol(OverlayButton button, OverlayInputScheme scheme, float cx, float cy, float radius) + { + _paint.Style = SKPaintStyle.Stroke; + _paint.StrokeWidth = Math.Max(1.2f, U(1.8f)); + _paint.StrokeCap = SKStrokeCap.Round; + _paint.StrokeJoin = SKStrokeJoin.Round; + _paint.Color = Palette.Text; + var size = radius * 0.44f; + using var path = new SKPath(); + switch (button) + { + case OverlayButton.Confirm: + Canvas.DrawLine(cx - size, cy - size, cx + size, cy + size, _paint); + Canvas.DrawLine(cx - size, cy + size, cx + size, cy - size, _paint); + break; + case OverlayButton.Cancel: + Canvas.DrawCircle(cx, cy, size * 1.05f, _paint); + break; + case OverlayButton.Triangle: + path.MoveTo(cx, cy - size * 1.15f); + path.LineTo(cx + size * 1.1f, cy + size * 0.8f); + path.LineTo(cx - size * 1.1f, cy + size * 0.8f); + path.Close(); + Canvas.DrawPath(path, _paint); + break; + case OverlayButton.Square: + Canvas.DrawRect(SKRect.Create(cx - size * 0.9f, cy - size * 0.9f, size * 1.8f, size * 1.8f), _paint); + break; + default: + _paint.Style = SKPaintStyle.Fill; + if (scheme == OverlayInputScheme.Xbox) + { + var arm = size * 1.25f; + var thick = size * 0.62f; + Canvas.DrawRoundRect(SKRect.Create(cx - thick / 2, cy - arm, thick, arm * 2), Unit, Unit, _paint); + Canvas.DrawRoundRect(SKRect.Create(cx - arm, cy - thick / 2, arm * 2, thick), Unit, Unit, _paint); + } + else + { + var half = size * 0.8f; + var gap = size * 0.25f; + path.MoveTo(cx, cy - gap - half * 1.5f); + path.LineTo(cx - half, cy - gap); + path.LineTo(cx + half, cy - gap); + path.Close(); + path.MoveTo(cx, cy + gap + half * 1.5f); + path.LineTo(cx - half, cy + gap); + path.LineTo(cx + half, cy + gap); + path.Close(); + Canvas.DrawPath(path, _paint); + } + + break; + } + + _paint.Style = SKPaintStyle.Fill; + } +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayPalette.cs b/src/SharpEmu.Libs/Overlay/OverlayPalette.cs new file mode 100644 index 000000000..05edb9aca --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayPalette.cs @@ -0,0 +1,68 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SkiaSharp; + +namespace SharpEmu.Libs.Overlay; + +public sealed record OverlayPalette( + SKColor Background, + SKColor Menu, + SKColor Card, + SKColor Elevated, + SKColor Raised, + SKColor Text, + SKColor Secondary, + SKColor Muted, + SKColor Faint, + SKColor Accent, + SKColor AccentForeground) +{ + public const string EnvironmentVariable = "SHARPEMU_UI_PALETTE"; + + private static readonly Lazy<OverlayPalette> Configured = + new(() => Parse(Environment.GetEnvironmentVariable(EnvironmentVariable)) ?? Graphite); + + public static OverlayPalette Graphite { get; } = new( + new SKColor(0x11, 0x11, 0x11), + new SKColor(0x19, 0x19, 0x19), + new SKColor(0x22, 0x22, 0x22), + new SKColor(0x2A, 0x2A, 0x2A), + new SKColor(0x31, 0x31, 0x31), + new SKColor(0xF5, 0xF5, 0xF5), + new SKColor(0xC8, 0xC8, 0xC8), + new SKColor(0x98, 0x98, 0x98), + new SKColor(0x60, 0x60, 0x60), + new SKColor(0xF2, 0xF2, 0xF2), + new SKColor(0x11, 0x11, 0x11)); + + public static OverlayPalette Current => Configured.Value; + + public static OverlayPalette? Parse(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + var parts = value.Split(',', StringSplitOptions.TrimEntries); + if (parts.Length != 11) + { + return null; + } + + var colors = new SKColor[parts.Length]; + for (var index = 0; index < parts.Length; index++) + { + if (!SKColor.TryParse(parts[index], out colors[index])) + { + return null; + } + + colors[index] = colors[index].WithAlpha(0xFF); + } + + return new OverlayPalette(colors[0], colors[1], colors[2], colors[3], colors[4], colors[5], colors[6], + colors[7], colors[8], colors[9], colors[10]); + } +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs b/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs new file mode 100644 index 000000000..8fc998478 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs @@ -0,0 +1,22 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Overlay; + +public enum OverlayInputScheme +{ + Keyboard, + PlayStation, + Xbox, +} + +public enum OverlayButton +{ + Confirm, + Cancel, + Triangle, + Square, + DirectionalPad, +} + +public readonly record struct OverlayPrompt(OverlayButton Button, string Label, string KeyLabel); diff --git a/src/SharpEmu.Libs/Overlay/OverlayStyle.cs b/src/SharpEmu.Libs/Overlay/OverlayStyle.cs new file mode 100644 index 000000000..df33d1dc7 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayStyle.cs @@ -0,0 +1,51 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SkiaSharp; + +namespace SharpEmu.Libs.Overlay; + +public enum OverlayWeight +{ + Light, + Regular, + Bold, +} + +public readonly record struct OverlayFont(float Size, OverlayWeight Weight); + +public static class OverlayStyle +{ + public const float ReferenceHeight = 1080f; + public const float Density = 0.84f; + + public static readonly OverlayFont Display = new(38, OverlayWeight.Light); + public static readonly OverlayFont Headline = new(31, OverlayWeight.Bold); + public static readonly OverlayFont Title = new(21, OverlayWeight.Bold); + public static readonly OverlayFont Body = new(18, OverlayWeight.Regular); + public static readonly OverlayFont Detail = new(16, OverlayWeight.Regular); + public static readonly OverlayFont Label = new(17, OverlayWeight.Regular); + public static readonly OverlayFont Caption = new(15, OverlayWeight.Regular); + public static readonly OverlayFont CaptionStrong = new(15, OverlayWeight.Bold); + public static readonly OverlayFont Overline = new(14, OverlayWeight.Bold); + public static readonly OverlayFont KeyCap = new(14, OverlayWeight.Bold); + + public const float Padding = 34; + public const float Gap = 10; + public const float CardRadius = 10; + public const float ImageRadius = 6; + public const float HeroImageRadius = 14; + public const float ModalRadius = 16; + public const float FocusRingWidth = 2.5f; + public const float FocusGlow = 9; + public const float HeaderHeight = 112; + public const float FooterHeight = 70; + public const float ListRowHeight = 112; + public const float PromptSpacing = 26; + public const float PromptGlyphRadius = 15; + + public static readonly SKColor Notice = new(0xF5, 0xC4, 0x6E); + + public static float UnitFor(float surfaceHeight) => + Math.Clamp(surfaceHeight / ReferenceHeight * Density, 0.7f, 3f); +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayText.cs b/src/SharpEmu.Libs/Overlay/OverlayText.cs new file mode 100644 index 000000000..d6edfddea --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayText.cs @@ -0,0 +1,121 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using System.Text.Json; + +namespace SharpEmu.Libs.Overlay; + +public static class OverlayText +{ + public const string LanguageVariable = "SHARPEMU_UI_LANGUAGE"; + public const string StringsVariable = "SHARPEMU_UI_STRINGS"; + public const string KeyPrefix = "Overlay."; + + private static readonly Lazy<Dictionary<string, string>> Strings = new(LoadStrings); + private static readonly Lazy<CultureInfo> LoadedCulture = new(LoadCulture); + + public static CultureInfo Culture => LoadedCulture.Value; + + public static string Get(string key, string fallback) => + Strings.Value.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) ? value : fallback; + + public static CultureInfo CultureFor(string? code) + { + var name = code?.Trim().ToLowerInvariant() switch + { + null or "" => null, + "br" => "pt-BR", + "pt" => "pt-PT", + "dk" => "da-DK", + "ee" => "et-EE", + "zh" => "zh-CN", + var other => other, + }; + if (name is null) + { + return CultureInfo.CurrentCulture; + } + + try + { + return CultureInfo.GetCultureInfo(name); + } + catch (CultureNotFoundException) + { + return CultureInfo.CurrentCulture; + } + } + + public static string FormatDate(DateTime utc) => FormatDate(utc, Culture); + + public static string FormatDate(DateTime utc, CultureInfo culture) + { + var local = utc.ToLocalTime(); + if (culture.TextInfo.IsRightToLeft) + { + return local.ToString("yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture); + } + + return local.ToString(culture.DateTimeFormat.ShortDatePattern, culture) + " " + + local.ToString(culture.DateTimeFormat.ShortTimePattern, culture); + } + + public static string FormatSize(long bytes) => FormatSize(bytes, Culture); + + public static string FormatSize(long bytes, CultureInfo culture) + { + if (culture.TextInfo.IsRightToLeft) + { + culture = CultureInfo.InvariantCulture; + } + + if (bytes < 1024) + { + return string.Create(culture, $"{bytes} B"); + } + + if (bytes < 1024 * 1024) + { + return string.Create(culture, $"{bytes / 1024.0:0.#} KB"); + } + + return bytes < 1024L * 1024 * 1024 + ? string.Create(culture, $"{bytes / (1024.0 * 1024):0.#} MB") + : string.Create(culture, $"{bytes / (1024.0 * 1024 * 1024):0.##} GB"); + } + + private static Dictionary<string, string> LoadStrings() + { + var strings = new Dictionary<string, string>(StringComparer.Ordinal); + var configured = Environment.GetEnvironmentVariable(StringsVariable); + if (string.IsNullOrWhiteSpace(configured)) + { + return strings; + } + + try + { + using var document = JsonDocument.Parse(configured); + if (document.RootElement.ValueKind != JsonValueKind.Object) + { + return strings; + } + + foreach (var property in document.RootElement.EnumerateObject()) + { + if (property.Value.ValueKind == JsonValueKind.String && property.Value.GetString() is { } value) + { + strings[property.Name] = value; + } + } + } + catch (JsonException) + { + } + + return strings; + } + + private static CultureInfo LoadCulture() => CultureFor(Environment.GetEnvironmentVariable(LanguageVariable)); +} diff --git a/src/SharpEmu.Libs/SharpEmu.Libs.csproj b/src/SharpEmu.Libs/SharpEmu.Libs.csproj index e04d960bd..5040d4639 100644 --- a/src/SharpEmu.Libs/SharpEmu.Libs.csproj +++ b/src/SharpEmu.Libs/SharpEmu.Libs.csproj @@ -37,6 +37,7 @@ SPDX-License-Identifier: GPL-2.0-or-later <PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" /> <PackageReference Include="SkiaSharp" /> <PackageReference Include="SkiaSharp.NativeAssets.Linux" /> + <PackageReference Include="SkiaSharp.HarfBuzz" /> <PackageReference Include="System.IO.Hashing" /> </ItemGroup> diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.OverlayLayers.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.OverlayLayers.cs new file mode 100644 index 000000000..b5e6cefa7 --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.OverlayLayers.cs @@ -0,0 +1,287 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.Libs.Overlay; +using SkiaSharp; +using Silk.NET.Vulkan; +using VkBuffer = Silk.NET.Vulkan.Buffer; + +internal static unsafe partial class VulkanVideoPresenter +{ + private sealed partial class Presenter + { + private readonly Dictionary<OverlayLayer, LayerTarget> _layerTargets = new(ReferenceEqualityComparer.Instance); + + private sealed class LayerTarget + { + public Image Image; + public DeviceMemory ImageMemory; + public bool Initialized; + public SKRectI Bounds; + public int UsedHeight; + public long ImageRevision = -1; + public long PixelsRevision = -1; + public byte[] Pixels = []; + public VkBuffer[] Staging = []; + public DeviceMemory[] StagingMemory = []; + public nint[] StagingMapped = []; + } + + private void RecordOverlayLayers(uint imageIndex, int frameSlot) + { + foreach (var layer in OverlayLayers.Snapshot()) + { + var revision = layer.Revision; + if (!layer.IsVisible) + { + continue; + } + + if (!_layerTargets.TryGetValue(layer, out var target)) + { + var bounds = layer.Bounds((int)_extent.Width, (int)_extent.Height); + if (bounds.Width <= 0 || bounds.Height <= 0 || bounds.Left < 0 || bounds.Top < 0 || + bounds.Right > _extent.Width || bounds.Bottom > _extent.Height) + { + continue; + } + + target = CreateLayerTarget(bounds); + _layerTargets[layer] = target; + } + + if (target.StagingMapped.Length <= frameSlot) + { + continue; + } + + if (target.ImageRevision != revision) + { + if (target.PixelsRevision != revision) + { + var unit = OverlayStyle.UnitFor(_extent.Height); + target.UsedHeight = OverlayPainter.RenderInto( + target.Pixels, + target.Bounds.Width, + target.Bounds.Height, + canvas => layer.Render(canvas, target.Bounds.Width, target.Bounds.Height, unit)); + target.PixelsRevision = revision; + } + + RecordLayerUpload(target, frameSlot); + target.ImageRevision = revision; + } + + RecordLayerCopy(target, imageIndex); + } + } + + private LayerTarget CreateLayerTarget(SKRectI bounds) + { + var target = new LayerTarget { Bounds = bounds, Pixels = new byte[checked(bounds.Width * bounds.Height * 4)] }; + var bytes = (ulong)target.Pixels.Length; + var imageInfo = new ImageCreateInfo + { + SType = StructureType.ImageCreateInfo, + ImageType = ImageType.Type2D, + Format = Format.B8G8R8A8Unorm, + Extent = new Extent3D((uint)bounds.Width, (uint)bounds.Height, 1), + MipLevels = 1, + ArrayLayers = 1, + Samples = SampleCountFlags.Count1Bit, + Tiling = ImageTiling.Optimal, + Usage = ImageUsageFlags.TransferDstBit | ImageUsageFlags.TransferSrcBit, + SharingMode = SharingMode.Exclusive, + InitialLayout = ImageLayout.Undefined, + }; + Check(_vk.CreateImage(_device, &imageInfo, null, out target.Image), "vkCreateImage(overlay layer)"); + _vk.GetImageMemoryRequirements(_device, target.Image, out var requirements); + var memoryInfo = new MemoryAllocateInfo + { + SType = StructureType.MemoryAllocateInfo, + AllocationSize = requirements.Size, + MemoryTypeIndex = FindMemoryType(requirements.MemoryTypeBits, MemoryPropertyFlags.DeviceLocalBit), + }; + Check(_deviceInfo.AllocateMemory(memoryInfo, out target.ImageMemory), "vkAllocateMemory(overlay layer)"); + Check(_vk.BindImageMemory(_device, target.Image, target.ImageMemory, 0), "vkBindImageMemory(overlay layer)"); + + target.Staging = new VkBuffer[MaxFramesInFlight]; + target.StagingMemory = new DeviceMemory[MaxFramesInFlight]; + target.StagingMapped = new nint[MaxFramesInFlight]; + for (var slot = 0; slot < MaxFramesInFlight; slot++) + { + target.Staging[slot] = CreateBuffer( + bytes, + BufferUsageFlags.TransferSrcBit, + MemoryPropertyFlags.HostVisibleBit | MemoryPropertyFlags.HostCoherentBit, + out target.StagingMemory[slot]); + void* mapped; + Check( + _vk.MapMemory(_device, target.StagingMemory[slot], 0, bytes, 0, &mapped), + "vkMapMemory(overlay layer staging)"); + target.StagingMapped[slot] = (nint)mapped; + } + + return target; + } + + private void DestroyOverlayLayerTargets() + { + foreach (var target in _layerTargets.Values) + { + if (target.Image.Handle != 0) + { + _vk.DestroyImage(_device, target.Image, null); + } + if (target.ImageMemory.Handle != 0) + { + _deviceInfo.FreeMemory(target.ImageMemory); + } + for (var slot = 0; slot < target.Staging.Length; slot++) + { + if (target.Staging[slot].Handle != 0) + { + _vk.DestroyBuffer(_device, target.Staging[slot], null); + } + if (target.StagingMemory[slot].Handle != 0) + { + _deviceInfo.FreeMemory(target.StagingMemory[slot]); + } + } + } + + _layerTargets.Clear(); + } + + private void RecordLayerUpload(LayerTarget target, int frameSlot) + { + fixed (byte* source = target.Pixels) + { + System.Buffer.MemoryCopy( + source, + (void*)target.StagingMapped[frameSlot], + target.Pixels.Length, + target.Pixels.Length); + } + + var toTransferDst = new ImageMemoryBarrier2 + { + SType = StructureType.ImageMemoryBarrier2, + SrcAccessMask = target.Initialized ? AccessFlags2.TransferReadBit : 0, + DstAccessMask = AccessFlags2.TransferWriteBit, + OldLayout = target.Initialized ? ImageLayout.TransferSrcOptimal : ImageLayout.Undefined, + NewLayout = ImageLayout.TransferDstOptimal, + SrcQueueFamilyIndex = Vk.QueueFamilyIgnored, + DstQueueFamilyIndex = Vk.QueueFamilyIgnored, + Image = target.Image, + SubresourceRange = ColorSubresourceRange(), + }; + VulkanSynchronization.PipelineBarrier(_vk, + _commandBuffer, + PipelineStageFlags.TransferBit, + PipelineStageFlags.TransferBit, + 0, 0, null, 0, null, 1, &toTransferDst); + + var copyRegion = new BufferImageCopy + { + ImageSubresource = new ImageSubresourceLayers(ImageAspectFlags.ColorBit, 0, 0, 1), + ImageExtent = new Extent3D((uint)target.Bounds.Width, (uint)target.Bounds.Height, 1), + }; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdCopyBufferToImage( + _commandBuffer, + target.Staging[frameSlot], + target.Image, + ImageLayout.TransferDstOptimal, + 1, + ©Region); + } + + var toTransferSrc = new ImageMemoryBarrier2 + { + SType = StructureType.ImageMemoryBarrier2, + SrcAccessMask = AccessFlags2.TransferWriteBit, + DstAccessMask = AccessFlags2.TransferReadBit, + OldLayout = ImageLayout.TransferDstOptimal, + NewLayout = ImageLayout.TransferSrcOptimal, + SrcQueueFamilyIndex = Vk.QueueFamilyIgnored, + DstQueueFamilyIndex = Vk.QueueFamilyIgnored, + Image = target.Image, + SubresourceRange = ColorSubresourceRange(), + }; + VulkanSynchronization.PipelineBarrier(_vk, + _commandBuffer, + PipelineStageFlags.TransferBit, + PipelineStageFlags.TransferBit, + 0, 0, null, 0, null, 1, &toTransferSrc); + target.Initialized = true; + } + + private void RecordLayerCopy(LayerTarget target, uint imageIndex) + { + var presentationTarget = PresentationTargetImage(imageIndex); + var toTransferDst = new ImageMemoryBarrier2 + { + SType = StructureType.ImageMemoryBarrier2, + SrcAccessMask = 0, + DstAccessMask = AccessFlags2.TransferWriteBit, + OldLayout = PresentationTargetFinalLayout, + NewLayout = ImageLayout.TransferDstOptimal, + SrcQueueFamilyIndex = Vk.QueueFamilyIgnored, + DstQueueFamilyIndex = Vk.QueueFamilyIgnored, + Image = presentationTarget, + SubresourceRange = ColorSubresourceRange(), + }; + VulkanSynchronization.PipelineBarrier(_vk, + _commandBuffer, + PipelineStageFlags.TransferBit | PipelineStageFlags.ColorAttachmentOutputBit, + PipelineStageFlags.TransferBit, + 0, 0, null, 0, null, 1, &toTransferDst); + + var copy = new ImageCopy + { + SrcSubresource = new ImageSubresourceLayers(ImageAspectFlags.ColorBit, 0, 0, 1), + DstSubresource = new ImageSubresourceLayers(ImageAspectFlags.ColorBit, 0, 0, 1), + SrcOffset = new Offset3D(0, 0, 0), + DstOffset = new Offset3D( + target.Bounds.Left, + target.Bounds.Top + (target.Bounds.Height - target.UsedHeight) / 2, + 0), + Extent = new Extent3D((uint)target.Bounds.Width, (uint)target.UsedHeight, 1), + }; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdCopyImage( + _commandBuffer, + target.Image, + ImageLayout.TransferSrcOptimal, + presentationTarget, + ImageLayout.TransferDstOptimal, + 1, + ©); + } + + var toFinal = new ImageMemoryBarrier2 + { + SType = StructureType.ImageMemoryBarrier2, + SrcAccessMask = AccessFlags2.TransferWriteBit, + DstAccessMask = _hdrOutputActive ? AccessFlags2.ShaderReadBit : 0, + OldLayout = ImageLayout.TransferDstOptimal, + NewLayout = PresentationTargetFinalLayout, + SrcQueueFamilyIndex = Vk.QueueFamilyIgnored, + DstQueueFamilyIndex = Vk.QueueFamilyIgnored, + Image = presentationTarget, + SubresourceRange = ColorSubresourceRange(), + }; + VulkanSynchronization.PipelineBarrier(_vk, + _commandBuffer, + PipelineStageFlags.TransferBit, + _hdrOutputActive ? PipelineStageFlags.FragmentShaderBit : PipelineStageFlags.BottomOfPipeBit, + 0, 0, null, 0, null, 1, &toFinal); + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.Swapchain.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.Swapchain.cs index 526d59993..c06935d80 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.Swapchain.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Present.Swapchain.cs @@ -598,6 +598,7 @@ private void DestroySwapchainResources() _overlayStagingMemory = []; _overlayStagingMapped = []; _overlayImageInitialized = false; + DestroyOverlayLayerTargets(); _frameInFlight = []; _frameTimelines = []; _frameGuestImageVersions = []; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs index fd2710eef..78a829e15 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs @@ -443,6 +443,8 @@ private void RenderCore() $"Unsupported translated guest draw: {presentation.DrawKind}."); } + RecordOverlayLayers(imageIndex, frameSlot); + if (PerfOverlay.DrawOnScreen) { RecordOverlayBlit(imageIndex, frameSlot); From 04d773c35fcf35447625082bf2026f07f0a49eb2 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:22:36 +0300 Subject: [PATCH 23/64] [SaveData] Show the save data dialog list as an overlay with delete, localized text and controller prompts --- src/SharpEmu.GUI/Languages/ar.json | 19 +- src/SharpEmu.GUI/Languages/az.json | 19 +- src/SharpEmu.GUI/Languages/br.json | 19 +- src/SharpEmu.GUI/Languages/de.json | 19 +- src/SharpEmu.GUI/Languages/dk.json | 19 +- src/SharpEmu.GUI/Languages/ee.json | 19 +- src/SharpEmu.GUI/Languages/en.json | 19 +- src/SharpEmu.GUI/Languages/es.json | 19 +- src/SharpEmu.GUI/Languages/fr.json | 19 +- src/SharpEmu.GUI/Languages/hu.json | 19 +- src/SharpEmu.GUI/Languages/it.json | 19 +- src/SharpEmu.GUI/Languages/ja.json | 19 +- src/SharpEmu.GUI/Languages/ko.json | 19 +- src/SharpEmu.GUI/Languages/nl.json | 19 +- src/SharpEmu.GUI/Languages/pl.json | 19 +- src/SharpEmu.GUI/Languages/pt.json | 19 +- src/SharpEmu.GUI/Languages/ru.json | 19 +- src/SharpEmu.GUI/Languages/tr.json | 19 +- src/SharpEmu.GUI/Languages/zh.json | 19 +- src/SharpEmu.Libs/Pad/HostWindowInput.cs | 1 + src/SharpEmu.Libs/Pad/PadExports.cs | 44 +- src/SharpEmu.Libs/Pad/SystemDialogInput.cs | 73 ++ .../SaveData/SaveDataDialogExports.cs | 692 ++++++++++++++++-- src/SharpEmu.Libs/SaveData/SaveDataExports.cs | 82 +++ .../SaveData/SaveDataListLayer.cs | 296 ++++++++ src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs | 1 + 26 files changed, 1477 insertions(+), 73 deletions(-) create mode 100644 src/SharpEmu.Libs/Pad/SystemDialogInput.cs create mode 100644 src/SharpEmu.Libs/SaveData/SaveDataListLayer.cs diff --git a/src/SharpEmu.GUI/Languages/ar.json b/src/SharpEmu.GUI/Languages/ar.json index 1647cace0..eeab885b4 100644 --- a/src/SharpEmu.GUI/Languages/ar.json +++ b/src/SharpEmu.GUI/Languages/ar.json @@ -502,5 +502,22 @@ "Trophies.Sort.Progress": "التقدّم", "Trophies.Sort.Name": "أ–ي", "Trophies.SearchWatermark": "ابحث عن لعبة", - "Trophies.NoMatch": "لا توجد لعبة تطابق بحثك." + "Trophies.NoMatch": "لا توجد لعبة تطابق بحثك.", + "Overlay.SaveData.Title": "البيانات المحفوظة", + "Overlay.SaveData.Caption.Load": "اختر البيانات المحفوظة التي تريد تحميلها.", + "Overlay.SaveData.Caption.Save": "اختر مكان الحفظ.", + "Overlay.SaveData.Caption.Delete": "اختر البيانات المحفوظة التي تريد حذفها.", + "Overlay.SaveData.Caption.Other": "اختر البيانات المحفوظة.", + "Overlay.SaveData.Select": "تحديد", + "Overlay.SaveData.Back": "رجوع", + "Overlay.SaveData.Move": "تنقّل", + "Overlay.SaveData.Delete": "حذف", + "Overlay.SaveData.Cancel": "إلغاء", + "Overlay.SaveData.NewItem": "بيانات محفوظة جديدة", + "Overlay.SaveData.NewItemDetail": "أنشئ حفظًا جديدًا في خانة فارغة.", + "Overlay.SaveData.LastSaved": "آخر حفظ", + "Overlay.SaveData.Size": "الحجم", + "Overlay.SaveData.ConfirmDelete": "هل تريد حذف هذه البيانات المحفوظة؟", + "Overlay.SaveData.ConfirmDeleteNote": "لا يمكن استعادة البيانات المحفوظة المحذوفة.", + "Overlay.SaveData.InUse": "هذه البيانات المحفوظة قيد الاستخدام ولا يمكن حذفها." } diff --git a/src/SharpEmu.GUI/Languages/az.json b/src/SharpEmu.GUI/Languages/az.json index b4cc864c4..346634b80 100644 --- a/src/SharpEmu.GUI/Languages/az.json +++ b/src/SharpEmu.GUI/Languages/az.json @@ -505,5 +505,22 @@ "Trophies.Sort.Progress": "İrəliləyiş", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Oyun axtar", - "Trophies.NoMatch": "Axtarışınıza uyğun oyun tapılmadı." + "Trophies.NoMatch": "Axtarışınıza uyğun oyun tapılmadı.", + "Overlay.SaveData.Title": "Yadda saxlanılmış məlumatlar", + "Overlay.SaveData.Caption.Load": "Yükləmək üçün yadda saxlanılmış məlumatı seçin.", + "Overlay.SaveData.Caption.Save": "Yadda saxlanacaq yeri seçin.", + "Overlay.SaveData.Caption.Delete": "Silmək üçün yadda saxlanılmış məlumatı seçin.", + "Overlay.SaveData.Caption.Other": "Yadda saxlanılmış məlumatı seçin.", + "Overlay.SaveData.Select": "Seç", + "Overlay.SaveData.Back": "Geri", + "Overlay.SaveData.Move": "Hərəkət", + "Overlay.SaveData.Delete": "Sil", + "Overlay.SaveData.Cancel": "Ləğv et", + "Overlay.SaveData.NewItem": "Yeni yadda saxlanılmış məlumat", + "Overlay.SaveData.NewItemDetail": "Boş yerdə yeni qeyd yaradın.", + "Overlay.SaveData.LastSaved": "Son yadda saxlama", + "Overlay.SaveData.Size": "Ölçü", + "Overlay.SaveData.ConfirmDelete": "Bu yadda saxlanılmış məlumat silinsin?", + "Overlay.SaveData.ConfirmDeleteNote": "Silinmiş yadda saxlanılmış məlumatlar bərpa edilə bilməz.", + "Overlay.SaveData.InUse": "Bu yadda saxlanılmış məlumat istifadədədir və silinə bilməz." } diff --git a/src/SharpEmu.GUI/Languages/br.json b/src/SharpEmu.GUI/Languages/br.json index cec2aaa7d..e5605781d 100644 --- a/src/SharpEmu.GUI/Languages/br.json +++ b/src/SharpEmu.GUI/Languages/br.json @@ -503,5 +503,22 @@ "Trophies.Sort.Progress": "Progresso", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Pesquisar jogos", - "Trophies.NoMatch": "Nenhum jogo corresponde à sua pesquisa." + "Trophies.NoMatch": "Nenhum jogo corresponde à sua pesquisa.", + "Overlay.SaveData.Title": "Dados salvos", + "Overlay.SaveData.Caption.Load": "Selecione os dados salvos para carregar.", + "Overlay.SaveData.Caption.Save": "Selecione onde salvar.", + "Overlay.SaveData.Caption.Delete": "Selecione os dados salvos para excluir.", + "Overlay.SaveData.Caption.Other": "Selecione dados salvos.", + "Overlay.SaveData.Select": "Selecionar", + "Overlay.SaveData.Back": "Voltar", + "Overlay.SaveData.Move": "Mover", + "Overlay.SaveData.Delete": "Excluir", + "Overlay.SaveData.Cancel": "Cancelar", + "Overlay.SaveData.NewItem": "Novos dados salvos", + "Overlay.SaveData.NewItemDetail": "Crie um novo salvamento em um espaço livre.", + "Overlay.SaveData.LastSaved": "Último salvamento", + "Overlay.SaveData.Size": "Tamanho", + "Overlay.SaveData.ConfirmDelete": "Excluir estes dados salvos?", + "Overlay.SaveData.ConfirmDeleteNote": "Dados salvos excluídos não podem ser restaurados.", + "Overlay.SaveData.InUse": "Estes dados salvos estão em uso e não podem ser excluídos." } diff --git a/src/SharpEmu.GUI/Languages/de.json b/src/SharpEmu.GUI/Languages/de.json index 9d5f426b1..8595c7f05 100644 --- a/src/SharpEmu.GUI/Languages/de.json +++ b/src/SharpEmu.GUI/Languages/de.json @@ -502,5 +502,22 @@ "Trophies.Sort.Progress": "Fortschritt", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Spiele suchen", - "Trophies.NoMatch": "Kein Spiel passt zu deiner Suche." + "Trophies.NoMatch": "Kein Spiel passt zu deiner Suche.", + "Overlay.SaveData.Title": "Gespeicherte Daten", + "Overlay.SaveData.Caption.Load": "Wähle die gespeicherten Daten zum Laden aus.", + "Overlay.SaveData.Caption.Save": "Wähle aus, wo gespeichert werden soll.", + "Overlay.SaveData.Caption.Delete": "Wähle die zu löschenden gespeicherten Daten aus.", + "Overlay.SaveData.Caption.Other": "Wähle gespeicherte Daten aus.", + "Overlay.SaveData.Select": "Auswählen", + "Overlay.SaveData.Back": "Zurück", + "Overlay.SaveData.Move": "Bewegen", + "Overlay.SaveData.Delete": "Löschen", + "Overlay.SaveData.Cancel": "Abbrechen", + "Overlay.SaveData.NewItem": "Neue gespeicherte Daten", + "Overlay.SaveData.NewItemDetail": "Einen neuen Spielstand auf einem freien Platz anlegen.", + "Overlay.SaveData.LastSaved": "Zuletzt gespeichert", + "Overlay.SaveData.Size": "Größe", + "Overlay.SaveData.ConfirmDelete": "Diese gespeicherten Daten löschen?", + "Overlay.SaveData.ConfirmDeleteNote": "Gelöschte gespeicherte Daten können nicht wiederhergestellt werden.", + "Overlay.SaveData.InUse": "Diese gespeicherten Daten werden verwendet und können nicht gelöscht werden." } diff --git a/src/SharpEmu.GUI/Languages/dk.json b/src/SharpEmu.GUI/Languages/dk.json index 20edb35d1..4fcfc0b53 100644 --- a/src/SharpEmu.GUI/Languages/dk.json +++ b/src/SharpEmu.GUI/Languages/dk.json @@ -502,5 +502,22 @@ "Trophies.Sort.Progress": "Fremskridt", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Søg efter spil", - "Trophies.NoMatch": "Intet spil matcher din søgning." + "Trophies.NoMatch": "Intet spil matcher din søgning.", + "Overlay.SaveData.Title": "Gemte data", + "Overlay.SaveData.Caption.Load": "Vælg de gemte data, der skal indlæses.", + "Overlay.SaveData.Caption.Save": "Vælg, hvor der skal gemmes.", + "Overlay.SaveData.Caption.Delete": "Vælg de gemte data, der skal slettes.", + "Overlay.SaveData.Caption.Other": "Vælg gemte data.", + "Overlay.SaveData.Select": "Vælg", + "Overlay.SaveData.Back": "Tilbage", + "Overlay.SaveData.Move": "Naviger", + "Overlay.SaveData.Delete": "Slet", + "Overlay.SaveData.Cancel": "Annuller", + "Overlay.SaveData.NewItem": "Nye gemte data", + "Overlay.SaveData.NewItemDetail": "Opret en ny gemning på en ledig plads.", + "Overlay.SaveData.LastSaved": "Sidst gemt", + "Overlay.SaveData.Size": "Størrelse", + "Overlay.SaveData.ConfirmDelete": "Vil du slette disse gemte data?", + "Overlay.SaveData.ConfirmDeleteNote": "Slettede gemte data kan ikke gendannes.", + "Overlay.SaveData.InUse": "Disse gemte data er i brug og kan ikke slettes." } diff --git a/src/SharpEmu.GUI/Languages/ee.json b/src/SharpEmu.GUI/Languages/ee.json index 057fe0f41..873d3aaaf 100644 --- a/src/SharpEmu.GUI/Languages/ee.json +++ b/src/SharpEmu.GUI/Languages/ee.json @@ -504,5 +504,22 @@ "Trophies.Sort.Progress": "Edenemine", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Otsi mänge", - "Trophies.NoMatch": "Sinu otsingule ei vasta ükski mäng." + "Trophies.NoMatch": "Sinu otsingule ei vasta ükski mäng.", + "Overlay.SaveData.Title": "Salvestatud andmed", + "Overlay.SaveData.Caption.Load": "Vali laaditavad salvestatud andmed.", + "Overlay.SaveData.Caption.Save": "Vali, kuhu salvestada.", + "Overlay.SaveData.Caption.Delete": "Vali kustutatavad salvestatud andmed.", + "Overlay.SaveData.Caption.Other": "Vali salvestatud andmed.", + "Overlay.SaveData.Select": "Vali", + "Overlay.SaveData.Back": "Tagasi", + "Overlay.SaveData.Move": "Liigu", + "Overlay.SaveData.Delete": "Kustuta", + "Overlay.SaveData.Cancel": "Tühista", + "Overlay.SaveData.NewItem": "Uued salvestatud andmed", + "Overlay.SaveData.NewItemDetail": "Loo vabasse pesasse uus salvestus.", + "Overlay.SaveData.LastSaved": "Viimati salvestatud", + "Overlay.SaveData.Size": "Suurus", + "Overlay.SaveData.ConfirmDelete": "Kas kustutada need salvestatud andmed?", + "Overlay.SaveData.ConfirmDeleteNote": "Kustutatud salvestatud andmeid ei saa taastada.", + "Overlay.SaveData.InUse": "Need salvestatud andmed on kasutusel ja neid ei saa kustutada." } diff --git a/src/SharpEmu.GUI/Languages/en.json b/src/SharpEmu.GUI/Languages/en.json index 5624d3b6e..7c9467121 100644 --- a/src/SharpEmu.GUI/Languages/en.json +++ b/src/SharpEmu.GUI/Languages/en.json @@ -506,5 +506,22 @@ "Trophies.Sort.Progress": "Progress", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Search games", - "Trophies.NoMatch": "No game matches your search." + "Trophies.NoMatch": "No game matches your search.", + "Overlay.SaveData.Title": "Saved Data", + "Overlay.SaveData.Caption.Load": "Select the saved data to load.", + "Overlay.SaveData.Caption.Save": "Select where to save.", + "Overlay.SaveData.Caption.Delete": "Select the saved data to delete.", + "Overlay.SaveData.Caption.Other": "Select saved data.", + "Overlay.SaveData.Select": "Select", + "Overlay.SaveData.Back": "Back", + "Overlay.SaveData.Move": "Move", + "Overlay.SaveData.Delete": "Delete", + "Overlay.SaveData.Cancel": "Cancel", + "Overlay.SaveData.NewItem": "New Saved Data", + "Overlay.SaveData.NewItemDetail": "Create a new save in an empty slot.", + "Overlay.SaveData.LastSaved": "Last saved", + "Overlay.SaveData.Size": "Size", + "Overlay.SaveData.ConfirmDelete": "Delete this saved data?", + "Overlay.SaveData.ConfirmDeleteNote": "Deleted saved data can't be restored.", + "Overlay.SaveData.InUse": "This saved data is in use and can't be deleted." } diff --git a/src/SharpEmu.GUI/Languages/es.json b/src/SharpEmu.GUI/Languages/es.json index dca27e5f8..4fa953aec 100644 --- a/src/SharpEmu.GUI/Languages/es.json +++ b/src/SharpEmu.GUI/Languages/es.json @@ -503,5 +503,22 @@ "Trophies.Sort.Progress": "Progreso", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Buscar juegos", - "Trophies.NoMatch": "Ningún juego coincide con tu búsqueda." + "Trophies.NoMatch": "Ningún juego coincide con tu búsqueda.", + "Overlay.SaveData.Title": "Datos guardados", + "Overlay.SaveData.Caption.Load": "Selecciona los datos guardados que quieres cargar.", + "Overlay.SaveData.Caption.Save": "Selecciona dónde guardar.", + "Overlay.SaveData.Caption.Delete": "Selecciona los datos guardados que quieres eliminar.", + "Overlay.SaveData.Caption.Other": "Selecciona datos guardados.", + "Overlay.SaveData.Select": "Seleccionar", + "Overlay.SaveData.Back": "Atrás", + "Overlay.SaveData.Move": "Mover", + "Overlay.SaveData.Delete": "Eliminar", + "Overlay.SaveData.Cancel": "Cancelar", + "Overlay.SaveData.NewItem": "Nuevos datos guardados", + "Overlay.SaveData.NewItemDetail": "Crea una partida guardada nueva en un espacio libre.", + "Overlay.SaveData.LastSaved": "Último guardado", + "Overlay.SaveData.Size": "Tamaño", + "Overlay.SaveData.ConfirmDelete": "¿Eliminar estos datos guardados?", + "Overlay.SaveData.ConfirmDeleteNote": "Los datos guardados eliminados no se pueden recuperar.", + "Overlay.SaveData.InUse": "Estos datos guardados están en uso y no se pueden eliminar." } diff --git a/src/SharpEmu.GUI/Languages/fr.json b/src/SharpEmu.GUI/Languages/fr.json index 25e35ed0f..77866b37b 100644 --- a/src/SharpEmu.GUI/Languages/fr.json +++ b/src/SharpEmu.GUI/Languages/fr.json @@ -503,5 +503,22 @@ "Trophies.Sort.Progress": "Progression", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Rechercher un jeu", - "Trophies.NoMatch": "Aucun jeu ne correspond à votre recherche." + "Trophies.NoMatch": "Aucun jeu ne correspond à votre recherche.", + "Overlay.SaveData.Title": "Données sauvegardées", + "Overlay.SaveData.Caption.Load": "Sélectionnez les données sauvegardées à charger.", + "Overlay.SaveData.Caption.Save": "Sélectionnez l’emplacement de la sauvegarde.", + "Overlay.SaveData.Caption.Delete": "Sélectionnez les données sauvegardées à supprimer.", + "Overlay.SaveData.Caption.Other": "Sélectionnez des données sauvegardées.", + "Overlay.SaveData.Select": "Sélectionner", + "Overlay.SaveData.Back": "Retour", + "Overlay.SaveData.Move": "Naviguer", + "Overlay.SaveData.Delete": "Supprimer", + "Overlay.SaveData.Cancel": "Annuler", + "Overlay.SaveData.NewItem": "Nouvelles données sauvegardées", + "Overlay.SaveData.NewItemDetail": "Créer une nouvelle sauvegarde dans un emplacement libre.", + "Overlay.SaveData.LastSaved": "Dernière sauvegarde", + "Overlay.SaveData.Size": "Taille", + "Overlay.SaveData.ConfirmDelete": "Supprimer ces données sauvegardées ?", + "Overlay.SaveData.ConfirmDeleteNote": "Les données sauvegardées supprimées ne peuvent pas être restaurées.", + "Overlay.SaveData.InUse": "Ces données sauvegardées sont en cours d’utilisation et ne peuvent pas être supprimées." } diff --git a/src/SharpEmu.GUI/Languages/hu.json b/src/SharpEmu.GUI/Languages/hu.json index 4a6f2ef6f..408a8764e 100644 --- a/src/SharpEmu.GUI/Languages/hu.json +++ b/src/SharpEmu.GUI/Languages/hu.json @@ -503,5 +503,22 @@ "Trophies.Sort.Progress": "Előrehaladás", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Játékok keresése", - "Trophies.NoMatch": "Nincs a keresésnek megfelelő játék." + "Trophies.NoMatch": "Nincs a keresésnek megfelelő játék.", + "Overlay.SaveData.Title": "Mentett adatok", + "Overlay.SaveData.Caption.Load": "Válaszd ki a betöltendő mentett adatot.", + "Overlay.SaveData.Caption.Save": "Válaszd ki a mentés helyét.", + "Overlay.SaveData.Caption.Delete": "Válaszd ki a törlendő mentett adatot.", + "Overlay.SaveData.Caption.Other": "Válassz mentett adatot.", + "Overlay.SaveData.Select": "Kiválasztás", + "Overlay.SaveData.Back": "Vissza", + "Overlay.SaveData.Move": "Mozgás", + "Overlay.SaveData.Delete": "Törlés", + "Overlay.SaveData.Cancel": "Mégse", + "Overlay.SaveData.NewItem": "Új mentett adat", + "Overlay.SaveData.NewItemDetail": "Új mentés létrehozása egy üres helyen.", + "Overlay.SaveData.LastSaved": "Utolsó mentés", + "Overlay.SaveData.Size": "Méret", + "Overlay.SaveData.ConfirmDelete": "Törlöd ezt a mentett adatot?", + "Overlay.SaveData.ConfirmDeleteNote": "A törölt mentett adatok nem állíthatók vissza.", + "Overlay.SaveData.InUse": "Ez a mentett adat használatban van, ezért nem törölhető." } diff --git a/src/SharpEmu.GUI/Languages/it.json b/src/SharpEmu.GUI/Languages/it.json index 38cfe5bee..b0b94b4ed 100644 --- a/src/SharpEmu.GUI/Languages/it.json +++ b/src/SharpEmu.GUI/Languages/it.json @@ -507,5 +507,22 @@ "Trophies.Sort.Progress": "Avanzamento", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Cerca giochi", - "Trophies.NoMatch": "Nessun gioco corrisponde alla ricerca." + "Trophies.NoMatch": "Nessun gioco corrisponde alla ricerca.", + "Overlay.SaveData.Title": "Dati salvati", + "Overlay.SaveData.Caption.Load": "Seleziona i dati salvati da caricare.", + "Overlay.SaveData.Caption.Save": "Seleziona dove salvare.", + "Overlay.SaveData.Caption.Delete": "Seleziona i dati salvati da eliminare.", + "Overlay.SaveData.Caption.Other": "Seleziona i dati salvati.", + "Overlay.SaveData.Select": "Seleziona", + "Overlay.SaveData.Back": "Indietro", + "Overlay.SaveData.Move": "Sposta", + "Overlay.SaveData.Delete": "Elimina", + "Overlay.SaveData.Cancel": "Annulla", + "Overlay.SaveData.NewItem": "Nuovi dati salvati", + "Overlay.SaveData.NewItemDetail": "Crea un nuovo salvataggio in uno slot libero.", + "Overlay.SaveData.LastSaved": "Ultimo salvataggio", + "Overlay.SaveData.Size": "Dimensione", + "Overlay.SaveData.ConfirmDelete": "Eliminare questi dati salvati?", + "Overlay.SaveData.ConfirmDeleteNote": "I dati salvati eliminati non possono essere ripristinati.", + "Overlay.SaveData.InUse": "Questi dati salvati sono in uso e non possono essere eliminati." } diff --git a/src/SharpEmu.GUI/Languages/ja.json b/src/SharpEmu.GUI/Languages/ja.json index 14fefaa4c..508a69c61 100644 --- a/src/SharpEmu.GUI/Languages/ja.json +++ b/src/SharpEmu.GUI/Languages/ja.json @@ -502,5 +502,22 @@ "Trophies.Sort.Progress": "進行状況", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "ゲームを検索", - "Trophies.NoMatch": "検索に一致するゲームはありません。" + "Trophies.NoMatch": "検索に一致するゲームはありません。", + "Overlay.SaveData.Title": "セーブデータ", + "Overlay.SaveData.Caption.Load": "ロードするセーブデータを選んでください。", + "Overlay.SaveData.Caption.Save": "セーブする場所を選んでください。", + "Overlay.SaveData.Caption.Delete": "削除するセーブデータを選んでください。", + "Overlay.SaveData.Caption.Other": "セーブデータを選んでください。", + "Overlay.SaveData.Select": "決定", + "Overlay.SaveData.Back": "戻る", + "Overlay.SaveData.Move": "移動", + "Overlay.SaveData.Delete": "削除", + "Overlay.SaveData.Cancel": "キャンセル", + "Overlay.SaveData.NewItem": "新しいセーブデータ", + "Overlay.SaveData.NewItemDetail": "空いているスロットに新しくセーブします。", + "Overlay.SaveData.LastSaved": "最終セーブ", + "Overlay.SaveData.Size": "サイズ", + "Overlay.SaveData.ConfirmDelete": "このセーブデータを削除しますか?", + "Overlay.SaveData.ConfirmDeleteNote": "削除したセーブデータは元に戻せません。", + "Overlay.SaveData.InUse": "このセーブデータは使用中のため削除できません。" } diff --git a/src/SharpEmu.GUI/Languages/ko.json b/src/SharpEmu.GUI/Languages/ko.json index 7d29b2c0b..92b9ed1da 100644 --- a/src/SharpEmu.GUI/Languages/ko.json +++ b/src/SharpEmu.GUI/Languages/ko.json @@ -502,5 +502,22 @@ "Trophies.Sort.Progress": "진행률", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "게임 검색", - "Trophies.NoMatch": "검색과 일치하는 게임이 없습니다." + "Trophies.NoMatch": "검색과 일치하는 게임이 없습니다.", + "Overlay.SaveData.Title": "저장 데이터", + "Overlay.SaveData.Caption.Load": "불러올 저장 데이터를 선택하세요.", + "Overlay.SaveData.Caption.Save": "저장할 위치를 선택하세요.", + "Overlay.SaveData.Caption.Delete": "삭제할 저장 데이터를 선택하세요.", + "Overlay.SaveData.Caption.Other": "저장 데이터를 선택하세요.", + "Overlay.SaveData.Select": "선택", + "Overlay.SaveData.Back": "뒤로", + "Overlay.SaveData.Move": "이동", + "Overlay.SaveData.Delete": "삭제", + "Overlay.SaveData.Cancel": "취소", + "Overlay.SaveData.NewItem": "새 저장 데이터", + "Overlay.SaveData.NewItemDetail": "빈 슬롯에 새로 저장합니다.", + "Overlay.SaveData.LastSaved": "마지막 저장", + "Overlay.SaveData.Size": "크기", + "Overlay.SaveData.ConfirmDelete": "이 저장 데이터를 삭제하시겠습니까?", + "Overlay.SaveData.ConfirmDeleteNote": "삭제한 저장 데이터는 복원할 수 없습니다.", + "Overlay.SaveData.InUse": "이 저장 데이터는 사용 중이어서 삭제할 수 없습니다." } diff --git a/src/SharpEmu.GUI/Languages/nl.json b/src/SharpEmu.GUI/Languages/nl.json index d6f92a784..a64873d25 100644 --- a/src/SharpEmu.GUI/Languages/nl.json +++ b/src/SharpEmu.GUI/Languages/nl.json @@ -502,5 +502,22 @@ "Trophies.Sort.Progress": "Voortgang", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Games zoeken", - "Trophies.NoMatch": "Geen game komt overeen met je zoekopdracht." + "Trophies.NoMatch": "Geen game komt overeen met je zoekopdracht.", + "Overlay.SaveData.Title": "Opgeslagen gegevens", + "Overlay.SaveData.Caption.Load": "Selecteer de opgeslagen gegevens om te laden.", + "Overlay.SaveData.Caption.Save": "Selecteer waar je wilt opslaan.", + "Overlay.SaveData.Caption.Delete": "Selecteer de opgeslagen gegevens om te verwijderen.", + "Overlay.SaveData.Caption.Other": "Selecteer opgeslagen gegevens.", + "Overlay.SaveData.Select": "Selecteren", + "Overlay.SaveData.Back": "Terug", + "Overlay.SaveData.Move": "Navigeren", + "Overlay.SaveData.Delete": "Verwijderen", + "Overlay.SaveData.Cancel": "Annuleren", + "Overlay.SaveData.NewItem": "Nieuwe opgeslagen gegevens", + "Overlay.SaveData.NewItemDetail": "Maak een nieuwe opslag op een lege plek.", + "Overlay.SaveData.LastSaved": "Laatst opgeslagen", + "Overlay.SaveData.Size": "Grootte", + "Overlay.SaveData.ConfirmDelete": "Deze opgeslagen gegevens verwijderen?", + "Overlay.SaveData.ConfirmDeleteNote": "Verwijderde opgeslagen gegevens kunnen niet worden hersteld.", + "Overlay.SaveData.InUse": "Deze opgeslagen gegevens zijn in gebruik en kunnen niet worden verwijderd." } diff --git a/src/SharpEmu.GUI/Languages/pl.json b/src/SharpEmu.GUI/Languages/pl.json index aab32feca..ca62b1e5c 100644 --- a/src/SharpEmu.GUI/Languages/pl.json +++ b/src/SharpEmu.GUI/Languages/pl.json @@ -504,5 +504,22 @@ "Trophies.Sort.Progress": "Postęp", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Szukaj gier", - "Trophies.NoMatch": "Żadna gra nie pasuje do wyszukiwania." + "Trophies.NoMatch": "Żadna gra nie pasuje do wyszukiwania.", + "Overlay.SaveData.Title": "Zapisane dane", + "Overlay.SaveData.Caption.Load": "Wybierz zapisane dane do wczytania.", + "Overlay.SaveData.Caption.Save": "Wybierz miejsce zapisu.", + "Overlay.SaveData.Caption.Delete": "Wybierz zapisane dane do usunięcia.", + "Overlay.SaveData.Caption.Other": "Wybierz zapisane dane.", + "Overlay.SaveData.Select": "Wybierz", + "Overlay.SaveData.Back": "Wstecz", + "Overlay.SaveData.Move": "Nawigacja", + "Overlay.SaveData.Delete": "Usuń", + "Overlay.SaveData.Cancel": "Anuluj", + "Overlay.SaveData.NewItem": "Nowe zapisane dane", + "Overlay.SaveData.NewItemDetail": "Utwórz nowy zapis w wolnym miejscu.", + "Overlay.SaveData.LastSaved": "Ostatni zapis", + "Overlay.SaveData.Size": "Rozmiar", + "Overlay.SaveData.ConfirmDelete": "Usunąć te zapisane dane?", + "Overlay.SaveData.ConfirmDeleteNote": "Usuniętych zapisanych danych nie można przywrócić.", + "Overlay.SaveData.InUse": "Te zapisane dane są w użyciu i nie można ich usunąć." } diff --git a/src/SharpEmu.GUI/Languages/pt.json b/src/SharpEmu.GUI/Languages/pt.json index 8fabbaf59..d36c5e0c7 100644 --- a/src/SharpEmu.GUI/Languages/pt.json +++ b/src/SharpEmu.GUI/Languages/pt.json @@ -503,5 +503,22 @@ "Trophies.Sort.Progress": "Progresso", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Pesquisar jogos", - "Trophies.NoMatch": "Nenhum jogo corresponde à tua pesquisa." + "Trophies.NoMatch": "Nenhum jogo corresponde à tua pesquisa.", + "Overlay.SaveData.Title": "Dados guardados", + "Overlay.SaveData.Caption.Load": "Selecione os dados guardados a carregar.", + "Overlay.SaveData.Caption.Save": "Selecione onde guardar.", + "Overlay.SaveData.Caption.Delete": "Selecione os dados guardados a eliminar.", + "Overlay.SaveData.Caption.Other": "Selecione dados guardados.", + "Overlay.SaveData.Select": "Selecionar", + "Overlay.SaveData.Back": "Voltar", + "Overlay.SaveData.Move": "Mover", + "Overlay.SaveData.Delete": "Eliminar", + "Overlay.SaveData.Cancel": "Cancelar", + "Overlay.SaveData.NewItem": "Novos dados guardados", + "Overlay.SaveData.NewItemDetail": "Crie um novo jogo guardado num espaço livre.", + "Overlay.SaveData.LastSaved": "Última gravação", + "Overlay.SaveData.Size": "Tamanho", + "Overlay.SaveData.ConfirmDelete": "Eliminar estes dados guardados?", + "Overlay.SaveData.ConfirmDeleteNote": "Os dados guardados eliminados não podem ser recuperados.", + "Overlay.SaveData.InUse": "Estes dados guardados estão a ser utilizados e não podem ser eliminados." } diff --git a/src/SharpEmu.GUI/Languages/ru.json b/src/SharpEmu.GUI/Languages/ru.json index 1f12689eb..7acd3f43c 100644 --- a/src/SharpEmu.GUI/Languages/ru.json +++ b/src/SharpEmu.GUI/Languages/ru.json @@ -505,5 +505,22 @@ "Trophies.Sort.Progress": "Прогресс", "Trophies.Sort.Name": "А–Я", "Trophies.SearchWatermark": "Поиск игр", - "Trophies.NoMatch": "Ни одна игра не соответствует запросу." + "Trophies.NoMatch": "Ни одна игра не соответствует запросу.", + "Overlay.SaveData.Title": "Сохраненные данные", + "Overlay.SaveData.Caption.Load": "Выберите сохраненные данные для загрузки.", + "Overlay.SaveData.Caption.Save": "Выберите, куда сохранить.", + "Overlay.SaveData.Caption.Delete": "Выберите сохраненные данные для удаления.", + "Overlay.SaveData.Caption.Other": "Выберите сохраненные данные.", + "Overlay.SaveData.Select": "Выбрать", + "Overlay.SaveData.Back": "Назад", + "Overlay.SaveData.Move": "Перемещение", + "Overlay.SaveData.Delete": "Удалить", + "Overlay.SaveData.Cancel": "Отмена", + "Overlay.SaveData.NewItem": "Новые сохраненные данные", + "Overlay.SaveData.NewItemDetail": "Создать новое сохранение в свободном слоте.", + "Overlay.SaveData.LastSaved": "Последнее сохранение", + "Overlay.SaveData.Size": "Размер", + "Overlay.SaveData.ConfirmDelete": "Удалить эти сохраненные данные?", + "Overlay.SaveData.ConfirmDeleteNote": "Удаленные сохраненные данные нельзя восстановить.", + "Overlay.SaveData.InUse": "Эти сохраненные данные используются, их нельзя удалить." } diff --git a/src/SharpEmu.GUI/Languages/tr.json b/src/SharpEmu.GUI/Languages/tr.json index 5555d42b9..2b3cacfce 100644 --- a/src/SharpEmu.GUI/Languages/tr.json +++ b/src/SharpEmu.GUI/Languages/tr.json @@ -504,5 +504,22 @@ "Trophies.Sort.Progress": "İlerleme", "Trophies.Sort.Name": "A–Z", "Trophies.SearchWatermark": "Oyun ara", - "Trophies.NoMatch": "Aramanızla eşleşen oyun yok." + "Trophies.NoMatch": "Aramanızla eşleşen oyun yok.", + "Overlay.SaveData.Title": "Kayıtlı Veriler", + "Overlay.SaveData.Caption.Load": "Yüklenecek kayıtlı veriyi seçin.", + "Overlay.SaveData.Caption.Save": "Kaydedilecek yeri seçin.", + "Overlay.SaveData.Caption.Delete": "Silinecek kayıtlı veriyi seçin.", + "Overlay.SaveData.Caption.Other": "Kayıtlı veri seçin.", + "Overlay.SaveData.Select": "Seç", + "Overlay.SaveData.Back": "Geri", + "Overlay.SaveData.Move": "Gezin", + "Overlay.SaveData.Delete": "Sil", + "Overlay.SaveData.Cancel": "İptal", + "Overlay.SaveData.NewItem": "Yeni Kayıtlı Veri", + "Overlay.SaveData.NewItemDetail": "Boş bir yuvada yeni kayıt oluşturun.", + "Overlay.SaveData.LastSaved": "Son kayıt", + "Overlay.SaveData.Size": "Boyut", + "Overlay.SaveData.ConfirmDelete": "Bu kayıtlı veri silinsin mi?", + "Overlay.SaveData.ConfirmDeleteNote": "Silinen kayıtlı veriler geri getirilemez.", + "Overlay.SaveData.InUse": "Bu kayıtlı veri kullanımda olduğu için silinemiyor." } diff --git a/src/SharpEmu.GUI/Languages/zh.json b/src/SharpEmu.GUI/Languages/zh.json index 1ee11582c..ca74f4614 100644 --- a/src/SharpEmu.GUI/Languages/zh.json +++ b/src/SharpEmu.GUI/Languages/zh.json @@ -504,5 +504,22 @@ "Trophies.Sort.Progress": "进度", "Trophies.Sort.Name": "名称", "Trophies.SearchWatermark": "搜索游戏", - "Trophies.NoMatch": "没有符合搜索条件的游戏。" + "Trophies.NoMatch": "没有符合搜索条件的游戏。", + "Overlay.SaveData.Title": "保存数据", + "Overlay.SaveData.Caption.Load": "请选择要读取的保存数据。", + "Overlay.SaveData.Caption.Save": "请选择保存位置。", + "Overlay.SaveData.Caption.Delete": "请选择要删除的保存数据。", + "Overlay.SaveData.Caption.Other": "请选择保存数据。", + "Overlay.SaveData.Select": "确定", + "Overlay.SaveData.Back": "返回", + "Overlay.SaveData.Move": "移动", + "Overlay.SaveData.Delete": "删除", + "Overlay.SaveData.Cancel": "取消", + "Overlay.SaveData.NewItem": "新建保存数据", + "Overlay.SaveData.NewItemDetail": "在空栏位中创建新的存档。", + "Overlay.SaveData.LastSaved": "最后保存", + "Overlay.SaveData.Size": "大小", + "Overlay.SaveData.ConfirmDelete": "要删除此保存数据吗?", + "Overlay.SaveData.ConfirmDeleteNote": "删除的保存数据无法恢复。", + "Overlay.SaveData.InUse": "此保存数据正在使用中,无法删除。" } diff --git a/src/SharpEmu.Libs/Pad/HostWindowInput.cs b/src/SharpEmu.Libs/Pad/HostWindowInput.cs index 060c68bd6..d02a5d396 100644 --- a/src/SharpEmu.Libs/Pad/HostWindowInput.cs +++ b/src/SharpEmu.Libs/Pad/HostWindowInput.cs @@ -79,6 +79,7 @@ public static void SetKey(int virtualKey, bool down) changed = down ? PressedKeys.Add(virtualKey) : PressedKeys.Remove(virtualKey); } + if (changed && down) SystemDialogInput.OnKeyDown(virtualKey); if (changed) Changed?.Invoke(); } diff --git a/src/SharpEmu.Libs/Pad/PadExports.cs b/src/SharpEmu.Libs/Pad/PadExports.cs index ae494fd27..a6a01039d 100644 --- a/src/SharpEmu.Libs/Pad/PadExports.cs +++ b/src/SharpEmu.Libs/Pad/PadExports.cs @@ -49,6 +49,7 @@ public static class PadExports private static readonly object HistoryGate = new(); private static readonly (PadState State, ulong Timestamp)[] History = new (PadState, ulong)[HistoryCapacity]; private static long _historyNext; + private static long _historyFloor; private static int _controlsAnnouncementLogged; private static readonly bool LogPadState = @@ -113,7 +114,7 @@ private static (PadState State, ulong Timestamp)[] TakeUnreadStates(PadSession s session.ReadSequence = _historyNext; } - var first = Math.Max(session.ReadSequence, _historyNext - HistoryCapacity); + var first = Math.Max(Math.Max(session.ReadSequence, _historyNext - HistoryCapacity), _historyFloor); var take = (int)Math.Min(_historyNext - first, count); more = _historyNext - first > take; if (take == 0) @@ -132,6 +133,44 @@ private static (PadState State, ulong Timestamp)[] TakeUnreadStates(PadSession s } } + internal static PadState ReadSystemDialogState() => ReadHostInputState(fresh: true); + + internal static long InputHistoryPosition => Volatile.Read(ref _historyNext); + + internal static void TakeControllerHistory(ref long sequence, List<uint> buttons) + { + lock (HistoryGate) + { + var first = Math.Max(sequence, _historyNext - HistoryCapacity); + for (var index = first; index < _historyNext; index++) + { + buttons.Add(History[(int)(index % HistoryCapacity)].State.ControllerButtons); + } + + sequence = _historyNext; + } + } + + internal static HostGamepadType? ConnectedGamepadType() + { + Span<HostGamepadState> gamepads = stackalloc HostGamepadState[2]; + return HostPlatform.Current.Input.GetGamepadStates(gamepads) > 0 ? gamepads[0].Type : null; + } + + internal static bool IsHostKeyDown(int virtualKey) + { + var input = HostPlatform.Current.Input; + return input.IsHostWindowFocused() && input.IsKeyDown(virtualKey); + } + + internal static void DiscardUnreadStates() + { + lock (HistoryGate) + { + _historyFloor = _historyNext; + } + } + #pragma warning disable SHEM006 [SysAbiExport( Nid = "n3kSX62fgNo", @@ -1021,9 +1060,10 @@ private static bool WritePadData(CpuContext ctx, ulong dataAddress, int handle, return ctx.Memory.TryWrite(dataAddress, data); } - private static bool WritePadState(CpuContext ctx, ulong dataAddress, int handle, PadSession session, in PadState input, + private static bool WritePadState(CpuContext ctx, ulong dataAddress, int handle, PadSession session, in PadState hostInput, ulong timestampMicroseconds, string exportName) { + var input = SystemDialogInput.Filter(hostInput); Span<byte> data = stackalloc byte[PadDataSize]; data.Clear(); var buttons = input.Buttons; diff --git a/src/SharpEmu.Libs/Pad/SystemDialogInput.cs b/src/SharpEmu.Libs/Pad/SystemDialogInput.cs new file mode 100644 index 000000000..36b4f6ebc --- /dev/null +++ b/src/SharpEmu.Libs/Pad/SystemDialogInput.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Pad; + +internal static class SystemDialogInput +{ + internal const uint InterceptedButton = 0x80000000; + + private static readonly System.Collections.Concurrent.ConcurrentQueue<int> Keys = new(); + private static int _capturing; + private static uint _residualButtons; + + internal static bool Capturing => Volatile.Read(ref _capturing) != 0; + + internal static void Capture() + { + Keys.Clear(); + Volatile.Write(ref _capturing, 1); + } + + internal static void OnKeyDown(int virtualKey) + { + if (Capturing) + { + Keys.Enqueue(virtualKey); + } + } + + internal static void TakeKeys(List<int> keys) + { + while (Keys.TryDequeue(out var key)) + { + keys.Add(key); + } + } + + internal static void Release() + { + Volatile.Write(ref _residualButtons, PadExports.ReadSystemDialogState().Buttons); + PadExports.DiscardUnreadStates(); + Volatile.Write(ref _capturing, 0); + } + + internal static PadState Filter(in PadState state) + { + if (Capturing) + { + return state with + { + Buttons = InterceptedButton, + LeftX = 128, + LeftY = 128, + RightX = 128, + RightY = 128, + L2 = 0, + R2 = 0, + Motion = default, + Touch = default, + }; + } + + var residual = Volatile.Read(ref _residualButtons); + if (residual == 0) + { + return state; + } + + var held = residual & state.Buttons; + Interlocked.CompareExchange(ref _residualButtons, held, residual); + return held == 0 ? state : state with { Buttons = state.Buttons & ~held }; + } +} diff --git a/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs b/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs index cb718b24e..9a588bc92 100644 --- a/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs +++ b/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs @@ -2,10 +2,23 @@ // SPDX-License-Identifier: GPL-2.0-or-later using SharpEmu.HLE; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Pad; +using SharpEmu.Libs.Overlay; using System.Buffers.Binary; +using System.Diagnostics; +using System.Text; namespace SharpEmu.Libs.SaveData; +internal sealed record SaveDataDialogSlot( + string DirName, + string SlotDir, + SaveDataMetadata Metadata, + DateTime LastWriteUtc, + long SizeBytes, + string? IconPath); + public static class SaveDataDialogExports { private const int StatusNone = 0; @@ -20,11 +33,36 @@ public static class SaveDataDialogExports private const int ErrorNotRunning = unchecked((int)0x80B8000B); private const int ErrorArgNull = unchecked((int)0x80B8000D); - private const int ResultSize = 0x48; - private const int ButtonIdAffirmative = 1; + private const int ModeList = 1; + private const int DispTypeSave = 1; + private const int DispTypeLoad = 2; + private const int DispTypeDelete = 3; + private const int ResultOk = 0; + private const int ResultUserCanceled = 1; + private const int ButtonIdInvalid = 0; + private const int ButtonIdOk = 1; + private const uint FocusListTail = 1; + private const uint FocusDataHead = 2; + private const uint FocusDataTail = 3; + private const uint FocusDataLatest = 4; + private const uint FocusDataOldest = 5; + private const uint FocusDirName = 6; + private const uint OptionBackDisabled = 1; + private const int DirNameSize = 32; + private const int TitleIdSize = 10; + private const int NewItemTitleMaxBytes = 128; + private const int MaxDialogItems = 1024; + + private static readonly object Gate = new(); private static int _status; private static int _lastMode; private static ulong _lastUserData; + private static int _result; + private static int _buttonId = ButtonIdOk; + private static string _dirName = string.Empty; + private static SaveDataDialogSlot? _slot; + private static ListSession? _list; + private static long _nextSession; [SysAbiExport( Nid = "s9e3+YpRnzw", @@ -33,17 +71,16 @@ public static class SaveDataDialogExports LibraryName = "libSceSaveDataDialog")] public static int SaveDataDialogInitialize(CpuContext ctx) { - var previous = Interlocked.CompareExchange( - ref _status, - StatusInitialized, - StatusNone); - if (previous == StatusNone || previous == StatusFinished) + lock (Gate) { - Interlocked.Exchange(ref _status, StatusInitialized); + if (_status is not (StatusNone or StatusFinished)) + { + return ctx.SetReturn(ErrorAlreadyInitialized); + } + + _status = StatusInitialized; return ctx.SetReturn(ErrorOk); } - - return ctx.SetReturn(ErrorAlreadyInitialized); } [SysAbiExport( @@ -59,19 +96,47 @@ public static int SaveDataDialogOpen(CpuContext ctx) return ctx.SetReturn(ErrorArgNull); } - if (_status is not (StatusInitialized or StatusFinished)) + lock (Gate) { - return ctx.SetReturn(ErrorNotInitialized); - } + if (_status is not (StatusInitialized or StatusFinished)) + { + return ctx.SetReturn(ErrorNotInitialized); + } - _lastMode = TryReadInt32(ctx, paramAddress + 0x34, out var mode) ? mode : 0; - _lastUserData = ctx.TryReadUInt64(paramAddress + 0x70, out var userData) ? userData : 0; + _lastMode = TryReadInt32(ctx, paramAddress + 0x34, out var mode) ? mode : 0; + var dispType = TryReadInt32(ctx, paramAddress + 0x38, out var type) ? type : 0; + _lastUserData = ctx.TryReadUInt64(paramAddress + 0x70, out var userData) ? userData : 0; + var backEnabled = !(ctx.TryReadUInt64(paramAddress + 0x78, out var optionAddress) && + optionAddress != 0 && + ctx.TryReadUInt32(optionAddress, out var back) && + back == OptionBackDisabled); + var items = ReadItems(ctx, paramAddress, dispType); - // There is no host save dialog yet. Enter RUNNING so the close path sees a live - // dialog; the guest's next status poll auto-dismisses it (see PollStatus). - Interlocked.Exchange(ref _status, StatusRunning); - TraceSaveDataDialog($"open mode={_lastMode} userData=0x{_lastUserData:X16} -> running"); - return ctx.SetReturn(ErrorOk); + _result = ResultOk; + _buttonId = ButtonIdOk; + _dirName = items.FirstDirName ?? string.Empty; + _slot = items.Slots.Find(slot => slot.DirName == _dirName); + _status = StatusRunning; + + if (_lastMode == ModeList && (items.Slots.Count > 0 || items.NewItemTitle is not null)) + { + _list = new ListSession( + Interlocked.Increment(ref _nextSession), + BuildEntries(items), + CaptionFor(dispType), + backEnabled, + dispType is DispTypeLoad or DispTypeSave); + _list.Focus = InitialFocus(_list.Entries, items); + _list.Begin(); + SystemDialogInput.Capture(); + SaveDataListLayer.Instance.Show(_list.View()); + Console.Error.WriteLine( + $"[LOADER][INFO] save_data_dialog.list type={dispType} items={_list.Entries.Count} focus={_list.Focus}"); + } + + TraceSaveDataDialog($"open mode={_lastMode} type={dispType} items={items.Slots.Count} userData=0x{_lastUserData:X16}"); + return ctx.SetReturn(ErrorOk); + } } [SysAbiExport( @@ -88,14 +153,43 @@ public static int SaveDataDialogOpen(CpuContext ctx) LibraryName = "libSceSaveDataDialog")] public static int SaveDataDialogUpdateStatus(CpuContext ctx) => ctx.SetReturn(PollStatus()); - // With no host UI the dialog cannot wait for user input: the first status poll after - // Open observes the dialog as already dismissed. Advancing on both UpdateStatus and - // GetStatus keeps every guest polling pattern free of infinite RUNNING loops, while - // an Open -> Close sequence with no poll in between still exercises the close path. private static int PollStatus() { - Interlocked.CompareExchange(ref _status, StatusFinished, StatusRunning); - return Volatile.Read(ref _status); + lock (Gate) + { + if (_status != StatusRunning) + { + return _status; + } + + if (_list is null) + { + _status = StatusFinished; + return _status; + } + + switch (_list.Poll()) + { + case ListInput.Changed: + SaveDataListLayer.Instance.Show(_list.View()); + break; + case ListInput.Delete: + DeleteFocusedEntry(_list); + break; + case ListInput.Choose: + var entry = _list.Entries[_list.Focus]; + FinishList(ResultOk, ButtonIdOk, entry.DirName, entry.Slot); + Console.Error.WriteLine( + $"[LOADER][INFO] save_data_dialog.chosen dir='{entry.DirName}'"); + break; + case ListInput.Back: + FinishList(ResultUserCanceled, ButtonIdInvalid, string.Empty, null); + Console.Error.WriteLine("[LOADER][INFO] save_data_dialog.canceled"); + break; + } + + return _status; + } } [SysAbiExport( @@ -118,26 +212,46 @@ public static int SaveDataDialogGetResult(CpuContext ctx) return ctx.SetReturn(ErrorArgNull); } - if (Volatile.Read(ref _status) != StatusFinished) + lock (Gate) { - return ctx.SetReturn(ErrorNotFinished); - } + if (_status != StatusFinished) + { + return ctx.SetReturn(ErrorNotFinished); + } - // Report the affirmative button so save prompts take the confirming branch; - // buttonId 0 is the "invalid" sentinel and games may treat it as an error. - Span<byte> result = stackalloc byte[ResultSize]; - result.Clear(); - BinaryPrimitives.WriteInt32LittleEndian(result[0x00..], _lastMode); - BinaryPrimitives.WriteInt32LittleEndian(result[0x04..], 0); - BinaryPrimitives.WriteInt32LittleEndian(result[0x08..], ButtonIdAffirmative); - BinaryPrimitives.WriteUInt64LittleEndian(result[0x20..], _lastUserData); + Span<byte> head = stackalloc byte[12]; + BinaryPrimitives.WriteInt32LittleEndian(head[0x00..], _lastMode); + BinaryPrimitives.WriteInt32LittleEndian(head[0x04..], _result); + BinaryPrimitives.WriteInt32LittleEndian(head[0x08..], _buttonId); + if (!ctx.Memory.TryWrite(resultAddress, head) || + !ctx.TryWriteUInt64(resultAddress + 0x20, _lastUserData)) + { + return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } - if (!ctx.Memory.TryWrite(resultAddress, result)) - { - return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); - } + if (_dirName.Length != 0 && + ctx.TryReadUInt64(resultAddress + 0x10, out var dirNameAddress) && + dirNameAddress != 0) + { + Span<byte> dirName = stackalloc byte[DirNameSize]; + dirName.Clear(); + Encoding.ASCII.GetBytes(_dirName.AsSpan(0, Math.Min(_dirName.Length, DirNameSize - 1)), dirName); + if (!ctx.Memory.TryWrite(dirNameAddress, dirName)) + { + return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + } - return ctx.SetReturn(ErrorOk); + if (_slot is not null && + ctx.TryReadUInt64(resultAddress + 0x18, out var paramAddress) && + paramAddress != 0 && + !SaveDataExports.TryWriteDialogParam(ctx, paramAddress, _slot)) + { + return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + return ctx.SetReturn(ErrorOk); + } } [SysAbiExport( @@ -147,12 +261,21 @@ public static int SaveDataDialogGetResult(CpuContext ctx) LibraryName = "libSceSaveDataDialog")] public static int SaveDataDialogClose(CpuContext ctx) { - if (Interlocked.CompareExchange(ref _status, StatusFinished, StatusRunning) != StatusRunning) + lock (Gate) { - return ctx.SetReturn(ErrorNotRunning); - } + if (_status != StatusRunning) + { + return ctx.SetReturn(ErrorNotRunning); + } + + if (_list is not null) + { + FinishList(ResultUserCanceled, ButtonIdInvalid, string.Empty, null); + } - return ctx.SetReturn(ErrorOk); + _status = StatusFinished; + return ctx.SetReturn(ErrorOk); + } } [SysAbiExport( @@ -162,14 +285,27 @@ public static int SaveDataDialogClose(CpuContext ctx) LibraryName = "libSceSaveDataDialog")] public static int SaveDataDialogTerminate(CpuContext ctx) { - if (Interlocked.Exchange(ref _status, StatusNone) == StatusNone) + lock (Gate) { - return ctx.SetReturn(ErrorNotInitialized); - } + if (_list is not null) + { + EndList(); + } + + if (_status == StatusNone) + { + return ctx.SetReturn(ErrorNotInitialized); + } - _lastMode = 0; - _lastUserData = 0; - return ctx.SetReturn(ErrorOk); + _status = StatusNone; + _lastMode = 0; + _lastUserData = 0; + _result = ResultOk; + _buttonId = ButtonIdOk; + _dirName = string.Empty; + _slot = null; + return ctx.SetReturn(ErrorOk); + } } [SysAbiExport( @@ -186,6 +322,220 @@ public static int SaveDataDialogTerminate(CpuContext ctx) LibraryName = "libSceSaveDataDialog")] public static int SaveDataDialogProgressBarSetValue(CpuContext ctx) => ctx.SetReturn(ErrorOk); + private static void FinishList(int result, int buttonId, string dirName, SaveDataDialogSlot? slot) + { + _result = result; + _buttonId = buttonId; + _dirName = dirName; + _slot = slot; + _status = StatusFinished; + EndList(); + } + + private static void EndList() + { + _list = null; + SaveDataListLayer.Instance.Hide(); + SystemDialogInput.Release(); + } + + private static DialogItems ReadItems(CpuContext ctx, ulong paramAddress, int dispType) + { + var items = new DialogItems(); + if (!ctx.TryReadUInt64(paramAddress + 0x48, out var itemsAddress) || itemsAddress == 0) + { + return items; + } + + var userId = TryReadInt32(ctx, itemsAddress, out var user) ? user : 0; + string? titleId = null; + if (ctx.TryReadUInt64(itemsAddress + 0x08, out var titleIdAddress) && titleIdAddress != 0 && + TryReadString(ctx, titleIdAddress, TitleIdSize, out var title) && title.Length != 0) + { + titleId = title; + } + + if (ctx.TryReadUInt64(itemsAddress + 0x10, out var dirNamesAddress) && dirNamesAddress != 0 && + ctx.TryReadUInt32(itemsAddress + 0x18, out var dirNameCount)) + { + var count = (int)Math.Min(dirNameCount, MaxDialogItems); + for (var index = 0; index < count; index++) + { + if (!TryReadString(ctx, dirNamesAddress + (ulong)(index * DirNameSize), DirNameSize, out var name) || + name.Length == 0) + { + continue; + } + + items.FirstDirName ??= name; + if (items.Slots.Exists(existing => existing.DirName == name)) + { + continue; + } + + if (SaveDataExports.DescribeDialogSlot(userId, titleId, name) is { } slot) + { + items.Slots.Add(slot); + } + } + } + + if (dispType == DispTypeSave && + ctx.TryReadUInt64(itemsAddress + 0x20, out var newItemAddress) && newItemAddress != 0) + { + items.NewItemTitle = + ctx.TryReadUInt64(newItemAddress, out var newTitleAddress) && newTitleAddress != 0 && + TryReadString(ctx, newTitleAddress, NewItemTitleMaxBytes, out var newTitle) && newTitle.Length != 0 + ? newTitle + : string.Empty; + } + + items.FocusPosition = ctx.TryReadUInt32(itemsAddress + 0x28, out var focus) ? focus : 0; + if (items.FocusPosition == FocusDirName && + ctx.TryReadUInt64(itemsAddress + 0x30, out var focusNameAddress) && focusNameAddress != 0 && + TryReadString(ctx, focusNameAddress, DirNameSize, out var focusName)) + { + items.FocusDirName = focusName; + } + + return items; + } + + private static List<ListEntry> BuildEntries(DialogItems items) + { + var entries = new List<ListEntry>(items.Slots.Count + 1); + if (items.NewItemTitle is not null) + { + var title = items.NewItemTitle.Length != 0 ? items.NewItemTitle : SaveDataListLayer.Text("NewItem"); + entries.Add(new ListEntry(string.Empty, null, + new SaveDataListItem(string.Empty, title, SaveDataListLayer.Text("NewItemDetail"), string.Empty, string.Empty, + null, IsNew: true))); + } + + foreach (var slot in items.Slots) + { + entries.Add(new ListEntry(slot.DirName, slot, DescribeEntry(slot))); + } + + return entries; + } + + private static SaveDataListItem DescribeEntry(SaveDataDialogSlot slot) + { + var metadata = slot.Metadata; + var hasSubTitle = !string.IsNullOrWhiteSpace(metadata.SubTitle); + var hasTitle = !string.IsNullOrWhiteSpace(metadata.Title); + var title = hasSubTitle ? metadata.SubTitle : hasTitle ? metadata.Title : slot.DirName; + var overline = hasSubTitle && hasTitle ? metadata.Title : string.Empty; + var detail = !string.IsNullOrWhiteSpace(metadata.Detail) + ? metadata.Detail + : title == slot.DirName ? string.Empty : slot.DirName; + return new SaveDataListItem( + overline, + title, + detail, + OverlayText.FormatDate(slot.LastWriteUtc), + OverlayText.FormatSize(slot.SizeBytes), + slot.IconPath, + IsNew: false); + } + + private static int InitialFocus(IReadOnlyList<ListEntry> entries, DialogItems items) + { + var dataStart = items.NewItemTitle is null ? 0 : 1; + switch (items.FocusPosition) + { + case FocusListTail: + case FocusDataTail: + return entries.Count - 1; + case FocusDataHead: + return Math.Min(dataStart, entries.Count - 1); + case FocusDataLatest: + case FocusDataOldest: + var pick = -1; + for (var index = dataStart; index < entries.Count; index++) + { + var candidate = entries[index].Slot!.LastWriteUtc; + if (pick < 0 || + (items.FocusPosition == FocusDataLatest + ? candidate > entries[pick].Slot!.LastWriteUtc + : candidate < entries[pick].Slot!.LastWriteUtc)) + { + pick = index; + } + } + + return Math.Max(0, pick); + case FocusDirName: + for (var index = 0; index < entries.Count; index++) + { + if (string.Equals(entries[index].DirName, items.FocusDirName, StringComparison.Ordinal)) + { + return index; + } + } + + return 0; + default: + return 0; + } + } + + private static string CaptionFor(int dispType) => dispType switch + { + DispTypeSave => SaveDataListLayer.Text("Caption.Save"), + DispTypeLoad => SaveDataListLayer.Text("Caption.Load"), + DispTypeDelete => SaveDataListLayer.Text("Caption.Delete"), + _ => SaveDataListLayer.Text("Caption.Other"), + }; + + private static void DeleteFocusedEntry(ListSession list) + { + var entry = list.Entries[list.Focus]; + if (entry.Slot is null || !SaveDataExports.TryDeleteDialogSlot(entry.Slot)) + { + list.CancelDelete(SaveDataListLayer.Text("InUse")); + SaveDataListLayer.Instance.Show(list.View()); + Console.Error.WriteLine($"[LOADER][WARN] save_data_dialog.delete_refused dir='{entry.DirName}'"); + return; + } + + Console.Error.WriteLine($"[LOADER][INFO] save_data_dialog.deleted dir='{entry.DirName}'"); + list.Remove(list.Focus); + if (list.Entries.Count == 0) + { + FinishList(ResultUserCanceled, ButtonIdInvalid, string.Empty, null); + return; + } + + SaveDataListLayer.Instance.Show(list.View()); + } + + private static bool TryReadString(CpuContext ctx, ulong address, int maxBytes, out string value) + { + value = string.Empty; + Span<byte> bytes = stackalloc byte[maxBytes]; + var length = 0; + Span<byte> one = stackalloc byte[1]; + while (length < maxBytes) + { + if (!ctx.Memory.TryRead(address + (ulong)length, one)) + { + return false; + } + + if (one[0] == 0) + { + break; + } + + bytes[length++] = one[0]; + } + + value = Encoding.UTF8.GetString(bytes[..length]); + return true; + } + private static bool TryReadInt32(CpuContext ctx, ulong address, out int value) { value = 0; @@ -208,4 +558,242 @@ private static void TraceSaveDataDialog(string message) Console.Error.WriteLine($"[LOADER][TRACE] save_data_dialog.{message}"); } + + private sealed class DialogItems + { + public string? FirstDirName { get; set; } + public List<SaveDataDialogSlot> Slots { get; } = []; + public string? NewItemTitle { get; set; } + public uint FocusPosition { get; set; } + public string? FocusDirName { get; set; } + } + + private readonly record struct ListEntry(string DirName, SaveDataDialogSlot? Slot, SaveDataListItem Item); + + private enum ListInput + { + None, + Changed, + Choose, + Back, + Delete, + } + + private enum Press + { + Up, + Down, + Confirm, + Cancel, + Delete, + } + + private sealed class ListSession( + long session, + List<ListEntry> entries, + string caption, + bool backEnabled, + bool deleteEnabled) + { + private const byte StickUpThreshold = 64; + private const byte StickDownThreshold = 192; + private const int KeyBackspace = 0x08; + private const int KeyEnter = 0x0D; + private const int KeyEscape = 0x1B; + private const int KeyUp = 0x26; + private const int KeyDown = 0x28; + private const int KeyDelete = 0x2E; + private const int KeyV = 0x56; + private const int KeyX = 0x58; + private const int KeyZ = 0x5A; + private static readonly long FirstRepeatTicks = Stopwatch.Frequency * 2 / 5; + private static readonly long NextRepeatTicks = Stopwatch.Frequency / 9; + + private readonly List<uint> _controllerChanges = []; + private readonly List<int> _keys = []; + private readonly List<Press> _presses = []; + private long _sequence; + private uint _previousButtons; + private int _heldDirection; + private long _repeatAt; + private bool _confirming; + private string? _notice; + private OverlayInputScheme _scheme; + + public List<ListEntry> Entries { get; } = entries; + + public int Focus { get; set; } + + public SaveDataListView View() + { + var items = new SaveDataListItem[Entries.Count]; + for (var index = 0; index < items.Length; index++) + { + items[index] = Entries[index].Item; + } + + return new SaveDataListView(session, caption, items, Focus, backEnabled, deleteEnabled, _scheme, + _confirming, _notice); + } + + public void Begin() + { + var state = PadExports.ReadSystemDialogState(); + _sequence = PadExports.InputHistoryPosition; + _previousButtons = state.ControllerButtons; + _heldDirection = HeldDirection(state); + _repeatAt = Stopwatch.GetTimestamp() + FirstRepeatTicks; + _scheme = CurrentScheme(); + } + + public void CancelDelete(string? notice) + { + _confirming = false; + _notice = notice; + } + + public void Remove(int index) + { + Entries.RemoveAt(index); + Focus = Math.Clamp(Focus, 0, Math.Max(0, Entries.Count - 1)); + _confirming = false; + _notice = null; + } + + public ListInput Poll() + { + var now = Stopwatch.GetTimestamp(); + var changed = false; + var scheme = CurrentScheme(); + if (scheme != _scheme) + { + _scheme = scheme; + changed = true; + } + + _presses.Clear(); + _keys.Clear(); + SystemDialogInput.TakeKeys(_keys); + foreach (var key in _keys) + { + switch (key) + { + case KeyUp: _presses.Add(Press.Up); break; + case KeyDown: _presses.Add(Press.Down); break; + case KeyEnter or KeyZ: _presses.Add(Press.Confirm); break; + case KeyEscape or KeyBackspace or KeyX: _presses.Add(Press.Cancel); break; + case KeyDelete or KeyV: _presses.Add(Press.Delete); break; + } + } + + _controllerChanges.Clear(); + PadExports.TakeControllerHistory(ref _sequence, _controllerChanges); + var current = PadExports.ReadSystemDialogState(); + _controllerChanges.Add(current.ControllerButtons); + foreach (var buttons in _controllerChanges) + { + var pressed = buttons & ~_previousButtons; + _previousButtons = buttons; + if ((pressed & OrbisPadButton.Up) != 0) _presses.Add(Press.Up); + if ((pressed & OrbisPadButton.Down) != 0) _presses.Add(Press.Down); + if ((pressed & OrbisPadButton.Cross) != 0) _presses.Add(Press.Confirm); + if ((pressed & OrbisPadButton.Circle) != 0) _presses.Add(Press.Cancel); + if ((pressed & OrbisPadButton.Triangle) != 0) _presses.Add(Press.Delete); + } + + foreach (var press in _presses) + { + if (_confirming) + { + if (press == Press.Confirm) + { + return ListInput.Delete; + } + + if (press == Press.Cancel) + { + _confirming = false; + changed = true; + } + + continue; + } + + switch (press) + { + case Press.Confirm: + return ListInput.Choose; + case Press.Cancel when backEnabled: + return ListInput.Back; + case Press.Delete when deleteEnabled && Entries[Focus].Slot is { } slot: + if (SaveDataExports.IsDialogSlotMounted(slot)) + { + _notice = SaveDataListLayer.Text("InUse"); + } + else + { + _confirming = true; + _notice = null; + } + + changed = true; + break; + case Press.Up or Press.Down: + var step = press == Press.Up ? -1 : 1; + changed |= Step(step); + _heldDirection = step; + _repeatAt = now + FirstRepeatTicks; + break; + } + } + + var direction = _confirming ? 0 : HeldDirection(current); + if (direction == 0) + { + _heldDirection = 0; + } + else if (direction != _heldDirection) + { + changed |= Step(direction); + _heldDirection = direction; + _repeatAt = now + FirstRepeatTicks; + } + else if (now >= _repeatAt) + { + changed |= Step(direction); + _repeatAt = now + NextRepeatTicks; + } + + return changed ? ListInput.Changed : ListInput.None; + } + + private bool Step(int step) + { + var next = Math.Clamp(Focus + step, 0, Entries.Count - 1); + if (next == Focus) + { + return false; + } + + Focus = next; + _notice = null; + return true; + } + + private static int HeldDirection(PadState state) + { + var up = (state.ControllerButtons & OrbisPadButton.Up) != 0 || state.LeftY < StickUpThreshold || + PadExports.IsHostKeyDown(KeyUp); + var down = (state.ControllerButtons & OrbisPadButton.Down) != 0 || state.LeftY > StickDownThreshold || + PadExports.IsHostKeyDown(KeyDown); + return up == down ? 0 : up ? -1 : 1; + } + + private static OverlayInputScheme CurrentScheme() => PadExports.ConnectedGamepadType() switch + { + null => OverlayInputScheme.Keyboard, + HostGamepadType.DualSense or HostGamepadType.DualShock4 => OverlayInputScheme.PlayStation, + _ => OverlayInputScheme.Xbox, + }; + } } diff --git a/src/SharpEmu.Libs/SaveData/SaveDataExports.cs b/src/SharpEmu.Libs/SaveData/SaveDataExports.cs index 55b22db91..e54eb031e 100644 --- a/src/SharpEmu.Libs/SaveData/SaveDataExports.cs +++ b/src/SharpEmu.Libs/SaveData/SaveDataExports.cs @@ -1464,6 +1464,88 @@ private readonly record struct SearchResult( private readonly record struct SaveEntry(string Name, string Path, DateTime LastWriteUtc); + internal static SaveDataDialogSlot? DescribeDialogSlot(int userId, string? titleId, string dirName) + { + try + { + var resolvedTitleId = string.IsNullOrWhiteSpace(titleId) + ? ResolveConfiguredTitleId() + : SanitizePathSegment(titleId); + var slotDir = SaveDataStorage.SlotDir(ResolveTitleSaveRoot(userId, resolvedTitleId), dirName); + if (!Directory.Exists(slotDir)) + { + return null; + } + + var lastWriteUtc = Directory.GetLastWriteTimeUtc(slotDir); + long sizeBytes = 0; + foreach (var file in new DirectoryInfo(slotDir).EnumerateFiles("*", SearchOption.AllDirectories)) + { + sizeBytes += file.Length; + if (file.LastWriteTimeUtc > lastWriteUtc) + { + lastWriteUtc = file.LastWriteTimeUtc; + } + } + + var iconPath = SaveDataStorage.IconPath(slotDir); + return new SaveDataDialogSlot( + dirName, + slotDir, + SaveDataStorage.ReadMetadata(slotDir), + lastWriteUtc, + sizeBytes, + File.Exists(iconPath) ? iconPath : null); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + internal static bool IsDialogSlotMounted(SaveDataDialogSlot slot) + { + lock (_mountGate) + { + foreach (var mount in _mounts.Values) + { + if (string.Equals(Path.GetFullPath(mount.SlotDir), Path.GetFullPath(slot.SlotDir), + StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + return false; + } + + internal static bool TryDeleteDialogSlot(SaveDataDialogSlot slot) + { + if (IsDialogSlotMounted(slot)) + { + return false; + } + + try + { + if (Directory.Exists(slot.SlotDir)) + { + Directory.Delete(slot.SlotDir, recursive: true); + } + + TraceSaveData($"dialog_delete dir='{slot.DirName}' path='{slot.SlotDir}'"); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + } + + internal static bool TryWriteDialogParam(CpuContext ctx, ulong address, SaveDataDialogSlot slot) => + TryWriteParam(ctx, address, new SaveEntry(slot.DirName, slot.SlotDir, slot.LastWriteUtc)); + [SysAbiExport( Nid = "sDCBrmc61XU", ExportName = "sceSaveDataPrepare", diff --git a/src/SharpEmu.Libs/SaveData/SaveDataListLayer.cs b/src/SharpEmu.Libs/SaveData/SaveDataListLayer.cs new file mode 100644 index 000000000..89a0d07a0 --- /dev/null +++ b/src/SharpEmu.Libs/SaveData/SaveDataListLayer.cs @@ -0,0 +1,296 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Overlay; +using SkiaSharp; + +namespace SharpEmu.Libs.SaveData; + +internal readonly record struct SaveDataListItem( + string Overline, + string Title, + string Detail, + string Date, + string Size, + string? IconPath, + bool IsNew); + +internal sealed record SaveDataListView( + long Session, + string Caption, + IReadOnlyList<SaveDataListItem> Items, + int Focus, + bool BackEnabled, + bool DeleteEnabled, + OverlayInputScheme Scheme, + bool ConfirmingDelete, + string? Notice); + +internal sealed class SaveDataListLayer : OverlayLayer +{ + internal static readonly SaveDataListLayer Instance = OverlayLayers.Register(new SaveDataListLayer()); + + private const float WidthShare = 0.56f; + private const float HeightShare = 0.62f; + + private static readonly Dictionary<string, string> English = new(StringComparer.Ordinal) + { + ["Title"] = "Saved Data", + ["Caption.Load"] = "Select the saved data to load.", + ["Caption.Save"] = "Select where to save.", + ["Caption.Delete"] = "Select the saved data to delete.", + ["Caption.Other"] = "Select saved data.", + ["Select"] = "Select", + ["Back"] = "Back", + ["Move"] = "Move", + ["Delete"] = "Delete", + ["Cancel"] = "Cancel", + ["NewItem"] = "New Saved Data", + ["NewItemDetail"] = "Create a new save in an empty slot.", + ["LastSaved"] = "Last saved", + ["Size"] = "Size", + ["ConfirmDelete"] = "Delete this saved data?", + ["ConfirmDeleteNote"] = "Deleted saved data can't be restored.", + ["InUse"] = "This saved data is in use and can't be deleted.", + }; + + private static readonly OverlayFont ConfirmFont = new(26, OverlayWeight.Bold); + + private readonly OverlayImages _images = new(); + private long _imageSession = -1; + private SaveDataListView? _view; + + private SaveDataListLayer() + { + } + + public override bool IsVisible => Volatile.Read(ref _view) is not null; + + internal static string Text(string key) => + OverlayText.Get(OverlayText.KeyPrefix + "SaveData." + key, English.TryGetValue(key, out var value) ? value : key); + + internal void Show(SaveDataListView view) + { + Volatile.Write(ref _view, view); + Invalidate(); + } + + internal void Hide() + { + Volatile.Write(ref _view, null); + Invalidate(); + } + + public override SKRectI Bounds(int surfaceWidth, int surfaceHeight) + { + if (surfaceWidth < 200 || surfaceHeight < 160) + { + return SKRectI.Empty; + } + + var scale = surfaceHeight / OverlayStyle.ReferenceHeight; + var width = Math.Min(surfaceWidth - 32, Math.Max((int)(860 * scale), (int)(surfaceWidth * WidthShare))); + var height = Math.Min(surfaceHeight - 32, Math.Max((int)(540 * scale), (int)(surfaceHeight * HeightShare))); + return Centered(surfaceWidth, surfaceHeight, width, height); + } + + public override int Render(SKCanvas canvas, int width, int height, float unit) + { + var view = Volatile.Read(ref _view); + using var painter = new OverlayPainter(canvas, OverlayPalette.Current, unit); + painter.Surface(width, height); + if (view is null) + { + return height; + } + + if (_imageSession != view.Session) + { + _images.Clear(); + _imageSession = view.Session; + } + + DrawPanel(painter, width, height, view); + return height; + } + + private void DrawPanel(OverlayPainter p, int width, int height, SaveDataListView view) + { + var palette = p.Palette; + var pad = p.U(OverlayStyle.Padding); + var countText = view.Items.Count == 0 + ? string.Empty + : string.Create(OverlayText.Culture, $"{view.Focus + 1} / {view.Items.Count}"); + var countWidth = countText.Length == 0 ? 0 : p.Measure(countText, OverlayStyle.Body) + pad; + p.Text(Text("Title"), pad, p.U(58), OverlayStyle.Display, palette.Text, width - pad * 2 - countWidth); + p.Text(countText, width - pad, p.U(58), OverlayStyle.Body, palette.Muted, countWidth, SKTextAlign.Right); + p.Text(view.Caption, pad, p.U(90), OverlayStyle.Body, palette.Muted, width - pad * 2); + + var contentTop = p.U(OverlayStyle.HeaderHeight); + var contentBottom = height - p.U(OverlayStyle.FooterHeight); + var listWidth = (width - pad * 3) * 0.5f; + DrawList(p, view, new SKRect(pad, contentTop, pad + listWidth, contentBottom)); + if (view.Items.Count > 0) + { + DrawHero(p, view.Items[view.Focus], + new SKRect(pad * 2 + listWidth, contentTop + p.U(6), width - pad, contentBottom)); + } + + p.Divider(pad, contentBottom, width - pad * 2); + var middle = contentBottom + p.U(OverlayStyle.FooterHeight) / 2; + var prompts = new List<OverlayPrompt> { new(OverlayButton.Confirm, Text("Select"), "Enter") }; + if (view.BackEnabled) + { + prompts.Add(new(OverlayButton.Cancel, Text("Back"), "Esc")); + } + + if (view.DeleteEnabled && view.Items.Count > 0 && !view.Items[view.Focus].IsNew) + { + prompts.Add(new(OverlayButton.Triangle, Text("Delete"), "Del")); + } + + prompts.Add(new(OverlayButton.DirectionalPad, Text("Move"), "↑ ↓")); + var promptsWidth = p.PromptsWidth(prompts, view.Scheme); + p.Prompts(prompts, view.Scheme, width - pad - promptsWidth, middle); + p.Text(view.Notice, pad, middle + p.U(6), OverlayStyle.Detail, OverlayStyle.Notice, + width - pad * 2 - promptsWidth - p.U(24)); + + if (view.ConfirmingDelete && view.Items.Count > 0) + { + DrawConfirm(p, view, width, height); + } + } + + private void DrawList(OverlayPainter p, SaveDataListView view, SKRect area) + { + var rowHeight = p.U(OverlayStyle.ListRowHeight); + var gap = p.U(OverlayStyle.Gap); + var inset = p.U(6); + var top = area.Top + inset; + var available = area.Bottom - inset - top; + var visible = Math.Max(1, (int)((available + gap) / (rowHeight + gap))); + var first = Math.Clamp(view.Focus - visible + 2, 0, Math.Max(0, view.Items.Count - visible)); + var scrollable = view.Items.Count > visible; + var right = area.Right - (scrollable ? p.U(14) : 0); + + p.Canvas.Save(); + p.Canvas.ClipRect(new SKRect(area.Left - p.U(12), area.Top, area.Right + p.U(12), area.Bottom)); + var y = top; + for (var index = first; index < view.Items.Count && index < first + visible; index++) + { + DrawRow(p, view.Items[index], index == view.Focus, new SKRect(area.Left + inset, y, right - inset, y + rowHeight)); + y += rowHeight + gap; + } + + p.Canvas.Restore(); + if (scrollable) + { + p.ScrollBar(new SKRect(area.Right - p.U(4), top, area.Right, area.Bottom - inset), first, visible, + view.Items.Count); + } + } + + private void DrawRow(OverlayPainter p, SaveDataListItem item, bool focused, SKRect bounds) + { + var palette = p.Palette; + p.Card(bounds, focused); + var thumbHeight = bounds.Height - p.U(24); + var thumb = new SKRect(bounds.Left + p.U(12), bounds.MidY - thumbHeight / 2, + bounds.Left + p.U(12) + thumbHeight * 16 / 9, bounds.MidY + thumbHeight / 2); + p.Image(_images.FromFile(item.IconPath), thumb, p.U(OverlayStyle.ImageRadius), item.Title, item.IsNew); + + var textLeft = thumb.Right + p.U(16); + var textWidth = bounds.Right - p.U(16) - textLeft; + var lines = Lines(item.Detail, 2); + var baseline = lines.Length switch + { + 0 => bounds.MidY + p.U(7), + 1 => bounds.MidY - p.U(4), + _ => bounds.MidY - p.U(14), + }; + p.Text(item.Title, textLeft, baseline, OverlayStyle.Title, palette.Text, textWidth); + for (var line = 0; line < lines.Length; line++) + { + baseline += p.U(line == 0 ? 25 : 21); + p.Text(lines[line], textLeft, baseline, OverlayStyle.Detail, + line == 0 && focused ? palette.Secondary : palette.Muted, textWidth); + } + } + + private void DrawHero(OverlayPainter p, SaveDataListItem item, SKRect area) + { + var palette = p.Palette; + var imageHeight = Math.Min(area.Width * 9 / 16, area.Height - p.U(196)); + var y = area.Top; + if (imageHeight >= p.U(60)) + { + p.Image(_images.FromFile(item.IconPath), new SKRect(area.Left, y, area.Right, y + imageHeight), + p.U(OverlayStyle.HeroImageRadius), item.Title, item.IsNew); + y += imageHeight + p.U(24); + } + + if (!string.IsNullOrEmpty(item.Overline)) + { + y += p.U(15); + p.Text(item.Overline.ToUpper(OverlayText.Culture), area.Left, y, OverlayStyle.Overline, palette.Faint, + area.Width); + y += p.U(12); + } + + y += p.U(30); + p.Text(item.Title, area.Left, y, OverlayStyle.Headline, palette.Text, area.Width); + y += p.U(8); + foreach (var line in Lines(item.Detail, 3)) + { + y += p.U(26); + p.Text(line, area.Left, y, OverlayStyle.Body, palette.Secondary, area.Width); + } + + if (string.IsNullOrEmpty(item.Date) && string.IsNullOrEmpty(item.Size)) + { + return; + } + + y += p.U(34); + var x = Meta(p, Text("LastSaved"), item.Date, area.Left, y, area.Right); + Meta(p, Text("Size"), item.Size, x + p.U(28), y, area.Right); + } + + private static float Meta(OverlayPainter p, string label, string value, float x, float baseline, float right) + { + if (string.IsNullOrEmpty(value) || x >= right) + { + return x; + } + + p.Text(label, x, baseline, OverlayStyle.Caption, p.Palette.Faint, right - x); + var valueLeft = x + p.Measure(label, OverlayStyle.Caption) + p.U(10); + p.Text(value, valueLeft, baseline, OverlayStyle.CaptionStrong, p.Palette.Secondary, right - valueLeft); + return valueLeft + p.Measure(value, OverlayStyle.CaptionStrong); + } + + private static void DrawConfirm(OverlayPainter p, SaveDataListView view, int width, int height) + { + var palette = p.Palette; + p.Dim(new SKRect(0, 0, width, height)); + var boxWidth = Math.Min(width - p.U(40), p.U(640)); + var box = SKRect.Create((width - boxWidth) / 2, (height - p.U(232)) / 2, boxWidth, p.U(232)); + p.Modal(box); + var inner = box.Width - p.U(56); + p.Text(Text("ConfirmDelete"), box.MidX, box.Top + p.U(62), ConfirmFont, palette.Text, inner, SKTextAlign.Center); + p.Text(view.Items[view.Focus].Title, box.MidX, box.Top + p.U(98), OverlayStyle.Body, palette.Secondary, inner, + SKTextAlign.Center); + p.Text(Text("ConfirmDeleteNote"), box.MidX, box.Top + p.U(128), OverlayStyle.Detail, palette.Muted, inner, + SKTextAlign.Center); + var prompts = new List<OverlayPrompt> + { + new(OverlayButton.Confirm, Text("Delete"), "Enter"), + new(OverlayButton.Cancel, Text("Cancel"), "Esc"), + }; + var promptsWidth = p.PromptsWidth(prompts, view.Scheme); + p.Prompts(prompts, view.Scheme, box.MidX - promptsWidth / 2, box.Bottom - p.U(46)); + } + + private static string[] Lines(string text, int max) => + text.Split('\n', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Take(max).ToArray(); +} diff --git a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs index 0e3d3bdd0..0aa7ba42a 100644 --- a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs +++ b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs @@ -930,6 +930,7 @@ private static bool TryMapVirtualKey(SDL_Keycode key, out int virtualKey) SDL_Keycode.SDLK_UP => 0x26, SDL_Keycode.SDLK_RIGHT => 0x27, SDL_Keycode.SDLK_DOWN => 0x28, + SDL_Keycode.SDLK_DELETE => 0x2E, >= SDL_Keycode.SDLK_A and <= SDL_Keycode.SDLK_Z => 0x41 + (int)(key - SDL_Keycode.SDLK_A), _ => 0, }; From 74df68c28982d957cc884758b5457b82ba45a4dc Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:52:22 +0300 Subject: [PATCH 24/64] [Overlay] Wrap paragraphs, draw progress bars and shadows, and load encoded images in the overlay kit --- src/SharpEmu.Libs/Overlay/OverlayFonts.cs | 62 +++++++++++++++++++++ src/SharpEmu.Libs/Overlay/OverlayImages.cs | 20 +++++++ src/SharpEmu.Libs/Overlay/OverlayPainter.cs | 44 +++++++++++++++ 3 files changed, 126 insertions(+) diff --git a/src/SharpEmu.Libs/Overlay/OverlayFonts.cs b/src/SharpEmu.Libs/Overlay/OverlayFonts.cs index 29816c2c4..39c7c3e6a 100644 --- a/src/SharpEmu.Libs/Overlay/OverlayFonts.cs +++ b/src/SharpEmu.Libs/Overlay/OverlayFonts.cs @@ -54,6 +54,68 @@ internal static void Draw(SKCanvas canvas, SKPaint paint, string text, float x, } } + internal static List<string> Wrap(string text, float size, OverlayWeight weight, float maxWidth, int maxLines) + { + var lines = new List<string>(); + if (string.IsNullOrEmpty(text) || maxWidth <= 0 || maxLines <= 0) + { + return lines; + } + + lock (Gate) + { + var typeface = Resolve(text, weight); + using var font = Create(typeface, size); + var shaper = Shaper(typeface); + foreach (var paragraph in text.Split('\n')) + { + var runes = paragraph.Trim().EnumerateRunes().ToArray(); + var start = 0; + while (start < runes.Length) + { + if (lines.Count == maxLines - 1) + { + lines.Add(Fit(shaper, font, Join(runes[start..], runes.Length - start), maxWidth)); + return lines; + } + + var end = start; + var lastBreak = -1; + while (end < runes.Length && + shaper.Shape(Join(runes[start..], end - start + 1), font).Width <= maxWidth) + { + if (Rune.IsWhiteSpace(runes[end])) + { + lastBreak = end; + } + + end++; + } + + if (end < runes.Length && lastBreak > start) + { + end = lastBreak; + } + + end = Math.Max(end, start + 1); + lines.Add(Join(runes[start..], end - start).Trim()); + start = end; + while (start < runes.Length && Rune.IsWhiteSpace(runes[start])) + { + start++; + } + } + + if (lines.Count == maxLines) + { + break; + } + } + } + + return lines; + } + private static string Fit(SKShaper shaper, SKFont font, string text, float maxWidth) { if (shaper.Shape(text, font).Width <= maxWidth) diff --git a/src/SharpEmu.Libs/Overlay/OverlayImages.cs b/src/SharpEmu.Libs/Overlay/OverlayImages.cs index 2fc6b0870..5a88049b7 100644 --- a/src/SharpEmu.Libs/Overlay/OverlayImages.cs +++ b/src/SharpEmu.Libs/Overlay/OverlayImages.cs @@ -38,6 +38,26 @@ public sealed class OverlayImages : IDisposable } } + public SKImage? FromBytes(string key, byte[]? encoded) + { + if (encoded is null || encoded.Length == 0) + { + return null; + } + + lock (_gate) + { + if (!_images.TryGetValue(key, out var image)) + { + using var data = SKData.CreateCopy(encoded); + image = SKImage.FromEncodedData(data); + _images[key] = image; + } + + return image; + } + } + public void Clear() { lock (_gate) diff --git a/src/SharpEmu.Libs/Overlay/OverlayPainter.cs b/src/SharpEmu.Libs/Overlay/OverlayPainter.cs index 1eae51904..d2796e347 100644 --- a/src/SharpEmu.Libs/Overlay/OverlayPainter.cs +++ b/src/SharpEmu.Libs/Overlay/OverlayPainter.cs @@ -120,6 +120,50 @@ public void Text(string? text, float x, float baseline, OverlayFont font, SKColo OverlayFonts.Draw(Canvas, _paint, text, x, baseline, U(font.Size), font.Weight, maxWidth, align); } + public float Paragraph(string? text, float x, float baseline, OverlayFont font, SKColor color, float maxWidth, + int maxLines, float lineHeight) + { + if (string.IsNullOrEmpty(text)) + { + return baseline - lineHeight; + } + + var lines = OverlayFonts.Wrap(text, U(font.Size), font.Weight, maxWidth, maxLines); + for (var index = 0; index < lines.Count; index++) + { + Text(lines[index], x, baseline + index * lineHeight, font, color, maxWidth); + } + + return baseline + (Math.Max(1, lines.Count) - 1) * lineHeight; + } + + public IReadOnlyList<string> Wrap(string? text, OverlayFont font, float maxWidth, int maxLines) => + string.IsNullOrEmpty(text) ? [] : OverlayFonts.Wrap(text, U(font.Size), font.Weight, maxWidth, maxLines); + + public void Shadow(SKRect bounds, float radius, float blur, float offsetY, byte alpha) + { + using var shadow = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, U(blur)); + _paint.Style = SKPaintStyle.Fill; + _paint.MaskFilter = shadow; + _paint.Color = new SKColor(0, 0, 0, alpha); + var shifted = bounds; + shifted.Offset(0, U(offsetY)); + Canvas.DrawRoundRect(shifted, radius, radius, _paint); + _paint.MaskFilter = null; + } + + public void Progress(SKRect track, float fraction) + { + var radius = track.Height / 2; + RoundRect(track, radius, Palette.Raised); + var width = track.Width * Math.Clamp(fraction, 0, 1); + if (width > 0) + { + RoundRect(new SKRect(track.Left, track.Top, track.Left + Math.Max(width, track.Height), track.Bottom), radius, + Palette.Accent); + } + } + public void Card(SKRect bounds, bool focused) { var radius = U(OverlayStyle.CardRadius); From 859bf587a689c95f4f0a078a5663d215a95aaf5c Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:52:22 +0300 Subject: [PATCH 25/64] [Overlay] Add a notification card that celebrates in time with its sound accents --- .../Overlay/OverlayNotificationCard.cs | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 src/SharpEmu.Libs/Overlay/OverlayNotificationCard.cs diff --git a/src/SharpEmu.Libs/Overlay/OverlayNotificationCard.cs b/src/SharpEmu.Libs/Overlay/OverlayNotificationCard.cs new file mode 100644 index 000000000..47a520e88 --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayNotificationCard.cs @@ -0,0 +1,318 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using SkiaSharp; + +namespace SharpEmu.Libs.Overlay; + +public sealed record OverlayNotification( + string Overline, + string Tag, + SKColor TagLight, + SKColor TagDeep, + string Title, + string Description, + byte[]? Icon, + string? Footer = null, + int Progress = 0, + int Total = 0); + +public readonly record struct OverlayAccent(double Offset, float Pan, float Strength); + +public readonly record struct OverlayCelebration( + double SinceImpact, + double Charge, + IReadOnlyList<OverlayAccent> Accents, + bool Grand) +{ + public static OverlayCelebration Settled { get; } = new(10, 1, [], false); +} + +public sealed class OverlayNotificationCard : IDisposable +{ + private const float Pad = 20; + private const float IconSize = 92; + private const float IconGap = 18; + + private readonly OverlayNotification _model; + private readonly CultureInfo _culture; + private readonly OverlayImages _images = new(); + private IReadOnlyList<string>? _description; + private float _descriptionWidth = -1; + + public OverlayNotificationCard(OverlayNotification model, CultureInfo culture) + { + _model = model; + _culture = culture; + } + + public float Height(OverlayPainter p, float width) + { + var lines = Description(p, TextWidth(p, width)); + var text = p.U(14) + p.U(27) + lines.Count * p.U(21) + (_model.Total > 0 ? p.U(41) : p.U(8)); + return p.U(Pad) * 2 + Math.Max(p.U(IconSize), text); + } + + public void Draw(OverlayPainter p, SKRect card, OverlayCelebration celebration, double progress) + { + var palette = p.Palette; + var radius = p.U(OverlayStyle.CardRadius * 1.6f); + p.Shadow(card, radius, 18, 8, 0x90); + p.RoundRect(card, radius, palette.Background); + p.Outline(card, radius, palette.Raised); + + var pad = p.U(Pad); + var icon = SKRect.Create(card.Left + pad, card.Top + pad, p.U(IconSize), p.U(IconSize)); + var iconRadius = p.U(OverlayStyle.ImageRadius * 1.5f); + DrawGlow(p, icon, iconRadius, celebration); + p.Image(_images.FromBytes("icon", _model.Icon), icon, iconRadius, _model.Title); + DrawImpact(p, icon, iconRadius, celebration); + DrawBadge(p, icon, BadgeScale(celebration)); + DrawSparkles(p, icon, celebration); + + var textLeft = icon.Right + p.U(IconGap); + var textWidth = TextWidth(p, card.Width); + var baseline = card.Top + pad + p.U(14); + var overline = _model.Overline.ToUpper(_culture); + p.Text(overline, textLeft, baseline, OverlayStyle.Overline, palette.Muted, textWidth); + if (!string.IsNullOrEmpty(_model.Tag)) + { + var tagLeft = textLeft + p.Measure(overline, OverlayStyle.Overline) + p.U(10); + p.RoundRect(SKRect.Create(tagLeft, baseline - p.U(5.5f), p.U(5), p.U(5)), p.U(2.5f), _model.TagLight); + p.Text(_model.Tag.ToUpper(_culture), tagLeft + p.U(11), baseline, OverlayStyle.Overline, _model.TagLight, + textLeft + textWidth - tagLeft - p.U(11)); + } + + baseline += p.U(27); + p.Text(_model.Title, textLeft, baseline, OverlayStyle.Title, palette.Text, textWidth); + foreach (var line in Description(p, textWidth)) + { + baseline += p.U(21); + p.Text(line, textLeft, baseline, OverlayStyle.Detail, palette.Secondary, textWidth); + } + + if (_model.Total <= 0) + { + return; + } + + var fill = Math.Clamp(progress, 0, 1); + var reached = Math.Clamp(_model.Progress, 0, _model.Total); + var before = Math.Max(0, reached - 1); + baseline += p.U(28); + var count = string.Create(_culture, $"{(fill > 0.5 ? reached : before)} / {_model.Total}"); + var countWidth = p.Measure(count, OverlayStyle.CaptionStrong); + p.Text(_model.Footer, textLeft, baseline, OverlayStyle.Caption, palette.Muted, textWidth - countWidth - p.U(12)); + p.Text(count, textLeft + textWidth, baseline, OverlayStyle.CaptionStrong, palette.Secondary, countWidth + 1, + SKTextAlign.Right); + p.Progress(SKRect.Create(textLeft, baseline + p.U(9), textWidth, p.U(4)), + (float)((before + (reached - before) * fill) / _model.Total)); + } + + public void Dispose() => _images.Dispose(); + + private float TextWidth(OverlayPainter p, float cardWidth) => + cardWidth - p.U(Pad) * 2 - p.U(IconSize) - p.U(IconGap); + + private IReadOnlyList<string> Description(OverlayPainter p, float width) + { + if (_description is null || Math.Abs(_descriptionWidth - width) > 0.5f) + { + _description = p.Wrap(_model.Description, OverlayStyle.Detail, width, 2); + _descriptionWidth = width; + } + + return _description; + } + + private static double BadgeScale(OverlayCelebration celebration) + { + var since = celebration.SinceImpact; + return since < 0 + ? 0.35 + 0.25 * celebration.Charge + : 1 + Math.Exp(-since * 7) * Math.Sin(since * 18) * 0.35; + } + + private void DrawGlow(OverlayPainter p, SKRect icon, float radius, OverlayCelebration celebration) + { + var since = celebration.SinceImpact; + var strength = since < 0 + ? 0.75 * Math.Pow(celebration.Charge, 1.5) + : 0.28 + 0.72 * Math.Exp(-since * 2.6); + if (celebration.Grand && since >= 0) + { + strength += 0.12 * (1 + Math.Sin(since * 5)); + } + + strength = Math.Clamp(strength, 0, 1); + if (strength <= 0.01) + { + return; + } + + using var blur = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, p.U(10 + 12 * (float)strength)); + using var paint = new SKPaint + { + IsAntialias = true, + MaskFilter = blur, + Color = _model.TagLight.WithAlpha((byte)(strength * 210)), + }; + var halo = icon; + halo.Inflate(p.U(3), p.U(3)); + p.Canvas.DrawRoundRect(halo, radius + p.U(3), radius + p.U(3), paint); + } + + private void DrawImpact(OverlayPainter p, SKRect icon, float radius, OverlayCelebration celebration) + { + var since = celebration.SinceImpact; + if (since < 0 || since > 1.6) + { + return; + } + + p.Canvas.Save(); + p.Canvas.ClipRoundRect(new SKRoundRect(icon, radius, radius), antialias: true); + var flash = Math.Exp(-since * 9) * 0.6; + if (flash > 0.01) + { + p.Rect(icon, SKColors.White.WithAlpha((byte)(flash * 255))); + } + + var sweep = (since - 0.05) / 0.6; + if (sweep is > 0 and < 1) + { + var eased = 1 - Math.Pow(1 - sweep, 3); + var band = icon.Width * 0.38f; + var center = icon.Left - band + (float)eased * (icon.Width + band * 2); + using var shader = SKShader.CreateLinearGradient( + new SKPoint(center - band / 2, icon.Top), + new SKPoint(center + band / 2, icon.Top + band * 0.4f), + [SKColors.White.WithAlpha(0), SKColors.White.WithAlpha(150), SKColors.White.WithAlpha(0)], + [0f, 0.5f, 1f], + SKShaderTileMode.Clamp); + using var paint = new SKPaint { IsAntialias = true, Shader = shader }; + p.Canvas.DrawRect(icon, paint); + } + + p.Canvas.Restore(); + Ring(p, icon, since); + if (celebration.Grand) + { + Ring(p, icon, since - 0.38); + } + } + + private void Ring(OverlayPainter p, SKRect icon, double age) + { + const double Life = 0.6; + if (age < 0 || age > Life) + { + return; + } + + var progress = age / Life; + var eased = (float)(1 - Math.Pow(1 - progress, 3)); + using var paint = new SKPaint + { + IsAntialias = true, + Style = SKPaintStyle.Stroke, + StrokeWidth = Math.Max(1, p.U(3) * (1 - eased * 0.6f)), + Color = _model.TagLight.WithAlpha((byte)((1 - progress) * 230)), + }; + var radius = icon.Width * 0.5f * (1.02f + 0.4f * eased); + p.Canvas.DrawRoundRect( + SKRect.Create(icon.MidX - radius, icon.MidY - radius, radius * 2, radius * 2), + radius * 0.45f, + radius * 0.45f, + paint); + } + + private void DrawSparkles(OverlayPainter p, SKRect icon, OverlayCelebration celebration) + { + const double Life = 0.65; + var since = celebration.SinceImpact; + if (since < 0) + { + return; + } + + for (var index = 0; index < celebration.Accents.Count; index++) + { + var accent = celebration.Accents[index]; + var age = since - accent.Offset; + if (age < 0 || age > Life) + { + continue; + } + + var progress = age / Life; + var jitter = ((index * 37) % 11 - 5) * 0.05; + var angle = Math.PI * (0.95 + 0.8 * (accent.Pan + 0.8) / 1.6) + jitter; + var reach = icon.Width * 0.5f * (0.8f + 0.55f * (float)(1 - Math.Pow(1 - progress, 2))); + var cx = icon.MidX + (float)Math.Cos(angle) * reach; + var cy = icon.MidY + (float)Math.Sin(angle) * reach; + var twinkle = (float)Math.Sin(Math.PI * progress); + var size = p.U(5 + 6 * accent.Strength) * twinkle; + if (size <= 0.2f) + { + continue; + } + + using (var blur = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, size * 0.9f)) + using (var halo = new SKPaint + { + IsAntialias = true, + MaskFilter = blur, + Color = _model.TagLight.WithAlpha((byte)(twinkle * 170)), + }) + { + p.Canvas.DrawCircle(cx, cy, size * 0.9f, halo); + } + + using var star = new SKPath(); + var waist = size * 0.22f; + star.MoveTo(cx, cy - size); + star.QuadTo(cx + waist, cy - waist, cx + size, cy); + star.QuadTo(cx + waist, cy + waist, cx, cy + size); + star.QuadTo(cx - waist, cy + waist, cx - size, cy); + star.QuadTo(cx - waist, cy - waist, cx, cy - size); + star.Close(); + using var fill = new SKPaint + { + IsAntialias = true, + Color = SKColors.White.WithAlpha((byte)(Math.Min(1, twinkle * 1.4f) * 255)), + }; + p.Canvas.DrawPath(star, fill); + } + } + + private void DrawBadge(OverlayPainter p, SKRect icon, double pop) + { + var radius = p.U(14) * (float)pop; + if (radius <= 0) + { + return; + } + + var cx = icon.Right - p.U(2); + var cy = icon.Bottom - p.U(2); + var rim = radius + p.U(3); + p.RoundRect(SKRect.Create(cx - rim, cy - rim, rim * 2, rim * 2), rim, p.Palette.Background); + using var shader = SKShader.CreateLinearGradient( + new SKPoint(cx - radius, cy - radius), + new SKPoint(cx + radius, cy + radius), + [_model.TagLight, _model.TagDeep], + SKShaderTileMode.Clamp); + using var fill = new SKPaint { IsAntialias = true, Shader = shader }; + p.Canvas.DrawCircle(cx, cy, radius, fill); + using var shine = new SKPaint + { + IsAntialias = true, + Style = SKPaintStyle.Stroke, + StrokeWidth = Math.Max(1, p.U(1.5f)), + Color = SKColors.White.WithAlpha(0x70), + }; + p.Canvas.DrawCircle(cx, cy, Math.Max(1, radius - p.U(3.5f)), shine); + } +} From 8241502acd0e3eec36834ba9e0783edeb9e86c85 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:52:22 +0300 Subject: [PATCH 26/64] [GUI] Draw overlay kit surfaces in Avalonia windows with the launcher theme palette --- src/SharpEmu.GUI/Controls/OverlaySurface.cs | 58 +++++++++++++++++++++ src/SharpEmu.GUI/LauncherThemes.cs | 22 ++++++++ 2 files changed, 80 insertions(+) create mode 100644 src/SharpEmu.GUI/Controls/OverlaySurface.cs diff --git a/src/SharpEmu.GUI/Controls/OverlaySurface.cs b/src/SharpEmu.GUI/Controls/OverlaySurface.cs new file mode 100644 index 000000000..42df3ff85 --- /dev/null +++ b/src/SharpEmu.GUI/Controls/OverlaySurface.cs @@ -0,0 +1,58 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.Platform; +using Avalonia.Rendering.SceneGraph; +using Avalonia.Skia; +using SkiaSharp; + +namespace SharpEmu.GUI.Controls; + +internal sealed class OverlaySurface : Control +{ + public Action<SKCanvas, Size>? Paint { get; set; } + + public override void Render(DrawingContext context) + { + if (Paint is { } paint) + { + context.Custom(new Operation(new Rect(Bounds.Size), paint)); + } + } + + private sealed class Operation(Rect bounds, Action<SKCanvas, Size> paint) : ICustomDrawOperation + { + public Rect Bounds { get; } = bounds; + + public bool HitTest(Point point) => false; + + public bool Equals(ICustomDrawOperation? other) => false; + + public void Dispose() + { + } + + public void Render(ImmediateDrawingContext context) + { + if (context.TryGetFeature<ISkiaSharpApiLeaseFeature>() is not { } feature) + { + return; + } + + using var lease = feature.Lease(); + var canvas = lease.SkCanvas; + var saved = canvas.Save(); + try + { + paint(canvas, Bounds.Size); + } + finally + { + canvas.RestoreToCount(saved); + } + } + } +} diff --git a/src/SharpEmu.GUI/LauncherThemes.cs b/src/SharpEmu.GUI/LauncherThemes.cs index 3cf1b61b2..38f4195dd 100644 --- a/src/SharpEmu.GUI/LauncherThemes.cs +++ b/src/SharpEmu.GUI/LauncherThemes.cs @@ -347,6 +347,28 @@ public static string EmulatorPalette(GuiSettings settings) palette.Accent, palette.AccentForeground); } + public static SharpEmu.Libs.Overlay.OverlayPalette CurrentOverlayPalette() + { + SkiaSharp.SKColor Read(string key, SkiaSharp.SKColor fallback) => + Brush(key) is ISolidColorBrush { Color: var color } + ? new SkiaSharp.SKColor(color.R, color.G, color.B) + : fallback; + + var graphite = SharpEmu.Libs.Overlay.OverlayPalette.Graphite; + return new SharpEmu.Libs.Overlay.OverlayPalette( + Read("BgBrush", graphite.Background), + Read("GameOptionsMenuBrush", graphite.Menu), + Read("CardBrush", graphite.Card), + Read("ElevatedBrush", graphite.Elevated), + Read("RaisedHoverBrush", graphite.Raised), + Read("TextBrush", graphite.Text), + Read("SecondaryTextBrush", graphite.Secondary), + Read("MutedBrush", graphite.Muted), + Read("FaintBrush", graphite.Faint), + Read("AccentBrush", graphite.Accent), + Read("AccentForegroundBrush", graphite.AccentForeground)); + } + public static void Apply(LauncherAppearance appearance) { if (Avalonia.Application.Current is not { } app) From 68d32b808035764d7442edc50dc6000bd3866a37 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:52:22 +0300 Subject: [PATCH 27/64] [GUI] Report the trophy chime's sparkle note timings --- src/SharpEmu.GUI/TrophySound.cs | 35 ++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.GUI/TrophySound.cs b/src/SharpEmu.GUI/TrophySound.cs index da4ebacd9..a2f641a2c 100644 --- a/src/SharpEmu.GUI/TrophySound.cs +++ b/src/SharpEmu.GUI/TrophySound.cs @@ -12,6 +12,7 @@ internal static class TrophySound private const int SampleRate = 48000; private static readonly Dictionary<int, byte[]> Rendered = []; + private static readonly Dictionary<int, SharpEmu.Libs.Overlay.OverlayAccent[]> RenderedAccents = []; public static bool Enabled { get; set; } = true; @@ -53,8 +54,27 @@ private static byte[] Get(int grade) } } + public static IReadOnlyList<SharpEmu.Libs.Overlay.OverlayAccent> Accents(int grade) + { + grade = Math.Clamp(grade, 1, 4); + lock (RenderedAccents) + { + if (RenderedAccents.TryGetValue(grade, out var cached)) + { + return cached; + } + } + + Render(grade); + lock (RenderedAccents) + { + return RenderedAccents[grade]; + } + } + internal static byte[] Render(int grade) { + var accents = new List<SharpEmu.Libs.Overlay.OverlayAccent>(); var tail = grade switch { 1 => 3.2, 2 => 2.6, _ => 2.2 }; var length = (int)((ImpactDelaySeconds + tail) * SampleRate); var left = new double[length]; @@ -85,9 +105,12 @@ internal static byte[] Render(int grade) double[] pentatonic = [1975.53, 2217.46, 2489.02, 2959.96, 3322.44, 3951.07]; for (var i = 0; i < sparkles; i++) { - var start = impact + (int)((0.05 + random.NextDouble() * (grade == 1 ? 1.1 : 0.6)) * SampleRate); - AddMallet(left, right, start, pentatonic[random.Next(pentatonic.Length)], 0.05 + random.NextDouble() * 0.04, 6.5, - random.NextDouble() * 1.6 - 0.8); + var offset = 0.05 + random.NextDouble() * (grade == 1 ? 1.1 : 0.6); + var note = pentatonic[random.Next(pentatonic.Length)]; + var gain = 0.05 + random.NextDouble() * 0.04; + var pan = random.NextDouble() * 1.6 - 0.8; + AddMallet(left, right, impact + (int)(offset * SampleRate), note, gain, 6.5, pan); + accents.Add(new(offset, (float)pan, (float)(gain / 0.09))); } if (grade == 1) @@ -96,9 +119,15 @@ internal static byte[] Render(int grade) for (var i = 0; i < climb.Length; i++) { AddMallet(left, right, impact + (int)((0.38 + i * 0.075) * SampleRate), climb[i], 0.12, 3.0, -0.3 + i * 0.2); + accents.Add(new(0.38 + i * 0.075, (float)(-0.3 + i * 0.2), 1.35f)); } } + lock (RenderedAccents) + { + RenderedAccents[grade] = [.. accents.OrderBy(accent => accent.Offset)]; + } + Reverb(left, right, grade == 1 ? 0.34 : 0.26); return ToPcm(left, right); } From fffc487fa2689169a7bd6027b8c3858e55e445c5 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:52:22 +0300 Subject: [PATCH 28/64] [GUI] Draw trophy notifications with the overlay notification card --- src/SharpEmu.GUI/TrophyToast.cs | 748 +++----------------------------- 1 file changed, 60 insertions(+), 688 deletions(-) diff --git a/src/SharpEmu.GUI/TrophyToast.cs b/src/SharpEmu.GUI/TrophyToast.cs index 42f4b770e..63a2c28c0 100644 --- a/src/SharpEmu.GUI/TrophyToast.cs +++ b/src/SharpEmu.GUI/TrophyToast.cs @@ -3,11 +3,10 @@ using Avalonia; using Avalonia.Controls; -using Avalonia.Layout; using Avalonia.Media; -using Avalonia.Rendering.Composition; -using Avalonia.Rendering.Composition.Animations; using SharpEmu.GUI.Controls; +using SharpEmu.Libs.Overlay; +using SkiaSharp; using System.Diagnostics; using System.Runtime.InteropServices; @@ -24,66 +23,29 @@ internal sealed record TrophyToastContent( internal sealed class TrophyToast : Window { - private const double WindowWidth = 840; - private const double WindowHeight = 340; - private const double CardWidth = 600; - private const double CardHeight = 158; - private const double CardMargin = 28; - private const double MedalSize = 104; - private const double MedalColumn = 140; - private const double PillSize = 56; - private const double CardRadius = 28; - private const double PopSeconds = 0.22; - private const double ExpandAt = 0.22; - private const double TextAt = 0.55; - private const double ExitSeconds = 0.45; - private const double SpinStart = 0.15; - private const double Impact = SpinStart + TrophySound.ImpactDelaySeconds; + private const double WindowWidth = 640; + private const double WindowHeight = 260; + private const float CardWidth = 560; + private const float CardMargin = 36; + private const float Unit = 0.9f; + private const double EnterSeconds = 0.32; + private const double ExitSeconds = 0.4; + private const double ChimeAt = 0.15; + private const double Impact = ChimeAt + TrophySound.ImpactDelaySeconds; private static readonly Queue<TrophyToastContent> Pending = new(); private static bool _showing; - // A sparkle's whole flight is handed to the compositor as keyframes when it spawns; the clock only retires it. - private sealed record Sparkle(Control Visual, double ExpiresAt); - - private const double SparkleSampleSeconds = 1.0 / 30; - - private static readonly Geometry SparkleShape = Geometry.Parse( - "M50,0 C53,35 65,47 100,50 C65,53 53,65 50,100 C47,65 35,53 0,50 C35,47 47,35 50,0 Z"); - private readonly TrophyToastContent _content; - private readonly Color _light, _mid, _dark; + private readonly OverlayPalette _palette = LauncherThemes.CurrentOverlayPalette(); + private readonly OverlayNotificationCard _card; + private readonly IReadOnlyList<OverlayAccent> _accents; private readonly bool _reducedMotion = ReducedMotion(); private readonly double _leaveAt; private readonly Stopwatch _clock = new(); - private readonly Random _random = new(); - private readonly List<Sparkle> _sparkles = []; - private readonly Canvas _overlay = new() { IsHitTestVisible = false }; - private readonly Grid _cardHost = new(); - private readonly Border _cardBorder = new(); - private readonly Border _edgeBorder = new(); - private readonly TranslateTransform _cardShift = new(); - private readonly ScaleTransform _cardScale = new(); - private readonly TranslateTransform _medalShift = new(); - private readonly Border _glow = new(); - private readonly TrophyMedal _medal = new() { Width = MedalSize, Height = MedalSize }; - private readonly ScaleTransform _medalScale = new(); - private readonly Border _burst = new(); - private readonly Canvas _rays = new() { IsHitTestVisible = false }; - private readonly Border _ring = new(); - private readonly ScaleTransform _ringScale = new(); - private readonly Border _shine = new(); - private readonly TranslateTransform _shineShift = new(); - private readonly TranslateTransform _auroraA = new(); - private readonly TranslateTransform _auroraB = new(); - private readonly RotateTransform _edgeSpin = new(); - private readonly Border _progressFill = new(); - private readonly ScaleTransform _progressScale = new(0, 1); - private readonly TextBlock _progressText = new(); - private readonly List<(Control Line, TranslateTransform Shift, double Delay)> _lines = []; + private readonly OverlaySurface _surface = new() { IsHitTestVisible = false }; + private double _time; private bool _chimed; - private bool _burstDone; - private bool _secondBurstDone; private bool _closed; public static void Show(TrophyToastContent content) @@ -106,7 +68,6 @@ private static void ShowNext() _showing = false; ShowNext(); }; - toast.Opacity = 0; toast.Show(); toast.Place(); toast.MakeClickThrough(); @@ -116,7 +77,21 @@ private static void ShowNext() private TrophyToast(TrophyToastContent content) { _content = content; - (_light, _mid, _dark) = TrophyMedal.Palette(content.Grade); + var (light, mid, _) = TrophyMedal.Palette(content.Grade); + _card = new OverlayNotificationCard( + new OverlayNotification( + Localization.Instance.Get("Trophies.Unlocked"), + TrophyUi.GradeName(content.Grade), + new SKColor(light.R, light.G, light.B), + new SKColor(mid.R, mid.G, mid.B), + content.Name, + content.Description, + content.IconPng, + content.GameName, + content.Earned, + content.Total), + OverlayText.CultureFor(Localization.Instance.CurrentCode)); + _accents = TrophySound.Accents(content.Grade); _leaveAt = content.Grade == 1 ? 4.0 : 3.5; Width = WindowWidth; @@ -129,7 +104,8 @@ private TrophyToast(TrophyToastContent content) Background = Brushes.Transparent; TransparencyLevelHint = [WindowTransparencyLevel.Transparent]; - Content = BuildContent(); + _surface.Paint = Paint; + Content = _surface; } protected override void OnClosed(EventArgs e) @@ -138,372 +114,9 @@ protected override void OnClosed(EventArgs e) base.OnClosed(e); } - private static double CardLeft => WindowWidth - CardMargin - CardWidth; - - private static Point MedalCenter => new(CardLeft + MedalColumn / 2, CardMargin + CardHeight / 2); - - private Control BuildContent() - { - var root = new Grid { IsHitTestVisible = false }; - root.Children.Add(BuildCard()); - root.Children.Add(_overlay); - - _ring.Width = MedalSize; - _ring.Height = MedalSize; - _ring.CornerRadius = new CornerRadius(MedalSize / 2); - _ring.BorderBrush = new SolidColorBrush(_light); - _ring.BorderThickness = new Thickness(3); - _ring.Opacity = 0; - _ring.RenderTransformOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative); - _ring.RenderTransform = _ringScale; - _ring.BoxShadow = new BoxShadows(new BoxShadow { Blur = 18, Color = Color.FromArgb(200, _mid.R, _mid.G, _mid.B) }); - Canvas.SetLeft(_ring, MedalCenter.X - MedalSize / 2); - Canvas.SetTop(_ring, MedalCenter.Y - MedalSize / 2); - _overlay.Children.Add(_ring); - return root; - } - - private Control BuildCard() - { - var (deep, deeper) = _content.Grade switch - { - 1 => (Color.Parse("#1F4466"), Color.Parse("#2B1A52")), - 2 => (Color.Parse("#5A3F0C"), Color.Parse("#2A1838")), - 3 => (Color.Parse("#39424F"), Color.Parse("#1B2030")), - _ => (Color.Parse("#5A2E17"), Color.Parse("#26172E")), - }; - - var aurora = new Canvas { IsHitTestVisible = false }; - aurora.Children.Add(Blob(_mid, 150, 360, -60, -170, _auroraA)); - aurora.Children.Add(Blob(Color.Parse("#8C6CFF"), 110, 320, 330, -60, _auroraB)); - - var glass = new Border - { - IsHitTestVisible = false, - Background = new LinearGradientBrush - { - StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative), - EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative), - GradientStops = - { - new GradientStop(Color.FromArgb(34, 255, 255, 255), 0), - new GradientStop(Color.FromArgb(0, 255, 255, 255), 0.55), - }, - }, - }; - - var content = new Grid - { - ColumnDefinitions = new ColumnDefinitions($"{MedalColumn},*"), - Width = CardWidth, - Height = CardHeight, - HorizontalAlignment = HorizontalAlignment.Left, - VerticalAlignment = VerticalAlignment.Top, - }; - content.Children.Add(BuildMedalArea()); - var text = BuildText(); - Grid.SetColumn(text, 1); - content.Children.Add(text); - - _shine.Width = 140; - _shine.Height = CardHeight * 2.2; - _shine.HorizontalAlignment = HorizontalAlignment.Left; - _shine.VerticalAlignment = VerticalAlignment.Center; - _shine.IsHitTestVisible = false; - _shine.Opacity = 0; - _shine.Background = new LinearGradientBrush - { - StartPoint = new RelativePoint(0, 0.5, RelativeUnit.Relative), - EndPoint = new RelativePoint(1, 0.5, RelativeUnit.Relative), - GradientStops = - { - new GradientStop(Color.FromArgb(0, 255, 255, 255), 0), - new GradientStop(Color.FromArgb(60, 255, 255, 255), 0.5), - new GradientStop(Color.FromArgb(0, 255, 255, 255), 1), - }, - }; - _shine.RenderTransform = new TransformGroup { Children = { new RotateTransform(20), _shineShift } }; - - var layers = new Grid(); - layers.Children.Add(aurora); - layers.Children.Add(glass); - layers.Children.Add(content); - layers.Children.Add(_shine); - - var card = _cardBorder; - card.CornerRadius = new CornerRadius(CardRadius); - card.ClipToBounds = true; - card.Background = new LinearGradientBrush - { - StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative), - EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative), - GradientStops = - { - new GradientStop(Color.FromArgb(245, deep.R, deep.G, deep.B), 0), - new GradientStop(Color.FromArgb(245, deeper.R, deeper.G, deeper.B), 1), - }, - }; - card.Child = layers; - - var edgeBrush = new LinearGradientBrush - { - StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative), - EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative), - Transform = _edgeSpin, - TransformOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), - }; - if (_content.Grade == 1) - { - edgeBrush.GradientStops.Add(new GradientStop(Color.Parse("#E08FE3FF"), 0)); - edgeBrush.GradientStops.Add(new GradientStop(Color.Parse("#C09B7CFF"), 0.35)); - edgeBrush.GradientStops.Add(new GradientStop(Color.Parse("#B0FF8FD8"), 0.65)); - edgeBrush.GradientStops.Add(new GradientStop(Color.Parse("#E08FE3FF"), 1)); - } - else - { - edgeBrush.GradientStops.Add(new GradientStop(Color.FromArgb(220, _light.R, _light.G, _light.B), 0)); - edgeBrush.GradientStops.Add(new GradientStop(Color.FromArgb(90, _mid.R, _mid.G, _mid.B), 0.45)); - edgeBrush.GradientStops.Add(new GradientStop(Color.FromArgb(30, 255, 255, 255), 1)); - } - - var edge = _edgeBorder; - edge.CornerRadius = new CornerRadius(CardRadius); - edge.BorderBrush = edgeBrush; - edge.BorderThickness = new Thickness(1.5); - edge.IsHitTestVisible = false; - - _glow.CornerRadius = new CornerRadius(CardRadius); - _glow.Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)); - _glow.BoxShadow = new BoxShadows( - new BoxShadow { OffsetY = 16, Blur = 36, Color = Color.FromArgb(150, 0, 0, 0) }, - [new BoxShadow { Blur = _content.Grade == 1 ? 56 : 38, Spread = 2, Color = Color.FromArgb(_content.Grade == 1 ? (byte)170 : (byte)120, _mid.R, _mid.G, _mid.B) }]); - - _cardHost.Width = CardWidth; - _cardHost.Height = CardHeight; - _cardHost.HorizontalAlignment = HorizontalAlignment.Right; - _cardHost.VerticalAlignment = VerticalAlignment.Top; - _cardHost.Margin = new Thickness(0, CardMargin, CardMargin, 0); - _cardHost.RenderTransformOrigin = new RelativePoint(1, 0, RelativeUnit.Relative); - _cardHost.RenderTransform = new TransformGroup { Children = { _cardScale, _cardShift } }; - _cardHost.Children.Add(_glow); - _cardHost.Children.Add(card); - _cardHost.Children.Add(edge); - return _cardHost; - } - - private Control BuildMedalArea() - { - var area = new Grid { Width = MedalColumn, Height = CardHeight }; - - _burst.Width = MedalSize * 1.7; - _burst.Height = MedalSize * 1.7; - _burst.CornerRadius = new CornerRadius(MedalSize); - _burst.HorizontalAlignment = HorizontalAlignment.Center; - _burst.VerticalAlignment = VerticalAlignment.Center; - _burst.Background = new RadialGradientBrush - { - GradientStops = - { - new GradientStop(Color.FromArgb(200, _light.R, _light.G, _light.B), 0), - new GradientStop(Color.FromArgb(70, _mid.R, _mid.G, _mid.B), 0.45), - new GradientStop(Color.FromArgb(0, _mid.R, _mid.G, _mid.B), 1), - }, - }; - _burst.Opacity = 0.35; - area.Children.Add(_burst); - - if (_content.Grade <= 2 && !_reducedMotion) - { - BuildRays(); - area.Children.Add(_rays); - } - - _medal.Grade = _content.Grade; - _medal.Icon = TrophyUi.LoadIcon(_content.IconPng); - _medal.HorizontalAlignment = HorizontalAlignment.Center; - _medal.VerticalAlignment = VerticalAlignment.Center; - _medal.RenderTransformOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative); - _medal.RenderTransform = new TransformGroup { Children = { _medalScale, _medalShift } }; - area.Children.Add(_medal); - return area; - } - - private Control BuildText() - { - var label = new TextBlock - { - Text = Localization.Instance.Get("Trophies.Unlocked").ToUpperInvariant(), - Foreground = new SolidColorBrush(Color.FromArgb(200, 255, 255, 255)), - FontSize = 11.5, - FontWeight = FontWeight.Bold, - LetterSpacing = 2, - VerticalAlignment = VerticalAlignment.Center, - }; - var pill = new Border - { - CornerRadius = new CornerRadius(10), - Padding = new Thickness(9, 2, 9, 3), - VerticalAlignment = VerticalAlignment.Center, - Background = new LinearGradientBrush - { - StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative), - EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative), - GradientStops = { new GradientStop(_light, 0), new GradientStop(_mid, 1) }, - }, - Child = new TextBlock - { - Text = TrophyUi.GradeName(_content.Grade).ToUpperInvariant(), - Foreground = new SolidColorBrush(TrophyMedal.Shade(_dark, 0.55)), - FontSize = 10.5, - FontWeight = FontWeight.Black, - LetterSpacing = 1.2, - }, - }; - var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Children = { label, pill } }; - var name = new TextBlock - { - Text = _content.Name, - Foreground = Brushes.White, - FontSize = 21, - FontWeight = FontWeight.Bold, - TextTrimming = TextTrimming.CharacterEllipsis, - }; - var description = new TextBlock - { - Text = _content.Description, - Foreground = new SolidColorBrush(Color.FromArgb(185, 255, 255, 255)), - FontSize = 13, - TextWrapping = TextWrapping.Wrap, - MaxHeight = 36, - TextTrimming = TextTrimming.CharacterEllipsis, - }; - - var stack = new StackPanel - { - Spacing = 3, - Margin = new Thickness(0, 16, 24, 14), - VerticalAlignment = VerticalAlignment.Center, - Children = { header, name, description }, - }; - if (_content.Total > 0) - { - stack.Children.Add(BuildProgress()); - } - - for (var i = 0; i < stack.Children.Count; i++) - { - var shift = new TranslateTransform(); - stack.Children[i].RenderTransform = shift; - _lines.Add((stack.Children[i], shift, TextAt + i * 0.09)); - } - - return stack; - } - - private Control BuildProgress() - { - var game = new TextBlock - { - Text = _content.GameName ?? string.Empty, - Foreground = new SolidColorBrush(Color.FromArgb(170, 255, 255, 255)), - FontSize = 11.5, - TextTrimming = TextTrimming.CharacterEllipsis, - }; - _progressText.Foreground = new SolidColorBrush(Color.FromArgb(220, 255, 255, 255)); - _progressText.FontSize = 11.5; - _progressText.FontWeight = FontWeight.SemiBold; - _progressText.Text = $"{Math.Max(0, _content.Earned - 1)} / {_content.Total}"; - var labels = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; - labels.Children.Add(game); - Grid.SetColumn(_progressText, 1); - labels.Children.Add(_progressText); - - // The fill is a full-width bar scaled from its left edge, so progress never triggers a layout pass. - _progressFill.RenderTransformOrigin = new RelativePoint(0, 0.5, RelativeUnit.Relative); - _progressFill.RenderTransform = _progressScale; - _progressScale.ScaleX = PercentOf(_content.Earned - 1) / 100; - _progressFill.Background = new LinearGradientBrush - { - StartPoint = new RelativePoint(0, 0.5, RelativeUnit.Relative), - EndPoint = new RelativePoint(1, 0.5, RelativeUnit.Relative), - GradientStops = { new GradientStop(_mid, 0), new GradientStop(_light, 1) }, - }; - var track = new Border - { - Height = 4, - CornerRadius = new CornerRadius(2), - ClipToBounds = true, - Background = new SolidColorBrush(Color.FromArgb(45, 255, 255, 255)), - Child = _progressFill, - }; - - return new StackPanel { Spacing = 4, Margin = new Thickness(0, 8, 0, 0), Children = { labels, track } }; - } - - private double PercentOf(int earned) => _content.Total == 0 ? 0 : Math.Clamp(earned, 0, _content.Total) * 100.0 / _content.Total; - - private static Control Blob(Color color, byte alpha, double size, double left, double top, TranslateTransform shift) - { - var blob = new Border - { - Width = size, - Height = size, - CornerRadius = new CornerRadius(size / 2), - Background = new RadialGradientBrush - { - GradientStops = - { - new GradientStop(Color.FromArgb(alpha, color.R, color.G, color.B), 0), - new GradientStop(Color.FromArgb(0, color.R, color.G, color.B), 1), - }, - }, - RenderTransform = shift, - }; - Canvas.SetLeft(blob, left); - Canvas.SetTop(blob, top); - return blob; - } - - private void BuildRays() - { - const double length = 120; - _rays.Width = MedalColumn; - _rays.Height = CardHeight; - _rays.Opacity = 0; - var count = _content.Grade == 1 ? 16 : 10; - for (var i = 0; i < count; i++) - { - var ray = new Border - { - Width = i % 2 == 0 ? 10 : 5, - Height = length, - Background = new LinearGradientBrush - { - StartPoint = new RelativePoint(0.5, 0, RelativeUnit.Relative), - EndPoint = new RelativePoint(0.5, 1, RelativeUnit.Relative), - GradientStops = - { - new GradientStop(Color.FromArgb(0, _light.R, _light.G, _light.B), 0), - new GradientStop(Color.FromArgb(120, _light.R, _light.G, _light.B), 1), - }, - }, - RenderTransformOrigin = new RelativePoint(0.5, 1, RelativeUnit.Relative), - RenderTransform = new RotateTransform(i * 360.0 / count), - }; - Canvas.SetLeft(ray, MedalColumn / 2 - ray.Width / 2); - Canvas.SetTop(ray, CardHeight / 2 - length); - _rays.Children.Add(ray); - } - } - private void Start() { _clock.Start(); - if (!_reducedMotion) - { - StartAmbientAnimations(); - } - Tick(); this.RequestAnimationFrame(OnFrame); } @@ -516,298 +129,57 @@ private void OnFrame(TimeSpan now) } } - // The endless loops run on the render thread, so they keep their pace whatever the UI thread is doing. - private void StartAmbientAnimations() - { - TrophyUi.WithVisual(_glow, glow => - { - const int steps = 8; - var pulse = glow.Compositor.CreateScalarKeyFrameAnimation(); - pulse.Target = "Opacity"; - pulse.Duration = TimeSpan.FromSeconds(2 * Math.PI / 2.4); - pulse.IterationBehavior = AnimationIterationBehavior.Forever; - for (var i = 0; i <= steps; i++) - { - var phase = (double)i / steps; - pulse.InsertKeyFrame((float)phase, (float)(0.75 + 0.25 * Math.Sin(phase * 2 * Math.PI))); - } - - glow.StartAnimation("Opacity", pulse); - }); - - if (_rays.Children.Count > 0) - { - TrophyUi.WithVisual(_rays, rays => - { - var spin = rays.Compositor.CreateScalarKeyFrameAnimation(); - spin.Target = "RotationAngle"; - spin.Duration = TimeSpan.FromSeconds(20); - spin.IterationBehavior = AnimationIterationBehavior.Forever; - spin.InsertKeyFrame(0f, 0f); - spin.InsertKeyFrame(1f, (float)(2 * Math.PI)); - rays.CenterPoint = new Vector3D(MedalColumn / 2, CardHeight / 2, 0); - rays.StartAnimation("RotationAngle", spin); - }); - } - } - private bool Tick() { - var t = _clock.Elapsed.TotalSeconds; - if (t >= _leaveAt + ExitSeconds) + _time = _clock.Elapsed.TotalSeconds; + if (_time >= _leaveAt + ExitSeconds) { Close(); return false; } - var leaving = t > _leaveAt; - var leave = leaving ? Math.Clamp((t - _leaveAt) / ExitSeconds, 0, 1) : 0; - if (t >= SpinStart && !_chimed) + if (_time >= ChimeAt && !_chimed) { _chimed = true; TrophySound.Play(_content.Grade); } - if (_reducedMotion) - { - Opacity = leaving ? 1 - leave : Math.Min(1, t / 0.25); - foreach (var (line, _, _) in _lines) - { - line.Opacity = 1; - } - - _medal.Spin = 0; - _medalScale.ScaleX = _medalScale.ScaleY = 1; - if (_content.Total > 0) - { - _progressScale.ScaleX = PercentOf(_content.Earned) / 100; - _progressText.Text = $"{_content.Earned} / {_content.Total}"; - } - - return true; - } - - Opacity = 1; - var pop = EaseOutCubic(Math.Clamp(t / PopSeconds, 0, 1)); - var textOut = EaseInOutCubic(Math.Clamp(leave / 0.33, 0, 1)); - var fold = EaseInOutCubic(Math.Clamp((leave - 0.2) / 0.55, 0, 1)); - var melt = EaseInOutCubic(Math.Clamp((leave - 0.65) / 0.35, 0, 1)); - var openW = leaving ? 1 - fold : Math.Max(0, Spring(t - ExpandAt, 11, 0.74)); - var openH = leaving ? 1 - fold : Math.Max(0, Spring(t - ExpandAt - 0.04, 10, 0.8)); - - // The pill-to-card morph is the one layout-driven step: it lasts about half a second at each end, and the - // subtree it re-arranges is fixed-size. - var width = PillSize + (CardWidth - PillSize) * openW; - var height = PillSize + (CardHeight - PillSize) * openH; - _cardHost.Width = width; - _cardHost.Height = height; - var radius = new CornerRadius(Math.Min(CardRadius, Math.Min(width, height) / 2)); - _cardBorder.CornerRadius = radius; - _edgeBorder.CornerRadius = radius; - _glow.CornerRadius = radius; - _cardHost.Opacity = Math.Min(1, t / 0.2) * (1 - melt); - _cardShift.Y = -10 * melt; - - var spin = Math.Clamp((t - SpinStart) / (Impact - SpinStart), 0, 1); - _medal.Spin = (1 - EaseOutQuart(spin)) * Math.PI * 6; - _medalShift.X = (PillSize / 2 - MedalColumn / 2) * (1 - openW); - _medalShift.Y = (PillSize / 2 - CardHeight / 2) * (1 - openH); - var grow = (PillSize * 0.86 / MedalSize) + (1 - PillSize * 0.86 / MedalSize) * openW; - var sinceImpact = t - Impact; - var thump = sinceImpact >= 0 ? Math.Exp(-sinceImpact * 9) * Math.Cos(sinceImpact * 28) * 0.14 : 0; - _medalScale.ScaleX = _medalScale.ScaleY = grow + thump; - _medal.Glint = sinceImpact is >= 0.05 and <= 0.75 ? (sinceImpact - 0.05) / 0.7 : -1; - - var landing = sinceImpact >= 0 && !leaving ? 1 + Math.Exp(-sinceImpact * 10) * Math.Sin(sinceImpact * 30) * 0.012 : 1; - _cardScale.ScaleX = _cardScale.ScaleY = (0.7 + 0.3 * pop) * (1 - 0.25 * melt) * landing; - _burst.Opacity = sinceImpact >= 0 - ? 0.4 + 0.6 * Math.Exp(-sinceImpact * 3.5) + 0.08 * Math.Sin(t * 3) - : 0.25 + 0.25 * spin; - if (sinceImpact >= 0 && !_burstDone) - { - _burstDone = true; - SpawnSparkles(t, _content.Grade switch { 1 => 26, 2 => 18, 3 => 14, _ => 10 }, _content.Grade == 1 ? 1.25 : 1.0); - } - - if (_content.Grade == 1 && sinceImpact >= 0.55 && !_secondBurstDone) - { - _secondBurstDone = true; - SpawnSparkles(t, 16, 0.8); - } - - var ring = sinceImpact / 0.7; - _ring.Opacity = ring is >= 0 and <= 1 ? 0.95 * (1 - ring) : 0; - if (ring is >= 0 and <= 1) - { - _ringScale.ScaleX = _ringScale.ScaleY = 1 + EaseOutCubic(ring) * (_content.Grade == 1 ? 1.9 : 1.2); - } - - _rays.Opacity = sinceImpact >= 0 ? Math.Min(1, sinceImpact * 3) * (1 - textOut) : 0; - - foreach (var (line, shift, delay) in _lines) - { - var progress = EaseOutCubic(Math.Clamp((t - delay) / 0.35, 0, 1)); - shift.Y = (1 - progress) * 10 - textOut * 4; - line.Opacity = progress * (1 - textOut); - } - - if (_content.Total > 0) - { - var fill = Math.Clamp((sinceImpact - 0.15) / 0.8, 0, 1); - var before = PercentOf(_content.Earned - 1); - _progressScale.ScaleX = (before + (PercentOf(_content.Earned) - before) * EaseOutCubic(fill)) / 100; - _progressText.Text = $"{(fill > 0.5 ? _content.Earned : Math.Max(0, _content.Earned - 1))} / {_content.Total}"; - } - - var sweep = (sinceImpact - 0.25) / 0.85; - _shine.Opacity = sweep is >= 0 and <= 1 ? 1 : 0; - _shineShift.X = -180 + EaseInOutCubic(Math.Clamp(sweep, 0, 1)) * (CardWidth + 320); - - _auroraA.X = Math.Sin(t * 0.7) * 60; - _auroraA.Y = Math.Cos(t * 0.5) * 25; - _auroraB.X = Math.Cos(t * 0.6) * 70; - _auroraB.Y = Math.Sin(t * 0.8) * 30; - if (_content.Grade == 1) - { - _edgeSpin.Angle = t * 40; - } - - RetireSparkles(t); + _surface.InvalidateVisual(); return true; } - private void SpawnSparkles(double now, int count, double reach) + private void Paint(SKCanvas canvas, Size size) { - Color[] colors = _content.Grade == 1 - ? [_light, Colors.White, Color.Parse("#C9B8FF"), Color.Parse("#FFC4EC")] - : [_light, Colors.White, _light, _mid]; - var looks = new Dictionary<Color, (IBrush Fill, IBrush Halo)>(); - var origin = MedalCenter; - for (var i = 0; i < count; i++) + var t = _time; + var enter = _reducedMotion ? Math.Min(1, t / 0.25) : EaseOutCubic(Math.Clamp(t / EnterSeconds, 0, 1)); + var leave = t > _leaveAt ? EaseInOutCubic(Math.Clamp((t - _leaveAt) / ExitSeconds, 0, 1)) : 0; + var opacity = (float)(enter * (1 - leave)); + if (opacity <= 0) { - var angle = (i + _random.NextDouble() * 0.8) / count * Math.PI * 2; - var speed = (90 + _random.NextDouble() * 170) * reach; - var dot = _random.NextDouble() < 0.3; - var size = dot ? 3 + _random.NextDouble() * 2 : 9 + _random.NextDouble() * (_content.Grade == 1 ? 12 : 8); - var color = colors[_random.Next(colors.Length)]; - if (!looks.TryGetValue(color, out var look)) - { - look = (new SolidColorBrush(color), new RadialGradientBrush - { - GradientStops = - { - new GradientStop(Color.FromArgb(150, color.R, color.G, color.B), 0), - new GradientStop(Color.FromArgb(0, color.R, color.G, color.B), 1), - }, - }); - looks[color] = look; - } - - // The soft halo is a gradient disc rather than a drop shadow, which would need an offscreen pass per frame. - var box = size * 2.6; - Control body = dot - ? new Border { Width = size, Height = size, CornerRadius = new CornerRadius(size / 2), Background = look.Fill } - : new Avalonia.Controls.Shapes.Path { Data = SparkleShape, Width = size, Height = size, Stretch = Stretch.Fill, Fill = look.Fill }; - body.HorizontalAlignment = HorizontalAlignment.Center; - body.VerticalAlignment = VerticalAlignment.Center; - var visual = new Grid - { - Width = box, - Height = box, - IsHitTestVisible = false, - Children = - { - new Border { CornerRadius = new CornerRadius(box / 2), Background = look.Halo }, - body, - }, - }; - Canvas.SetLeft(visual, origin.X - box / 2); - Canvas.SetTop(visual, origin.Y - box / 2); - _overlay.Children.Add(visual); - - var life = 0.55 + _random.NextDouble() * 0.5; - AnimateSparkle( - visual, - new Vector(Math.Cos(angle) * speed, Math.Sin(angle) * speed), - life, - _random.NextDouble() * 45, - (_random.NextDouble() - 0.5) * 240, - 14 + _random.NextDouble() * 12); - _sparkles.Add(new Sparkle(visual, now + life + 0.1)); - } - } - - private static void AnimateSparkle(Control visual, Vector velocity, double life, double rotation, double spin, double twinkle) - { - // Closed form of the original drag-and-lift integration: velocity decays by dragRate and an upward drift fights it. - const double dragRate = 5.5; - const double lift = 30; - var steps = (int)Math.Ceiling(life / SparkleSampleSeconds); - TrophyUi.WithVisual(visual, composition => - { - var compositor = composition.Compositor; - var move = compositor.CreateVector3DKeyFrameAnimation(); - var scale = compositor.CreateVector3DKeyFrameAnimation(); - var fade = compositor.CreateScalarKeyFrameAnimation(); - var turn = compositor.CreateScalarKeyFrameAnimation(); - move.Target = "Translation"; - scale.Target = "Scale"; - fade.Target = "Opacity"; - turn.Target = "RotationAngle"; - move.Duration = scale.Duration = fade.Duration = turn.Duration = TimeSpan.FromSeconds(life); - for (var i = 0; i <= steps; i++) - { - var fraction = (double)i / steps; - var age = fraction * life; - var decay = 1 - Math.Exp(-dragRate * age); - var x = velocity.X / dragRate * decay; - var y = (velocity.Y + lift / dragRate) / dragRate * decay - lift / dragRate * age; - var twinkling = 0.8 + 0.2 * Math.Sin(age * twinkle); - var size = Math.Min(1, fraction * 6) * twinkling * (1 - 0.5 * fraction); - move.InsertKeyFrame((float)fraction, new Vector3D(x, y, 0)); - scale.InsertKeyFrame((float)fraction, new Vector3D(size, size, 1)); - fade.InsertKeyFrame((float)fraction, (float)(1 - EaseInCubic(fraction))); - } - - turn.InsertKeyFrame(0f, (float)(rotation * Math.PI / 180)); - turn.InsertKeyFrame(1f, (float)((rotation + spin * life) * Math.PI / 180)); - composition.CenterPoint = new Vector3D(visual.Width / 2, visual.Height / 2, 0); - composition.StartAnimation("Translation", move); - composition.StartAnimation("Scale", scale); - composition.StartAnimation("Opacity", fade); - composition.StartAnimation("RotationAngle", turn); - }, () => visual.IsVisible = false); - } - - private void RetireSparkles(double now) - { - for (var i = _sparkles.Count - 1; i >= 0; i--) - { - if (now >= _sparkles[i].ExpiresAt) - { - _overlay.Children.Remove(_sparkles[i].Visual); - _sparkles.RemoveAt(i); - } + return; } - } - private static double Spring(double t, double omega, double zeta) - { - if (t <= 0) - { - return 0; - } + using var painter = new OverlayPainter(canvas, _palette, Unit); + var left = (float)size.Width - CardMargin - CardWidth; + var card = SKRect.Create(left, CardMargin, CardWidth, _card.Height(painter, CardWidth)); + var shiftX = _reducedMotion ? 0 : (float)((1 - enter) * 48); + var shiftY = _reducedMotion ? 0 : (float)(-12 * leave); - var damped = omega * Math.Sqrt(1 - zeta * zeta); - return 1 - Math.Exp(-zeta * omega * t) * (Math.Cos(damped * t) + zeta * omega / damped * Math.Sin(damped * t)); + using var layer = new SKPaint { Color = SKColors.White.WithAlpha((byte)(opacity * 255)) }; + canvas.SaveLayer(layer); + canvas.Translate(shiftX, shiftY); + var sinceImpact = t - Impact; + var charge = Math.Clamp((t - ChimeAt - 0.08) / (Impact - ChimeAt - 0.08), 0, 1); + var celebration = _reducedMotion + ? OverlayCelebration.Settled + : new OverlayCelebration(sinceImpact, charge, _accents, _content.Grade == 1); + var progress = _reducedMotion ? 1 : EaseOutCubic(Math.Clamp((sinceImpact - 0.15) / 0.8, 0, 1)); + _card.Draw(painter, card, celebration, progress); + canvas.Restore(); } private static double EaseOutCubic(double t) => 1 - Math.Pow(1 - t, 3); - private static double EaseOutQuart(double t) => 1 - Math.Pow(1 - t, 4); - - private static double EaseInCubic(double t) => t * t * t; - private static double EaseInOutCubic(double t) => t < 0.5 ? 4 * t * t * t : 1 - Math.Pow(-2 * t + 2, 3) / 2; private void Place() From 3cc24a9a8bc4fd1a82133531af31d08494f3cfae Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:27:07 +0300 Subject: [PATCH 29/64] [Ime] Open an on-screen keyboard for sceImeDialog with PS5 IME shortcuts, typed text and localized layouts --- docs/sharpemu-gui-undocumented-env-vars.md | 1 + src/SharpEmu.GUI/Languages/ar.json | 13 +- src/SharpEmu.GUI/Languages/az.json | 13 +- src/SharpEmu.GUI/Languages/br.json | 13 +- src/SharpEmu.GUI/Languages/de.json | 13 +- src/SharpEmu.GUI/Languages/dk.json | 13 +- src/SharpEmu.GUI/Languages/ee.json | 13 +- src/SharpEmu.GUI/Languages/en.json | 13 +- src/SharpEmu.GUI/Languages/es.json | 13 +- src/SharpEmu.GUI/Languages/fr.json | 13 +- src/SharpEmu.GUI/Languages/hu.json | 13 +- src/SharpEmu.GUI/Languages/it.json | 13 +- src/SharpEmu.GUI/Languages/ja.json | 13 +- src/SharpEmu.GUI/Languages/ko.json | 13 +- src/SharpEmu.GUI/Languages/nl.json | 13 +- src/SharpEmu.GUI/Languages/pl.json | 13 +- src/SharpEmu.GUI/Languages/pt.json | 13 +- src/SharpEmu.GUI/Languages/ru.json | 13 +- src/SharpEmu.GUI/Languages/tr.json | 13 +- src/SharpEmu.GUI/Languages/zh.json | 13 +- src/SharpEmu.Libs/Ime/ImeDialogExports.cs | 261 ++++++-- src/SharpEmu.Libs/Ime/ImeKeyboardLayer.cs | 295 +++++++++ src/SharpEmu.Libs/Ime/ImeKeyboardLayout.cs | 122 ++++ src/SharpEmu.Libs/Ime/ImeKeyboardSession.cs | 564 ++++++++++++++++++ src/SharpEmu.Libs/Overlay/OverlayPainter.cs | 75 ++- src/SharpEmu.Libs/Overlay/OverlayPrompts.cs | 6 + src/SharpEmu.Libs/Pad/PadExports.cs | 6 + src/SharpEmu.Libs/Pad/PadState.cs | 2 + src/SharpEmu.Libs/Pad/SystemDialogInput.cs | 36 +- .../SaveData/SaveDataDialogExports.cs | 8 +- src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs | 24 + 31 files changed, 1546 insertions(+), 101 deletions(-) create mode 100644 src/SharpEmu.Libs/Ime/ImeKeyboardLayer.cs create mode 100644 src/SharpEmu.Libs/Ime/ImeKeyboardLayout.cs create mode 100644 src/SharpEmu.Libs/Ime/ImeKeyboardSession.cs diff --git a/docs/sharpemu-gui-undocumented-env-vars.md b/docs/sharpemu-gui-undocumented-env-vars.md index 1a5c2d423..b5e894954 100644 --- a/docs/sharpemu-gui-undocumented-env-vars.md +++ b/docs/sharpemu-gui-undocumented-env-vars.md @@ -274,6 +274,7 @@ These variables apply to the controller and input libraries. | `SHARPEMU_BTHID_EVENT_CODE` | number (decimal or `0x` hex) | Sets the event code of the synthetic Bluetooth HID callback event. The default is 0. It has an effect only with `SHARPEMU_BTHID_FIRE_CALLBACK=1`. | `BluetoothHidExports.cs` | | `SHARPEMU_BTHID_EVENT_SIZE` | number (bytes, decimal or `0x` hex) | Sets the size of the zeroed event structure for the synthetic Bluetooth HID callback. The default is 256. It has an effect only with `SHARPEMU_BTHID_FIRE_CALLBACK=1`. | `BluetoothHidExports.cs` | | `SHARPEMU_BTHID_FIRE_CALLBACK` | `1` | Calls the registered Bluetooth HID guest callback one time with a zeroed event structure. The call occurs at the first `sceBluetoothHidRegisterDevice`. The default is off. | `BluetoothHidExports.cs` | +| `SHARPEMU_IME_AUTOFILL` | `1` | Skips the on-screen keyboard of `sceImeDialogInit` and fills the game's text buffer at once with its existing text, or with `SHARPEMU_DEFAULT_PROFILE` (default `Sharp`) when it is empty. The default opens the keyboard. | `ImeDialogExports.cs` | ## Memory and CPU diff --git a/src/SharpEmu.GUI/Languages/ar.json b/src/SharpEmu.GUI/Languages/ar.json index eeab885b4..a5662e59b 100644 --- a/src/SharpEmu.GUI/Languages/ar.json +++ b/src/SharpEmu.GUI/Languages/ar.json @@ -519,5 +519,16 @@ "Overlay.SaveData.Size": "الحجم", "Overlay.SaveData.ConfirmDelete": "هل تريد حذف هذه البيانات المحفوظة؟", "Overlay.SaveData.ConfirmDeleteNote": "لا يمكن استعادة البيانات المحفوظة المحذوفة.", - "Overlay.SaveData.InUse": "هذه البيانات المحفوظة قيد الاستخدام ولا يمكن حذفها." + "Overlay.SaveData.InUse": "هذه البيانات المحفوظة قيد الاستخدام ولا يمكن حذفها.", + "Overlay.Ime.Title": "أدخل النص", + "Overlay.Ime.Done": "تم", + "Overlay.Ime.Send": "إرسال", + "Overlay.Ime.Search": "بحث", + "Overlay.Ime.Go": "انتقال", + "Overlay.Ime.Close": "إغلاق", + "Overlay.Ime.Delete": "حذف", + "Overlay.Ime.Space": "مسافة", + "Overlay.Ime.Cursor": "المؤشر", + "Overlay.Ime.Select": "تحديد", + "Overlay.Ime.Type": "اكتب باستخدام لوحة المفاتيح" } diff --git a/src/SharpEmu.GUI/Languages/az.json b/src/SharpEmu.GUI/Languages/az.json index 346634b80..ca210382b 100644 --- a/src/SharpEmu.GUI/Languages/az.json +++ b/src/SharpEmu.GUI/Languages/az.json @@ -522,5 +522,16 @@ "Overlay.SaveData.Size": "Ölçü", "Overlay.SaveData.ConfirmDelete": "Bu yadda saxlanılmış məlumat silinsin?", "Overlay.SaveData.ConfirmDeleteNote": "Silinmiş yadda saxlanılmış məlumatlar bərpa edilə bilməz.", - "Overlay.SaveData.InUse": "Bu yadda saxlanılmış məlumat istifadədədir və silinə bilməz." + "Overlay.SaveData.InUse": "Bu yadda saxlanılmış məlumat istifadədədir və silinə bilməz.", + "Overlay.Ime.Title": "Mətn daxil edin", + "Overlay.Ime.Done": "Hazırdır", + "Overlay.Ime.Send": "Göndər", + "Overlay.Ime.Search": "Axtar", + "Overlay.Ime.Go": "Keç", + "Overlay.Ime.Close": "Bağla", + "Overlay.Ime.Delete": "Sil", + "Overlay.Ime.Space": "Boşluq", + "Overlay.Ime.Cursor": "Kursor", + "Overlay.Ime.Select": "Seç", + "Overlay.Ime.Type": "Klaviatura ilə yazın" } diff --git a/src/SharpEmu.GUI/Languages/br.json b/src/SharpEmu.GUI/Languages/br.json index e5605781d..cf10a5ed0 100644 --- a/src/SharpEmu.GUI/Languages/br.json +++ b/src/SharpEmu.GUI/Languages/br.json @@ -520,5 +520,16 @@ "Overlay.SaveData.Size": "Tamanho", "Overlay.SaveData.ConfirmDelete": "Excluir estes dados salvos?", "Overlay.SaveData.ConfirmDeleteNote": "Dados salvos excluídos não podem ser restaurados.", - "Overlay.SaveData.InUse": "Estes dados salvos estão em uso e não podem ser excluídos." + "Overlay.SaveData.InUse": "Estes dados salvos estão em uso e não podem ser excluídos.", + "Overlay.Ime.Title": "Digitar texto", + "Overlay.Ime.Done": "Concluído", + "Overlay.Ime.Send": "Enviar", + "Overlay.Ime.Search": "Pesquisar", + "Overlay.Ime.Go": "Ir", + "Overlay.Ime.Close": "Fechar", + "Overlay.Ime.Delete": "Excluir", + "Overlay.Ime.Space": "Espaço", + "Overlay.Ime.Cursor": "Cursor", + "Overlay.Ime.Select": "Selecionar", + "Overlay.Ime.Type": "Digite com o teclado" } diff --git a/src/SharpEmu.GUI/Languages/de.json b/src/SharpEmu.GUI/Languages/de.json index 8595c7f05..51f585d8d 100644 --- a/src/SharpEmu.GUI/Languages/de.json +++ b/src/SharpEmu.GUI/Languages/de.json @@ -519,5 +519,16 @@ "Overlay.SaveData.Size": "Größe", "Overlay.SaveData.ConfirmDelete": "Diese gespeicherten Daten löschen?", "Overlay.SaveData.ConfirmDeleteNote": "Gelöschte gespeicherte Daten können nicht wiederhergestellt werden.", - "Overlay.SaveData.InUse": "Diese gespeicherten Daten werden verwendet und können nicht gelöscht werden." + "Overlay.SaveData.InUse": "Diese gespeicherten Daten werden verwendet und können nicht gelöscht werden.", + "Overlay.Ime.Title": "Text eingeben", + "Overlay.Ime.Done": "Fertig", + "Overlay.Ime.Send": "Senden", + "Overlay.Ime.Search": "Suchen", + "Overlay.Ime.Go": "Los", + "Overlay.Ime.Close": "Schließen", + "Overlay.Ime.Delete": "Löschen", + "Overlay.Ime.Space": "Leertaste", + "Overlay.Ime.Cursor": "Cursor", + "Overlay.Ime.Select": "Auswählen", + "Overlay.Ime.Type": "Mit der Tastatur tippen" } diff --git a/src/SharpEmu.GUI/Languages/dk.json b/src/SharpEmu.GUI/Languages/dk.json index 4fcfc0b53..580812a64 100644 --- a/src/SharpEmu.GUI/Languages/dk.json +++ b/src/SharpEmu.GUI/Languages/dk.json @@ -519,5 +519,16 @@ "Overlay.SaveData.Size": "Størrelse", "Overlay.SaveData.ConfirmDelete": "Vil du slette disse gemte data?", "Overlay.SaveData.ConfirmDeleteNote": "Slettede gemte data kan ikke gendannes.", - "Overlay.SaveData.InUse": "Disse gemte data er i brug og kan ikke slettes." + "Overlay.SaveData.InUse": "Disse gemte data er i brug og kan ikke slettes.", + "Overlay.Ime.Title": "Indtast tekst", + "Overlay.Ime.Done": "Færdig", + "Overlay.Ime.Send": "Send", + "Overlay.Ime.Search": "Søg", + "Overlay.Ime.Go": "Gå", + "Overlay.Ime.Close": "Luk", + "Overlay.Ime.Delete": "Slet", + "Overlay.Ime.Space": "Mellemrum", + "Overlay.Ime.Cursor": "Markør", + "Overlay.Ime.Select": "Vælg", + "Overlay.Ime.Type": "Skriv med dit tastatur" } diff --git a/src/SharpEmu.GUI/Languages/ee.json b/src/SharpEmu.GUI/Languages/ee.json index 873d3aaaf..291b8c8dc 100644 --- a/src/SharpEmu.GUI/Languages/ee.json +++ b/src/SharpEmu.GUI/Languages/ee.json @@ -521,5 +521,16 @@ "Overlay.SaveData.Size": "Suurus", "Overlay.SaveData.ConfirmDelete": "Kas kustutada need salvestatud andmed?", "Overlay.SaveData.ConfirmDeleteNote": "Kustutatud salvestatud andmeid ei saa taastada.", - "Overlay.SaveData.InUse": "Need salvestatud andmed on kasutusel ja neid ei saa kustutada." + "Overlay.SaveData.InUse": "Need salvestatud andmed on kasutusel ja neid ei saa kustutada.", + "Overlay.Ime.Title": "Sisesta tekst", + "Overlay.Ime.Done": "Valmis", + "Overlay.Ime.Send": "Saada", + "Overlay.Ime.Search": "Otsi", + "Overlay.Ime.Go": "Mine", + "Overlay.Ime.Close": "Sulge", + "Overlay.Ime.Delete": "Kustuta", + "Overlay.Ime.Space": "Tühik", + "Overlay.Ime.Cursor": "Kursor", + "Overlay.Ime.Select": "Vali", + "Overlay.Ime.Type": "Kirjuta klaviatuuriga" } diff --git a/src/SharpEmu.GUI/Languages/en.json b/src/SharpEmu.GUI/Languages/en.json index 7c9467121..b5d5f55a9 100644 --- a/src/SharpEmu.GUI/Languages/en.json +++ b/src/SharpEmu.GUI/Languages/en.json @@ -523,5 +523,16 @@ "Overlay.SaveData.Size": "Size", "Overlay.SaveData.ConfirmDelete": "Delete this saved data?", "Overlay.SaveData.ConfirmDeleteNote": "Deleted saved data can't be restored.", - "Overlay.SaveData.InUse": "This saved data is in use and can't be deleted." + "Overlay.SaveData.InUse": "This saved data is in use and can't be deleted.", + "Overlay.Ime.Title": "Enter text", + "Overlay.Ime.Done": "Done", + "Overlay.Ime.Send": "Send", + "Overlay.Ime.Search": "Search", + "Overlay.Ime.Go": "Go", + "Overlay.Ime.Close": "Close", + "Overlay.Ime.Delete": "Delete", + "Overlay.Ime.Space": "Space", + "Overlay.Ime.Cursor": "Cursor", + "Overlay.Ime.Select": "Select", + "Overlay.Ime.Type": "Type with your keyboard" } diff --git a/src/SharpEmu.GUI/Languages/es.json b/src/SharpEmu.GUI/Languages/es.json index 4fa953aec..6987d484b 100644 --- a/src/SharpEmu.GUI/Languages/es.json +++ b/src/SharpEmu.GUI/Languages/es.json @@ -520,5 +520,16 @@ "Overlay.SaveData.Size": "Tamaño", "Overlay.SaveData.ConfirmDelete": "¿Eliminar estos datos guardados?", "Overlay.SaveData.ConfirmDeleteNote": "Los datos guardados eliminados no se pueden recuperar.", - "Overlay.SaveData.InUse": "Estos datos guardados están en uso y no se pueden eliminar." + "Overlay.SaveData.InUse": "Estos datos guardados están en uso y no se pueden eliminar.", + "Overlay.Ime.Title": "Introducir texto", + "Overlay.Ime.Done": "Hecho", + "Overlay.Ime.Send": "Enviar", + "Overlay.Ime.Search": "Buscar", + "Overlay.Ime.Go": "Ir", + "Overlay.Ime.Close": "Cerrar", + "Overlay.Ime.Delete": "Eliminar", + "Overlay.Ime.Space": "Espacio", + "Overlay.Ime.Cursor": "Cursor", + "Overlay.Ime.Select": "Seleccionar", + "Overlay.Ime.Type": "Escribe con el teclado" } diff --git a/src/SharpEmu.GUI/Languages/fr.json b/src/SharpEmu.GUI/Languages/fr.json index 77866b37b..f2aad69d4 100644 --- a/src/SharpEmu.GUI/Languages/fr.json +++ b/src/SharpEmu.GUI/Languages/fr.json @@ -520,5 +520,16 @@ "Overlay.SaveData.Size": "Taille", "Overlay.SaveData.ConfirmDelete": "Supprimer ces données sauvegardées ?", "Overlay.SaveData.ConfirmDeleteNote": "Les données sauvegardées supprimées ne peuvent pas être restaurées.", - "Overlay.SaveData.InUse": "Ces données sauvegardées sont en cours d’utilisation et ne peuvent pas être supprimées." + "Overlay.SaveData.InUse": "Ces données sauvegardées sont en cours d’utilisation et ne peuvent pas être supprimées.", + "Overlay.Ime.Title": "Saisir du texte", + "Overlay.Ime.Done": "Terminé", + "Overlay.Ime.Send": "Envoyer", + "Overlay.Ime.Search": "Rechercher", + "Overlay.Ime.Go": "OK", + "Overlay.Ime.Close": "Fermer", + "Overlay.Ime.Delete": "Supprimer", + "Overlay.Ime.Space": "Espace", + "Overlay.Ime.Cursor": "Curseur", + "Overlay.Ime.Select": "Sélectionner", + "Overlay.Ime.Type": "Tapez avec votre clavier" } diff --git a/src/SharpEmu.GUI/Languages/hu.json b/src/SharpEmu.GUI/Languages/hu.json index 408a8764e..9559f9bd6 100644 --- a/src/SharpEmu.GUI/Languages/hu.json +++ b/src/SharpEmu.GUI/Languages/hu.json @@ -520,5 +520,16 @@ "Overlay.SaveData.Size": "Méret", "Overlay.SaveData.ConfirmDelete": "Törlöd ezt a mentett adatot?", "Overlay.SaveData.ConfirmDeleteNote": "A törölt mentett adatok nem állíthatók vissza.", - "Overlay.SaveData.InUse": "Ez a mentett adat használatban van, ezért nem törölhető." + "Overlay.SaveData.InUse": "Ez a mentett adat használatban van, ezért nem törölhető.", + "Overlay.Ime.Title": "Szöveg beírása", + "Overlay.Ime.Done": "Kész", + "Overlay.Ime.Send": "Küldés", + "Overlay.Ime.Search": "Keresés", + "Overlay.Ime.Go": "Ugrás", + "Overlay.Ime.Close": "Bezárás", + "Overlay.Ime.Delete": "Törlés", + "Overlay.Ime.Space": "Szóköz", + "Overlay.Ime.Cursor": "Kurzor", + "Overlay.Ime.Select": "Kiválasztás", + "Overlay.Ime.Type": "Gépelj a billentyűzeteddel" } diff --git a/src/SharpEmu.GUI/Languages/it.json b/src/SharpEmu.GUI/Languages/it.json index b0b94b4ed..d7c140ae9 100644 --- a/src/SharpEmu.GUI/Languages/it.json +++ b/src/SharpEmu.GUI/Languages/it.json @@ -524,5 +524,16 @@ "Overlay.SaveData.Size": "Dimensione", "Overlay.SaveData.ConfirmDelete": "Eliminare questi dati salvati?", "Overlay.SaveData.ConfirmDeleteNote": "I dati salvati eliminati non possono essere ripristinati.", - "Overlay.SaveData.InUse": "Questi dati salvati sono in uso e non possono essere eliminati." + "Overlay.SaveData.InUse": "Questi dati salvati sono in uso e non possono essere eliminati.", + "Overlay.Ime.Title": "Inserisci testo", + "Overlay.Ime.Done": "Fine", + "Overlay.Ime.Send": "Invia", + "Overlay.Ime.Search": "Cerca", + "Overlay.Ime.Go": "Vai", + "Overlay.Ime.Close": "Chiudi", + "Overlay.Ime.Delete": "Elimina", + "Overlay.Ime.Space": "Spazio", + "Overlay.Ime.Cursor": "Cursore", + "Overlay.Ime.Select": "Seleziona", + "Overlay.Ime.Type": "Scrivi con la tastiera" } diff --git a/src/SharpEmu.GUI/Languages/ja.json b/src/SharpEmu.GUI/Languages/ja.json index 508a69c61..1a9b7fa09 100644 --- a/src/SharpEmu.GUI/Languages/ja.json +++ b/src/SharpEmu.GUI/Languages/ja.json @@ -519,5 +519,16 @@ "Overlay.SaveData.Size": "サイズ", "Overlay.SaveData.ConfirmDelete": "このセーブデータを削除しますか?", "Overlay.SaveData.ConfirmDeleteNote": "削除したセーブデータは元に戻せません。", - "Overlay.SaveData.InUse": "このセーブデータは使用中のため削除できません。" + "Overlay.SaveData.InUse": "このセーブデータは使用中のため削除できません。", + "Overlay.Ime.Title": "テキストを入力", + "Overlay.Ime.Done": "決定", + "Overlay.Ime.Send": "送信", + "Overlay.Ime.Search": "検索", + "Overlay.Ime.Go": "移動", + "Overlay.Ime.Close": "閉じる", + "Overlay.Ime.Delete": "削除", + "Overlay.Ime.Space": "スペース", + "Overlay.Ime.Cursor": "カーソル", + "Overlay.Ime.Select": "選択", + "Overlay.Ime.Type": "キーボードで入力" } diff --git a/src/SharpEmu.GUI/Languages/ko.json b/src/SharpEmu.GUI/Languages/ko.json index 92b9ed1da..2dae23bd4 100644 --- a/src/SharpEmu.GUI/Languages/ko.json +++ b/src/SharpEmu.GUI/Languages/ko.json @@ -519,5 +519,16 @@ "Overlay.SaveData.Size": "크기", "Overlay.SaveData.ConfirmDelete": "이 저장 데이터를 삭제하시겠습니까?", "Overlay.SaveData.ConfirmDeleteNote": "삭제한 저장 데이터는 복원할 수 없습니다.", - "Overlay.SaveData.InUse": "이 저장 데이터는 사용 중이어서 삭제할 수 없습니다." + "Overlay.SaveData.InUse": "이 저장 데이터는 사용 중이어서 삭제할 수 없습니다.", + "Overlay.Ime.Title": "텍스트 입력", + "Overlay.Ime.Done": "완료", + "Overlay.Ime.Send": "보내기", + "Overlay.Ime.Search": "검색", + "Overlay.Ime.Go": "이동", + "Overlay.Ime.Close": "닫기", + "Overlay.Ime.Delete": "삭제", + "Overlay.Ime.Space": "스페이스", + "Overlay.Ime.Cursor": "커서", + "Overlay.Ime.Select": "선택", + "Overlay.Ime.Type": "키보드로 입력하세요" } diff --git a/src/SharpEmu.GUI/Languages/nl.json b/src/SharpEmu.GUI/Languages/nl.json index a64873d25..eba7df69c 100644 --- a/src/SharpEmu.GUI/Languages/nl.json +++ b/src/SharpEmu.GUI/Languages/nl.json @@ -519,5 +519,16 @@ "Overlay.SaveData.Size": "Grootte", "Overlay.SaveData.ConfirmDelete": "Deze opgeslagen gegevens verwijderen?", "Overlay.SaveData.ConfirmDeleteNote": "Verwijderde opgeslagen gegevens kunnen niet worden hersteld.", - "Overlay.SaveData.InUse": "Deze opgeslagen gegevens zijn in gebruik en kunnen niet worden verwijderd." + "Overlay.SaveData.InUse": "Deze opgeslagen gegevens zijn in gebruik en kunnen niet worden verwijderd.", + "Overlay.Ime.Title": "Tekst invoeren", + "Overlay.Ime.Done": "Gereed", + "Overlay.Ime.Send": "Verzenden", + "Overlay.Ime.Search": "Zoeken", + "Overlay.Ime.Go": "Ga", + "Overlay.Ime.Close": "Sluiten", + "Overlay.Ime.Delete": "Verwijderen", + "Overlay.Ime.Space": "Spatie", + "Overlay.Ime.Cursor": "Cursor", + "Overlay.Ime.Select": "Selecteren", + "Overlay.Ime.Type": "Typ met je toetsenbord" } diff --git a/src/SharpEmu.GUI/Languages/pl.json b/src/SharpEmu.GUI/Languages/pl.json index ca62b1e5c..d3a6c3215 100644 --- a/src/SharpEmu.GUI/Languages/pl.json +++ b/src/SharpEmu.GUI/Languages/pl.json @@ -521,5 +521,16 @@ "Overlay.SaveData.Size": "Rozmiar", "Overlay.SaveData.ConfirmDelete": "Usunąć te zapisane dane?", "Overlay.SaveData.ConfirmDeleteNote": "Usuniętych zapisanych danych nie można przywrócić.", - "Overlay.SaveData.InUse": "Te zapisane dane są w użyciu i nie można ich usunąć." + "Overlay.SaveData.InUse": "Te zapisane dane są w użyciu i nie można ich usunąć.", + "Overlay.Ime.Title": "Wprowadź tekst", + "Overlay.Ime.Done": "Gotowe", + "Overlay.Ime.Send": "Wyślij", + "Overlay.Ime.Search": "Szukaj", + "Overlay.Ime.Go": "Przejdź", + "Overlay.Ime.Close": "Zamknij", + "Overlay.Ime.Delete": "Usuń", + "Overlay.Ime.Space": "Spacja", + "Overlay.Ime.Cursor": "Kursor", + "Overlay.Ime.Select": "Wybierz", + "Overlay.Ime.Type": "Pisz na klawiaturze" } diff --git a/src/SharpEmu.GUI/Languages/pt.json b/src/SharpEmu.GUI/Languages/pt.json index d36c5e0c7..42703d097 100644 --- a/src/SharpEmu.GUI/Languages/pt.json +++ b/src/SharpEmu.GUI/Languages/pt.json @@ -520,5 +520,16 @@ "Overlay.SaveData.Size": "Tamanho", "Overlay.SaveData.ConfirmDelete": "Eliminar estes dados guardados?", "Overlay.SaveData.ConfirmDeleteNote": "Os dados guardados eliminados não podem ser recuperados.", - "Overlay.SaveData.InUse": "Estes dados guardados estão a ser utilizados e não podem ser eliminados." + "Overlay.SaveData.InUse": "Estes dados guardados estão a ser utilizados e não podem ser eliminados.", + "Overlay.Ime.Title": "Introduzir texto", + "Overlay.Ime.Done": "Concluído", + "Overlay.Ime.Send": "Enviar", + "Overlay.Ime.Search": "Pesquisar", + "Overlay.Ime.Go": "Ir", + "Overlay.Ime.Close": "Fechar", + "Overlay.Ime.Delete": "Eliminar", + "Overlay.Ime.Space": "Espaço", + "Overlay.Ime.Cursor": "Cursor", + "Overlay.Ime.Select": "Selecionar", + "Overlay.Ime.Type": "Escreva com o teclado" } diff --git a/src/SharpEmu.GUI/Languages/ru.json b/src/SharpEmu.GUI/Languages/ru.json index 7acd3f43c..6f573a8e9 100644 --- a/src/SharpEmu.GUI/Languages/ru.json +++ b/src/SharpEmu.GUI/Languages/ru.json @@ -522,5 +522,16 @@ "Overlay.SaveData.Size": "Размер", "Overlay.SaveData.ConfirmDelete": "Удалить эти сохраненные данные?", "Overlay.SaveData.ConfirmDeleteNote": "Удаленные сохраненные данные нельзя восстановить.", - "Overlay.SaveData.InUse": "Эти сохраненные данные используются, их нельзя удалить." + "Overlay.SaveData.InUse": "Эти сохраненные данные используются, их нельзя удалить.", + "Overlay.Ime.Title": "Введите текст", + "Overlay.Ime.Done": "Готово", + "Overlay.Ime.Send": "Отправить", + "Overlay.Ime.Search": "Поиск", + "Overlay.Ime.Go": "Перейти", + "Overlay.Ime.Close": "Закрыть", + "Overlay.Ime.Delete": "Удалить", + "Overlay.Ime.Space": "Пробел", + "Overlay.Ime.Cursor": "Курсор", + "Overlay.Ime.Select": "Выбрать", + "Overlay.Ime.Type": "Печатайте на клавиатуре" } diff --git a/src/SharpEmu.GUI/Languages/tr.json b/src/SharpEmu.GUI/Languages/tr.json index 2b3cacfce..649fc0f82 100644 --- a/src/SharpEmu.GUI/Languages/tr.json +++ b/src/SharpEmu.GUI/Languages/tr.json @@ -521,5 +521,16 @@ "Overlay.SaveData.Size": "Boyut", "Overlay.SaveData.ConfirmDelete": "Bu kayıtlı veri silinsin mi?", "Overlay.SaveData.ConfirmDeleteNote": "Silinen kayıtlı veriler geri getirilemez.", - "Overlay.SaveData.InUse": "Bu kayıtlı veri kullanımda olduğu için silinemiyor." + "Overlay.SaveData.InUse": "Bu kayıtlı veri kullanımda olduğu için silinemiyor.", + "Overlay.Ime.Title": "Metin girin", + "Overlay.Ime.Done": "Bitti", + "Overlay.Ime.Send": "Gönder", + "Overlay.Ime.Search": "Ara", + "Overlay.Ime.Go": "Git", + "Overlay.Ime.Close": "Kapat", + "Overlay.Ime.Delete": "Sil", + "Overlay.Ime.Space": "Boşluk", + "Overlay.Ime.Cursor": "İmleç", + "Overlay.Ime.Select": "Seç", + "Overlay.Ime.Type": "Klavyenizle yazın" } diff --git a/src/SharpEmu.GUI/Languages/zh.json b/src/SharpEmu.GUI/Languages/zh.json index ca74f4614..eee5dd926 100644 --- a/src/SharpEmu.GUI/Languages/zh.json +++ b/src/SharpEmu.GUI/Languages/zh.json @@ -521,5 +521,16 @@ "Overlay.SaveData.Size": "大小", "Overlay.SaveData.ConfirmDelete": "要删除此保存数据吗?", "Overlay.SaveData.ConfirmDeleteNote": "删除的保存数据无法恢复。", - "Overlay.SaveData.InUse": "此保存数据正在使用中,无法删除。" + "Overlay.SaveData.InUse": "此保存数据正在使用中,无法删除。", + "Overlay.Ime.Title": "输入文本", + "Overlay.Ime.Done": "完成", + "Overlay.Ime.Send": "发送", + "Overlay.Ime.Search": "搜索", + "Overlay.Ime.Go": "前往", + "Overlay.Ime.Close": "关闭", + "Overlay.Ime.Delete": "删除", + "Overlay.Ime.Space": "空格", + "Overlay.Ime.Cursor": "光标", + "Overlay.Ime.Select": "选择", + "Overlay.Ime.Type": "使用键盘输入" } diff --git a/src/SharpEmu.Libs/Ime/ImeDialogExports.cs b/src/SharpEmu.Libs/Ime/ImeDialogExports.cs index a29159158..4e1855308 100644 --- a/src/SharpEmu.Libs/Ime/ImeDialogExports.cs +++ b/src/SharpEmu.Libs/Ime/ImeDialogExports.cs @@ -1,29 +1,55 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later -using System; using System.Buffers.Binary; using System.Text; using SharpEmu.HLE; +using SharpEmu.Libs.Overlay; +using SharpEmu.Libs.Pad; namespace SharpEmu.Libs.Ime; public static class ImeDialogExports { private const int StatusNone = 0; + private const int StatusRunning = 1; private const int StatusFinished = 2; private const int EndStatusOk = 0; + private const int EndStatusUserCanceled = 1; + private const int EndStatusAborted = 2; + private const ulong ParamTypeOffset = 0x04; + private const ulong ParamEnterLabelOffset = 0x10; + private const ulong ParamOptionOffset = 0x20; private const ulong ParamMaxTextLengthOffset = 0x24; private const ulong ParamInputTextBufferOffset = 0x28; + private const ulong ParamPlaceholderOffset = 0x40; + private const ulong ParamTitleOffset = 0x48; - private const int ImeDialogErrorInvalidAddress = unchecked((int)0x80BC0001); + private const uint OptionNoAutoCapitalization = 0x2; + private const uint OptionPassword = 0x4; + private const int MaxTextLength = 2048; + private const int MaxLabelLength = 256; + + private const int ImeErrorBusy = unchecked((int)0x80BC0001); + private const int ImeErrorInvalidMaxTextLength = unchecked((int)0x80BC0016); + private const int ImeErrorInvalidInputTextBuffer = unchecked((int)0x80BC0017); + private const int ImeErrorInvalidAddress = unchecked((int)0x80BC0031); + private const int ImeErrorDialogNotRunning = unchecked((int)0x80BC0105); + private const int ImeErrorDialogNotFinished = unchecked((int)0x80BC0106); + private const int ImeErrorDialogNotInUse = unchecked((int)0x80BC0107); private const string DefaultInputText = "Sharp"; + private const string AutofillVariable = "SHARPEMU_IME_AUTOFILL"; private static readonly object _gate = new(); private static int _status = StatusNone; + private static int _endStatus = EndStatusOk; + private static long _nextSession; + private static ImeKeyboardSession? _session; + private static ulong _bufferAddress; + private static int _maxTextLength; [SysAbiExport( Nid = "NUeBrN7hzf0", @@ -35,17 +61,77 @@ public static int ImeDialogInit(CpuContext ctx) var parameterAddress = ctx[CpuRegister.Rdi]; if (parameterAddress == 0) { - return SetReturn(ctx, ImeDialogErrorInvalidAddress); + return SetReturn(ctx, ImeErrorInvalidAddress); } - TryWriteInputText(ctx, parameterAddress); - lock (_gate) { - _status = StatusFinished; - } + if (_status != StatusNone) + { + return SetReturn(ctx, ImeErrorBusy); + } - return SetReturn(ctx, 0); + if (!ctx.TryReadUInt32(parameterAddress + ParamMaxTextLengthOffset, out var maxTextLength)) + { + return SetReturn(ctx, ImeErrorInvalidAddress); + } + + if (maxTextLength is 0 or > MaxTextLength) + { + return SetReturn(ctx, ImeErrorInvalidMaxTextLength); + } + + if (!ctx.TryReadUInt64(parameterAddress + ParamInputTextBufferOffset, out var bufferAddress) || + bufferAddress == 0) + { + return SetReturn(ctx, ImeErrorInvalidInputTextBuffer); + } + + var kind = ctx.TryReadUInt32(parameterAddress + ParamTypeOffset, out var type) && type <= 4 + ? (ImeTextKind)type + : ImeTextKind.Default; + var enterLabel = ctx.TryReadUInt32(parameterAddress + ParamEnterLabelOffset, out var label) && label <= 3 + ? (ImeEnterLabel)label + : ImeEnterLabel.Default; + var option = ctx.TryReadUInt32(parameterAddress + ParamOptionOffset, out var options) ? options : 0; + var title = ReadGuestString(ctx, parameterAddress + ParamTitleOffset, MaxLabelLength); + var placeholder = ReadGuestString(ctx, parameterAddress + ParamPlaceholderOffset, MaxLabelLength); + var initial = ReadUtf16(ctx, bufferAddress, (int)maxTextLength); + if (string.IsNullOrEmpty(initial) && kind != ImeTextKind.Number) + { + initial = FallbackText(); + } + + _bufferAddress = bufferAddress; + _maxTextLength = (int)maxTextLength; + _endStatus = EndStatusOk; + if (string.Equals(Environment.GetEnvironmentVariable(AutofillVariable), "1", StringComparison.Ordinal)) + { + WriteText(ctx, initial); + _status = StatusFinished; + Console.Error.WriteLine($"[LOADER][INFO] ime_dialog.autofill text=\"{initial}\""); + return SetReturn(ctx, 0); + } + + _session = new ImeKeyboardSession( + Interlocked.Increment(ref _nextSession), + title, + placeholder, + initial, + (int)maxTextLength, + kind, + (option & OptionPassword) != 0, + (option & OptionNoAutoCapitalization) == 0, + enterLabel, + Environment.GetEnvironmentVariable(OverlayText.LanguageVariable)); + _session.Begin(); + SystemDialogInput.Capture(wantsText: true); + ImeKeyboardLayer.Instance.Show(_session.View()); + _status = StatusRunning; + Console.Error.WriteLine( + $"[LOADER][INFO] ime_dialog.open type={kind} max={maxTextLength} option=0x{option:X} title=\"{title}\""); + return SetReturn(ctx, 0); + } } [SysAbiExport( @@ -55,14 +141,27 @@ public static int ImeDialogInit(CpuContext ctx) LibraryName = "libSceImeDialog")] public static int ImeDialogGetStatus(CpuContext ctx) { - int status; lock (_gate) { - status = _status; - } + if (_status == StatusRunning && _session is { } session) + { + switch (session.Poll()) + { + case ImeKeyboardInput.Changed: + ImeKeyboardLayer.Instance.Show(session.View()); + break; + case ImeKeyboardInput.Done: + Finish(EndStatusOk, ctx); + break; + case ImeKeyboardInput.Cancel: + Finish(EndStatusUserCanceled, ctx); + break; + } + } - ctx[CpuRegister.Rax] = unchecked((ulong)(long)status); - return status; + ctx[CpuRegister.Rax] = unchecked((ulong)(long)_status); + return _status; + } } [SysAbiExport( @@ -75,15 +174,27 @@ public static int ImeDialogGetResult(CpuContext ctx) var resultAddress = ctx[CpuRegister.Rdi]; if (resultAddress == 0) { - return SetReturn(ctx, ImeDialogErrorInvalidAddress); + return SetReturn(ctx, ImeErrorInvalidAddress); } - Span<byte> result = stackalloc byte[8]; - result.Clear(); - BinaryPrimitives.WriteInt32LittleEndian(result, EndStatusOk); - ctx.Memory.TryWrite(resultAddress, result); + lock (_gate) + { + if (_status == StatusNone) + { + return SetReturn(ctx, ImeErrorDialogNotInUse); + } + + if (_status == StatusRunning) + { + return SetReturn(ctx, ImeErrorDialogNotFinished); + } - return SetReturn(ctx, 0); + Span<byte> result = stackalloc byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(result, _endStatus); + return ctx.Memory.TryWrite(resultAddress, result) + ? SetReturn(ctx, 0) + : SetReturn(ctx, ImeErrorInvalidAddress); + } } [SysAbiExport( @@ -95,10 +206,19 @@ public static int ImeDialogAbort(CpuContext ctx) { lock (_gate) { - _status = StatusFinished; - } + if (_status == StatusNone) + { + return SetReturn(ctx, ImeErrorDialogNotInUse); + } - return SetReturn(ctx, 0); + if (_status != StatusRunning) + { + return SetReturn(ctx, ImeErrorDialogNotRunning); + } + + Finish(EndStatusAborted, ctx); + return SetReturn(ctx, 0); + } } [SysAbiExport( @@ -110,60 +230,85 @@ public static int ImeDialogTerm(CpuContext ctx) { lock (_gate) { + if (_status == StatusNone) + { + return SetReturn(ctx, ImeErrorDialogNotInUse); + } + + if (_session is not null) + { + Close(); + } + _status = StatusNone; + return SetReturn(ctx, 0); } - - return SetReturn(ctx, 0); } - private static void TryWriteInputText(CpuContext ctx, ulong parameterAddress) + private static void Finish(int endStatus, CpuContext ctx) { - Span<byte> field = stackalloc byte[8]; - if (!ctx.Memory.TryRead(parameterAddress + ParamInputTextBufferOffset, field)) + _endStatus = endStatus; + if (endStatus == EndStatusOk && _session is { } session) { - return; + WriteText(ctx, session.Text); } - var bufferAddress = BinaryPrimitives.ReadUInt64LittleEndian(field); - if (bufferAddress == 0) - { - return; - } + Console.Error.WriteLine($"[LOADER][INFO] ime_dialog.finish end={endStatus}"); + Close(); + _status = StatusFinished; + } - var maxTextLength = 16u; - Span<byte> lengthField = stackalloc byte[4]; - if (ctx.Memory.TryRead(parameterAddress + ParamMaxTextLengthOffset, lengthField)) + private static void Close() + { + _session = null; + ImeKeyboardLayer.Instance.Hide(); + SystemDialogInput.Release(); + } + + private static void WriteText(CpuContext ctx, string text) + { + if (text.Length > _maxTextLength) { - var declared = BinaryPrimitives.ReadUInt32LittleEndian(lengthField); - if (declared is > 0 and <= 256) - { - maxTextLength = declared; - } + text = text[.._maxTextLength]; } + var payload = new byte[(text.Length + 1) * 2]; + Encoding.Unicode.GetBytes(text, payload); + ctx.Memory.TryWrite(_bufferAddress, payload); + } + + private static string FallbackText() + { var text = Environment.GetEnvironmentVariable("SHARPEMU_DEFAULT_PROFILE"); - if (string.IsNullOrEmpty(text)) - { - text = DefaultInputText; - } + return string.IsNullOrWhiteSpace(text) ? DefaultInputText : text.Trim(); + } + + private static string ReadGuestString(CpuContext ctx, ulong pointerAddress, int maxLength) => + ctx.TryReadUInt64(pointerAddress, out var address) && address != 0 + ? ReadUtf16(ctx, address, maxLength) + : string.Empty; - if ((uint)text.Length > maxTextLength) + private static string ReadUtf16(CpuContext ctx, ulong address, int maxLength) + { + var builder = new StringBuilder(); + Span<byte> unit = stackalloc byte[2]; + for (var index = 0; index < maxLength; index++) { - text = text[..(int)maxTextLength]; - } + if (!ctx.Memory.TryRead(address + (ulong)(index * 2), unit)) + { + break; + } - var encoded = Encoding.Unicode.GetBytes(text); - Span<byte> payload = stackalloc byte[encoded.Length + 2]; - encoded.CopyTo(payload); - payload[^2] = 0; - payload[^1] = 0; + var value = BinaryPrimitives.ReadUInt16LittleEndian(unit); + if (value == 0) + { + break; + } - if (ctx.Memory.TryWrite(bufferAddress, payload)) - { - Console.Error.WriteLine( - $"[LOADER][WARN] ime.dialog_autofill buf=0x{bufferAddress:X16} " + - $"max={maxTextLength} text=\"{text}\""); + builder.Append((char)value); } + + return builder.ToString(); } private static int SetReturn(CpuContext ctx, int result) diff --git a/src/SharpEmu.Libs/Ime/ImeKeyboardLayer.cs b/src/SharpEmu.Libs/Ime/ImeKeyboardLayer.cs new file mode 100644 index 000000000..48a946233 --- /dev/null +++ b/src/SharpEmu.Libs/Ime/ImeKeyboardLayer.cs @@ -0,0 +1,295 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Overlay; +using SkiaSharp; + +namespace SharpEmu.Libs.Ime; + +internal sealed class ImeKeyboardLayer : OverlayLayer +{ + internal static readonly ImeKeyboardLayer Instance = OverlayLayers.Register(new ImeKeyboardLayer()); + + private const float Pad = 26; + private const float HeaderHeight = 44; + private const float FieldHeight = 62; + private const float KeyHeight = 58; + private const float KeyGap = 8; + private const float FooterHeight = 54; + private const float HintScale = 0.8f; + + private static readonly OverlayFont FieldFont = new(24, OverlayWeight.Regular); + private static readonly OverlayFont KeyFont = new(22, OverlayWeight.Regular); + private static readonly OverlayFont KeyLabelFont = new(16, OverlayWeight.Bold); + + private static readonly Dictionary<string, string> English = new(StringComparer.Ordinal) + { + ["Title"] = "Enter text", + ["Done"] = "Done", + ["Send"] = "Send", + ["Search"] = "Search", + ["Go"] = "Go", + ["Close"] = "Close", + ["Delete"] = "Delete", + ["Space"] = "Space", + ["Cursor"] = "Cursor", + ["Select"] = "Select", + ["Type"] = "Type with your keyboard", + }; + + private ImeKeyboardView? _view; + + private ImeKeyboardLayer() + { + } + + public override bool IsVisible => Volatile.Read(ref _view) is not null; + + internal static string Text(string key) => + OverlayText.Get(OverlayText.KeyPrefix + "Ime." + key, English.TryGetValue(key, out var value) ? value : key); + + internal void Show(ImeKeyboardView view) + { + Volatile.Write(ref _view, view); + Invalidate(); + } + + internal void Hide() + { + Volatile.Write(ref _view, null); + Invalidate(); + } + + public override SKRectI Bounds(int surfaceWidth, int surfaceHeight) + { + if (surfaceWidth < 240 || surfaceHeight < 200) + { + return SKRectI.Empty; + } + + var unit = OverlayStyle.UnitFor(surfaceHeight); + var scale = surfaceHeight / OverlayStyle.ReferenceHeight; + var width = Math.Min(surfaceWidth - 32, Math.Max((int)(1000 * scale), (int)(surfaceWidth * 0.6f))); + var height = Math.Min(surfaceHeight - 32, (int)Math.Ceiling(PanelHeight * unit)); + var bottomMargin = Math.Max(16, (int)(surfaceHeight * 0.05f)); + return SKRectI.Create((surfaceWidth - width) / 2, Math.Max(16, surfaceHeight - height - bottomMargin), width, height); + } + + private static float PanelHeight => + Pad + HeaderHeight + FieldHeight + 18 + 5 * KeyHeight + 4 * KeyGap + 18 + FooterHeight; + + public override int Render(SKCanvas canvas, int width, int height, float unit) + { + var view = Volatile.Read(ref _view); + using var p = new OverlayPainter(canvas, OverlayPalette.Current, unit); + p.Surface(width, height); + if (view is null) + { + return height; + } + + var palette = p.Palette; + var pad = p.U(Pad); + var counter = string.Create(OverlayText.Culture, $"{view.Length} / {view.MaxLength}"); + var counterWidth = p.Measure(counter, OverlayStyle.Caption) + pad; + var title = string.IsNullOrWhiteSpace(view.Title) ? Text("Title") : view.Title; + p.Text(title, pad, pad + p.U(22), OverlayStyle.Title, palette.Text, width - pad * 2 - counterWidth); + p.Text(counter, width - pad, pad + p.U(22), OverlayStyle.Caption, palette.Muted, counterWidth, SKTextAlign.Right); + + var field = SKRect.Create(pad, pad + p.U(HeaderHeight), width - pad * 2, p.U(FieldHeight)); + DrawField(p, view, field); + + var keysTop = field.Bottom + p.U(18); + var keysWidth = width - pad * 2; + var gap = p.U(KeyGap); + var keyUnit = (keysWidth - gap * (ImeKeyboardLayout.Columns - 1)) / ImeKeyboardLayout.Columns; + for (var row = 0; row < view.Rows.Count; row++) + { + var keys = view.Rows[row]; + var rowWidth = ImeKeyboardLayout.RowWidth(keys); + var x = pad + (ImeKeyboardLayout.Columns - rowWidth) / 2 * (keyUnit + gap); + var y = keysTop + row * (p.U(KeyHeight) + gap); + for (var column = 0; column < keys.Count; column++) + { + var key = keys[column]; + var keyWidth = key.Width * keyUnit + (key.Width - 1) * gap; + DrawKey(p, view, key, SKRect.Create(x, y, keyWidth, p.U(KeyHeight)), + row == view.FocusRow && column == view.FocusColumn); + x += keyWidth + gap; + } + } + + var footerTop = height - p.U(FooterHeight); + p.Divider(pad, footerTop, width - pad * 2); + DrawFooter(p, view, pad, footerTop + p.U(FooterHeight) / 2, width - pad); + return height; + } + + private static void DrawField(OverlayPainter p, ImeKeyboardView view, SKRect field) + { + var palette = p.Palette; + var radius = p.U(OverlayStyle.CardRadius); + p.RoundRect(field, radius, palette.Elevated); + p.Outline(field, radius, palette.Accent, 2); + + var inset = p.U(18); + var inner = new SKRect(field.Left + inset, field.Top, field.Right - inset, field.Bottom); + var baseline = field.MidY + p.U(9); + if (view.Text.Length == 0) + { + p.Text(view.Placeholder, inner.Left, baseline, FieldFont, palette.Faint, inner.Width); + } + + var caretX = p.Measure(view.Text[..Math.Clamp(view.Caret, 0, view.Text.Length)], FieldFont); + var offset = Math.Max(0, caretX - inner.Width + p.U(4)); + p.Canvas.Save(); + p.Canvas.ClipRect(inner); + p.Text(view.Text, inner.Left - offset, baseline, FieldFont, palette.Text, float.MaxValue); + if (view.CaretVisible) + { + var caret = SKRect.Create(inner.Left - offset + caretX, field.MidY - p.U(15), Math.Max(2, p.U(2.5f)), p.U(30)); + p.Rect(caret, palette.Accent); + } + + p.Canvas.Restore(); + } + + private static void DrawKey(OverlayPainter p, ImeKeyboardView view, ImeKey key, SKRect bounds, bool focused) + { + var palette = p.Palette; + var radius = p.U(8); + var disabled = key.Kind == ImeKeyKind.Character && view.NumbersOnly && !IsNumeric(key.Lower) || + key.Kind == ImeKeyKind.Shift && view.Page == ImePage.Symbols; + if (key.Kind == ImeKeyKind.Done) + { + if (focused) + { + var ring = bounds; + ring.Inflate(p.U(3), p.U(3)); + p.Outline(ring, radius + p.U(3), palette.Text, 2.5f); + } + + p.RoundRect(bounds, radius, palette.Accent); + p.Text(DoneLabel(view.EnterLabel), bounds.MidX, bounds.MidY + p.U(6), KeyLabelFont, palette.AccentForeground, + bounds.Width - p.U(12), SKTextAlign.Center); + DrawHint(p, view, key, bounds, palette.AccentForeground); + return; + } + + p.Card(bounds, focused); + if (key.Kind == ImeKeyKind.Shift && view.Shift == ImeShift.Locked && !disabled) + { + p.RoundRect(bounds, radius, palette.Accent.WithAlpha(0x40)); + } + + var color = disabled ? palette.Faint : palette.Text; + switch (key.Kind) + { + case ImeKeyKind.Character: + var label = view.Shift == ImeShift.Off || view.Page == ImePage.Symbols ? key.Lower : key.Upper; + p.Text(label, bounds.MidX, bounds.MidY + p.U(8), KeyFont, color, bounds.Width, SKTextAlign.Center); + break; + case ImeKeyKind.Shift: + p.Text("⇧", bounds.MidX, bounds.MidY + p.U(8), KeyFont, + view.Shift != ImeShift.Off && !disabled ? palette.Accent : color, bounds.Width, SKTextAlign.Center); + break; + case ImeKeyKind.Page: + var page = view.Page switch + { + ImePage.Letters => "!#1", + ImePage.Symbols => "àé", + _ => "ABC", + }; + p.Text(page, bounds.MidX, bounds.MidY + p.U(6), KeyLabelFont, color, bounds.Width, SKTextAlign.Center); + break; + case ImeKeyKind.Space: + p.Text(Text("Space"), bounds.MidX, bounds.MidY + p.U(6), KeyLabelFont, palette.Secondary, bounds.Width, + SKTextAlign.Center); + break; + case ImeKeyKind.Backspace: + p.Text("⌫", bounds.MidX, bounds.MidY + p.U(8), KeyFont, color, bounds.Width, SKTextAlign.Center); + break; + case ImeKeyKind.CursorLeft: + p.Text("←", bounds.MidX, bounds.MidY + p.U(8), KeyFont, color, bounds.Width, SKTextAlign.Center); + break; + case ImeKeyKind.CursorRight: + p.Text("→", bounds.MidX, bounds.MidY + p.U(8), KeyFont, color, bounds.Width, SKTextAlign.Center); + break; + } + + DrawHint(p, view, key, bounds, palette.Text); + } + + private static void DrawHint(OverlayPainter p, ImeKeyboardView view, ImeKey key, SKRect bounds, SKColor ink) + { + if (view.Scheme == OverlayInputScheme.Keyboard) + { + return; + } + + OverlayButton? button = key.Kind switch + { + ImeKeyKind.Shift => OverlayButton.L2, + ImeKeyKind.Page => OverlayButton.L3, + ImeKeyKind.Space => OverlayButton.Triangle, + ImeKeyKind.Backspace => OverlayButton.Square, + ImeKeyKind.CursorLeft => OverlayButton.L1, + ImeKeyKind.CursorRight => OverlayButton.R1, + ImeKeyKind.Done => OverlayButton.R2, + _ => null, + }; + if (button is not { } shortcut) + { + return; + } + + var prompt = new OverlayPrompt(shortcut, string.Empty, string.Empty); + var width = p.PromptGlyphWidth(prompt, view.Scheme, HintScale); + var middle = bounds.Top + p.U(15); + if (width > bounds.Width * 0.6f) + { + return; + } + + p.PromptGlyph(prompt, view.Scheme, bounds.Right - width - p.U(6), middle, HintScale); + } + + private static void DrawFooter(OverlayPainter p, ImeKeyboardView view, float left, float middle, float right) + { + List<OverlayPrompt> prompts; + if (view.Scheme == OverlayInputScheme.Keyboard) + { + prompts = + [ + new(OverlayButton.R2, DoneLabel(view.EnterLabel), "Enter"), + new(OverlayButton.Cancel, Text("Close"), "Esc"), + new(OverlayButton.Square, Text("Delete"), "Backspace"), + new(OverlayButton.L1, Text("Cursor"), "← →"), + ]; + p.Text(Text("Type"), left, middle + p.U(6), OverlayStyle.Label, p.Palette.Muted, + right - left - p.PromptsWidth(prompts, view.Scheme) - p.U(24)); + } + else + { + prompts = + [ + new(OverlayButton.Confirm, Text("Select"), "Enter"), + new(OverlayButton.Cancel, Text("Close"), "Esc"), + ]; + } + + var width = p.PromptsWidth(prompts, view.Scheme); + p.Prompts(prompts, view.Scheme, right - width, middle); + } + + private static string DoneLabel(ImeEnterLabel label) => label switch + { + ImeEnterLabel.Send => Text("Send"), + ImeEnterLabel.Search => Text("Search"), + ImeEnterLabel.Go => Text("Go"), + _ => Text("Done"), + }; + + private static bool IsNumeric(string text) => + text.Length == 1 && (char.IsDigit(text[0]) || text[0] is '.' or ',' or '-' or '+'); +} diff --git a/src/SharpEmu.Libs/Ime/ImeKeyboardLayout.cs b/src/SharpEmu.Libs/Ime/ImeKeyboardLayout.cs new file mode 100644 index 000000000..9d3d19fa8 --- /dev/null +++ b/src/SharpEmu.Libs/Ime/ImeKeyboardLayout.cs @@ -0,0 +1,122 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; + +namespace SharpEmu.Libs.Ime; + +internal enum ImeKeyKind +{ + Character, + Shift, + Page, + Space, + Backspace, + CursorLeft, + CursorRight, + Done, +} + +internal enum ImePage +{ + Letters, + Symbols, + Accents, +} + +internal sealed record ImeKey(ImeKeyKind Kind, string Lower, string Upper, float Width); + +internal static class ImeKeyboardLayout +{ + internal const float Columns = 12; + + private const string AccentsRow0 = "àáâäåæçćčèéê"; + private const string AccentsRow1 = "ëęəìíîïığłñń"; + private const string AccentsRow2 = "òóôöõőøœśşšß"; + private const string AccentsRow3 = "ùúûüűiźżž"; + + private static readonly CultureInfo Turkish = CultureInfo.GetCultureInfo("tr-TR"); + + internal static IReadOnlyList<IReadOnlyList<ImeKey>> Rows(ImePage page, string? language) + { + var rows = new List<IReadOnlyList<ImeKey>>(5); + switch (page) + { + case ImePage.Symbols: + rows.Add(Characters("1234567890", CultureInfo.InvariantCulture)); + rows.Add(Characters("!@#$%^&*()-_", CultureInfo.InvariantCulture)); + rows.Add(Characters("=+/\\:;'\"?~`|", CultureInfo.InvariantCulture)); + rows.Add(ShiftRow("<>[]{}€£¥", CultureInfo.InvariantCulture)); + break; + case ImePage.Accents: + rows.Add(Characters(AccentsRow0, Turkish)); + rows.Add(Characters(AccentsRow1, Turkish)); + rows.Add(Characters(AccentsRow2, Turkish)); + rows.Add(ShiftRow(AccentsRow3, Turkish)); + break; + default: + var (top, middle, bottom, culture) = Letters(language); + rows.Add(Characters("1234567890", CultureInfo.InvariantCulture)); + rows.Add(Characters(top, culture)); + rows.Add(Characters(middle, culture)); + rows.Add(ShiftRow(bottom, culture)); + break; + } + + rows.Add( + [ + new ImeKey(ImeKeyKind.Page, string.Empty, string.Empty, 1.5f), + Character(",", CultureInfo.InvariantCulture), + new ImeKey(ImeKeyKind.Space, " ", " ", 4), + Character(".", CultureInfo.InvariantCulture), + new ImeKey(ImeKeyKind.CursorLeft, string.Empty, string.Empty, 1), + new ImeKey(ImeKeyKind.CursorRight, string.Empty, string.Empty, 1), + new ImeKey(ImeKeyKind.Done, string.Empty, string.Empty, 2.5f), + ]); + return rows; + } + + internal static float RowWidth(IReadOnlyList<ImeKey> row) + { + var width = 0f; + foreach (var key in row) + { + width += key.Width; + } + + return width; + } + + private static (string Top, string Middle, string Bottom, CultureInfo Culture) Letters(string? language) => + language?.Trim().ToLowerInvariant() switch + { + "tr" or "az" => ("qwertyuıopğü", "asdfghjklşi", "zxcvbnmöç", Turkish), + "de" => ("qwertzuiopü", "asdfghjklöä", "yxcvbnmß-", CultureInfo.InvariantCulture), + _ => ("qwertyuiop", "asdfghjkl", "zxcvbnm-'", CultureInfo.InvariantCulture), + }; + + private static List<ImeKey> Characters(string characters, CultureInfo culture) + { + var keys = new List<ImeKey>(characters.Length); + foreach (var rune in characters.EnumerateRunes()) + { + keys.Add(Character(rune.ToString(), culture)); + } + + return keys; + } + + private static List<ImeKey> ShiftRow(string characters, CultureInfo culture) + { + var keys = new List<ImeKey> { new(ImeKeyKind.Shift, string.Empty, string.Empty, 1.5f) }; + keys.AddRange(Characters(characters, culture)); + keys.Add(new ImeKey(ImeKeyKind.Backspace, string.Empty, string.Empty, 1.5f)); + return keys; + } + + private static ImeKey Character(string lower, CultureInfo culture) => + new(ImeKeyKind.Character, lower, Upper(lower, culture), 1); + + private static string Upper(string lower, CultureInfo culture) => + lower == "ß" ? "ẞ" : lower.ToUpper(culture); +} diff --git a/src/SharpEmu.Libs/Ime/ImeKeyboardSession.cs b/src/SharpEmu.Libs/Ime/ImeKeyboardSession.cs new file mode 100644 index 000000000..3dac281d8 --- /dev/null +++ b/src/SharpEmu.Libs/Ime/ImeKeyboardSession.cs @@ -0,0 +1,564 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Text; +using SharpEmu.Libs.Overlay; +using SharpEmu.Libs.Pad; + +namespace SharpEmu.Libs.Ime; + +internal enum ImeShift +{ + Off, + Once, + Locked, +} + +internal enum ImeTextKind +{ + Default = 0, + BasicLatin = 1, + Url = 2, + Mail = 3, + Number = 4, +} + +internal enum ImeEnterLabel +{ + Default = 0, + Send = 1, + Search = 2, + Go = 3, +} + +internal enum ImeKeyboardInput +{ + None, + Changed, + Done, + Cancel, +} + +internal sealed record ImeKeyboardView( + long Session, + string Title, + string Placeholder, + string Text, + int Caret, + int Length, + int MaxLength, + ImePage Page, + ImeShift Shift, + IReadOnlyList<IReadOnlyList<ImeKey>> Rows, + int FocusRow, + int FocusColumn, + OverlayInputScheme Scheme, + ImeEnterLabel EnterLabel, + bool CaretVisible, + bool NumbersOnly); + +internal sealed class ImeKeyboardSession +{ + private const byte StickLow = 64; + private const byte StickHigh = 192; + private const int KeyBackspace = 0x08; + private const int KeyEnter = 0x0D; + private const int KeyEscape = 0x1B; + private const int KeyLeft = 0x25; + private const int KeyRight = 0x27; + private const int KeyDelete = 0x2E; + private const uint StickUp = 1u << 28; + private const uint StickDown = 1u << 29; + private const uint StickLeft = 1u << 30; + private const uint StickRight = 1u << 31; + private static readonly long FirstRepeatTicks = Stopwatch.Frequency * 2 / 5; + private static readonly long NextRepeatTicks = Stopwatch.Frequency / 12; + private static readonly long BlinkTicks = Stopwatch.Frequency * 53 / 100; + + private readonly long _session; + private readonly string _title; + private readonly string _placeholder; + private readonly string? _language; + private readonly int _maxLength; + private readonly ImeTextKind _kind; + private readonly bool _password; + private readonly ImeEnterLabel _enterLabel; + private readonly List<uint> _controllerChanges = []; + private readonly List<int> _keys = []; + private readonly List<string> _texts = []; + private readonly Dictionary<Repeat, long> _repeatAt = []; + private readonly StringBuilder _text = new(); + private IReadOnlyList<IReadOnlyList<ImeKey>> _rows; + private long _sequence; + private uint _previousButtons; + private long _lastEdit; + private bool _caretVisible = true; + private OverlayInputScheme _scheme; + + internal ImeKeyboardSession(long session, string title, string placeholder, string initialText, int maxLength, + ImeTextKind kind, bool password, bool autoCapitalize, ImeEnterLabel enterLabel, string? language) + { + _session = session; + _title = title; + _placeholder = placeholder; + _language = language; + _maxLength = Math.Max(1, maxLength); + _kind = kind; + _password = password; + _enterLabel = enterLabel; + Page = kind == ImeTextKind.Number ? ImePage.Symbols : ImePage.Letters; + _rows = ImeKeyboardLayout.Rows(Page, language); + Insert(initialText, fromKeyboard: true); + Shift = autoCapitalize && _text.Length == 0 && kind is ImeTextKind.Default or ImeTextKind.BasicLatin + ? ImeShift.Once + : ImeShift.Off; + FocusRow = 1; + FocusColumn = 0; + } + + private enum Repeat + { + Up, + Down, + Left, + Right, + Delete, + CaretLeft, + CaretRight, + KeyBackspace, + KeyDelete, + KeyLeft, + KeyRight, + } + + internal string Text => _text.ToString(); + + internal int Caret { get; private set; } + + internal ImePage Page { get; private set; } + + internal ImeShift Shift { get; private set; } + + internal int FocusRow { get; private set; } + + internal int FocusColumn { get; private set; } + + internal ImeKeyboardView View() + { + var text = _password ? new string('●', _text.Length) : _text.ToString(); + return new ImeKeyboardView(_session, _title, _placeholder, text, Caret, _text.Length, _maxLength, Page, Shift, + _rows, FocusRow, FocusColumn, _scheme, _enterLabel, _caretVisible, _kind == ImeTextKind.Number); + } + + internal void Begin() + { + var state = PadExports.ReadSystemDialogState(); + _sequence = PadExports.InputHistoryPosition; + _previousButtons = state.ControllerButtons | StickMask(state); + _scheme = SystemDialogInput.CurrentScheme(); + _lastEdit = Stopwatch.GetTimestamp(); + } + + internal ImeKeyboardInput Poll() + { + var now = Stopwatch.GetTimestamp(); + var changed = false; + var scheme = SystemDialogInput.CurrentScheme(); + if (scheme != _scheme) + { + _scheme = scheme; + changed = true; + } + + _texts.Clear(); + SystemDialogInput.TakeTexts(_texts); + foreach (var text in _texts) + { + changed |= Insert(text, fromKeyboard: true); + } + + _keys.Clear(); + SystemDialogInput.TakeKeys(_keys); + foreach (var key in _keys) + { + switch (key) + { + case KeyEnter: + return ImeKeyboardInput.Done; + case KeyEscape: + return ImeKeyboardInput.Cancel; + case KeyBackspace: + changed |= DeleteBackward(); + Arm(Repeat.KeyBackspace, now); + break; + case KeyDelete: + changed |= DeleteForward(); + Arm(Repeat.KeyDelete, now); + break; + case KeyLeft: + changed |= MoveCaret(-1); + Arm(Repeat.KeyLeft, now); + break; + case KeyRight: + changed |= MoveCaret(1); + Arm(Repeat.KeyRight, now); + break; + } + } + + _controllerChanges.Clear(); + PadExports.TakeControllerHistory(ref _sequence, _controllerChanges); + var current = PadExports.ReadSystemDialogState(); + var currentButtons = current.ControllerButtons | StickMask(current); + _controllerChanges.Add(currentButtons); + foreach (var buttons in _controllerChanges) + { + var pressed = buttons & ~_previousButtons; + _previousButtons = buttons; + if (pressed == 0) + { + continue; + } + + if ((pressed & OrbisPadButton.R2) != 0) + { + return ImeKeyboardInput.Done; + } + + if ((pressed & OrbisPadButton.Circle) != 0) + { + return ImeKeyboardInput.Cancel; + } + + if ((pressed & (OrbisPadButton.Cross | OrbisPadButton.TouchPad)) != 0 && PressFocused() is var result && + result != ImeKeyboardInput.None) + { + if (result != ImeKeyboardInput.Changed) + { + return result; + } + + changed = true; + } + + if ((pressed & OrbisPadButton.Square) != 0) + { + changed |= DeleteBackward(); + Arm(Repeat.Delete, now); + } + + if ((pressed & OrbisPadButton.Triangle) != 0) + { + changed |= Insert(" ", fromKeyboard: false); + } + + if ((pressed & OrbisPadButton.L1) != 0) + { + changed |= MoveCaret(-1); + Arm(Repeat.CaretLeft, now); + } + + if ((pressed & OrbisPadButton.R1) != 0) + { + changed |= MoveCaret(1); + Arm(Repeat.CaretRight, now); + } + + if ((pressed & OrbisPadButton.L2) != 0) + { + changed |= CycleShift(); + } + + if ((pressed & OrbisPadButton.L3) != 0) + { + NextPage(); + changed = true; + } + + if ((pressed & (OrbisPadButton.Up | StickUp)) != 0) + { + changed |= MoveFocus(0, -1); + Arm(Repeat.Up, now); + } + + if ((pressed & (OrbisPadButton.Down | StickDown)) != 0) + { + changed |= MoveFocus(0, 1); + Arm(Repeat.Down, now); + } + + if ((pressed & (OrbisPadButton.Left | StickLeft)) != 0) + { + changed |= MoveFocus(-1, 0); + Arm(Repeat.Left, now); + } + + if ((pressed & (OrbisPadButton.Right | StickRight)) != 0) + { + changed |= MoveFocus(1, 0); + Arm(Repeat.Right, now); + } + } + + changed |= Held(Repeat.Up, (currentButtons & (OrbisPadButton.Up | StickUp)) != 0, now, () => MoveFocus(0, -1)); + changed |= Held(Repeat.Down, (currentButtons & (OrbisPadButton.Down | StickDown)) != 0, now, () => MoveFocus(0, 1)); + changed |= Held(Repeat.Left, (currentButtons & (OrbisPadButton.Left | StickLeft)) != 0, now, () => MoveFocus(-1, 0)); + changed |= Held(Repeat.Right, (currentButtons & (OrbisPadButton.Right | StickRight)) != 0, now, () => MoveFocus(1, 0)); + changed |= Held(Repeat.Delete, (currentButtons & OrbisPadButton.Square) != 0, now, DeleteBackward); + changed |= Held(Repeat.CaretLeft, (currentButtons & OrbisPadButton.L1) != 0, now, () => MoveCaret(-1)); + changed |= Held(Repeat.CaretRight, (currentButtons & OrbisPadButton.R1) != 0, now, () => MoveCaret(1)); + changed |= Held(Repeat.KeyBackspace, PadExports.IsHostKeyDown(KeyBackspace), now, DeleteBackward); + changed |= Held(Repeat.KeyDelete, PadExports.IsHostKeyDown(KeyDelete), now, DeleteForward); + changed |= Held(Repeat.KeyLeft, PadExports.IsHostKeyDown(KeyLeft), now, () => MoveCaret(-1)); + changed |= Held(Repeat.KeyRight, PadExports.IsHostKeyDown(KeyRight), now, () => MoveCaret(1)); + + if (changed) + { + _lastEdit = now; + } + + var visible = (now - _lastEdit) / BlinkTicks % 2 == 0; + if (visible != _caretVisible) + { + _caretVisible = visible; + changed = true; + } + + return changed ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + } + + internal ImeKeyboardInput PressFocused() + { + var key = _rows[FocusRow][FocusColumn]; + switch (key.Kind) + { + case ImeKeyKind.Character: + var inserted = Insert(Shift == ImeShift.Off || Page == ImePage.Symbols ? key.Lower : key.Upper, + fromKeyboard: false); + return inserted ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + case ImeKeyKind.Shift: + return CycleShift() ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + case ImeKeyKind.Page: + NextPage(); + return ImeKeyboardInput.Changed; + case ImeKeyKind.Space: + return Insert(" ", fromKeyboard: false) ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + case ImeKeyKind.Backspace: + return DeleteBackward() ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + case ImeKeyKind.CursorLeft: + return MoveCaret(-1) ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + case ImeKeyKind.CursorRight: + return MoveCaret(1) ? ImeKeyboardInput.Changed : ImeKeyboardInput.None; + default: + return ImeKeyboardInput.Done; + } + } + + internal bool Insert(string text, bool fromKeyboard) + { + var inserted = false; + foreach (var rune in text.EnumerateRunes()) + { + if (Rune.IsControl(rune) || !Accepts(rune)) + { + continue; + } + + var encoded = rune.ToString(); + if (_text.Length + encoded.Length > _maxLength) + { + break; + } + + _text.Insert(Caret, encoded); + Caret += encoded.Length; + inserted = true; + } + + if (inserted && !fromKeyboard && Shift == ImeShift.Once) + { + Shift = ImeShift.Off; + } + + return inserted; + } + + internal bool DeleteBackward() + { + if (Caret == 0) + { + return false; + } + + var length = Caret >= 2 && char.IsSurrogatePair(_text[Caret - 2], _text[Caret - 1]) ? 2 : 1; + _text.Remove(Caret - length, length); + Caret -= length; + return true; + } + + internal bool DeleteForward() + { + if (Caret >= _text.Length) + { + return false; + } + + var length = Caret + 1 < _text.Length && char.IsSurrogatePair(_text[Caret], _text[Caret + 1]) ? 2 : 1; + _text.Remove(Caret, length); + return true; + } + + internal bool MoveCaret(int step) + { + var next = Caret; + if (step < 0 && next > 0) + { + next -= next >= 2 && char.IsSurrogatePair(_text[next - 2], _text[next - 1]) ? 2 : 1; + } + else if (step > 0 && next < _text.Length) + { + next += next + 1 < _text.Length && char.IsSurrogatePair(_text[next], _text[next + 1]) ? 2 : 1; + } + + if (next == Caret) + { + return false; + } + + Caret = next; + return true; + } + + internal bool CycleShift() + { + if (Page == ImePage.Symbols) + { + return false; + } + + Shift = Shift switch + { + ImeShift.Off => ImeShift.Once, + ImeShift.Once => ImeShift.Locked, + _ => ImeShift.Off, + }; + return true; + } + + internal void NextPage() + { + Page = Page switch + { + ImePage.Letters => ImePage.Symbols, + ImePage.Symbols => ImePage.Accents, + _ => ImePage.Letters, + }; + _rows = ImeKeyboardLayout.Rows(Page, _language); + FocusRow = Math.Clamp(FocusRow, 0, _rows.Count - 1); + FocusColumn = Math.Clamp(FocusColumn, 0, _rows[FocusRow].Count - 1); + } + + internal bool MoveFocus(int columns, int rows) + { + var row = FocusRow; + var column = FocusColumn; + if (columns != 0) + { + var count = _rows[row].Count; + column = ((column + columns) % count + count) % count; + } + + if (rows != 0) + { + var target = Math.Clamp(row + rows, 0, _rows.Count - 1); + if (target != row) + { + column = Nearest(_rows[target], KeyCenter(_rows[row], column)); + row = target; + } + } + + if (row == FocusRow && column == FocusColumn) + { + return false; + } + + FocusRow = row; + FocusColumn = column; + return true; + } + + private bool Accepts(Rune rune) + { + if (_kind != ImeTextKind.Number) + { + return true; + } + + return Rune.IsDigit(rune) || rune.Value is '.' or ',' or '-' or '+'; + } + + private static float KeyCenter(IReadOnlyList<ImeKey> row, int column) + { + var x = (ImeKeyboardLayout.Columns - ImeKeyboardLayout.RowWidth(row)) / 2; + for (var index = 0; index < column; index++) + { + x += row[index].Width; + } + + return x + row[column].Width / 2; + } + + private static int Nearest(IReadOnlyList<ImeKey> row, float center) + { + var best = 0; + var bestDistance = float.MaxValue; + for (var index = 0; index < row.Count; index++) + { + var distance = Math.Abs(KeyCenter(row, index) - center); + if (distance < bestDistance) + { + best = index; + bestDistance = distance; + } + } + + return best; + } + + private static uint StickMask(PadState state) + { + var mask = 0u; + if (state.ControllerLeftY < StickLow) mask |= StickUp; + if (state.ControllerLeftY > StickHigh) mask |= StickDown; + if (state.ControllerLeftX < StickLow) mask |= StickLeft; + if (state.ControllerLeftX > StickHigh) mask |= StickRight; + return mask; + } + + private void Arm(Repeat repeat, long now) => _repeatAt[repeat] = now + FirstRepeatTicks; + + private bool Held(Repeat repeat, bool down, long now, Func<bool> action) + { + if (!down) + { + _repeatAt.Remove(repeat); + return false; + } + + if (!_repeatAt.TryGetValue(repeat, out var at)) + { + _repeatAt[repeat] = now + FirstRepeatTicks; + return false; + } + + if (now < at) + { + return false; + } + + _repeatAt[repeat] = now + NextRepeatTicks; + return action(); + } +} diff --git a/src/SharpEmu.Libs/Overlay/OverlayPainter.cs b/src/SharpEmu.Libs/Overlay/OverlayPainter.cs index d2796e347..5dd8d55d6 100644 --- a/src/SharpEmu.Libs/Overlay/OverlayPainter.cs +++ b/src/SharpEmu.Libs/Overlay/OverlayPainter.cs @@ -278,24 +278,67 @@ public void Prompts(IReadOnlyList<OverlayPrompt> prompts, OverlayInputScheme sch public void Dispose() => _paint.Dispose(); - private float GlyphWidth(OverlayPrompt prompt, OverlayInputScheme scheme) => - scheme == OverlayInputScheme.Keyboard - ? Measure(prompt.KeyLabel, OverlayStyle.KeyCap) + U(18) - : U(OverlayStyle.PromptGlyphRadius * 2); + public float PromptGlyphWidth(OverlayPrompt prompt, OverlayInputScheme scheme, float scale = 1) => + GlyphWidth(prompt, scheme, scale); - private float Glyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, float middle) + public float PromptGlyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, float middle, float scale = 1) => + Glyph(prompt, scheme, x, middle, scale); + + private static string? ShoulderLabel(OverlayButton button, OverlayInputScheme scheme) => (button, scheme) switch + { + (OverlayButton.L1, OverlayInputScheme.Xbox) => "LB", + (OverlayButton.R1, OverlayInputScheme.Xbox) => "RB", + (OverlayButton.L2, OverlayInputScheme.Xbox) => "LT", + (OverlayButton.R2, OverlayInputScheme.Xbox) => "RT", + (OverlayButton.L3, OverlayInputScheme.Xbox) => "LS", + (OverlayButton.R3, OverlayInputScheme.Xbox) => "RS", + (OverlayButton.L1, _) => "L1", + (OverlayButton.R1, _) => "R1", + (OverlayButton.L2, _) => "L2", + (OverlayButton.R2, _) => "R2", + (OverlayButton.L3, _) => "L3", + (OverlayButton.R3, _) => "R3", + _ => null, + }; + + private float GlyphWidth(OverlayPrompt prompt, OverlayInputScheme scheme, float scale = 1) + { + if (scheme == OverlayInputScheme.Keyboard) + { + return Measure(prompt.KeyLabel, Scaled(OverlayStyle.KeyCap, scale)) + U(18 * scale); + } + + return ShoulderLabel(prompt.Button, scheme) is { } label + ? Measure(label, Scaled(OverlayStyle.KeyCap, scale)) + U(16 * scale) + : U(OverlayStyle.PromptGlyphRadius * 2 * scale); + } + + private static OverlayFont Scaled(OverlayFont font, float scale) => font with { Size = font.Size * scale }; + + private float Glyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, float middle, float scale = 1) { - var width = GlyphWidth(prompt, scheme); - var radius = U(OverlayStyle.PromptGlyphRadius); + var width = GlyphWidth(prompt, scheme, scale); + var radius = U(OverlayStyle.PromptGlyphRadius * scale); var cx = x + width / 2; if (scheme == OverlayInputScheme.Keyboard) { - var key = SKRect.Create(x, middle - U(14), width, U(28)); - RoundRect(key, U(6), Palette.Elevated); - Outline(key, U(6), Palette.Faint); - Rect(new SKRect(key.Left + U(5), key.Bottom - U(2.5f), key.Right - U(5), key.Bottom - U(2.5f) + Math.Max(1, Unit)), - Palette.Faint); - Text(prompt.KeyLabel, cx, middle + U(5), OverlayStyle.KeyCap, Palette.Text, width, SKTextAlign.Center); + var key = SKRect.Create(x, middle - U(14 * scale), width, U(28 * scale)); + RoundRect(key, U(6 * scale), Palette.Elevated); + Outline(key, U(6 * scale), Palette.Faint); + Rect(new SKRect(key.Left + U(5 * scale), key.Bottom - U(2.5f * scale), key.Right - U(5 * scale), + key.Bottom - U(2.5f * scale) + Math.Max(1, Unit)), Palette.Faint); + Text(prompt.KeyLabel, cx, middle + U(5 * scale), Scaled(OverlayStyle.KeyCap, scale), Palette.Text, width, + SKTextAlign.Center); + return width; + } + + if (ShoulderLabel(prompt.Button, scheme) is { } shoulder) + { + var pill = SKRect.Create(x, middle - U(12 * scale), width, U(24 * scale)); + RoundRect(pill, U(12 * scale), Palette.Elevated); + Outline(pill, U(12 * scale), Palette.Faint); + Text(shoulder, cx, middle + U(5 * scale), Scaled(OverlayStyle.KeyCap, scale), Palette.Text, width, + SKTextAlign.Center); return width; } @@ -311,7 +354,7 @@ private float Glyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, fl _paint.Style = SKPaintStyle.Fill; _paint.Color = fill; Canvas.DrawCircle(cx, middle, radius, _paint); - Text(letter, cx, middle + U(6), new OverlayFont(17, OverlayWeight.Bold), ink, width, SKTextAlign.Center); + Text(letter, cx, middle + U(6 * scale), new OverlayFont(17 * scale, OverlayWeight.Bold), ink, width, SKTextAlign.Center); return width; } @@ -319,7 +362,7 @@ private float Glyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, fl _paint.Color = Palette.Elevated; Canvas.DrawCircle(cx, middle, radius, _paint); _paint.Style = SKPaintStyle.Stroke; - _paint.StrokeWidth = Math.Max(1, U(1.2f)); + _paint.StrokeWidth = Math.Max(1, U(1.2f * scale)); _paint.Color = Palette.Faint; Canvas.DrawCircle(cx, middle, radius, _paint); Symbol(prompt.Button, scheme, cx, middle, radius); @@ -330,7 +373,7 @@ private float Glyph(OverlayPrompt prompt, OverlayInputScheme scheme, float x, fl private void Symbol(OverlayButton button, OverlayInputScheme scheme, float cx, float cy, float radius) { _paint.Style = SKPaintStyle.Stroke; - _paint.StrokeWidth = Math.Max(1.2f, U(1.8f)); + _paint.StrokeWidth = Math.Max(1.2f, radius * 0.12f); _paint.StrokeCap = SKStrokeCap.Round; _paint.StrokeJoin = SKStrokeJoin.Round; _paint.Color = Palette.Text; diff --git a/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs b/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs index 8fc998478..1e8cb93d8 100644 --- a/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs +++ b/src/SharpEmu.Libs/Overlay/OverlayPrompts.cs @@ -17,6 +17,12 @@ public enum OverlayButton Triangle, Square, DirectionalPad, + L1, + R1, + L2, + R2, + L3, + R3, } public readonly record struct OverlayPrompt(OverlayButton Button, string Label, string KeyLabel); diff --git a/src/SharpEmu.Libs/Pad/PadExports.cs b/src/SharpEmu.Libs/Pad/PadExports.cs index a6a01039d..c92fb4389 100644 --- a/src/SharpEmu.Libs/Pad/PadExports.cs +++ b/src/SharpEmu.Libs/Pad/PadExports.cs @@ -1131,6 +1131,8 @@ private static PadState ReadHostInputState(bool fresh = false) var acceptsKeyboardInput = input.IsHostWindowFocused(); var keyboardButtons = acceptsKeyboardInput ? ReadKeyboardButtons(input) : 0; var controllerButtons = 0u; + var controllerLeftX = (byte)128; + var controllerLeftY = (byte)128; var buttons = keyboardButtons; var leftX = acceptsKeyboardInput ? ReadAnalogStick(input.IsKeyDown(0x41), input.IsKeyDown(0x44)) : (byte)128; var leftY = acceptsKeyboardInput ? ReadAnalogStick(input.IsKeyDown(0x57), input.IsKeyDown(0x53)) : (byte)128; @@ -1155,6 +1157,8 @@ private static PadState ReadHostInputState(bool fresh = false) // small deadzone; otherwise any keyboard value stays. leftX = MergeAxis(pad.LeftX, leftX); leftY = MergeAxis(pad.LeftY, leftY); + controllerLeftX = MergeAxis(pad.LeftX, controllerLeftX); + controllerLeftY = MergeAxis(pad.LeftY, controllerLeftY); rightX = MergeAxis(pad.RightX, rightX); rightY = MergeAxis(pad.RightY, rightY); l2 = Math.Max(l2, pad.LeftTrigger); @@ -1206,6 +1210,8 @@ private static PadState ReadHostInputState(bool fresh = false) HostWindowFocused = acceptsKeyboardInput, KeyboardButtons = keyboardButtons, ControllerButtons = controllerButtons, + ControllerLeftX = controllerLeftX, + ControllerLeftY = controllerLeftY, }; _lastInputSampleTicks = now; _cachedInputHistory = history; diff --git a/src/SharpEmu.Libs/Pad/PadState.cs b/src/SharpEmu.Libs/Pad/PadState.cs index e7a75aeb5..afcd2cad3 100644 --- a/src/SharpEmu.Libs/Pad/PadState.cs +++ b/src/SharpEmu.Libs/Pad/PadState.cs @@ -27,6 +27,8 @@ internal readonly record struct PadState( internal bool HostWindowFocused { get; init; } internal uint KeyboardButtons { get; init; } internal uint ControllerButtons { get; init; } + internal byte ControllerLeftX { get; init; } = 128; + internal byte ControllerLeftY { get; init; } = 128; } /// <summary>SCE_PAD_BUTTON bit values.</summary> diff --git a/src/SharpEmu.Libs/Pad/SystemDialogInput.cs b/src/SharpEmu.Libs/Pad/SystemDialogInput.cs index 36b4f6ebc..455c8ad91 100644 --- a/src/SharpEmu.Libs/Pad/SystemDialogInput.cs +++ b/src/SharpEmu.Libs/Pad/SystemDialogInput.cs @@ -1,6 +1,9 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Overlay; + namespace SharpEmu.Libs.Pad; internal static class SystemDialogInput @@ -8,17 +11,46 @@ internal static class SystemDialogInput internal const uint InterceptedButton = 0x80000000; private static readonly System.Collections.Concurrent.ConcurrentQueue<int> Keys = new(); + private static readonly System.Collections.Concurrent.ConcurrentQueue<string> Texts = new(); private static int _capturing; + private static int _wantsText; private static uint _residualButtons; internal static bool Capturing => Volatile.Read(ref _capturing) != 0; - internal static void Capture() + internal static bool WantsText => Volatile.Read(ref _wantsText) != 0; + + internal static void Capture(bool wantsText = false) { Keys.Clear(); + Texts.Clear(); + Volatile.Write(ref _wantsText, wantsText ? 1 : 0); Volatile.Write(ref _capturing, 1); } + internal static void OnText(string text) + { + if (Capturing && WantsText && !string.IsNullOrEmpty(text)) + { + Texts.Enqueue(text); + } + } + + internal static void TakeTexts(List<string> texts) + { + while (Texts.TryDequeue(out var text)) + { + texts.Add(text); + } + } + + internal static OverlayInputScheme CurrentScheme() => PadExports.ConnectedGamepadType() switch + { + null => OverlayInputScheme.Keyboard, + HostGamepadType.DualSense or HostGamepadType.DualShock4 => OverlayInputScheme.PlayStation, + _ => OverlayInputScheme.Xbox, + }; + internal static void OnKeyDown(int virtualKey) { if (Capturing) @@ -39,6 +71,8 @@ internal static void Release() { Volatile.Write(ref _residualButtons, PadExports.ReadSystemDialogState().Buttons); PadExports.DiscardUnreadStates(); + Volatile.Write(ref _wantsText, 0); + Texts.Clear(); Volatile.Write(ref _capturing, 0); } diff --git a/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs b/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs index 9a588bc92..bf01e1a9a 100644 --- a/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs +++ b/src/SharpEmu.Libs/SaveData/SaveDataDialogExports.cs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: GPL-2.0-or-later using SharpEmu.HLE; -using SharpEmu.HLE.Host; using SharpEmu.Libs.Pad; using SharpEmu.Libs.Overlay; using System.Buffers.Binary; @@ -789,11 +788,6 @@ private static int HeldDirection(PadState state) return up == down ? 0 : up ? -1 : 1; } - private static OverlayInputScheme CurrentScheme() => PadExports.ConnectedGamepadType() switch - { - null => OverlayInputScheme.Keyboard, - HostGamepadType.DualSense or HostGamepadType.DualShock4 => OverlayInputScheme.PlayStation, - _ => OverlayInputScheme.Xbox, - }; + private static OverlayInputScheme CurrentScheme() => SystemDialogInput.CurrentScheme(); } } diff --git a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs index 0aa7ba42a..fa0e5cedf 100644 --- a/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs +++ b/src/SharpEmu.Libs/VideoOut/SdlHostWindow.cs @@ -27,6 +27,7 @@ internal sealed unsafe class SdlHostWindow : IDisposable, IHostGamepadOutput private readonly Action? _toggleBackendHud; private readonly object _gamepadGate = new(); private SDL_Window* _window; + private bool _textInputActive; private SDL_Gamepad* _gamepad; private readonly Pad.TouchContactIds _touchIds = new(); private HostGamepadType _gamepadType; @@ -453,6 +454,7 @@ private void PumpEvents() } _lastEventPumpTimestamp = timestamp; } + SyncTextInput(); SDL_Event windowEvent; while (PollWindowEvent(&windowEvent)) { @@ -497,6 +499,9 @@ private void PumpEvents() case SDL_EventType.SDL_EVENT_KEY_UP: HandleKey(windowEvent.key); break; + case SDL_EventType.SDL_EVENT_TEXT_INPUT: + SystemDialogInput.OnText(PtrToStringUTF8(windowEvent.text.text) ?? string.Empty); + break; case SDL_EventType.SDL_EVENT_MOUSE_MOTION: ShowCursorTemporarily(); break; @@ -532,6 +537,25 @@ private void PumpEvents() } } + private void SyncTextInput() + { + var wanted = SystemDialogInput.WantsText; + if (wanted == _textInputActive || _window is null) + { + return; + } + + _textInputActive = wanted; + if (wanted) + { + SDL_StartTextInput(_window); + } + else + { + SDL_StopTextInput(_window); + } + } + private void ApplySensorEvent(in SDL_Event windowEvent) { lock (_gamepadGate) From 7f0cae729af2e181053673540c1317e24e6b5e99 Mon Sep 17 00:00:00 2001 From: Berk <12572227+par274@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:24:37 +0300 Subject: [PATCH 30/64] Merge/pr 1176 1156 1161 (#1177) * fix(ampr): add the AMM command buffer constructor, destructor and MapDirect Death Stranding builds its AMM buffers with sceAmprAmmCommandBufferConstructor and maps its direct memory with sceAmprAmmCommandBufferMapDirect; both were unresolved, so the title stopped on mapDirect failing before its first frame. MapDirect takes (buffer, va, direct memory offset, size, type, protection) and maps the named offset instead of taking auto pages; its runs are not returned to the auto pool when they are unmapped. The constructor and destructor only drop stale host state, as the buffer itself is set up with SetBuffer. * fix(kernel): add sceKernelPreadv Death Stranding reads with preadv right after its file devices start and crashed on the unresolved import. Fills each iovec in turn from one positional read and returns the bytes read. * fix(ampr): keep queued commands when an attached buffer is set again Death Stranding calls sceAmprCommandBufferSetBuffer with the same buffer before every read it appends. Each call reset the write offset, so only the last read of a batch survived: of the 143 archive headers only the last was read, the other archives looked empty and the title stopped on 'Unable to retrieve prefetch list'. A buffer stays attached until ClearBuffer; setting it again now returns EBUSY and changes nothing. * fix(ampr): only count a buffer this module attached as busy SetBuffer read the guest header alone to decide a buffer was still attached. The APR and AMM constructors leave that header untouched, so a recycled object holding an old pointer would refuse its first SetBuffer and queue nothing. The buffer must also be the one recorded when it was attached here. * fix(kernel): add sceKernelPwritev Death Stranding saves with pwritev and retried the unresolved import forever. Gathers the { base, length } entries and writes them back to back at the offset, like pwrite. * fix(np): add sceNpUnregisterStateCallbackA Death Stranding unregisters its state callback on every offline network retry; registration keeps nothing, so there is nothing to drop. * fix(cpu): allocate the TLS handler within rel32 range of guest code Guest fs:[0] loads are patched into rel32 calls, so the handler must sit within 2 GiB of every patched site. Walk free regions with VirtualQuery around the code instead of probing fixed addresses, and report sites that stay out of range. * fix(gnm): reserve a module arena below 2 GiB before PS4 modules load The presenter starts before modules load and its host allocations fill the low 2 GiB, so later PS4 modules could not be placed. Reserve an arena right after the main image and place non-main modules inside it. * feat(kernel): map files with mmap and sceKernelMmap il2cpp maps global-metadata.dat read-only with MAP_SHARED; only anonymous mappings were supported, so every class and method lookup returned null. * feat(kernel): add pthread_setcancelstate * feat(kernel): deliver Unity's GC suspend callback through arch_raise_user PS4 Unity titles stop the world with libkernel_unity: arch_init_gc registers a callback taking (registers, sp) and arch_raise_user runs it on each mutator thread. Without it the collector waited forever for an acknowledgement. Reuse the guest exception delivery with a Unity argument layout, and report ESRCH whenever the callback cannot be delivered. * fix(gpu): accept 32-bit end-of-pipe timestamps with cache write-back * fix(gnm): decode s_ttracedata in GCN shaders * feat(userservice): add sceUserServiceGetUserColor Unity's PS4 player aborts a login when it fails, so the pad was never opened. * fix(videoout): start the presenter outside the VideoOut state lock Registering a new buffer group under the state lock while the presenter asked whether a flip was pending deadlocked both threads. * fix(gnm): handle the 32-bit write-back timestamps in the GNM end-of-pipe handler The shared interpreter accepted these PS4 forms, so AGC streams changed too. Map them in the GNM handler to the shared 32-bit write-back label instead, and keep the AGC validation as it was. * fix(hle): add the SharePlay connection-info and SystemGesture touch-event imports Street Fighter 6 calls Street Fighter 6 (PPSA02633) spins on libSceSharePlay and libSceSystemGesture imports that resolved to NOT_FOUND: - sceSharePlayGetCurrentConnectionInfoA writes a zeroed 72-byte SceSharePlayConnectionInfoA (status DORMANT: no SharePlay session). - sceSystemGestureGetTouchEvents and sceSystemGestureGetPrimitiveTouchEvents report no touch events. * fix(appcontent): stop the add-on mount retry loop and scope offline entitlements per title Street Fighter 6 booted past the shader fix but then burned several CPU cores for 20+ minutes without ever finishing its boot; the import-loop watchdog only caught it at shutdown ("Detected repeating import loop and forced guest unwind to host"). The last import warnings showed sceAppContentAddcontMount called in a tight loop, and the label trace (SHARPEMU_LOG_APP_CONTENT) showed which labels: "85y-je", "5d5c48", "_mtqu6", "GHOST2APP0000000", "GHOST2BASE000000" - the offline entitlement list that belongs to GTA V Enhanced (PPSA04264) and Ghost of Yotei (PPSA26344). Root cause ---------- NpEntitlementAccess reported that global list for every title. SF6 received it as its own add-on content, tried to mount each package, and sceAppContentAddcontMount always refused with DRM_NO_ENTITLEMENT, so the title retried the mount forever. The fix ------- - NpEntitlementAccessExports scopes the offline entitlements to the titles they belong to (OwnedEntitlements() keyed by ApplicationTitleId); every other title owns none and sees no add-on content to mount. - sceAppContentAddcontMount now grants the mount (writes the "/addcont0" mount point) instead of always refusing. A dump's pak files already carry the add-on data, and the PSN entitlement the real hardware checks cannot be reproduced offline, so refusing only makes titles retry. The label is traced through SHARPEMU_LOG_APP_CONTENT. - NpEntitlementAccessExportsTests configure the running title and add a test that other titles own no add-on entitlements. Result ------ SF6 mounts none of the foreign labels (0 mount traces) and no longer spins; the boot proceeds past the add-on phase. * refactor(np): data-driven add-on entitlements instead of a hard-coded list Review follow-up to the Street Fighter 6 boot fix: the owned add-on entitlements were a hard-coded, global label list in NpEntitlementAccessExports (later scoped to two title ids in code). Make the source of truth editable data instead of code: - New AddcontEntitlements owns the lookup. The labels a title owns are merged from two sources: - user/entitlements.json, a title id -> label array map; the built-in defaults (GTA V Enhanced, Ghost of Yotei) are only the fallback for a missing file, so they can be changed per machine without rebuilding; - an addcont directory (SHARPEMU_ADDCONT_DIR, else <app0>/../addcont, the PS5 dump layout): every subfolder is one installed add-on package and its folder name is its label. - sceAppContentAddcontMount now mounts the package through the existing guest file-system mount registry (RegisterGuestPathMount) onto sequential /addcontN mount points, backed by the package's host folder. A label whose package is not present mounts an empty folder: the title's pak files carry the content, and refusing only makes titles retry the mount forever. Boot verification of Street Fighter 6 is unchanged: zero add-on mounts and no import loop, with the first guest frame presented. * feat(ampr): implement sceAmprAmmCommandBufferConstructor and Destructor Street Fighter 6 imports sceAmprAmmCommandBufferConstructor and Destructor (the only AMM exports its eboot and modules import) and the constructor was missing, so the import resolved to NOT_FOUND. The AMM command buffer lives in GPU-mapped memory the guest manages itself, so unlike the plain command buffer there is nothing for the host to initialize or track: - sceAmprAmmCommandBufferConstructor refuses a null buffer with EINVAL and otherwise returns success without touching the buffer; - sceAmprAmmCommandBufferDestructor returns success. The rest of the AMM family (map/remap/PRT records, submit, wait, measure sizes, usage stats) is left for a title that imports it. * fix(avplayer): run the video on the playback clock when the game never enables the audio stream Street Fighter 6 boots to a permanently black screen at 60 fps: the swapchain readback showed every presented frame as pure black (nonblack_pixels=0, alpha only), and the AvPlayer stats showed the intro movie stuck on its first frame (delivered=1 next_frame=1 last_ts=0 while the game polled GetVideoData 270k+ times). The game plays its movies with the video stream alone - it enables stream 0 (enable_stream index=0), queries the audio stream info, and plays the movie audio through its own Wwise system, never calling sceAvPlayerGetAudioData. The default A/V sync followed the delivered audio whenever the source had an audio track (HasAudio), so a movie whose audio the game never consumes stalls the video on frame 1 forever: the expected frame stays 0 because no audio block was ever delivered. The default sync now follows the audio only when the game enabled the audio stream (AudioStreamIndex >= 0, set by sceAvPlayerEnableStream); otherwise the video runs on the playback clock. sceAvPlayerCurrentTime applies the same gate so it reports the playback clock instead of the stopped audio clock. Verified with Street Fighter 6: the 4972 ms intro movie plays to completion (video_end next_frame=149) and the presented frames carry content (nonblack_pixels=453260/2073600 with a changing frame hash). * fix(avplayer): treat the audio as the sync master once the game pulls audio data * fix(appcontent): validate add-on labels, reuse mount points and cache entitlements atomically Guest labels must match the entitlement charset before reaching a path, the same label keeps one mount point, and the per-title entitlement list is one immutable snapshot with a label lookup instead of two racing statics. * test(appcontent): compare a refused mount point as an empty string * fix(playgo): count RE Engine re_chunk_NNN.pak files as installed chunks A dump without a PlayGo sidecar derives its chunk set from the pak files on disk, but only recognised Unreal's pakchunk<N>-<platform>.pak names. Street Fighter 6 ships re_chunk_000.pak and re_chunk_001.pak (25 GB and 169 GB, the bulk of its content), so scePlayGoGetChunkId reported chunk 0 alone and the title stayed in its "installation in progress" mode: training only, default avatar, and most character textures and models missing. The fallback now also parses re_chunk_<NNN>.pak; SF6 then queries chunks 0 and 1 and receives both as LocalFast. * feat(avplayer): implement sceAvPlayerDisableStream SF6 disables the audio stream of its intro movie; the call was unresolved. Disabling the selected audio stream drops it from A/V sync. * fix(appcontent): mount only add-on packages present on disk Granting every label changed the behaviour of titles without add-ons and was not needed: once entitlements are scoped per title, Street Fighter 6 mounts nothing. A label whose package folder is missing is refused with DRM_NO_ENTITLEMENT again. * fix(np): key the default add-on entitlements by concept id The built-in offline entitlements were keyed by title id, which is per region: the EU GTA V dump (PPSA04263) matched no row and lost the Story Mode labels the global list used to give it. Upstream's list had applied to every title, so the regression only appeared once it was scoped. No file in a dump lists the owned labels (real hardware gets them from the PSN account; Ghost of Yotei's labels only exist inside its eboot, GTA V and Street Fighter 6 enumerate them through sceNpEntitlementAccessGetAddcontEntitlementInfoList), so a table stays necessary. Key it by the param.json conceptId instead, which every regional release of a game shares: GTA V 201930, Ghost of Yotei 10003923. - Ps5ParamJsonReader reads conceptId; SelfImage carries it and the runtime hands it to AddcontEntitlements.ConfigureConceptId. - The entitlement snapshot is cached per (title id, concept id). - user/entitlements.json accepts a concept id key too; a title id entry wins. - Tests: GTA EU owns the three GTA labels, Street Fighter 6's concept owns nothing, title id beats concept id, conceptId is read from param.json. * [Ampr] Keep a single AMM command buffer constructor and destructor after merging both PRs * [GPU] Queue a deferred slice's completion when its tick is reserved so priority work stays in tick order --------- Co-authored-by: foued <attar.foued@gmail.com> --- .../Cpu/Native/DirectExecutionBackend.cs | 193 +++++++++++--- src/SharpEmu.Core/Loader/ParamLoader.cs | 21 +- src/SharpEmu.Core/Loader/SelfImage.cs | 7 +- src/SharpEmu.Core/Loader/SelfLoader.cs | 8 +- .../Memory/PhysicalVirtualMemory.cs | 40 +++ src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs | 2 + src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs | 25 ++ src/SharpEmu.GnmMode/Loader/GnmSelfLoader.cs | 47 +++- .../Shaders/GcnShaderDecoder.cs | 2 +- src/SharpEmu.HLE/GuestThreadExecution.cs | 33 +++ src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs | 104 +++++++- src/SharpEmu.Libs/Ampr/AmprExports.cs | 29 +++ .../AppContent/AppContentExports.cs | 89 ++++++- src/SharpEmu.Libs/AvPlayer/AvPlayerExports.cs | 38 ++- .../Gpu/Scheduling/SubmissionScheduler.cs | 25 +- .../Kernel/KernelExceptionCompatExports.cs | 83 +++++- .../Kernel/KernelFileExtendedExports.cs | 132 ++++++++++ .../Kernel/KernelMemoryCompatExports.Mmap.cs | 158 ++++++++++-- .../Kernel/KernelPthreadCompatExports.cs | 28 ++ src/SharpEmu.Libs/Np/AddcontEntitlements.cs | 240 ++++++++++++++++++ .../Np/NpEntitlementAccessExports.cs | 43 +--- src/SharpEmu.Libs/Np/NpManagerExports.cs | 13 + src/SharpEmu.Libs/PlayGo/PlayGoExports.cs | 46 ++-- src/SharpEmu.Libs/Share/SharePlayExports.cs | 22 ++ .../SystemGesture/SystemGestureExports.cs | 24 ++ .../UserService/UserServiceExports.cs | 26 ++ src/SharpEmu.Libs/VideoOut/VideoOutExports.cs | 35 ++- .../Ampr/AmprSetBufferTests.cs | 91 +++++++ .../AppContent/AddcontMountTests.cs | 198 +++++++++++++++ .../Cpu/GuestExceptionExecutorHandoffTests.cs | 3 +- .../Cpu/NativeTlsNearAllocationTests.cs | 56 ++++ .../Kernel/KernelArchRaiseUserTests.cs | 143 +++++++++++ .../Kernel/PosixMemoryAndSignalTests.cs | 79 ++++++ .../Loader/GcnShaderTests.cs | 9 + .../Loader/GnmEndOfPipeTests.cs | 54 ++++ .../Loader/Ps5ParamJsonReaderTests.cs | 33 +++ .../Memory/PhysicalVirtualMemoryTests.cs | 21 ++ .../Np/NpEntitlementAccessExportsTests.cs | 33 ++- .../PlayGo/PlayGoExportsTests.cs | 12 + .../Pthread/PthreadSetCancelStateTests.cs | 33 +++ .../UserService/UserServiceExportsTests.cs | 26 ++ 41 files changed, 2134 insertions(+), 170 deletions(-) create mode 100644 src/SharpEmu.Libs/Np/AddcontEntitlements.cs create mode 100644 tests/SharpEmu.Libs.Tests/Ampr/AmprSetBufferTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/AppContent/AddcontMountTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Cpu/NativeTlsNearAllocationTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Kernel/KernelArchRaiseUserTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Loader/Ps5ParamJsonReaderTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Pthread/PthreadSetCancelStateTests.cs diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs index 72a5dd5b0..267897ccd 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.cs @@ -559,7 +559,8 @@ private sealed class ExternalGuestThreadState private readonly record struct PendingGuestException( ulong Handler, int ExceptionType, - ulong ExceptionStackBase); + ulong ExceptionStackBase, + GuestExceptionHandlerArguments Arguments); private sealed class GuestContinuationRunner : IDisposable { @@ -3360,17 +3361,49 @@ private unsafe nint CreateExceptionHandlerTrampoline(nint managedHandler) return (nint)ptr; } + // rel32 calls from guest code reach +-2 GiB; stay well inside it so stubs at both ends of the block are reachable. + private const ulong NearEntryWindow = 0x70000000uL; + private const ulong AllocationGranularity = 0x10000uL; + private const ulong MaxUserAddress = 0x00007FFFFFFE0000uL; + private const uint MEM_FREE = 0x10000u; + private unsafe void* TryAllocateNearEntry(nuint size) { - ulong entryPoint = _entryPoint; - ulong baseAddress = entryPoint & 0xFFFFFFFFFFFF0000uL; - for (long num = 0L; num <= 1879048192; num += 16777216) + ulong baseAddress = _entryPoint & ~(AllocationGranularity - 1); + ulong lowLimit = baseAddress > NearEntryWindow ? baseAddress - NearEntryWindow : 0; + if (lowLimit < AllocationGranularity) + { + lowLimit = AllocationGranularity; + } + ulong highLimit = Math.Min(baseAddress + NearEntryWindow, MaxUserAddress); + + // Grid probing missed every gap in crowded layouts; ask the OS where the free ranges are instead. + var freeRegions = new List<(ulong Start, ulong End)>(); + ulong cursor = lowLimit; + while (cursor < highLimit) { - if (TryAllocAt(baseAddress, num, size, out var memory)) + if (VirtualQuery((void*)cursor, out var information, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0 || + information.RegionSize == 0) { - return memory; + break; + } + ulong regionStart = information.BaseAddress; + ulong regionEnd = regionStart + information.RegionSize; + if (information.State == MEM_FREE) + { + freeRegions.Add((regionStart, regionEnd)); } - if (num != 0L && TryAllocAt(baseAddress, -num, size, out memory)) + if (regionEnd <= cursor) + { + break; + } + cursor = regionEnd; + } + + foreach (ulong candidate in OrderNearEntryCandidates(freeRegions, baseAddress, size, lowLimit, highLimit)) + { + void* memory = VirtualAlloc((void*)candidate, size, 12288u, 64u); + if (memory != null) { return memory; } @@ -3378,36 +3411,52 @@ private unsafe nint CreateExceptionHandlerTrampoline(nint managedHandler) return null; } - private unsafe static bool TryAllocAt(ulong baseAddress, long signedDelta, nuint size, out void* memory) + // Returns 64 KiB-aligned addresses where `size` bytes fit inside a free region and inside + // [lowLimit, highLimit), nearest to entryBase first. + internal static List<ulong> OrderNearEntryCandidates( + IReadOnlyList<(ulong Start, ulong End)> freeRegions, + ulong entryBase, + ulong size, + ulong lowLimit, + ulong highLimit) { - memory = null; - ulong num; - if (signedDelta >= 0) + var candidates = new List<(ulong Distance, ulong Address)>(); + foreach (var (regionStart, regionEnd) in freeRegions) { - if (baseAddress > (ulong)(-1 - signedDelta)) + ulong start = (Math.Max(regionStart, lowLimit) + AllocationGranularity - 1) & ~(AllocationGranularity - 1); + ulong end = Math.Min(regionEnd, highLimit); + if (end <= start || end - start < size) { - return false; + continue; } - num = baseAddress + (ulong)signedDelta; - } - else - { - ulong num2 = (ulong)(-signedDelta); - if (baseAddress < num2) + + // Candidate above the entry: the lowest aligned address at or after it. + ulong above = (Math.Max(start, entryBase) + AllocationGranularity - 1) & ~(AllocationGranularity - 1); + if (above <= end && end - above >= size) { - return false; + candidates.Add((above - entryBase, above)); + } + + // Candidate below the entry: the highest aligned address whose block ends at or before it. + ulong belowEnd = Math.Min(end, entryBase); + if (belowEnd >= start && belowEnd - start >= size) + { + ulong below = (belowEnd - size) & ~(AllocationGranularity - 1); + if (below >= start) + { + candidates.Add((entryBase - below, below)); + } } - num = baseAddress - num2; } - void* ptr = VirtualAlloc((void*)num, size, 12288u, 64u); - if (ptr == null) + + candidates.Sort(static (left, right) => left.Distance.CompareTo(right.Distance)); + var result = new List<ulong>(candidates.Count); + foreach (var candidate in candidates) { - return false; + result.Add(candidate.Address); } - memory = ptr; - return true; + return result; } - internal readonly record struct TlsPatchScanRange(ulong Start, ulong End); private readonly record struct TlsPatchCounts( @@ -3495,10 +3544,15 @@ private unsafe void PatchTlsPatterns() } } + var outOfRange = Volatile.Read(ref _tlsOutOfRangeSites); Console.Error.WriteLine( $"[LOADER][INFO] Patched {counts.Loads} TLS loads, {counts.Stores} TLS stores, " + $"{counts.StackCanaries} stack-canary accesses " + - $"across {scannedRanges} executable range(s), bytes=0x{scannedBytes:X}, reused={reusedRanges}"); + $"across {scannedRanges} executable range(s), bytes=0x{scannedBytes:X}, reused={reusedRanges}, out_of_range={outOfRange}"); + if (outOfRange > 0) + { + Console.Error.WriteLine($"[LOADER][WARNING] {outOfRange} TLS site(s) are beyond rel32 range of the TLS handler at 0x{_tlsHandlerAddress:X16}."); + } } private unsafe TlsPatchCounts PatchTlsPatternsInRange(ulong rangeStart, ulong rangeEnd) @@ -3706,7 +3760,10 @@ private unsafe bool PatchTlsLoadInstruction(nint address, int instructionLength, } var displacement = (long)handler - ((long)address + 6); if (displacement < int.MinValue || displacement > int.MaxValue) + { + Interlocked.Increment(ref _tlsOutOfRangeSites); return false; + } // REX.W keeps retained operand-size prefixes from changing the call width. Span<byte> patch = stackalloc byte[instructionLength]; patch.Fill(0x90); @@ -3716,6 +3773,8 @@ private unsafe bool PatchTlsLoadInstruction(nint address, int instructionLength, return WriteTlsInstruction(address, patch); } + private int _tlsOutOfRangeSites; + private readonly nint[] _tlsRegisterLoadHelpers = new nint[16]; private unsafe nint CreateTlsRegisterLoadHelper(int destinationRegister) @@ -3771,6 +3830,7 @@ private unsafe nint CreateTlsImmediateStoreHelper(int tlsOffset, int immediateVa long num3 = _tlsHandlerAddress - (num + num2 + 4); if (num3 < int.MinValue || num3 > int.MaxValue) { + Interlocked.Increment(ref _tlsOutOfRangeSites); Console.Error.WriteLine($"[LOADER][WARNING] TLS store helper out of rel32 range at 0x{num:X16}"); return 0; } @@ -3823,6 +3883,7 @@ private unsafe bool PatchCallSite(nint address, int instructionLength, nint targ var displacement = (long)target - ((long)address + 5); if (displacement < int.MinValue || displacement > int.MaxValue) { + Interlocked.Increment(ref _tlsOutOfRangeSites); Console.Error.WriteLine($"[LOADER][WARNING] TLS patch out of rel32 range at 0x{address:X16}"); return false; } @@ -4987,6 +5048,23 @@ public bool TryRaiseGuestException( ulong handler, int exceptionType, out string? error) + { + return TryRaiseGuestException( + callerContext, + threadHandle, + handler, + exceptionType, + GuestExceptionHandlerArguments.Signal, + out error); + } + + public bool TryRaiseGuestException( + CpuContext callerContext, + ulong threadHandle, + ulong handler, + int exceptionType, + GuestExceptionHandlerArguments arguments, + out string? error) { error = null; var logGuestExceptions = string.Equals( @@ -5051,7 +5129,8 @@ public bool TryRaiseGuestException( QueuePendingGuestExceptionLocked(threadHandle, new PendingGuestException( handler, exceptionType, - external.ExceptionStackBase)); + external.ExceptionStackBase, + arguments)); return true; } @@ -5063,7 +5142,8 @@ public bool TryRaiseGuestException( QueuePendingGuestExceptionLocked(threadHandle, new PendingGuestException( handler, exceptionType, - external.ExceptionStackBase)); + external.ExceptionStackBase, + arguments)); if (logGuestExceptions) { Console.Error.WriteLine( @@ -5111,14 +5191,16 @@ public bool TryRaiseGuestException( QueuePendingGuestExceptionLocked(threadHandle, new PendingGuestException( handler, exceptionType, - exceptionStackBase)); + exceptionStackBase, + arguments)); return true; } QueuePendingGuestExceptionLocked(threadHandle, new PendingGuestException( handler, exceptionType, - exceptionStackBase)); + exceptionStackBase, + arguments)); if (logGuestExceptions) { Console.Error.WriteLine( @@ -5230,11 +5312,18 @@ void DeliverException() var deliveryStarted = Stopwatch.GetTimestamp(); try { + ResolveGuestExceptionHandlerArguments( + target.Context, + arguments, + exceptionType, + exceptionContextAddress, + out var handlerArg0, + out var handlerArg1); deliverySucceeded = TryCallGuestFunction( target.Context, handler, - unchecked((ulong)exceptionType), - exceptionContextAddress, + handlerArg0, + handlerArg1, exceptionStackBase + callbackStackOffset, callbackStackSize, $"kernel exception 0x{exceptionType:X2}", @@ -5289,6 +5378,7 @@ void DeliverException() threadHandle, pendingFollowUp.Handler, pendingFollowUp.ExceptionType, + pendingFollowUp.Arguments, out var followUpError)) { Console.Error.WriteLine( @@ -5438,11 +5528,18 @@ private void DeliverPendingGuestExceptionAtSafePoint( $"rip=0x{interruptedContinuation.Rip:X16}"); } + ResolveGuestExceptionHandlerArguments( + currentContext, + pending.Arguments, + pending.ExceptionType, + exceptionContextAddress, + out var handlerArg0, + out var handlerArg1); if (!TryCallGuestFunction( currentContext, pending.Handler, - unchecked((ulong)pending.ExceptionType), - exceptionContextAddress, + handlerArg0, + handlerArg1, pending.ExceptionStackBase + callbackStackOffset, callbackStackSize, $"kernel exception 0x{pending.ExceptionType:X2} safe point", @@ -5463,6 +5560,29 @@ private void DeliverPendingGuestExceptionAtSafePoint( } } + // A Unity GC suspend callback takes (mcontext, interrupted rsp), where the signal + // convention takes (type, mcontext). The rsp is read back from the context the + // writer just filled in, so both paths agree on the interrupted stack pointer. + internal static void ResolveGuestExceptionHandlerArguments( + CpuContext context, + GuestExceptionHandlerArguments arguments, + int exceptionType, + ulong exceptionContextAddress, + out ulong arg0, + out ulong arg1) + { + if (arguments == GuestExceptionHandlerArguments.UnityGcSuspend) + { + _ = context.TryReadUInt64(exceptionContextAddress + 0xB8, out var interruptedRsp); + arg0 = exceptionContextAddress; + arg1 = interruptedRsp; + return; + } + + arg0 = unchecked((ulong)exceptionType); + arg1 = exceptionContextAddress; + } + private void QueuePendingGuestExceptionLocked( ulong threadHandle, PendingGuestException pending) @@ -6186,6 +6306,7 @@ thread.BlockWaiter is not null && thread.ThreadHandle, pendingException.Handler, pendingException.ExceptionType, + pendingException.Arguments, out var pendingError)) { Console.Error.WriteLine( diff --git a/src/SharpEmu.Core/Loader/ParamLoader.cs b/src/SharpEmu.Core/Loader/ParamLoader.cs index 614dcc766..f29794009 100644 --- a/src/SharpEmu.Core/Loader/ParamLoader.cs +++ b/src/SharpEmu.Core/Loader/ParamLoader.cs @@ -27,21 +27,21 @@ public sealed record Disc(LocalizedParameters? LocalizedParameters); public static class Ps5ParamJsonReader { - public static (string? Title, string? TitleId, string? Version) TryReadPs5Param(IFileSystem fs, string paramJsonPath) + public static (string? Title, string? TitleId, string? Version, string? ConceptId) TryReadPs5Param(IFileSystem fs, string paramJsonPath) { if (!fs.Exists(paramJsonPath)) - return (null, null, null); + return (null, null, null, null); if (!fs.TryReadAllBytes(paramJsonPath, out var data)) - return (null, null, null); + return (null, null, null, null); return TryReadPs5Param(data); } - public static (string? Title, string? TitleId, string? Version) TryReadPs5Param(byte[] data) + public static (string? Title, string? TitleId, string? Version, string? ConceptId) TryReadPs5Param(byte[] data) { if (data == null || data.Length == 0) - return (null, null, null); + return (null, null, null, null); try { @@ -56,14 +56,14 @@ public static (string? Title, string? TitleId, string? Version) TryReadPs5Param( } catch (JsonException) { - return (null, null, null); + return (null, null, null, null); } } - private static (string? Title, string? TitleId, string? Version) TryReadPs5Param(JsonElement root) + private static (string? Title, string? TitleId, string? Version, string? ConceptId) TryReadPs5Param(JsonElement root) { if (root.ValueKind != JsonValueKind.Object) - return (null, null, null); + return (null, null, null, null); var titleId = GetString(root, "titleId"); @@ -74,7 +74,10 @@ private static (string? Title, string? TitleId, string? Version) TryReadPs5Param string? title = ExtractTitleName(root); - return (title, titleId, ver); + // conceptId is shared by every regional release of one game (param.sfo has none). + var conceptId = GetString(root, "conceptId"); + + return (title, titleId, ver, conceptId); } private static string? ExtractTitleName(JsonElement root) diff --git a/src/SharpEmu.Core/Loader/SelfImage.cs b/src/SharpEmu.Core/Loader/SelfImage.cs index 98516af0a..62df9c058 100644 --- a/src/SharpEmu.Core/Loader/SelfImage.cs +++ b/src/SharpEmu.Core/Loader/SelfImage.cs @@ -28,7 +28,8 @@ public SelfImage( uint tlsModuleId = 0, ulong tlsMemorySize = 0, ulong tlsStaticOffset = 0, - IReadOnlyList<string>? importedModuleNames = null) + IReadOnlyList<string>? importedModuleNames = null, + string? conceptId = null) { ArgumentNullException.ThrowIfNull(programHeaders); ArgumentNullException.ThrowIfNull(mappedRegions); @@ -48,6 +49,7 @@ public SelfImage( Title = title; TitleId = titleId; Version = version; + ConceptId = conceptId; TlsModuleId = tlsModuleId; TlsMemorySize = tlsMemorySize; TlsStaticOffset = tlsStaticOffset; @@ -84,6 +86,9 @@ public SelfImage( public string? Version { get; } + /// <summary>The PS5 concept id shared by every regional release of the game, when param.json has one.</summary> + public string? ConceptId { get; } + public uint TlsModuleId { get; } public ulong TlsMemorySize { get; } diff --git a/src/SharpEmu.Core/Loader/SelfLoader.cs b/src/SharpEmu.Core/Loader/SelfLoader.cs index 72764066e..7caf326db 100644 --- a/src/SharpEmu.Core/Loader/SelfLoader.cs +++ b/src/SharpEmu.Core/Loader/SelfLoader.cs @@ -383,10 +383,11 @@ private SelfImage LoadCore( tlsModuleId, tlsInfo.MemorySize, tlsInfo.StaticOffset, - importedModuleNames); + importedModuleNames, + applicationInfo.ConceptId); } - private static (string? Title, string? TitleId, string? Version) TryLoadParamJson( + private static (string? Title, string? TitleId, string? Version, string? ConceptId) TryLoadParamJson( IFileSystem? fs, string? mountRoot) { @@ -421,7 +422,8 @@ private static (string? Title, string? TitleId, string? Version) TryLoadParamJso Console.WriteLine( $"[LOADER] Title: {applicationInfo.Title ?? "(unknown)"}, " + $"TitleId: {applicationInfo.TitleId ?? "(unknown)"}, " + - $"Version: {applicationInfo.Version ?? "(unknown)"}"); + $"Version: {applicationInfo.Version ?? "(unknown)"}, " + + $"ConceptId: {applicationInfo.ConceptId ?? "(unknown)"}"); return applicationInfo; } diff --git a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs index 54f440985..e6ba07fb5 100644 --- a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs +++ b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs @@ -394,6 +394,46 @@ public bool TryAllocateAtExact(ulong desiredAddress, ulong size, bool executable return true; } + // Reserves [address, address + size) on the host without committing it and marks the + // reservation as ours, so later fixed allocations can commit sub-ranges inside it while + // unrelated host allocations cannot take the space. Clear() releases it with the other + // granule reservations. Windows only; false when the range is not free at exactly address. + public bool TryReserveOwnedRange(ulong address, ulong size) + { + if (!OperatingSystem.IsWindows() || address == 0 || size == 0 || + (address & (HostAllocationGranularity - 1)) != 0) + { + return false; + } + + var alignedSize = AlignUp(size, HostAllocationGranularity); + _gate.EnterReadLock(); + try + { + lock (_fixedAllocationGate) + { + var reserved = _hostMemory.Reserve(address, alignedSize, HostPageProtection.ReadWrite); + if (reserved == 0) + { + return false; + } + + if (reserved != address) + { + _hostMemory.Free(reserved); + return false; + } + + _fixedGranuleReservationBases.Add(address); + return true; + } + } + finally + { + _gate.ExitReadLock(); + } + } + // Aligned starts of the free host ranges in [low, highExclusive) that can hold size // bytes, from the host's own region map. The ranges are free when listed; another // thread may take one before the caller allocates it. diff --git a/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs b/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs index 5c0fc6129..8f7c229c2 100644 --- a/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs +++ b/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs @@ -193,11 +193,13 @@ public OrbisGen2Result Run(string ebootPath) FiberExports.ResetRuntimeState(); Http2Exports.ResetRuntimeState(); NpAuthExports.ResetRuntimeState(); + AppContentExports.ResetRuntimeState(); NpUniversalDataSystemExports.ResetRuntimeState(); KernelModuleRegistry.Reset(); var image = LoadImage(normalizedEbootPath, _executableRelativePath is null ? null : app0Root); VideoOutExports.ConfigureApplicationInfo(image.Title, image.TitleId, image.Version); KernelMemoryCompatExports.ConfigureApplicationInfo(image.TitleId); + AddcontEntitlements.ConfigureConceptId(image.ConceptId); SaveDataExports.ConfigureApplicationInfo(image.TitleId); SystemServiceExports.ConfigureApplicationInfo(image.TitleId, _systemLanguage); VideoOutExports.StartPresenter(); diff --git a/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs b/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs index 4bc4731e3..435fd61ff 100644 --- a/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs +++ b/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs @@ -353,6 +353,31 @@ private static uint EventWriteEndOfPipe(GpuCommandInterpreter interpreter, in Pa var control = payload[0]; var cachePolicy = (control >> 25) & 3u; var dataSource = (payload[2] >> 29) & 7u; + // PS4 titles (e.g. Signalis) emit a 32-bit CACHE_FLUSH_TS / BOTTOM_OF_PIPE_TS with a full cache + // write-back; it is mapped to the shared 32-bit write-back label here so AGC (PS5) streams keep + // their own validation. + var eventType = control & 0x3Fu; + var interruptSelector = (payload[2] >> 24) & 7u; + var eventWriteDestination = ((control >> 23) & 0x10u) | ((payload[2] >> 16) & 1u); + if (dataSource == 1 && eventWriteDestination == 0 && + ((control >> 8) & 7u) == 5 && ((control >> 12) & 0x3Fu) == 0x38 && + (eventType == 0x04 || eventType == 0x28 && interruptSelector is 0 or 3)) + { + interpreter.WriteEndOfPipe( + is64Bit: false, + cachePolicy: cachePolicy is 1 or 2 ? 0u : cachePolicy, + eventWriteDestination: 0, + eopEventType: 0x2F, + cacheAction: 0x38, + eventIndex: 6, + eventWriteSource: 2, + destination: payload[1] | ((ulong)(payload[2] & 0xFFFFu) << 32), + value: payload[3], + interruptSelector: interruptSelector, + interruptContextId: 0); + return 5; + } + var classicBottomOfPipe = (control & 0x3Fu) == 0x28 && ((control >> 8) & 7u) == 5 && (dataSource is 2 or 4 || dataSource == 1 && ((control >> 12) & 0x3Fu) == 0); diff --git a/src/SharpEmu.GnmMode/Loader/GnmSelfLoader.cs b/src/SharpEmu.GnmMode/Loader/GnmSelfLoader.cs index 1d2c0f145..856ffe1ff 100644 --- a/src/SharpEmu.GnmMode/Loader/GnmSelfLoader.cs +++ b/src/SharpEmu.GnmMode/Loader/GnmSelfLoader.cs @@ -140,10 +140,45 @@ private SelfImage LoadCore(ReadOnlySpan<byte> data, IVirtualMemory memory, IModu private static bool IsLoad(ProgramHeader header) => header.HeaderType is ProgramHeaderType.Load or ProgramHeaderType.SceRelro; + // Module arena reserved below 2 GiB right after the main image (0 when none). + private static ulong _moduleArenaStart; + private static ulong _moduleArenaEnd; + + // Presenter and driver host allocations race module loading for the low 2 GiB that PS4 + // module relocations need, so hold a block of it now and commit module images inside it. + private static void ReserveModuleArena(PhysicalVirtualMemory physical, ulong mainImageBase, ulong mainImageSize) + { + _moduleArenaStart = 0; + _moduleArenaEnd = 0; + const ulong limit = 0x80000000; + var start = checked(((Align(mainImageBase + mainImageSize) + 0x1FFFFF) & ~0x1FFFFFUL) + 0x200000); + foreach (var wanted in new[] { 0x40000000UL, 0x20000000UL, 0x10000000UL, 0x8000000UL }) + { + if (start >= limit) + break; + var arenaSize = Math.Min(wanted, limit - start); + if (!physical.TryReserveOwnedRange(start, arenaSize)) + continue; + _moduleArenaStart = start; + _moduleArenaEnd = start + arenaSize; + Console.Error.WriteLine($"[GNM][LOADER] Module arena reserved at 0x{start:X}-0x{_moduleArenaEnd:X}."); + return; + } + + Console.Error.WriteLine("[GNM][LOADER] Warning: could not reserve a module arena below 2 GiB."); + } + private static ulong AllocateImage(IVirtualMemory memory, ulong size, bool main) { - var address = main ? 0x400000UL : Math.Max(0x2000000UL, - memory.SnapshotRegions().Where(region => region.VirtualAddress < 0x40000000) + if (main) + { + _moduleArenaStart = 0; + _moduleArenaEnd = 0; + } + + var regionLimit = _moduleArenaEnd != 0 ? _moduleArenaEnd : 0x40000000UL; + var address = main ? 0x400000UL : Math.Max(Math.Max(0x2000000UL, _moduleArenaStart), + memory.SnapshotRegions().Where(region => region.VirtualAddress < regionLimit) .Select(region => Align(checked(region.VirtualAddress + region.MemorySize + 0x200000))).DefaultIfEmpty().Max()); if (memory is not PhysicalVirtualMemory physical || size == 0) return address; @@ -151,7 +186,10 @@ private static ulong AllocateImage(IVirtualMemory memory, ulong size, bool main) if (main) { if (physical.TryAllocateAtExact(address, size, true, out var allocated)) + { + ReserveModuleArena(physical, allocated, size); return allocated; + } // The Windows host can occupy 0x400000 before the PS4 image loads. // Keep the image below 2 GiB for relocations with 32-bit targets. @@ -160,14 +198,15 @@ private static ulong AllocateImage(IVirtualMemory memory, ulong size, bool main) if (!physical.TryAllocateAtExact(candidate, size, true, out allocated)) continue; Console.Error.WriteLine($"[GNM][LOADER] Main image relocated to free host address 0x{allocated:X}."); + ReserveModuleArena(physical, allocated, size); return allocated; } } else { - for (var attempt = 0; attempt < 256; attempt++, address += 0x200000) + for (var attempt = 0; attempt < 512; attempt++, address += 0x200000) { - if (address >= 0x40000000 || size > 0x40000000 - address) + if (address >= regionLimit || size > regionLimit - address) break; if (physical.TryAllocateAtExact(address, size, true, out var allocated)) return allocated; diff --git a/src/SharpEmu.GnmMode/Shaders/GcnShaderDecoder.cs b/src/SharpEmu.GnmMode/Shaders/GcnShaderDecoder.cs index 230286ab4..af674e466 100644 --- a/src/SharpEmu.GnmMode/Shaders/GcnShaderDecoder.cs +++ b/src/SharpEmu.GnmMode/Shaders/GcnShaderDecoder.cs @@ -616,7 +616,7 @@ private static int ImageAddressCount(string name, bool array) { 0 => "SNop", 1 => "SEndpgm", 2 => "SBranch", 4 => "SCbranchScc0", 5 => "SCbranchScc1", 6 => "SCbranchVccz", 7 => "SCbranchVccnz", 8 => "SCbranchExecz", 9 => "SCbranchExecnz", - 10 => "SBarrier", 12 => "SWaitcnt", 15 => "SSetprio", _ => "", + 10 => "SBarrier", 12 => "SWaitcnt", 15 => "SSetprio", 22 => "STtraceData", _ => "", }, }; diff --git a/src/SharpEmu.HLE/GuestThreadExecution.cs b/src/SharpEmu.HLE/GuestThreadExecution.cs index bb941a15c..b02be9611 100644 --- a/src/SharpEmu.HLE/GuestThreadExecution.cs +++ b/src/SharpEmu.HLE/GuestThreadExecution.cs @@ -174,6 +174,39 @@ bool TryRaiseGuestException( ulong handler, int exceptionType, out string? error); + + /// <summary> + /// Same as the signal overload, but lets the caller choose how the handler is + /// called. Schedulers that only know signal delivery refuse the other conventions. + /// </summary> + bool TryRaiseGuestException( + CpuContext callerContext, + ulong threadHandle, + ulong handler, + int exceptionType, + GuestExceptionHandlerArguments arguments, + out string? error) + { + if (arguments == GuestExceptionHandlerArguments.Signal) + { + return TryRaiseGuestException(callerContext, threadHandle, handler, exceptionType, out error); + } + + error = $"guest exception arguments {arguments} are not supported"; + return false; + } +} + +/// <summary> +/// Argument convention a raised guest exception handler is called with. +/// </summary> +public enum GuestExceptionHandlerArguments +{ + /// <summary>Signal handler: (exception type, mcontext pointer).</summary> + Signal, + + /// <summary>Unity GC suspend callback: (mcontext pointer, interrupted rsp).</summary> + UnityGcSuspend, } public readonly record struct GuestImportCallFrame( diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs b/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs index bda20831a..6d2271be8 100644 --- a/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs +++ b/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs @@ -32,7 +32,7 @@ public static partial class AmprExports private static readonly object _ammGate = new(); // Free auto pages and the mapped runs, both sorted by start. private static readonly List<(ulong Offset, ulong Length)> _ammFreePages = []; - private static readonly List<(ulong Address, ulong Length, ulong Offset)> _ammMappings = []; + private static readonly List<(ulong Address, ulong Length, ulong Offset, bool Auto)> _ammMappings = []; private static bool _ammAreaReserved; private static ulong _ammAddressSlot; @@ -43,6 +43,8 @@ private sealed class AmmCommand public ulong Address; public ulong Size; public int Protection; + // Set for MapDirect: the title names the direct memory offset instead of taking auto pages. + public ulong? DirectOffset; } [SysAbiExport( @@ -135,6 +137,58 @@ usage is not (AmmUsageDirect or AmmUsageAuto)) public static int AmmCommandBufferMap(CpuContext ctx) => AppendAmmCommand(ctx, unmap: false, ctx[CpuRegister.Rsi], ctx[CpuRegister.Rdx], unchecked((int)ctx[CpuRegister.R8])); + [SysAbiExport( + Nid = "8TBE+9XCZbI", + ExportName = "sceAmprAmmCommandBufferMapDirect", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmCommandBufferMapDirect(CpuContext ctx) => + AppendAmmMapDirect(ctx); + + [SysAbiExport( + Nid = "kOfZlhbVAkc", + ExportName = "sceAmprAmmCommandBufferMapDirectWithGpuMaskId", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmCommandBufferMapDirectWithGpuMaskId(CpuContext ctx) => + AppendAmmMapDirect(ctx); + + // The AMM buffer object is plain memory the title sets up with SetBuffer; only stale host state goes. + [SysAbiExport( + Nid = "EDq5bqCqYpA", + ExportName = "sceAmprAmmCommandBufferConstructor", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmCommandBufferConstructor(CpuContext ctx) + { + var commandBuffer = ctx[CpuRegister.Rdi]; + if (commandBuffer == 0) + { + return SetAmmResult(ctx, KernelEinval); + } + + RemoveCommandBufferState(commandBuffer); + TraceAmpr(ctx, "amm_ctor", commandBuffer, 0, 0); + return SetAmmResult(ctx, 0); + } + + [SysAbiExport( + Nid = "pvUFDOHilnE", + ExportName = "sceAmprAmmCommandBufferDestructor", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmCommandBufferDestructor(CpuContext ctx) + { + var commandBuffer = ctx[CpuRegister.Rdi]; + if (commandBuffer != 0) + { + RemoveCommandBufferState(commandBuffer); + } + + TraceAmpr(ctx, "amm_dtor", commandBuffer, 0, 0); + return SetAmmResult(ctx, 0); + } + [SysAbiExport( Nid = "M-VFI2DJWQA", ExportName = "sceAmprAmmCommandBufferUnmap", @@ -188,7 +242,19 @@ private static void ReportAmmFailure(ulong commandBuffer, int executionResult, u } } - private static int AppendAmmCommand(CpuContext ctx, bool unmap, ulong address, ulong size, int protection) + // MapDirect takes (buffer, va, direct memory offset, size, memory type, protection). + private static int AppendAmmMapDirect(CpuContext ctx) + { + var offset = ctx[CpuRegister.Rdx]; + if (offset % AmmPageSize != 0) + { + return SetAmmResult(ctx, KernelEinval); + } + + return AppendAmmCommand(ctx, unmap: false, ctx[CpuRegister.Rsi], ctx[CpuRegister.Rcx], unchecked((int)ctx[CpuRegister.R9]), offset); + } + + private static int AppendAmmCommand(CpuContext ctx, bool unmap, ulong address, ulong size, int protection, ulong? directOffset = null) { var commandBuffer = ctx[CpuRegister.Rdi]; if (commandBuffer == 0 || size == 0 || address % AmmPageSize != 0 || size % AmmPageSize != 0 || @@ -233,6 +299,7 @@ private static int AppendAmmCommand(CpuContext ctx, bool unmap, ulong address, u Address = address, Size = size, Protection = protection, + DirectOffset = directOffset, }); } @@ -256,9 +323,18 @@ private static int ExecuteAmmCommand(CpuContext ctx, AmmCommand command) return result; } - if (!TryTakeAmmPagesLocked(command.Size, out var runs)) + var auto = command.DirectOffset is null; + List<(ulong Offset, ulong Length)> runs; + if (auto) { - return KernelEagain; + if (!TryTakeAmmPagesLocked(command.Size, out runs)) + { + return KernelEagain; + } + } + else + { + runs = [(command.DirectOffset!.Value, command.Size)]; } var address = command.Address; @@ -278,7 +354,7 @@ private static int ExecuteAmmCommand(CpuContext ctx, AmmCommand command) : KernelEfault; if (result != 0) { - for (var j = i; j < runs.Count; j++) + for (var j = i; auto && j < runs.Count; j++) { ReleaseAmmPagesLocked(runs[j].Offset, runs[j].Length); } @@ -287,7 +363,7 @@ private static int ExecuteAmmCommand(CpuContext ctx, AmmCommand command) return result; } - InsertAmmMappingLocked(address, length, offset); + InsertAmmMappingLocked(address, length, offset, auto); address += length; } @@ -320,30 +396,34 @@ private static int ReleaseAmmRangeLocked(CpuContext ctx, ulong address, ulong si while (first < _ammMappings.Count && _ammMappings[first].Address < end) { - var (mappedAddress, length, offset) = _ammMappings[first]; + var (mappedAddress, length, offset, auto) = _ammMappings[first]; _ammMappings.RemoveAt(first); var mappedEnd = mappedAddress + length; var cutStart = Math.Max(mappedAddress, address); var cutEnd = Math.Min(mappedEnd, end); - ReleaseAmmPagesLocked(offset + (cutStart - mappedAddress), cutEnd - cutStart); + if (auto) + { + ReleaseAmmPagesLocked(offset + (cutStart - mappedAddress), cutEnd - cutStart); + } + if (mappedAddress < cutStart) { - _ammMappings.Insert(first++, (mappedAddress, cutStart - mappedAddress, offset)); + _ammMappings.Insert(first++, (mappedAddress, cutStart - mappedAddress, offset, auto)); } if (cutEnd < mappedEnd) { - _ammMappings.Insert(first++, (cutEnd, mappedEnd - cutEnd, offset + (cutEnd - mappedAddress))); + _ammMappings.Insert(first++, (cutEnd, mappedEnd - cutEnd, offset + (cutEnd - mappedAddress), auto)); } } return 0; } - private static void InsertAmmMappingLocked(ulong address, ulong length, ulong offset) + private static void InsertAmmMappingLocked(ulong address, ulong length, ulong offset, bool auto) { var index = _ammMappings.FindIndex(mapping => mapping.Address > address); - _ammMappings.Insert(index < 0 ? _ammMappings.Count : index, (address, length, offset)); + _ammMappings.Insert(index < 0 ? _ammMappings.Count : index, (address, length, offset, auto)); } private static bool TryTakeAmmPagesLocked(ulong size, out List<(ulong Offset, ulong Length)> runs) diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.cs b/src/SharpEmu.Libs/Ampr/AmprExports.cs index 777a09758..77a2ae857 100644 --- a/src/SharpEmu.Libs/Ampr/AmprExports.cs +++ b/src/SharpEmu.Libs/Ampr/AmprExports.cs @@ -273,6 +273,22 @@ public static int CommandBufferSetBuffer(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; } + // A buffer stays attached until ClearBuffer: setting it again is refused and keeps the + // queued commands. Death Stranding calls SetBuffer before every read it appends. + // Only a buffer this module attached counts: leftover bytes in an object no + // constructor cleared (the APR and AMM ones keep the header) must not read as busy. + if (!ctx.TryReadUInt64(commandBuffer + CommandBufferDataOffset, out var attached)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + if (attached != 0 && IsAttachedHere(commandBuffer, attached)) + { + TraceAmpr(ctx, "set_buffer_busy", commandBuffer, buffer, size); + ctx[CpuRegister.Rax] = unchecked((ulong)(long)KernelEbusy); + return KernelEbusy; + } + if (!WriteCommandBufferPointers(ctx, commandBuffer, buffer, size)) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; @@ -1336,6 +1352,19 @@ private static void RegisterCommandBufferAlias(ulong commandBuffer, ulong buffer } } + private static bool IsAttachedHere(ulong commandBuffer, ulong buffer) + { + if (!_commandBuffers.TryGetValue(commandBuffer, out var state)) + { + return false; + } + + lock (state) + { + return state.Buffer == buffer; + } + } + private static void RemoveCommandBufferState(ulong commandBuffer) { _commandBuffers.TryRemove(commandBuffer, out _); diff --git a/src/SharpEmu.Libs/AppContent/AppContentExports.cs b/src/SharpEmu.Libs/AppContent/AppContentExports.cs index 06a3759e4..ea4c83edf 100644 --- a/src/SharpEmu.Libs/AppContent/AppContentExports.cs +++ b/src/SharpEmu.Libs/AppContent/AppContentExports.cs @@ -3,7 +3,9 @@ using SharpEmu.HLE; using SharpEmu.Libs.Kernel; +using SharpEmu.Libs.Np; using System.Buffers.Binary; +using System.Collections.Concurrent; using System.Text; using System.Text.Json; @@ -15,11 +17,34 @@ public static class AppContentExports private const int AppContentErrorParameter = unchecked((int)0x80D90002); private const int AppContentErrorDrmNoEntitlement = unchecked((int)0x80D90007); private const int MountPointSize = 16; + private const int EntitlementLabelSize = 17; private const ulong BootParamAttrOffset = 4; private const string Temp0MountPoint = "/temp0"; private const uint AppParamSkuFlag = 0; private const int AppParamSkuFlagFull = 3; + // Each add-on package gets its own guest mount point, as the SDK does; mounting the + // same label again returns the mount point it already has. + private static readonly ConcurrentDictionary<string, string> AddcontMounts = new(StringComparer.Ordinal); + private static readonly object AddcontMountGate = new(); + private static int _addcontMountIndex = -1; + + public static void ResetRuntimeState() + { + lock (AddcontMountGate) + { + foreach (var mountPoint in AddcontMounts.Values) + { + KernelMemoryCompatExports.UnregisterGuestPathMount(mountPoint); + } + + AddcontMounts.Clear(); + Volatile.Write(ref _addcontMountIndex, -1); + } + + AddcontEntitlements.ResetRuntimeState(); + } + [SysAbiExport( Nid = "R9lA82OraNs", ExportName = "sceAppContentInitialize", @@ -116,13 +141,58 @@ public static int AppContentAddcontMount(CpuContext ctx) return ctx.SetReturn(AppContentErrorParameter); } - Span<byte> emptyMountPoint = stackalloc byte[MountPointSize]; - if (!ctx.Memory.TryWrite(mountPointAddress, emptyMountPoint)) + Span<byte> labelBytes = stackalloc byte[EntitlementLabelSize]; + if (!ctx.Memory.TryRead(entitlementLabelAddress, labelBytes)) + { + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + var label = ReadLabel(labelBytes); + if (!AddcontEntitlements.IsValidLabel(label)) + { + TraceAppContent("addcont_mount rejected an invalid label"); + return ctx.SetReturn(AppContentErrorParameter); + } + + TraceAppContent($"addcont_mount label='{label}'"); + + // Only an add-on package present on disk is mounted; any other label is refused as + // before, so titles without installed add-ons keep their usual behaviour. + if (!AddcontEntitlements.TryResolvePackageRoot(label, out var packageRoot)) + { + Span<byte> emptyMountPoint = stackalloc byte[MountPointSize]; + emptyMountPoint.Clear(); + if (!ctx.Memory.TryWrite(mountPointAddress, emptyMountPoint)) + { + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + return ctx.SetReturn(AppContentErrorDrmNoEntitlement); + } + + // Each package gets its own guest mount point backed by its host folder. + if (!AddcontMounts.TryGetValue(label, out var mountPoint)) + { + lock (AddcontMountGate) + { + if (!AddcontMounts.TryGetValue(label, out mountPoint)) + { + mountPoint = $"/addcont{Interlocked.Increment(ref _addcontMountIndex)}"; + KernelMemoryCompatExports.RegisterGuestPathMount(mountPoint, packageRoot); + AddcontMounts[label] = mountPoint; + } + } + } + + Span<byte> mountPointBytes = stackalloc byte[MountPointSize]; + mountPointBytes.Clear(); + Encoding.ASCII.GetBytes(mountPoint).CopyTo(mountPointBytes); + if (!ctx.Memory.TryWrite(mountPointAddress, mountPointBytes)) { return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } - return ctx.SetReturn(AppContentErrorDrmNoEntitlement); + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK); } [SysAbiExport( @@ -257,6 +327,19 @@ private static bool TryReadUserDefinedParam(uint paramId, out int value) } } + private static string ReadLabel(ReadOnlySpan<byte> bytes) + { + var length = 0; + while (length < bytes.Length && bytes[length] != 0) + { + length++; + } + + return length == 0 + ? string.Empty + : Encoding.ASCII.GetString(bytes[..length]); + } + private static void TraceAppContent(string message) { if (!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_APP_CONTENT"), "1", StringComparison.Ordinal)) diff --git a/src/SharpEmu.Libs/AvPlayer/AvPlayerExports.cs b/src/SharpEmu.Libs/AvPlayer/AvPlayerExports.cs index 53e1c75bd..30ca3f82c 100644 --- a/src/SharpEmu.Libs/AvPlayer/AvPlayerExports.cs +++ b/src/SharpEmu.Libs/AvPlayer/AvPlayerExports.cs @@ -930,6 +930,29 @@ player.AudioDecoderOutput is null && return ValidatePlayer(ctx); } + [SysAbiExport( + Nid = "BOVKAzRmuTQ", + ExportName = "sceAvPlayerDisableStream", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceAvPlayer")] + public static int AvPlayerDisableStream(CpuContext ctx) + { + TraceOnce( + $"disable_stream_{ctx[CpuRegister.Rsi]}", + $"disable_stream index={ctx[CpuRegister.Rsi]}"); + lock (StateGate) + { + if (Players.TryGetValue(ctx[CpuRegister.Rdi], out var player) && + player.AudioDecoderOutput is null && + ctx[CpuRegister.Rsi] < (ulong)player.Streams.Length && + player.Streams[(int)ctx[CpuRegister.Rsi]].Index == player.AudioStreamIndex) + { + player.AudioStreamIndex = -1; + } + } + return ValidatePlayer(ctx); + } + [SysAbiExport( Nid = "k-q+xOxdc3E", ExportName = "sceAvPlayerSetAvSyncMode", @@ -1179,7 +1202,8 @@ public static int AvPlayerCurrentTime(CpuContext ctx) return SetReturn(ctx, InvalidParameters); } - var milliseconds = player.AvSyncMode == AvSyncModeDefault && player.HasAudio + var milliseconds = player.AvSyncMode == AvSyncModeDefault && + AudioClockIsMaster(player) ? player.StartTimeMilliseconds + DefaultSyncElapsedMilliseconds( player.NextAudioFrameIndex, SecondsSinceAudioEnded(player.AudioEndedSeconds, player.PlaybackClock.Elapsed.TotalSeconds)) @@ -1811,8 +1835,10 @@ private static int GetVideoData(CpuContext ctx, bool extended) var expectedFrame = player.NextFrameIndex; if (player.AvSyncMode == AvSyncModeDefault) { + // The default sync follows the delivered audio only when the game consumes + // it (see AudioClockIsMaster); otherwise the video runs on the playback clock. expectedFrame = CalculateExpectedDefaultSyncVideoFrame( - player.HasAudio, + AudioClockIsMaster(player), player.NextAudioFrameIndex, player.PlaybackClock.Elapsed.TotalSeconds, fps, @@ -2806,6 +2832,14 @@ internal static int NormalizeOutputVideoFrameBufferCount(int requested) => ? requested : DefaultFrameBufferCount; + // Street Fighter 6 enables the video stream alone and plays the movie audio through its own + // audio system: following the never-consumed audio track stalled the video on its first frame + // forever. The audio is the master clock only once the game enabled the audio stream or pulled + // audio data (autoStart titles never call sceAvPlayerEnableStream; the first + // sceAvPlayerGetAudioData opens the decoder). Both fields are cleared when the player resets. + private static bool AudioClockIsMaster(PlayerState player) => + player.HasAudio && (player.AudioStreamIndex >= 0 || player.AudioDecoderOutput is not null); + internal static bool IsValidAvSyncMode(uint mode) => mode is AvSyncModeDefault or AvSyncModeNone; diff --git a/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs b/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs index 058eec343..c765a6292 100644 --- a/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs +++ b/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs @@ -368,6 +368,13 @@ public ulong FlushDeferred(ReadOnlySpan<RecordingBuffer> trailing) { tick = _timeline.ReserveTick(); } + + if (_completed is { } completed) + { + var reserved = tick; + _priority.Enqueue(new TickWork(() => completed(reserved), reserved)); + Monitor.Pulse(_operationLock); + } } _deferredBuffers.Add(_command.Buffer); @@ -420,7 +427,6 @@ public void SubmitDeferred() if (submitted) { NoteDeferredSubmitted(System.Diagnostics.Stopwatch.GetTimestamp()); - EnqueueDeferredCompletions(); } } @@ -433,21 +439,6 @@ public void SubmitDeferred() _deferredTicks.Clear(); } - private void EnqueueDeferredCompletions() - { - if (_completed is not { } completed) - { - return; - } - - foreach (var tick in _deferredTicks) - { - _priority.Enqueue(new TickWork(() => completed(tick), tick)); - } - - Monitor.Pulse(_operationLock); - } - public void EnsureSubmitted(ulong tick) { if (_deferredTicks.Count != 0 && tick >= _deferredTicks[0]) @@ -829,8 +820,6 @@ public ulong Submit(SubmitBundle? bundle = null, ReadOnlySpan<RecordingBuffer> t _submitsFolded.Increment(); NoteDeferredSubmitted(now); } - - EnqueueDeferredCompletions(); } if (submitted && _completed is { } completed) diff --git a/src/SharpEmu.Libs/Kernel/KernelExceptionCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelExceptionCompatExports.cs index 4008f7b9d..23c23a805 100644 --- a/src/SharpEmu.Libs/Kernel/KernelExceptionCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelExceptionCompatExports.cs @@ -11,6 +11,83 @@ public static class KernelExceptionCompatExports private static readonly Dictionary<int, ulong> _installedHandlers = new(); private static readonly object _gate = new(); + private const int UnixSearchError = unchecked((int)0x80020003); + + private static ulong _unityGcSuspendCallback; + + // Unity's libkernel_unity GC hook: the il2cpp collector registers the callback that + // arch_raise_user later runs on every mutator thread to stop the world. The callback + // is only recorded here; it is never called at registration time. + [SysAbiExport( + Nid = "XAKDgxcra6k", + ExportName = "arch_init_gc", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libkernel_unity")] + public static int ArchInitGc(CpuContext ctx) + { + Volatile.Write(ref _unityGcSuspendCallback, ctx[CpuRegister.Rdi]); + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + // Interrupts a guest thread and runs the registered GC callback on it with the + // interrupted register state. The collector counts every thread this returns success + // for and then waits for its acknowledgement, so any case where the callback cannot + // be delivered must report ESRCH: the collector skips such a thread instead of + // waiting on it forever. + [SysAbiExport( + Nid = "J3edELK4FvM", + ExportName = "arch_raise_user", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libkernel_unity")] + public static int ArchRaiseUser(CpuContext ctx) + { + var targetThread = ctx[CpuRegister.Rdi]; + var callback = Volatile.Read(ref _unityGcSuspendCallback); + if (targetThread == 0 || callback == 0) + { + return SetRawReturn(ctx, UnixSearchError); + } + + if (string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_IGNORE_GUEST_EXCEPTIONS"), + "1", + StringComparison.Ordinal)) + { + return SetRawReturn(ctx, UnixSearchError); + } + + var scheduler = GuestThreadExecution.Scheduler; + string? error = null; + if (scheduler is null || + !scheduler.TryRaiseGuestException( + ctx, + targetThread, + callback, + exceptionType: 0, + GuestExceptionHandlerArguments.UnityGcSuspend, + out error)) + { + Console.Error.WriteLine( + $"[LOADER][WARN] arch_raise_user delivery failed: " + + $"target=0x{targetThread:X16} callback=0x{callback:X16} " + + $"error={error ?? "scheduler unavailable"}"); + return SetRawReturn(ctx, UnixSearchError); + } + + if (string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_LOG_GUEST_EXCEPTIONS"), + "1", + StringComparison.Ordinal)) + { + Console.Error.WriteLine( + $"[LOADER][TRACE] guest_exception.arch_raise_user " + + $"target=0x{targetThread:X16} callback=0x{callback:X16}"); + } + + return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_OK); + } + [SysAbiExport( Nid = "WkwEd3N7w0Y", ExportName = "sceKernelInstallExceptionHandler", @@ -127,9 +204,11 @@ public static int RaiseException(CpuContext ctx) return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_OK); } - private static int SetReturn(CpuContext ctx, OrbisGen2Result result) + private static int SetReturn(CpuContext ctx, OrbisGen2Result result) => + SetRawReturn(ctx, (int)result); + + private static int SetRawReturn(CpuContext ctx, int value) { - var value = (int)result; ctx[CpuRegister.Rax] = unchecked((ulong)value); return value; } diff --git a/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs b/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs index 4fa781bac..08c692650 100644 --- a/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelFileExtendedExports.cs @@ -122,6 +122,78 @@ private static int KernelPreadCore(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + // preadv(fd, iov, iovcnt, offset): fills each { base, length } entry in turn from one positional read. + [SysAbiExport(Nid = "yTj62I7kw4s", ExportName = "sceKernelPreadv", + Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libKernel")] + public static int KernelPreadv(CpuContext ctx) + { + const int MaxIov = 1024; + var fd = unchecked((int)ctx[CpuRegister.Rdi]); + var iov = ctx[CpuRegister.Rsi]; + var count = unchecked((int)ctx[CpuRegister.Rdx]); + var offset = unchecked((long)ctx[CpuRegister.Rcx]); + if (count < 0 || count > MaxIov || (count > 0 && iov == 0) || offset < 0) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + var stream = GetOpenFile(fd); + if (stream is null) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; + } + + var entries = new (ulong Base, int Length)[count]; + long total = 0; + for (var i = 0; i < count; i++) + { + var entry = iov + (ulong)i * 16; + if (!ctx.TryReadUInt64(entry, out var entryBase) || !ctx.TryReadUInt64(entry + 8, out var entryLength)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + if (entryLength > int.MaxValue || total + (long)entryLength > int.MaxValue || (entryLength != 0 && entryBase == 0)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + total += (long)entryLength; + entries[i] = (entryBase, (int)entryLength); + } + + var buffer = GC.AllocateUninitializedArray<byte>((int)total); + int read; + try + { + read = total == 0 ? 0 : ReadOpenFileAt(stream, buffer, offset); + } + catch (IOException) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + var copied = 0; + foreach (var (entryBase, length) in entries) + { + var part = Math.Min(length, read - copied); + if (part <= 0) + { + break; + } + + if (!ctx.Memory.TryWrite(entryBase, buffer.AsSpan(copied, part))) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + copied += part; + } + + ctx[CpuRegister.Rax] = unchecked((ulong)read); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + [SysAbiExport(Nid = "C2kJ-byS5rM", ExportName = "pwrite", Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libKernel")] public static int PosixPwrite(CpuContext ctx) => KernelPwriteCore(ctx); @@ -172,6 +244,66 @@ private static int KernelPwriteCore(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + // pwritev(fd, iov, iovcnt, offset): writes the { base, length } entries back to back at offset. + [SysAbiExport(Nid = "mBd4AfLP+u8", ExportName = "sceKernelPwritev", + Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libKernel")] + public static int KernelPwritev(CpuContext ctx) + { + const int MaxIov = 1024; + var fd = unchecked((int)ctx[CpuRegister.Rdi]); + var iov = ctx[CpuRegister.Rsi]; + var count = unchecked((int)ctx[CpuRegister.Rdx]); + var offset = unchecked((long)ctx[CpuRegister.Rcx]); + if (count < 0 || count > MaxIov || (count > 0 && iov == 0) || offset < 0) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + var stream = GetOpenFile(fd); + if (stream is null) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; + } + + var payload = new MemoryStream(); + for (var i = 0; i < count; i++) + { + var entry = iov + (ulong)i * 16; + if (!ctx.TryReadUInt64(entry, out var entryBase) || !ctx.TryReadUInt64(entry + 8, out var entryLength)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + if (entryLength > int.MaxValue || payload.Length + (long)entryLength > int.MaxValue || (entryLength != 0 && entryBase == 0)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + var part = GC.AllocateUninitializedArray<byte>((int)entryLength); + if (!ctx.Memory.TryRead(entryBase, part)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + payload.Write(part); + } + + if (payload.Length != 0) + { + try + { + WriteOpenFileAt(stream, payload.GetBuffer().AsSpan(0, (int)payload.Length), offset); + } + catch (IOException) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + } + + ctx[CpuRegister.Rax] = unchecked((ulong)payload.Length); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + // ---- Synchronization ---- [SysAbiExport(Nid = "juWbTNM+8hw", ExportName = "fsync", diff --git a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.Mmap.cs b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.Mmap.cs index 139dbc365..2ef031d78 100644 --- a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.Mmap.cs +++ b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.Mmap.cs @@ -7,37 +7,159 @@ namespace SharpEmu.Libs.Kernel; public static partial class KernelMemoryCompatExports { + private const int MemoryBadDescriptor = unchecked((int)0x80020009); + private const int MemoryNoDevice = unchecked((int)0x80020013); + private const uint MmapShared = 0x1; + private const uint MmapAnonymous = 0x1000; + private static int _sharedWritableFileMapWarned; + [SysAbiExport(Nid = "BPE9s9vQQXo", ExportName = "mmap", Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libKernel")] public static int PosixMmap(CpuContext ctx) { - var requested = ctx[CpuRegister.Rdi]; - var length = ctx[CpuRegister.Rsi]; - var protection = (int)ctx[CpuRegister.Rdx]; - var flags = (uint)ctx[CpuRegister.Rcx]; - var descriptor = (int)ctx[CpuRegister.R8]; - var offset = ctx[CpuRegister.R9]; - if (length == 0 || length > ulong.MaxValue - (OrbisPageSize - 1) || - (flags & 3) != 2 || (flags & 0x1000) == 0 || (flags & ~0xFF001012u) != 0 || - descriptor != -1 || offset != 0 || !TryDecodeMappedProtection(protection, out var mode)) - return PosixFailure(ctx, MemoryInvalidArgument, Einval); + var result = MmapCore(ctx, ctx[CpuRegister.Rdi], ctx[CpuRegister.Rsi], (int)ctx[CpuRegister.Rdx], + (uint)ctx[CpuRegister.Rcx], (int)ctx[CpuRegister.R8], ctx[CpuRegister.R9], out var address); + if (result != 0) + return PosixFailure(ctx, result, result & 0xFFFF); + ctx[CpuRegister.Rax] = address; + return 0; + } + + // sceKernelMmap(addr, len, prot, flags, fd, offset, void** res): same mapping as mmap(2), + // but returns an Orbis error code and stores the address through the 7th (stack) argument. + [SysAbiExport(Nid = "PGhQHd-dzv8", ExportName = "sceKernelMmap", Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libKernel")] + public static int KernelMmap(CpuContext ctx) + { + if (!ctx.TryReadUInt64(ctx[CpuRegister.Rsp] + sizeof(ulong), out var resultAddress) || resultAddress == 0) + return MemoryInvalidArgument; + var result = MmapCore(ctx, ctx[CpuRegister.Rdi], ctx[CpuRegister.Rsi], (int)ctx[CpuRegister.Rdx], + (uint)ctx[CpuRegister.Rcx], (int)ctx[CpuRegister.R8], ctx[CpuRegister.R9], out var address); + if (result != 0) + return result; + return ctx.TryWriteUInt64(resultAddress, address) ? 0 : MemoryFault; + } + + private static int MmapCore(CpuContext ctx, ulong requested, ulong length, int protection, uint flags, + int descriptor, ulong offset, out ulong address) + { + address = 0; + var anonymous = (flags & MmapAnonymous) != 0; + // Anonymous mappings stay private with fd -1; file mappings (e.g. il2cpp mapping + // global-metadata.dat; without it every class/method lookup returns null) may be shared. + var validFlags = anonymous + ? (flags & 3) == 2 && (flags & ~0xFF001012u) == 0 && descriptor == -1 && offset == 0 + : ((flags & 3) is 1 or 2) && (flags & ~0xFF0E0013u) == 0 && descriptor >= 0 && + IsAligned(offset, OrbisPageSize); + if (length == 0 || length > ulong.MaxValue - (OrbisPageSize - 1) || !validFlags || + !TryDecodeMappedProtection(protection, out var mode)) + return MemoryInvalidArgument; length = (length + OrbisPageSize - 1) & ~(OrbisPageSize - 1); var shift = flags >> 24; if (shift != 0 && shift is < 14 or > 31) - return PosixFailure(ctx, MemoryInvalidArgument, Einval); + return MemoryInvalidArgument; var alignment = shift == 0 ? OrbisPageSize : 1UL << (int)shift; if ((flags & OrbisKernelMapFixed) != 0 && (requested == 0 || !IsAligned(requested, alignment) || requested > ulong.MaxValue - length)) - return PosixFailure(ctx, MemoryInvalidArgument, Einval); - var address = 0UL; + return MemoryInvalidArgument; + + byte[]? fileBytes = null; + if (!anonymous) + { + var read = TryReadMappedFileBytes(descriptor, offset, length, out fileBytes); + if (read != 0) + return read; + if ((flags & MmapShared) != 0 && (mode & GuestPageProtection.Write) != 0 && + Interlocked.Exchange(ref _sharedWritableFileMapWarned, 1) == 0) + Console.Error.WriteLine( + "[LOADER][WARN] mmap: shared writable file mappings are not written back to the file"); + } + + var mapped = 0UL; var result = RunMappingTransaction(() => { lock (_memoryGate) - return MapFlexibleRangeLocked(ctx, requested, length, protection, - flags & ~0x1002u, alignment, mode, out address); + { + // A file mapping is filled while writable, then switched to the requested protection. + var mapResult = MapFlexibleRangeLocked(ctx, requested, length, + anonymous ? protection : 3, flags & ~0x1003u, alignment, + anonymous ? mode : GuestPageProtection.Read | GuestPageProtection.Write, out mapped); + if (mapResult != 0 || anonymous) + return mapResult; + if (fileBytes!.Length > 0 && !ctx.Memory.TryWrite(mapped, fileBytes)) + return MemoryFault; + return protection == 3 ? 0 : ProtectMappedRange(ctx, mapped, length, protection); + } }); - if (result != 0) - return PosixFailure(ctx, result, result & 0xFFFF); - ctx[CpuRegister.Rax] = address; + if (result == 0) + address = mapped; + return result; + } + + // Reads min(length, fileLength - offset) bytes without touching the descriptor's own position. + private static int TryReadMappedFileBytes(int descriptor, ulong offset, ulong length, out byte[]? bytes) + { + bytes = null; + Stream? stream; + lock (_fdGate) + { + if (!_openFiles.TryGetValue(descriptor, out stream)) + return _openDirectories.ContainsKey(descriptor) || _randomDeviceDescriptors.Contains(descriptor) + ? MemoryNoDevice + : MemoryBadDescriptor; + } + try + { + if (stream is FileStream file) + { + // Separate handle: the guest's descriptor keeps its position. + using var reader = new FileStream(file.Name, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete); + return ReadMappedBytes(reader, offset, length, out bytes); + } + if (!stream.CanSeek || !stream.CanRead) + return MemoryNoDevice; + lock (stream) + { + var saved = stream.Position; + try { return ReadMappedBytes(stream, offset, length, out bytes); } + finally { stream.Position = saved; } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ObjectDisposedException) + { + return MemoryBadDescriptor; + } + } + + private static int ReadMappedBytes(Stream stream, ulong offset, ulong length, out byte[]? bytes) + { + var fileLength = (ulong)stream.Length; + var count = offset >= fileLength ? 0UL : Math.Min(length, fileLength - offset); + bytes = new byte[count]; + if (count == 0) + return 0; + stream.Position = (long)offset; + var total = 0; + while (total < bytes.Length) + { + var read = stream.Read(bytes, total, bytes.Length - total); + if (read <= 0) + break; + total += read; + } + if (total < bytes.Length) + Array.Resize(ref bytes, total); return 0; } + + internal static void RegisterOpenFileForTests(int descriptor, Stream stream) + { + lock (_fdGate) + _openFiles[descriptor] = stream; + } + + internal static void UnregisterOpenFileForTests(int descriptor) + { + lock (_fdGate) + _openFiles.Remove(descriptor); + } } diff --git a/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs index 63041c6c2..04ca0357a 100644 --- a/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelPthreadCompatExports.cs @@ -665,6 +665,34 @@ public static int PthreadCondattrDestroy(CpuContext ctx) public static int PosixPthreadCondattrDestroy(CpuContext ctx) => PthreadCondattrDestroyCore(ctx, ctx[CpuRegister.Rdi], posixErrors: true); + // Per guest thread; guest threads run 1:1 on host threads. 0 = PTHREAD_CANCEL_ENABLE (default). + [ThreadStatic] + private static int _cancelState; + + [SysAbiExport( + Nid = "lZzFeSxPl08", + ExportName = "pthread_setcancelstate", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libKernel")] + public static int PosixPthreadSetcancelstate(CpuContext ctx) + { + var state = unchecked((int)ctx[CpuRegister.Rdi]); + var oldStateAddress = ctx[CpuRegister.Rsi]; + if (state is not (0 or 1)) + { + return PosixInvalidArgument; + } + + var previous = _cancelState; + if (oldStateAddress != 0 && !TryWriteUInt32(ctx, oldStateAddress, unchecked((uint)previous))) + { + return PosixBadAddress; + } + + _cancelState = state; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + [SysAbiExport( Nid = "cTDYxTUNPhM", ExportName = "pthread_condattr_getclock", diff --git a/src/SharpEmu.Libs/Np/AddcontEntitlements.cs b/src/SharpEmu.Libs/Np/AddcontEntitlements.cs new file mode 100644 index 000000000..de3713f16 --- /dev/null +++ b/src/SharpEmu.Libs/Np/AddcontEntitlements.cs @@ -0,0 +1,240 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Frozen; +using System.Text.Json; +using SharpEmu.Libs.Kernel; + +namespace SharpEmu.Libs.Np; + +// The add-on (DLC) entitlements a title owns offline. Real hardware reads them from +// the signed-in PSN account. No file in a game dump lists them: Ghost of Yotei's labels +// only exist inside its eboot, and GTA V and Street Fighter 6 enumerate them at run time +// through sceNpEntitlementAccessGetAddcontEntitlementInfoList. Offline the emulator +// therefore derives them from editable data instead of hard-coding a global list: +// +// - user/entitlements.json maps a title id (or a concept id) to its owned labels, for +// example { "PPSA04264": ["85y-je", "5d5c48", "_mtqu6"] }. A title id entry wins over a +// concept id entry. The built-in defaults below only serve as the fallback for a +// missing entry, so they can be changed per machine without rebuilding. +// - The built-in defaults are keyed by the PS5 concept id from param.json, not by title +// id: a title id is per region, while every regional release of a game (for example +// PPSA04264 and PPSA04263 for GTA V) shares one concept id and so matches the same row. +// - An addcont directory (SHARPEMU_ADDCONT_DIR, else <app0>/../addcont): every +// subfolder is one installed add-on package and its folder name is its label. +public static class AddcontEntitlements +{ + public readonly record struct Entitlement(string Label, uint PackageType, uint DownloadStatus); + + // package_type 3 = PSAL (license-style add-on); download_status 4 = INSTALLED. + private const uint PackageTypePsal = 3; + private const uint DownloadStatusInstalled = 4; + private const int EntitlementLabelLength = 16; + private const string EntitlementsFileName = "entitlements.json"; + + // Built-in defaults for the games the emulator was tested with, keyed by concept id: + // GTA V Enhanced (201930) gates Story Mode on its three labels and Ghost of Yotei + // (10003923) checks its application and base game entitlements before it creates the + // frontend. A user/entitlements.json entry overrides them. + private static readonly Dictionary<string, string[]> DefaultLabels = new() + { + ["201930"] = ["85y-je", "5d5c48", "_mtqu6"], + ["10003923"] = ["GHOST2APP0000000", "GHOST2BASE000000"], + }; + + // The concept id of the running title (null for a PS4 title or a missing param.json). + private static string? _conceptId; + + // One immutable snapshot per (title, concept id), swapped as a whole so a racing + // reader never pairs a title with another title's labels. + private sealed class Snapshot(string title, string? conceptId, Entitlement[] owned) + { + public string Title { get; } = title; + public string? ConceptId { get; } = conceptId; + public Entitlement[] Owned { get; } = owned; + public FrozenDictionary<string, Entitlement> ByLabel { get; } = + owned.ToFrozenDictionary(entitlement => entitlement.Label, StringComparer.Ordinal); + } + + private static Snapshot? _snapshot; + + // Test seams: the folders the configuration file and the packages are read from. + internal static string? DataRootOverride { get; set; } + internal static string? AddcontRootOverride { get; set; } + + internal static void ResetRuntimeState() + { + Volatile.Write(ref _conceptId, null); + Volatile.Write(ref _snapshot, null); + } + + // Records the concept id of the loaded title; the cached snapshot rebuilds when it changes. + public static void ConfigureConceptId(string? conceptId) => + Volatile.Write(ref _conceptId, string.IsNullOrWhiteSpace(conceptId) ? null : conceptId); + + // Entitlement labels are at most 16 characters of letters, digits, '-' and '_'. The + // guest chooses the label passed to the mount call, so nothing else may reach a path. + public static bool IsValidLabel(string? label) + { + if (string.IsNullOrEmpty(label) || label.Length > EntitlementLabelLength) + { + return false; + } + + foreach (var character in label) + { + if (!(char.IsAsciiLetterOrDigit(character) || character is '-' or '_')) + { + return false; + } + } + + return true; + } + + // The labels the running title owns, merged from the configuration file, the + // built-in defaults and the installed addcont packages. Cached per title and concept id. + public static IReadOnlyList<Entitlement> Owned() => GetSnapshot().Owned; + + public static bool Owns(string label) => GetSnapshot().ByLabel.ContainsKey(label); + + public static bool TryGet(string label, out Entitlement entitlement) => + GetSnapshot().ByLabel.TryGetValue(label, out entitlement); + + private static Snapshot GetSnapshot() + { + var title = KernelMemoryCompatExports.ApplicationTitleId; + var conceptId = Volatile.Read(ref _conceptId); + var current = Volatile.Read(ref _snapshot); + if (current is not null && + string.Equals(current.Title, title, StringComparison.Ordinal) && + string.Equals(current.ConceptId, conceptId, StringComparison.Ordinal)) + { + return current; + } + + var labels = new List<string>(); + if (TryLoadConfiguredLabels(title, conceptId, out var configured)) + { + labels.AddRange(configured); + } + else if (conceptId is not null && DefaultLabels.TryGetValue(conceptId, out var defaults)) + { + labels.AddRange(defaults); + } + + labels.AddRange(EnumerateAddcontLabels()); + + var owned = labels + .Select(NormalizeLabel) + .Where(IsValidLabel) + .Distinct(StringComparer.Ordinal) + .Select(label => new Entitlement(label, PackageTypePsal, DownloadStatusInstalled)) + .ToArray(); + + var snapshot = new Snapshot(title, conceptId, owned); + Volatile.Write(ref _snapshot, snapshot); + return snapshot; + } + + // The host folder add-on packages are read from: an explicit variable, else the + // addcont folder next to the game image (the PS5 dump layout). + public static string AddcontRoot() + { + if (AddcontRootOverride is not null) + { + return AddcontRootOverride; + } + + var configured = Environment.GetEnvironmentVariable("SHARPEMU_ADDCONT_DIR"); + if (!string.IsNullOrWhiteSpace(configured)) + { + return Path.GetFullPath(configured); + } + + var app0Root = Environment.GetEnvironmentVariable("SHARPEMU_APP0_DIR"); + return string.IsNullOrWhiteSpace(app0Root) + ? Path.GetFullPath("addcont") + : Path.GetFullPath(Path.Combine(app0Root, "..", "addcont")); + } + + // The host folder of one installed add-on package, when it exists. + public static bool TryResolvePackageRoot(string label, out string hostRoot) + { + hostRoot = string.Empty; + if (!IsValidLabel(label)) + { + return false; + } + + hostRoot = Path.Combine(AddcontRoot(), label); + return Directory.Exists(hostRoot); + } + + private static string[] EnumerateAddcontLabels() + { + var root = AddcontRoot(); + if (!Directory.Exists(root)) + { + return []; + } + + try + { + return Directory.GetDirectories(root) + .Select(Path.GetFileName) + .Where(IsValidLabel) + .Select(name => name!) + .ToArray(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return []; + } + } + + private static bool TryLoadConfiguredLabels(string title, string? conceptId, out string[] labels) + { + labels = []; + var path = Path.Combine(DataRootOverride ?? SharpEmuPaths.DataRoot, "user", EntitlementsFileName); + if (!File.Exists(path)) + { + return false; + } + + try + { + using var stream = File.OpenRead(path); + using var document = JsonDocument.Parse(stream); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return false; + } + + // The title id entry wins over the concept id entry. + if (!(root.TryGetProperty(title, out var element) && element.ValueKind == JsonValueKind.Array) && + !(conceptId is not null && root.TryGetProperty(conceptId, out element) && + element.ValueKind == JsonValueKind.Array)) + { + return false; + } + + labels = element.EnumerateArray() + .Where(item => item.ValueKind == JsonValueKind.String) + .Select(item => item.GetString()) + .Where(label => !string.IsNullOrWhiteSpace(label)) + .Select(label => label!) + .ToArray(); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException) + { + return false; + } + } + + // An entitlement label clamped to the field length the guest APIs read and write. + public static string NormalizeLabel(string label) => + label.Length > EntitlementLabelLength ? label[..EntitlementLabelLength] : label; +} diff --git a/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs b/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs index d716a61ec..b41c66101 100644 --- a/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs +++ b/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs @@ -4,6 +4,7 @@ using System.Buffers.Binary; using System.Text; using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; namespace SharpEmu.Libs.Np; @@ -17,8 +18,6 @@ public static class NpEntitlementAccessExports // libSceNpEntitlementAccess package / download codes observed on Prospero. // package_type 3 = PSAL (license-style add-on); download_status 4 = INSTALLED. - private const uint PackageTypePsal = 3; - private const uint DownloadStatusInstalled = 4; private const uint SkuFlagFull = 3; private const int NpEntitlementAccessErrorParameter = unchecked((int)0x817D0002); @@ -32,26 +31,9 @@ public static class NpEntitlementAccessExports private static readonly System.Collections.Concurrent.ConcurrentDictionary<long, int> Requests = new(); private static long _nextRequestId; - // Offline entitlements queried by titles through NpEntitlementAccess. - // GTA V Enhanced (PPSA04264) gates Story Mode on these three labels; without - // them the frontend offers "Buy GTAV Story Mode" despite a full dump. - // Ghost of Yotei (PPSA26344) separately checks its application and base - // game entitlements before it creates the frontend. These represent the - // locally installed main package only; optional editions and add-ons remain - // unowned. - private static readonly AddcontEntitlement[] OwnedAddcontEntitlements = - [ - new("85y-je", PackageTypePsal, DownloadStatusInstalled), - new("5d5c48", PackageTypePsal, DownloadStatusInstalled), - new("_mtqu6", PackageTypePsal, DownloadStatusInstalled), - new("GHOST2APP0000000", PackageTypePsal, DownloadStatusInstalled), - new("GHOST2BASE000000", PackageTypePsal, DownloadStatusInstalled), - ]; - - private readonly record struct AddcontEntitlement( - string Label, - uint PackageType, - uint DownloadStatus); + // The owned labels of the running title, from AddcontEntitlements: the + // user/entitlements.json configuration (or the built-in defaults), plus the + // addcont packages installed next to the game image. [SysAbiExport( Nid = "jO8DM8oyego", @@ -138,7 +120,8 @@ public static int NpEntitlementAccessGetAddcontEntitlementInfoList(CpuContext ct return ctx.SetReturn(NpEntitlementAccessErrorParameter); } - var hitNum = (uint)OwnedAddcontEntitlements.Length; + var owned = AddcontEntitlements.Owned(); + var hitNum = (uint)owned.Count; Span<byte> hitNumBytes = stackalloc byte[sizeof(uint)]; BinaryPrimitives.WriteUInt32LittleEndian(hitNumBytes, hitNum); if (!ctx.Memory.TryWrite(hitNumAddress, hitNumBytes)) @@ -164,7 +147,7 @@ public static int NpEntitlementAccessGetAddcontEntitlementInfoList(CpuContext ct if (!TryWriteAddcontEntitlementInfo( ctx, listAddress + index * (ulong)AddcontEntitlementInfoSize, - OwnedAddcontEntitlements[(int)index])) + owned[(int)index])) { return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } @@ -205,13 +188,8 @@ public static int NpEntitlementAccessGetAddcontEntitlementInfo(CpuContext ctx) return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } - foreach (var entitlement in OwnedAddcontEntitlements) + if (AddcontEntitlements.TryGet(label, out var entitlement)) { - if (!string.Equals(label, entitlement.Label, StringComparison.Ordinal)) - { - continue; - } - if (!TryWriteAddcontEntitlementInfo(ctx, infoAddress, entitlement)) { return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); @@ -255,8 +233,7 @@ public static int NpEntitlementAccessGetEntitlementKey(CpuContext ctx) return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } - return ctx.SetReturn(OwnedAddcontEntitlements.Any(entitlement => - string.Equals(label, entitlement.Label, StringComparison.Ordinal)) + return ctx.SetReturn(AddcontEntitlements.Owns(label) ? (int)OrbisGen2Result.ORBIS_GEN2_OK : NpEntitlementAccessErrorNoEntitlement); } @@ -348,7 +325,7 @@ public static int NpEntitlementAccessAbortRequest(CpuContext ctx) => private static bool TryWriteAddcontEntitlementInfo( CpuContext ctx, ulong address, - AddcontEntitlement entitlement) + AddcontEntitlements.Entitlement entitlement) { Span<byte> info = stackalloc byte[AddcontEntitlementInfoSize]; info.Clear(); diff --git a/src/SharpEmu.Libs/Np/NpManagerExports.cs b/src/SharpEmu.Libs/Np/NpManagerExports.cs index 7b449469b..c5e3e67f5 100644 --- a/src/SharpEmu.Libs/Np/NpManagerExports.cs +++ b/src/SharpEmu.Libs/Np/NpManagerExports.cs @@ -147,6 +147,19 @@ public static int NpRegisterStateCallback(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + // Registration keeps nothing, so there is nothing to drop. Death Stranding unregisters on every + // network retry while offline. + [SysAbiExport( + Nid = "M3wFXbYQtAA", + ExportName = "sceNpUnregisterStateCallbackA", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceNpManager")] + public static int NpUnregisterStateCallbackA(CpuContext ctx) + { + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + /// <summary> /// Accepts the reachability callback and never invokes it. Reachability /// transitions only ever fire on a real PSN connection, which an offline diff --git a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs index 0b04e2fad..4dbedbaf4 100644 --- a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs +++ b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs @@ -938,28 +938,26 @@ private static PlayGoMetadata CreateBaseChunkMetadata(PlayGoChunkIdKnowledge kno [(ushort)0], knowledge); - // Chunk ids for a title that ships no PlayGo sidecar, taken from the - // pakchunk<N>-<platform>.pak files on disk. Chunk 0 is always included: it - // is the base chunk and must resolve even for a title with no pak files at - // all (which keeps the single-chunk behaviour for such titles). + // Chunk ids for a title that ships no PlayGo sidecar, taken from the pak files on + // disk: Unreal names them pakchunk<N>-<platform>.pak and RE Engine re_chunk_<NNN>.pak + // (Street Fighter 6 ships re_chunk_000 and re_chunk_001, its bulk content; reporting + // only chunk 0 left the title in its "installation in progress" mode with most + // textures and models unavailable). Chunk 0 is always included: it is the base chunk + // and must resolve even for a title with no pak files at all (which keeps the + // single-chunk behaviour for such titles). private static ushort[] DiscoverInstalledChunkIds(string app0Root) { var ids = new SortedSet<ushort> { 0 }; try { - foreach (var pakFile in App0Archive.EnumerateFilesRecursive(app0Root, "pakchunk*.pak")) + foreach (var (pattern, prefix) in PakChunkPatterns) { - var name = Path.GetFileNameWithoutExtension(pakFile); - var digits = name.AsSpan("pakchunk".Length); - var length = 0; - while (length < digits.Length && char.IsAsciiDigit(digits[length])) + foreach (var pakFile in App0Archive.EnumerateFilesRecursive(app0Root, pattern)) { - length++; - } - - if (length > 0 && ushort.TryParse(digits[..length], out var chunkId)) - { - ids.Add(chunkId); + if (TryParseLeadingChunkId(Path.GetFileName(pakFile).AsSpan(prefix.Length), out var chunkId)) + { + ids.Add(chunkId); + } } } } @@ -973,6 +971,24 @@ private static ushort[] DiscoverInstalledChunkIds(string app0Root) return ids.ToArray(); } + private static readonly (string Pattern, string Prefix)[] PakChunkPatterns = + [ + ("pakchunk*.pak", "pakchunk"), + ("re_chunk_*.pak", "re_chunk_"), + ]; + + private static bool TryParseLeadingChunkId(ReadOnlySpan<char> digits, out ushort chunkId) + { + var length = 0; + while (length < digits.Length && char.IsAsciiDigit(digits[length])) + { + length++; + } + + chunkId = 0; + return length > 0 && ushort.TryParse(digits[..length], out chunkId); + } + private static ushort[] LoadChunkIds(string chunkDefsXml) { if (!File.Exists(chunkDefsXml)) diff --git a/src/SharpEmu.Libs/Share/SharePlayExports.cs b/src/SharpEmu.Libs/Share/SharePlayExports.cs index 9baffec39..d44f48b25 100644 --- a/src/SharpEmu.Libs/Share/SharePlayExports.cs +++ b/src/SharpEmu.Libs/Share/SharePlayExports.cs @@ -26,6 +26,28 @@ public static int SharePlayProhibitController(CpuContext ctx) return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK); } + [SysAbiExport( + Nid = "+MCXJlWdi+s", + ExportName = "sceSharePlayGetCurrentConnectionInfoA", + Target = Generation.Gen5, + LibraryName = "libSceSharePlay")] + public static int SharePlayGetCurrentConnectionInfoA(CpuContext ctx) + { + var address = ctx[CpuRegister.Rdi]; + if (address == 0) + { + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); + } + + // No SharePlay session is running: the 72-byte connection info (SceSharePlayConnectionInfoA) + // reads as zeroed, i.e. status ORBIS_SHARE_PLAY_CONNECTION_STATUS_DORMANT (not connected). + Span<byte> info = stackalloc byte[0x48]; + info.Clear(); + return ctx.Memory.TryWrite(address, info) + ? ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK) + : ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + public static void ResetRuntimeState() => Volatile.Write(ref _controllerProhibited, 0); internal static bool IsControllerProhibited => Volatile.Read(ref _controllerProhibited) != 0; diff --git a/src/SharpEmu.Libs/SystemGesture/SystemGestureExports.cs b/src/SharpEmu.Libs/SystemGesture/SystemGestureExports.cs index 97a4c3491..65f9da471 100644 --- a/src/SharpEmu.Libs/SystemGesture/SystemGestureExports.cs +++ b/src/SharpEmu.Libs/SystemGesture/SystemGestureExports.cs @@ -73,6 +73,30 @@ public static int SystemGestureGetTouchEventsCount(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + [SysAbiExport( + Nid = "fLTseA7XiWY", + ExportName = "sceSystemGestureGetTouchEvents", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceSystemGesture")] + public static int SystemGestureGetTouchEvents(CpuContext ctx) + { + // No touch input is reported: the recognizer holds no events. + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + [SysAbiExport( + Nid = "L8YmemOeSNY", + ExportName = "sceSystemGestureGetPrimitiveTouchEvents", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceSystemGesture")] + public static int SystemGestureGetPrimitiveTouchEvents(CpuContext ctx) + { + // No touch input is reported: the recognizer holds no events. + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + [SysAbiExport( Nid = "1MMK0W-kMgA", ExportName = "sceSystemGestureAppendTouchRecognizer", diff --git a/src/SharpEmu.Libs/UserService/UserServiceExports.cs b/src/SharpEmu.Libs/UserService/UserServiceExports.cs index d86eb6920..500d912be 100644 --- a/src/SharpEmu.Libs/UserService/UserServiceExports.cs +++ b/src/SharpEmu.Libs/UserService/UserServiceExports.cs @@ -179,6 +179,32 @@ public static int UserServiceGetUserNumber(CpuContext ctx) : SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); } + // Unity's PS4 player aborts a login (and never opens that user's pad) when this fails. + [SysAbiExport( + Nid = "lUoqwTQu4Go", + ExportName = "sceUserServiceGetUserColor", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceUserService")] + public static int UserServiceGetUserColor(CpuContext ctx) + { + const int UserColorBlue = 0; + var userId = unchecked((int)ctx[CpuRegister.Rdi]); + var colorAddress = ctx[CpuRegister.Rsi]; + if (colorAddress == 0) + { + return SetReturn(ctx, OrbisUserServiceErrorInvalidArgument); + } + + if (userId != PrimaryUserId && userId != 1) + { + return SetReturn(ctx, OrbisUserServiceErrorInvalidParameter); + } + + return TryWriteInt32(ctx, colorAddress, UserColorBlue) + ? SetReturnWithTrace(ctx, 0, $"get_user_color user={userId} color={UserColorBlue} out=0x{colorAddress:X16}") + : SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + // Name not yet in ps5_names.txt and the NID was captured from titles; revisit when the symbol is catalogued. #pragma warning disable SHEM006 [SysAbiExport( diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs index f86b8a599..ec82aefa2 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs @@ -1949,6 +1949,30 @@ private static bool PaceFlip(int handle, int flipMode) } private static int RegisterBufferRange(VideoOutPortState port, int startIndex, ReadOnlySpan<ulong> addresses, BufferAttribute attribute, int requestedGroupIndex = -1) + { + var groupIndex = RegisterBufferRangeLocked(port, startIndex, addresses, attribute, requestedGroupIndex); + if (groupIndex < 0) + { + return groupIndex; + } + + // Outside _stateGate: the presenter takes its own gate before asking VideoOut whether a + // flip is pending, so starting it under _stateGate deadlocks a title that registers a + // new buffer group (e.g. on a scene change) while frames are being presented. + GuestGpu.Current.EnsureStarted(attribute.Width, attribute.Height); + var guestFormat = MapPixelFormatToGuestTextureFormat(attribute.PixelFormat); + if (guestFormat != 0) + { + foreach (var address in addresses) + { + GuestGpu.Current.RegisterKnownDisplayBuffer(address, guestFormat); + } + } + + return groupIndex; + } + + private static int RegisterBufferRangeLocked(VideoOutPortState port, int startIndex, ReadOnlySpan<ulong> addresses, BufferAttribute attribute, int requestedGroupIndex) { lock (_stateGate) { @@ -1991,17 +2015,6 @@ private static int RegisterBufferRange(VideoOutPortState port, int startIndex, R $"videoout.register_buffers handle={port.Handle} group={groupIndex} start={startIndex} count={addresses.Length} " + $"addresses=[{string.Join(',', addresses.ToArray().Select(static address => $"0x{address:X16}"))}] " + $"fmt=0x{attribute.PixelFormat:X} tile={attribute.TilingMode} {attribute.Width}x{attribute.Height} pitch={attribute.PitchInPixel}"); - GuestGpu.Current.EnsureStarted(attribute.Width, attribute.Height); - - var guestFormat = MapPixelFormatToGuestTextureFormat(attribute.PixelFormat); - if (guestFormat != 0) - { - foreach (var address in addresses) - { - GuestGpu.Current.RegisterKnownDisplayBuffer(address, guestFormat); - } - } - return groupIndex; } } diff --git a/tests/SharpEmu.Libs.Tests/Ampr/AmprSetBufferTests.cs b/tests/SharpEmu.Libs.Tests/Ampr/AmprSetBufferTests.cs new file mode 100644 index 000000000..afd108335 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Ampr/AmprSetBufferTests.cs @@ -0,0 +1,91 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Ampr; +using Xunit; + +namespace SharpEmu.Libs.Tests.Ampr; + +[Collection("AmprFileRegistry")] +public sealed class AmprSetBufferTests +{ + private const ulong MemoryBase = 0x3_0000_0000; + private const ulong CommandBuffer = MemoryBase + 0x100; + private const ulong Records = MemoryBase + 0x200; + private const ulong Output = MemoryBase + 0x800; + private const ulong SecondOutput = MemoryBase + 0x808; + + // Death Stranding sets the same buffer before every command it appends; the commands + // already queued must survive, or only the last one runs. + [Fact] + public void SettingAnAttachedBufferAgainKeepsItsQueuedCommands() + { + var context = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + Construct(context); + Assert.Equal(0, SetBuffer(context)); + Write(context, Output, 1); + + Assert.Equal(unchecked((int)0x80020010), SetBuffer(context)); + Write(context, SecondOutput, 2); + + Assert.Equal(0, AmprExports.SubmitCommandBuffer(context, CommandBuffer, AmprExports.AmprEngine.Apr, 0x7201, null, out var submission)); + Assert.True(submission!.CompletedInline); + Assert.Equal(1UL, Read(context, Output)); + Assert.Equal(2UL, Read(context, SecondOutput)); + } + + [Fact] + public void AClearedBufferCanBeSetAgain() + { + var context = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + Construct(context); + Assert.Equal(0, SetBuffer(context)); + + context[CpuRegister.Rdi] = CommandBuffer; + Assert.Equal(0, AmprExports.CommandBufferClearBuffer(context)); + + Assert.Equal(0, SetBuffer(context)); + } + + // The APR and AMM constructors leave the header alone, so a recycled object can hold an old + // pointer there: only a buffer this module attached makes SetBuffer busy. + [Fact] + public void LeftoverBytesInAnObjectNeverSetAreNotBusy() + { + var context = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + Construct(context); + Assert.True(context.TryWriteUInt64(CommandBuffer + 0x10, 0x1234_5000)); + + Assert.Equal(0, SetBuffer(context)); + Assert.Equal(Records, Read(context, CommandBuffer + 0x10)); + } + + private static void Construct(CpuContext context) + { + context[CpuRegister.Rdi] = CommandBuffer; + Assert.Equal(0, AmprExports.CommandBufferConstructor(context)); + } + + private static int SetBuffer(CpuContext context) + { + context[CpuRegister.Rdi] = CommandBuffer; + context[CpuRegister.Rsi] = Records; + context[CpuRegister.Rdx] = 0x100; + return AmprExports.CommandBufferSetBuffer(context); + } + + private static void Write(CpuContext context, ulong address, ulong value) + { + context[CpuRegister.Rdi] = CommandBuffer; + context[CpuRegister.Rsi] = address; + context[CpuRegister.Rdx] = value; + Assert.Equal(0, AmprExports.CommandBufferWriteAddress0400(context)); + } + + private static ulong Read(CpuContext context, ulong address) + { + Assert.True(context.TryReadUInt64(address, out var value)); + return value; + } +} diff --git a/tests/SharpEmu.Libs.Tests/AppContent/AddcontMountTests.cs b/tests/SharpEmu.Libs.Tests/AppContent/AddcontMountTests.cs new file mode 100644 index 000000000..cc4490331 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/AppContent/AddcontMountTests.cs @@ -0,0 +1,198 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; +using SharpEmu.HLE; +using SharpEmu.Libs.AppContent; +using SharpEmu.Libs.Kernel; +using SharpEmu.Libs.Np; +using Xunit; + +namespace SharpEmu.Libs.Tests.AppContent; + +// The add-on state is static, so these tests must not run beside each other. +[CollectionDefinition(nameof(AddcontStateCollection), DisableParallelization = true)] +public sealed class AddcontStateCollection; + +[Collection(nameof(AddcontStateCollection))] +public sealed class AddcontMountTests : IDisposable +{ + private const ulong MemoryBase = 0x1_0000_0000; + private const ulong LabelAddress = MemoryBase; + private const ulong MountPointAddress = MemoryBase + 0x100; + private const int ErrorParameter = unchecked((int)0x80D90002); + private const int ErrorDrmNoEntitlement = unchecked((int)0x80D90007); + + private readonly string _root = Path.Combine(Path.GetTempPath(), "sharpemu-addcont-" + Guid.NewGuid().ToString("N")); + + public AddcontMountTests() + { + Directory.CreateDirectory(Path.Combine(_root, "data")); + Directory.CreateDirectory(Path.Combine(_root, "addcont")); + AddcontEntitlements.DataRootOverride = Path.Combine(_root, "data"); + AddcontEntitlements.AddcontRootOverride = Path.Combine(_root, "addcont"); + AppContentExports.ResetRuntimeState(); + } + + public void Dispose() + { + AppContentExports.ResetRuntimeState(); + AddcontEntitlements.DataRootOverride = null; + AddcontEntitlements.AddcontRootOverride = null; + KernelMemoryCompatExports.ConfigureApplicationInfo(null); + AddcontEntitlements.ConfigureConceptId(null); + AddcontEntitlements.ResetRuntimeState(); + try + { + Directory.Delete(_root, recursive: true); + } + catch (IOException) + { + } + } + + [Theory] + [InlineData("85y-je", true)] + [InlineData("GHOST2APP0000000", true)] + [InlineData("_mtqu6", true)] + [InlineData("", false)] + [InlineData("12345678901234567", false)] + [InlineData("..", false)] + [InlineData("a/b", false)] + [InlineData("a\b", false)] + [InlineData("c:evil", false)] + [InlineData("a b", false)] + [InlineData("café", false)] + public void LabelsFollowTheEntitlementCharset(string label, bool valid) => + Assert.Equal(valid, AddcontEntitlements.IsValidLabel(label)); + + [Fact] + public void MountRejectsAnInvalidLabelWithoutMounting() + { + var (context, memory) = CreateContext("../evil"); + Assert.Equal(ErrorParameter, AppContentExports.AppContentAddcontMount(context)); + Assert.Equal(string.Empty, ReadMountPoint(memory)); + Assert.False(Directory.Exists(Path.Combine(_root, "evil"))); + } + + [Fact] + public void MountingTheSameLabelTwiceReturnsTheSameMountPoint() + { + Directory.CreateDirectory(Path.Combine(_root, "addcont", "85y-je")); + Directory.CreateDirectory(Path.Combine(_root, "addcont", "5d5c48")); + var (context, memory) = CreateContext("85y-je"); + Assert.Equal(0, AppContentExports.AppContentAddcontMount(context)); + var first = ReadMountPoint(memory); + + Assert.Equal(0, AppContentExports.AppContentAddcontMount(context)); + Assert.Equal(first, ReadMountPoint(memory)); + + WriteLabel(memory, "5d5c48"); + Assert.Equal(0, AppContentExports.AppContentAddcontMount(context)); + Assert.NotEqual(first, ReadMountPoint(memory)); + } + + [Fact] + public void AMissingPackageIsRefusedWithoutAMountPoint() + { + var (context, memory) = CreateContext("85y-je"); + Assert.Equal(ErrorDrmNoEntitlement, AppContentExports.AppContentAddcontMount(context)); + Assert.Equal(string.Empty, ReadMountPoint(memory)); + Assert.False(Directory.Exists(Path.Combine(_root, "addcont", "85y-je"))); + } + + [Fact] + public void OwnedLabelsComeFromTheTitleDefaultsAndOnlyForThatTitle() + { + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA26344"); + AddcontEntitlements.ConfigureConceptId("10003923"); + Assert.Equal( + new[] { "GHOST2APP0000000", "GHOST2BASE000000" }, + AddcontEntitlements.Owned().Select(entitlement => entitlement.Label)); + Assert.True(AddcontEntitlements.Owns("GHOST2APP0000000")); + Assert.True(AddcontEntitlements.TryGet("GHOST2BASE000000", out var entitlement)); + Assert.Equal(4u, entitlement.DownloadStatus); + Assert.Same(AddcontEntitlements.Owned(), AddcontEntitlements.Owned()); + + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA00000"); + AddcontEntitlements.ConfigureConceptId(null); + Assert.Empty(AddcontEntitlements.Owned()); + Assert.False(AddcontEntitlements.Owns("GHOST2APP0000000")); + } + + // Every regional release of a game shares one concept id: the EU GTA V dump + // (PPSA04263) owns the same labels as the US one. + [Fact] + public void ARegionalTitleIdMatchesTheDefaultsOfItsConceptId() + { + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA04263"); + AddcontEntitlements.ConfigureConceptId("201930"); + Assert.Equal( + new[] { "85y-je", "5d5c48", "_mtqu6" }, + AddcontEntitlements.Owned().Select(entitlement => entitlement.Label)); + } + + // Street Fighter 6 has no default row: an unknown concept id owns nothing. + [Fact] + public void AnUnknownConceptIdOwnsNothing() + { + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA02633"); + AddcontEntitlements.ConfigureConceptId("10001615"); + Assert.Empty(AddcontEntitlements.Owned()); + } + + [Fact] + public void ATitleIdEntryInTheConfigurationFileWinsOverAConceptIdEntry() + { + File.WriteAllText( + Path.Combine(_root, "data", "entitlements.json"), + "{}"); + Directory.CreateDirectory(Path.Combine(_root, "data", "user")); + File.WriteAllText( + Path.Combine(_root, "data", "user", "entitlements.json"), + "{ \"10001615\": [\"CONCEPT-1\"], \"PPSA02633\": [\"TITLE-1\"] }"); + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA02633"); + AddcontEntitlements.ConfigureConceptId("10001615"); + Assert.Equal(new[] { "TITLE-1" }, AddcontEntitlements.Owned().Select(entitlement => entitlement.Label)); + + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA02634"); + Assert.Equal(new[] { "CONCEPT-1" }, AddcontEntitlements.Owned().Select(entitlement => entitlement.Label)); + } + + [Fact] + public void OnlyValidAddcontFolderNamesAreEnumerated() + { + Directory.CreateDirectory(Path.Combine(_root, "addcont", "PACK-1")); + Directory.CreateDirectory(Path.Combine(_root, "addcont", "bad name")); + Directory.CreateDirectory(Path.Combine(_root, "addcont", "THIS_LABEL_IS_FAR_TOO_LONG")); + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA00000"); + AddcontEntitlements.ResetRuntimeState(); + Assert.Equal(new[] { "PACK-1" }, AddcontEntitlements.Owned().Select(entitlement => entitlement.Label)); + } + + private static (CpuContext Context, FakeCpuMemory Memory) CreateContext(string label) + { + var memory = new FakeCpuMemory(MemoryBase, 0x1_000); + var context = new CpuContext(memory, Generation.Gen5); + WriteLabel(memory, label); + context[CpuRegister.Rdi] = 0; + context[CpuRegister.Rsi] = LabelAddress; + context[CpuRegister.Rdx] = MountPointAddress; + return (context, memory); + } + + private static void WriteLabel(FakeCpuMemory memory, string label) + { + var bytes = new byte[17]; + Encoding.UTF8.GetBytes(label).AsSpan(0, Math.Min(17, Encoding.UTF8.GetByteCount(label))).CopyTo(bytes); + Assert.True(memory.TryWrite(LabelAddress, bytes)); + } + + private static string ReadMountPoint(FakeCpuMemory memory) + { + var bytes = new byte[16]; + Assert.True(memory.TryRead(MountPointAddress, bytes)); + var length = Array.IndexOf(bytes, (byte)0); + return Encoding.ASCII.GetString(bytes, 0, length < 0 ? bytes.Length : length); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Cpu/GuestExceptionExecutorHandoffTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/GuestExceptionExecutorHandoffTests.cs index 128f185c3..3e394c87f 100644 --- a/tests/SharpEmu.Libs.Tests/Cpu/GuestExceptionExecutorHandoffTests.cs +++ b/tests/SharpEmu.Libs.Tests/Cpu/GuestExceptionExecutorHandoffTests.cs @@ -52,7 +52,8 @@ public void BlockedThreadTakesPendingExceptionWhenExecutorReleasesIt(bool signal pendingType, handler, exceptionType, - exceptionStack); + exceptionStack, + GuestExceptionHandlerArguments.Signal); Assert.NotNull(pending); var pendingDictionary = Assert.IsAssignableFrom<IDictionary>( backendType.GetField( diff --git a/tests/SharpEmu.Libs.Tests/Cpu/NativeTlsNearAllocationTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/NativeTlsNearAllocationTests.cs new file mode 100644 index 000000000..11feb157f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Cpu/NativeTlsNearAllocationTests.cs @@ -0,0 +1,56 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Core.Cpu.Native; +using Xunit; + +namespace SharpEmu.Libs.Tests.Cpu; + +public sealed class NativeTlsNearAllocationTests +{ + private const ulong Entry = 0x0F20_0000; + private const ulong Size = 0x10000; + + [Fact] + public void OrderNearEntryCandidates_PicksNearestFreeGapAcrossBothSides() + { + var free = new List<(ulong Start, ulong End)> + { + (0x1_0000, 0x5_0000), + (0x0F00_0000, 0x0F10_0000), + (0x1000_0000, 0x1001_0000), + (0x5000_0000, 0x6000_0000), + }; + + var result = DirectExecutionBackend.OrderNearEntryCandidates(free, Entry, Size, 0x1_0000, Entry + 0x7000_0000); + + Assert.Equal(0x0F0F_0000ul, result[0]); + Assert.Equal(0x1000_0000ul, result[1]); + Assert.Equal(0x0004_0000ul, result[2]); + Assert.Equal(0x5000_0000ul, result[3]); + } + + [Fact] + public void OrderNearEntryCandidates_SkipsGapsTooSmallOrOutsideTheWindow() + { + var free = new List<(ulong Start, ulong End)> + { + (0x0F30_0000, 0x0F30_8000), + (0x1_4E00_0000, 0x1_5000_0000), + }; + + var result = DirectExecutionBackend.OrderNearEntryCandidates(free, Entry, Size, 0x1_0000, Entry + 0x7000_0000); + + Assert.Empty(result); + } + + [Fact] + public void OrderNearEntryCandidates_AlignsToAllocationGranularity() + { + var free = new List<(ulong Start, ulong End)> { (0x0F40_1000, 0x0F42_0000) }; + + var result = DirectExecutionBackend.OrderNearEntryCandidates(free, Entry, Size, 0x1_0000, Entry + 0x7000_0000); + + Assert.Equal(0x0F41_0000ul, result[0]); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Kernel/KernelArchRaiseUserTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/KernelArchRaiseUserTests.cs new file mode 100644 index 000000000..f954db7f6 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Kernel/KernelArchRaiseUserTests.cs @@ -0,0 +1,143 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Core.Cpu.Native; +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; +using Xunit; + +namespace SharpEmu.Libs.Tests.Kernel; + +[Collection("GuestThreadFlowProfile")] +public sealed class KernelArchRaiseUserTests +{ + private const int Esrch = unchecked((int)0x80020003); + private const ulong Callback = 0x1_2345_6780; + private const ulong Thread = 0x1_7000_0010; + private const ulong MemoryBase = 0x1_3000_0000; + + [Fact] + public void RaiseWithoutRegisteredCallbackReportsNoSuchThread() + { + var ctx = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + Register(0); + ctx[CpuRegister.Rdi] = Thread; + + Assert.Equal(Esrch, KernelExceptionCompatExports.ArchRaiseUser(ctx)); + Assert.Equal(unchecked((ulong)Esrch), ctx[CpuRegister.Rax]); + } + + [Fact] + public void RaiseDeliversTheGcCallbackWithUnityArguments() + { + var ctx = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + var scheduler = DispatchProxy.Create<IGuestThreadScheduler, RaiseScheduler>(); + var proxy = (RaiseScheduler)(object)scheduler; + var previous = GuestThreadExecution.Scheduler; + try + { + GuestThreadExecution.Scheduler = scheduler; + Register(Callback); + ctx[CpuRegister.Rdi] = Thread; + + Assert.Equal(0, KernelExceptionCompatExports.ArchRaiseUser(ctx)); + Assert.Equal(0UL, ctx[CpuRegister.Rax]); + Assert.Equal(1, proxy.Calls); + Assert.Equal(Thread, proxy.Thread); + Assert.Equal(Callback, proxy.Handler); + Assert.Equal(GuestExceptionHandlerArguments.UnityGcSuspend, proxy.Arguments); + } + finally + { + GuestThreadExecution.Scheduler = previous; + Register(0); + } + } + + [Fact] + public void SchedulerFailureReportsNoSuchThread() + { + var ctx = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + var scheduler = DispatchProxy.Create<IGuestThreadScheduler, RaiseScheduler>(); + ((RaiseScheduler)(object)scheduler).Succeed = false; + var previous = GuestThreadExecution.Scheduler; + try + { + GuestThreadExecution.Scheduler = scheduler; + Register(Callback); + ctx[CpuRegister.Rdi] = Thread; + + Assert.Equal(Esrch, KernelExceptionCompatExports.ArchRaiseUser(ctx)); + Assert.Equal(unchecked((ulong)Esrch), ctx[CpuRegister.Rax]); + } + finally + { + GuestThreadExecution.Scheduler = previous; + Register(0); + } + } + + [Fact] + public void HandlerArgumentsFollowTheConvention() + { + var memory = new FakeCpuMemory(MemoryBase, 0x1000); + var ctx = new CpuContext(memory, Generation.Gen5); + var contextAddress = MemoryBase + 0x100; + var continuation = default(GuestCpuContinuation) with + { + Rip = 0x1_1000_0000, + Rsp = 0x1_6000_0F00, + Rflags = 0x202, + }; + Assert.True(DirectExecutionBackend.TryWriteGuestExceptionContext(ctx, contextAddress, continuation, 0x500)); + + DirectExecutionBackend.ResolveGuestExceptionHandlerArguments( + ctx, GuestExceptionHandlerArguments.Signal, 11, contextAddress, out var a0, out var a1); + Assert.Equal(11UL, a0); + Assert.Equal(contextAddress, a1); + + DirectExecutionBackend.ResolveGuestExceptionHandlerArguments( + ctx, GuestExceptionHandlerArguments.UnityGcSuspend, 0, contextAddress, out a0, out a1); + Assert.Equal(contextAddress, a0); + Assert.Equal(0x1_6000_0F00UL, a1); + } + + private static void Register(ulong callback) + { + var ctx = new CpuContext(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + ctx[CpuRegister.Rdi] = callback; + Assert.Equal(0, KernelExceptionCompatExports.ArchInitGc(ctx)); + } + + public class RaiseScheduler : DispatchProxy + { + private int _calls; + + public bool Succeed { get; set; } = true; + + public int Calls => Volatile.Read(ref _calls); + + public ulong Thread { get; private set; } + + public ulong Handler { get; private set; } + + public GuestExceptionHandlerArguments Arguments { get; private set; } + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + if (targetMethod?.Name == nameof(IGuestThreadScheduler.TryRaiseGuestException) && + args is { Length: 6 }) + { + Interlocked.Increment(ref _calls); + Thread = (ulong)args[1]!; + Handler = (ulong)args[2]!; + Arguments = (GuestExceptionHandlerArguments)args[4]!; + args[5] = Succeed ? null : "refused"; + return Succeed; + } + + throw new NotSupportedException(targetMethod?.Name); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Kernel/PosixMemoryAndSignalTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/PosixMemoryAndSignalTests.cs index 28136fbcc..8a81d6f5d 100644 --- a/tests/SharpEmu.Libs.Tests/Kernel/PosixMemoryAndSignalTests.cs +++ b/tests/SharpEmu.Libs.Tests/Kernel/PosixMemoryAndSignalTests.cs @@ -64,6 +64,85 @@ public void InvalidMmapReturnsMapFailedNotAKernelErrorPointer(ulong length, uint Assert.Equal(ulong.MaxValue, test.Context[CpuRegister.Rax]); } + [Fact] + public void ReadOnlySharedFileMappingReturnsFileBytesAndZeroTail() + { + using var test = new BackedKernelMemory(); + var path = Path.GetTempFileName(); + var data = Enumerable.Range(1, 100).Select(i => (byte)i).ToArray(); + File.WriteAllBytes(path, data); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + stream.Position = 5; + const int fd = 7001; + KernelMemoryCompatExports.RegisterOpenFileForTests(fd, stream); + try + { + SetFileMmapArguments(test.Context, 0x8000, 1, 1, fd, 0); + Assert.Equal(0, KernelMemoryCompatExports.PosixMmap(test.Context)); + var address = test.Context[CpuRegister.Rax]; + var contents = new byte[0x4000]; + Assert.True(test.Memory.TryRead(address, contents)); + Assert.Equal(data, contents[..data.Length]); + Assert.All(contents[data.Length..], value => Assert.Equal(0, value)); + Assert.Equal(5, stream.Position); + } + finally + { + KernelMemoryCompatExports.UnregisterOpenFileForTests(fd); + stream.Dispose(); + File.Delete(path); + } + } + + [Fact] + public void FileMappingHonoursPageAlignedOffset() + { + using var test = new BackedKernelMemory(); + var path = Path.GetTempFileName(); + var data = new byte[0x4000 + 8]; + for (var i = 0; i < data.Length; i++) + data[i] = (byte)(i < 0x4000 ? 1 : 9); + File.WriteAllBytes(path, data); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + const int fd = 7002; + KernelMemoryCompatExports.RegisterOpenFileForTests(fd, stream); + try + { + SetFileMmapArguments(test.Context, 0x4000, 3, 2, fd, 0x4000); + Assert.Equal(0, KernelMemoryCompatExports.PosixMmap(test.Context)); + var contents = new byte[16]; + Assert.True(test.Memory.TryRead(test.Context[CpuRegister.Rax], contents)); + Assert.Equal(new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0 }, contents); + SetFileMmapArguments(test.Context, 0x4000, 1, 2, fd, 0x100); + Assert.Equal(-1, KernelMemoryCompatExports.PosixMmap(test.Context)); + } + finally + { + KernelMemoryCompatExports.UnregisterOpenFileForTests(fd); + stream.Dispose(); + File.Delete(path); + } + } + + [Fact] + public void FileMappingWithUnknownDescriptorFailsWithEbadf() + { + using var test = new BackedKernelMemory(); + SetFileMmapArguments(test.Context, 0x4000, 1, 1, 7999, 0); + Assert.Equal(-1, KernelMemoryCompatExports.PosixMmap(test.Context)); + Assert.Equal(ulong.MaxValue, test.Context[CpuRegister.Rax]); + } + + private static void SetFileMmapArguments(CpuContext context, ulong length, int protection, uint flags, int fd, ulong offset) + { + context[CpuRegister.Rdi] = 0; + context[CpuRegister.Rsi] = length; + context[CpuRegister.Rdx] = (ulong)protection; + context[CpuRegister.Rcx] = flags; + context[CpuRegister.R8] = unchecked((ulong)(long)fd); + context[CpuRegister.R9] = offset; + } + [Fact] public void SignalMaskOperationsPreserveThePreviousMaskAndAllowAnAliasedOutput() { diff --git a/tests/SharpEmu.Libs.Tests/Loader/GcnShaderTests.cs b/tests/SharpEmu.Libs.Tests/Loader/GcnShaderTests.cs index 863b8411b..2d13f9686 100644 --- a/tests/SharpEmu.Libs.Tests/Loader/GcnShaderTests.cs +++ b/tests/SharpEmu.Libs.Tests/Loader/GcnShaderTests.cs @@ -162,6 +162,15 @@ public void GcnLdexpDoesNotConsumeTheFollowingInstructionAsAGen5Literal() Assert.Equal("SEndpgm", program.Instructions[1].Opcode); } + // Shipped PS4 pixel shaders (Signalis) keep s_ttracedata; the hardware treats it as a no-op. + [Fact] + public void ThreadTraceDataDecodesAsASingleWordScalarControl() + { + var program = Decode(0xBF960000, 0xBF810000); + Assert.Equal("STtraceData", program.Instructions[0].Opcode); + Assert.Equal(4u, program.Instructions[1].Pc); + } + [Fact] public void ScalarAndVectorLiteralWidthsPreserveTheOriginalProgramCounters() { diff --git a/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs b/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs new file mode 100644 index 000000000..9fe5aadfd --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs @@ -0,0 +1,54 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.GnmMode; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Tests.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Libs.Tests.Loader; + +public sealed class GnmEndOfPipeTests +{ + private const ulong Label = StreamRunner.LabelAddress; + + private static uint[] EventWriteEop(uint eventType, uint eventIndex, uint cacheAction, uint source, uint interruptSelector, ulong destination, ulong value) => + StreamRunner.Packet( + PacketOpcode.EventWriteEndOfPipe, + eventType | (eventIndex << 8) | (cacheAction << 12), + StreamRunner.Low(destination), + (StreamRunner.High(destination) & 0xFFFF) | (interruptSelector << 24) | (source << 29), + StreamRunner.Low(value), + StreamRunner.High(value)); + + // A PS4 Unity title (Signalis) emits a 32-bit cache-flush timestamp with a full cache write-back. + [Theory] + [InlineData(0x04u, 0x00u, EndOfPipeWriteKind.Write32)] + [InlineData(0x04u, 0x38u, EndOfPipeWriteKind.WriteBack32)] + [InlineData(0x28u, 0x38u, EndOfPipeWriteKind.WriteBack32)] + public void GnmEndOfPipeLowDword_TimestampWritesThirtyTwoBits(uint eventType, uint cacheAction, EndOfPipeWriteKind expected) + { + var runner = new StreamRunner(); + var packets = typeof(GnmRuntime).Assembly.GetType("SharpEmu.GnmMode.Gpu.GnmCommandPackets")!; + var handlers = (PacketHandler?[])packets.GetField("Handlers", BindingFlags.Static | BindingFlags.NonPublic)! + .GetValue(null)!; + runner.Interpreter.SetPacketHandlers(handlers); + runner.Host.WriteQword(Label, 0xFFFF_FFFF_FFFF_FFFF); + + runner.Run(EventWriteEop(eventType, 5, cacheAction, 1, 0, Label, 0x1122_3344_5566_7788)); + + Assert.Equal(expected, Assert.Single(runner.Host.EndOfPipeWrites).Kind); + Assert.Equal(0xFFFF_FFFF_5566_7788UL, runner.Host.ReadQword(Label)); + } + + [Fact] + public void AgcEndOfPipeLowDword_WriteBackTimestampStaysRejected() + { + var runner = new StreamRunner(); + + var fatal = runner.RunExpectingFatal(EventWriteEop(0x04, 5, 0x38, 1, 0, Label, 0x1122_3344_5566_7788)); + + Assert.Contains("type=0x04", fatal.Message); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Loader/Ps5ParamJsonReaderTests.cs b/tests/SharpEmu.Libs.Tests/Loader/Ps5ParamJsonReaderTests.cs new file mode 100644 index 000000000..7e4246bc6 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Loader/Ps5ParamJsonReaderTests.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; +using SharpEmu.Core.Loader; +using Xunit; + +namespace SharpEmu.Libs.Tests.Loader; + +public sealed class Ps5ParamJsonReaderTests +{ + [Fact] + public void ReadsTheConceptIdSharedByRegionalReleases() + { + var json = """ + { "titleId": "PPSA04263", "conceptId": "201930", "contentVersion": "01.000.000", + "localizedParameters": { "defaultLanguage": "en-US", "en-US": { "titleName": "Test" } } } + """; + var info = Ps5ParamJsonReader.TryReadPs5Param(Encoding.UTF8.GetBytes(json)); + Assert.Equal("PPSA04263", info.TitleId); + Assert.Equal("201930", info.ConceptId); + Assert.Equal("Test", info.Title); + Assert.Equal("01.000.000", info.Version); + } + + [Fact] + public void ConceptIdIsNullWhenParamJsonHasNone() + { + var info = Ps5ParamJsonReader.TryReadPs5Param(Encoding.UTF8.GetBytes("""{ "titleId": "PPSA00001" }""")); + Assert.Equal("PPSA00001", info.TitleId); + Assert.Null(info.ConceptId); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/PhysicalVirtualMemoryTests.cs b/tests/SharpEmu.Libs.Tests/Memory/PhysicalVirtualMemoryTests.cs index 740d708de..e464e5bb7 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/PhysicalVirtualMemoryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/PhysicalVirtualMemoryTests.cs @@ -35,6 +35,27 @@ public void FreeHostRangesSkipTakenAndTooSmallRegionsAndStayInsideTheWindow() Assert.Empty(memory.EnumerateFreeHostRanges(0x72000, 0x91000, 0x2000, 0x10000)); } + [Fact] + public void ExactAllocationCommitsInsideAnOwnedReservedRange() + { + if (!OperatingSystem.IsWindows()) + return; + + using var memory = new PhysicalVirtualMemory(); + const ulong arenaSize = 0x800000; + var arena = memory.EnumerateFreeHostRanges(0x10000000, 0x7F000000, arenaSize, 0x200000) + .First(candidate => memory.TryReserveOwnedRange(candidate, arenaSize)); + + var module = arena + 0x200000; + Assert.True(memory.TryAllocateAtExact(module, 0x3000, true, out var actual)); + Assert.Equal(module, actual); + Assert.True(memory.TryWrite(module, new byte[] { 1, 2, 3 })); + + // The rest of the arena stays reserved, so an unrelated host allocation cannot take it. + Assert.DoesNotContain(arena + 0x400000, memory.EnumerateFreeHostRanges(arena, arena + arenaSize, 0x1000, 0x10000)); + memory.Clear(); + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs b/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs index 45b3ff63b..329a9370f 100644 --- a/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs @@ -3,15 +3,24 @@ using System.Buffers.Binary; using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; using SharpEmu.Libs.Np; using Xunit; namespace SharpEmu.Libs.Tests.Np; -public sealed class NpEntitlementAccessExportsTests +[Collection(nameof(SharpEmu.Libs.Tests.AppContent.AddcontStateCollection))] +public sealed class NpEntitlementAccessExportsTests : IDisposable { private const ulong MemoryBase = 0x1_0000_0000; + public void Dispose() + { + KernelMemoryCompatExports.ConfigureApplicationInfo(null); + AddcontEntitlements.ConfigureConceptId(null); + AddcontEntitlements.ResetRuntimeState(); + } + [Fact] public void GetGameTrialsFlagReportsAFullGameAndOnlyWritesOneWord() { @@ -79,6 +88,8 @@ public void UnifiedEntitlementListRequestFinishesSignedOutUntilDeleted() [InlineData("GHOST2BASE000000")] public void GhostOfYoteiMainEntitlement_IsReportedAsInstalled(string label) { + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA26344"); + AddcontEntitlements.ConfigureConceptId("10003923"); var memory = new FakeCpuMemory(MemoryBase, 0x1_000); var context = new CpuContext(memory, Generation.Gen5); var labelAddress = MemoryBase + 0x100; @@ -99,6 +110,8 @@ public void GhostOfYoteiMainEntitlement_IsReportedAsInstalled(string label) [Fact] public void GhostOfYoteiOptionalEntitlement_RemainsUnowned() { + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA26344"); + AddcontEntitlements.ConfigureConceptId("10003923"); var memory = new FakeCpuMemory(MemoryBase, 0x1_000); var context = new CpuContext(memory, Generation.Gen5); var labelAddress = MemoryBase + 0x100; @@ -112,6 +125,24 @@ public void GhostOfYoteiOptionalEntitlement_RemainsUnowned() NpEntitlementAccessExports.NpEntitlementAccessGetAddcontEntitlementInfo(context)); } + [Fact] + public void OtherTitlesOwnNoAddcontEntitlements() + { + KernelMemoryCompatExports.ConfigureApplicationInfo("PPSA02633"); + AddcontEntitlements.ConfigureConceptId("10001615"); + var memory = new FakeCpuMemory(MemoryBase, 0x1_000); + var context = new CpuContext(memory, Generation.Gen5); + var labelAddress = MemoryBase + 0x100; + var infoAddress = MemoryBase + 0x200; + memory.WriteCString(labelAddress, "GHOST2APP0000000"); + context[CpuRegister.Rsi] = labelAddress; + context[CpuRegister.Rdx] = infoAddress; + + Assert.Equal( + unchecked((int)0x817D0007), + NpEntitlementAccessExports.NpEntitlementAccessGetAddcontEntitlementInfo(context)); + } + private static string ReadCString(ReadOnlySpan<byte> value) { var length = value.IndexOf((byte)0); diff --git a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs index aaf48f58b..41decec3b 100644 --- a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs @@ -71,6 +71,18 @@ public void GetLocus_ParsedChunkDefinitions_WritesPrefixAndRejectsFirstUnknownCh Assert.Equal(new byte[] { LocusLocalFast, LocusNotDownloaded }, ReadLoci(2)); } + [Fact] + public void GetLocus_WithoutMetadata_ReportsReEngineChunkPaksAsInstalled() + { + File.WriteAllBytes(Path.Combine(_app0Root, "re_chunk_000.pak"), []); + File.WriteAllBytes(Path.Combine(_app0Root, "re_chunk_001.pak"), []); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 1])); + Assert.Equal(new byte[] { LocusLocalFast, LocusLocalFast }, ReadLoci(2)); + Assert.Equal(BadChunkId, GetLocus(handle, [2])); + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/SharpEmu.Libs.Tests/Pthread/PthreadSetCancelStateTests.cs b/tests/SharpEmu.Libs.Tests/Pthread/PthreadSetCancelStateTests.cs new file mode 100644 index 000000000..5d8f261a3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Pthread/PthreadSetCancelStateTests.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; +using Xunit; + +namespace SharpEmu.Libs.Tests.Pthread; + +public sealed class PthreadSetCancelStateTests +{ + [Fact] + public void SetCancelState_ReturnsPreviousStateAndRejectsInvalid() + { + const ulong memoryBase = 0x4_0000_0000; + const ulong oldAddress = memoryBase + 0x100; + var context = new CpuContext(new FakeCpuMemory(memoryBase, 0x1000), Generation.Gen5); + + context[CpuRegister.Rdi] = 1; + context[CpuRegister.Rsi] = oldAddress; + Assert.Equal(0, KernelPthreadCompatExports.PosixPthreadSetcancelstate(context)); + Assert.True(context.TryReadUInt32(oldAddress, out var old)); + Assert.Equal(0U, old); + + context[CpuRegister.Rdi] = 0; + Assert.Equal(0, KernelPthreadCompatExports.PosixPthreadSetcancelstate(context)); + Assert.True(context.TryReadUInt32(oldAddress, out old)); + Assert.Equal(1U, old); + + context[CpuRegister.Rdi] = 2; + Assert.Equal(22, KernelPthreadCompatExports.PosixPthreadSetcancelstate(context)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs b/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs index f70fcfec7..cd2528ff0 100644 --- a/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/UserService/UserServiceExportsTests.cs @@ -60,6 +60,32 @@ public void TriggerEffectAndVibrationIntensitiesReportTheStandardSetting() } } + [Fact] + public void GetUserColorWritesBlueForTheSignedInUser() + { + const ulong address = 0x1_0000_0000; + var memory = new FakeCpuMemory(address, 0x100); + var ctx = new CpuContext(memory, Generation.Gen4); + Assert.True(memory.TryWrite(address, new byte[] { 0xEE, 0xEE, 0xEE, 0xEE, 0xAA })); + ctx[CpuRegister.Rdi] = 0x10000000; + ctx[CpuRegister.Rsi] = address; + Assert.Equal(0, UserServiceExports.UserServiceGetUserColor(ctx)); + Span<byte> actual = stackalloc byte[5]; + Assert.True(memory.TryRead(address, actual)); + Assert.Equal(new byte[] { 0, 0, 0, 0, 0xAA }, actual.ToArray()); + } + + [Theory] + [InlineData(0x10000001, 0x1_0000_0000UL, unchecked((int)0x80960009))] + [InlineData(0x10000000, 0UL, unchecked((int)0x80960005))] + public void GetUserColorValidatesUserAndOutput(int userId, ulong address, int expected) + { + var ctx = new CpuContext(new FakeCpuMemory(0x1_0000_0000, 0x100), Generation.Gen4); + ctx[CpuRegister.Rdi] = unchecked((ulong)userId); + ctx[CpuRegister.Rsi] = address; + Assert.Equal(expected, UserServiceExports.UserServiceGetUserColor(ctx)); + } + [Fact] public void TerminateResetsTheLoginEvent() { From 933e47bf23a88cd725912d7299b469b2a2ae36d2 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:08:08 +0300 Subject: [PATCH 31/64] Added AGENTS.md file to document the agents used in the project --- AGENTS.md | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..642e87ced --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,76 @@ +<!-- +SPDX-FileCopyrightText: 2026 SharpEmu Emulator Project +SPDX-License-Identifier: GPL-2.0-or-later +--> + +# Working on SharpEmu + +SharpEmu is a C# PS5 emulator with a PS4 backward-compatibility mode. + +- Correctness before compatibility numbers. +- General solutions before title-specific workarounds. +- Measured performance before speculative optimization. +- Verified results before claims. + +## Emulation changes + +- Fix the guest-visible behavior shared by titles that exercise the same path. For a rendering bug, identify the command, resource state or shader operation responsible. Do not introduce title-specific workarounds based on game IDs, shader hashes, hardcoded guest addresses or other incidental identifiers. +- Check which guest mode owns the behavior. When consulting a PS4 reference for a shared command, verify its fields and semantics on the PS5 path before changing code used by both modes. +- Keep all PS4-specific optimizations and implementations within GnmMode whenever possible. Do not mix PS4-specific behavior with the native PS5 execution path. Shared infrastructure should remain platform-neutral unless a change is explicitly required by both modes. +- Implement the effects a guest can observe from an HLE export, including output values, resource lifetime, callbacks and errors as applicable. A resolved import alone does not demonstrate that the guest can use the function. +- Do not silently skip unsupported guest operations or return fabricated success values. Report unsupported behavior explicitly with actionable diagnostics. Do not hide failures by weakening validation or disabling execution paths. +- Use public documentation, clean-room findings or original research. When real PS5 output or a minimal homebrew reproducer is available, record the inputs and compare the result against the emulator. +- Follow [.editorconfig](.editorconfig) and the surrounding C# conventions. Reuse existing helpers, express intent through names and keep unrelated refactoring out of the diff. Include the project's SPDX header in new files and preserve existing copyright and license notices. + +## Graphics and shader compilation + +- Preserve guest instruction semantics, including execution masks, subgroup behavior, memory ordering and synchronization. +- Fix shader translation at the instruction, IR or lowering level responsible for the incorrect behavior. +- Do not replace unsupported instructions with no-ops or arbitrary constants. +- Preserve resource barriers, image layouts and queue synchronization semantics. +- Verify changes against both native PS5 and PS4 backward-compatibility paths when shared infrastructure is affected. + +## Performance + +- Avoid unnecessary allocations, copying, locking and synchronization in hot paths. +- Preserve asynchronous execution where possible. Do not introduce blocking waits merely to simplify implementation. +- Profile before optimizing. Do not claim performance improvements without measurements. +- Preserve cache correctness, resource lifetime and invalidation semantics when optimizing. + +## Change scope + +- Make the smallest complete change that fixes the underlying issue. +- Do not introduce new abstractions, dependencies or architectural changes unless required by the task. +- Preserve existing public interfaces and configuration behavior unless explicitly requested otherwise. +- Do not revert or overwrite unrelated working-tree changes. + +## Verification + +- Never claim that a game boots, renders correctly or performs better unless it has actually been tested. +- Distinguish build verification, automated tests and in-game verification. +- Report regressions, failed or skipped checks and unverified behavior explicitly. +- Do not weaken existing tests to make an implementation pass. +- If a required verification cannot be performed, explain why rather than implying success. + +## Commits + +- Use a single subject line in the form `[Tag] Short English imperative`. Choose the subsystem that owns the change, such as `[GPU]`, `[Vulkan]`, `[ShaderCompiler]`, `[AudioOut2]` or `[GUI]`. Omit the body, signatures and co-author trailers by default. Preserve required attribution and genuine co-author trailers; never invent or remove legitimate credit. +- **Emulation paths:** split independent behavior changes into small commits, even when they touch the same file. For example, a guest descriptor-size fix and an unrelated GPU synchronization fix should be individually reviewable and revertible. Keep a change and the wiring it needs to compile together. +- **GUI features:** a single feature can be one commit across the view, settings, event handling and translations. For example, `[GUI] Add Xbox controller glyphs and hints to the GUI` can include all the files needed to display those hints. Hunk staging is optional when whole files belong to the same change. +- For mixed files, stage selected hunks with a contextual patch and `git apply --cached`. Keep context around insertions and inspect `git diff --cached` before committing so adjacent edits stay with their owner. +- Order commits by dependency so each builds. Group independent test changes in one final `[Tests]` commit, but keep regression tests with their corresponding fix when necessary for independent verification or atomicity. Check the full series against the intended diff and build the final tree with `dotnet build SharpEmu.slnx`. Verify intermediate commits individually when needed to establish that each builds; a final build alone does not establish this. Run the full test suite on request or before pushing. For in-game verification, use a Release publish of the affected entry point. +- When asked to commit on the current branch, use that branch, including `main`. Rebase a local feature branch when it needs updates from `main`, provided unrelated working-tree changes are protected. Do not rewrite shared or published history without explicit approval. Push only when asked. + +## Pull requests + +When asked for PR summary text, use the exact heading below and usually three or four bullets. Write one short English sentence per bullet. Add bullets for larger changes when there are distinct effects to describe. Keep the summary free of extra sections, introductory paragraphs and generated-by lines. + +```markdown +# What PR does? + +- Add Xbox controller glyphs to the launcher. +- Show the matching button hint for each action. +- Update translations for the new hints. +``` + +For submission, the contributor writes the summary in their own words and includes it above the required template sections. Record the game or application tested and the observed result under Testing, or use `N/A` for changes with no runtime impact. Complete the checklist personally. See the [PR template](.github/pull_request_template.md) and [contribution guidelines](CONTRIBUTING.md). From d364227d25e2e7b53043b330efdd3fead1a5210b Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:47:59 +0300 Subject: [PATCH 32/64] [Diagnostics] Log the host region that blocks a failed direct memory map --- .../Kernel/KernelMemoryCompatExports.cs | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs index caaf65cc0..c61ed2636 100644 --- a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs @@ -187,6 +187,22 @@ private struct MemoryBasicInformation public uint Type; } + private static int _mapFailureReports; + + private static void ReportMapFailure(string reason, ulong address, ulong length, ulong directMemoryStart, ulong flags) + { + if (Interlocked.Increment(ref _mapFailureReports) > 16 && !ShouldTraceDirectMemory()) + { + return; + } + + var region = VirtualQuery((nint)address, out var info, 0) == 0 + ? "unknown" + : $"base=0x{info.BaseAddress:X} allocation_base=0x{info.AllocationBase:X} size=0x{info.RegionSize:X} state=0x{info.State:X} type=0x{info.Type:X} protect=0x{info.Protect:X}"; + Console.Error.WriteLine($"[LOADER][WARN] map_direct failed={reason} address=0x{address:X} size=0x{length:X} offset=0x{directMemoryStart:X} " + + $"flags=0x{flags:X} host_region: {region}"); + } + private static unsafe nuint VirtualQuery(nint lpAddress, out MemoryBasicInformation lpBuffer, nuint dwLength) { _ = dwLength; @@ -3302,21 +3318,18 @@ private static int MapDirectMemoryTransaction(CpuContext ctx, ulong inOutAddress physicalSpanValid = HasPhysicalSpan(directMemoryStart, length); if (!physicalSpanValid) { - if (ShouldTraceDirectMemory()) - Console.Error.WriteLine($"[LOADER][TRACE] map_direct failed=physical-span address=0x{requested:X} size=0x{length:X} offset=0x{directMemoryStart:X}"); + ReportMapFailure("physical-span", requested, length, directMemoryStart, flags); return MemoryNoSpace; } var space = ResolveBackingSpace(ctx); if (space is null || !TrySelectBackingAddress(space, requested, length, alignment, flags, out var address)) { - if (ShouldTraceDirectMemory()) - Console.Error.WriteLine($"[LOADER][TRACE] map_direct failed=address-selection address=0x{requested:X} size=0x{length:X} offset=0x{directMemoryStart:X} flags=0x{flags:X} backing={space is not null}"); + ReportMapFailure(space is null ? "no-backing" : "address-selection", requested, length, directMemoryStart, flags); return MemoryNoSpace; } if (!space.TryMapBacked(address, length, directMemoryStart, mode, out var failure)) { - if (ShouldTraceDirectMemory()) - Console.Error.WriteLine($"[LOADER][TRACE] map_direct failed=host-view reason={failure} address=0x{address:X} size=0x{length:X} offset=0x{directMemoryStart:X} protection=0x{protection:X}"); + ReportMapFailure($"host-view:{failure}", address, length, directMemoryStart, flags); return MemoryNoSpace; } ReplaceMappedRegionRangeLocked(new MappedRegion(address, length, protection, From 7c2ebae324c72a071def79c9ad22631f371af350 Mon Sep 17 00:00:00 2001 From: Foued Attar <attar.foued@gmail.com> Date: Thu, 26 Nov 2026 10:23:19 +0100 Subject: [PATCH 33/64] fix(pkg): drop the 512 GiB NAPS mount size cap (#1181) GTA VI's unpacked inner image is about 540 GiB (0x872CD70000), so the installer refused a valid package. The mount size is a 40-bit field and cannot exceed 1 TiB anyway, and a forged size only costs block records for its sparse regions. --- src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs | 8 -------- .../FileSystem/Ps5PkgTests.cs | 16 ---------------- 2 files changed, 24 deletions(-) diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs index 14034a979..c4f940f4c 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Naps.cs @@ -63,10 +63,6 @@ internal sealed class Ps5Naps // File-offset kind of the terminal mount-size entry and of sparse regions. public const byte KindMount = 0x40; - // Largest inner image accepted. Sparse regions cost no stored bytes, so a forged mount size - // would otherwise make the reader build one 256 KiB block record per step of a huge image. - public const long MaxMountSize = 512L << 30; - private Ps5Naps(NapsCounts counts, NapsFileOffset[] fileOffsets, List<NapsCandidate> candidates) { Counts = counts; @@ -102,10 +98,6 @@ public static Ps5Naps Parse(byte[] blob) } fileOffsets[i] = new NapsFileOffset(blob[at + 5], offset); - if (fileOffsets[i].Kind == KindMount && offset > MaxMountSize) - { - throw new InvalidDataException($"The NAPS mount size 0x{offset:X} is implausibly large."); - } } var fileOffsetsEnd = pos + fileCount * FileOffsetStride; diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs index d6a32ee11..72dea2abf 100644 --- a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs +++ b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs @@ -284,22 +284,6 @@ public void CblockInfoTableStartsAfterTheEightByteU2cPadding() Assert.Equal(new[] { 56 }, Ps5Naps.Parse(blob[..89]).Candidates.Select(c => c.Start).ToArray()); } - [Fact] - public void ImplausibleMountSizeIsRefused() - { - var blob = new byte[90]; - BinaryPrimitives.WriteUInt64LittleEndian(blob, 1UL | (9UL << 32)); - BinaryPrimitives.WriteUInt64LittleEndian(blob.AsSpan(8), 1UL); - blob[32] = 0x24; - blob[34] = 0xFF; // mount size 0xFF00240000, about 1 TiB - blob[35] = 0x40; - blob[74] = 4; - blob[81] = 10; - - var refused = Assert.Throws<InvalidDataException>(() => Ps5Naps.Parse(blob)); - Assert.Contains("mount size", refused.Message); - } - [Fact] public void U2cMayStartRightAfterTheFileOffsets() { From 1d2fa2a35154cf650aee2e3b386e109294ac6847 Mon Sep 17 00:00:00 2001 From: Foued Attar <attar.foued@gmail.com> Date: Thu, 26 Nov 2026 10:37:25 +0100 Subject: [PATCH 34/64] perf(pkg): extract PS5 packages on several threads (#1182) A PS5 package was written one file at a time on one thread, with every 256 KiB block Kraken-decoded there, so installing a 200 GB game was bound to a single core. Files are now split into 64 MiB ranges decoded and written in parallel (half the cores, up to 8), each worker with its own block reader. Files are created at full size first and marked sparse on Windows, so out-of-order writes do not make NTFS zero-fill the gaps. Worker exceptions are unwrapped so callers still see the original InvalidDataException, IOException or cancellation. --- .../FileSystem/Pkg/Ps5InnerImage.cs | 117 +++++++----- src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs | 175 ++++++++++++++++-- .../FileSystem/Ps5PkgTests.cs | 66 +++++++ 3 files changed, 291 insertions(+), 67 deletions(-) diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs index 10818d897..604ac4552 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs @@ -13,7 +13,9 @@ internal sealed record Ps5InnerFile(string[] Components, long Logical, long Size // or Kraken-compressed, as NAPS describes. The inner superblock, inodes and directories sit after // the last file in logical order, so they are found by decoding that tail and looking for a // superblock whose size matches the NAPS mount size. Blocks are decoded one at a time (the last one -// is cached) so an image of any size needs a few hundred KiB of memory. +// is cached) so an image of any size needs a few hundred KiB of memory per BlockReader. The block +// table is immutable after Open; only a reader holds decode state, so one reader per thread can +// decode the same image in parallel. internal sealed class Ps5InnerImage { private const int InnerInodeSize = 0xA8; @@ -30,9 +32,8 @@ internal sealed class Ps5InnerImage // NAPS file-offset entries: logical offsets of file boundaries. private readonly ulong[] _boundaries; - private int _cachedIndex = -1; - private byte[] _decoded = []; - private byte[] _payload = []; + // Reader behind ReadAt and CopyTo; not shared with the parallel extraction workers. + private readonly BlockReader _defaultReader; internal readonly record struct UBlock(long Logical, long OnDisk, uint Compressed, uint Uncompressed, bool Kraken, uint EvenComp, uint Flags); @@ -42,6 +43,7 @@ private Ps5InnerImage(Ps5OuterFile image, UBlock[] blocks, ulong[] boundaries, l _blocks = blocks; _boundaries = boundaries; Mount = mount; + _defaultReader = new BlockReader(this); } // Logical size of the inner image. @@ -227,26 +229,10 @@ public void ReadAt(long logical, byte[] buffer) } // Streams logical bytes to `sink` one block at a time. - public void CopyTo(long logical, long size, SpanAction sink) - { - if (logical < 0 || size < 0 || size > long.MaxValue - logical) - { - throw new InvalidDataException("A logical range of the inner image overflows."); - } + public void CopyTo(long logical, long size, SpanAction sink) => _defaultReader.CopyTo(logical, size, sink); - var position = logical; - var end = logical + size; - while (position < end) - { - var index = FindBlock(position); - var block = _blocks[index]; - var within = (int)(position - block.Logical); - var count = (int)Math.Min(block.Uncompressed - within, end - position); - LoadBlock(index); - sink(_decoded.AsSpan(within, count)); - position += count; - } - } + // A reader with its own decode buffers, for one thread of a parallel extraction. + internal BlockReader CreateReader() => new(this); public delegate void SpanAction(ReadOnlySpan<byte> chunk); @@ -280,51 +266,84 @@ private int FindBlock(long logical) return index; } - private void LoadBlock(int index) + // Decode state of one thread: the last decoded block and its stored payload. + internal sealed class BlockReader { - if (_cachedIndex == index) - { - return; - } + private readonly Ps5InnerImage _owner; + private int _cachedIndex = -1; + private byte[] _decoded = []; + private byte[] _payload = []; - _cachedIndex = -1; - var block = _blocks[index]; - if (_decoded.Length != block.Uncompressed) - { - _decoded = new byte[block.Uncompressed]; - } + internal BlockReader(Ps5InnerImage owner) => _owner = owner; - if (block.Compressed == 0) + // Streams logical bytes to `sink` one block at a time. + public void CopyTo(long logical, long size, SpanAction sink) { - Array.Clear(_decoded); + if (logical < 0 || size < 0 || size > long.MaxValue - logical) + { + throw new InvalidDataException("A logical range of the inner image overflows."); + } + + var position = logical; + var end = logical + size; + while (position < end) + { + var index = _owner.FindBlock(position); + var block = _owner._blocks[index]; + var within = (int)(position - block.Logical); + var count = (int)Math.Min(block.Uncompressed - within, end - position); + LoadBlock(index); + sink(_decoded.AsSpan(within, count)); + position += count; + } } - else + + private void LoadBlock(int index) { - if (_payload.Length != block.Compressed) + if (_cachedIndex == index) { - _payload = new byte[block.Compressed]; + return; } - _image.ReadExactAt(_payload, block.OnDisk); - if (_payload.Length == _decoded.Length) + _cachedIndex = -1; + var block = _owner._blocks[index]; + if (_decoded.Length != block.Uncompressed) { - _payload.CopyTo(_decoded, 0); + _decoded = new byte[block.Uncompressed]; + } + + if (block.Compressed == 0) + { + Array.Clear(_decoded); } else { - try + if (_payload.Length != block.Compressed) + { + _payload = new byte[block.Compressed]; + } + + _owner._image.ReadExactAt(_payload, block.OnDisk); + if (_payload.Length == _decoded.Length) { - Kraken.DecodeBlock(_payload, block.Flags, block.EvenComp, _decoded); + _payload.CopyTo(_decoded, 0); } - catch (InvalidDataException exception) + else { - throw new InvalidDataException( - $"{exception.Message} (block at logical 0x{block.Logical:X}, stored at 0x{block.OnDisk:X}, {block.Compressed} -> {block.Uncompressed} bytes, flags 0x{block.Flags:X})."); + try + { + Kraken.DecodeBlock(_payload, block.Flags, block.EvenComp, _decoded); + } + catch (InvalidDataException exception) + { + throw new InvalidDataException( + $"{exception.Message} (block at logical 0x{block.Logical:X}, stored at 0x{block.OnDisk:X}, {block.Compressed} -> {block.Uncompressed} bytes, flags 0x{block.Flags:X})."); + } } } - } - _cachedIndex = index; + _cachedIndex = index; + } } // Builds the logical-to-stored block list from the CblockInfo records. diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs index 342c6f048..224dfd967 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs @@ -1,19 +1,25 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Collections.Concurrent; +using System.Runtime.ExceptionServices; using System.Text.Json; namespace SharpEmu.HLE.FileSystem.Pkg; // A fake/debug PS5 package ("\x7FFIH") opened for reading. Retail packages and packages whose outer -// PFS is encrypted are refused at Open: their files need console keys. Extraction streams every -// file block by block, so a package of any size needs only a few hundred KiB of memory. +// PFS is encrypted are refused at Open: their files need console keys. Extraction decodes the files +// block by block on several threads (a big file is split into ranges too), so a package of any +// size needs only a few hundred KiB of memory per worker. public sealed class Ps5Package : IGamePackage { private const string ImageFileName = "pfs_image.dat"; private const string LayoutFileName = "naps_pkg_layout.dat"; // A layout is a few MiB at most; anything larger is not a NAPS file. private const long MaxLayoutSize = 256L << 20; + // Logical range of one parallel work item: large enough to keep seeks rare, small enough that a + // few huge files still spread over every worker. + private const long DefaultChunkBytes = 64L << 20; private readonly Ps5Source _source; private readonly Ps5Fih _fih; @@ -92,8 +98,27 @@ internal void Extract( IProgress<PkgExtractProgress>? progress, CancellationToken cancellation, long progressStepBytes, - long? availableBytes) + long? availableBytes) => + Extract( + destination, + progress, + cancellation, + progressStepBytes, + availableBytes, + DefaultChunkBytes, + Math.Clamp(Environment.ProcessorCount / 2, 1, 8)); + + internal void Extract( + string destination, + IProgress<PkgExtractProgress>? progress, + CancellationToken cancellation, + long progressStepBytes, + long? availableBytes, + long chunkBytes, + int maxParallelism) { + ArgumentOutOfRangeException.ThrowIfLessThan(chunkBytes, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(maxParallelism, 1); var (image, files) = LoadTree(); var total = _filesSize; @@ -121,33 +146,147 @@ internal void Extract( File.WriteAllBytes(path, bytes); } - long done = 0; + targets = DeduplicateTargets(targets); + + // Create every file at its final size first, so workers only write inside existing files and + // never race to create or grow one. + var items = new List<WorkItem>(); foreach (var (path, file) in targets) { cancellation.ThrowIfCancellationRequested(); Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using (var created = File.OpenHandle(path, FileMode.Create, FileAccess.Write, FileShare.None)) + { + MarkSparse(created); + RandomAccess.SetLength(created, file.Size); + } + var relative = Path.GetRelativePath(destination, path); - progress?.Report(new PkgExtractProgress(done, total, relative)); - var sinceReport = 0L; - using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 20, FileOptions.SequentialScan); - image.CopyTo(file.Logical, file.Size, chunk => + for (long offset = 0; offset < file.Size; offset += chunkBytes) { - output.Write(chunk); - done += chunk.Length; - sinceReport += chunk.Length; - cancellation.ThrowIfCancellationRequested(); - if (sinceReport >= progressStepBytes) + items.Add(new WorkItem(path, relative, file.Logical, offset, Math.Min(chunkBytes, file.Size - offset))); + } + } + + progress?.Report(new PkgExtractProgress(0, total, string.Empty)); + var tracker = new ProgressTracker(progress, total, progressStepBytes); + var options = new ParallelOptions { MaxDegreeOfParallelism = maxParallelism, CancellationToken = cancellation }; + try + { + // Load-balanced partitioning hands out one item at a time, so a few big files still keep + // every worker busy. + Parallel.ForEach( + Partitioner.Create(items, loadBalance: true), + options, + image.CreateReader, + (item, _, reader) => { - sinceReport = 0; - progress?.Report(new PkgExtractProgress(done, total, relative)); - } - }); - progress?.Report(new PkgExtractProgress(done, total, relative)); + WriteRange(reader, item, cancellation, tracker); + return reader; + }, + _ => { }); + } + catch (AggregateException aggregate) + { + // Callers catch the specific exception types, not AggregateException. + cancellation.ThrowIfCancellationRequested(); + var inner = aggregate.Flatten().InnerExceptions; + ExceptionDispatchInfo.Capture(inner.FirstOrDefault(e => e is not OperationCanceledException) ?? inner[0]).Throw(); } progress?.Report(new PkgExtractProgress(total, total, string.Empty)); } + private static void WriteRange(Ps5InnerImage.BlockReader reader, WorkItem item, CancellationToken cancellation, ProgressTracker tracker) + { + cancellation.ThrowIfCancellationRequested(); + using var output = File.OpenHandle(item.Path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); + var position = item.Offset; + reader.CopyTo(item.Logical + item.Offset, item.Length, chunk => + { + RandomAccess.Write(output, chunk, position); + position += chunk.Length; + tracker.Add(chunk.Length, item.Relative); + cancellation.ThrowIfCancellationRequested(); + }); + } + + // Two inner files can map to one host path (names differing only by case on Windows). The old + // sequential loop let the later one overwrite the earlier, so only the last occurrence is kept. + private static List<(string Path, Ps5InnerFile File)> DeduplicateTargets(List<(string Path, Ps5InnerFile File)> targets) + { + var seen = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + var kept = new List<(string Path, Ps5InnerFile File)>(targets.Count); + for (var i = targets.Count - 1; i >= 0; i--) + { + if (seen.Add(targets[i].Path)) + { + kept.Add(targets[i]); + } + } + + kept.Reverse(); + return kept; + } + + // Workers write the ranges of one file out of order. NTFS zero-fills everything between the + // last written byte and a write past it, so a non-sparse file would get most of its bytes + // written twice; a sparse file skips that fill. The file ends fully written, so no hole is + // left. Volumes without sparse support (FAT, exFAT) just keep the zero fill. + private static void MarkSparse(Microsoft.Win32.SafeHandles.SafeFileHandle handle) + { + if (OperatingSystem.IsWindows()) + { + _ = DeviceIoControl(handle, FsctlSetSparse, 0, 0, 0, 0, out _, 0); + } + } + + private const uint FsctlSetSparse = 0x000900C4; + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + private static extern bool DeviceIoControl( + Microsoft.Win32.SafeHandles.SafeFileHandle device, + uint controlCode, + nint inBuffer, + uint inBufferSize, + nint outBuffer, + uint outBufferSize, + out uint bytesReturned, + nint overlapped); + + private readonly record struct WorkItem(string Path, string Relative, long Logical, long Offset, long Length); + + // Progress from several threads: bytes add up atomically and a report goes out at most every + // `step` bytes, under a lock, with a BytesDone that never goes backwards. + private sealed class ProgressTracker(IProgress<PkgExtractProgress>? progress, long total, long step) + { + private readonly object _gate = new(); + private long _done; + private long _reported; + + public void Add(int bytes, string file) + { + var done = Interlocked.Add(ref _done, bytes); + if (progress is null || done - Volatile.Read(ref _reported) < step) + { + return; + } + + lock (_gate) + { + // Read again under the lock: other workers may have added bytes meanwhile. + var current = Interlocked.Read(ref _done); + if (current - _reported < step) + { + return; + } + + _reported = current; + progress.Report(new PkgExtractProgress(current, total, file)); + } + } + } + // Opens the inner image and lists its files once; both GetInstalledSize and Extract need them. private (Ps5InnerImage Image, List<Ps5InnerFile> Files) LoadTree() { diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs index 72dea2abf..b422ee602 100644 --- a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs +++ b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs @@ -226,6 +226,72 @@ public void ExtractHonoursCancellation() }); } + [Theory] + [InlineData(4096L, 4)] + [InlineData(0x8000L, 4)] + [InlineData(4096L, 1)] + [InlineData(1L, 3)] + public void ParallelExtractMatchesTheExpectedFiles(long chunkBytes, int parallelism) + { + var built = BuildPackage(new Spec()); + WithPackage(built.Bytes, (package, destination) => + { + var reports = new List<PkgExtractProgress>(); + package.Extract(destination, new CollectingProgress<PkgExtractProgress>(reports.Add), default, 1, null, chunkBytes, parallelism); + + var written = ReadTree(destination); + Assert.Equal(built.ExpectedFiles.Keys.OrderBy(k => k, StringComparer.Ordinal), written.Keys.OrderBy(k => k, StringComparer.Ordinal)); + foreach (var (name, bytes) in built.ExpectedFiles) + { + Assert.True(bytes.AsSpan().SequenceEqual(written[name]), name); + } + + Assert.NotEmpty(reports); + Assert.Equal((built.GameBytes, built.GameBytes), (reports[^1].BytesDone, reports[^1].BytesTotal)); + for (var i = 1; i < reports.Count; i++) + { + Assert.True(reports[i].BytesDone >= reports[i - 1].BytesDone, $"report {i} went backwards"); + } + }); + } + + [Fact] + public void ParallelExtractHonoursCancellationWithoutAnAggregateException() + { + WithPackage(BuildPackage(new Spec()).Bytes, (package, destination) => + { + using var source = new CancellationTokenSource(); + var progress = new CollectingProgress<PkgExtractProgress>(report => + { + if (report.BytesDone > 0) + { + source.Cancel(); + } + }); + Assert.Throws<OperationCanceledException>(() => package.Extract(destination, progress, source.Token, 1, null, 4096, 4)); + }); + } + + [Fact] + public void ParallelExtractRethrowsACorruptBlockAsInvalidData() + { + var built = BuildPackage(new Spec()); + // The Kraken block starts with the seed bytes of the stored image at logical 0x8000: find + // them in the package and break the literal count that follows the 8 seed bytes. + var seed = built.ExpectedFiles["assets/data.bin"].AsSpan(0x100, 8).ToArray(); + // The seed alone also occurs in the periodic test patterns, so match the literal count too. + byte[] needle = [.. seed, 0x00, 0x7F, 0xF8]; + var at = built.Bytes.AsSpan().IndexOf(needle); + Assert.True(at >= 0); + var corrupt = (byte[])built.Bytes.Clone(); + corrupt[at + 8] = 0; + corrupt[at + 9] = 0x10; + corrupt[at + 10] = 0; + + WithPackage(corrupt, (package, destination) => + Assert.Throws<InvalidDataException>(() => package.Extract(destination, null, default, PkgPackage.ProgressStepBytes, null, 4096, 4))); + } + // ---- NAPS ---------------------------------------------------------------------------------- [Fact] From 7e90585965aad63f50b3209dc9db53ee0a849f3b Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:46:07 +0000 Subject: [PATCH 35/64] [Merge] Bump the split protocol to 9 for the haptic rumble message GamepadOutputMessage grew a DurationMs field (40 -> 44 bytes) for GpuSplitGamepadOutput.HapticRumble; version 8 is now refused like the older ones. --- src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs | 5 +++-- tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs | 3 ++- tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs index 1112d82a0..97e20e199 100644 --- a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs +++ b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs @@ -13,8 +13,9 @@ public static class GpuRemoteProtocol /// 3: <see cref="GpuRemoteMessage.TessellationRings"/>. /// 4: frame-boundary messages. 5: input-change and display reservations. /// 6: pending-writeback pages. 7: combined frame, input and writeback layout. - /// 8: <see cref="GpuRemoteSyncOpcode.ResidencyRange"/>.</remarks> - public const uint Version = 8; + /// 8: <see cref="GpuRemoteSyncOpcode.ResidencyRange"/>. + /// 9: <see cref="GpuSplitGamepadOutput.HapticRumble"/> and <see cref="GamepadOutputMessage.DurationMs"/>.</remarks> + public const uint Version = 9; } diff --git a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs index 53ddcf75a..c082716c7 100644 --- a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs @@ -88,13 +88,14 @@ public void AttachRefusesAnotherProtocolVersion() [InlineData(5u)] [InlineData(6u)] [InlineData(7u)] + [InlineData(8u)] public void CombinedLayoutRefusesEveryIndependentRecoveryProtocol(uint version) { if (!OperatingSystem.IsMacOS()) return; using var host = GpuRemoteChannel.Create(SharedMemoryRegion.CreateUniqueName("setest")); using (var raw = SharedMemoryRegion.Open(host.Name)) ((RegionHeader*)raw.Pointer)->Version = version; - Assert.Equal(8u, GpuRemoteProtocol.Version); + Assert.Equal(9u, GpuRemoteProtocol.Version); Assert.Throws<InvalidDataException>(() => GpuRemoteChannel.Attach(host.Name)); } diff --git a/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs b/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs index 8b2cecf24..0e7ced742 100644 --- a/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs @@ -216,7 +216,7 @@ public void SplitPayloadsKeepTheirSizesOnEveryArchitecture() Assert.Equal(32, sizeof(SubmitCommandStreamMessage)); Assert.Equal(40, sizeof(FlipRequestMessage)); Assert.Equal(40, sizeof(ProtectRequestMessage)); - Assert.Equal(40, sizeof(GamepadOutputMessage)); + Assert.Equal(44, sizeof(GamepadOutputMessage)); Assert.Equal(48, sizeof(DisplayBufferResponse)); Assert.Equal(64, sizeof(ReserveFlipResponse)); Assert.Equal(32, sizeof(SpanRequest)); From 49dc2db8348af5ec38e860f0c403cbb3ff4f4c48 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:46:07 +0000 Subject: [PATCH 36/64] [Metal] Take IRenderHost.TryReplayDispatch's replaceTable and miss on a replaced table Upstream added the replaceTable parameter; the 2-argument Metal method no longer implemented the interface, so every dispatch replay answered with the interface default (false). A stage that differs only in its flattened table now misses as 'table' and records in full, as before the merge. --- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs index a53b4b41c..a1647f1a1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs @@ -195,7 +195,7 @@ private enum ReplayRefusal private enum ReplayMiss { - Off, Unsealed, Serial, Scope, Stages, Images, Buffers, Vertex, Patch, Count, + Off, Unsealed, Serial, Scope, Stages, Images, Buffers, Vertex, Patch, Table, Count, } private static readonly string[] ReplayRefusalNames = @@ -204,7 +204,7 @@ private enum ReplayMiss "argument_field", "traces", "memo_off", "epoch_moved", "vertex_map", "labels", "thread_limits", "not_in_place", "bindings", ]; - private static readonly string[] ReplayMissNames = ["off", "unsealed", "serial", "scope", "stages", "images", "buffers", "vertex", "patch"]; + private static readonly string[] ReplayMissNames = ["off", "unsealed", "serial", "scope", "stages", "images", "buffers", "vertex", "patch", "table"]; private readonly long[] _drawCaptureRefusals = new long[(int)ReplayRefusal.Count]; private readonly long[] _dispatchCaptureRefusals = new long[(int)ReplayRefusal.Count]; @@ -934,7 +934,9 @@ public bool TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan<uint> vertexU return true; } - public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage) + // replaceTable (the stage differs from the sealed one only in its flattened resource table) is not replayed here: + // the replay rebinds the captured table, so such a dispatch misses and records in full. + public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage, bool replaceTable) { var capture = _dispatchReplay; if (!DispatchReplayEnabled) @@ -950,6 +952,11 @@ public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResource } capture.Sealed = false; + if (replaceTable) + { + return MissDispatch(ReplayMiss.Table); + } + if (_commandBuffer == 0 || capture.Serial != _submissionSerial) { return MissDispatch(ReplayMiss.Serial); From 55dedb1855cfb1397139efa4efe4f8ada8cef06a Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:46:07 +0000 Subject: [PATCH 37/64] [GPU] Bound a repeated indexed draw's emission like the full resolve TryRepeatIndexed (upstream) left DrawEmission.IndirectIndexLimit at its default; DrawIndexedCore sets it to the index count unless the buffer is unbounded. RepeatDrawTests compare the two records. --- src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs index 5602b4298..a73f1c16d 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs @@ -656,7 +656,9 @@ internal bool TryRepeatIndexed(ResolvedDraw template, ulong submitId, RegisterBa drawn.BaseVertex + (drawn.BaseVertexInRegister ? ResolveVertexOffset(0, vertexInput) : 0), 0, drawn.FirstInstance + (drawn.FirstInstanceInRegister ? ResolveInstanceOffset(vertexInput) : 0), - drawn.IndirectArgumentsAddress); + drawn.IndirectArgumentsAddress, + // As DrawIndexedCore bounds it (the fork's IndirectIndexLimit); a repeatable draw expands no indices. + drawn.UnboundedIndexBuffer ? uint.MaxValue : drawn.IndexCount); record.PacketAddress = drawn.PacketAddress; Record(record); return true; From ca65d8df84010581d894293371de1a67ccc09c24 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:46:08 +0000 Subject: [PATCH 38/64] [Tests] Adapt merged tests to the fork's behaviour and upstream's new semantics - FontPackageBoundaryTests: Libs now references SkiaSharp (upstream overlay kit); check that no SharpEmu.Libs.Font type touches a Skia type instead of the assembly reference. - DeferredDispatchRunTests rollback: turn off the fork's dispatch overlap marking (initiator bit 31) for this rollback test. - GnmEndOfPipeTests: the fork decodes EOP fields on their own, so an AGC low-dword timestamp with write-back lands as WriteBack32 instead of being rejected. - AgcPackedRegisterPacketTests: the fork coalesces SH register runs (one state read, one write, one cursor move). - CommandStreamQueueTests: a release now yields to older compute work first (upstream release order), so the recorded label lands a slice later. - ImeDialogExportsTests: run the keyboard-less path (SHARPEMU_IME_AUTOFILL=1). - AmprHeaderWriteRefusalTests: SetBuffer reads the header's data pointer for upstream's busy check. - AudioOut2QueueTests: the first output primes the dropout reserve with silence before the grain. --- .../Agc/AgcPackedRegisterPacketTests.cs | 6 +++--- .../Ampr/AmprHeaderWriteRefusalTests.cs | 14 +++++++++++-- .../FontPackageBoundaryTests.cs | 21 ++++++++++++++++++- .../Audio/AudioOut2QueueTests.cs | 3 ++- .../GpuCommands/CommandStreamQueueTests.cs | 15 +++++++++---- .../GpuCommands/DeferredDispatchRunTests.cs | 3 +++ .../Ime/ImeDialogExportsTests.cs | 9 +++++++- .../Loader/GnmEndOfPipeTests.cs | 11 +++++++--- 8 files changed, 67 insertions(+), 15 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs index 7729c15bf..cc93cd4c1 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcPackedRegisterPacketTests.cs @@ -139,9 +139,9 @@ public void EachPacketTakesOneAllocationAndOneWrite() Assert.Equal(PacketAddress, EmitShRegisters(memory, entries.Length)); - // One read of the entries; each of the two packets (registers 0x10-0x12, then 0x20) reads the buffer state, moves - // the cursor and is written. - Assert.Equal((3, 4, 2), (memory.Reads, memory.Writes, memory.CursorWrites)); + // One read of the entries. The fork coalesces the call's runs (AgcExports.CoalesceShRegisterRuns, default on): both + // packets (registers 0x10-0x12, then 0x20) take one buffer-state read, one write and one cursor move together. + Assert.Equal((2, 2, 1), (memory.Reads, memory.Writes, memory.CursorWrites)); Assert.Equal(PacketAddress + 32, ReadUInt64(memory.Inner, CursorAddress)); memory.ResetCounts(); diff --git a/tests/SharpEmu.Libs.Tests/Ampr/AmprHeaderWriteRefusalTests.cs b/tests/SharpEmu.Libs.Tests/Ampr/AmprHeaderWriteRefusalTests.cs index 6b709617b..ef58bd39f 100644 --- a/tests/SharpEmu.Libs.Tests/Ampr/AmprHeaderWriteRefusalTests.cs +++ b/tests/SharpEmu.Libs.Tests/Ampr/AmprHeaderWriteRefusalTests.cs @@ -117,8 +117,18 @@ private sealed class HeaderMemory : ICpuMemory { internal readonly List<(ulong Address, int Count)> Writes = []; internal int FailAttempt; - public bool TryRead(ulong address, Span<byte> destination) => - throw new InvalidOperationException("Header writes must not read guest memory or the supplied data buffer."); + // SetBuffer reads the header's own data pointer first to refuse a buffer that is still attached (upstream's busy + // check); the header reads as unattached. Any other read (the supplied data buffer) is still refused. + public bool TryRead(ulong address, Span<byte> destination) + { + if (address >= Header && address + (ulong)destination.Length <= Header + 24) + { + destination.Clear(); + return true; + } + + throw new InvalidOperationException("Header writes must not read guest memory outside the header or the supplied data buffer."); + } public bool TryWrite(ulong address, ReadOnlySpan<byte> source) { Writes.Add((address, source.Length)); diff --git a/tests/SharpEmu.Libs.Tests/ArchitectureRules/FontPackageBoundaryTests.cs b/tests/SharpEmu.Libs.Tests/ArchitectureRules/FontPackageBoundaryTests.cs index 3d2535333..6e8b6317c 100644 --- a/tests/SharpEmu.Libs.Tests/ArchitectureRules/FontPackageBoundaryTests.cs +++ b/tests/SharpEmu.Libs.Tests/ArchitectureRules/FontPackageBoundaryTests.cs @@ -11,7 +11,26 @@ public sealed class FontPackageBoundaryTests [Fact] public void SharedGuestFontAbiHasNoSkiaAssemblyReference() { - Assert.DoesNotContain(typeof(FontExports).Assembly.GetReferencedAssemblies(), reference => reference.Name!.StartsWith("Skia")); + // SharpEmu.Libs references SkiaSharp for upstream's in-game overlay kit (Overlay/, the IME keyboard and save-data + // layers), so the rule is held at the guest font ABI itself: no SharpEmu.Libs.Font type touches a Skia type. + const System.Reflection.BindingFlags all = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly; + static bool IsSkia(Type? type) => type is not null && + ((type.Namespace?.StartsWith("Skia") ?? false) || (type.HasElementType && IsSkia(type.GetElementType())) || + (type.IsGenericType && type.GetGenericArguments().Any(IsSkia))); + var fontTypes = typeof(FontExports).Assembly.GetTypes() + .Where(type => type.Namespace?.StartsWith("SharpEmu.Libs.Font", StringComparison.Ordinal) == true).ToArray(); + Assert.NotEmpty(fontTypes); + foreach (var type in fontTypes) + { + Assert.False(IsSkia(type.BaseType), type.FullName); + Assert.DoesNotContain(type.GetFields(all), field => IsSkia(field.FieldType)); + Assert.DoesNotContain(type.GetProperties(all), property => IsSkia(property.PropertyType)); + Assert.DoesNotContain(type.GetMethods(all), method => + IsSkia(method.ReturnType) || method.GetParameters().Any(parameter => IsSkia(parameter.ParameterType)) || + (method.GetMethodBody()?.LocalVariables.Any(local => IsSkia(local.LocalType)) ?? false)); + } + Assert.DoesNotContain(typeof(IFontFactory).Assembly.GetReferencedAssemblies(), reference => reference.Name!.StartsWith("SharpEmu.") || reference.Name!.StartsWith("Skia")); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2QueueTests.cs b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2QueueTests.cs index 910664e1d..466f74485 100644 --- a/tests/SharpEmu.Libs.Tests/Audio/AudioOut2QueueTests.cs +++ b/tests/SharpEmu.Libs.Tests/Audio/AudioOut2QueueTests.cs @@ -127,7 +127,8 @@ public void SilentGrainsAfterDeviceAudioStillHoldTheQueue() SetPcmAttribute(port, LongGrain); Advance(context); Assert.Equal(0, Push(context, NonBlocking)); - Assert.Single(stream.Submissions); + // The first output primes the dropout reserve with silence before the grain (upstream's AudioOut2 reserve). + Assert.Equal(2, stream.Submissions.Count); // Grains with no audio that follow occupy the queue on the context's clock; reporting the // empty device instead made Wwise render a full queue every update. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs index 3c0765714..d14665755 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs @@ -405,12 +405,19 @@ public void AnotherQueuesRecordedLabelSatisfiesAWaitUntilItLands() Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); Enqueue(host, queue, Graphics, 2, ReleaseMemoryInterrupt(Label, 1)); - Assert.Equal(SliceResult.Completed, queue.ProcessOne()); - // The GPU has not written the label, yet the compute head goes on. - Assert.Equal(0u, host.ReadDword(Label)); - Assert.Equal(SliceResult.Completed, queue.ProcessOne()); + // The release first lets the older compute submission run (upstream's release order, YieldToOlderWork); that head + // is still blocked on the label, so the release then lands as a recorded label. The GPU has not written the label, + // yet the compute head goes on. + var results = new List<SliceResult>(); + while (host.ReadDword(Label + 8) != 7u && results.Count < 8) + { + results.Add(queue.ProcessOne()); + } + Assert.Equal(7u, host.ReadDword(Label + 8)); + Assert.Equal(0u, host.ReadDword(Label)); + Assert.Equal(SliceResult.Completed, results[^1]); // Once that tick completes the label is memory's business again: the slot still // holds 0, so a later wait on it sleeps instead of seeing the old value. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs index 0f7e8d2bc..65d0bc496 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredDispatchRunTests.cs @@ -99,6 +99,9 @@ public void RollbackRunsThePacketsAgainFromThePoisonedMemberWithItsRegisters() var runner = new StreamRunner(); var runs = new FakeRuns(runner.Interpreter) { RewindTo = 1 }; runner.Host.DispatchRuns = runs; + // The fork marks a dispatch reached through user data alone as one that may overlap the one before it (bit 31 of + // the initiator, DispatchOverlap); this test is about the rollback, so the initiators are compared unmarked. + runner.Interpreter.TrackDispatchOverlap = false; runner.Run( UserData(0xA), Dispatch(1), diff --git a/tests/SharpEmu.Libs.Tests/Ime/ImeDialogExportsTests.cs b/tests/SharpEmu.Libs.Tests/Ime/ImeDialogExportsTests.cs index 0316acc6b..d174c11bb 100644 --- a/tests/SharpEmu.Libs.Tests/Ime/ImeDialogExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Ime/ImeDialogExportsTests.cs @@ -35,20 +35,27 @@ public sealed class ImeDialogExportsTests : IDisposable private readonly FakeCpuMemory _memory = new(Base, 0x1000); private readonly CpuContext _ctx; + private const string AutofillVariable = "SHARPEMU_IME_AUTOFILL"; private readonly string? _savedText; + private readonly string? _savedAutofill; + // These tests cover the keyboard-less Running -> Finished path (SHARPEMU_IME_AUTOFILL=1). Without it Init opens the + // on-screen keyboard, whose close reads the host pad (SystemDialogInput.Release), which an arm64 test host cannot create. public ImeDialogExportsTests() { _ctx = new CpuContext(_memory, Generation.Gen5); _savedText = Environment.GetEnvironmentVariable(ImeDialogExports.DefaultTextEnvironmentVariable); + _savedAutofill = Environment.GetEnvironmentVariable(AutofillVariable); Environment.SetEnvironmentVariable(ImeDialogExports.DefaultTextEnvironmentVariable, null); + Environment.SetEnvironmentVariable(AutofillVariable, "1"); ImeDialogExports.ResetForTests(); } public void Dispose() { - Environment.SetEnvironmentVariable(ImeDialogExports.DefaultTextEnvironmentVariable, _savedText); ImeDialogExports.ResetForTests(); + Environment.SetEnvironmentVariable(ImeDialogExports.DefaultTextEnvironmentVariable, _savedText); + Environment.SetEnvironmentVariable(AutofillVariable, _savedAutofill); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs b/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs index 9fe5aadfd..1ea1b42e5 100644 --- a/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Loader/GnmEndOfPipeTests.cs @@ -42,13 +42,18 @@ public void GnmEndOfPipeLowDword_TimestampWritesThirtyTwoBits(uint eventType, ui Assert.Equal(0xFFFF_FFFF_5566_7788UL, runner.Host.ReadQword(Label)); } + // Upstream keeps a list of accepted AGC event/action/index combinations and rejects this one. The fork decodes each + // EOP field on its own (GpuCommandInterpreter.WriteEndOfPipe): a timestamp event with a write-back cache action + // lands the low dword as a write-back, on AGC as on GNM. [Fact] - public void AgcEndOfPipeLowDword_WriteBackTimestampStaysRejected() + public void AgcEndOfPipeLowDword_WriteBackTimestampLandsTheLowDword() { var runner = new StreamRunner(); + runner.Host.WriteQword(Label, 0xFFFF_FFFF_FFFF_FFFF); - var fatal = runner.RunExpectingFatal(EventWriteEop(0x04, 5, 0x38, 1, 0, Label, 0x1122_3344_5566_7788)); + runner.Run(EventWriteEop(0x04, 5, 0x38, 1, 0, Label, 0x1122_3344_5566_7788)); - Assert.Contains("type=0x04", fatal.Message); + Assert.Equal(EndOfPipeWriteKind.WriteBack32, Assert.Single(runner.Host.EndOfPipeWrites).Kind); + Assert.Equal(0xFFFF_FFFF_5566_7788UL, runner.Host.ReadQword(Label)); } } From 55091a490759ff00c427f366b7b7ec79004573f7 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:57:18 +0000 Subject: [PATCH 39/64] [Shader] Refine the MSL integer reciprocal with one fma Newton step Port of upstream 5036e2761. V_RCP_IFLAG_F32 lowered to a plain 1.0f / x, which Metal returns one ulp above the correctly rounded reciprocal for 708 of 8012 inputs (device sweep), the error upstream saw break AMD's unsigned division sequence on NVIDIA. One fma Newton step now refines it; an infinite, NaN or zero result keeps the division's. Device tests cover the reciprocal against IEEE 1/x and the gfx1011 udiv sequence for exact quotients. --- .../Gen5MslTranslator.Alu.cs | 14 +- .../Gen5MslDivisionTests.cs | 156 +++++++++++++++++- 2 files changed, 167 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs index 6982858e3..cd1f81b24 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs @@ -336,7 +336,7 @@ private bool TryEmitVectorValue( : _options.FastReciprocals ? $"fast::divide(1.0f, sharpemu_flush_f32_denorm({F(instruction, 0)}))" : $"(1.0f / sharpemu_flush_f32_denorm({F(instruction, 0)}))"), - "VRcpIflagF32" => FloatResult(instruction, $"(1.0f / {F(instruction, 0)})"), + "VRcpIflagF32" => FloatResult(instruction, EmitIntegerReciprocal(F(instruction, 0))), "VLogF32" => InvalidNanF32Result(instruction, "fast::log2"), "VExpF32" => FloatResult(instruction, $"fast::exp2(sharpemu_flush_f32_denorm({F(instruction, 0)}))"), // GCN sin/cos take revolutions; reduce to one cycle first, then mirror @@ -1067,6 +1067,18 @@ private string EmitCvtPkU8F32(Gen5ShaderInstruction instruction) return $"(({baseValue} & ~(0xFFu << {offset})) | (({converted} & 0xFFu) << {offset}))"; } + // V_RCP_IFLAG_F32, the reciprocal estimate of AMD's integer division, whose corrections can return a wrong quotient + // from a reciprocal one ulp above the correctly rounded one. Metal's 1.0f / x is one ulp high for 708 of 8012 + // inputs (Gen5MslDivisionTests), so one fma Newton step refines it to the correctly rounded value (upstream + // 5036e2761); an infinite, NaN or zero quotient keeps the division's result. + private string EmitIntegerReciprocal(string source) + { + var value = Temp("float", source); + var estimate = Temp("float", $"(1.0f / {value})"); + var refined = $"fma({estimate}, fma(-{value}, {estimate}, 1.0f), {estimate})"; + return $"((isinf({estimate}) || isnan({estimate}) || {estimate} == 0.0f) ? {estimate} : {refined})"; + } + private string EmitCvtPkrtzF16F32(Gen5ShaderInstruction instruction) { var first = TruncateFloat32ForPack(F(instruction, 0)); diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslDivisionTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslDivisionTests.cs index 6c4aebccc..d48114c3e 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslDivisionTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslDivisionTests.cs @@ -59,6 +59,87 @@ public sealed class Gen5MslDivisionTests(ITestOutputHelper output) 0xBF810000, // s_endpgm ]; + // `udiv i32` as llc -mcpu=gfx1011 lowers it, with the V_RCP_IFLAG_F32 its AMDGPU expansion takes as the reciprocal + // estimate (newer LLVM spells it V_RCP_F32): the estimate, scaled just under 2^32, refined once in integers and + // corrected twice. A reciprocal above the correctly rounded one can push the estimate past the true quotient, and the + // unsigned corrections then return a wrong quotient (upstream 5036e2761: divisors 27012373 and 91382283 on NVIDIA). + private static readonly uint[] UnsignedDivision = + [ + 0x342A0083, // v_lshlrev_b32 v21, 3, v0 (local id * 8) + 0xE0341000, 0x80020015, // buffer_load_dwordx2 v[0:1], v21, s[8:11], 0 offen (n, d) + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0x7E040D01, // v_cvt_f32_u32 v2, v1 + 0x4C060280, // v_sub_nc_u32 v3, 0, v1 + 0x7E045702, // v_rcp_iflag_f32 v2, v2 + 0x100404FF, 0x4F7FFFFE, // v_mul_f32 v2, 0x4f7ffffe, v2 + 0x7E040F02, // v_cvt_u32_f32 v2, v2 + 0xD5690003, 0x02020503, // v_mul_lo_u32 v3, v3, v2 + 0xD56A0003, 0x02020702, // v_mul_hi_u32 v3, v2, v3 + 0x4A040702, // v_add_nc_u32 v2, v2, v3 + 0xD56A0002, 0x02020500, // v_mul_hi_u32 v2, v0, v2 + 0xD5690003, 0x02020302, // v_mul_lo_u32 v3, v2, v1 + 0x4C000700, // v_sub_nc_u32 v0, v0, v3 + 0x4A060481, // v_add_nc_u32 v3, 1, v2 + 0x4C080300, // v_sub_nc_u32 v4, v0, v1 + 0x7D8C0300, // v_cmp_ge_u32 vcc, v0, v1 + 0x02040702, // v_cndmask_b32 v2, v2, v3, vcc + 0x02000900, // v_cndmask_b32 v0, v0, v4, vcc + 0x4A060481, // v_add_nc_u32 v3, 1, v2 + 0x7D8C0300, // v_cmp_ge_u32 vcc, v0, v1 + 0x02000702, // v_cndmask_b32 v0, v2, v3, vcc + 0xE0701000, 0x80020015, // buffer_store_dword v0, v21, s[8:11], 0 offen + 0xBF810000, // s_endpgm + ]; + + private static readonly uint[] IntegerReciprocal = + [ + 0x342A0082, // v_lshlrev_b32 v21, 2, v0 (local id * 4) + 0xE0301000, 0x80020015, // buffer_load_dword v0, v21, s[8:11], 0 offen + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0x7E005700, // v_rcp_iflag_f32 v0, v0 + 0xE0701000, 0x80020015, // buffer_store_dword v0, v21, s[8:11], 0 offen + 0xBF810000, // s_endpgm + ]; + + // Every quotient of the integer division sequence is exact. + [Fact] + public void UnsignedDivisionThroughTheIntegerReciprocalIsExact() + { + var shader = Gen5ComputeFixtures.CompileRequestOrThrow( + new Gen5ComputeFixture("udiv-u32", UnsignedDivision, StoreScalarResourceBase: 8, StoreBackingBytes: Threads * 8), + localSizeX: Threads); + if (!DeviceGateOpen()) + { + return; + } + + var inputs = UnsignedDivisionInputs(); + var results = Run(shader, inputs.Select(pair => ((ulong)pair.N, (ulong)pair.D)).ToList(), 8, 4); + Report(inputs.Count, Enumerable.Range(0, inputs.Count) + .Select(index => ((ulong)inputs[index].N, (ulong)inputs[index].D, results[index], (ulong)(inputs[index].N / inputs[index].D)))); + } + + // V_RCP_IFLAG_F32 of a normal input with a normal reciprocal is the correctly rounded 1/x, which a plain division + // does not guarantee on every device (upstream 5036e2761 refines it with one fma Newton step); infinity, NaN and zero + // keep the division's result. + [Fact] + public void IntegerReciprocalIsCorrectlyRounded() + { + var shader = Gen5ComputeFixtures.CompileRequestOrThrow( + new Gen5ComputeFixture("rcp-iflag", IntegerReciprocal, StoreScalarResourceBase: 8, StoreBackingBytes: Threads * 4), + localSizeX: Threads); + Assert.Contains("fma(", shader.Source, StringComparison.Ordinal); + if (!DeviceGateOpen()) + { + return; + } + + var inputs = ReciprocalInputs(); + var results = Run(shader, inputs.Select(value => ((ulong)value, 0ul)).ToList(), 4, 4); + Report(inputs.Count, Enumerable.Range(0, inputs.Count) + .Select(index => ((ulong)inputs[index], 0ul, results[index], (ulong)Reciprocal(inputs[index])))); + } + [Fact] public void Float64DivisionSequenceIsCorrectlyRounded() { @@ -112,7 +193,7 @@ private void Report(int count, IEnumerable<(ulong N, ulong D, ulong Actual, ulon Assert.True(failures == 0, $"{failures} of {count} mismatched:\n{mismatches}"); } - // Each record holds n then d, `stride` bytes apart; the quotient overwrites n. + // Each record holds n then d (a 4-byte record holds n alone), `stride` bytes apart; the result overwrites n. private static ulong[] Run(Gen5MslShader shader, List<(ulong N, ulong D)> inputs, int stride, int size) { Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var error), error + shader.Source); @@ -133,7 +214,10 @@ private static ulong[] Run(Gen5MslShader shader, List<(ulong N, ulong D)> inputs else { BinaryPrimitives.WriteUInt32LittleEndian(record, (uint)n); - BinaryPrimitives.WriteUInt32LittleEndian(record[4..], (uint)d); + if (stride >= 8) + { + BinaryPrimitives.WriteUInt32LittleEndian(record[4..], (uint)d); + } } } @@ -341,6 +425,74 @@ private static uint Float32Quotient(uint n, uint d) return inputs; } + private static uint Reciprocal(uint bits) + { + var value = BitConverter.UInt32BitsToSingle(bits); + return float.IsNaN(value) ? bits | 0x00400000 : BitConverter.SingleToUInt32Bits(1f / value); + } + + private static List<(uint N, uint D)> UnsignedDivisionInputs() + { + var random = new Random(0x0D1F0032); + var divisors = new List<uint> { 1, 2, 3, 5, 7, 10, 255, 256, 65535, 65536, 65537, 27012373, 91382283, 0x7FFFFFFF, + 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF }; + for (var bit = 2; bit < 32; bit++) + { + divisors.Add((1u << bit) - 1); + divisors.Add((1u << bit) + 1); + } + + var inputs = new List<(uint, uint)>(); + foreach (var d in divisors) + { + // Numerators around the divisor's multiples, where an estimate one too high or low shows. + foreach (var n in new uint[] { 0, 1, d - 1, d, d + 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF }) + { + inputs.Add((n, d)); + } + + for (var i = 0; i < 48; i++) + { + var multiple = (ulong)random.NextInt64(0, (long)(uint.MaxValue / d) + 1) * d; + inputs.Add(((uint)Math.Min(multiple + (ulong)random.Next(-1, 2), uint.MaxValue), d)); + inputs.Add(((uint)random.NextInt64(0, 1L << 32), d)); + } + } + + for (var i = 0; i < 4000; i++) + { + // Divisors of every width. + var d = (uint)random.NextInt64(1, 1L << random.Next(1, 33)); + inputs.Add(((uint)random.NextInt64(0, 1L << 32), Math.Max(d, 1u))); + } + + return inputs; + } + + private static List<uint> ReciprocalInputs() + { + var random = new Random(0x0D1F0033); + var inputs = new List<uint> { 0x00000000, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00000 }; + foreach (var integer in new uint[] { 27012373, 91382283, 1, 3, 7, 0xFFFFFFFF, 0x80000001 }) + { + inputs.Add(BitConverter.SingleToUInt32Bits(integer)); + } + + for (var i = 0; i < 4000; i++) + { + // The u32 conversions the integer division takes the reciprocal of, every width. + inputs.Add(BitConverter.SingleToUInt32Bits((uint)random.NextInt64(1, 1L << random.Next(1, 33)))); + } + + for (var i = 0; i < 4000; i++) + { + // Normal inputs whose reciprocal is normal too. + inputs.Add(Normal32(random, 1, 252)); + } + + return inputs; + } + private static ulong Bits64(Random random) => (ulong)random.NextInt64() ^ ((ulong)random.Next(2) << 63); private static ulong Normal64(Random random, int minimumExponent, int maximumExponent) => From 97176db7d736e0969ff9ccd1e2082bacc2082758 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:57:18 +0000 Subject: [PATCH 40/64] [Shader] Mark the compiled branch selection's reads of a plan that writes memory Upstream c30081163 selects a plan's resource branches on lowered registers (MaterializationProgram.BranchSelection) instead of the evaluator. For a plan that writes memory the evaluator read every predicate and written descriptor through ResourceBranchWriteGuard, which sets ReadingWords; the compiled walk read them bare, so the Metal host waited for a GPU write still landing in such a word instead of refusing it (SHARPEMU_GUARD_READS_REFUSE_PENDING, the Demon's Souls stream stall fix). The walk now marks those reads the same way. --- .../MaterializationProgram.Branches.cs | 19 ++++++++++- .../Resources/ResourceBranchTests.cs | 34 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs index a47b71738..7e792e2e0 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.Branches.cs @@ -360,6 +360,23 @@ private bool EvaluateStep(in Step step, ResourceRuntimeInputs inputs, GuestWordR } } + // A plan that writes memory reads every predicate and written descriptor word through its write guard, which marks + // the read (ResourceBranchWriteGuard.ReadingWords) so a host whose clean reader would wait for a GPU write still + // landing in the word refuses it instead (Metal: MetalRenderHost.RefusesPendingGuardRead). The selection reads the + // same words, so it marks them too. + private bool ReadWord(GuestWordReader clean, ulong address, out uint word) + { + if (!_guarded) + { + return clean(address, out word); + } + + using (ResourceBranchWriteGuard.EnterReads()) + { + return clean(address, out word); + } + } + // RuntimeValueEvaluator.EvaluateRawRead and ReadRawWord: the handle's low and high words, the offset, then a buffer's // records and word 3, and one aligned dword. Every predicate reader is clean, so a refused word reads as zero only // through a null base. @@ -387,7 +404,7 @@ private bool ReadClean(in ReadStep read, ResourceRuntimeInputs inputs, GuestWord return true; } - if (!clean(address, out var word)) + if (!ReadWord(clean, address, out var word)) { return (baseAddress & ~3ul) == 0; } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs index 89c8bc9e7..d6ba57397 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs @@ -695,6 +695,40 @@ bool Reentering(ulong address, out uint word) Assert.Equal(1, nested); } + // A plan that writes memory marks every word its selection reads (ResourceBranchWriteGuard.ReadingWords), through the + // compiled selection as through the evaluator's write guard, so a host refuses a word a GPU write still owns instead of + // waiting for it; a plan without writes reads unmarked. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AGuardedSelectionMarksEveryWordItReads(bool writes) + { + var plan = writes ? ExtractWithWrites(CountedSampleThenStore(), true) : Extract(LoadedPredicate()); + Assert.Equal(writes, plan.ResourceBranchesWithWrites); + var memory = new WordMemory(); + memory.Words[0x1000] = 0; + memory.Words[0x3000] = 1; + var marks = new List<bool>(); + bool Marking(ulong address, out uint word) + { + marks.Add(ResourceBranchWriteGuard.ReadingWords); + return memory.Read(address, out word); + } + + uint[] userData = writes + ? [0x1000, 0, 16, 0, 0x1800, 0, 64, 0, .. VolumeImage, 0, 0, 0, 0] + : [.. UserData(0), 0, 0, 0, 0x3000, 0]; + var selection = Assert.IsType<MaterializationProgram.BranchSelection>(plan.BranchSelection); + Assert.True(selection.TrySelect(Inputs(userData, GeneralRead, Marking), new bool[selection.SourceCount])); + var compiled = marks.ToArray(); + marks.Clear(); + RuntimeValueEvaluator.EvaluateActiveSources(plan, Inputs(userData, GeneralRead, Marking)); + Assert.NotEmpty(compiled); + Assert.All(compiled, mark => Assert.Equal(writes, mark)); + Assert.Equal(compiled, marks); + Assert.False(ResourceBranchWriteGuard.ReadingWords); + } + // A T# whose halves are scalar buffer reads at a uniform record offset is evaluated word by word; the arm that reads it // is pruned like any other, through the program's full and fast paths. [Theory] From 65efef1b7407123fd7412e60e09c6572c8dbc475 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:57:18 +0000 Subject: [PATCH 41/64] [Tests] Vertex programs keep each float rounding in MSL, as upstream's contraction test checks The Metal twin of upstream's Gen5FloatContractionTests (cb790c35e): a vertex program keeps #pragma clang fp contract(off) even when SHARPEMU_MSL_CONTRACT=1 lets pixel and compute programs fuse. --- .../Gen5ComputeFixtures.cs | 9 +++++---- .../MetalRuntimeTests.cs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs index f74f69190..ecbb7120b 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs @@ -366,8 +366,8 @@ internal static class Gen5ComputeFixtures 0xBF810000, // s_endpgm ]; - public static Gen5MslShader CompileVertexOrThrow(int requiredVertexOutputCount = 0) => - CompileStageRequestOrThrow(VertexWords, ShaderStage.Vertex, requiredVertexOutputCount); + public static Gen5MslShader CompileVertexOrThrow(int requiredVertexOutputCount = 0, Gen5MslCodegenOptions? options = null) => + CompileStageRequestOrThrow(VertexWords, ShaderStage.Vertex, requiredVertexOutputCount, options); public static Gen5MslShader CompilePixelOrThrow( Gen5PixelOutputKind outputKind = Gen5PixelOutputKind.Float, @@ -974,7 +974,8 @@ public static ShaderCompileRequest CreateComputeRequest(Gen5ComputeFixture fixtu floatMode: floatMode); } - public static Gen5MslShader CompileStageRequestOrThrow(uint[] words, ShaderStage stage, int requiredVertexOutputCount = 0) + public static Gen5MslShader CompileStageRequestOrThrow(uint[] words, ShaderStage stage, int requiredVertexOutputCount = 0, + Gen5MslCodegenOptions? options = null) { var memory = new FakeGuestMemory(); memory.AddRegion(ProgramAddress, words); @@ -985,7 +986,7 @@ public static Gen5MslShader CompileStageRequestOrThrow(uint[] words, ShaderStage } var request = RequestOrThrow(program!, stage, requiredVertexOutputCount: requiredVertexOutputCount); - if (!Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error)) + if (!Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error, options)) { throw new InvalidOperationException($"[{stage}] MSL request emit failed: {error}"); } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs index 5db948f39..b27a3f675 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeTests.cs @@ -552,6 +552,25 @@ public void OnlyAQueueDrainingLoopIsMarkedPersistentThreads() Assert.False(Gen5ComputeFixtures.CompileRequestOrThrow(Gen5ComputeFixtures.Loop).PersistentThreads); } + // A depth prepass and the pass that tests its depth for equality compute one position in two programs; a compiler that + // fuses a multiply with an add in only one of them moves a vertex by an ulp and the second pass drops the triangle. A + // program before rasterization keeps each operation's rounding even when pixel and compute programs may fuse + // (SHARPEMU_MSL_CONTRACT=1); the twin of upstream's Gen5FloatContractionTests (cb790c35e). + [Fact] + public void ProgramsBeforeRasterizationKeepEachFloatRounding() + { + const string KeepRounding = "#pragma clang fp contract(off)"; + foreach (var contract in new[] { false, true }) + { + var options = Gen5MslCodegenOptions.FromEnvironment with { ContractPixelCompute = contract }; + Assert.Contains(KeepRounding, Gen5ComputeFixtures.CompileVertexOrThrow(options: options).Source, StringComparison.Ordinal); + var pixel = Gen5ComputeFixtures.CompilePixelOrThrow(options: options).Source; + var compute = Gen5ComputeFixtures.CompileRequestOrThrow(Gen5ComputeFixtures.MadVersusFma, options: options).Source; + Assert.Equal(!contract, pixel.Contains(KeepRounding, StringComparison.Ordinal)); + Assert.Equal(!contract, compute.Contains(KeepRounding, StringComparison.Ordinal)); + } + } + // V_MAD_F32 rounds its product like a separate multiply and add; V_FMA_F32 does not. [Fact] public void LegacyMadRoundsTheProductAndFmaDoesNot() From d037ac79e3fa3d3461fedcc63dce188767757517 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:59:40 +0000 Subject: [PATCH 42/64] [Audio] Honour AudioOut2's caller-chosen queue cap on the CoreAudio output The merged AudioOut2 opens its context mix through the four-argument OpenPcmStream with a 256 KiB float cap. MacCoreAudioOutput only had the three-argument overload, so the interface default dropped the cap and the stream got AudioOut's 60 ms latency cap: the device cushion, dropout reserve and producer naps then read a queue a tenth as deep as they expect. --- .../Audio/MacCoreAudioOutput.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs index 6506660ba..5d417a143 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs @@ -61,6 +61,20 @@ public IHostAudioStream OpenStereoPcm16Stream(uint sampleRate, int maxQueuedPcmB public IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmFormat format) => OpenStream(sampleRate, channels, format, LatencyCapBytes(sampleRate, channels, format)); + /// <summary> + /// Guest-format stream with a caller-chosen backpressure cap in guest + /// bytes, for callers that pace the guest themselves (AudioOut2's context + /// mix): its device cushion, dropout reserve and producer naps read + /// <see cref="IHostAudioStream.QueuedMilliseconds"/> against a queue this + /// deep, so the cap must not fall back to the + /// <see cref="TargetQueuedMilliseconds"/> one. Zero or less keeps that + /// default, as the SDL backend does. + /// </summary> + public IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmFormat format, int maxQueuedBytes) + => maxQueuedBytes > 0 + ? OpenStream(sampleRate, channels, format, maxQueuedBytes) + : OpenPcmStream(sampleRate, channels, format); + /// <summary> /// Queue cap in guest bytes for <see cref="TargetQueuedMilliseconds"/> of /// audio in the guest's own format. From 6ce6fe5bfe4691fac883bba38df080c5fb37afc7 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:59:40 +0000 Subject: [PATCH 43/64] [Pad] Drive vibration-port rumble as timed, rate-limited rumble and drop the dead HapticRumble Upstream's HapticRumble had no caller after the merge: the fork's PadHaptics already turns vibration-port audio into rumble. PadHaptics now takes what HapticRumble had and it lacked: the haptic envelope goes out as timed rumble (250 ms, refreshed every 100 ms while it runs) that the host layers over the scePadSetVibration motors, so a port the guest stops feeding no longer leaves the motors running; updates are rate-limited (stop and start at once, a change of 6 after 16 ms); SHARPEMU_HAPTIC_RUMBLE_GAIN scales the envelope (default 1, 0 turns audio rumble off). Exactly one path drives audio rumble. --- src/SharpEmu.Libs/Audio/HapticRumble.cs | 140 ------------------ src/SharpEmu.Libs/Pad/PadHaptics.cs | 104 +++++++++---- .../Pad/PadHapticsTests.cs | 56 ++++++- 3 files changed, 128 insertions(+), 172 deletions(-) delete mode 100644 src/SharpEmu.Libs/Audio/HapticRumble.cs diff --git a/src/SharpEmu.Libs/Audio/HapticRumble.cs b/src/SharpEmu.Libs/Audio/HapticRumble.cs deleted file mode 100644 index 9cf7bc5c4..000000000 --- a/src/SharpEmu.Libs/Audio/HapticRumble.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using System.Globalization; -using SharpEmu.HLE.Host; - -namespace SharpEmu.Libs.Audio; - -internal static class HapticRumble -{ - private const float NoiseFloor = 0.02f; - private const float FullScale = 0.7f; - private const float Curve = 0.75f; - private const double ReleaseSeconds = 0.08; - private const long MinimumIntervalMs = 16; - private const long RefreshIntervalMs = 100; - private const uint DurationMs = 250; - private const int ChangeThreshold = 6; - - private static readonly float Gain = ReadGain(); - private static readonly object Gate = new(); - private static float _left; - private static float _right; - private static byte _sentLarge; - private static byte _sentSmall; - private static long _sentAt; - - internal static bool Enabled => Gain > 0f; - - internal static void MeasurePeaks( - ReadOnlySpan<byte> source, - int frames, - int channels, - int bytesPerSample, - bool isFloat, - float gain, - ref float left, - ref float right) - { - var frameSize = channels * bytesPerSample; - if (frameSize <= 0) - { - return; - } - - frames = Math.Min(frames, source.Length / frameSize); - for (var frame = 0; frame < frames; frame++) - { - var frameBytes = source.Slice(frame * frameSize, frameSize); - var first = MathF.Abs(AudioOut2Exports.ReadNormalizedSample(frameBytes, 0, bytesPerSample, isFloat) * gain); - var second = channels == 1 - ? first - : MathF.Abs(AudioOut2Exports.ReadNormalizedSample(frameBytes, 1, bytesPerSample, isFloat) * gain); - left = MathF.Max(left, first); - right = MathF.Max(right, second); - } - } - - internal static void Update(float leftPeak, float rightPeak, double seconds) - { - if (!Enabled) - { - return; - } - - lock (Gate) - { - var decay = (float)Math.Exp(-Math.Max(0, seconds) / ReleaseSeconds); - _left = MathF.Max(leftPeak, _left * decay); - _right = MathF.Max(rightPeak, _right * decay); - var large = ToMotor(_left); - var small = ToMotor(_right); - var now = Environment.TickCount64; - if (!ShouldSend(large, small, now - _sentAt)) - { - return; - } - - _sentLarge = large; - _sentSmall = small; - _sentAt = now; - HostPlatform.Current.Input.SetHapticRumble(large, small, DurationMs); - } - } - - internal static void Stop() - { - lock (Gate) - { - _left = 0f; - _right = 0f; - if ((_sentLarge | _sentSmall) == 0) - { - return; - } - - _sentLarge = 0; - _sentSmall = 0; - _sentAt = Environment.TickCount64; - HostPlatform.Current.Input.SetHapticRumble(0, 0, DurationMs); - } - } - - internal static byte ToMotor(float level) - { - var scaled = level * Gain; - if (scaled <= NoiseFloor) - { - return 0; - } - - var normalized = MathF.Min(1f, (scaled - NoiseFloor) / (FullScale - NoiseFloor)); - return (byte)MathF.Round(MathF.Pow(normalized, Curve) * 255f); - } - - private static bool ShouldSend(byte large, byte small, long elapsedMs) - { - var wasRunning = (_sentLarge | _sentSmall) != 0; - if ((large | small) == 0) - { - return wasRunning; - } - - if (!wasRunning || elapsedMs >= RefreshIntervalMs) - { - return true; - } - - return elapsedMs >= MinimumIntervalMs && - (Math.Abs(large - _sentLarge) >= ChangeThreshold || Math.Abs(small - _sentSmall) >= ChangeThreshold); - } - - private static float ReadGain() - { - var value = Environment.GetEnvironmentVariable("SHARPEMU_HAPTIC_RUMBLE_GAIN"); - return float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var gain) && float.IsFinite(gain) - ? Math.Max(0f, gain) - : 0.5f; - } -} diff --git a/src/SharpEmu.Libs/Pad/PadHaptics.cs b/src/SharpEmu.Libs/Pad/PadHaptics.cs index 48e0679ab..0beca7d2d 100644 --- a/src/SharpEmu.Libs/Pad/PadHaptics.cs +++ b/src/SharpEmu.Libs/Pad/PadHaptics.cs @@ -17,9 +17,18 @@ namespace SharpEmu.Libs.Pad; /// itself never reaches the speakers. /// </summary> /// <remarks> -/// scePadSetVibration keeps working alongside: the host motors run at the -/// stronger of the compat vibration and the haptic envelope, so a title that -/// clears the compat vibration every frame does not cut its haptics. +/// scePadSetVibration keeps working alongside: it sets the host pad's steady +/// motors (<see cref="IHostInput.SetRumble"/>), while the haptic envelope goes +/// out as timed rumble (<see cref="IHostInput.SetHapticRumble"/>) that the host +/// layers over them at the stronger of the two, so a title that clears the +/// compat vibration every frame does not cut its haptics. The timed level +/// lapses <see cref="HapticDurationMs"/> after the last refresh, so a port the +/// guest stops feeding (a stall, a hang) does not leave the motors running. +/// Updates are rate-limited as upstream's HapticRumble was: a stop and a start +/// go at once, a change of at least <see cref="HapticChangeThreshold"/> after +/// <see cref="HapticMinimumIntervalMs"/>, and a running level is refreshed every +/// <see cref="HapticRefreshIntervalMs"/>. <c>SHARPEMU_HAPTIC_RUMBLE_GAIN</c> +/// scales the envelope (default 1; 0 turns audio-driven rumble off). /// </remarks> public static class PadHaptics { @@ -27,14 +36,19 @@ public static class PadHaptics // so dither and DC-free noise floors do not keep the motors spinning. internal const double SilenceRms = 0.01; + internal const uint HapticDurationMs = 250; + internal const long HapticRefreshIntervalMs = 100; + internal const long HapticMinimumIntervalMs = 16; + internal const int HapticChangeThreshold = 6; + + private static readonly float Gain = ReadGain(); + private static readonly object Gate = new(); - private static byte _vibrationLarge; - private static byte _vibrationSmall; - private static byte _hapticLeft; - private static byte _hapticRight; - private static byte _appliedLarge; - private static byte _appliedSmall; + private static byte _sentHapticLeft; + private static byte _sentHapticRight; + private static long _sentHapticAt; private static IHostInput? _hostInputForTests; + private static Func<long>? _clockForTests; /// <summary> /// Reduces one chunk of interleaved haptic PCM to an intensity per @@ -103,15 +117,29 @@ private static byte ChannelIntensity( /// <summary> /// Sets the actuator intensities derived from the latest haptic chunk. - /// The host motors are only updated when the combined level changes. + /// The host pad gets them as timed rumble, rate-limited (see the remarks). /// </summary> public static void SubmitAudioHaptics(byte left, byte right) { + if (Gain <= 0f) + { + return; + } + + left = Scale(left); + right = Scale(right); lock (Gate) { - _hapticLeft = left; - _hapticRight = right; - ApplyLocked(force: false); + var now = (Volatile.Read(ref _clockForTests) ?? ClockMilliseconds)(); + if (!ShouldSendHaptics(left, right, now - _sentHapticAt)) + { + return; + } + + _sentHapticLeft = left; + _sentHapticRight = right; + _sentHapticAt = now; + Input.SetHapticRumble(left, right, HapticDurationMs); } } @@ -123,26 +151,48 @@ internal static void SetVibration(byte largeMotor, byte smallMotor) { lock (Gate) { - _vibrationLarge = largeMotor; - _vibrationSmall = smallMotor; - ApplyLocked(force: true); + Input.SetRumble(largeMotor, smallMotor); } } - private static void ApplyLocked(bool force) + private static IHostInput Input => Volatile.Read(ref _hostInputForTests) ?? HostPlatform.Current.Input; + + private static long ClockMilliseconds() => Environment.TickCount64; + + // Caller holds Gate. + private static bool ShouldSendHaptics(byte left, byte right, long elapsedMs) { - var large = Math.Max(_vibrationLarge, _hapticLeft); - var small = Math.Max(_vibrationSmall, _hapticRight); - if (!force && large == _appliedLarge && small == _appliedSmall) + var wasRunning = (_sentHapticLeft | _sentHapticRight) != 0; + if ((left | right) == 0) { - return; + return wasRunning; + } + + if (!wasRunning || elapsedMs >= HapticRefreshIntervalMs) + { + return true; } - _appliedLarge = large; - _appliedSmall = small; - (Volatile.Read(ref _hostInputForTests) ?? HostPlatform.Current.Input).SetRumble(large, small); + return elapsedMs >= HapticMinimumIntervalMs && + (Math.Abs(left - _sentHapticLeft) >= HapticChangeThreshold || + Math.Abs(right - _sentHapticRight) >= HapticChangeThreshold); } + private static byte Scale(byte level) => + Gain == 1f ? level : (byte)Math.Clamp(MathF.Round(level * Gain), 0f, 255f); + + private static float ReadGain() + { + var value = Environment.GetEnvironmentVariable("SHARPEMU_HAPTIC_RUMBLE_GAIN"); + return float.TryParse(value, System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out var gain) && float.IsFinite(gain) + ? Math.Max(0f, gain) + : 1f; + } + + internal static void SetClockForTests(Func<long>? clock) => + Volatile.Write(ref _clockForTests, clock); + internal static void SetHostInputForTests(IHostInput? input) => Volatile.Write(ref _hostInputForTests, input); @@ -150,11 +200,11 @@ internal static void ResetForTests() { lock (Gate) { - _vibrationLarge = _vibrationSmall = 0; - _hapticLeft = _hapticRight = 0; - _appliedLarge = _appliedSmall = 0; + _sentHapticLeft = _sentHapticRight = 0; + _sentHapticAt = 0; } Volatile.Write(ref _hostInputForTests, null); + Volatile.Write(ref _clockForTests, null); } } diff --git a/tests/SharpEmu.Libs.Tests/Pad/PadHapticsTests.cs b/tests/SharpEmu.Libs.Tests/Pad/PadHapticsTests.cs index 941f084e3..495af6622 100644 --- a/tests/SharpEmu.Libs.Tests/Pad/PadHapticsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Pad/PadHapticsTests.cs @@ -63,14 +63,43 @@ public void IntensityFromPcm_MonoDrivesBothActuatorsAndReadsS16() } [Fact] - public void AudioHapticsCombineWithCompatVibration() + public void AudioHapticsAreTimedRumbleBesideCompatVibration() { + var now = 1_000L; + PadHaptics.SetClockForTests(() => now); + PadHaptics.SubmitAudioHaptics(100, 20); PadHaptics.SubmitAudioHaptics(100, 20); PadHaptics.SetVibration(50, 60); PadHaptics.ReleaseAudioHaptics(); - Assert.Equal([((byte)100, (byte)20), ((byte)100, (byte)60), ((byte)50, (byte)60)], _input.Rumble); + // The compat vibration holds the steady motors; the haptic envelope is a timed layer the host combines with + // them, so neither overwrites the other. + Assert.Equal([((byte)50, (byte)60)], _input.SteadyRumble); + Assert.Equal([((byte)100, (byte)20), ((byte)0, (byte)0)], _input.TimedRumble); + Assert.All(_input.TimedDurations, duration => Assert.Equal(PadHaptics.HapticDurationMs, duration)); + } + + [Fact] + public void AudioHapticsAreRateLimitedAndRefreshedWhileRunning() + { + var now = 1_000L; + PadHaptics.SetClockForTests(() => now); + + PadHaptics.SubmitAudioHaptics(100, 100); + now += 5; + PadHaptics.SubmitAudioHaptics(200, 200); // too soon after the start + now += PadHaptics.HapticMinimumIntervalMs; + PadHaptics.SubmitAudioHaptics(102, 100); // below the change threshold + PadHaptics.SubmitAudioHaptics(200, 100); // a real change after the minimum interval + now += PadHaptics.HapticRefreshIntervalMs; + PadHaptics.SubmitAudioHaptics(200, 100); // same level: refreshed before it lapses + PadHaptics.SubmitAudioHaptics(0, 0); // a stop goes at once + + Assert.Equal( + [((byte)100, (byte)100), ((byte)200, (byte)100), ((byte)200, (byte)100), ((byte)0, (byte)0)], + _input.TimedRumble); + Assert.True(PadHaptics.HapticRefreshIntervalMs < PadHaptics.HapticDurationMs); } [NativeX64Fact] @@ -89,7 +118,8 @@ public void SetVibrationExport_RoutesThroughHaptics() Assert.True(_memory.TryWrite(Base + 0x100, new byte[] { 10, 90 })); Assert.Equal(0, PadExports.PadSetVibration(_ctx)); - Assert.Equal(((byte)200, (byte)90), _input.Rumble[^1]); + Assert.Equal(((byte)10, (byte)90), _input.SteadyRumble[^1]); + Assert.Equal(((byte)200, (byte)0), _input.TimedRumble[^1]); } internal static byte[] Float32(params float[] samples) @@ -106,8 +136,15 @@ internal static byte[] Float32(params float[] samples) internal sealed class RecordingHostInput : IHostInput { + /// <summary>Every rumble change, steady and timed, in order.</summary> public List<(byte Large, byte Small)> Rumble { get; } = []; + public List<(byte Large, byte Small)> SteadyRumble { get; } = []; + + public List<(byte Large, byte Small)> TimedRumble { get; } = []; + + public List<uint> TimedDurations { get; } = []; + public void EnsureStarted() { } @@ -116,9 +153,18 @@ public void EnsureStarted() public string? DescribeConnectedGamepad() => null; - public void SetRumble(byte largeMotor, byte smallMotor) => Rumble.Add((largeMotor, smallMotor)); + public void SetRumble(byte largeMotor, byte smallMotor) + { + Rumble.Add((largeMotor, smallMotor)); + SteadyRumble.Add((largeMotor, smallMotor)); + } - public void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs) => Rumble.Add((largeMotor, smallMotor)); + public void SetHapticRumble(byte largeMotor, byte smallMotor, uint durationMs) + { + Rumble.Add((largeMotor, smallMotor)); + TimedRumble.Add((largeMotor, smallMotor)); + TimedDurations.Add(durationMs); + } public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger) { From 3f430d97948c37f6f081452e5a0406ebc2cc3a9a Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 19:59:40 +0000 Subject: [PATCH 44/64] [Pad] Feed the pad orientation from GameController motion, across the GPU split MacGameControllerGamepad never fed HostWindowInput.ApplyGamepadMotion, so the merged MotionOrientation stayed at identity on macOS. MacMotionFeed installs a GCMotion valueChangedHandler on a serial queue of its own and feeds every gyro and accelerometer reading, turns the sensors on for pads that need it (DualSense, DualShock 4) and reads the unsplit acceleration those pads report. With the split the pad lives in the GPU process: the orientation accumulates there and crosses in GamepadStateWire (protocol 10), the guest keeps it, and scePadResetOrientation / scePadSetTiltCorrectionState cross back as two new gamepad output kinds. --- src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs | 6 +- src/SharpEmu.GpuRemote/GpuSplitMessages.cs | 10 + src/SharpEmu.GpuSplit/GuestProcessSide.cs | 3 +- src/SharpEmu.GpuSplit/SplitConvert.cs | 10 +- src/SharpEmu.GpuSplit/SplitGamepadOutput.cs | 7 + src/SharpEmu.GpuSplit/SplitGpuHost.cs | 6 + src/SharpEmu.Libs/Pad/HostWindowInput.cs | 36 ++- .../Input/MacGameControllerGamepad.cs | 31 ++- .../Input/MacMotionFeed.cs | 229 ++++++++++++++++++ .../GpuRemoteChannelTests.cs | 3 +- .../SplitInProcessTests.cs | 28 +++ 11 files changed, 343 insertions(+), 26 deletions(-) create mode 100644 src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacMotionFeed.cs diff --git a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs index 97e20e199..c40b9089c 100644 --- a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs +++ b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs @@ -14,8 +14,10 @@ public static class GpuRemoteProtocol /// 4: frame-boundary messages. 5: input-change and display reservations. /// 6: pending-writeback pages. 7: combined frame, input and writeback layout. /// 8: <see cref="GpuRemoteSyncOpcode.ResidencyRange"/>. - /// 9: <see cref="GpuSplitGamepadOutput.HapticRumble"/> and <see cref="GamepadOutputMessage.DurationMs"/>.</remarks> - public const uint Version = 9; + /// 9: <see cref="GpuSplitGamepadOutput.HapticRumble"/> and <see cref="GamepadOutputMessage.DurationMs"/>. + /// 10: the pad orientation in <see cref="GamepadStateWire"/>, <see cref="GpuSplitGamepadOutput.ResetOrientation"/> + /// and <see cref="GpuSplitGamepadOutput.TiltCorrection"/>.</remarks> + public const uint Version = 10; } diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs index 563bcf546..fa1b3d797 100644 --- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs +++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs @@ -98,6 +98,12 @@ public enum GpuSplitGamepadOutput : uint Lightbar = 4, ResetLightbar = 5, HapticRumble = 6, + + /// <summary>scePadResetOrientation: the GPU process restarts the orientation it accumulates.</summary> + ResetOrientation = 7, + + /// <summary>scePadSetTiltCorrectionState: A is 1 for on, 0 for off.</summary> + TiltCorrection = 8, } /// <summary>Status codes of the split's synchronous calls (0 is success).</summary> @@ -350,6 +356,10 @@ public struct GamepadStateWire public float AngularVelocityX; public float AngularVelocityY; public float AngularVelocityZ; + public float OrientationX; + public float OrientationY; + public float OrientationZ; + public float OrientationW; public uint FirstTouchActive; public uint FirstTouchId; public float FirstTouchX; diff --git a/src/SharpEmu.GpuSplit/GuestProcessSide.cs b/src/SharpEmu.GpuSplit/GuestProcessSide.cs index da4d46cd2..4fa0cb5a0 100644 --- a/src/SharpEmu.GpuSplit/GuestProcessSide.cs +++ b/src/SharpEmu.GpuSplit/GuestProcessSide.cs @@ -108,7 +108,8 @@ public void Input(bool focused, ReadOnlySpan<int> keys, in HostGamepadState game HostWindowInput.SetKeys(keys); if (gamepad.Connected) { - HostWindowInput.SetGamepad(gamepadName, gamepad); + // The GPU process feeds the sensor readings to its own orientation and sends the result. + HostWindowInput.SetGamepad(gamepadName, gamepad, sourceOrientation: true); } else { diff --git a/src/SharpEmu.GpuSplit/SplitConvert.cs b/src/SharpEmu.GpuSplit/SplitConvert.cs index bb2dc0aaf..21fd9fa4c 100644 --- a/src/SharpEmu.GpuSplit/SplitConvert.cs +++ b/src/SharpEmu.GpuSplit/SplitConvert.cs @@ -61,6 +61,10 @@ internal static class SplitConvert AngularVelocityX = state.Motion.AngularVelocityX, AngularVelocityY = state.Motion.AngularVelocityY, AngularVelocityZ = state.Motion.AngularVelocityZ, + OrientationX = state.Motion.OrientationX, + OrientationY = state.Motion.OrientationY, + OrientationZ = state.Motion.OrientationZ, + OrientationW = state.Motion.OrientationW, FirstTouchActive = state.Touch.First.Active ? 1u : 0u, FirstTouchId = state.Touch.First.Id, FirstTouchX = state.Touch.First.X, @@ -90,7 +94,11 @@ internal static class SplitConvert wire.AccelerationZ, wire.AngularVelocityX, wire.AngularVelocityY, - wire.AngularVelocityZ), + wire.AngularVelocityZ, + wire.OrientationX, + wire.OrientationY, + wire.OrientationZ, + wire.OrientationW), new HostTouchState( new HostTouchPoint(wire.FirstTouchActive != 0, (byte)wire.FirstTouchId, wire.FirstTouchX, wire.FirstTouchY), new HostTouchPoint(wire.SecondTouchActive != 0, (byte)wire.SecondTouchId, wire.SecondTouchX, wire.SecondTouchY)), diff --git a/src/SharpEmu.GpuSplit/SplitGamepadOutput.cs b/src/SharpEmu.GpuSplit/SplitGamepadOutput.cs index a97e9e2a0..7375f0132 100644 --- a/src/SharpEmu.GpuSplit/SplitGamepadOutput.cs +++ b/src/SharpEmu.GpuSplit/SplitGamepadOutput.cs @@ -44,5 +44,12 @@ public void SetLightbar(byte red, byte green, byte blue) => public void ResetLightbar() => Send(new GamepadOutputMessage { Kind = (uint)GpuSplitGamepadOutput.ResetLightbar }); + // The orientation accumulates in the GPU process, where the gamepad's sensor readings arrive. + public void ResetMotionOrientation() => + Send(new GamepadOutputMessage { Kind = (uint)GpuSplitGamepadOutput.ResetOrientation }); + + public void SetMotionTiltCorrection(bool enabled) => + Send(new GamepadOutputMessage { Kind = (uint)GpuSplitGamepadOutput.TiltCorrection, A = enabled ? (byte)1 : (byte)0 }); + private void Send(in GamepadOutputMessage message) => _ = writer.Write(GpuRemoteMessage.GamepadOutput, in message); } diff --git a/src/SharpEmu.GpuSplit/SplitGpuHost.cs b/src/SharpEmu.GpuSplit/SplitGpuHost.cs index 311d520b7..5d899d2d0 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuHost.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuHost.cs @@ -439,6 +439,12 @@ private static void ApplyGamepadOutput(in GamepadOutputMessage message) case GpuSplitGamepadOutput.ResetLightbar: input.ResetLightbar(); break; + case GpuSplitGamepadOutput.ResetOrientation: + HostWindowInput.ResetMotionOrientation(forwardToOutput: false); + break; + case GpuSplitGamepadOutput.TiltCorrection: + HostWindowInput.SetMotionTiltCorrection(message.A != 0, forwardToOutput: false); + break; } } diff --git a/src/SharpEmu.Libs/Pad/HostWindowInput.cs b/src/SharpEmu.Libs/Pad/HostWindowInput.cs index 7c8f41eca..061c2c880 100644 --- a/src/SharpEmu.Libs/Pad/HostWindowInput.cs +++ b/src/SharpEmu.Libs/Pad/HostWindowInput.cs @@ -174,14 +174,21 @@ public static void SetKey(int virtualKey, bool down) if (changed) Changed?.Invoke(); } - public static void SetGamepad(string? name, HostGamepadState state) + public static void SetGamepad(string? name, HostGamepadState state) => + SetGamepad(name, state, sourceOrientation: false); + + /// <summary> + /// <paramref name="sourceOrientation"/>: the state already carries the pad's orientation, accumulated where the + /// gamepad's sensor readings arrive (the two-process split's GPU process), so it is kept instead of this process's. + /// </summary> + public static void SetGamepad(string? name, HostGamepadState state, bool sourceOrientation) { bool changed; lock (Gate) { changed = _gamepadConnected != state.Connected || _gamepadState.Buttons != state.Buttons || !SameContacts(_gamepadState.Touch, state.Touch); - if (state.Motion.Available) + if (state.Motion.Available && !sourceOrientation) { var orientation = Orientation.Orientation; state = state with @@ -257,20 +264,31 @@ public static void ApplyGamepadMotion(bool angularVelocity, float x, float y, fl } } - internal static void ResetMotionOrientation() + // The game's reset and tilt correction also go to the gamepad output, which forwards them to the process that + // accumulates the orientation when that is another one (the two-process split). That process applies them with + // forwardToOutput false, so they never travel back. + public static void ResetMotionOrientation(bool forwardToOutput = true) { + IHostGamepadOutput? output; lock (Gate) { Orientation.Reset(); + output = forwardToOutput ? _gamepadOutput : null; } + + output?.ResetMotionOrientation(); } - internal static void SetMotionTiltCorrection(bool enabled) + public static void SetMotionTiltCorrection(bool enabled, bool forwardToOutput = true) { + IHostGamepadOutput? output; lock (Gate) { Orientation.TiltCorrection = enabled; + output = forwardToOutput ? _gamepadOutput : null; } + + output?.SetMotionTiltCorrection(enabled); } private static bool SameContacts(HostTouchState left, HostTouchState right) => @@ -405,4 +423,14 @@ void SetAdaptiveTriggerEffect( void SetLightbar(byte red, byte green, byte blue); void ResetLightbar(); + + /// <summary>scePadResetOrientation, for an output whose process accumulates the orientation elsewhere.</summary> + void ResetMotionOrientation() + { + } + + /// <summary>scePadSetTiltCorrectionState, for an output whose process accumulates the orientation elsewhere.</summary> + void SetMotionTiltCorrection(bool enabled) + { + } } diff --git a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs index 93a58ffc0..da91cd7c5 100644 --- a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs +++ b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs @@ -217,6 +217,7 @@ private void SyncConnectedController() "setModeOff"); _supportsTouchpad = MacObjC.Responds(_profile, "touchpadPrimary"); CreateHaptics(); + var motionFed = _outputEnabled && MacMotionFeed.Attach(_controller); // A fresh pad starts from the configured lightbar colour and silent motors. lock (_outputGate) { @@ -227,7 +228,7 @@ private void SyncConnectedController() Console.Error.WriteLine( $"[PAD][INFO] GameController gamepad connected: {_name} type={_type} " + - $"adaptive_triggers={_supportsAdaptiveTriggers} touchpad={_supportsTouchpad}"); + $"adaptive_triggers={_supportsAdaptiveTriggers} touchpad={_supportsTouchpad} motion_feed={motionFed}"); } /// <summary> @@ -281,6 +282,11 @@ private void CreateHaptics() private void CloseController() { + if (_outputEnabled) + { + MacMotionFeed.Detach(_controller); + } + _leftHandle?.Dispose(); _rightHandle?.Dispose(); _leftTriggerMotor?.Dispose(); @@ -400,27 +406,18 @@ private HostMotionState ReadMotion() return default; } - var hasAcceleration = !MacObjC.Responds(motion, "hasGravityAndUserAcceleration") || - MacObjC.SendBool(motion, MacObjC.Selector("hasGravityAndUserAcceleration")); - var hasRotation = !MacObjC.Responds(motion, "hasRotationRate") || - MacObjC.SendBool(motion, MacObjC.Selector("hasRotationRate")); + var hasAcceleration = MacMotionFeed.TryReadAcceleration(motion, out var acceleration); + var hasRotation = MacMotionFeed.HasRotationRate(motion); if (!hasAcceleration && !hasRotation) { return default; } - var acceleration = default(MacVector3); - if (hasAcceleration) - { - // GCMotion splits the accelerometer into gravity and user - // acceleration, both in g; SDL_SENSOR_ACCEL reported m/s^2, so sum - // them and scale to keep guest-visible magnitudes identical. - var gravity = MacObjC.SendVector3(motion, MacObjC.Selector("gravity")); - var user = MacObjC.SendVector3(motion, MacObjC.Selector("userAcceleration")); - acceleration.X = (gravity.X + user.X) * StandardGravity; - acceleration.Y = (gravity.Y + user.Y) * StandardGravity; - acceleration.Z = (gravity.Z + user.Z) * StandardGravity; - } + // GCMotion reports acceleration in g; SDL_SENSOR_ACCEL reported m/s^2, so + // scale to keep guest-visible magnitudes identical. + acceleration.X *= StandardGravity; + acceleration.Y *= StandardGravity; + acceleration.Z *= StandardGravity; // GCMotion rotationRate is radians/second, the same unit SDL's gyro used. var rotation = hasRotation diff --git a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacMotionFeed.cs b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacMotionFeed.cs new file mode 100644 index 000000000..5e7238f3e --- /dev/null +++ b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacMotionFeed.cs @@ -0,0 +1,229 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using SharpEmu.Libs.Pad; + +namespace SharpEmu.Platform.MacOS.Input; + +/// <summary> +/// Feeds every sensor reading of the open GameController pad to the pad's orientation +/// (<see cref="HostWindowInput.ApplyGamepadMotion"/>), as the SDL window does with its sensor events: each gyro reading +/// turns the orientation by its own interval, which the window loop's once-a-frame poll of the latest reading cannot +/// do. The readings come from <c>GCMotion.valueChangedHandler</c> on a serial queue of their own (the controller's +/// <c>handlerQueue</c>), so they arrive as GameController receives them, not batched behind the main run loop. +/// </summary> +/// <remarks> +/// GCMotion carries no per-reading timestamp, so a reading is stamped with the host's monotonic clock when its +/// handler runs. Attitude (<c>hasAttitude</c>) is reported only by Siri Remote-class devices, not by the DualSense, +/// DualShock 4 or Xbox pads, so the orientation always comes from the gyro. +/// </remarks> +[SupportedOSPlatform("macos")] +internal static unsafe class MacMotionFeed +{ + private const int BlockIsGlobal = 1 << 28; + private const double StandardGravity = 9.80665; + + private static readonly object Gate = new(); + private static BlockLiteral* _block; + private static nint _queue; + private static nint _motion; + + [StructLayout(LayoutKind.Sequential)] + private struct BlockDescriptor + { + public nuint Reserved; + public nuint Size; + } + + [StructLayout(LayoutKind.Sequential)] + private struct BlockLiteral + { + public nint Isa; + public int Flags; + public int Reserved; + public delegate* unmanaged<nint, nint, void> Invoke; + public BlockDescriptor* Descriptor; + } + + /// <summary> + /// Starts the readings of <paramref name="controller"/>'s motion: turns its sensors on where they need it (the + /// DualSense and DualShock 4 start with them off) and installs the handler. False when the pad has no motion. + /// </summary> + public static bool Attach(nint controller) + { + var motion = controller == 0 ? 0 : MacObjC.Send(controller, MacObjC.Selector("motion")); + if (motion == 0) + { + return false; + } + + lock (Gate) + { + if (!EnsureBlock()) + { + return false; + } + + if (MacObjC.Responds(motion, "sensorsRequireManualActivation") && + MacObjC.SendBool(motion, MacObjC.Selector("sensorsRequireManualActivation"))) + { + MacObjC.SendVoidBool(motion, MacObjC.Selector("setSensorsActive:"), true); + } + + if (MacObjC.Responds(controller, "setHandlerQueue:")) + { + MacObjC.SendVoid(controller, MacObjC.Selector("setHandlerQueue:"), _queue); + } + + _motion = motion; + MacObjC.SendVoid(motion, MacObjC.Selector("setValueChangedHandler:"), (nint)_block); + } + + return true; + } + + /// <summary>Stops the readings of <paramref name="controller"/>'s motion and turns its sensors off.</summary> + public static void Detach(nint controller) + { + var motion = controller == 0 ? 0 : MacObjC.Send(controller, MacObjC.Selector("motion")); + lock (Gate) + { + if (motion != 0) + { + MacObjC.SendVoid(motion, MacObjC.Selector("setValueChangedHandler:"), 0); + if (MacObjC.Responds(motion, "sensorsRequireManualActivation") && + MacObjC.SendBool(motion, MacObjC.Selector("sensorsRequireManualActivation"))) + { + MacObjC.SendVoidBool(motion, MacObjC.Selector("setSensorsActive:"), false); + } + } + + if (_motion == motion) + { + _motion = 0; + } + } + } + + /// <summary> + /// The accelerometer in g, gravity included: <c>gravity + userAcceleration</c> where GameController splits them, + /// otherwise its raw <c>acceleration</c> (the DualSense and DualShock 4 report it unsplit). + /// </summary> + public static bool TryReadAcceleration(nint motion, out MacVector3 acceleration) + { + acceleration = default; + if (!MacObjC.Responds(motion, "hasGravityAndUserAcceleration") || + MacObjC.SendBool(motion, MacObjC.Selector("hasGravityAndUserAcceleration"))) + { + var gravity = MacObjC.SendVector3(motion, MacObjC.Selector("gravity")); + var user = MacObjC.SendVector3(motion, MacObjC.Selector("userAcceleration")); + acceleration.X = gravity.X + user.X; + acceleration.Y = gravity.Y + user.Y; + acceleration.Z = gravity.Z + user.Z; + return true; + } + + if (MacObjC.Responds(motion, "acceleration")) + { + acceleration = MacObjC.SendVector3(motion, MacObjC.Selector("acceleration")); + return true; + } + + return false; + } + + public static bool HasRotationRate(nint motion) => + !MacObjC.Responds(motion, "hasRotationRate") || + MacObjC.SendBool(motion, MacObjC.Selector("hasRotationRate")); + + /// <summary>The host's monotonic clock in nanoseconds, never 0 (the orientation's "no reading yet").</summary> + internal static ulong TimestampNanoseconds(long ticks, long frequency) => + Math.Max(1UL, (ulong)((Int128)ticks * 1_000_000_000 / frequency)); + + private static bool EnsureBlock() + { + if (_block is not null) + { + return true; + } + + if (!NativeLibrary.TryLoad("/usr/lib/libSystem.B.dylib", out var system) || + !NativeLibrary.TryGetExport(system, "_NSConcreteGlobalBlock", out var globalBlockClass)) + { + Console.Error.WriteLine("[PAD][WARN] GameController motion: no block runtime; orientation is not fed."); + return false; + } + + if (_queue == 0) + { + var label = "net.sharpemu.gamepad-motion\0"u8; + fixed (byte* name = label) + { + _queue = dispatch_queue_create(name, 0); + } + + if (_queue == 0) + { + Console.Error.WriteLine("[PAD][WARN] GameController motion: no dispatch queue; orientation is not fed."); + return false; + } + } + + // A global block captures nothing and is never copied or freed, so it lives in native memory for good. + var descriptor = (BlockDescriptor*)NativeMemory.AllocZeroed((nuint)sizeof(BlockDescriptor)); + descriptor->Size = (nuint)sizeof(BlockLiteral); + var block = (BlockLiteral*)NativeMemory.AllocZeroed((nuint)sizeof(BlockLiteral)); + block->Isa = globalBlockClass; + block->Flags = BlockIsGlobal; + block->Invoke = &OnMotion; + block->Descriptor = descriptor; + _block = block; + return true; + } + + [UnmanagedCallersOnly] + private static void OnMotion(nint block, nint motion) + { + try + { + if (motion == 0 || motion != Volatile.Read(ref _motion)) + { + return; + } + + var timestamp = TimestampNanoseconds(Stopwatch.GetTimestamp(), Stopwatch.Frequency); + if (TryReadAcceleration(motion, out var acceleration)) + { + HostWindowInput.ApplyGamepadMotion( + angularVelocity: false, + (float)(acceleration.X * StandardGravity), + (float)(acceleration.Y * StandardGravity), + (float)(acceleration.Z * StandardGravity), + timestamp); + } + + if (HasRotationRate(motion)) + { + var rate = MacObjC.SendVector3(motion, MacObjC.Selector("rotationRate")); + HostWindowInput.ApplyGamepadMotion( + angularVelocity: true, + (float)rate.X, + (float)rate.Y, + (float)rate.Z, + timestamp); + } + } + catch (Exception exception) + { + // Never let an exception unwind into GameController's queue. + Console.Error.WriteLine($"[PAD][WARN] GameController motion reading failed: {exception.Message}"); + } + } + + [DllImport("/usr/lib/libSystem.B.dylib")] + private static extern nint dispatch_queue_create(byte* label, nint attributes); +} diff --git a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs index c082716c7..2ec25da6f 100644 --- a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs @@ -89,13 +89,14 @@ public void AttachRefusesAnotherProtocolVersion() [InlineData(6u)] [InlineData(7u)] [InlineData(8u)] + [InlineData(9u)] public void CombinedLayoutRefusesEveryIndependentRecoveryProtocol(uint version) { if (!OperatingSystem.IsMacOS()) return; using var host = GpuRemoteChannel.Create(SharedMemoryRegion.CreateUniqueName("setest")); using (var raw = SharedMemoryRegion.Open(host.Name)) ((RegionHeader*)raw.Pointer)->Version = version; - Assert.Equal(9u, GpuRemoteProtocol.Version); + Assert.Equal(10u, GpuRemoteProtocol.Version); Assert.Throws<InvalidDataException>(() => GpuRemoteChannel.Attach(host.Name)); } diff --git a/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs b/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs index 3d8091acd..5a94b60c0 100644 --- a/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs +++ b/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs @@ -489,10 +489,38 @@ public void ControlCallsFramesQueriesAndMirrorsCross() output.ResetLightbar(); _ = backend.SubmitDone(null!); Assert.Equal(new[] { "rumble 10 20", "triggers 7", "lightbar 1 2 3", "adaptive 11 none", "reset" }, source.Calls); + + // The orientation accumulates on the GPU side, where the sensor readings arrive; the game's reset + // crosses to it, and the orientation crosses back with the pad state. + var motion = new HostGamepadState( + Connected: true, Buttons: 0, LeftX: 128, LeftY: 128, RightX: 128, RightY: 128, LeftTrigger: 0, + RightTrigger: 0, Type: HostGamepadType.DualSense, Connection: HostGamepadConnection.Unknown, + Motion: new HostMotionState(true, 0, -9.8f, 0, 0, 0, 0), Touch: default, BatteryPercent: 100); + HostWindowInput.ApplyGamepadMotion(angularVelocity: true, 0, 0, 1f, 1_000_000); + HostWindowInput.ApplyGamepadMotion(angularVelocity: true, 0, 0, 1f, 51_000_000); + HostWindowInput.SetGamepad("pad", motion); + _ = HostWindowInput.CopyState(stackalloc int[4], out _, out var turned, out _); + Assert.True(turned.Motion.OrientationW < 0.9999f); + var crossed = SplitConvert.FromWire(SplitConvert.ToWire(turned)); + Assert.Equal(turned.Motion, crossed.Motion); + + output.SetMotionTiltCorrection(true); + output.ResetMotionOrientation(); + _ = backend.SubmitDone(null!); + HostWindowInput.SetGamepad("pad", motion); + _ = HostWindowInput.CopyState(stackalloc int[4], out _, out var reset, out _); + Assert.Equal(1f, reset.Motion.OrientationW); + + // A state that carries its source's orientation keeps it. + HostWindowInput.SetGamepad("pad", crossed, sourceOrientation: true); + _ = HostWindowInput.CopyState(stackalloc int[4], out _, out var kept, out _); + Assert.Equal(crossed.Motion, kept.Motion); } finally { HostWindowInputSource.Clear(source); + HostWindowInput.SetMotionTiltCorrection(false, forwardToOutput: false); + HostWindowInput.ClearGamepad(); } backend.RequestClose(); From 3f820783ca3b3864038117ef82b4291ed6f8a99d Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:04:48 +0000 Subject: [PATCH 45/64] [Metal] Draw the in-game overlay layers over presented frames Port of upstream c88d6b0b2's RecordOverlayLayers to the Metal v2 presenter: the registered OverlayLayers (IME keyboard, save data list) are painted for the drawable size and blended premultiplied over the frame, 1:1 at their bounds, before the performance overlay. OverlayLayerOutput.Source says where the painted layers come from (this process by default) so the split's GPU process can take them from the guest process. --- src/SharpEmu.Libs/Overlay/OverlayLayer.cs | 20 +- .../Overlay/OverlayLayerFrames.cs | 199 +++++++++++++ .../V2/MetalOverlayLayerCompositor.cs | 262 ++++++++++++++++++ .../V2/MetalV2Presenter.OverlayLayers.cs | 56 ++++ .../SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs | 8 +- .../MetalOverlayLayerCompositorTests.cs | 233 ++++++++++++++++ 6 files changed, 775 insertions(+), 3 deletions(-) create mode 100644 src/SharpEmu.Libs/Overlay/OverlayLayerFrames.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalOverlayLayerCompositor.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.OverlayLayers.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalOverlayLayerCompositorTests.cs diff --git a/src/SharpEmu.Libs/Overlay/OverlayLayer.cs b/src/SharpEmu.Libs/Overlay/OverlayLayer.cs index d3b168e59..3378e9074 100644 --- a/src/SharpEmu.Libs/Overlay/OverlayLayer.cs +++ b/src/SharpEmu.Libs/Overlay/OverlayLayer.cs @@ -17,7 +17,11 @@ public abstract class OverlayLayer public abstract int Render(SKCanvas canvas, int width, int height, float unit); - protected void Invalidate() => Interlocked.Increment(ref _revision); + protected void Invalidate() + { + Interlocked.Increment(ref _revision); + OverlayLayers.NoteChanged(); + } protected static SKRectI Centered(int surfaceWidth, int surfaceHeight, int width, int height) => SKRectI.Create((surfaceWidth - width) / 2, (surfaceHeight - height) / 2, width, height); @@ -27,6 +31,13 @@ public static class OverlayLayers { private static readonly object Gate = new(); private static OverlayLayer[] _layers = []; + private static long _version; + + /// <summary>Moves whenever a layer is registered or changes (shown, hidden or redrawn).</summary> + public static long Version => Interlocked.Read(ref _version); + + /// <summary>Raised after <see cref="Version"/> moved, on the thread that changed the layer.</summary> + public static event Action? Changed; public static T Register<T>(T layer) where T : OverlayLayer { @@ -35,8 +46,15 @@ public static T Register<T>(T layer) where T : OverlayLayer _layers = [.. _layers, layer]; } + NoteChanged(); return layer; } public static OverlayLayer[] Snapshot() => Volatile.Read(ref _layers); + + internal static void NoteChanged() + { + Interlocked.Increment(ref _version); + Changed?.Invoke(); + } } diff --git a/src/SharpEmu.Libs/Overlay/OverlayLayerFrames.cs b/src/SharpEmu.Libs/Overlay/OverlayLayerFrames.cs new file mode 100644 index 000000000..93d6203ea --- /dev/null +++ b/src/SharpEmu.Libs/Overlay/OverlayLayerFrames.cs @@ -0,0 +1,199 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Overlay; + +/// <summary> +/// One overlay layer painted for a presentation surface: <see cref="Height"/> rows of +/// <see cref="Width"/> premultiplied BGRA pixels, to be blended over the presented frame with their +/// top-left corner at (<see cref="Left"/>, <see cref="Top"/>). Immutable once made; a presenter can +/// tell a repaint from the frame it already uploaded by reference. +/// </summary> +public sealed class OverlayLayerFrame +{ + public OverlayLayerFrame( + int id, long revision, int surfaceWidth, int surfaceHeight, int left, int top, int width, int height, byte[] pixels) + { + ArgumentNullException.ThrowIfNull(pixels); + if (width <= 0 || height <= 0 || pixels.Length != checked(width * height * 4)) + { + throw new ArgumentException("An overlay layer frame's pixels must match its size.", nameof(pixels)); + } + + Id = id; + Revision = revision; + SurfaceWidth = surfaceWidth; + SurfaceHeight = surfaceHeight; + Left = left; + Top = top; + Width = width; + Height = height; + Pixels = pixels; + } + + /// <summary>The layer's index in <see cref="OverlayLayers.Snapshot"/>: its draw order.</summary> + public int Id { get; } + + public long Revision { get; } + + public int SurfaceWidth { get; } + + public int SurfaceHeight { get; } + + public int Left { get; } + + public int Top { get; } + + public int Width { get; } + + public int Height { get; } + + public byte[] Pixels { get; } + + /// <summary>Whether the frame was painted for this surface and lies inside it.</summary> + public bool Fits(int surfaceWidth, int surfaceHeight) => + SurfaceWidth == surfaceWidth && SurfaceHeight == surfaceHeight && Left >= 0 && Top >= 0 && + (long)Left + Width <= surfaceWidth && (long)Top + Height <= surfaceHeight; +} + +/// <summary>Where a presenter takes the overlay layers it draws over each presented frame.</summary> +public interface IOverlayLayerSource +{ + /// <summary>Moves whenever a layer appears, changes or hides: a presenter that saw it last can skip a present.</summary> + long Version { get; } + + /// <summary> + /// Adds the visible layers painted for a surface of this size to <paramref name="frames"/>, in + /// draw order. A layer that has nothing to draw at this size is left out. + /// </summary> + void Collect(int surfaceWidth, int surfaceHeight, List<OverlayLayerFrame> frames); +} + +/// <summary> +/// Paints the registered <see cref="OverlayLayer"/>s in this process, repainting a layer only when +/// its revision or the surface size changed. A layer is placed as the Vulkan presenter places it: +/// its bounds for the surface, the rows its render reports used centred vertically in them. +/// </summary> +public sealed class OverlayLayerPainter : IOverlayLayerSource +{ + private readonly object _gate = new(); + private readonly Dictionary<int, OverlayLayerFrame> _frames = new(); + private readonly Func<OverlayLayer[]> _layers; + + public OverlayLayerPainter() + : this(OverlayLayers.Snapshot) + { + } + + public OverlayLayerPainter(Func<OverlayLayer[]> layers) + { + _layers = layers; + } + + public long Version => OverlayLayers.Version; + + public void Collect(int surfaceWidth, int surfaceHeight, List<OverlayLayerFrame> frames) + { + lock (_gate) + { + var layers = _layers(); + for (var id = 0; id < layers.Length; id++) + { + var layer = layers[id]; + // Read before the visibility, as the Vulkan presenter does: a change in between is + // painted again on the next collection. + var revision = layer.Revision; + if (!layer.IsVisible) + { + _frames.Remove(id); + continue; + } + + if (_frames.TryGetValue(id, out var frame) && frame.Revision == revision && + frame.SurfaceWidth == surfaceWidth && frame.SurfaceHeight == surfaceHeight) + { + frames.Add(frame); + continue; + } + + var painted = Paint(id, layer, revision, surfaceWidth, surfaceHeight); + if (painted is null) + { + _frames.Remove(id); + continue; + } + + _frames[id] = painted; + frames.Add(painted); + } + + if (_frames.Count > layers.Length) + { + foreach (var stale in _frames.Keys.Where(id => id >= layers.Length).ToList()) + { + _frames.Remove(stale); + } + } + } + } + + /// <summary>Paints one layer for a surface, or null when it has no room on it (a surface too small for it).</summary> + public static OverlayLayerFrame? Paint(int id, OverlayLayer layer, long revision, int surfaceWidth, int surfaceHeight) + { + var bounds = layer.Bounds(surfaceWidth, surfaceHeight); + if (bounds.Width <= 0 || bounds.Height <= 0 || bounds.Left < 0 || bounds.Top < 0 || + bounds.Right > surfaceWidth || bounds.Bottom > surfaceHeight) + { + return null; + } + + var pixels = new byte[checked(bounds.Width * bounds.Height * 4)]; + var unit = OverlayStyle.UnitFor(surfaceHeight); + var used = OverlayPainter.RenderInto( + pixels, bounds.Width, bounds.Height, canvas => layer.Render(canvas, bounds.Width, bounds.Height, unit)); + var rows = used == bounds.Height ? pixels : pixels.AsSpan(0, bounds.Width * used * 4).ToArray(); + return new OverlayLayerFrame( + id, revision, surfaceWidth, surfaceHeight, bounds.Left, bounds.Top + (bounds.Height - used) / 2, + bounds.Width, used, rows); + } +} + +/// <summary> +/// The presenter's side of the overlay layers: where it takes them from, and the size of the surface +/// it presents to, which the painting side needs. By default the layers of this process are painted +/// on the presenting thread; the split's GPU process takes them from the guest process instead. +/// </summary> +public static class OverlayLayerOutput +{ + private static IOverlayLayerSource _source = new OverlayLayerPainter(); + private static long _surface; + + public static IOverlayLayerSource Source + { + get => Volatile.Read(ref _source); + set => Volatile.Write(ref _source, value ?? throw new ArgumentNullException(nameof(value))); + } + + /// <summary>The presented surface's size in pixels; (0, 0) before the presenter reported one.</summary> + public static (int Width, int Height) Surface + { + get + { + var packed = Interlocked.Read(ref _surface); + return ((int)(packed >> 32), (int)(uint)packed); + } + } + + /// <summary>Raised when <see cref="ReportSurface"/> changed the size.</summary> + public static event Action<int, int>? SurfaceChanged; + + /// <summary>Called by the presenter when its drawable takes a new size.</summary> + public static void ReportSurface(int width, int height) + { + var packed = (long)(uint)width << 32 | (uint)height; + if (Interlocked.Exchange(ref _surface, packed) != packed) + { + SurfaceChanged?.Invoke(width, height); + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalOverlayLayerCompositor.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalOverlayLayerCompositor.cs new file mode 100644 index 000000000..bd02c27b6 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalOverlayLayerCompositor.cs @@ -0,0 +1,262 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Overlay; +using SharpEmu.ShaderCompiler.Metal; + +namespace SharpEmu.Gpu.Metal.V2; + +/// <summary> +/// Draws the in-game overlay layers (<see cref="OverlayLayer"/>: the IME keyboard, the save data +/// list) over the presented frame, the Metal counterpart of the Vulkan presenter's +/// RecordOverlayLayers. Each layer's painted BGRA rows live in a texture of their own size, drawn +/// 1:1 at the layer's place with one fullscreen triangle under a viewport and scissor of that +/// rectangle, blended premultiplied over the frame (the panels are opaque, so this is the Vulkan +/// copy; on an extended-range drawable the sRGB pixels are decoded as the performance overlay's are). +/// </summary> +/// <remarks> +/// A repainted layer gets a new texture instead of a write into the one an earlier command buffer may +/// still be sampling; the command buffer keeps the old one alive until it completes. +/// </remarks> +internal sealed class MetalOverlayLayerCompositor : IDisposable +{ + private readonly nint _device; + private readonly Dictionary<int, (nint Texture, OverlayLayerFrame Frame)> _textures = new(); + private readonly HashSet<int> _drawn = new(); + private nint _pipeline; + private nint _hdrPipeline; + private nint _sampler; + private bool _failed; + private int _refusals; + + public MetalOverlayLayerCompositor(nint device) + { + _device = device; + } + + /// <summary>Layers drawn by the last <see cref="Encode"/>.</summary> + public int DrawnLayers { get; private set; } + + /// <summary> + /// Draws <paramref name="frames"/> into the render pass of <paramref name="encoder"/>, whose target + /// is <paramref name="surfaceWidth"/> x <paramref name="surfaceHeight"/>. A frame painted for + /// another size (a resize the painting side has not caught up with) is skipped until its repaint. + /// </summary> + public unsafe bool Encode( + nint encoder, IReadOnlyList<OverlayLayerFrame> frames, int surfaceWidth, int surfaceHeight, bool hdr, double headroom) + { + DrawnLayers = 0; + _drawn.Clear(); + if (frames.Count == 0 || surfaceWidth < 1 || surfaceHeight < 1 || !EnsurePipelines()) + { + ReleaseUndrawn(); + return false; + } + + var bound = false; + foreach (var frame in frames) + { + if (!frame.Fits(surfaceWidth, surfaceHeight)) + { + if (frame.SurfaceWidth == surfaceWidth && frame.SurfaceHeight == surfaceHeight) + { + Refuse($"layer {frame.Id} at {frame.Left},{frame.Top} {frame.Width}x{frame.Height} reaches past the " + + $"{surfaceWidth}x{surfaceHeight} surface it was painted for"); + } + + continue; + } + + var texture = TextureFor(frame); + if (texture == 0) + { + continue; + } + + if (!bound) + { + if (hdr) + { + MetalV2Presenter.EncodeHdrPresentState(encoder, _hdrPipeline, false, headroom); + } + else + { + MetalNative.SendVoid(encoder, MetalNative.Selector("setRenderPipelineState:"), _pipeline); + } + + MetalNative.SendSetAtIndex( + encoder, MetalNative.Selector("setFragmentSamplerState:atIndex:"), _sampler, 0); + bound = true; + } + + MetalNative.SendVoidViewport( + encoder, + MetalNative.Selector("setViewport:"), + new MtlViewport + { + OriginX = frame.Left, + OriginY = frame.Top, + Width = frame.Width, + Height = frame.Height, + ZNear = 0, + ZFar = 1, + }); + MetalNative.SendVoidScissor( + encoder, + MetalNative.Selector("setScissorRect:"), + new MtlScissorRect + { + X = (nuint)frame.Left, + Y = (nuint)frame.Top, + Width = (nuint)frame.Width, + Height = (nuint)frame.Height, + }); + MetalNative.SendSetAtIndex(encoder, MetalNative.Selector("setFragmentTexture:atIndex:"), texture, 0); + MetalNative.SendDrawPrimitives( + encoder, MetalNative.Selector("drawPrimitives:vertexStart:vertexCount:"), Mtl.PrimitiveTriangle, 0, 3); + _drawn.Add(frame.Id); + DrawnLayers++; + } + + if (bound) + { + // Later draws in this encoder (the performance overlay) must not inherit the last layer's rectangle. + MetalNative.SendVoidViewport( + encoder, + MetalNative.Selector("setViewport:"), + new MtlViewport { Width = surfaceWidth, Height = surfaceHeight, ZNear = 0, ZFar = 1 }); + MetalNative.SendVoidScissor( + encoder, + MetalNative.Selector("setScissorRect:"), + new MtlScissorRect { Width = (nuint)surfaceWidth, Height = (nuint)surfaceHeight }); + } + + ReleaseUndrawn(); + return DrawnLayers != 0; + } + + private unsafe nint TextureFor(OverlayLayerFrame frame) + { + if (_textures.TryGetValue(frame.Id, out var cached) && ReferenceEquals(cached.Frame, frame)) + { + return cached.Texture; + } + + var descriptor = MetalNative.SendTextureDescriptor( + MetalNative.Class("MTLTextureDescriptor"), + MetalNative.Selector("texture2DDescriptorWithPixelFormat:width:height:mipmapped:"), + (nuint)MtlFormat.Bgra8Unorm, + (nuint)frame.Width, + (nuint)frame.Height, + mipmapped: false); + var texture = MetalNative.Send(_device, MetalNative.Selector("newTextureWithDescriptor:"), descriptor); + if (texture == 0) + { + Refuse($"no texture for layer {frame.Id} ({frame.Width}x{frame.Height})"); + return 0; + } + + fixed (byte* pixels = frame.Pixels) + { + MetalNative.SendReplaceRegion( + texture, + MetalNative.Selector("replaceRegion:mipmapLevel:withBytes:bytesPerRow:"), + new MtlRegion { Width = (nuint)frame.Width, Height = (nuint)frame.Height, Depth = 1 }, + 0, + (nint)pixels, + (nuint)(frame.Width * 4)); + } + + if (cached.Texture != 0) + { + MetalNative.SendVoid(cached.Texture, MetalNative.Selector("release")); + } + + _textures[frame.Id] = (texture, frame); + return texture; + } + + // A layer that was not drawn this time (hidden, or waiting for its repaint at a new size) gives + // its texture back; it is uploaded again when it returns. + private void ReleaseUndrawn() + { + if (_textures.Count == _drawn.Count) + { + return; + } + + foreach (var id in _textures.Keys.Where(id => !_drawn.Contains(id)).ToList()) + { + MetalNative.SendVoid(_textures[id].Texture, MetalNative.Selector("release")); + _textures.Remove(id); + } + } + + private bool EnsurePipelines() + { + if (_pipeline != 0 && _hdrPipeline != 0 && _sampler != 0) + { + return true; + } + + if (_failed) + { + return false; + } + + var source = MslFixedShaders.CreateOverlayFragment(); + if (!MetalV2Presenter.TryCreatePresentPipeline(_device, out _pipeline, out var error, source, "overlay_fs", + MtlFormat.Bgra8Unorm, premultipliedBlend: true) || + !MetalV2Presenter.TryCreatePresentPipeline(_device, out _hdrPipeline, out error, source, "overlay_hdr_fs", + MetalV2HdrOutput.PixelFormat, premultipliedBlend: true)) + { + Console.Error.WriteLine($"[METAL-V2][ERROR] The overlay layer pipeline failed; overlay layers are not drawn: {error}"); + _failed = true; + return false; + } + + // Nearest filtering (the sampler default): every layer is drawn 1:1. + var samplerDescriptor = MetalNative.Send( + MetalNative.Send(MetalNative.Class("MTLSamplerDescriptor"), MetalNative.Selector("alloc")), + MetalNative.Selector("init")); + _sampler = MetalNative.Send(_device, MetalNative.Selector("newSamplerStateWithDescriptor:"), samplerDescriptor); + MetalNative.SendVoid(samplerDescriptor, MetalNative.Selector("release")); + if (_sampler == 0) + { + Console.Error.WriteLine("[METAL-V2][ERROR] The overlay layer sampler failed; overlay layers are not drawn."); + _failed = true; + return false; + } + + return true; + } + + private void Refuse(string what) + { + if (++_refusals <= 8) + { + Console.Error.WriteLine($"[METAL-V2][WARN] Overlay layer not drawn: {what}."); + } + } + + public void Dispose() + { + foreach (var (texture, _) in _textures.Values) + { + MetalNative.SendVoid(texture, MetalNative.Selector("release")); + } + + _textures.Clear(); + foreach (var handle in new[] { _pipeline, _hdrPipeline, _sampler }) + { + if (handle != 0) + { + MetalNative.SendVoid(handle, MetalNative.Selector("release")); + } + } + + _pipeline = 0; + _hdrPipeline = 0; + _sampler = 0; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.OverlayLayers.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.OverlayLayers.cs new file mode 100644 index 000000000..4038c28c9 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.OverlayLayers.cs @@ -0,0 +1,56 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Overlay; + +namespace SharpEmu.Gpu.Metal.V2; + +// The in-game overlay layers (system dialogs drawn by the emulator: the IME keyboard, the save +// data list), drawn over every presented frame before the performance overlay, as the Vulkan +// presenter records them. OverlayLayerOutput.Source says where they come from: painted here in a +// single process, or painted in the guest process and shipped over the split. +internal static partial class MetalV2Presenter +{ + private static readonly List<OverlayLayerFrame> _overlayLayerFrames = []; + private static MetalOverlayLayerCompositor? _overlayLayerCompositor; + private static long _overlayLayersPresentedVersion = -1; + + // True when a layer appeared, changed or hid since the last present: an unchanged guest frame + // is presented again to show it. + private static bool OverlayLayersNeedPresent() => + OverlayLayerOutput.Source.Version != Volatile.Read(ref _overlayLayersPresentedVersion); + + // Runs on the window thread, inside the present encoder, after the frame is drawn. + private static void EncodeOverlayLayers(nint encoder) + { + var source = OverlayLayerOutput.Source; + // Read before collecting: a change made while the layers are collected presents again. + var version = source.Version; + _overlayLayerFrames.Clear(); + var width = (int)_drawableWidth; + var height = (int)_drawableHeight; + if (width > 0 && height > 0) + { + source.Collect(width, height, _overlayLayerFrames); + } + + Volatile.Write(ref _overlayLayersPresentedVersion, version); + if (_overlayLayerFrames.Count == 0 && _overlayLayerCompositor is null) + { + return; + } + + _overlayLayerCompositor ??= new MetalOverlayLayerCompositor(_device); + _ = _overlayLayerCompositor.Encode( + encoder, _overlayLayerFrames, width, height, _layerHdrActive, _edrCurrentHeadroom); + _overlayLayerFrames.Clear(); + } + + private static void ReleaseOverlayLayerResources() + { + _overlayLayerCompositor?.Dispose(); + _overlayLayerCompositor = null; + _overlayLayerFrames.Clear(); + Volatile.Write(ref _overlayLayersPresentedVersion, -1); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs index bc099f327..8b0dccd1d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs @@ -611,6 +611,7 @@ private static void RunWindow() finally { ReleasePerfOverlayResources(); + ReleaseOverlayLayerResources(); Volatile.Write(ref _hostWindow, null); _metalLayer = 0; lock (_gate) @@ -661,6 +662,7 @@ private static void SyncDrawableSize() _drawableWidth = pixelWidth; _drawableHeight = pixelHeight; SharpEmu.Libs.Media.MoviePresentationServices.SetPresentationSize((uint)pixelWidth, (uint)pixelHeight); + SharpEmu.Libs.Overlay.OverlayLayerOutput.ReportSurface(pixelWidth, pixelHeight); MetalNative.SendVoidSize( _metalLayer, MetalNative.Selector("setDrawableSize:"), @@ -748,7 +750,8 @@ private static void PresentFrame() // Before a guest/movie image exists, the prewarm overlay may animate. // The performance panel refreshes on its own clock, so it also counts as animated. if (ReusePresentedFrame && - !PresentationCache.NeedsPresent(in stamp, (presented == 0 && !movie) || PerfOverlayNeedsPresent())) + !PresentationCache.NeedsPresent( + in stamp, (presented == 0 && !movie) || PerfOverlayNeedsPresent() || OverlayLayersNeedPresent())) { ReportPresentationStatistics(presented: false); // nextDrawable normally paces this loop; skipping it must not spin. @@ -784,6 +787,7 @@ private static void PresentFrame() EncodePresent(encoder, texture, width, height, !movie && presented != 0 && presentedHdr); } + EncodeOverlayLayers(encoder); EncodePerfOverlay(encoder, window.ContentsScale); MetalNative.SendVoid(encoder, MetalNative.Selector("endEncoding")); MetalNative.SendVoid(commandBuffer, MetalNative.Selector("presentDrawable:"), drawable); @@ -1181,7 +1185,7 @@ private static void EncodePresent(nint encoder, nint texture, uint frameWidth, u encoder, MetalNative.Selector("drawPrimitives:vertexStart:vertexCount:"), Mtl.PrimitiveTriangle, 0, 3); } - private static bool TryCreatePresentPipeline( + internal static bool TryCreatePresentPipeline( nint device, out nint pipeline, out string error, diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalOverlayLayerCompositorTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalOverlayLayerCompositorTests.cs new file mode 100644 index 000000000..8a2eeb37e --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalOverlayLayerCompositorTests.cs @@ -0,0 +1,233 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Overlay; +using Xunit; +using Xunit.Abstractions; +using Native = SharpEmu.Gpu.Metal.MetalNative; + +namespace SharpEmu.Gpu.Metal.Tests; + +// The in-game overlay layers on the v2 presenter: a layer's painted pixels land on the presented +// image at the layer's place, 1:1, blended premultiplied over the frame, and nothing outside it moves. +public sealed class MetalOverlayLayerCompositorTests(ITestOutputHelper output) +{ + private const int SurfaceWidth = 32; + private const int SurfaceHeight = 16; + + // The frame under the layers: BGRA (40, 80, 120, 255). + private const byte FrameB = 40, FrameG = 80, FrameR = 120; + + [Fact] + public void ALayersPixelsLandAtItsPlaceBlendedOverTheFrame() + { + if (!RequireDevice()) return; + + // A 6x3 layer at (10, 5): an opaque row, a half-transparent row, a transparent row; each + // row's first pixel is marked so a flip or an offset shows. + const int left = 10, top = 5, width = 6, height = 3; + var pixels = new byte[width * height * 4]; + for (var x = 0; x < width; x++) + { + Put(pixels, width, x, 0, 200, 10, 30, 255); + Put(pixels, width, x, 1, 100, 0, 0, 128); + Put(pixels, width, x, 2, 0, 0, 0, 0); + } + + Put(pixels, width, 0, 0, 1, 2, 3, 255); + var frame = new OverlayLayerFrame(0, 1, SurfaceWidth, SurfaceHeight, left, top, width, height, pixels); + + var image = Composite([frame], out var drawn); + Assert.Equal(1, drawn); + + for (var y = 0; y < SurfaceHeight; y++) + { + for (var x = 0; x < SurfaceWidth; x++) + { + var inside = x >= left && x < left + width && y >= top && y < top + height; + var (b, g, r, a) = Get(image, x, y); + if (!inside) + { + Assert.True((b, g, r, a) == (FrameB, FrameG, FrameR, 255), $"({x}, {y}) outside the layer changed: {(b, g, r, a)}"); + continue; + } + + var row = y - top; + var column = x - left; + var (sb, sg, sr, sa) = (pixels[(row * width + column) * 4], pixels[(row * width + column) * 4 + 1], + pixels[(row * width + column) * 4 + 2], pixels[(row * width + column) * 4 + 3]); + // Premultiplied source-over: out = src + dst * (1 - src.a). + AssertNear(sb + FrameB * (255 - sa) / 255.0, b, $"({x}, {y}) blue"); + AssertNear(sg + FrameG * (255 - sa) / 255.0, g, $"({x}, {y}) green"); + AssertNear(sr + FrameR * (255 - sa) / 255.0, r, $"({x}, {y}) red"); + } + } + + Assert.Equal((1, 2, 3), (Get(image, left, top).B, Get(image, left, top).G, Get(image, left, top).R)); + } + + [Fact] + public void ALayerPaintedForAnotherSurfaceWaitsForItsRepaint() + { + if (!RequireDevice()) return; + + var pixels = new byte[4 * 4 * 4]; + Array.Fill(pixels, (byte)255); + var stale = new OverlayLayerFrame(0, 1, SurfaceWidth * 2, SurfaceHeight * 2, 0, 0, 4, 4, pixels); + var image = Composite([stale], out var drawn); + Assert.Equal(0, drawn); + Assert.Equal((FrameB, FrameG, FrameR, (byte)255), Get(image, 0, 0)); + } + + [Fact] + public void LayersDrawInOrderAndARepaintReplacesTheImage() + { + if (!RequireDevice()) return; + + var below = Solid(0, 1, 2, 2, 8, 8, 0, 0, 255, 255); + var above = Solid(1, 1, 6, 6, 8, 8, 255, 0, 0, 255); + var device = Device.Value; + using var compositor = new MetalOverlayLayerCompositor(device); + var image = Composite(compositor, [below, above], out var drawn); + Assert.Equal(2, drawn); + Assert.Equal(((byte)0, (byte)0, (byte)255, (byte)255), Get(image, 3, 3)); + Assert.Equal(((byte)255, (byte)0, (byte)0, (byte)255), Get(image, 7, 7)); + + // The same layer repainted green: the compositor uploads the new frame, not the cached one. + var repainted = Solid(1, 2, 6, 6, 8, 8, 0, 255, 0, 255); + image = Composite(compositor, [below, repainted], out drawn); + Assert.Equal(2, drawn); + Assert.Equal(((byte)0, (byte)255, (byte)0, (byte)255), Get(image, 7, 7)); + } + + private static OverlayLayerFrame Solid(int id, long revision, int left, int top, int width, int height, + byte b, byte g, byte r, byte a) + { + var pixels = new byte[width * height * 4]; + for (var index = 0; index < width * height; index++) + { + pixels[index * 4] = b; + pixels[index * 4 + 1] = g; + pixels[index * 4 + 2] = r; + pixels[index * 4 + 3] = a; + } + + return new OverlayLayerFrame(id, revision, SurfaceWidth, SurfaceHeight, left, top, width, height, pixels); + } + + private static void Put(byte[] pixels, int width, int x, int y, byte b, byte g, byte r, byte a) + { + var offset = (y * width + x) * 4; + pixels[offset] = b; + pixels[offset + 1] = g; + pixels[offset + 2] = r; + pixels[offset + 3] = a; + } + + private static (byte B, byte G, byte R, byte A) Get(byte[] image, int x, int y) + { + var offset = (y * SurfaceWidth + x) * 4; + return (image[offset], image[offset + 1], image[offset + 2], image[offset + 3]); + } + + private static void AssertNear(double expected, byte actual, string what) => + Assert.True(Math.Abs(expected - actual) <= 1.5, $"{what}: expected {expected:F1}, got {actual}"); + + private static byte[] Composite(IReadOnlyList<OverlayLayerFrame> frames, out int drawn) + { + using var compositor = new MetalOverlayLayerCompositor(Device.Value); + return Composite(compositor, frames, out drawn); + } + + // Clears a BGRA8 target to the frame colour, composites the layers in the same render pass, as + // the presenter does after drawing the frame, and reads the target back. + private static unsafe byte[] Composite(MetalOverlayLayerCompositor compositor, IReadOnlyList<OverlayLayerFrame> frames, out int drawn) + { + var device = Device.Value; + var pool = Native.objc_autoreleasePoolPush(); + nint target = 0, buffer = 0, queue = 0; + try + { + var descriptor = Native.SendTextureDescriptor( + Native.Class("MTLTextureDescriptor"), + Native.Selector("texture2DDescriptorWithPixelFormat:width:height:mipmapped:"), + (nuint)MtlFormat.Bgra8Unorm, + SurfaceWidth, + SurfaceHeight, + mipmapped: false); + Native.SendVoidNUInt(descriptor, Native.Selector("setUsage:"), 4); + target = Native.Send(device, Native.Selector("newTextureWithDescriptor:"), descriptor); + Assert.NotEqual(0, target); + const int bytes = SurfaceWidth * SurfaceHeight * 4; + buffer = Native.SendNewBuffer(device, Native.Selector("newBufferWithLength:options:"), bytes, 0); + queue = Native.Send(device, Native.Selector("newCommandQueue")); + var command = Native.Send(queue, Native.Selector("commandBuffer")); + + var pass = Native.Send(Native.Class("MTLRenderPassDescriptor"), Native.Selector("renderPassDescriptor")); + var attachment = Native.SendAtIndex( + Native.Send(pass, Native.Selector("colorAttachments")), Native.Selector("objectAtIndexedSubscript:"), 0); + Native.SendVoid(attachment, Native.Selector("setTexture:"), target); + Native.SendVoidNUInt(attachment, Native.Selector("setLoadAction:"), (nuint)Mtl.LoadActionClear); + Native.SendVoidNUInt(attachment, Native.Selector("setStoreAction:"), (nuint)Mtl.StoreActionStore); + Native.SendVoidClearColor( + attachment, + Native.Selector("setClearColor:"), + new MtlClearColor { Red = FrameR / 255.0, Green = FrameG / 255.0, Blue = FrameB / 255.0, Alpha = 1 }); + var encoder = Native.Send(command, Native.Selector("renderCommandEncoderWithDescriptor:"), pass); + compositor.Encode(encoder, frames, SurfaceWidth, SurfaceHeight, hdr: false, headroom: 1); + drawn = compositor.DrawnLayers; + Native.SendVoid(encoder, Native.Selector("endEncoding")); + + var blit = Native.Send(command, Native.Selector("blitCommandEncoder")); + Native.SendCopyTextureToBuffer( + blit, + Native.Selector( + "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:" + + "destinationOffset:destinationBytesPerRow:destinationBytesPerImage:"), + target, + 0, + 0, + default, + new MtlSize { Width = SurfaceWidth, Height = SurfaceHeight, Depth = 1 }, + buffer, + 0, + SurfaceWidth * 4, + bytes); + Native.SendVoid(blit, Native.Selector("endEncoding")); + Native.SendVoid(command, Native.Selector("commit")); + Native.SendVoid(command, Native.Selector("waitUntilCompleted")); + + var result = new byte[bytes]; + new ReadOnlySpan<byte>((void*)Native.Send(buffer, Native.Selector("contents")), bytes).CopyTo(result); + return result; + } + finally + { + foreach (var handle in new[] { target, buffer, queue }) + { + if (handle != 0) + { + Native.SendVoid(handle, Native.Selector("release")); + } + } + + Native.objc_autoreleasePoolPop(pool); + } + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("The overlay layer compositor runs on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } + + private static readonly Lazy<nint> Device = new(Native.MTLCreateSystemDefaultDevice); +} From 6755ca8bca5c964e22c63283f8d35a063c8dbd0d Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:04:48 +0000 Subject: [PATCH 46/64] [Pad] Type text into system dialogs from the macOS window Port of upstream 3cc24a9a8's SDL text input to AppKit: while a system dialog takes text, a key press also submits its layout-translated characters (-[NSEvent characters], control and function keys filtered) to SystemDialogInput.OnText. Forward delete maps to VK_DELETE as upstream's SDLK_DELETE does, and the split's key state reports new presses to the dialog. --- src/SharpEmu.Libs/Pad/HostWindowInput.cs | 46 +++++++++++++++++++ src/SharpEmu.Libs/Pad/SystemDialogInput.cs | 15 +++++- .../Input/MacKeyMap.cs | 28 ++++++++++- .../Windowing/MacHostWindow.cs | 19 +++++++- .../Platform/MacKeyMapTests.cs | 15 ++++++ 5 files changed, 118 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/Pad/HostWindowInput.cs b/src/SharpEmu.Libs/Pad/HostWindowInput.cs index 7c8f41eca..655633112 100644 --- a/src/SharpEmu.Libs/Pad/HostWindowInput.cs +++ b/src/SharpEmu.Libs/Pad/HostWindowInput.cs @@ -80,6 +80,7 @@ public static int CopyState(Span<int> keys, out bool focused, out HostGamepadSta public static void SetKeys(ReadOnlySpan<int> keys) { bool changed; + List<int>? pressed = null; lock (Gate) { var before = PressedKeys.Count; @@ -90,6 +91,10 @@ public static void SetKeys(ReadOnlySpan<int> keys) { kept++; } + else + { + (pressed ??= []).Add(key); + } } PressedKeys.Clear(); @@ -102,10 +107,51 @@ public static void SetKeys(ReadOnlySpan<int> keys) Bump(); } + // A key that went down since the last state is a press for a system dialog, as SetKey reports it. + if (pressed is not null) + { + foreach (var key in pressed) + { + SystemDialogInput.OnKeyDown(key); + } + } + // The guest process's pad history (PadExports.RecordInputChange) sees the split's key changes too. if (changed) Changed?.Invoke(); } + private static int _peerWantsText; + + /// <summary> + /// Whether the window should turn key presses into typed text: a system dialog of this process + /// takes text, or (in the split's GPU process, which owns the window) one of the guest process's. + /// </summary> + public static bool WantsText => SystemDialogInput.WantsText || Volatile.Read(ref _peerWantsText) != 0; + + /// <summary>The split's GPU process: the guest process's system dialog started or stopped taking text.</summary> + public static void SetPeerWantsText(bool wanted) => Volatile.Write(ref _peerWantsText, wanted ? 1 : 0); + + /// <summary>Set by the split's GPU process: typed text goes to the guest process instead of this one.</summary> + public static Action<string>? TextForwarder { get; set; } + + /// <summary>Text the user typed into the window (layout-translated characters, no control keys).</summary> + public static void SubmitText(string text) + { + if (string.IsNullOrEmpty(text)) + { + return; + } + + if (TextForwarder is { } forward) + { + forward(text); + } + else + { + SystemDialogInput.OnText(text); + } + } + public static void Connect(IHostGamepadOutput? gamepadOutput = null) { lock (Gate) diff --git a/src/SharpEmu.Libs/Pad/SystemDialogInput.cs b/src/SharpEmu.Libs/Pad/SystemDialogInput.cs index b2f4a6b64..2895c37fd 100644 --- a/src/SharpEmu.Libs/Pad/SystemDialogInput.cs +++ b/src/SharpEmu.Libs/Pad/SystemDialogInput.cs @@ -20,11 +20,22 @@ public static class SystemDialogInput public static bool WantsText => Volatile.Read(ref _wantsText) != 0; + /// <summary>Raised when <see cref="WantsText"/> changes; the split's guest process tells the window's process.</summary> + public static event Action<bool>? WantsTextChanged; + + private static void SetWantsText(bool wanted) + { + if (Interlocked.Exchange(ref _wantsText, wanted ? 1 : 0) != (wanted ? 1 : 0)) + { + WantsTextChanged?.Invoke(wanted); + } + } + internal static void Capture(bool wantsText = false) { Keys.Clear(); Texts.Clear(); - Volatile.Write(ref _wantsText, wantsText ? 1 : 0); + SetWantsText(wantsText); Volatile.Write(ref _capturing, 1); } @@ -71,7 +82,7 @@ internal static void Release() { Volatile.Write(ref _residualButtons, PadExports.ReadSystemDialogState().Buttons); PadExports.DiscardUnreadStates(); - Volatile.Write(ref _wantsText, 0); + SetWantsText(false); Texts.Clear(); Volatile.Write(ref _capturing, 0); } diff --git a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacKeyMap.cs b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacKeyMap.cs index f8867b237..3e53a9189 100644 --- a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacKeyMap.cs +++ b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacKeyMap.cs @@ -39,6 +39,7 @@ internal static class MacVirtualKeyCode public const ushort M = 0x2E; public const ushort Tab = 0x30; public const ushort Delete = 0x33; + public const ushort ForwardDelete = 0x75; public const ushort Escape = 0x35; public const ushort F11 = 0x67; public const ushort F3 = 0x63; @@ -60,7 +61,7 @@ internal static class MacVirtualKeyCode /// window. The guest-facing key set is defined by what /// <c>HostWindowInput.SetKey</c> consumers expect, which the SDL host window /// produced from SDL keycodes; this table reproduces exactly that set (A-Z plus -/// backspace, tab, return, escape and the four arrows) so key behaviour is +/// backspace, tab, return, escape, forward delete and the four arrows) so key behaviour is /// identical on both windowing backends. Pure logic, no AppKit — unit tested. /// </summary> internal static class MacKeyMap @@ -77,6 +78,7 @@ public static bool TryMapVirtualKey(ushort keyCode, out int virtualKey) MacVirtualKeyCode.Tab => 0x09, // VK_TAB MacVirtualKeyCode.Return => 0x0D, // VK_RETURN MacVirtualKeyCode.Escape => 0x1B, // VK_ESCAPE + MacVirtualKeyCode.ForwardDelete => 0x2E, // VK_DELETE MacVirtualKeyCode.LeftArrow => 0x25, // VK_LEFT MacVirtualKeyCode.UpArrow => 0x26, // VK_UP MacVirtualKeyCode.RightArrow => 0x27, // VK_RIGHT @@ -111,4 +113,28 @@ public static bool TryMapVirtualKey(ushort keyCode, out int virtualKey) }; return virtualKey != 0; } + + /// <summary> + /// The text a key press types, from <c>-[NSEvent characters]</c> (already translated by the + /// keyboard layout, dead keys included): everything but control characters and the private-use + /// range AppKit reports function, arrow and navigation keys in (U+F700-U+F8FF). + /// </summary> + public static string TypedText(string? characters) + { + if (string.IsNullOrEmpty(characters)) + { + return string.Empty; + } + + var builder = new System.Text.StringBuilder(characters.Length); + foreach (var character in characters) + { + if (!char.IsControl(character) && character is not (>= '\uF700' and <= '\uF8FF')) + { + builder.Append(character); + } + } + + return builder.ToString(); + } } diff --git a/src/platforms/macos/SharpEmu.Platform.MacOS/Windowing/MacHostWindow.cs b/src/platforms/macos/SharpEmu.Platform.MacOS/Windowing/MacHostWindow.cs index c37219a09..46dd94a7c 100644 --- a/src/platforms/macos/SharpEmu.Platform.MacOS/Windowing/MacHostWindow.cs +++ b/src/platforms/macos/SharpEmu.Platform.MacOS/Windowing/MacHostWindow.cs @@ -737,11 +737,26 @@ private bool HandleKeyEvent(nint nsEvent, bool down) return true; } + // While a system dialog takes text (the IME keyboard), a press, repeats included, also + // types its layout-translated characters, as SDL's text input events do for the other + // windows; the key itself still reaches the guest below. Command chords stay with the menu bar. + var typed = false; + if (down && !command && HostWindowInput.WantsText) + { + var text = MacKeyMap.TypedText( + MacObjC.ReadNsString(MacObjC.Send(nsEvent, MacObjC.Selector("characters")))); + if (text.Length != 0) + { + HostWindowInput.SubmitText(text); + typed = true; + } + } + if (!MacKeyMap.TryMapVirtualKey(keyCode, out var virtualKey)) { // Unmapped keys stay with AppKit so menu key equivalents and text - // input in system UI keep working. - return false; + // input in system UI keep working; one that typed text is taken. + return typed; } // Command chords belong to the menu bar, never to the guest. diff --git a/tests/SharpEmu.Libs.Tests/Platform/MacKeyMapTests.cs b/tests/SharpEmu.Libs.Tests/Platform/MacKeyMapTests.cs index c86a92715..2aa6b45c6 100644 --- a/tests/SharpEmu.Libs.Tests/Platform/MacKeyMapTests.cs +++ b/tests/SharpEmu.Libs.Tests/Platform/MacKeyMapTests.cs @@ -18,6 +18,7 @@ public sealed class MacKeyMapTests [InlineData(MacVirtualKeyCode.Tab, 0x09)] [InlineData(MacVirtualKeyCode.Return, 0x0D)] [InlineData(MacVirtualKeyCode.Escape, 0x1B)] + [InlineData(MacVirtualKeyCode.ForwardDelete, 0x2E)] [InlineData(MacVirtualKeyCode.LeftArrow, 0x25)] [InlineData(MacVirtualKeyCode.UpArrow, 0x26)] [InlineData(MacVirtualKeyCode.RightArrow, 0x27)] @@ -74,4 +75,18 @@ public void HotkeysAndModifiersAreNotForwardedToTheGuest(ushort keyCode) Assert.False(MacKeyMap.TryMapVirtualKey(keyCode, out var virtualKey)); Assert.Equal(0, virtualKey); } + + [Theory] + [InlineData("a", "a")] + [InlineData("é", "é")] + [InlineData(" ", " ")] + [InlineData("\r", "")] + [InlineData("\t", "")] + [InlineData("\u007F", "")] + [InlineData("\u001B", "")] + [InlineData("\uF702", "")] // NSLeftArrowFunctionKey + [InlineData("\uF728", "")] // NSDeleteFunctionKey + [InlineData(null, "")] + public void OnlyPrintableCharactersAreTyped(string? characters, string expected) => + Assert.Equal(expected, MacKeyMap.TypedText(characters)); } From dead4ef79a8b0cf25c7e53d47b96a301ec18e69b Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:04:48 +0000 Subject: [PATCH 47/64] [GPU] Carry overlay layers and typed text across the split (protocol 10) The overlay layers live with the guest's system dialogs in the guest process and the presenter in the GPU process: the GPU process reports its drawable size (OverlaySurface), the guest process paints the layers for it and sends each repaint or hide in 256 KiB pieces (OverlayLayer), and the GPU process's presenter draws them. The guest's dialog tells the window when to type text (Control TextInput) and typed text comes back as a TypedText notice. --- docs/macos/split-protocol.md | 9 +- src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs | 12 +- src/SharpEmu.GpuRemote/GpuSplitMessages.cs | 38 ++++ src/SharpEmu.GpuSplit/GuestProcessSide.cs | 3 + src/SharpEmu.GpuSplit/RemoteOverlayLayers.cs | 111 +++++++++++ src/SharpEmu.GpuSplit/SplitGpuHost.cs | 44 +++++ src/SharpEmu.GpuSplit/SplitGpuSession.cs | 24 +++ .../SplitOverlayLayerSender.cs | 186 ++++++++++++++++++ .../SplitTransportTests.cs | 2 + .../SplitInProcessTests.cs | 88 +++++++++ 10 files changed, 512 insertions(+), 5 deletions(-) create mode 100644 src/SharpEmu.GpuSplit/RemoteOverlayLayers.cs create mode 100644 src/SharpEmu.GpuSplit/SplitOverlayLayerSender.cs diff --git a/docs/macos/split-protocol.md b/docs/macos/split-protocol.md index 756732fcc..1af13a2eb 100644 --- a/docs/macos/split-protocol.md +++ b/docs/macos/split-protocol.md @@ -31,7 +31,8 @@ page watches 100-2600/s (batch); submissions 30 and 200-350/s; SubmitDone/flips All records are little-endian blittable structs (`GpuSplitMessages.cs`) on the transport rings; synchronous calls use `SyncCallTable` both ways: A → B (`SyncCalls`, signal-safe on the A side) and B → A (`ReverseSyncCalls`, ordinary B -threads). Add new kinds at the end of the enums; bump `GpuRemoteProtocol.Version` (now 7). +threads). Add new kinds at the end of the enums; bump `GpuRemoteProtocol.Version` (now 10; the history is in its +remarks). Revision 7 combines frame-boundary messages, input-change/display reservations and the pending-writeback page summary. Independent revisions 4, 5 and 6 are rejected @@ -56,8 +57,9 @@ fused program. | `CpuWrite` | address, size | A managed write that has landed, only for ranges the GPU-interest summary marks. B calls its stores' `MarkCpuWriteLanded` in ring order, before any later submission. | | `ShaderHeader` | codeAddress, headerAddress | Mirrors `AgcExports._shaderHeadersByCode` into B (lookups stay local in B). | | `FusedProgram` | entry, entryHeader, continuation, continuationHeader (zeros: unregistered) | Mirrors `Gen5ShaderTranslator`'s fused-program registry, which B's command streams read, keyed by B's address space. | -| `Control` | EnsureStarted(w,h), HideSplashScreen, RequestClose, CountShaderCompilation | One-way calls of `IGuestGpuBackend`. RequestClose also requests B's session shutdown. | +| `Control` | EnsureStarted(w,h), HideSplashScreen, RequestClose, CountShaderCompilation, TextInput(on) | One-way calls of `IGuestGpuBackend`. RequestClose also requests B's session shutdown. TextInput follows A's `SystemDialogInput.WantsText` (the IME keyboard is up): B's window then turns key presses into typed text. | | `HostFrame` | width, height, total, offset + piece | `Submit` of a CPU frame (splash, video), in pieces of 256 KiB written back to back. | +| `OverlayLayer` | id, visible, revision, surface size, place, size, total, offset + piece | An in-game overlay layer (IME keyboard, save data list) A painted for B's drawable (`SplitOverlayLayerSender`), in pieces of 256 KiB written back to back; visible 0 hides it. B's presenter draws it over every frame (`RemoteOverlayLayers` is its `OverlayLayerOutput.Source`). | | `GamepadOutput` | rumble, trigger rumble, adaptive triggers, lightbar | To the pad, which lives with B's window. | | `VideoOptions` | window options | Options configured after the start. | | `FrameBoundary` | ticket | The ordering half of a split `SubmitDone` (`BeginSubmitDone`): B queues the boundary behind the submissions before it and keeps its wait for `WaitFrameBoundary`. A sends it under its submission gate and waits after releasing it. | @@ -88,7 +90,8 @@ many, so they come after A's earlier records. | `ProtectRequest` | sequence, address, size, guest access, access, flags | B's `PageGuard` (watch arm/drop, ledger changes). A applies it at once on its inbound thread (`TryApplyDerivedProtection`, skipping memory A no longer registers) and raises the shared protection counter (below). A request that takes rights away waits in B until it is applied; one that gives them back does not (the fault path waits instead). | | `Interrupt` | eventId, contextId | `EndOfPipeEvents.Deliver` in A, for an interrupt raised on B's ring thread. Elsewhere interrupts are calls (below). | | `FlipEvent` | kind, flipRequestId | Flip steps sent from B's ring thread (a refused `FlipRequest`). Elsewhere flip steps are calls (below). | -| `VideoOutNotice` | kind, text | CancelOutstandingFlips, PresentationWindowClosed, ReportPresentedFrame, SelectedGpuName. | +| `VideoOutNotice` | kind, text | CancelOutstandingFlips, PresentationWindowClosed, ReportPresentedFrame, SelectedGpuName, TypedText (`SystemDialogInput.OnText` in A). | +| `OverlaySurface` | width, height | B's drawable size, at the start and on every change: A paints the overlay layers for it. | | `Input` | focus, pressed keys, gamepad state and name | B polls its `HostWindowInput` every 4 ms and sends it when it changed; A applies it to its own `HostWindowInput`. | A's inbound thread applies protections itself and hands everything else to an event thread, in order, so a slow event diff --git a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs index 97e20e199..71e55fc03 100644 --- a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs +++ b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs @@ -14,8 +14,10 @@ public static class GpuRemoteProtocol /// 4: frame-boundary messages. 5: input-change and display reservations. /// 6: pending-writeback pages. 7: combined frame, input and writeback layout. /// 8: <see cref="GpuRemoteSyncOpcode.ResidencyRange"/>. - /// 9: <see cref="GpuSplitGamepadOutput.HapticRumble"/> and <see cref="GamepadOutputMessage.DurationMs"/>.</remarks> - public const uint Version = 9; + /// 9: <see cref="GpuSplitGamepadOutput.HapticRumble"/> and <see cref="GamepadOutputMessage.DurationMs"/>. + /// 10: overlay layers (<see cref="GpuRemoteMessage.OverlayLayer"/>, <see cref="GpuRemoteMessage.OverlaySurface"/>) + /// and typed text (<see cref="GpuSplitControl.TextInput"/>, <see cref="GpuSplitNotice.TypedText"/>).</remarks> + public const uint Version = 10; } @@ -101,6 +103,12 @@ public enum GpuRemoteMessage : uint /// <summary>A → B: <see cref="FrameBoundaryMessage"/>, the ordering half of a split <c>SubmitDone</c>.</summary> FrameBoundary = 26, + + /// <summary>A → B: <see cref="OverlayLayerMessage"/>, then one piece of an overlay layer's BGRA pixels (none when hidden).</summary> + OverlayLayer = 27, + + /// <summary>B → A: <see cref="OverlaySurfaceMessage"/>, the drawable size the overlay layers are painted for.</summary> + OverlaySurface = 28, } /// <summary>Opcodes of the A → B synchronous call table.</summary> diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs index 563bcf546..7c6963141 100644 --- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs +++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs @@ -21,6 +21,9 @@ public enum GpuSplitControl : uint HideSplashScreen = 2, RequestClose = 3, CountShaderCompilation = 4, + + /// <summary>Width 1 while a system dialog in A takes typed text, 0 when it stops (<c>SystemDialogInput.WantsText</c>).</summary> + TextInput = 5, } /// <summary>The steps of a flip that B reports to A's video-out state (<see cref="GpuRemoteMessage.FlipEvent"/>).</summary> @@ -57,6 +60,9 @@ public enum GpuSplitNotice : uint /// <summary>The text is the GPU's name, for the window title (<c>SetSelectedGpuName</c>).</summary> SelectedGpuName = 4, + + /// <summary>The text is what the user typed into the window (<c>SystemDialogInput.OnText</c>).</summary> + TypedText = 5, } /// <summary>What a <see cref="GpuRemoteSyncOpcode.Query"/> asks.</summary> @@ -245,6 +251,38 @@ public struct HostFrameMessage public uint Offset; } +[StructLayout(LayoutKind.Sequential)] +public struct OverlayLayerMessage +{ + /// <summary>The layer's index in A's overlay layer registry (its draw order).</summary> + public uint Id; + + /// <summary>0: the layer is hidden and no pixels follow; 1: the pixels of a painted layer follow.</summary> + public uint Visible; + public long Revision; + + /// <summary>The surface the layer was painted for (an <see cref="OverlaySurfaceMessage"/> of B's).</summary> + public uint SurfaceWidth; + public uint SurfaceHeight; + public int Left; + public int Top; + public uint Width; + public uint Height; + + /// <summary>Bytes of the whole layer (Width * Height * 4); B takes it once every piece arrived.</summary> + public uint TotalBytes; + + /// <summary>Where this record's piece goes in the layer.</summary> + public uint Offset; +} + +[StructLayout(LayoutKind.Sequential)] +public struct OverlaySurfaceMessage +{ + public uint Width; + public uint Height; +} + [StructLayout(LayoutKind.Sequential)] public struct AdaptiveTriggerWire { diff --git a/src/SharpEmu.GpuSplit/GuestProcessSide.cs b/src/SharpEmu.GpuSplit/GuestProcessSide.cs index da4d46cd2..03966ca19 100644 --- a/src/SharpEmu.GpuSplit/GuestProcessSide.cs +++ b/src/SharpEmu.GpuSplit/GuestProcessSide.cs @@ -99,6 +99,9 @@ public void Notice(GpuSplitNotice kind, string text) case GpuSplitNotice.SelectedGpuName: VideoOutBackendServices.SetSelectedGpuName(text); break; + case GpuSplitNotice.TypedText: + SystemDialogInput.OnText(text); + break; } } diff --git a/src/SharpEmu.GpuSplit/RemoteOverlayLayers.cs b/src/SharpEmu.GpuSplit/RemoteOverlayLayers.cs new file mode 100644 index 000000000..82bfde1ee --- /dev/null +++ b/src/SharpEmu.GpuSplit/RemoteOverlayLayers.cs @@ -0,0 +1,111 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.CompilerServices; +using SharpEmu.GpuRemote; +using SharpEmu.Libs.Overlay; + +namespace SharpEmu.GpuSplit; + +/// <summary> +/// Process B's overlay layers: the frames the guest process painted (<see cref="SplitOverlayLayerSender"/>), +/// put together from their <see cref="GpuRemoteMessage.OverlayLayer"/> pieces, for the presenter +/// (<see cref="OverlayLayerOutput.Source"/>). +/// </summary> +internal sealed class RemoteOverlayLayers : IOverlayLayerSource +{ + private readonly object _gate = new(); + private readonly SortedDictionary<int, OverlayLayerFrame> _frames = new(); + private readonly Action<string> _report; + private long _version; + + // The layer being received: its pieces arrive back to back on the ring thread. + private OverlayLayerMessage _pending; + private byte[]? _pixels; + private uint _received; + + public RemoteOverlayLayers(Action<string> report) + { + _report = report; + } + + public long Version => Interlocked.Read(ref _version); + + public void Collect(int surfaceWidth, int surfaceHeight, List<OverlayLayerFrame> frames) + { + lock (_gate) + { + foreach (var frame in _frames.Values) + { + // A layer painted for the previous size waits for its repaint at this one. + if (frame.SurfaceWidth == surfaceWidth && frame.SurfaceHeight == surfaceHeight) + { + frames.Add(frame); + } + } + } + } + + /// <summary>One <see cref="GpuRemoteMessage.OverlayLayer"/> record, on the ring thread.</summary> + public void Take(ReadOnlySpan<byte> payload) + { + var header = GpuSplitWire.Read<OverlayLayerMessage>(payload); + var piece = payload[Unsafe.SizeOf<OverlayLayerMessage>()..]; + if (header.Visible == 0) + { + _pixels = null; + lock (_gate) + { + if (_frames.Remove((int)header.Id)) + { + Interlocked.Increment(ref _version); + } + } + + return; + } + + if ((ulong)header.Width * header.Height * 4 != header.TotalBytes || header.TotalBytes == 0) + { + _report($"An overlay layer record's size {header.Width}x{header.Height} does not match its {header.TotalBytes} bytes; the layer is dropped."); + _pixels = null; + return; + } + + if (header.Offset == 0) + { + _pending = header; + _pixels = new byte[header.TotalBytes]; + _received = 0; + } + else if (_pixels is null || _pending.Id != header.Id || _pending.Revision != header.Revision || + _pending.TotalBytes != header.TotalBytes || _received != header.Offset) + { + _report("An overlay layer piece arrived out of order; the layer is dropped."); + _pixels = null; + return; + } + + if ((ulong)header.Offset + (ulong)piece.Length > header.TotalBytes) + { + throw new InvalidDataException("An overlay layer piece reaches past its layer."); + } + + piece.CopyTo(_pixels!.AsSpan((int)header.Offset)); + _received = header.Offset + (uint)piece.Length; + if (_received != header.TotalBytes) + { + return; + } + + var frame = new OverlayLayerFrame( + (int)header.Id, header.Revision, (int)header.SurfaceWidth, (int)header.SurfaceHeight, header.Left, + header.Top, (int)header.Width, (int)header.Height, _pixels); + _pixels = null; + lock (_gate) + { + _frames[frame.Id] = frame; + Interlocked.Increment(ref _version); + } + } +} diff --git a/src/SharpEmu.GpuSplit/SplitGpuHost.cs b/src/SharpEmu.GpuSplit/SplitGpuHost.cs index 311d520b7..83c32f51b 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuHost.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuHost.cs @@ -14,6 +14,7 @@ using SharpEmu.Libs.Gpu; using SharpEmu.Libs.Gpu.GpuCommands; using SharpEmu.Libs.Gpu.Scheduling; +using SharpEmu.Libs.Overlay; using SharpEmu.Libs.Pad; using SharpEmu.Libs.VideoOut; using SharpEmu.ShaderCompiler; @@ -139,8 +140,12 @@ public SplitGpuHost(GpuRemoteChannel channel, object outboundLock, SplitGpuHostO _channel = channel; _writer = new SplitWriter(channel, channel.Outbound, outboundLock); _options = options; + GuestOverlayLayers = new RemoteOverlayLayers(Report); } + /// <summary>The overlay layers the guest process painted, for the presenter here.</summary> + internal RemoteOverlayLayers GuestOverlayLayers { get; } + /// <summary>True once the start succeeded and the backend is composed.</summary> public bool IsReady => _ready; @@ -259,6 +264,10 @@ private void Dispatch(GpuRemoteMessage type, ReadOnlySpan<byte> payload) TakeHostFrame(backend, payload); break; + case GpuRemoteMessage.OverlayLayer: + GuestOverlayLayers.Take(payload); + break; + case GpuRemoteMessage.GamepadOutput: ApplyGamepadOutput(GpuSplitWire.Read<GamepadOutputMessage>(payload)); break; @@ -328,11 +337,22 @@ private void Start(ReadOnlySpan<byte> payload) // The overlay counts guest flip submissions, which happen in the guest process; // this one presents every guest frame, so it counts those instead (else 0 fps). PerfOverlay.UsePresentedGuestFrameTiming(); + // The system dialogs' overlay layers are painted in the guest process, for the + // drawable here; the window's typed text goes there. + OverlayLayerOutput.Source = GuestOverlayLayers; + OverlayLayerOutput.SurfaceChanged += SendOverlaySurface; + HostWindowInput.TextForwarder = SendTypedText; _globalsInstalled = true; } _backend = _options.ComposeBackend(new SplitGpuEnvironment(_memory, _space, video)); _ready = true; + if (_globalsInstalled) + { + var (width, height) = OverlayLayerOutput.Surface; + SendOverlaySurface(width, height); + } + StartInputPoll(); StartReplicaFollower(); Console.Error.WriteLine( @@ -373,6 +393,9 @@ private static void RunControl(IGuestGpuBackend backend, in ControlMessage contr case GpuSplitControl.CountShaderCompilation: backend.CountShaderCompilation(); break; + case GpuSplitControl.TextInput: + HostWindowInput.SetPeerWantsText(control.Width != 0); + break; } } @@ -777,6 +800,19 @@ internal void SendFlipEvent(GpuSplitFlipEvent kind, ulong requestId) _ = _writer.Write(GpuRemoteMessage.FlipEvent, in message); } + /// <summary>The drawable took a new size: the guest process paints the overlay layers for it.</summary> + internal void SendOverlaySurface(int width, int height) + { + if (width > 0 && height > 0) + { + _ = _writer.Write( + GpuRemoteMessage.OverlaySurface, new OverlaySurfaceMessage { Width = (uint)width, Height = (uint)height }); + } + } + + /// <summary>Text typed into the window, for the guest process's system dialog.</summary> + internal void SendTypedText(string text) => SendNotice(GpuSplitNotice.TypedText, text); + internal void SendNotice(GpuSplitNotice kind, string? text = null) { var notice = new VideoOutNoticeMessage { Kind = (uint)kind }; @@ -1007,6 +1043,14 @@ public void Dispose() Stop(); if (_globalsInstalled) { + OverlayLayerOutput.SurfaceChanged -= SendOverlaySurface; + if (ReferenceEquals(OverlayLayerOutput.Source, GuestOverlayLayers)) + { + OverlayLayerOutput.Source = new OverlayLayerPainter(); + } + + HostWindowInput.TextForwarder = null; + HostWindowInput.SetPeerWantsText(false); EndOfPipeEvents.Redirect = null; VideoOutBackendServices.Bridge = null; if (ReferenceEquals(GuestGpuMemoryHook.Current, _memory)) diff --git a/src/SharpEmu.GpuSplit/SplitGpuSession.cs b/src/SharpEmu.GpuSplit/SplitGpuSession.cs index 3923d735a..38f016f7b 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuSession.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuSession.cs @@ -89,8 +89,12 @@ internal SplitGpuSession(GpuRemoteChannel channel, object outboundLock, GuestGpu Relay = new RemoteGpuQueueRelay(this); ImageStore = new RemoteImageStore(this, channel.SyncCalls, _state); Backend = new RemoteGpuBackend(this); + OverlayLayerSender = new SplitOverlayLayerSender(Writer, () => IsAlive); } + /// <summary>Paints this process's overlay layers for the GPU process's drawable and sends them there.</summary> + internal SplitOverlayLayerSender OverlayLayerSender { get; } + /// <summary>The proxy <see cref="Libs.Gpu.IGuestGpuBackend"/> the guest's exports call.</summary> public RemoteGpuBackend Backend { get; } @@ -229,6 +233,7 @@ internal void Begin(string serviceName, HostVideoOptions? videoOptions, string t _memory.AttachGpuQueue(Relay, null); _memory.AttachSpanObserver(ImageStore); + OverlayLayerSender.Start(); if (installGlobals) { InstallGlobals(); @@ -262,6 +267,8 @@ private void InstallGlobals() } HostWindowInput.Connect(new SplitGamepadOutput(Writer)); + SystemDialogInput.WantsTextChanged += SendWantsText; + SendWantsText(SystemDialogInput.WantsText); MirrorResidencyRanges(); _globalsInstalled = true; } @@ -483,6 +490,13 @@ private void Take(GpuRemoteMessage type, ReadOnlySpan<byte> payload) TakeInput(payload); break; + case GpuRemoteMessage.OverlaySurface: + { + var message = GpuSplitWire.Read<OverlaySurfaceMessage>(payload); + OverlayLayerSender.SetSurface(message.Width, message.Height); + break; + } + default: Report($"Ignoring record type {type} from the GPU process ({payload.Length} bytes)."); break; @@ -803,9 +817,18 @@ private void Detach() AgcBackendServices.ShaderHeaderObserver = null; TessellationRings.Observer = null; Gen5ShaderTranslator.FusedProgramObserver = null; + SystemDialogInput.WantsTextChanged -= SendWantsText; } } + // The window lives in the GPU process: it turns key presses into text only while a dialog here takes it. + private void SendWantsText(bool wanted) => + _ = Writer.Write(GpuRemoteMessage.Control, new ControlMessage + { + Kind = (uint)GpuSplitControl.TextInput, + Width = wanted ? 1u : 0u, + }); + internal void Report(string message) { if (Interlocked.Increment(ref _reports) <= MaxReports) @@ -833,6 +856,7 @@ public void Dispose() Detach(); } + OverlayLayerSender.Dispose(); Writer.Close(); _events.Complete(); _spinEvents?.CompleteAdding(); diff --git a/src/SharpEmu.GpuSplit/SplitOverlayLayerSender.cs b/src/SharpEmu.GpuSplit/SplitOverlayLayerSender.cs new file mode 100644 index 000000000..caf7508d1 --- /dev/null +++ b/src/SharpEmu.GpuSplit/SplitOverlayLayerSender.cs @@ -0,0 +1,186 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.GpuRemote; +using SharpEmu.Libs.Overlay; + +namespace SharpEmu.GpuSplit; + +/// <summary> +/// Process A's half of the overlay layers. The layers (the IME keyboard, the save data list) live +/// with the guest's system dialogs in this process, and the presenter in the GPU process: this paints +/// them for the drawable size the GPU process reports (<see cref="GpuRemoteMessage.OverlaySurface"/>) +/// and sends each repaint, and each hide, as <see cref="GpuRemoteMessage.OverlayLayer"/> records. +/// </summary> +/// <remarks> +/// The thread sleeps until a layer changes (<see cref="OverlayLayers.Changed"/>) or the surface +/// does; a layer that did not change is not sent again. +/// </remarks> +internal sealed class SplitOverlayLayerSender : IDisposable +{ + // Under a ring record's payload cap with room for the header, as a host frame's pieces. + internal const int PieceBytes = 256 * 1024; + + // Wakes now and then even without a change signal, so a missed one costs a delay, not a stuck layer. + private static readonly TimeSpan IdleWake = TimeSpan.FromMilliseconds(250); + + private readonly SplitWriter _writer; + private readonly Func<bool> _alive; + private readonly AutoResetEvent _wake = new(false); + private readonly Dictionary<int, OverlayLayerFrame> _sent = new(); + private readonly List<OverlayLayerFrame> _frames = []; + private OverlayLayerPainter _painter = new(); + private long _surface; + private volatile bool _stopping; + private SharpEmu.HLE.Host.HostHelperThread? _thread; + + public SplitOverlayLayerSender(SplitWriter writer, Func<bool> alive) + { + _writer = writer; + _alive = alive; + OverlayLayers.Changed += Wake; + } + + /// <summary>Records sent so far, pieces included (tests).</summary> + internal long RecordsSent { get; private set; } + + /// <summary>Replaces where the layers come from (tests); the next pass sends what it paints.</summary> + internal Func<OverlayLayer[]> Layers + { + set + { + lock (_sent) + { + _painter = new OverlayLayerPainter(value); + } + + Wake(); + } + } + + public void Start() => + _thread = SharpEmu.HLE.Host.HostHelperThread.Start("SharpEmu GPU split overlay layers", 1024 * 1024, Run); + + /// <summary>The GPU process's drawable took this size.</summary> + public void SetSurface(uint width, uint height) + { + Interlocked.Exchange(ref _surface, (long)width << 32 | height); + Wake(); + } + + private void Wake() + { + if (!_stopping) + { + _wake.Set(); + } + } + + private void Run() + { + while (!_stopping && _alive()) + { + try + { + SendChanges(); + } + catch (Exception exception) + { + // A layer that cannot paint must not take the split down; it is reported, and the + // presenter keeps the last frame it received. + Console.Error.WriteLine($"[GPU-SPLIT][ERROR] An overlay layer could not be painted: {exception}"); + } + + _ = _wake.WaitOne(IdleWake); + } + } + + /// <summary>One pass: paints what changed and sends it; internal so a test can drive it.</summary> + internal void SendChanges() + { + var packed = Interlocked.Read(ref _surface); + var width = (int)(packed >> 32); + var height = (int)(uint)packed; + if (width <= 0 || height <= 0) + { + return; + } + + lock (_sent) + { + _frames.Clear(); + _painter.Collect(width, height, _frames); + foreach (var frame in _frames) + { + if (_sent.TryGetValue(frame.Id, out var sent) && ReferenceEquals(sent, frame)) + { + continue; + } + + if (!Send(frame)) + { + return; + } + + _sent[frame.Id] = frame; + } + + foreach (var id in _sent.Keys.Where(id => !_frames.Exists(frame => frame.Id == id)).ToList()) + { + var hide = new OverlayLayerMessage { Id = (uint)id, Visible = 0 }; + if (!_writer.Write(GpuRemoteMessage.OverlayLayer, in hide)) + { + return; + } + + RecordsSent++; + _sent.Remove(id); + } + } + } + + // The pieces go back to back: another writer cannot put a record between them. + private bool Send(OverlayLayerFrame frame) + { + lock (_writer.Gate) + { + for (var offset = 0; offset < frame.Pixels.Length; offset += PieceBytes) + { + var length = Math.Min(PieceBytes, frame.Pixels.Length - offset); + var header = new OverlayLayerMessage + { + Id = (uint)frame.Id, + Visible = 1, + Revision = frame.Revision, + SurfaceWidth = (uint)frame.SurfaceWidth, + SurfaceHeight = (uint)frame.SurfaceHeight, + Left = frame.Left, + Top = frame.Top, + Width = (uint)frame.Width, + Height = (uint)frame.Height, + TotalBytes = (uint)frame.Pixels.Length, + Offset = (uint)offset, + }; + if (!_writer.Write(GpuRemoteMessage.OverlayLayer, in header, frame.Pixels.AsSpan(offset, length))) + { + return false; + } + + RecordsSent++; + } + } + + return true; + } + + public void Dispose() + { + _stopping = true; + OverlayLayers.Changed -= Wake; + _wake.Set(); + if (_thread is { IsCurrentThread: false } thread) + { + _ = thread.Join(TimeSpan.FromSeconds(2)); + } + } +} diff --git a/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs b/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs index 0e7ced742..e5bd7606b 100644 --- a/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/SplitTransportTests.cs @@ -220,6 +220,8 @@ public void SplitPayloadsKeepTheirSizesOnEveryArchitecture() Assert.Equal(48, sizeof(DisplayBufferResponse)); Assert.Equal(64, sizeof(ReserveFlipResponse)); Assert.Equal(32, sizeof(SpanRequest)); + Assert.Equal(48, sizeof(OverlayLayerMessage)); + Assert.Equal(8, sizeof(OverlaySurfaceMessage)); Assert.True(sizeof(InputMessage) < 512); } diff --git a/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs b/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs index 3d8091acd..cfcaf76a1 100644 --- a/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs +++ b/tests/SharpEmu.GpuSplit.Tests/SplitInProcessTests.cs @@ -9,9 +9,11 @@ using SharpEmu.Host.MacOS; using SharpEmu.Libs.Agc; using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Overlay; using SharpEmu.Libs.Pad; using SharpEmu.Libs.VideoOut; using SharpEmu.ShaderCompiler; +using SkiaSharp; using Xunit; namespace SharpEmu.GpuSplit.Tests; @@ -445,6 +447,92 @@ public void InterruptsAndWindowInputReachTheGuest() } } + [MacOSFact] + public void OverlayLayersArePaintedForTheGpuSidesSurfaceAndCrossInPieces() + { + using var split = new InProcessSplit(); + var layer = new SolidLayer(); + split.Session.OverlayLayerSender.Layers = () => [layer]; + var store = split.Host.GuestOverlayLayers; + + // Nothing is painted before the GPU side reports its drawable. + layer.Show(); + split.Session.OverlayLayerSender.SendChanges(); + Assert.Empty(Collect(store, 1280, 720)); + + split.Host.SendOverlaySurface(1280, 720); + Wait.Until(() => Collect(store, 1280, 720).Count == 1, "the painted layer"); + var frame = Assert.Single(Collect(store, 1280, 720)); + // The layer's 600x400 bounds are centred; its render used 300 rows, centred in them as the + // Vulkan presenter places them. 600 * 300 * 4 bytes take several ring records. + Assert.Equal((340, 160 + 50, 600, 300), (frame.Left, frame.Top, frame.Width, frame.Height)); + Assert.True(frame.Pixels.Length > SplitOverlayLayerSender.PieceBytes); + Assert.Equal(new byte[] { 30, 20, 10, 255 }, frame.Pixels[^4..]); + var version = store.Version; + + // An unchanged layer is not sent again; a new drawable size repaints it. + split.Session.OverlayLayerSender.SendChanges(); + split.Host.SendOverlaySurface(1920, 1080); + Wait.Until(() => Collect(store, 1920, 1080).Count == 1, "the layer repainted for the new size"); + Assert.Empty(Collect(store, 1280, 720)); + Assert.Equal(version + 1, store.Version); + + layer.Hide(); + Wait.Until(() => Collect(store, 1920, 1080).Count == 0, "the hidden layer"); + + // Typed text goes back to the guest; the guest's dialog says when the window should type. + split.Host.SendTypedText("é1"); + Wait.Until(() => split.GuestSide.Notices.Contains((GpuSplitNotice.TypedText, "é1")), "the typed text"); + try + { + Assert.True(split.Session.Writer.Write( + GpuRemoteMessage.Control, new ControlMessage { Kind = (uint)GpuSplitControl.TextInput, Width = 1 })); + Wait.Until(() => HostWindowInput.WantsText, "the window taking text"); + Assert.True(split.Session.Writer.Write( + GpuRemoteMessage.Control, new ControlMessage { Kind = (uint)GpuSplitControl.TextInput, Width = 0 })); + Wait.Until(() => !HostWindowInput.WantsText, "the window no longer taking text"); + } + finally + { + HostWindowInput.SetPeerWantsText(false); + } + } + + private static List<OverlayLayerFrame> Collect(IOverlayLayerSource source, int width, int height) + { + var frames = new List<OverlayLayerFrame>(); + source.Collect(width, height, frames); + return frames; + } + + private sealed class SolidLayer : OverlayLayer + { + private volatile bool _visible; + + public override bool IsVisible => _visible; + + public void Show() + { + _visible = true; + Invalidate(); + } + + public void Hide() + { + _visible = false; + Invalidate(); + } + + public override SKRectI Bounds(int surfaceWidth, int surfaceHeight) => + Centered(surfaceWidth, surfaceHeight, 600, 400); + + public override int Render(SKCanvas canvas, int width, int height, float unit) + { + canvas.Clear(new SKColor(10, 20, 30)); + return 300; + } + } + [MacOSFact] public void ControlCallsFramesQueriesAndMirrorsCross() { From 1c39d347a9991edb7cbf5fdd0195aeb5d727b10c Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:04:48 +0000 Subject: [PATCH 48/64] [GUI] Pass the default profile and the overlay theme and language to games Upstream's launcher sets SHARPEMU_DEFAULT_PROFILE, SHARPEMU_UI_PALETTE (the launcher theme), SHARPEMU_UI_LANGUAGE and SHARPEMU_UI_STRINGS at launch; the fork's GUI and CLI launches now do too, under any custom variable. Adds the DefaultProfile launcher setting and its Options row. --- .../ApplicationSettings.cs | 10 ++++++++ .../SettingsSplitMigration.cs | 3 ++- src/SharpEmu.CLI/Program.cs | 9 ++++++++ src/SharpEmu.GUI/EmulatorLaunchVariables.cs | 23 +++++++++++++++++++ src/SharpEmu.GUI/MainWindow.axaml | 10 ++++++++ src/SharpEmu.GUI/MainWindow.axaml.cs | 15 ++++++++++-- 6 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 src/SharpEmu.GUI/EmulatorLaunchVariables.cs diff --git a/src/SharpEmu.Application/ApplicationSettings.cs b/src/SharpEmu.Application/ApplicationSettings.cs index bfd1246c1..aaf201ec9 100644 --- a/src/SharpEmu.Application/ApplicationSettings.cs +++ b/src/SharpEmu.Application/ApplicationSettings.cs @@ -45,6 +45,9 @@ public sealed class ApplicationSettings public string GnmTrophyKey { get; set; } = string.Empty; + /// <summary>The on-screen keyboard's default text (a game asking for a name); machine-wide.</summary> + public string DefaultProfile { get; set; } = "Sharp"; + public string LibraryLayout { get; set; } = "Carousel"; /// <summary>Cover size in the grid view, as a multiple of the size that fits the window.</summary> @@ -133,6 +136,7 @@ public static ApplicationSettings NormalizeFromJson(string json) settings.GameFolders = FilterNullOrEmpty(settings.GameFolders); settings.ExcludedGames = FilterNullOrEmpty(settings.ExcludedGames); settings.Language ??= "en"; + settings.DefaultProfile = NormalizeDefaultProfile(settings.DefaultProfile); settings.GnmTrophyKey = TryNormalizeTrophyKey(settings.GnmTrophyKey, out var trophyKey) ? trophyKey : string.Empty; settings.DiscordClientId ??= "1525606762248540221"; @@ -207,6 +211,12 @@ private static bool TryNormalizeTrophyKey(string? key, out string normalized) return normalized.Length == 0 || normalized.Length == 32 && normalized.All(char.IsAsciiHexDigit); } + public static string NormalizeDefaultProfile(string? value) + { + var trimmed = value?.Trim(); + return string.IsNullOrEmpty(trimmed) ? "Sharp" : trimmed; + } + internal static string NormalizeChoice(string? value, string fallback, params string[] choices) => choices.Prepend(fallback).FirstOrDefault( choice => string.Equals(choice, value, StringComparison.OrdinalIgnoreCase)) ?? fallback; diff --git a/src/SharpEmu.Application/SettingsSplitMigration.cs b/src/SharpEmu.Application/SettingsSplitMigration.cs index 8ecfed010..4ed625188 100644 --- a/src/SharpEmu.Application/SettingsSplitMigration.cs +++ b/src/SharpEmu.Application/SettingsSplitMigration.cs @@ -140,7 +140,8 @@ public static PerGameSettings CarriedValues(string legacyGlobalJson) if (legacy.OverlayMode == "TitleBar") legacy.OverlayMode = null; legacy.DisplayIndex = legacy.DisplayIndex is { } displayIndex ? Math.Max(0, displayIndex) : null; legacy.RefreshRate = legacy.RefreshRate is { } refreshRate ? Math.Clamp(refreshRate, 0, 1000) : null; - // Nothing reads SHARPEMU_DEFAULT_PROFILE any more; older files may still carry it. + // SHARPEMU_DEFAULT_PROFILE is the launcher's DefaultProfile setting now, set at every launch; + // an old per-game switch for it must not override that. legacy.EnvironmentToggles?.RemoveAll(entry => string.Equals( EnvironmentOverrides.Name(entry), "SHARPEMU_DEFAULT_PROFILE", diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs index 61aafa4de..bd4cf9aeb 100644 --- a/src/SharpEmu.CLI/Program.cs +++ b/src/SharpEmu.CLI/Program.cs @@ -1585,6 +1585,15 @@ private static bool TryParseArguments( { Environment.SetEnvironmentVariable(name, value); } + // The launcher's own settings (keyboard default text, overlay theme and language), under + // anything the launcher, a script or the game's custom variables already set. + foreach (var (name, value) in SharpEmu.GUI.EmulatorLaunchVariables.Build(launcher)) + { + if (Environment.GetEnvironmentVariable(name) is null) + { + Environment.SetEnvironmentVariable(name, value); + } + } if (!HasOption(args, "--log-level") && SharpEmuLog.TryParseLevel( Environment.GetEnvironmentVariable("SHARPEMU_LOG_LEVEL") ?? configured.Settings.LogLevel, out var configuredLogLevel)) { diff --git a/src/SharpEmu.GUI/EmulatorLaunchVariables.cs b/src/SharpEmu.GUI/EmulatorLaunchVariables.cs new file mode 100644 index 000000000..e31dd1e26 --- /dev/null +++ b/src/SharpEmu.GUI/EmulatorLaunchVariables.cs @@ -0,0 +1,23 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Overlay; + +namespace SharpEmu.GUI; + +/// <summary> +/// What a game takes from the launcher's own settings rather than its launch configuration: the +/// on-screen keyboard's default text, and the palette, language and strings the in-game overlays +/// (the IME keyboard, the save data list) are drawn with, so they follow the launcher's theme and language. +/// </summary> +public static class EmulatorLaunchVariables +{ + public static IReadOnlyDictionary<string, string?> Build(GuiSettings settings) => + new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase) + { + [LaunchConfiguration.DefaultProfileVariable] = GuiSettings.NormalizeDefaultProfile(settings.DefaultProfile), + [OverlayPalette.EnvironmentVariable] = LauncherThemes.EmulatorPalette(settings), + [OverlayText.LanguageVariable] = EmulatorOverlayText.Language(settings), + [OverlayText.StringsVariable] = EmulatorOverlayText.Strings(settings), + }; +} diff --git a/src/SharpEmu.GUI/MainWindow.axaml b/src/SharpEmu.GUI/MainWindow.axaml index 1096b5509..b219b8942 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml +++ b/src/SharpEmu.GUI/MainWindow.axaml @@ -1495,6 +1495,16 @@ SPDX-License-Identifier: GPL-2.0-or-later VerticalAlignment="Center" /> </local:SettingRow> + <local:SettingRow x:Name="DefaultProfileRow" + Classes="optionRow" + Label="{Binding [Options.DefaultProfile.Label], Source={x:Static local:Localization.Instance}}" + Description="{Binding [Options.DefaultProfile.Desc], Source={x:Static local:Localization.Instance}}"> + <TextBox x:Name="DefaultProfileBox" + Classes="optionValue" + MaxLength="16" + VerticalAlignment="Center" /> + </local:SettingRow> + <local:SettingRow x:Name="PortableDataRow" Classes="optionRow" Label="{Binding [Options.PortableData.Label], Source={x:Static local:Localization.Instance}}" diff --git a/src/SharpEmu.GUI/MainWindow.axaml.cs b/src/SharpEmu.GUI/MainWindow.axaml.cs index 263235f58..b8e3d0927 100644 --- a/src/SharpEmu.GUI/MainWindow.axaml.cs +++ b/src/SharpEmu.GUI/MainWindow.axaml.cs @@ -430,6 +430,11 @@ public MainWindow() UpdateButton.Click += async (_, _) => await OnUpdateButtonAsync(); SelectLogFilePathButton.Click += async (_, _) => await SelectLogFilePathAsync(); OpenLogsFolderButton.Click += (_, _) => OpenLogsFolder(); + DefaultProfileBox.TextChanged += (_, _) => + { + _settings.DefaultProfile = GuiSettings.NormalizeDefaultProfile(DefaultProfileBox.Text); + ScheduleSettingsSave(); + }; GnmTrophyKeyBox.TextChanged += (_, _) => { var valid = GnmTrophyPackageReader.TryNormalizeKey(GnmTrophyKeyBox.Text, out var key); @@ -1617,6 +1622,7 @@ private void ApplySettingsToControls() PortableDataToggle.IsChecked = SharpEmu.Logging.SharpEmuPaths.IsPortableMarkerPresent(); GnmTrophyPackageReader.Configure(_settings.GnmTrophyKey); GnmTrophyKeyBox.Text = _settings.GnmTrophyKey; + DefaultProfileBox.Text = _settings.DefaultProfile; UpdateLogFilePathText(); _settingsSaveTimer.Stop(); } @@ -2999,8 +3005,8 @@ private void Launch( StartPendingSession(); } - // The GNM trophy key is a launcher setting rather than a game's; a custom variable that - // names it still wins. + // The GNM trophy key, the keyboard's default text and the overlays' theme and language are + // launcher settings rather than a game's; a custom variable that names one still wins. private IReadOnlyDictionary<string, string?> BuildLaunchEnvironment(LaunchConfiguration configuration) { var environment = new Dictionary<string, string?>( @@ -3009,6 +3015,11 @@ private void Launch( environment.TryAdd( GnmTrophyPackageReader.KeyEnvironmentName, string.IsNullOrEmpty(_settings.GnmTrophyKey) ? null : _settings.GnmTrophyKey); + foreach (var (name, value) in EmulatorLaunchVariables.Build(_settings)) + { + environment.TryAdd(name, value); + } + return environment; } From b8e1a285bd2b5f098e67f0e922e19a286fb9d7c5 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:04:48 +0000 Subject: [PATCH 49/64] [Pad] Classify Xbox controllers on macOS for the Xbox glyphs Upstream 94d833daa draws Xbox glyphs and LB/RB hints for an Xbox pad; the GameController reader reported it as generic. GCXboxGamepad and the Xbox product categories now map to HostGamepadType.Xbox. --- .../Input/MacGameControllerGamepad.cs | 7 +++++++ .../Platform/MacHostWindowTitleTests.cs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs index 93a58ffc0..0c0d2ec50 100644 --- a/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs +++ b/src/platforms/macos/SharpEmu.Platform.MacOS/Input/MacGameControllerGamepad.cs @@ -247,6 +247,11 @@ internal static HostGamepadType ClassifyProfile(nint profile, nint controller) return HostGamepadType.DualShock4; } + if (MacObjC.IsKindOf(profile, "GCXboxGamepad")) + { + return HostGamepadType.Xbox; + } + return MapProductCategory( MacObjC.ReadNsString(MacObjC.Send(controller, MacObjC.Selector("productCategory")))); } @@ -256,6 +261,8 @@ internal static HostGamepadType ClassifyProfile(nint profile, nint controller) { "DualSense" => HostGamepadType.DualSense, "DualShock 4" => HostGamepadType.DualShock4, + // GCProductCategoryXboxOne ("Xbox One") also names the Series X|S pads. + { } category when category.StartsWith("Xbox", StringComparison.Ordinal) => HostGamepadType.Xbox, _ => HostGamepadType.Generic, }; diff --git a/tests/SharpEmu.Libs.Tests/Platform/MacHostWindowTitleTests.cs b/tests/SharpEmu.Libs.Tests/Platform/MacHostWindowTitleTests.cs index aa63c2dfc..4a85da1c8 100644 --- a/tests/SharpEmu.Libs.Tests/Platform/MacHostWindowTitleTests.cs +++ b/tests/SharpEmu.Libs.Tests/Platform/MacHostWindowTitleTests.cs @@ -41,7 +41,7 @@ public void TitleNeverAdvertisesARenderDocCaptureKey() [Theory] [InlineData("DualSense", HostGamepadType.DualSense)] [InlineData("DualShock 4", HostGamepadType.DualShock4)] - [InlineData("Xbox One", HostGamepadType.Generic)] + [InlineData("Xbox One", HostGamepadType.Xbox)] [InlineData("MFi", HostGamepadType.Generic)] [InlineData(null, HostGamepadType.Generic)] public void ProductCategoryMapsToTheHostPadType(string? productCategory, HostGamepadType expected) From c2863cbd611fabc88cdbf78ad31d6f3ddd29c30d Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:05:17 +0000 Subject: [PATCH 50/64] [Metal] Rent posted word copy buffers from the shared pool instead of allocating each copy Port of upstream c30081163 (pooled buffers for posted word copies): a copy of up to 16 MiB allocated a new array every time. Both consumers take the bytes before they return, so the buffer goes back at once. --- .../V2/MetalRenderHost.PostedWordCopy.cs | 70 +++++++++++-------- 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs index 726b26642..615e9a289 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Buffers; using SharpEmu.Libs.Gpu.Rendering; namespace SharpEmu.Gpu.Metal.V2; @@ -163,38 +164,49 @@ private PostedWordCopyRefusal PostWordCopy(ulong destination, ulong source, ulon return PostedWordCopyRefusal.Input; } - var data = GC.AllocateUninitializedArray<byte>((int)size); - if (!_memory.TryRead(source, data.AsSpan(0, (int)sourceSize))) - { - return PostedWordCopyRefusal.Input; - } - - for (var filled = (int)sourceSize; filled < data.Length;) - { - var count = Math.Min(filled, data.Length - filled); - data.AsSpan(0, count).CopyTo(data.AsSpan(filled)); - filled += count; - } - - if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) - { - SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(destination, size, SharpEmu.HLE.GpuMemory.OverlapWrite.CpWrite); - } - - if (hostStore) - { - StorePostedWordCopy(destination, data); - Interlocked.Increment(ref _postedWordCopyHostStores); + // Upstream c30081163 rents these from a bounded pool (StoreBufferPool) instead of allocating up to 16 MiB per copy, + // which churned the large object heap. Both consumers below take the bytes before they return (the host store + // writes them, the command-processor write copies them to staging), so the buffer goes back at once. + var rented = ArrayPool<byte>.Shared.Rent((int)size); + try + { + var data = rented.AsSpan(0, (int)size); + if (!_memory.TryRead(source, data[..(int)sourceSize])) + { + return PostedWordCopyRefusal.Input; + } + + for (var filled = (int)sourceSize; filled < data.Length;) + { + var count = Math.Min(filled, data.Length - filled); + data[..count].CopyTo(data[filled..]); + filled += count; + } + + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(destination, size, SharpEmu.HLE.GpuMemory.OverlapWrite.CpWrite); + } + + if (hostStore) + { + StorePostedWordCopy(destination, data); + Interlocked.Increment(ref _postedWordCopyHostStores); + return PostedWordCopyRefusal.None; + } + + if (!TryEncodeCommandProcessorWrite(destination, data, "word copy", causal: true)) + { + return PostedWordCopyRefusal.Encode; + } + + Interlocked.Increment(ref _gpuTimedCommandProcessorWrites); return PostedWordCopyRefusal.None; } - - if (!TryEncodeCommandProcessorWrite(destination, data, "word copy", causal: true)) + finally { - return PostedWordCopyRefusal.Encode; + ArrayPool<byte>.Shared.Return(rented); } - - Interlocked.Increment(ref _gpuTimedCommandProcessorWrites); - return PostedWordCopyRefusal.None; } // Whether no GPU work recorded or submitted can still read or write these bytes: no command buffer open (everything @@ -209,7 +221,7 @@ private bool NoGpuWorkCanTouch(ulong address, ulong size) => // The copy's bytes stored now, as a host fill stores (TryFillGuestMemoryOnHost), and logged with no pending serial: a // look-ahead resolution that read these bytes before the store is refused at its take (LoggedWriteCoversRead). The // store comes first, so a resolution that begins after the log entry reads the stored bytes. - private void StorePostedWordCopy(ulong destination, byte[] data) + private void StorePostedWordCopy(ulong destination, ReadOnlySpan<byte> data) { var size = (ulong)data.Length; if (!_memory.TryWrite(destination, data)) From 60598d57d864fcfbed514345932a82f1071f6a51 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:05:17 +0000 Subject: [PATCH 51/64] [Metal] Replay dispatches of flattened-table programs and take a replaced table Port of upstream c30081163 (dispatch replay with a new flattened table): the host now captures a compute stage whose one per-item argument field is its flattened table, and a replay whose table alone differs (replaceTable) writes the stage's argument buffer again, which uploads the new table. SHARPEMU_METAL_V2_TABLE_REPLAY=0 refuses such stages at capture as before. --- .../V2/MetalRenderHost.Replay.cs | 49 ++++++++++++--- .../Scenes/ReplaySceneTests.cs | 61 +++++++++++++++++++ 2 files changed, 103 insertions(+), 7 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs index a1647f1a1..8c5121475 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs @@ -29,7 +29,9 @@ namespace SharpEmu.Gpu.Metal.V2; /// bytes are what WriteArgumentBuffer would write while every resolved binding they name is unchanged (below) and /// the argument plan names nothing else that moves: a stage whose plan has a pointer field (GDS, device-address /// page table, fault buffer, flattened table, shader data, mip statistics), a word field other than the constant -/// fault-buffer word, or a bindless image table is never captured.</item> +/// fault-buffer word, or a bindless image table is never captured. The one exception is a dispatch's flattened table +/// (FlattenedTableReplay): the captured pointer names this submission's upload of the sealed table, and a dispatch with +/// another table writes the argument buffer again (TryReplayDispatch's replaceTable).</item> /// <item>The textures: every image binding of the stage was a texture-memo hit or was memoised by its acquire, so /// each had a stamp (MetalImageCache.TryStampTextureLocked: no DCC read, no stencil plane, bounded aliases), and /// the image cache's binding epoch and image set did not move from the start of the stage's BindResources to the @@ -66,6 +68,14 @@ internal sealed partial class MetalRenderHost internal bool DispatchReplayEnabled { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_REPLAY") != "0"; + /// <summary> + /// Upstream c30081163 ("dispatch replay with a new flattened table"): a compute program that binds a flattened + /// resource table is captured too, and a dispatch whose stage differs from the sealed one only in that table + /// (RenderRecorder's replaceTable) replays with the table uploaded again and the stage's argument buffer rewritten. + /// SHARPEMU_METAL_V2_TABLE_REPLAY=0 refuses such programs at capture again (argument_field). + /// </summary> + internal bool FlattenedTableReplay { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_TABLE_REPLAY") != "0"; + /// <summary> /// Tests: runs when a replay is asked for (true for a dispatch), before any check, as work a completion or another /// thread does between two items would. @@ -116,6 +126,9 @@ private sealed class ReplayStage public ulong ArgumentOffset; public bool ArgumentValid; public bool UsesDeviceAddresses; + + // The argument plan has a flattened-table field (dispatches only; FlattenedTableReplay). + public bool HasTable; public BindingLayout Layout = null!; public uint UserDataBase; @@ -215,11 +228,15 @@ private enum ReplayMiss private long _drawCaptures; private long _dispatchCaptures; private long _dispatchReplaysRebound; + private long _dispatchReplaysTable; /// <summary>Draws and dispatches the host replayed, for tests.</summary> internal (long Draws, long Dispatches, long DispatchesRebound) ReplayCounts => (_drawReplaysServed, _dispatchReplaysServed, _dispatchReplaysRebound); + /// <summary>Dispatches the host replayed with a new flattened table, for tests.</summary> + internal long TableReplays => _dispatchReplaysTable; + /// <summary>Whether a draw (dispatch) is sealed and captured, for tests.</summary> internal bool ReplaySealed(bool dispatch) => (dispatch ? _dispatchReplay : _drawReplay).Sealed; @@ -258,8 +275,8 @@ private string TakeReplayHostReport() { var text = string.Create( System.Globalization.CultureInfo.InvariantCulture, - $"replay_host=(draws={_drawReplaysServed},captured={_drawCaptures},capture_refused=[{FormatReplayCounts(_drawCaptureRefusals, ReplayRefusalNames)}],miss=[{FormatReplayCounts(_drawReplayMisses, ReplayMissNames)}]) dispatch_replay_host=(dispatches={_dispatchReplaysServed},rebound={_dispatchReplaysRebound},captured={_dispatchCaptures},capture_refused=[{FormatReplayCounts(_dispatchCaptureRefusals, ReplayRefusalNames)}],miss=[{FormatReplayCounts(_dispatchReplayMisses, ReplayMissNames)}])"); - _drawReplaysServed = _drawCaptures = _dispatchReplaysServed = _dispatchCaptures = _dispatchReplaysRebound = 0; + $"replay_host=(draws={_drawReplaysServed},captured={_drawCaptures},capture_refused=[{FormatReplayCounts(_drawCaptureRefusals, ReplayRefusalNames)}],miss=[{FormatReplayCounts(_drawReplayMisses, ReplayMissNames)}]) dispatch_replay_host=(dispatches={_dispatchReplaysServed},rebound={_dispatchReplaysRebound},table={_dispatchReplaysTable},captured={_dispatchCaptures},capture_refused=[{FormatReplayCounts(_dispatchCaptureRefusals, ReplayRefusalNames)}],miss=[{FormatReplayCounts(_dispatchReplayMisses, ReplayMissNames)}])"); + _drawReplaysServed = _drawCaptures = _dispatchReplaysServed = _dispatchCaptures = _dispatchReplaysRebound = _dispatchReplaysTable = 0; return text; } @@ -478,9 +495,16 @@ private bool CaptureStages(ReplayCapture capture, bool compute) // resident buffer, made once), the shader-data size, the zero fault word, the step-report slot (a program keeps // it for good) and the pair-lock table. Anything else (the device-address table, the flattened table, shader // data uploaded out of line) is written per item. + // A dispatch's flattened table (its pointer and word count) is the one per-item field a replay writes again: the + // captured pointer names this submission's upload of the sealed table, which stands for a dispatch with the same + // table, and a dispatch whose table differs (replaceTable) rewrites the argument buffer with its own upload. + captured.HasTable = false; foreach (var field in ArgumentPlanOf(layout).Fields) { - var stands = field.FieldKind switch + var table = compute && FlattenedTableReplay && field.Kind == DescriptorBindingKind.FlattenedResourceTable && + field.FieldKind is MslArgumentFieldKind.Pointer or MslArgumentFieldKind.Word; + captured.HasTable |= table; + var stands = table || field.FieldKind switch { MslArgumentFieldKind.Pointer => field.Kind is DescriptorBindingKind.GlobalDataShare or DescriptorBindingKind.MipStatistics, MslArgumentFieldKind.Word => field.Kind is DescriptorBindingKind.GlobalDataShare or @@ -934,8 +958,10 @@ public bool TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan<uint> vertexU return true; } - // replaceTable (the stage differs from the sealed one only in its flattened resource table) is not replayed here: - // the replay rebinds the captured table, so such a dispatch misses and records in full. + // replaceTable: the stage differs from the sealed one only in its flattened resource table. The captured argument + // buffer names the sealed table's upload, so the replay writes the stage's argument buffer again, which uploads this + // dispatch's table as the full path does (PointerFieldValue); everything else it names is what the capture bound. + // A capture without a table field cannot take a new table and misses (table). public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage, bool replaceTable) { var capture = _dispatchReplay; @@ -952,7 +978,7 @@ public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResource } capture.Sealed = false; - if (replaceTable) + if (replaceTable && (capture.StageCount != 1 || !capture.Stages[0].HasTable)) { return MissDispatch(ReplayMiss.Table); } @@ -1033,6 +1059,7 @@ public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResource WriteArgumentBuffer(bindings, StageCompute); capture.Commit = -1; _dispatchReplaysRebound++; + replaceTable = false; } } finally @@ -1042,6 +1069,14 @@ public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResource } } + if (replaceTable) + { + // The next seal captures the rewritten argument buffer, whose table pointer is this dispatch's upload. + WriteArgumentBuffer(bindings, StageCompute); + capture.Commit = -1; + _dispatchReplaysTable++; + } + NoteBufferWordComputeStage(entry, [bindings]); PublishReplayPushData(capture); _dispatchReplaysServed++; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs index fddb161f6..8d80446eb 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs @@ -73,6 +73,17 @@ public sealed class ReplaySceneTests(ITestOutputHelper output) : SceneTestBase(o 0xBF810000, // s_endpgm ]; + // One 64-thread group; thread t writes the user-data word s0 to record t of the V# the table at s[4:5] holds (a scalar + // load materialized into the dispatch's flattened resource table). + private static readonly uint[] StoreTableWord = + [ + 0xF4080202, 0xFA000000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xBF8CC07F, // s_waitcnt lgkmcnt(0) + 0x7E040200, // v_mov_b32_e32 v2, s0 + 0xE0702000, 0x80020200, // buffer_store_dword v2, v0, s[8:11], 0 idxen + 0xBF810000, // s_endpgm + ]; + private static readonly SceneVertex[] Quad = [ SceneVertex.At(-1, -1, 0.5f, 0, 1, 0, 1), SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), @@ -396,4 +407,54 @@ public void AnEpochMovedBetweenDispatchesRefusesTheReplay() Assert.All(with[..64], word => Assert.Equal(4u, word)); Assert.All(with[64..], word => Assert.Equal(13u, word)); } + + private uint[] StoreTableWords(bool replay, bool tableReplay, out long replays, out long tableReplays, out long fieldRefusals) + { + using var rig = CreateReplayRig()!; + rig.Host.DrawReplayEnabled = replay; + rig.Host.DispatchReplayEnabled = replay; + rig.Host.FlattenedTableReplay = tableReplay; + var output = rig.Memory.Allocate(64 * 4, 0x10000); + var pm4 = new ScenePm4(); + // Four dispatches of one program that binds a flattened table, each through a table of its own with the same + // words: each replays the one before through the captured table pointer, with its own user data. + for (var index = 0u; index < 4; index++) + { + var table = rig.Memory.Allocate(256, 256); + rig.Memory.Write<uint>(table, Descriptors.Buffer(output, 4, 64)); + rig.Dispatch(pm4, StoreTableWord, [21 + index, 0, 0, 0, (uint)table, (uint)(table >> 32)], 1); + } + + rig.Submit(pm4); + Report(rig, $"table replay={replay}/{tableReplay}"); + replays = rig.Host.ReplayCounts.Dispatches; + tableReplays = rig.Host.TableReplays; + fieldRefusals = rig.Host.ReplayCount(true, "argument_field"); + Assert.Empty(rig.Fatals); + return rig.Read<uint>(output, 64); + } + + // Upstream c30081163 seals compute programs whose one replay refusal is their flattened table. The Metal host now + // captures them (the table pointer and word count are the one per-item field), so their dispatches replay; with + // SHARPEMU_METAL_V2_TABLE_REPLAY=0 they are refused at capture (argument_field) as before. The words written are + // those of the full path either way. (A dispatch whose table alone differs, replaceTable, rewrites the argument + // buffer; the engine side of it is DispatchTableReplayTests in SharpEmu.Libs.Tests.) + [Fact] + public void DispatchesOfAFlattenedTableProgramReplayThroughTheCapturedTable() + { + if (CreateReplayRig() is not { } probe) return; + probe.Dispose(); + var with = StoreTableWords(replay: true, tableReplay: true, out var replays, out var tableReplays, out var fieldRefusals); + var without = StoreTableWords(replay: false, tableReplay: true, out var none, out _, out _); + var refused = StoreTableWords(replay: true, tableReplay: false, out var refusedReplays, out _, out var refusedFields); + Assert.All(with, word => Assert.Equal(24u, word)); + Assert.Equal(without, with); + Assert.Equal(without, refused); + Assert.True(replays >= 1, "no dispatch of the table program was replayed"); + Assert.Equal(0, tableReplays); + Assert.Equal(0, fieldRefusals); + Assert.Equal(0, none); + Assert.Equal(0, refusedReplays); + Assert.True(refusedFields >= 1, "with the table replay off, the table program was not refused at capture"); + } } From 4d0be049fe21da1a1043fe9e4eec3926e3ca021d Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:06:02 +0000 Subject: [PATCH 52/64] [Metal] Find a texture read as a volume again instead of making a new image each time Port of upstream 957d1dc90. A program that reads a two-dimensional texture as a volume (a bindless heap looking it up every frame) found its image, released it because a volume view needs a 3D image, and made another from the texture's description, which is flat again. Only a volume request now replaces an image for a volume view; any other keeps the image, and the caller refuses or warns on the view as before. Tests: the upstream ImageTypes case, and the two BlockAlias cases of cb790c35e (an image of the other block class over a mip chain, and the reverse), which the Metal cache already passes: it never views or copies across block classes except the one-level, same-size device block-word copy. --- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 9 +- .../MetalImageAliasTests.UpstreamLookups.cs | 191 ++++++++++++++++++ 2 files changed, 199 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index c67d5dbb0..873c5112b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -348,7 +348,14 @@ private ResourceSlotIdentifier LookUpImageLocked(ref ImageRequest request, bool var resolved = _slots[result]; var formatMismatch = exactFormat && resolved.Description.PixelFormat != request.Description.PixelFormat; var fewerResources = resolved.Description.Resources < request.Description.Resources; - if (formatMismatch || fewerResources || !resolved.SupportsViewType(request.View)) + // A volume view needs a 3D image, and only a volume request makes one: an image made again from any + // other request is flat too, so each lookup would replace the image with another that never serves + // the view. A program that reads a 2D texture as a volume through a bindless heap looked it up every + // frame and filled device memory with copies of it (upstream 957d1dc90). The image is kept; the caller + // refuses or warns on the view as before (MetalCachedImage.GetOrCreateView, the bindless heap's check). + var wrongViewType = !resolved.SupportsViewType(request.View) && + (request.View.Type != GpuImageViewType.Type3D || request.Description.IsVolume); + if (formatMismatch || fewerResources || wrongViewType) { var cause = formatMismatch ? MetalImageReleaseCause.FormatMismatch diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs new file mode 100644 index 000000000..6e320d2cc --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs @@ -0,0 +1,191 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// Lookups ported from upstream's GuestImageCacheTests (ImageTypes 957d1dc90, BlockAlias cb790c35e). +public sealed unsafe partial class MetalImageAliasTests +{ + // A program can read a two-dimensional texture as a volume. Its image is not 3D, and an image made from the + // texture's description would not be either: the lookup finds the same image again instead of making a new one + // each time. + [Fact] + public void ATwoDimensionalTextureReadAsAVolumeIsFoundAgain() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var request = VolumeViewOfTexture(ImageAddress); + var identifier = rig.Cache.FindImage(ref request); + var images = rig.Cache.ImageCount; + + for (var lookup = 0; lookup < 3; lookup++) + { + var again = VolumeViewOfTexture(ImageAddress); + Assert.Equal(identifier, rig.Cache.FindImage(ref again)); + } + + Assert.Equal(images, rig.Cache.ImageCount); + Assert.False(rig.Cache.GetImage(identifier).SupportsViewType(request.View)); + } + + private static ImageRequest VolumeViewOfTexture(ulong address) + { + var request = Rig.Request(address, 64, ImageRole.Texture); + request.View = request.View with { Type = GpuImageViewType.Type3D }; + return request; + } + + // A linear 64x64 BC1 texture with two levels and a one-level 16x16 R32G32Uint image (texels as large as the chain's + // blocks, as many as its level 0 holds), laid out as the console lays them out (TileGeometry, which the transfer + // follows): rows padded to the linear pitch. + private static (ulong Size, TileLevelSpan[] Levels) ChainLayout() + { + var levels = new TileLevelSpan[TiledSurfaceLayout.MaxLevels]; + Assert.True(TileGeometry.TryGetTextureSize( + GuestPixelFormat.Bc1Srgb, 64, 64, 2, GuestTileMode.Linear, out var total, levels, null)); + return (total.Size, levels); + } + + private static ulong BlockSizedImageBytes => + TileGeometry.TextureTotalSize(GuestPixelFormat.Bits32_32UInt, 16, 16, 1, 1, GuestTileMode.Linear, volume: false).Size; + + private static ImageRequest MippedCompressedTexture(ulong address) + { + var (size, levels) = ChainLayout(); + var description = ImageDescription.Create(); + description.Data = new GuestSpan(address, size); + description.PixelFormat = GpuFormat.BC1RgbaSrgbBlock; + description.GuestFormat = GuestPixelFormat.Bc1Srgb; + description.Type = GuestImageType.Color2D; + description.Extent = new GpuExtent3D(64, 64, 1); + description.Resources = new SubresourceCount(2, 1); + description.Pitch = TileGeometry.TexturePitch(GuestPixelFormat.Bc1Srgb, 64, GuestTileMode.Linear); + description.BytesPerBlock = 8; + description.Samples = 1; + description.TileMode = GuestTileMode.Linear; + description.MipLayout[0] = new MipLevelLayout { Offset = levels[0].Offset, Size = levels[0].Size, Pitch = description.Pitch, Height = 64 }; + description.MipLayout[1] = new MipLevelLayout { Offset = levels[1].Offset, Size = levels[1].Size, Pitch = description.Pitch / 2, Height = 32 }; + var view = ImageViewDescription.Default with + { + Format = GpuFormat.BC1RgbaSrgbBlock, + Type = GpuImageViewType.Type2D, + Aspect = GpuImageAspect.ColorBit, + LevelCount = 2, + LayerCount = 1, + Usage = GpuImageUsage.SampledBit, + }; + return new ImageRequest(description, view, ImageRole.Texture); + } + + private static ImageRequest BlockSizedImage(ulong address) + { + var size = BlockSizedImageBytes; + var description = ImageDescription.Create(); + description.Data = new GuestSpan(address, size); + description.PixelFormat = GpuFormat.R32G32Uint; + description.GuestFormat = GuestPixelFormat.Bits32_32UInt; + description.Type = GuestImageType.Color2D; + description.Extent = new GpuExtent3D(16, 16, 1); + description.Resources = new SubresourceCount(1, 1); + description.Pitch = TileGeometry.TexturePitch(GuestPixelFormat.Bits32_32UInt, 16, GuestTileMode.Linear); + description.BytesPerBlock = 8; + description.Samples = 1; + description.TileMode = GuestTileMode.Linear; + description.MipLayout[0] = new MipLevelLayout { Offset = 0, Size = size, Pitch = description.Pitch, Height = 16 }; + var view = ImageViewDescription.Default with + { + Format = GpuFormat.R32G32Uint, + Type = GpuImageViewType.Type2D, + Aspect = GpuImageAspect.ColorBit, + LayerCount = 1, + Usage = GpuImageUsage.SampledBit, + }; + return new ImageRequest(description, view, ImageRole.Texture); + } + + // Guest bytes whose row padding is zero, as a texture read back into guest layout leaves it: 16 rows of 16 + // eight-byte elements (texels, or a BC1 level's blocks) from offset, each row at its padded pitch. + private static byte[] PaddedRows(int length, uint seed, ulong offset, ulong levelBytes) + { + var bytes = MetalTileOracle.Pattern(length, seed); + var pitch = (int)(levelBytes / 16); + for (var row = 0; row < 16; row++) + { + Array.Clear(bytes, (int)offset + (row * pitch) + (16 * 8), pitch - (16 * 8)); + } + + return bytes; + } + + // The memory of a texture the guest gave up now holds a one-level image whose texels are as large as the texture's + // blocks (a 16x16 R32G32 state where a 64x64 BC1 chain was). The texture is neither viewed in the other format nor + // copied across: the image is its own, made from guest memory, and the texture stays registered beside it unless + // it is past the removal window. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AnImageOfTheOtherBlockClassOverAMipChainIsItsOwn(bool aged) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var (chainBytes, _) = ChainLayout(); + rig.WriteGuest(ImageAddress, MetalTileOracle.Pattern((int)chainBytes, 0x31)); + var textureId = rig.Acquire(MippedCompressedTexture(ImageAddress)); + rig.Cache.GetImage(textureId).MarkGpuModified(); + rig.Harness.Submit(); + rig.Harness.Begin(); + if (aged) + { + for (var tick = 0; tick < 40; tick++) + { + rig.Cache.Collect(); + } + } + + // The guest's store reaches guest memory after the texture's GPU bytes there are written back. + var state = PaddedRows((int)BlockSizedImageBytes, 0x77, 0, BlockSizedImageBytes); + Assert.True(((IGuestImageStore)rig.Cache).MarkCpuWrite(ImageAddress, BlockSizedImageBytes)); + rig.WriteGuest(ImageAddress, state); + var imageId = rig.Acquire(BlockSizedImage(ImageAddress)); + rig.Harness.Submit(); + rig.Harness.Begin(); + + Assert.NotEqual(textureId, imageId); + var image = rig.Cache.GetImage(imageId); + Assert.False(image.Description.IsBlock); + Assert.Equal(state, ReadTexture(rig, image)); + Assert.Equal(!aged, rig.Cache.TryGetImage(textureId, out var texture) && texture.Description.IsBlock); + } + + // The other way: a compressed chain requested where a one-level image of its block size lies. The chain is its own + // image, made from the guest bytes, not from the image's texels. + [Fact] + public void ACompressedChainOverAnImageOfItsBlockSizeIsMadeFromGuestMemory() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var imageId = rig.Acquire(BlockSizedImage(ImageAddress)); + rig.Harness.Submit(); + rig.Harness.Begin(); + + var (chainBytes, levels) = ChainLayout(); + var blocks = PaddedRows((int)chainBytes, 0x5C, levels[0].Offset, levels[0].Size); + Assert.True(((IGuestImageStore)rig.Cache).MarkCpuWrite(ImageAddress, chainBytes)); + rig.WriteGuest(ImageAddress, blocks); + var textureId = rig.Acquire(MippedCompressedTexture(ImageAddress)); + rig.Harness.Submit(); + rig.Harness.Begin(); + + Assert.NotEqual(imageId, textureId); + var texture = rig.Cache.GetImage(textureId); + Assert.True(texture.Description.IsBlock); + var level0 = new Range((int)levels[0].Offset, (int)(levels[0].Offset + levels[0].Size)); + Assert.Equal(blocks[level0], ReadTexture(rig, texture)[level0]); + } +} From bf2ec23d53decb6dcb6e54d0d5476d541f4775f0 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:06:35 +0000 Subject: [PATCH 53/64] [Metal] Sample a depth surface's pending HTILE clear as the cleared value Port of upstream cb790c35e (Demon's Souls, PR #1172). A compute pass that clears a depth surface's HTILE leaves the clear pending until the surface is next bound as a depth target. A surface sampled before that bind kept its older contents, where the console's texture unit reads the cleared value through the HTILE; a game that clears an occlusion depth this way and builds its culling pyramid from it culled with the occluders of the last frame that drew any. The render host notes each HTILE depth bind's clear value (DB_DEPTH_CLEAR). A sample of a one-layer, one-level depth surface whose HTILE slice is marked cleared now clears the depth plane with that value first (stencil untouched), takes GPU ownership and consumes the clear. A layered surface keeps its pending clear for its next bind. A memoised sampled binding of such a surface carries a version that moves whenever an HTILE clear becomes pending, so it misses and the full acquire records the clear. SHARPEMU_METAL_V2_SAMPLED_DEPTH_CLEAR=0 turns it off. Tests: upstream's SampledDepthClear cases, plus the colour-twin sample, no noted value, and the memo miss. --- .../V2/MetalImageCache.SampledDepthClear.cs | 118 +++++++++++++ .../V2/MetalImageCache.Tracking.cs | 15 ++ .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 14 +- .../V2/MetalRenderHost.Images.cs | 7 + ...cMaterializationTests.SampledDepthClear.cs | 165 ++++++++++++++++++ .../MetalDccMaterializationTests.cs | 7 +- 6 files changed, 321 insertions(+), 5 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.SampledDepthClear.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.SampledDepthClear.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.SampledDepthClear.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.SampledDepthClear.cs new file mode 100644 index 000000000..79a3ef913 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.SampledDepthClear.cs @@ -0,0 +1,118 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; + +namespace SharpEmu.Gpu.Metal.V2; + +// A depth surface whose HTILE a compute pass cleared keeps that clear pending until the surface is next bound as a depth +// target, whose load then clears it (MetalRenderHost.AcquireDepthAttachment). A surface sampled before that bind kept its +// older contents, where the console's texture unit reads the cleared value through the HTILE. A game that clears an +// occlusion depth this way each frame and builds its culling pyramid from it then culled with the occluders of the last +// frame that drew any (Demon's Souls, upstream cb790c35e). +// +// A sample of a one-layer, one-level depth surface with a pending clear now clears it first, with the clear value of the +// surface's last depth-target bind (the value that bind would load), and consumes the clear. A layered surface keeps its +// pending clear for its next bind, as its clear bits are not exact per layer. The stencil plane is left as it is. +// SHARPEMU_METAL_V2_SAMPLED_DEPTH_CLEAR=0 leaves every pending clear to the next bind again. +internal sealed partial class MetalImageCache +{ + private static readonly bool SampledDepthClearDefault = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_SAMPLED_DEPTH_CLEAR") != "0"; + + /// <summary>Whether a sample takes a depth surface's pending HTILE clear (test hook; see the file comment).</summary> + internal bool SampledDepthClears { get; set; } = SampledDepthClearDefault; + + // Moves whenever a sampled depth surface may have a clear to take that it had not before: an HTILE slice marked + // cleared, a new registration, or a first clear value. A memoised sampled binding of such a surface is stamped + // with it (TryStampTextureLocked), so the next bind after a clear takes the full acquire, which records the clear. + private long _sampledDepthClearVersion; + + private long _sampledDepthClearsTaken; + + /// <summary>Pending HTILE clears a sample recorded since the last call.</summary> + public long TakeSampledDepthClears() => Interlocked.Exchange(ref _sampledDepthClearsTaken, 0); + + private void NoteHtileClearPendingLocked() => Interlocked.Increment(ref _sampledDepthClearVersion); + + /// <summary> + /// The depth clear value (DB_DEPTH_CLEAR) of a depth-target bind with HTILE: what a pending HTILE clear loads at + /// the next bind, and what a sample reads before that bind. + /// </summary> + public void NoteDepthClearValue(ulong htileAddress, float value) + { + using var held = _lock.Hold(); + if (_surfaceMetadata.TryGetValue(htileAddress, out var found) && found.Kind == SurfaceMetadataKind.HTile) + { + if (!found.HasDepthClearValue) + { + NoteHtileClearPendingLocked(); + } + + found.DepthClearValue = value; + found.HasDepthClearValue = true; + } + } + + // The stamp value for a sampled binding of the image: the version above when the image is the shape whose samples + // can take a pending clear, otherwise -1 (never compared). Caller holds the lock. + private long SampledDepthClearStamp(MetalCachedImage image) => + SampledDepthClears && IsSampledDepthClearShape(in image.Description) ? Volatile.Read(ref _sampledDepthClearVersion) : -1; + + private bool SampledDepthClearStampHolds(long stamped) => + stamped < 0 || stamped == Volatile.Read(ref _sampledDepthClearVersion); + + private static bool IsSampledDepthClearShape(in ImageDescription description) => + description.IsDepth && description.Resources.Levels == 1 && description.Resources.Layers == 1 && + description.Metadata.Kind == MetadataKind.Htile; + + // The registration whose pending clear a sample of the image takes, or null. Caller holds the lock. + private SurfaceMetadata? SampleClearsDepthLocked(MetalCachedImage image) + { + ref readonly var description = ref image.Description; + return SampledDepthClears && image.Texture != 0 && IsSampledDepthClearShape(in description) && + _surfaceMetadata.TryGetValue(description.Metadata.Range.Address, out var metadata) && + metadata is { Kind: SurfaceMetadataKind.HTile, Invalidated: false, HasDepthClearValue: true } && + metadata.IsSliceClear(0) + ? metadata + : null; + } + + // Records the clear the next depth-target bind would load, ahead of a sample, and consumes it. A write like any + // pass's: the image takes the bytes from its aliases and owes guest memory a writeback. Its stencil plane, which the + // clear leaves alone, is brought up to date first, since taking ownership drops what the image still owed it. + // Caller holds the lock. + private void ClearDepthBeforeSampleLocked(ResourceSlotIdentifier imageIdentifier, MetalCachedImage image, SurfaceMetadata metadata) + { + PromoteLinearView(image); + MapSparseLayers(image, 0, 1); + WatchImage(imageIdentifier); + DrainOverlappingDeferredRefreshesLocked(image); + SynchronizeAliases(imageIdentifier, takesGpuOwnership: true, role: "depth"); + if (image.Description.HasStencil) + { + RefreshFromGuest(image); + } + + var range = new SubresourceRange(0, 1, 0, 1); + _owner.ClearTextureDepthStencil( + image.Texture, image.Shape.PixelFormat, in range, + image.Description.Extent.Width, image.Description.Extent.Height, + metadata.DepthClearValue, 0, clearDepth: true, clearStencil: false); + NoteRefusedRewrite(image, whole: !image.Description.HasStencil); + image.RefreshComplete(); + image.MarkGpuModified(); + NoteLinearGpuWrite(image); + image.GpuWriteSerial = _owner.CurrentSerial; + metadata.SetSliceClear(0, false); + _sampledDepthClearsTaken++; + if (SharpEmu.Libs.Gpu.Rendering.RenderExecutor.TraceHtile) + { + Console.Error.WriteLine( + $"[METAL-V2][HTILE] sampled-clear depth=0x{image.Description.Data.Address:X16} " + + $"htile=0x{image.Description.Metadata.Range.Address:X16} value={metadata.DepthClearValue}"); + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs index 1908e9caa..ddc1bc3e2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs @@ -1764,6 +1764,7 @@ private void RegisterHtileMetadata(in ImageDescription description) ClearMask = RegisteredHtileClearMaskLocked(address, in description, "none"), Size = description.Metadata.Range.Size, }); + NoteHtileClearPendingLocked(); return; } @@ -1775,6 +1776,9 @@ private void RegisterHtileMetadata(in ImageDescription description) metadata.Kind = SurfaceMetadataKind.HTile; metadata.FillValue = 0xffffffff; metadata.FillSize = 0; + // Nor is the depth clear value of the last bind (MetalImageCache.SampledDepthClear.cs). + metadata.HasDepthClearValue = false; + NoteHtileClearPendingLocked(); } if (metadata.Kind == SurfaceMetadataKind.HTile) @@ -1840,6 +1844,11 @@ private bool SetMetadataSliceLocked(ulong address, uint slice, bool isClear) } found.SetSliceClear(slice, isClear); + if (isClear && found.Kind == SurfaceMetadataKind.HTile) + { + NoteHtileClearPendingLocked(); + } + return true; } @@ -1857,7 +1866,13 @@ public bool ClearMetadata(ulong address) return false; } + var newlyClear = found.ClearMask != uint.MaxValue; found.ClearMask = uint.MaxValue; + if (newlyClear && found.Kind == SurfaceMetadataKind.HTile) + { + NoteHtileClearPendingLocked(); + } + return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 873c5112b..2e0385d5f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -1442,7 +1442,7 @@ public nint AcquireTextureViewForMemo( /// <summary>When a memoised sampled binding still holds; see <see cref="TryStampTextureLocked"/>.</summary> internal readonly record struct TextureMemoStamp( MetalCachedImage Image, long ImageVersion, ulong RangeStart, ulong RangeSize, long PageVersions, long StencilOwners, - MetalCachedImage[]? Others = null, long OthersVersion = 0); + MetalCachedImage[]? Others = null, long OthersVersion = 0, long DepthClears = -1); // The images over the same bytes a memoised binding can stand beside: past this many the // binding takes the full acquire every time. @@ -1527,7 +1527,7 @@ public long RequestPageVersions(in ImageRequest request) => var aliases = others?.ToArray(); return new TextureMemoStamp(image, image.BindingVersion, start, end - start, _pageOwners.VersionSum(start, end - start), _stencilOwnersVersion, - aliases, aliases is null ? 0 : AliasVersion(image, aliases)); + aliases, aliases is null ? 0 : AliasVersion(image, aliases), SampledDepthClearStamp(image)); } /// <summary> @@ -1539,6 +1539,7 @@ public bool StampHoldsUnlocked(in TextureMemoStamp stamp, bool imageSetUnchanged Volatile.Read(ref stamp.Image.BindingVersion) == stamp.ImageVersion && stamp.StencilOwners == Volatile.Read(ref _stencilOwnersVersion) && (stamp.Others is null || AliasVersion(stamp.Image, stamp.Others) == stamp.OthersVersion) && + SampledDepthClearStampHolds(stamp.DepthClears) && (imageSetUnchanged || _pageOwners.VersionSum(stamp.RangeStart, stamp.RangeSize) == stamp.PageVersions); /// <summary> @@ -1549,6 +1550,7 @@ public bool TextureStampMayHold(in TextureMemoStamp stamp) => !HasDeferredRefreshes && Volatile.Read(ref stamp.Image.BindingVersion) == stamp.ImageVersion && (stamp.Others is null || AliasVersion(stamp.Image, stamp.Others) == stamp.OthersVersion) && + SampledDepthClearStampHolds(stamp.DepthClears) && _pageOwners.VersionSum(stamp.RangeStart, stamp.RangeSize) == stamp.PageVersions; private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in ImageRequest request, out ulong resourceId) @@ -1615,6 +1617,13 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in image.NoteUse(_owner.CurrentSerial); } + // A depth surface sampled while its HTILE holds a clear the next depth bind would load reads the cleared value + // (MetalImageCache.SampledDepthClear.cs). + if (request.Role == ImageRole.Texture && SampleClearsDepthLocked(image) is { } pendingClear) + { + ClearDepthBeforeSampleLocked(imageIdentifier, image, pendingClear); + } + MaterializeSampledDccClear(imageIdentifier, image, in request); if (request.Role == ImageRole.Texture && image.Description.IsDepth && TryDepthTwinView(image, in request.View, out var depthView)) @@ -1686,6 +1695,7 @@ internal bool TryReacquireTextureViewHeld(ResourceSlotIdentifier imageIdentifier if (_deferredRefreshes.Count != 0 || !ReferenceEquals(_slots.TryGet(imageIdentifier), image) || image.BindingVersion != stamp.ImageVersion || _stencilOwnersVersion != stamp.StencilOwners || (stamp.Others is not null && AliasVersion(image, stamp.Others) != stamp.OthersVersion) || + !SampledDepthClearStampHolds(stamp.DepthClears) || _pageOwners.VersionSum(stamp.RangeStart, stamp.RangeSize) != stamp.PageVersions) { return false; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs index 11f0c052d..00122ff4a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs @@ -167,6 +167,13 @@ DepthAttachmentAcquisition IRenderHost.AcquireDepthAttachment(in DepthAttachment } } + // The value a later pending HTILE clear loads at the next bind, and what a sample before that bind reads + // (MetalImageCache.SampledDepthClear.cs). + if (resolution.HasHtile) + { + _imageCache.NoteDepthClearValue(resolution.HtileAddress, depth.Target.State.DepthClearValue); + } + var image = _imageCache.GetImage(imageIdentifier); if (_dumpSnapshots) { diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.SampledDepthClear.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.SampledDepthClear.cs new file mode 100644 index 000000000..bcea99578 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.SampledDepthClear.cs @@ -0,0 +1,165 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// A depth surface the guest clears through its HTILE and then samples before binding it as a depth target again +// (upstream GuestImageCacheTests.SampledDepthClear, cb790c35e): the sample reads the cleared value. +public sealed unsafe partial class MetalDccMaterializationTests +{ + private const ulong SampledHtileAddress = DepthAddress + 0x280000; + + private static ImageRequest HtileDepth(uint layers, bool stencil = false) + { + var depth = DepthAliasRequest(ImageRole.DepthTarget, stencil); + if (layers > 1) + { + var size = depth.Description.Data.Size; + depth.Description.Data = new GuestSpan(depth.Description.Data.Address, size * layers); + depth.Description.Resources = new SubresourceCount(1, layers); + depth.Description.MipLayout[0] = depth.Description.MipLayout[0] with { Size = size * layers }; + depth.View = depth.View with { Type = GpuImageViewType.Type2DArray, LayerCount = layers }; + } + + depth.Description.Metadata.Kind = MetadataKind.Htile; + depth.Description.Metadata.Range = new GuestSpan(SampledHtileAddress, 0x1000 * layers); + return depth; + } + + private static ImageRequest SampledDepth(ImageRequest depth) + { + depth.Role = ImageRole.Texture; + depth.Description.Metadata = default; + depth.Description.Stencil = default; + depth.View = depth.View with { Usage = GpuImageUsage.SampledBit }; + return depth; + } + + // A bind with HTILE, the clear it loads consumed as the render host does, the bind's clear value noted, and then a + // compute clear of the HTILE that leaves the clear pending. + private static ResourceSlotIdentifier BoundThenHtileCleared(Rig rig, ImageRequest depth, float clearValue) + { + var depthId = rig.Cache.FindImage(ref depth); + rig.Cache.AcquireDepthTargetView(depthId, in depth); + Assert.True(rig.Cache.SetMetadataSlice(SampledHtileAddress, depth.View.BaseLayer, false)); + rig.Cache.NoteDepthClearValue(SampledHtileAddress, clearValue); + Assert.True(rig.Cache.ClearMetadata(SampledHtileAddress)); + return depthId; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ASampledDepthTakesThePendingHtileClearWithTheValueOfItsLastBind(bool stencil) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var depth = HtileDepth(1, stencil); + var depthId = BoundThenHtileCleared(rig, depth, 0.25f); + rig.Owner.DepthClears.Clear(); + + var sampled = SampledDepth(depth); + Assert.Equal(depthId, rig.Cache.FindImage(ref sampled)); + rig.Cache.AcquireTextureView(depthId, in sampled); + + var clear = Assert.Single(rig.Owner.DepthClears); + Assert.Equal(0.25f, clear.Depth); + Assert.True(clear.ClearDepth); + Assert.False(clear.ClearStencil); + Assert.Equal(new SubresourceRange(0, 1, 0, 1), clear.Range); + Assert.False(rig.Cache.IsMetadataCleared(SampledHtileAddress, 0)); + Assert.True(rig.Cache.GetImage(depthId).IsGpuModified); + Assert.Equal(1, rig.Cache.TakeSampledDepthClears()); + + // Taken once: the next sample reads what the clear left. + rig.Cache.AcquireTextureView(depthId, in sampled); + Assert.Single(rig.Owner.DepthClears); + rig.Harness.Submit(); + } + + // Sampled as its R32 colour twin, the depth surface binds its own texture and takes the clear the same way. + [Fact] + public void ADepthSampledAsItsColourTwinTakesThePendingHtileClear() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + rig.Cache.DepthTwins = true; + var depthId = BoundThenHtileCleared(rig, HtileDepth(1), 0.5f); + rig.Owner.DepthClears.Clear(); + + var twin = DepthAliasRequest(ImageRole.Texture); + Assert.Equal(depthId, rig.Cache.FindImage(ref twin)); + rig.Cache.AcquireTextureView(depthId, in twin); + + Assert.Equal(0.5f, Assert.Single(rig.Owner.DepthClears).Depth); + Assert.False(rig.Cache.IsMetadataCleared(SampledHtileAddress, 0)); + rig.Harness.Submit(); + } + + // A layered surface's clear bits are not exact per slice: its pending clear stays for its next depth-target bind. + [Fact] + public void ASampledDepthLeavesALayeredSurfacesPendingClearToItsNextBind() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var depth = HtileDepth(2); + var depthId = BoundThenHtileCleared(rig, depth, 0.25f); + rig.Owner.DepthClears.Clear(); + + var sampled = SampledDepth(depth); + Assert.Equal(depthId, rig.Cache.FindImage(ref sampled)); + rig.Cache.AcquireTextureView(depthId, in sampled); + + Assert.Empty(rig.Owner.DepthClears); + Assert.True(rig.Cache.IsMetadataCleared(SampledHtileAddress, 0)); + rig.Harness.Submit(); + } + + // No bind noted a clear value: nothing says what the clear loads, so the sample leaves it to the next bind. + [Fact] + public void ASampledDepthWithNoBoundClearValueLeavesThePendingClear() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var depth = HtileDepth(1); + var depthId = rig.Cache.FindImage(ref depth); + rig.Cache.AcquireDepthTargetView(depthId, in depth); + Assert.True(rig.Cache.ClearMetadata(SampledHtileAddress)); + rig.Owner.DepthClears.Clear(); + + var sampled = SampledDepth(depth); + rig.Cache.AcquireTextureView(depthId, in sampled); + + Assert.Empty(rig.Owner.DepthClears); + Assert.True(rig.Cache.IsMetadataCleared(SampledHtileAddress, 0)); + rig.Harness.Submit(); + } + + // A memoised sampled binding of the surface stops holding once its HTILE is cleared again, so the next bind takes + // the full acquire, which records the clear. + [Fact] + public void AMemoisedSampledDepthMissesOnceItsHtileIsClearedAgain() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var depth = HtileDepth(1); + var depthId = BoundThenHtileCleared(rig, depth, 0.25f); + var sampled = SampledDepth(depth); + var pages = rig.Cache.RequestPageVersions(in sampled); + Assert.Equal(depthId, rig.Cache.FindImage(ref sampled)); + rig.Cache.AcquireTextureViewForMemo(depthId, in sampled, pages, out _, out var stamp); + Assert.NotNull(stamp); + Assert.True(rig.Cache.TryReacquireTextureView(depthId, in sampled, stamp!.Value)); + + Assert.True(rig.Cache.ClearMetadata(SampledHtileAddress)); + Assert.False(rig.Cache.TextureStampMayHold(stamp.Value)); + Assert.False(rig.Cache.TryReacquireTextureView(depthId, in sampled, stamp.Value)); + rig.Harness.Submit(); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.cs index fae55abb3..6ec3cdbc1 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalDccMaterializationTests.cs @@ -125,10 +125,11 @@ public void ClearTextureColor(nint texture, ulong pixelFormat, in SubresourceRan ClearRanges.Add(range); } + public readonly List<(float Depth, bool ClearDepth, bool ClearStencil, SubresourceRange Range)> DepthClears = []; + public void ClearTextureDepthStencil(nint texture, ulong pixelFormat, in SubresourceRange range, uint width, uint height, - float depth, byte stencil, bool clearDepth, bool clearStencil) - { - } + float depth, byte stencil, bool clearDepth, bool clearStencil) => + DepthClears.Add((depth, clearDepth, clearStencil, range)); } private sealed class Rig : IDisposable From e30d67b54881437d1cea69a11484a21ce896524c Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:06:44 +0000 Subject: [PATCH 54/64] [Metal] Keep an alias the current frame or a recurring pair uses where overlaps release images Port of upstream c30081163 (GuestImageCache.UsedThisFrameForOverlap). Overlap resolution released a cached image once it was past a 32-tick window, but ticks advance per completed submission and a frame spans hundreds of them: an alias the frame had used early on was released, and two aliases of the same memory a title uses every frame swapped at each one's first use in a frame (a writeback of the GPU-written one, and the next frame made it again from guest memory). An image the current frame used, or one used in each of the two frames before, now counts as in use there. Each use stamps the tick of the use before the frame's first (MetalCachedImage.PreviousUseTick). An image only the frame before used is released as before, and before the first presented frame the tick window decides alone. SHARPEMU_METAL_V2_FRAME_ALIASES=0 restores the tick window alone. --- .../SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs | 4 ++ .../V2/MetalImageCache.FrameAliases.cs | 55 +++++++++++++++ .../V2/MetalImageCache.KernelFills.cs | 2 +- .../V2/MetalImageCache.Tracking.cs | 1 + .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 15 +++-- .../MetalImageAliasTests.UpstreamLookups.cs | 67 ++++++++++++++++++- 6 files changed, 135 insertions(+), 9 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.FrameAliases.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs index ea5c4efaf..81edf0a18 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCachedImage.cs @@ -425,6 +425,10 @@ public ulong LastAccessTick } } + // The collection tick of the last use before the current frame's first, or ulong.MaxValue for none: an image used + // in each of the two frames before the current one is a recurring alias (MetalImageCache.FrameAliases.cs). + public ulong PreviousUseTick = ulong.MaxValue; + /// <summary>Stopwatch ticks of the last use; kept only with SHARPEMU_LOG_MEMORY=1 (idle-age census).</summary> public long LastAccessTimestamp; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.FrameAliases.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.FrameAliases.cs new file mode 100644 index 000000000..a2f824968 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.FrameAliases.cs @@ -0,0 +1,55 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Gpu.Metal.V2; + +// Where an overlapping request decides whether a cached image is safe to release (ResolveOverlap), an image the current +// frame used counts as in use, and so does a recurring alias: one used in each of the two frames before this one +// (upstream c30081163, GuestImageCache.UsedThisFrameForOverlap). Collection ticks advance per completed submission and a +// frame spans hundreds of them, so the tick window alone released an alias the frame had used early on, and two aliases +// of the same memory that a title uses every frame swapped at each one's first use in a frame: each request released the +// other (a writeback when the GPU wrote it) and the next frame made it again from guest memory. An image the frame +// before used but the one before it did not is released as before, so the one-off images a title places in the same +// memory frame after frame do not pile up. Before the first presented frame no frame is known, and the tick window +// decides alone, as it did. SHARPEMU_METAL_V2_FRAME_ALIASES=0 restores the tick window alone. +internal sealed partial class MetalImageCache +{ + private static readonly bool FrameAliasesDefault = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_FRAME_ALIASES") != "0"; + + /// <summary>Whether overlap resolution keeps aliases this frame or a recurring pair uses (test hook; see above).</summary> + internal bool FrameAliases { get; set; } = FrameAliasesDefault; + + // The collection tick at which the frame before the previous one began (MarkFrame). + private ulong _secondPreviousFrameStartTick; + + // Stamps a use of the image: the first use in a frame keeps the tick of the use before it. Caller holds the lock. + private void TouchImage(MetalCachedImage image) + { + if (image.LastAccessTick < _frameStartTick) + { + image.PreviousUseTick = image.LastAccessTick; + } + + image.LastAccessTick = _collectionTick; + } + + // Whether an overlapping cached image counts as in use for overlap resolution. Caller holds the lock. + private bool UsedThisFrameForOverlap(MetalCachedImage cached) + { + if (!FrameAliases || _idleClock.Frames == 0) + { + return false; + } + + var lastUse = cached.LastAccessTick; + if (lastUse >= _frameStartTick) + { + return true; + } + + var previous = cached.PreviousUseTick; + return _idleClock.Frames >= 2 && lastUse >= _previousFrameStartTick && + previous != ulong.MaxValue && previous >= _secondPreviousFrameStartTick && previous < _previousFrameStartTick; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs index 6d25419dd..01b2ccf71 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.KernelFills.cs @@ -290,7 +290,7 @@ private bool TakeKernelWriteOwnershipLocked(ResourceSlotIdentifier imageIdentifi return false; } - image.LastAccessTick = _collectionTick; + TouchImage(image); WatchImage(imageIdentifier); SynchronizeAliases(imageIdentifier, takesGpuOwnership: true); return true; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs index ddc1bc3e2..dc896f2d1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.Tracking.cs @@ -656,6 +656,7 @@ public void StopWatching() public void MarkFrame() { using var held = _lock.Hold(); + _secondPreviousFrameStartTick = _previousFrameStartTick; _previousFrameStartTick = _frameStartTick; _frameStartTick = _collectionTick; _idleClock.MarkFrame(_collectionTick); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 2e0385d5f..82c1e4172 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -388,7 +388,7 @@ private ResourceSlotIdentifier LookUpImageLocked(ref ImageRequest request, bool request.View = request.View with { BaseLayer = (uint)viewLayer }; } - image.LastAccessTick = _collectionTick; + TouchImage(image); return result; } @@ -1559,7 +1559,7 @@ private nint AcquireTextureViewLocked(ResourceSlotIdentifier imageIdentifier, in // now must see it the way the acquire left it before the wait existed. DrainDeferredRefreshesLocked(); var image = _slots[imageIdentifier]; - image.LastAccessTick = _collectionTick; + TouchImage(image); var traced = TracedImageAddress != 0 && image.Description.Data.Address == TracedImageAddress && (_tracedAcquires++ < 64 || request.Role == ImageRole.StorageImage && _tracedAcquires < 4000); if (traced) @@ -1668,7 +1668,7 @@ public void NoteMemoisedTextureUses(ReadOnlySpan<TextureMemoStamp?> stamps) { if (stamp is { } taken) { - taken.Image.LastAccessTick = _collectionTick; + TouchImage(taken.Image); taken.Image.NoteUse(serial); } } @@ -1701,7 +1701,7 @@ internal bool TryReacquireTextureViewHeld(ResourceSlotIdentifier imageIdentifier return false; } - image.LastAccessTick = _collectionTick; + TouchImage(image); FitResidentLevelsLocked(image, in request.View); if (image.BindingVersion != stamp.ImageVersion) { @@ -1834,7 +1834,7 @@ public nint AcquireColorTargetView( using var held = _lock.Hold(); var image = _slots[imageIdentifier]; DrainOverlappingDeferredRefreshesLocked(image); - image.LastAccessTick = _collectionTick; + TouchImage(image); PromoteLinearView(image); EnsureViewUsageLocked(image, in request.View); WatchImage(imageIdentifier); @@ -1915,7 +1915,7 @@ public nint AcquireDepthTargetView( using var held = _lock.Hold(); var image = _slots[imageIdentifier]; DrainOverlappingDeferredRefreshesLocked(image); - image.LastAccessTick = _collectionTick; + TouchImage(image); PromoteLinearView(image); writes |= !ReadOnlyDepthPassesEnabled; @@ -2567,7 +2567,8 @@ private OverlapResolution ResolveOverlap( ref var cachedInfo = ref cached.Description; var role = request.Role; - var safeToDelete = _collectionTick - Math.Min(_collectionTick, cached.LastAccessTick) > TicksBeforeRemoval; + var safeToDelete = !UsedThisFrameForOverlap(cached) && + _collectionTick - Math.Min(_collectionTick, cached.LastAccessTick) > TicksBeforeRemoval; var requestedBlock = requested.BytesPerBlock * requested.Samples; var cachedBlock = cachedInfo.BytesPerBlock * cachedInfo.Samples; var requestedExtent = requested.BlockExtent; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs index 6e320d2cc..48b626276 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageAliasTests.UpstreamLookups.cs @@ -4,12 +4,14 @@ using SharpEmu.Gpu.Metal.V2; using SharpEmu.HLE.GpuMemory; using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; using SharpEmu.Libs.Gpu.Images; using Xunit; namespace SharpEmu.Gpu.Metal.Tests; -// Lookups ported from upstream's GuestImageCacheTests (ImageTypes 957d1dc90, BlockAlias cb790c35e). +// Lookups ported from upstream's GuestImageCacheTests (ImageTypes 957d1dc90, BlockAlias cb790c35e) and its overlap rule +// for aliases a frame uses (c30081163). public sealed unsafe partial class MetalImageAliasTests { // A program can read a two-dimensional texture as a volume. Its image is not 3D, and an image made from the @@ -188,4 +190,67 @@ public void ACompressedChainOverAnImageOfItsBlockSizeIsMadeFromGuestMemory() var level0 = new Range((int)levels[0].Offset, (int)(levels[0].Offset + levels[0].Size)); Assert.Equal(blocks[level0], ReadTexture(rig, texture)[level0]); } + + public enum FrameUse + { + ThisFrame, + EachOfTheTwoFramesBefore, + OnlyTheFrameBefore, + } + + // Past the tick window, an overlapping request releases a cached image only when neither the current frame used it + // nor each of the two frames before did: two aliases a title uses every frame keep both registered, and a one-off + // image the frame before placed there is released as before. + [Theory] + [InlineData(FrameUse.ThisFrame, true, true)] + [InlineData(FrameUse.EachOfTheTwoFramesBefore, true, true)] + [InlineData(FrameUse.OnlyTheFrameBefore, true, false)] + [InlineData(FrameUse.EachOfTheTwoFramesBefore, false, false)] + public void AnOverlappingRequestKeepsAnAliasTheFramesUse(FrameUse use, bool frameAliases, bool kept) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + rig.Cache.FrameAliases = frameAliases; + + // Past the tick window, the last submission of the frame completed, and then the flip. + void NextFrame() + { + for (var tick = 0; tick < 40; tick++) + { + rig.Cache.Collect(); + } + + rig.Cache.MarkFrame(); + } + + NextFrame(); + var aliasId = ResourceSlotIdentifier.Invalid; + switch (use) + { + case FrameUse.ThisFrame: + aliasId = rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture); + break; + case FrameUse.EachOfTheTwoFramesBefore: + aliasId = rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture); + NextFrame(); + Assert.Equal(aliasId, rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture)); + NextFrame(); + break; + case FrameUse.OnlyTheFrameBefore: + NextFrame(); + aliasId = rig.Acquire(ImageAddress, LargeSide, ImageRole.Texture); + NextFrame(); + break; + } + + for (var tick = 0; tick < 40; tick++) + { + rig.Cache.Collect(); + } + + // The same bytes as a 128x32 surface: no view of the 64x64 one, and not the same surface either. + var other = rig.Acquire(Rig.Request(ImageAddress, LargeSide * 2, LargeSide / 2, ImageRole.Texture)); + Assert.NotEqual(aliasId, other); + Assert.Equal(kept, rig.Cache.TryGetImage(aliasId, out _)); + } } From 2b0f8118aaede066d2e26b809a2781343abbff58 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:07:32 +0000 Subject: [PATCH 55/64] [Tests] Pin split protocol 10 and refuse a revision 9 region --- tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs index c082716c7..2ec25da6f 100644 --- a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs @@ -89,13 +89,14 @@ public void AttachRefusesAnotherProtocolVersion() [InlineData(6u)] [InlineData(7u)] [InlineData(8u)] + [InlineData(9u)] public void CombinedLayoutRefusesEveryIndependentRecoveryProtocol(uint version) { if (!OperatingSystem.IsMacOS()) return; using var host = GpuRemoteChannel.Create(SharedMemoryRegion.CreateUniqueName("setest")); using (var raw = SharedMemoryRegion.Open(host.Name)) ((RegionHeader*)raw.Pointer)->Version = version; - Assert.Equal(9u, GpuRemoteProtocol.Version); + Assert.Equal(10u, GpuRemoteProtocol.Version); Assert.Throws<InvalidDataException>(() => GpuRemoteChannel.Attach(host.Name)); } From 69b353d9d341908e59d8d1067234e4e7a129db93 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:29:38 +0000 Subject: [PATCH 56/64] [GPU] Add SHARPEMU_DEFERRED_DISPATCH_RUNS=0 and make no worker rebind pools for whole-work hosts Upstream c30081163's deferred dispatch runs had no off-switch. A host that resolves whole draws and dispatches where they run (the Metal host) prefetches dispatch rebinds on its own resolve thread and serves no strict or ticket worker reads, so neither the deferred-run pool nor the compute-ticket pool (next commit) is made for it: they were idle threads there. --- .../Agc/AgcExports.DeferredDispatchRuns.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs b/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs index 04f4dd37f..9004b6a26 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.DeferredDispatchRuns.cs @@ -62,10 +62,20 @@ public sealed partial class CommandStreamTranslation internal IDeferredDispatchRuns? DispatchRuns => _dispatchRuns; + // SHARPEMU_DEFERRED_DISPATCH_RUNS=0 keeps every direct dispatch on the command thread. + internal static readonly bool DeferredDispatchRunsEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_DEFERRED_DISPATCH_RUNS") != "0"; + + // A host that resolves whole draws and dispatches where they run (_defersWholeWork: the Metal host) prefetches + // dispatch rebinds on its own resolve thread (ParallelProgramPrefetch) and serves no strict worker reads, so it + // takes no deferred runs and no compute tickets, and neither pool is made for it. + private bool UsesWorkerDispatchRebinds => !_defersWholeWork; + private void ReplaceDispatchRuns(bool create) { _dispatchRuns?.Dispose(); - _dispatchRuns = create && _executor is not null && _pipelines is { SupportsParallelResolution: true } && _host.RenderHost is { } renderHost + _dispatchRuns = create && DeferredDispatchRunsEnabled && UsesWorkerDispatchRebinds && _executor is not null && + _pipelines is { SupportsParallelResolution: true } && _host.RenderHost is { } renderHost ? new DeferredDispatchRuns(this, renderHost, DeferredDispatchWorkers) : null; } From 39ea95b7a7d0f803d29897d0853bbf606cec2a46 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:29:38 +0000 Subject: [PATCH 57/64] [Metal] Take indexed draw runs on the Metal host Port of upstream c30081163/cb790c35e indexed draw runs to the Metal host: - the interpreter looks for a run in the command block when no shared packet window holds the packet (the Metal host hands over command blocks), and leaves draws that must execute (predication, open occlusion query) to their own handler; - the translation defers a run whole, with its offsets, as it defers a draw for a host that resolves where it runs; the run check resolves targets into thread scratch, not the executor's cached resolution, and the learnt draw writes are concurrent; - a run's resolve takes the run's MustExecute (RenderExecutor.DrawIndexedRun); - the Metal host forwards TryDrawIndexedRun (SHARPEMU_METAL_V2_INDEXED_RUNS=0 off) and implements CanShareIndexedBindings (no storage image, movie plane, texture that is a target, or fill held over the records' page), with counts on the TBDR line. The compute-ticket pool is no longer made for a whole-work host either. --- .../Agc/AgcExports.CommandStream.cs | 89 ++++++++++---- .../Agc/AgcExports.ResolvePool.cs | 8 +- .../GpuCommandInterpreter.Draws.cs | 15 ++- .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 35 +++++- .../Gpu/Rendering/RenderExecutor.cs | 30 +++++ .../V2/MetalCommandStream.cs | 44 +++++++ .../V2/MetalRenderHost.MeshIndirect.cs | 4 + .../V2/MetalRenderHost.Rendering.cs | 53 +++++++++ .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 3 +- .../Scenes/IndexedRunSceneTests.cs | 112 ++++++++++++++++++ 10 files changed, 352 insertions(+), 41 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/IndexedRunSceneTests.cs diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs index 268e9aa84..38cd8ca6a 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandStream.cs @@ -301,6 +301,8 @@ private sealed record PendingDraw : DeferredWork public SubmittedVertexSnapshot? VertexSnapshot; public SubmittedIndexSnapshot? IndexSnapshot; public ParallelProgramPrefetch.Job? Job; + // An indexed draw run's indirect offsets (TryDrawIndexedRun), or null for one draw. + public uint[]? IndirectOffsets; } // Only the interpreter/render thread's local queue owns reusable wrappers. A sink @@ -327,6 +329,7 @@ private PendingDraw TakePendingDraw(bool producing, ulong submitId, SubmittedDcb draw.VertexSnapshot = state.CurrentVertexSnapshot; draw.IndexSnapshot = state.CurrentIndexSnapshot; draw.Job = job; + draw.IndirectOffsets = null; return draw; } @@ -344,6 +347,7 @@ private void ReturnLocalDraw(PendingDraw draw) draw.VertexSnapshot = null; draw.IndexSnapshot = null; draw.Job = null; + draw.IndirectOffsets = null; _spareLocalDraws.Push(draw); } @@ -402,7 +406,7 @@ _host.RenderHost is { } renderHost && _host.ResolveWorkerCount > 0 : null; ReplaceDispatchRuns(value is not null); _computeTicketPool?.Dispose(); - _computeTicketPool = value is not null && _executor is not null && _pipelines is { SupportsParallelResolution: true } pipelines && + _computeTicketPool = value is not null && UsesWorkerDispatchRebinds && _executor is not null && _pipelines is { SupportsParallelResolution: true } pipelines && ComputeTickets.Mode != ComputeTickets.TicketMode.Off ? new ComputeTickets(pipelines, reads => _host.BeginWorkerResolve(long.MaxValue, reads), () => _host.EndWorkerResolve(), reads => _host.ValidateTicketReads(reads), ComputeTickets.WorkerCount, verify: ComputeTickets.Mode == ComputeTickets.TicketMode.Verify) @@ -478,7 +482,7 @@ public void RunDeferred(DeferredWork work) try { RunExecutorDraw(draw.SubmitId, draw.State, draw.Banks, draw.Indexed, draw.IndexedArguments, draw.AutoArguments, - clearSnapshots: false); + clearSnapshots: false, draw.IndirectOffsets); } finally { @@ -670,7 +674,8 @@ private void DrainPendingDrawsCore() try { - RunExecutorDraw(pending.SubmitId, state, pending.Banks, pending.Indexed, pending.IndexedArguments, pending.AutoArguments); + RunExecutorDraw(pending.SubmitId, state, pending.Banks, pending.Indexed, pending.IndexedArguments, pending.AutoArguments, + offsets: pending.IndirectOffsets); } finally { @@ -773,22 +778,7 @@ private bool TryRunExecutorDraw(ulong submitId, SubmittedDcbState state, bool in if (_defersWholeWork && (_parallel is not null || producing)) { - var snapshot = banks.Snapshot(); - var pending = TakePendingDraw(producing, submitId, state, snapshot, indexed, in indexedArguments, in autoArguments, - _parallel?.SubmitDrawAhead(snapshot, producing ? (_drawsCrossDispatches ? Sink!.DispatchGate : Sink!.Gate) : 0, - producing ? Sink!.Gate : 0, indexed, - indexed ? indexedArguments.StartInstanceUserData : autoArguments.StartInstanceUserData)); - if (producing) - { - Sink!.EnqueueDeferred(pending, isDraw: true); - } - else - { - _pendingDraws.Enqueue(pending); - } - - state.CurrentIndexSnapshot = null; - state.CurrentVertexSnapshot = null; + DeferWholeDraw(producing, submitId, state, banks, indexed, in indexedArguments, in autoArguments, offsets: null); return true; } @@ -806,15 +796,42 @@ private bool TryRunExecutorDraw(ulong submitId, SubmittedDcbState state, bool in return true; } + // A draw (or an indexed draw run) deferred whole to where it runs, with its programs prefetched (_defersWholeWork). + private void DeferWholeDraw(bool producing, ulong submitId, SubmittedDcbState state, RegisterBanks banks, bool indexed, + in DrawIndexedArguments indexedArguments, in DrawAutoArguments autoArguments, uint[]? offsets) + { + var snapshot = banks.Snapshot(); + var pending = TakePendingDraw(producing, submitId, state, snapshot, indexed, in indexedArguments, in autoArguments, + _parallel?.SubmitDrawAhead(snapshot, producing ? (_drawsCrossDispatches ? Sink!.DispatchGate : Sink!.Gate) : 0, + producing ? Sink!.Gate : 0, indexed, + indexed ? indexedArguments.StartInstanceUserData : autoArguments.StartInstanceUserData)); + pending.IndirectOffsets = offsets; + if (producing) + { + Sink!.EnqueueDeferred(pending, isDraw: true); + } + else + { + _pendingDraws.Enqueue(pending); + } + + state.CurrentIndexSnapshot = null; + state.CurrentVertexSnapshot = null; + } + private void RunExecutorDraw(ulong submitId, SubmittedDcbState state, RegisterBanks banks, bool indexed, in DrawIndexedArguments indexedArguments, in DrawAutoArguments autoArguments, - bool clearSnapshots = true) + bool clearSnapshots = true, uint[]? offsets = null) { var executor = _executor!; var drawStarted = DcbParseProfile.Begin(); _learningKey = (banks.Shader.Vertex.ExportAddress, banks.Shader.Pixel.Address); try { - if (indexed) + if (indexed && offsets is not null) + { + executor.DrawIndexedRun(submitId, banks, in indexedArguments, offsets); + } + else if (indexed) { executor.DrawIndexed(submitId, banks, in indexedArguments); } @@ -906,19 +923,39 @@ internal void RecordIndexedDrawState(in DrawIndexedArguments arguments) SelectSnapshots(state, arguments.PacketAddress, indexed: true, arguments.IndexAddress, arguments.IndexCount); } - internal bool TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) + // A host that resolves whole draws where they run (_defersWholeWork: the Metal host) takes the run as one deferred + // draw carrying its offsets, as TryRunExecutorDraw defers a draw; a host with resolve workers defers it to them. + public bool TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) { var state = RequireCurrent(); var banks = RequireTypedRegisters(state); - if (_resolvePool is not { } pool || _executor is null || !Producing || + var producing = Producing; + var whole = _defersWholeWork && (_parallel is not null || producing); + var pool = _resolvePool; + if ((!whole && (pool is null || !producing)) || _executor is null || state.ActiveVertexSnapshots is { Count: > 0 } || state.ActiveIndexSnapshots is { Count: > 0 } || !_drawWrites.TryGetValue((banks.Shader.Vertex.ExportAddress, banks.Shader.Pixel.Address), out var known) || - !known.Group || known.Registrations != ShaderHeaderRegistry.Registrations || !_executor.CanGroupIndexed(banks, in first)) return false; + !known.Group || known.Registrations != ShaderHeaderRegistry.Registrations || + !(whole ? _executor.CanGroupIndexedConcurrently(banks, in first) : _executor.CanGroupIndexed(banks, in first))) return false; Diagnostics.DispatchRunTally.NoteDraw(); RecordIndexedDrawState(in first); - RecordKnownColorTargets(state, banks); var run = offsets.ToArray(); - DeferDraw(pool, submitId, banks, true, in first, default, run); + if (whole) + { + if (!producing) + { + // A whole draw deferred to the render thread records its targets there (RunDeferred). + RecordKnownColorTargets(state, banks); + } + + DeferWholeDraw(producing, submitId, state, banks, indexed: true, in first, default, run); + } + else + { + RecordKnownColorTargets(state, banks); + DeferDraw(pool!, submitId, banks, true, in first, default, run); + } + state.FrameDrawCount += (uint)run.Length; state.SawIndexedDraw = true; state.CurrentIndexSnapshot = null; diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs b/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs index 95b6aaf54..ddf8d9291 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.ResolvePool.cs @@ -98,7 +98,9 @@ public sealed partial class CommandStreamTranslation private CapturingSink? _joinSink; private readonly ConcurrentQueue<DeferredDraw> _spareDeferred = new(); - private readonly Dictionary<(ulong Vertex, ulong Pixel), (bool Writes, long Registrations, bool Group)> _drawWrites = new(); + // Concurrent: a host that resolves whole draws where they run (_defersWholeWork) learns on its render thread while the + // stream thread reads it for indexed draw runs (TryDrawIndexedRun). + private readonly ConcurrentDictionary<(ulong Vertex, ulong Pixel), (bool Writes, long Registrations, bool Group)> _drawWrites = new(); private (ulong Vertex, ulong Pixel) _learningKey; // Only a draw whose shaders are known not to write memory resolves ahead of the stream: its @@ -314,7 +316,7 @@ private ResolvedDraw ResolveOnThisThread(DeferredDraw deferred, DrawIndexedArgum { var args = next ?? deferred.IndexedArguments; if (next is null && deferred.IndirectOffsets is { } offsets) - executor.DrawIndexedCore(deferred.SubmitId, deferred.Banks, in args, offsets); + executor.DrawIndexedRun(deferred.SubmitId, deferred.Banks, in args, offsets); else executor.DrawIndexed(deferred.SubmitId, deferred.Banks, in args); } @@ -529,7 +531,7 @@ private void ResolveInFull(Worker worker, DeferredDraw work) if (work.Indexed) { if (work.IndirectOffsets is { } offsets) - worker.Executor.DrawIndexedCore(work.SubmitId, work.Banks, in work.IndexedArguments, offsets); + worker.Executor.DrawIndexedRun(work.SubmitId, work.Banks, in work.IndexedArguments, offsets); else worker.Executor.DrawIndexed(work.SubmitId, work.Banks, in work.IndexedArguments); } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs index aac04b583..57514e4c3 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs @@ -22,17 +22,20 @@ public sealed partial class GpuCommandInterpreter private const uint DrawIndirectArgumentsSize = 16; private const uint DrawIndexedIndirectArgumentsSize = 20; - private int TryDrawIndexedRun(in PacketContext packet, PacketWindow window) + private const int MaxIndexedRunDraws = 32; + + // words: the dwords from this packet on (RunWords); fewer than two packets' worth looks for no run. + private int TryDrawIndexedRun(in PacketContext packet, ReadOnlySpan<uint> words) { - if (!_host.ResolvesIndirectDrawOnGpu || packet.Remaining < 10 || !window.Holds(packet.PacketAddress, 10) || + // A draw that must execute (predication set, an occlusion query open: DrawsMustExecute) takes the packet's own + // handler, which passes MustExecute on; the run's arguments carry none. + if (!_host.ResolvesIndirectDrawOnGpu || DrawsMustExecute || words.Length < 10 || IndexTypeAndSize > 1 || IndexBaseAddress == 0 || DrawIndirectArgumentsBase == 0 || IndexedDrawTrace.Enabled || Rendering.RenderTrace.Enabled || Rendering.ScissorTrace.Instance is { Active: true } || !Rendering.RenderExecutor.RunsPlainVertexProgram(TypedRegisters.Context.ShaderStages) || TypedRegisters.UserConfig.PrimitiveType != (uint)Rendering.GuestPrimitiveType.TriangleList) return 0; - int start = window.IndexOf(packet.PacketAddress); - var words = window.Words.AsSpan(start, (int)Math.Min(window.DwordCount - (uint)start, packet.Remaining)); if (words[5] != packet.Header || (words[4] & ~0x20u) != 2u) return 0; var locations = DrawRegisterLocations.FromPacket(words[2], words[3]); int vertex = VertexUserDataIndex(locations.BaseVertex); @@ -41,7 +44,7 @@ private int TryDrawIndexedRun(in PacketContext packet, PacketWindow window) (DrawRegisterLocations.Names(locations.BaseVertex) && vertex < 0) || (DrawRegisterLocations.Names(locations.StartInstance) && instance < 0)) return 0; - int limit = Math.Min(32, words.Length / 5); + int limit = Math.Min(MaxIndexedRunDraws, words.Length / 5); var indexCount = IndexBufferSize; if (indexCount == 0) { @@ -52,7 +55,7 @@ private int TryDrawIndexedRun(in PacketContext packet, PacketWindow window) } if (indexCount == 0 || (ulong)indexCount * IndexElementSize > 64ul << 20) return 0; - Span<uint> offsets = stackalloc uint[32]; + Span<uint> offsets = stackalloc uint[MaxIndexedRunDraws]; ulong first = DrawIndirectArgumentsBase + words[1]; if (first < DrawIndirectArgumentsBase) return 0; int count = 0; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index dd757fd62..39380ea1f 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -815,9 +815,8 @@ 0 or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or var waitedBefore = SharpEmu.Libs.Diagnostics.PacketHandlerTally.WaitedTicks; using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.CommandPacketHandler)) { - var run = header == PacketHeader.Make(5, PacketOpcode.DrawIndexIndirect) && - SharedPacketWindow(cursorIndex, packetAddress) is { } runWindow - ? TryDrawIndexedRun(in packet, runWindow) : 0; + var run = header == PacketHeader.Make(5, PacketOpcode.DrawIndexIndirect) + ? TryDrawIndexedRun(in packet, RunWords(cursorIndex, in cursor, in packet)) : 0; consumed = run == 0 ? handler(this, in packet, payload) + 1 : (uint)run * 5; if (run > 1) _packetSerial += (uint)run - 1; @@ -1045,12 +1044,38 @@ public bool Covers(ulong packetAddress, long generation) => private const ulong PacketWindowPageBytes = 0x1000; - // The per-depth window (ObtainPacketWindow) that still holds this packet, or null: a packet served from a command - // block or a one-off read has none, and an indexed draw run (TryDrawIndexedRun) then is not looked for. + // The per-depth window (ObtainPacketWindow) that still holds this packet, or null. private PacketWindow? SharedPacketWindow(int depth, ulong packetAddress) => depth < _packetWindowsByDepth.Count && _packetWindowsByDepth[depth] is var window && window.Covers(packetAddress, _packetWindowGeneration) ? window : null; + // The dwords from this packet on in which an indexed draw run (TryDrawIndexedRun) is looked for: those of the per-depth + // window that still holds it, else those of the command block of this depth (a host that hands over command blocks, + // such as the Metal host, has no shared windows), else none, and no run is looked for: a packet behind a ring chunk + // advance, where the guest may still be appending, or one served by a one-off read. + private ReadOnlySpan<uint> RunWords(int depth, in PacketCursor cursor, in PacketContext packet) + { + if (packet.Remaining < 10) + { + return default; + } + + if (SharedPacketWindow(depth, packet.PacketAddress) is { } window) + { + if (!window.Holds(packet.PacketAddress, 10)) + { + return default; + } + + var start = window.IndexOf(packet.PacketAddress); + return window.Words.AsSpan(start, (int)Math.Min(window.DwordCount - (uint)start, packet.Remaining)); + } + + return cursor.FollowedChunkAdvance + ? default + : BlockWords(depth, packet.PacketAddress, packet.Remaining, 10, Math.Min(packet.Remaining, MaxIndexedRunDraws * 5)); + } + private PacketWindow? ObtainPacketWindow(int depth, in PacketCursor cursor, ulong packetAddress) { if (cursor.FollowedChunkAdvance) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs index a73f1c16d..b9cbbffb7 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs @@ -314,12 +314,42 @@ private bool TryReadCpuArguments(RegisterBanks banks, ulong submitId, in DrawInd internal bool CanGroupIndexed(RegisterBanks banks, in DrawIndexedArguments first) => CanDrawIndirectOnGpu(banks, in first) && DrawHasTargets(banks) && !MeshDrawTrace.Active; + // CanGroupIndexed for a thread other than the one this executor resolves on (the stream thread of a host that resolves + // whole draws where they run): the targets are resolved into scratch of the calling thread, not into the executor's + // cached DrawResolution, which the resolving thread owns. + internal bool CanGroupIndexedConcurrently(RegisterBanks banks, in DrawIndexedArguments first) + { + if (!CanDrawIndirectOnGpu(banks, in first) || MeshDrawTrace.Active || ConsumesColorMetadataOperation(banks.Context)) + { + return false; + } + + var colors = _groupColors ??= new ColorTargetResolution[RenderingState.ColorAttachmentCapacity]; + var slots = _groupSlots ??= new uint[RenderingState.ColorAttachmentCapacity]; + return ResolveColorTargets(banks.Context, colors, slots) != 0 || + DepthTargetResolver.Resolve(banks.Context, _host.FormatSupport, HostFatal) is not null; + } + + [ThreadStatic] + private static ColorTargetResolution[]? _groupColors; + + [ThreadStatic] + private static uint[]? _groupSlots; + internal static bool SafeForRun(ShaderProgramInfo? program) => program is { UsesDeviceAddresses: false, CallRecordCallees.Count: 0 } && program.Frontend?.RequiresOrderedImagePreparation != true && !Array.Exists(program.Buffers, static buffer => buffer.Written) && !WritesStorageImage(program) && program.Bindings?.UsesBindlessHeap != true && program.Bindings?.Find(SharpEmu.ShaderCompiler.Resources.DescriptorBindingKind.GlobalDataShare) is null; + // An indexed draw run (GpuCommandInterpreter.TryDrawIndexedRun): one resolve whose record carries the run's indirect + // offsets. It takes the run's MustExecute as DrawIndexed takes a draw's, instead of the one the last draw left. + internal void DrawIndexedRun(ulong submitId, RegisterBanks banks, in DrawIndexedArguments arguments, uint[] offsets) + { + _drawMustExecute = arguments.MustExecute; + DrawIndexedCore(submitId, banks, in arguments, offsets); + } + internal void DrawIndexedCore(ulong submitId, RegisterBanks banks, in DrawIndexedArguments arguments, uint[]? offsets = null, DrawIndexedArguments? originalIndirectIndexedDraw = null) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 0e1b49bf5..9a5b91dc3 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -3324,6 +3324,50 @@ public void DrawIndexed(ulong submitId, in DrawIndexedArguments arguments) _translation!.DrawIndexed(submitId, in arguments); } + /// <summary> + /// Upstream c30081163/cb790c35e indexed draw runs: consecutive DRAW_INDEX_INDIRECT packets under the same registers + /// whose records lie in one page reach the translation as one deferred draw carrying the records' offsets + /// (CommandStreamTranslation.TryDrawIndexedRun), resolved once where it runs; the recorder binds once and issues one + /// indirect draw per record when the host can share the bindings (CanShareIndexedBindings), else it records each + /// offset in full. SHARPEMU_METAL_V2_INDEXED_RUNS=0 leaves every packet to its own handler. + /// </summary> + internal bool IndexedRunsEnabled { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_INDEXED_RUNS") != "0"; + + // Runs the translation took and the draws in them (stream thread); stages of runs whose bindings the host shared or + // refused to share, the run then recorded per offset (render worker, CanShareIndexedBindings). + private long _indexedRunsTaken; + private long _indexedRunDraws; + private long _indexedRunsShared; + private long _indexedRunsRefused; + + /// <summary>Indexed draw runs taken, their draws, and run stages whose bindings were shared or refused, for tests.</summary> + internal (long Taken, long Draws, long Shared, long Refused) IndexedRunCounts => + (Interlocked.Read(ref _indexedRunsTaken), Interlocked.Read(ref _indexedRunDraws), Interlocked.Read(ref _indexedRunsShared), + Interlocked.Read(ref _indexedRunsRefused)); + + // The [METAL-V2][TBDR] line's part; resets the counts. + private string TakeIndexedRunReport() => string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"indexed_runs=(taken={Interlocked.Exchange(ref _indexedRunsTaken, 0)},draws={Interlocked.Exchange(ref _indexedRunDraws, 0)},shared_stages={Interlocked.Exchange(ref _indexedRunsShared, 0)},refused_stages={Interlocked.Exchange(ref _indexedRunsRefused, 0)})"); + + bool ICommandStreamHost.TryDrawIndexedRun(ulong submitId, in DrawIndexedArguments first, ReadOnlySpan<uint> offsets) + { + if (!IndexedRunsEnabled) + { + return false; + } + + using var entryScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail( + SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandDrawEntry); + if (!_translation!.TryDrawIndexedRun(submitId, in first, offsets)) + { + return false; + } + + Interlocked.Increment(ref _indexedRunsTaken); + Interlocked.Add(ref _indexedRunDraws, offsets.Length); + return true; + } + public void DrawAuto(ulong submitId, in DrawAutoArguments arguments) { using var entryScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail( diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs index 085a81f4c..683f543dd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs @@ -210,10 +210,14 @@ public bool TakesIndirectAutoRectangleListArguments(VertexInputInfo vertexInput, private bool TakesLaunchArguments(ulong address, ulong size) => IndirectArgumentsOnGpu && (address & 0x3) == 0 && HasPendingGpuWrite(address, size); + // The record address the last PrepareIndirectDraw was given (CanShareIndexedBindings). + private ulong _preparedIndirectAddress; + public void PrepareIndirectDraw(in PipelineHandle pipeline, ulong argumentsAddress, BufferBinding arguments, bool indexed, uint indexLimit) { _requestedLaunch = null; _tracedIndirectArguments = argumentsAddress; + _preparedIndirectAddress = argumentsAddress; // The draw reads its record: a fill the open pass holds over it lands first. LandDeferredFillsOver(argumentsAddress, 64); var entry = RequirePipelineEntry(in pipeline); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index cb8306aac..301bffc86 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -2106,6 +2106,59 @@ private unsafe bool TryForceIndirectDraw(MetalPipelineEntry entry, uint instance return true; } + /// <summary> + /// Whether every indirect draw of an indexed draw run may take the bindings this stage was prepared and bound with once + /// (RenderRecorder: the run then issues one DrawIndexedIndirect per record). As upstream's host refuses: a storage + /// image, a host-movie plane, or a texture that is one of the draw's color or depth targets (the earlier draws of the + /// run write what the later ones would sample). Refused too when a fill held for the pass end lies on the records' + /// page: PrepareIndirectDraw lands such fills over the first record only, and each record of a run lies in its page + /// (GpuCommandInterpreter.TryDrawIndexedRun). A refused run records each offset in full. + /// </summary> + bool IRenderHost.CanShareIndexedBindings(IPreparedBindings stage, ReadOnlySpan<ColorTargetState> colors, in DepthAttachmentState depth) + { + if (!SharesIndexedBindings((MetalStageBindings)stage, colors, in depth)) + { + Interlocked.Increment(ref _indexedRunsRefused); + return false; + } + + Interlocked.Increment(ref _indexedRunsShared); + return true; + } + + private bool SharesIndexedBindings(MetalStageBindings bindings, ReadOnlySpan<ColorTargetState> colors, in DepthAttachmentState depth) + { + if (bindings.MovieLuma >= 0 || bindings.MovieChroma >= 0 || + DeferredFillsOver(_preparedIndirectAddress & ~0xFFFUL, 0x1000)) + { + return false; + } + + for (var index = 0; index < bindings.ImageCount; index++) + { + if (bindings.IsStorage[index]) + { + return false; + } + + var image = bindings.Images[index]; + if (depth.HasTarget && image == depth.Image) + { + return false; + } + + foreach (ref readonly var color in colors) + { + if (image == color.Image) + { + return false; + } + } + } + + return true; + } + void IRenderHost.DrawIndexedIndirect(BufferBinding arguments) { using var overlapOp = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Op(dispatch: false); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index d029bd096..96fb21dee 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -3184,7 +3184,8 @@ public void ReportCounters() $"transfers=[{TakeTransferCauses()}] {TakePreludeText()}" + (CopiesShareCompute ? $" copies_in_encoder={_copiesInEncoder}" : "") + $" alias_writes_discarded={_imageCache.TakeAliasWritesDiscarded()} " + - SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport() + " " + TakeReplayHostReport()); + SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport() + " " + TakeReplayHostReport() + " " + + TakeIndexedRunReport()); if (_guard is not null) { Console.Error.WriteLine($"[METAL-V2][GUARD] {_guard.Report()}"); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/IndexedRunSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/IndexedRunSceneTests.cs new file mode 100644 index 000000000..b4366061a --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/IndexedRunSceneTests.cs @@ -0,0 +1,112 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// <summary> +/// Indexed draw runs on the Metal host (upstream c30081163/cb790c35e): consecutive DRAW_INDEX_INDIRECT packets under the +/// same registers whose records lie in one page reach the translation as one deferred draw carrying the records' offsets +/// (MetalRenderHost.TryDrawIndexedRun), resolved once; the recorder binds once and issues one indirect draw per record +/// when the host shares the bindings (CanShareIndexedBindings). The picture is the one the packets draw one by one. +/// </summary> +public sealed class IndexedRunSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Width = 16; + private const int Stripes = 4; + + // MRT0 = the four user-data words s[0:3] as floats. + private static readonly uint[] ConstantColor = + [ + 0x7E040200, // v_mov_b32_e32 v2, s0 + 0x7E060201, // v_mov_b32_e32 v3, s1 + 0x7E080202, // v_mov_b32_e32 v4, s2 + 0x7E0A0203, // v_mov_b32_e32 v5, s3 + 0xF800180F, 0x05040302, // exp mrt0 v2, v3, v4, v5 done vm + 0xBF810000, // s_endpgm + ]; + + private static readonly uint[] Green = [SceneState.F(0), SceneState.F(1), SceneState.F(0), SceneState.F(1)]; + + // Draws stripes 0, 1 and 3 of four vertical stripes, each through its own indexed indirect record, after one + // learning draw of stripe 0 in a submission of its own (the translation groups only programs it has seen resolve + // without stores). Stripe 2 is left clear. + private byte[] DrawRun(bool runs, out (long Taken, long Draws, long Shared, long Refused) counts) + { + using var rig = CreateRig()!; + rig.Host.IndexedRunsEnabled = runs; + var vertices = new List<SceneVertex>(); + var indices = new List<ushort>(); + for (var stripe = 0; stripe < Stripes; stripe++) + { + var left = -1f + (2f * stripe / Stripes); + var right = left + (2f / Stripes); + var first = (ushort)vertices.Count; + vertices.AddRange( + [ + SceneVertex.At(left, -1, 0.5f, 0, 0, 0), SceneVertex.At(right, -1, 0.5f, 0, 0, 0), + SceneVertex.At(left, 1, 0.5f, 0, 0, 0), SceneVertex.At(right, 1, 0.5f, 0, 0, 0), + ]); + indices.AddRange([first, (ushort)(first + 1), (ushort)(first + 2), (ushort)(first + 2), (ushort)(first + 1), (ushort)(first + 3)]); + } + + var mesh = rig.UploadMesh(vertices); + var indexAddress = rig.Memory.Upload<ushort>(indices.ToArray()); + // Records (indexCount, instanceCount, firstIndex, vertexOffset, firstInstance), 20 bytes apart in one page. + var arguments = rig.Memory.Allocate(0x1000, 0x1000); + rig.Memory.Write<uint>(arguments, [6, 1, 0, 0, 0, 6, 1, 6, 0, 0, 6, 1, 18, 0, 0]); + var target = rig.ColorTarget(Width, Width, 16); + var vertex = rig.Program(ScenePrograms.FetchVertex); + var pixel = rig.Program(ConstantColor); + + ScenePm4 Begin() + { + var pm4 = new ScenePm4(); + new SceneState(Width, Width).ColorTarget(0, target, Width, Width, format: 14, numberType: 7) + .VertexShader(vertex, mesh).PixelShader(pixel, Green).Emit(pm4); + pm4.NumInstances(1); + pm4.Raw(ScenePm4.Header(4, ScenePm4.OpSetBase), 1u, (uint)arguments, (uint)(arguments >> 32)); + pm4.IndexType(0).Packet(ScenePm4.OpIndexBase, (uint)indexAddress, (uint)(indexAddress >> 32)) + .Packet(ScenePm4.OpIndexBufferSize, (uint)indices.Count); + return pm4; + } + + rig.Submit(Begin().Packet(ScenePm4.OpDrawIndexIndirect, 0u, 0u, 0u, 2u)); + var run = Begin(); + foreach (var offset in new uint[] { 0, 20, 40 }) + { + run.Packet(ScenePm4.OpDrawIndexIndirect, offset, 0u, 0u, 2u); + } + + rig.Submit(run); + counts = rig.Host.IndexedRunCounts; + Output.WriteLine($"runs={runs}: taken={counts.Taken} draws={counts.Draws} shared={counts.Shared} refused={counts.Refused}"); + Assert.Empty(rig.Fatals); + return rig.ReadImage(target, Width, Width, 16); + } + + [Fact] + public void ARunOfIndexedIndirectDrawsSharesItsBindingsAndDrawsEachRecord() + { + if (CreateRig() is not { } probe) return; + probe.Dispose(); + var with = DrawRun(runs: true, out var counts); + var without = DrawRun(runs: false, out var none); + Assert.Equal(1, counts.Taken); + Assert.Equal(3, counts.Draws); + Assert.True(counts.Shared >= 1, "the run's bindings were not shared"); + Assert.Equal(0, counts.Refused); + Assert.Equal(0, none.Taken); + Assert.Equal(without, with); + var pixels = System.Runtime.InteropServices.MemoryMarshal.Cast<byte, float>(with); + for (var stripe = 0; stripe < Stripes; stripe++) + { + var x = (stripe * (int)Width / Stripes) + 1; + var green = pixels[(int)(((8 * Width) + (uint)x) * 4) + 1]; + Assert.Equal(stripe == 2 ? 0f : 1f, green); + } + } +} From 71873ef57c515637ef61014078706a69086d0836 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:41:29 +0000 Subject: [PATCH 58/64] [Audio] Open the DualSense's own audio on macOS: the USB 4-channel device, Bluetooth Opus reports Port of upstream cb790c35e (SDL controller audio stream). USB: exactly one 4-channel CoreAudio device named DualSense/Wireless Controller, opened through the HAL output unit with raw channel order (speaker pair, then the two actuators). Bluetooth: IOHID output report 0x39 with 64 actuator frames at 3 kHz and two Concentus Opus packets for the speaker. The speaker is routed while the stream is open and restored on close. The stream drops its oldest audio past the cap and does not report the guest clock. No pad, or more than one, returns null. SHARPEMU_DUALSENSE_AUDIO=0 turns it off. Report framing, CRC, Opus and channel mapping are unit-tested; the hardware paths are unverified. --- .../Audio/DualSense/MacCoreAudioDevices.cs | 143 +++++ .../Audio/DualSense/MacCoreFoundation.cs | 104 ++++ .../Audio/DualSense/MacDualSenseBluetooth.cs | 561 ++++++++++++++++++ .../Audio/DualSense/MacDualSenseHid.cs | 237 ++++++++ .../Audio/DualSense/MacDualSenseReports.cs | 159 +++++ .../Audio/MacAudioRingBuffer.cs | 39 +- .../Audio/MacCoreAudioInterop.cs | 39 ++ .../Audio/MacCoreAudioOutput.cs | 114 ++++ .../Audio/MacCoreAudioStream.cs | 67 ++- .../SharpEmu.Host.MacOS.csproj | 8 +- .../Audio/MacDualSenseTests.cs | 318 ++++++++++ 11 files changed, 1778 insertions(+), 11 deletions(-) create mode 100644 src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreAudioDevices.cs create mode 100644 src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreFoundation.cs create mode 100644 src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseBluetooth.cs create mode 100644 src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseHid.cs create mode 100644 src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseReports.cs create mode 100644 tests/SharpEmu.Libs.Tests/Audio/MacDualSenseTests.cs diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreAudioDevices.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreAudioDevices.cs new file mode 100644 index 000000000..d1d6c3285 --- /dev/null +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreAudioDevices.cs @@ -0,0 +1,143 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.Versioning; +using static SharpEmu.Host.MacOS.MacCoreAudioInterop; + +namespace SharpEmu.Host.MacOS; + +/// <summary>One CoreAudio device with its name and output channel count.</summary> +internal readonly record struct MacAudioDeviceInfo(uint Id, string Name, int OutputChannels); + +/// <summary>The CoreAudio device list, for finding the DualSense's own output device.</summary> +[SupportedOSPlatform("macos")] +internal static unsafe class MacCoreAudioDevices +{ + /// <summary>The channel count of a wired DualSense's output: speaker pair, then the two actuators.</summary> + internal const int ControllerChannels = 4; + + /// <summary>Every device that has output channels.</summary> + public static List<MacAudioDeviceInfo> ListOutputDevices() + { + var devices = new List<MacAudioDeviceInfo>(); + var address = new AudioObjectPropertyAddress + { + Selector = AudioHardwarePropertyDevices, + Scope = AudioObjectScopeGlobal, + Element = AudioObjectElementMain, + }; + uint size = 0; + if (AudioObjectGetPropertyDataSize(AudioObjectSystemObject, &address, 0, null, &size) != 0 || size == 0) + { + return devices; + } + + var ids = new uint[size / sizeof(uint)]; + fixed (uint* data = ids) + { + if (AudioObjectGetPropertyData(AudioObjectSystemObject, &address, 0, null, &size, data) != 0) + { + return devices; + } + } + + foreach (var id in ids.AsSpan(0, (int)(size / sizeof(uint)))) + { + var channels = OutputChannels(id); + if (channels > 0) + { + devices.Add(new MacAudioDeviceInfo(id, Name(id) ?? string.Empty, channels)); + } + } + + return devices; + } + + /// <summary> + /// The controller's output device: exactly one device with four output channels named for a DualSense + /// ("DualSense", or "Wireless Controller", the name the pad reports over USB). CoreAudio ties no device to a + /// gamepad, so two candidates give none rather than a guess, as upstream's SDL host does. + /// </summary> + internal static bool TrySelectControllerDevice(IReadOnlyList<MacAudioDeviceInfo> devices, out MacAudioDeviceInfo device) + { + device = default; + var found = 0; + foreach (var candidate in devices) + { + if (candidate.OutputChannels == ControllerChannels && + (candidate.Name.Contains("DualSense", StringComparison.OrdinalIgnoreCase) || + candidate.Name.Contains("Wireless Controller", StringComparison.OrdinalIgnoreCase))) + { + device = candidate; + found++; + } + } + + return found == 1; + } + + private static string? Name(uint device) + { + var address = new AudioObjectPropertyAddress + { + Selector = AudioObjectPropertyName, + Scope = AudioObjectScopeGlobal, + Element = AudioObjectElementMain, + }; + nint name = 0; + var size = (uint)sizeof(nint); + if (AudioObjectGetPropertyData(device, &address, 0, null, &size, &name) != 0 || name == 0) + { + return null; + } + + try + { + return MacCoreFoundation.ReadString(name); + } + finally + { + MacCoreFoundation.CFRelease(name); + } + } + + private static int OutputChannels(uint device) + { + var address = new AudioObjectPropertyAddress + { + Selector = AudioDevicePropertyStreamConfiguration, + Scope = AudioObjectScopeOutput, + Element = AudioObjectElementMain, + }; + uint size = 0; + if (AudioObjectGetPropertyDataSize(device, &address, 0, null, &size) != 0 || + size < sizeof(uint)) + { + return 0; + } + + var blob = new byte[size]; + fixed (byte* data = blob) + { + if (AudioObjectGetPropertyData(device, &address, 0, null, &size, data) != 0) + { + return 0; + } + + var list = (AudioBufferList*)data; + var buffers = &list->Buffers; + var channels = 0; + for (var index = 0u; index < list->NumberBuffers; index++) + { + if ((byte*)(buffers + index + 1) > data + size) + { + break; + } + + channels += (int)buffers[index].NumberChannels; + } + + return channels; + } + } +} diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreFoundation.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreFoundation.cs new file mode 100644 index 000000000..f3595aae4 --- /dev/null +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacCoreFoundation.cs @@ -0,0 +1,104 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Text; + +namespace SharpEmu.Host.MacOS; + +/// <summary>The CoreFoundation calls the controller audio needs to read CoreAudio and IOKit properties.</summary> +[SupportedOSPlatform("macos")] +internal static unsafe class MacCoreFoundation +{ + private const string Library = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; + private const uint StringEncodingUtf8 = 0x0800_0100; + private const int NumberSInt32Type = 3; + + [DllImport(Library)] + internal static extern void CFRelease(nint value); + + [DllImport(Library)] + internal static extern nint CFRetain(nint value); + + [DllImport(Library)] + private static extern nuint CFGetTypeID(nint value); + + [DllImport(Library)] + private static extern nuint CFStringGetTypeID(); + + [DllImport(Library)] + private static extern nuint CFNumberGetTypeID(); + + [DllImport(Library)] + private static extern nint CFStringGetLength(nint value); + + [DllImport(Library)] + private static extern nint CFStringGetMaximumSizeForEncoding(nint length, uint encoding); + + [DllImport(Library)] + [return: MarshalAs(UnmanagedType.I1)] + private static extern bool CFStringGetCString(nint value, byte* buffer, nint bufferSize, uint encoding); + + [DllImport(Library)] + private static extern nint CFStringCreateWithCString(nint allocator, byte* text, uint encoding); + + [DllImport(Library)] + [return: MarshalAs(UnmanagedType.I1)] + private static extern bool CFNumberGetValue(nint number, int type, int* value); + + [DllImport(Library)] + internal static extern nint CFSetGetCount(nint set); + + [DllImport(Library)] + internal static extern void CFSetGetValues(nint set, nint* values); + + /// <summary>A CFString's text, or null for anything that is not a CFString.</summary> + internal static string? ReadString(nint value) + { + if (value == 0 || CFGetTypeID(value) != CFStringGetTypeID()) + { + return null; + } + + var size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), StringEncodingUtf8) + 1; + if (size <= 0 || size > 4096) + { + return null; + } + + var buffer = stackalloc byte[(int)size]; + return CFStringGetCString(value, buffer, size, StringEncodingUtf8) + ? Marshal.PtrToStringUTF8((nint)buffer) + : null; + } + + /// <summary>A CFNumber's value as a 32-bit integer.</summary> + internal static bool TryReadInt32(nint value, out int result) + { + result = 0; + if (value == 0 || CFGetTypeID(value) != CFNumberGetTypeID()) + { + return false; + } + + int number; + if (!CFNumberGetValue(value, NumberSInt32Type, &number)) + { + return false; + } + + result = number; + return true; + } + + /// <summary>A new CFString (released by the caller).</summary> + internal static nint CreateString(string text) + { + var bytes = Encoding.UTF8.GetBytes(text + "\0"); + fixed (byte* data = bytes) + { + return CFStringCreateWithCString(0, data, StringEncodingUtf8); + } + } +} diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseBluetooth.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseBluetooth.cs new file mode 100644 index 000000000..955c1aaf3 --- /dev/null +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseBluetooth.cs @@ -0,0 +1,561 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using Concentus; +using Concentus.Enums; +using SharpEmu.HLE.Host; + +namespace SharpEmu.Host.MacOS; + +/// <summary> +/// The controller stream of a DualSense on Bluetooth, which lists no audio device: the actuators' samples (3 kHz, a +/// signed byte each) and the speaker's audio (two 200-byte Opus packets) go in output report 0x39, one report every +/// 64 actuator frames (21.3 ms), as upstream's SdlDualSenseBluetooth sends them. One sender thread serves every open +/// stream: the AudioOut and AudioOut2 controller streams mix into the same report. +/// </summary> +[SupportedOSPlatform("macos")] +internal sealed class MacDualSenseBluetooth +{ + internal const int InputChannels = 4; + internal const int HapticRate = 3000; + internal const int SpeakerRate = 45000; + internal const int OpusSampleRate = 48000; + internal const int OpusFrames = 480; + internal const int SpeakerFrames = MacDualSenseReports.OpusPackets * OpusFrames; + private const int ReopenDelayMilliseconds = 1000; + private static readonly long PeriodTicks = Stopwatch.Frequency * MacDualSenseReports.HapticFrames / HapticRate; + + private static readonly object RegistryGate = new(); + private static MacDualSenseBluetooth? _shared; + + private readonly object _gate = new(); + private readonly object _deviceGate = new(); + private readonly List<Client> _clients = []; + private readonly AutoResetEvent _signal = new(false); + private readonly Thread _sender; + private readonly MacDualSenseOpus _opus = new(); + private MacDualSenseHid? _device; + private bool _stopping; + private byte _sequence; + private byte _counter; + private long _reopenAt; + private bool _writeFailureLogged; + + private MacDualSenseBluetooth(MacDualSenseHid device) + { + _device = device; + _sender = new Thread(Run) + { + IsBackground = true, + Name = "DualSense Bluetooth audio", + Priority = ThreadPriority.AboveNormal, + }; + _sender.Start(); + } + + /// <summary>A stream on the one DualSense connected over Bluetooth, or null when there is none (or several).</summary> + public static IHostAudioStream? TryOpen(uint sampleRate, int maxQueuedBytes, bool speaker) + { + lock (RegistryGate) + { + var link = _shared; + if (link is null) + { + var device = MacDualSenseHid.TryOpenSingle(MacDualSenseTransport.Bluetooth); + if (device is null) + { + return null; + } + + link = new MacDualSenseBluetooth(device); + } + + _shared = link; + try + { + return link.Attach(sampleRate, maxQueuedBytes, speaker); + } + catch + { + if (link.ClientCount == 0) + { + link.Shutdown(); + } + + throw; + } + } + } + + /// <summary>The effects report (the speaker routing) on the link's device, serialized with the audio reports.</summary> + public static bool TrySendEffects(ReadOnlySpan<byte> effects) + { + MacDualSenseBluetooth? link; + lock (RegistryGate) + { + link = _shared; + } + + if (link is null) + { + return false; + } + + lock (link._deviceGate) + { + return link._device?.TrySendEffects(effects) == true; + } + } + + private int ClientCount + { + get + { + lock (_gate) + { + return _clients.Count; + } + } + } + + private Client Attach(uint sampleRate, int maxQueuedBytes, bool speaker) + { + var queueMilliseconds = maxQueuedBytes * 1000.0 / ((double)sampleRate * InputChannels * sizeof(float)); + var client = new Client(this, sampleRate, queueMilliseconds, speaker); + lock (_gate) + { + _clients.Add(client); + } + + return client; + } + + private void Detach(Client client) + { + lock (RegistryGate) + { + lock (_gate) + { + _clients.Remove(client); + if (_clients.Count > 0) + { + return; + } + } + + Shutdown(); + } + } + + // Caller holds RegistryGate. + private void Shutdown() + { + lock (_gate) + { + _stopping = true; + } + + if (ReferenceEquals(_shared, this)) + { + _shared = null; + } + + _signal.Set(); + _sender.Join(); + lock (_deviceGate) + { + _device?.Dispose(); + _device = null; + } + } + + private void Run() + { + var report = new byte[MacDualSenseReports.BluetoothAudioReportLength]; + var haptics = new float[MacDualSenseReports.HapticFrames * 2]; + var speaker = new float[SpeakerFrames * 2]; + var packets = new byte[MacDualSenseReports.OpusPackets * MacDualSenseReports.OpusPacketBytes]; + var next = 0L; + while (true) + { + bool active; + bool speakerOpen; + lock (_gate) + { + if (_stopping) + { + return; + } + + Array.Clear(haptics); + Array.Clear(speaker); + active = false; + speakerOpen = false; + foreach (var client in _clients) + { + active |= client.Haptics.MixInto(haptics); + if (client.Speaker is { } lane) + { + speakerOpen = true; + active |= lane.MixInto(speaker); + } + } + } + + if (!active) + { + next = 0; + _signal.WaitOne(250); + continue; + } + + var encoded = speakerOpen && _opus.TryEncode(speaker, packets); + _counter += 2; + MacDualSenseReports.BuildBluetoothAudioReport( + report, + _sequence, + _counter, + haptics, + encoded ? packets : ReadOnlySpan<byte>.Empty); + _sequence = (byte)((_sequence + 1) & 0x0F); + Send(report); + + var now = Stopwatch.GetTimestamp(); + next = (next == 0 ? now : next) + PeriodTicks; + if (now - next > PeriodTicks) + { + next = now; + } + + var wait = next - Stopwatch.GetTimestamp(); + if (wait > 0) + { + Thread.Sleep(TimeSpan.FromTicks(wait * TimeSpan.TicksPerSecond / Stopwatch.Frequency)); + } + } + } + + private void Send(byte[] report) + { + lock (_deviceGate) + { + if (_device is null) + { + if (Stopwatch.GetTimestamp() < _reopenAt) + { + return; + } + + _device = MacDualSenseHid.TryOpenSingle(MacDualSenseTransport.Bluetooth); + if (_device is null) + { + _reopenAt = Stopwatch.GetTimestamp() + Stopwatch.Frequency * ReopenDelayMilliseconds / 1000; + return; + } + } + + if (_device.TrySendOutputReport(report, out var status)) + { + return; + } + + if (!_writeFailureLogged) + { + _writeFailureLogged = true; + Console.Error.WriteLine( + $"[LOADER][WARN] DualSense Bluetooth audio report refused: IOReturn 0x{status:X8}"); + } + + _device.Dispose(); + _device = null; + _reopenAt = Stopwatch.GetTimestamp() + Stopwatch.Frequency * ReopenDelayMilliseconds / 1000; + } + } + + /// <summary> + /// One controller stream: four float channels per frame, the speaker pair first and the actuator pair last, as on + /// a wired DualSense's audio device. + /// </summary> + internal sealed class Client : IHostAudioStream + { + private readonly MacDualSenseBluetooth? _link; + private int _disposed; + + internal Client(MacDualSenseBluetooth? link, uint sampleRate, double queueMilliseconds, bool speaker) + { + _link = link; + Haptics = new MacDualSenseLane(sampleRate, HapticRate, MacDualSenseReports.HapticFrames, queueMilliseconds); + Speaker = speaker ? new MacDualSenseLane(sampleRate, SpeakerRate, SpeakerFrames, queueMilliseconds) : null; + } + + public MacDualSenseLane Haptics { get; } + + public MacDualSenseLane? Speaker { get; } + + public int QueuedMilliseconds => Volatile.Read(ref _disposed) != 0 ? -1 : Haptics.QueuedMilliseconds; + + public bool Submit(ReadOnlySpan<byte> pcm) + { + if (Volatile.Read(ref _disposed) != 0) + { + return false; + } + + var samples = MemoryMarshal.Cast<byte, float>(pcm); + var frames = samples.Length / InputChannels; + if (frames == 0) + { + return true; + } + + var pair = ArrayPool<float>.Shared.Rent(frames * 2); + try + { + var stereo = pair.AsSpan(0, frames * 2); + if (Speaker is not null) + { + CopyPair(samples, stereo, 0); + Speaker.Put(stereo); + } + + CopyPair(samples, stereo, 2); + Haptics.Put(stereo); + } + finally + { + ArrayPool<float>.Shared.Return(pair); + } + + _link?._signal.Set(); + return true; + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + _link?.Detach(this); + } + } + + /// <summary>One pair of the four channels, starting at <paramref name="firstChannel"/>, as stereo.</summary> + internal static void CopyPair(ReadOnlySpan<float> samples, Span<float> stereo, int firstChannel) + { + for (var frame = 0; frame < stereo.Length / 2; frame++) + { + stereo[2 * frame] = samples[(frame * InputChannels) + firstChannel]; + stereo[(2 * frame) + 1] = samples[(frame * InputChannels) + firstChannel + 1]; + } + } + } +} + +/// <summary> +/// The DualSense speaker's Opus encoder: 48 kHz stereo, restricted low delay, constant 200-byte packets of 480 +/// frames, complexity 0, as upstream configures it. Concentus is fully managed. +/// </summary> +internal sealed class MacDualSenseOpus +{ + private IOpusEncoder? _encoder; + private bool _failureLogged; + + /// <summary> + /// Encodes <see cref="MacDualSenseBluetooth.SpeakerFrames"/> stereo frames into two packets of exactly + /// <see cref="MacDualSenseReports.OpusPacketBytes"/>; false (and a cleared destination) when either is not. + /// </summary> + public bool TryEncode(float[] speaker, Span<byte> destination) + { + for (var index = 0; index < speaker.Length; index++) + { + speaker[index] = float.IsFinite(speaker[index]) ? Math.Clamp(speaker[index], -1f, 1f) : 0f; + } + + try + { + if (_encoder is null) + { + OpusCodecFactory.AttemptToUseNativeLibrary = false; + var encoder = OpusCodecFactory.CreateEncoder( + MacDualSenseBluetooth.OpusSampleRate, + 2, + OpusApplication.OPUS_APPLICATION_RESTRICTED_LOWDELAY); + encoder.Bitrate = MacDualSenseReports.OpusPacketBytes * 8 * MacDualSenseBluetooth.OpusSampleRate / + MacDualSenseBluetooth.OpusFrames; + encoder.UseVBR = false; + encoder.Complexity = 0; + _encoder = encoder; + } + + const int frames = MacDualSenseBluetooth.OpusFrames; + const int bytes = MacDualSenseReports.OpusPacketBytes; + for (var packet = 0; packet < MacDualSenseReports.OpusPackets; packet++) + { + var encoded = _encoder.Encode( + speaker.AsSpan(packet * frames * 2, frames * 2), + frames, + destination.Slice(packet * bytes, bytes), + bytes); + if (encoded != bytes) + { + destination.Clear(); + return false; + } + } + + return true; + } + catch (Exception exception) + { + destination.Clear(); + if (!_failureLogged) + { + _failureLogged = true; + Console.Error.WriteLine($"[LOADER][WARN] DualSense Bluetooth speaker encoding failed: {exception.Message}"); + } + + return false; + } + } +} + +/// <summary> +/// One pair of the controller stream at the rate its report wants: resampled from the guest's rate, held up to the +/// stream's queue limit (the oldest audio goes past it, as the stream never blocks the guest), and handed out one +/// report at a time once 1.5 reports are queued, so a report is not sent half empty at the start. +/// </summary> +internal sealed class MacDualSenseLane +{ + private readonly object _gate = new(); + private readonly int _outputRate; + private readonly int _primeFrames; + private readonly int _capacityFrames; + private readonly double _step; + private readonly float[] _queue; + private int _head; + private int _count; + private bool _primed; + + // Area-averaging resampler state: the input still owed to the output frame being built. + private double _need; + private double _left; + private double _right; + + public MacDualSenseLane(uint inputRate, int outputRate, int reportFrames, double queueMilliseconds) + { + if (inputRate == 0 || outputRate <= 0 || reportFrames <= 0) + { + throw new ArgumentOutOfRangeException(nameof(inputRate)); + } + + _outputRate = outputRate; + _primeFrames = reportFrames * 3 / 2; + _capacityFrames = Math.Max(2 * reportFrames, (int)(outputRate * queueMilliseconds / 1000)); + _queue = new float[_capacityFrames * 2]; + _step = (double)inputRate / outputRate; + _need = _step; + } + + public int QueuedFrames + { + get + { + lock (_gate) + { + return _count; + } + } + } + + public int QueuedMilliseconds => (int)(QueuedFrames * 1000L / _outputRate); + + /// <summary> + /// Appends guest-rate stereo audio. Each output frame is the mean of the input over its own interval, so the + /// 16:1 step down to the actuators' 3 kHz filters what they cannot play instead of folding it back. + /// </summary> + public void Put(ReadOnlySpan<float> stereo) + { + lock (_gate) + { + for (var frame = 0; frame < stereo.Length / 2; frame++) + { + double left = stereo[2 * frame]; + double right = stereo[(2 * frame) + 1]; + if (!double.IsFinite(left)) + { + left = 0; + } + + if (!double.IsFinite(right)) + { + right = 0; + } + + var available = 1.0; + while (available > 1e-12) + { + var take = Math.Min(available, _need); + _left += left * take; + _right += right * take; + available -= take; + _need -= take; + if (_need <= 1e-12) + { + Enqueue((float)(_left / _step), (float)(_right / _step)); + _left = 0; + _right = 0; + _need = _step; + } + } + } + } + } + + /// <summary>Adds the next report's frames into <paramref name="destination"/>; false when it had none to give.</summary> + public bool MixInto(Span<float> destination) + { + lock (_gate) + { + if (!_primed && _count < _primeFrames) + { + return false; + } + + var wanted = destination.Length / 2; + var frames = Math.Min(wanted, _count); + _primed = frames == wanted; + if (frames == 0) + { + return false; + } + + for (var frame = 0; frame < frames; frame++) + { + destination[2 * frame] += _queue[2 * _head]; + destination[(2 * frame) + 1] += _queue[(2 * _head) + 1]; + _head = (_head + 1) % _capacityFrames; + } + + _count -= frames; + return true; + } + } + + // Caller holds _gate. A full queue drops its oldest frame. + private void Enqueue(float left, float right) + { + if (_count == _capacityFrames) + { + _head = (_head + 1) % _capacityFrames; + _count--; + } + + var tail = (_head + _count) % _capacityFrames; + _queue[2 * tail] = left; + _queue[(2 * tail) + 1] = right; + _count++; + } +} diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseHid.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseHid.cs new file mode 100644 index 000000000..2f727be13 --- /dev/null +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseHid.cs @@ -0,0 +1,237 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace SharpEmu.Host.MacOS; + +internal enum MacDualSenseTransport +{ + Usb, + Bluetooth, +} + +/// <summary> +/// A DualSense's HID interface through IOKit, for the output reports GameController has no API for: the audio routing +/// in the effects report and, over Bluetooth, the audio report that carries the actuator samples and the speaker's +/// Opus packets. The device is opened shared (GameController keeps reading it), and only one pad per transport is +/// used, since nothing ties a HID device to the CoreAudio device or GameController pad of the same controller. +/// </summary> +[SupportedOSPlatform("macos")] +internal sealed unsafe class MacDualSenseHid : IDisposable +{ + internal const int SonyVendorId = 0x054C; + internal const int DualSenseProductId = 0x0CE6; + internal const int DualSenseEdgeProductId = 0x0DF2; + + private const string IoKit = "/System/Library/Frameworks/IOKit.framework/IOKit"; + private const uint ReportTypeOutput = 1; + private const uint OptionsNone = 0; + + private nint _manager; + private nint _device; + + private MacDualSenseHid(nint manager, nint device, MacDualSenseTransport transport) + { + _manager = manager; + _device = device; + Transport = transport; + } + + public MacDualSenseTransport Transport { get; } + + /// <summary>How many DualSense pads each transport has, and the one to open when a transport has exactly one.</summary> + internal readonly record struct Candidate(int ProductId, string? Transport, int UsagePage, int Usage); + + /// <summary> + /// The transport a HID device of a DualSense is on, or null when it is not a DualSense gamepad interface. Pure: + /// unit tested. + /// </summary> + internal static MacDualSenseTransport? Classify(int vendorId, in Candidate candidate) + { + if (vendorId != SonyVendorId || + candidate.ProductId is not (DualSenseProductId or DualSenseEdgeProductId) || + (candidate.UsagePage != 0 && (candidate.UsagePage != 1 || candidate.Usage != 5))) + { + return null; + } + + if (string.Equals(candidate.Transport, "USB", StringComparison.OrdinalIgnoreCase)) + { + return MacDualSenseTransport.Usb; + } + + return candidate.Transport is not null && + candidate.Transport.StartsWith("Bluetooth", StringComparison.OrdinalIgnoreCase) + ? MacDualSenseTransport.Bluetooth + : null; + } + + /// <summary>The one DualSense on <paramref name="transport"/>, opened; null when there is none or more than one.</summary> + public static MacDualSenseHid? TryOpenSingle(MacDualSenseTransport transport) + { + var manager = IOHIDManagerCreate(0, OptionsNone); + if (manager == 0) + { + return null; + } + + nint chosen = 0; + var found = 0; + var set = (nint)0; + try + { + // No matching dictionary: every HID device, filtered below by its properties. + IOHIDManagerSetDeviceMatching(manager, 0); + set = IOHIDManagerCopyDevices(manager); + var count = set == 0 ? 0 : (int)MacCoreFoundation.CFSetGetCount(set); + if (count > 0) + { + var devices = new nint[count]; + fixed (nint* values = devices) + { + MacCoreFoundation.CFSetGetValues(set, values); + } + + foreach (var device in devices) + { + if (Classify(IntProperty(device, "VendorID"), ReadCandidate(device)) == transport) + { + chosen = device; + found++; + } + } + } + + if (found != 1) + { + return null; + } + + MacCoreFoundation.CFRetain(chosen); + var status = IOHIDDeviceOpen(chosen, OptionsNone); + if (status != 0) + { + MacCoreFoundation.CFRelease(chosen); + Console.Error.WriteLine( + $"[LOADER][WARN] DualSense ({transport}) HID interface refused to open: IOReturn 0x{status:X8}"); + return null; + } + + var pad = new MacDualSenseHid(manager, chosen, transport); + manager = 0; + return pad; + } + finally + { + if (set != 0) + { + MacCoreFoundation.CFRelease(set); + } + + if (manager != 0) + { + MacCoreFoundation.CFRelease(manager); + } + } + } + + /// <summary>Sends one output report; its first byte is the report ID, as on the wire.</summary> + public bool TrySendOutputReport(ReadOnlySpan<byte> report, out int status) + { + status = -1; + if (_device == 0 || report.IsEmpty) + { + return false; + } + + fixed (byte* data = report) + { + status = IOHIDDeviceSetReport(_device, ReportTypeOutput, report[0], data, report.Length); + } + + return status == 0; + } + + /// <summary> + /// The pad's effects report (the same 47-byte state SDL_SendGamepadEffect takes), wrapped for this transport. + /// </summary> + public bool TrySendEffects(ReadOnlySpan<byte> effects) + { + Span<byte> report = stackalloc byte[MacDualSenseReports.BluetoothEffectsReportLength]; + var length = Transport == MacDualSenseTransport.Usb + ? MacDualSenseReports.BuildUsbEffectsReport(effects, report) + : MacDualSenseReports.BuildBluetoothEffectsReport(effects, report); + return TrySendOutputReport(report[..length], out _); + } + + public void Dispose() + { + if (_device != 0) + { + _ = IOHIDDeviceClose(_device, OptionsNone); + MacCoreFoundation.CFRelease(_device); + _device = 0; + } + + if (_manager != 0) + { + MacCoreFoundation.CFRelease(_manager); + _manager = 0; + } + } + + private static Candidate ReadCandidate(nint device) => new( + IntProperty(device, "ProductID"), + StringProperty(device, "Transport"), + IntProperty(device, "PrimaryUsagePage"), + IntProperty(device, "PrimaryUsage")); + + private static int IntProperty(nint device, string key) + { + var name = MacCoreFoundation.CreateString(key); + try + { + return MacCoreFoundation.TryReadInt32(IOHIDDeviceGetProperty(device, name), out var value) ? value : 0; + } + finally + { + MacCoreFoundation.CFRelease(name); + } + } + + private static string? StringProperty(nint device, string key) + { + var name = MacCoreFoundation.CreateString(key); + try + { + return MacCoreFoundation.ReadString(IOHIDDeviceGetProperty(device, name)); + } + finally + { + MacCoreFoundation.CFRelease(name); + } + } + + [DllImport(IoKit)] + private static extern nint IOHIDManagerCreate(nint allocator, uint options); + + [DllImport(IoKit)] + private static extern void IOHIDManagerSetDeviceMatching(nint manager, nint matching); + + [DllImport(IoKit)] + private static extern nint IOHIDManagerCopyDevices(nint manager); + + [DllImport(IoKit)] + private static extern nint IOHIDDeviceGetProperty(nint device, nint key); + + [DllImport(IoKit)] + private static extern int IOHIDDeviceOpen(nint device, uint options); + + [DllImport(IoKit)] + private static extern int IOHIDDeviceClose(nint device, uint options); + + [DllImport(IoKit)] + private static extern int IOHIDDeviceSetReport(nint device, uint reportType, nint reportId, byte* report, nint length); +} diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseReports.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseReports.cs new file mode 100644 index 000000000..04b9eb821 --- /dev/null +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/DualSense/MacDualSenseReports.cs @@ -0,0 +1,159 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; + +namespace SharpEmu.Host.MacOS; + +/// <summary> +/// The DualSense output reports the controller audio sends, byte for byte as upstream's SDL host builds them +/// (SdlHostAudio.ControllerAudioRoute, SDL_SendGamepadEffect, SdlDualSenseBluetooth.BuildReport). Pure: unit tested. +/// </summary> +internal static class MacDualSenseReports +{ + /// <summary>The effects state SDL_SendGamepadEffect takes for a PS5 pad (DS5EffectsState_t).</summary> + internal const int EffectsLength = 47; + + /// <summary>The route effects upstream sends: the first 38 bytes of the effects state.</summary> + internal const int RouteLength = 38; + + internal const byte UsbEffectsReportId = 0x02; + internal const int UsbEffectsReportLength = 48; + internal const byte BluetoothEffectsReportId = 0x31; + internal const int BluetoothEffectsReportLength = 78; + + internal const byte BluetoothAudioReportId = 0x39; + internal const int BluetoothAudioReportLength = 547; + internal const int HapticFrames = 64; + internal const int HapticOffset = 12; + internal const byte HapticBlockBytes = 64; + internal const int SpeakerHeaderOffset = 140; + internal const int SpeakerOffset = 142; + internal const int OpusPacketBytes = 200; + internal const int OpusPackets = 2; + private const byte AudioBufferLength = 48; + + /// <summary> + /// The pad's audio routing: with the speaker, the right channel of the front pair plays on the speaker and the + /// headphone jack is muted (audio control and speaker volume valid, speaker volume 0x64, output path 0x30, speaker + /// preamp +6 dB: the values Linux's driver uses without headphones); without it, the front pair goes back to the + /// headphone jack. Plugged-in headphones are not detected. + /// </summary> + internal static byte[] AudioRoute(bool speaker) + { + var effects = new byte[RouteLength]; + effects[0] = 0x80; + if (speaker) + { + effects[0] |= 0x20; + effects[1] = 0x80; + effects[5] = 0x64; + effects[7] = 0x30; + effects[37] = 0x02; + } + + return effects; + } + + /// <summary>USB output report 0x02: the report ID, then the effects state. Returns the report length.</summary> + internal static int BuildUsbEffectsReport(ReadOnlySpan<byte> effects, Span<byte> report) + { + report[..UsbEffectsReportLength].Clear(); + report[0] = UsbEffectsReportId; + effects[..Math.Min(effects.Length, UsbEffectsReportLength - 1)].CopyTo(report[1..]); + return UsbEffectsReportLength; + } + + /// <summary> + /// Bluetooth output report 0x31: the report ID, SDL's fixed 0x02, the effects state, and the CRC-32 over the HID + /// transaction header 0xA2 and the report. Returns the report length. + /// </summary> + internal static int BuildBluetoothEffectsReport(ReadOnlySpan<byte> effects, Span<byte> report) + { + var body = report[..BluetoothEffectsReportLength]; + body.Clear(); + body[0] = BluetoothEffectsReportId; + body[1] = 0x02; + effects[..Math.Min(effects.Length, BluetoothEffectsReportLength - 2 - sizeof(uint))].CopyTo(body[2..]); + WriteCrc(body); + return BluetoothEffectsReportLength; + } + + /// <summary> + /// Bluetooth output report 0x39: the actuators' next <see cref="HapticFrames"/> stereo frames at 3 kHz as signed + /// bytes and, when <paramref name="speakerPackets"/> holds two encoded Opus packets, the speaker's audio. + /// </summary> + internal static void BuildBluetoothAudioReport( + Span<byte> report, + byte sequence, + byte counter, + ReadOnlySpan<float> haptics, + ReadOnlySpan<byte> speakerPackets) + { + report = report[..BluetoothAudioReportLength]; + report.Clear(); + report[0] = BluetoothAudioReportId; + report[1] = (byte)(sequence << 4); + report[2] = 0x91; + report[3] = 6; + report[4] = 0x7E; + report.Slice(5, 4).Fill(AudioBufferLength); + report[9] = counter; + report[10] = 0xD2; + report[11] = HapticBlockBytes; + for (var index = 0; index < Math.Min(haptics.Length, HapticFrames * 2); index++) + { + report[HapticOffset + index] = (byte)(sbyte)ToHapticSample(haptics[index]); + } + + if (speakerPackets.Length == OpusPackets * OpusPacketBytes) + { + report[SpeakerHeaderOffset] = 0xD3; + report[SpeakerHeaderOffset + 1] = OpusPacketBytes; + speakerPackets.CopyTo(report[SpeakerOffset..]); + } + + WriteCrc(report); + } + + internal static int ToHapticSample(float value) => + float.IsFinite(value) ? (int)MathF.Round(Math.Clamp(value, -1f, 1f) * 127f) : 0; + + /// <summary>The CRC-32 of a Bluetooth output report: over 0xA2 and every byte but the last four, stored there.</summary> + internal static void WriteCrc(Span<byte> report) + { + var crc = Crc32(Crc32(0, [0xA2]), report[..^sizeof(uint)]); + BinaryPrimitives.WriteUInt32LittleEndian(report[^sizeof(uint)..], crc); + } + + /// <summary>The zlib CRC-32, chained like SDL_crc32 (start with 0).</summary> + internal static uint Crc32(uint crc, ReadOnlySpan<byte> data) + { + crc = ~crc; + foreach (var value in data) + { + crc = CrcTable[(byte)(crc ^ value)] ^ (crc >> 8); + } + + return ~crc; + } + + private static readonly uint[] CrcTable = BuildCrcTable(); + + private static uint[] BuildCrcTable() + { + var table = new uint[256]; + for (var index = 0u; index < table.Length; index++) + { + var value = index; + for (var bit = 0; bit < 8; bit++) + { + value = (value & 1) != 0 ? 0xEDB88320u ^ (value >> 1) : value >> 1; + } + + table[index] = value; + } + + return table; + } +} diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacAudioRingBuffer.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacAudioRingBuffer.cs index ea587aaa1..755cf58a6 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacAudioRingBuffer.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacAudioRingBuffer.cs @@ -31,6 +31,10 @@ internal sealed unsafe class MacAudioRingBuffer : IDisposable private long _written; private long _read; + // Producer-set read position the consumer skips to before its next read (DiscardOldestBeyond): the oldest frames + // are dropped on the consumer's side, so the ring stays single-producer, single-consumer. + private long _discardTo; + public MacAudioRingBuffer(int channels, int capacityFrames) { if (channels < 1) @@ -62,12 +66,27 @@ public long QueuedFrames // Read the consumer's counter first: a concurrent advance of either // counter can then only make the result look deeper than it is, // which errs towards the guest waiting rather than overrunning. - var read = Volatile.Read(ref _read); + var read = Math.Max(Volatile.Read(ref _read), Volatile.Read(ref _discardTo)); return Math.Max(0, Volatile.Read(ref _written) - read); } } - public long FreeFrames => _capacityFrames - QueuedFrames; + // Space the producer can write: frames still awaiting a discard occupy the ring until the consumer skips them. + public long FreeFrames => _capacityFrames - Math.Max(0, Volatile.Read(ref _written) - Volatile.Read(ref _read)); + + /// <summary> + /// Producer side: drops all but the newest <paramref name="keepFrames"/> queued frames. The consumer skips them on + /// its next read; <see cref="QueuedFrames"/> no longer counts them from now on. For a stream the guest is not + /// paced by, so a device stall leaves a gap near one block rather than a growing delay. + /// </summary> + public void DiscardOldestBeyond(long keepFrames) + { + var target = Volatile.Read(ref _written) - Math.Max(0, keepFrames); + if (target > Volatile.Read(ref _discardTo)) + { + Volatile.Write(ref _discardTo, target); + } + } /// <summary> /// Producer side. Copies whole frames and returns how many fit; a short @@ -117,10 +136,24 @@ public int Read(float* destination, int frames) } var read = Volatile.Read(ref _read); - var available = Math.Max(0, Volatile.Read(ref _written) - read); + var written = Volatile.Read(ref _written); + var discardTo = Volatile.Read(ref _discardTo); + var skipped = false; + if (discardTo > read) + { + read = Math.Min(discardTo, written); + skipped = true; + } + + var available = Math.Max(0, written - read); var count = (int)Math.Min(frames, available); if (count <= 0) { + if (skipped) + { + Volatile.Write(ref _read, read); + } + return 0; } diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioInterop.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioInterop.cs index b726250c1..8355bd28f 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioInterop.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioInterop.cs @@ -23,6 +23,7 @@ internal static unsafe class MacCoreAudioInterop // Four-character codes from AUComponent.h / CoreAudioBaseTypes.h. internal const uint AudioUnitTypeOutput = 0x6175_6F75; // 'auou' internal const uint AudioUnitSubTypeDefaultOutput = 0x6465_6620; // 'def ' + internal const uint AudioUnitSubTypeHalOutput = 0x6168_616C; // 'ahal' internal const uint AudioUnitManufacturerApple = 0x6170_706C; // 'appl' internal const uint AudioFormatLinearPcm = 0x6C70_636D; // 'lpcm' @@ -38,6 +39,44 @@ internal static unsafe class MacCoreAudioInterop internal const uint PropertyAudioChannelLayout = 19; internal const uint PropertySetRenderCallback = 23; + /// <summary>kAudioOutputUnitProperty_CurrentDevice (AudioUnitProperties.h).</summary> + internal const uint PropertyCurrentDevice = 2000; + + // AudioHardware.h / AudioHardwareBase.h. + private const string CoreAudio = "/System/Library/Frameworks/CoreAudio.framework/CoreAudio"; + internal const uint AudioObjectSystemObject = 1; + internal const uint AudioObjectScopeGlobal = 0x676C_6F62; // 'glob' + internal const uint AudioObjectScopeOutput = 0x6F75_7470; // 'outp' + internal const uint AudioObjectElementMain = 0; + internal const uint AudioHardwarePropertyDevices = 0x6465_7623; // 'dev#' + internal const uint AudioObjectPropertyName = 0x6C6E_616D; // 'lnam' + internal const uint AudioDevicePropertyStreamConfiguration = 0x736C_6179; // 'slay' + + [StructLayout(LayoutKind.Sequential)] + internal struct AudioObjectPropertyAddress + { + public uint Selector; + public uint Scope; + public uint Element; + } + + [DllImport(CoreAudio)] + internal static extern int AudioObjectGetPropertyDataSize( + uint objectId, + AudioObjectPropertyAddress* address, + uint qualifierDataSize, + void* qualifierData, + uint* dataSize); + + [DllImport(CoreAudio)] + internal static extern int AudioObjectGetPropertyData( + uint objectId, + AudioObjectPropertyAddress* address, + uint qualifierDataSize, + void* qualifierData, + uint* dataSize, + void* data); + /// <summary>Render-callback action flag telling the unit the buffer is silent.</summary> internal const uint RenderActionOutputIsSilence = 1u << 4; diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs index 5d417a143..a6b60f0fc 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioOutput.cs @@ -75,6 +75,120 @@ public IHostAudioStream OpenPcmStream(uint sampleRate, int channels, HostPcmForm ? OpenStream(sampleRate, channels, format, maxQueuedBytes) : OpenPcmStream(sampleRate, channels, format); + /// <summary> + /// SHARPEMU_DUALSENSE_AUDIO=0 keeps the controller-less paths (the pad + /// speaker on the speakers, vibration as rumble) even with a DualSense. + /// </summary> + internal static readonly bool ControllerAudioEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_DUALSENSE_AUDIO") != "0"; + + /// <summary> + /// The DualSense's own output, as upstream's SDL host opens it: on USB its + /// four-channel CoreAudio device (speaker pair, then the two actuators), + /// on Bluetooth the audio output report with the actuator samples and the + /// speaker's Opus packets. Exactly one pad on the transport and, on USB, + /// exactly one matching device, or null: nothing ties a GameController pad + /// to its audio device, so anything else gives no stream rather than a + /// guess, and the callers keep their controller-less paths. While the + /// stream is open the pad's speaker plays the front pair (restored on + /// close). The stream drops its oldest audio past the cap instead of + /// blocking and does not report the guest audio clock. + /// </summary> + public IHostAudioStream? TryOpenControllerStream(uint sampleRate, int maxQueuedBytes, out int channels, bool routeSpeaker = true) + { + channels = 0; + if (!ControllerAudioEnabled) + { + return null; + } + + IHostAudioStream stream; + string outputName; + MacDualSenseHid? usbPad = null; + MacAudioDeviceInfo device; + if (MacCoreAudioDevices.TrySelectControllerDevice(MacCoreAudioDevices.ListOutputDevices(), out device)) + { + // The device exists only while the pad is wired. Its HID interface carries the speaker routing; without + // it (another process holds the pad exclusively) the audio still plays, unrouted. + usbPad = MacDualSenseHid.TryOpenSingle(MacDualSenseTransport.Usb); + try + { + stream = new MacCoreAudioStream( + sampleRate, + MacCoreAudioDevices.ControllerChannels, + HostPcmFormat.Float32, + maxQueuedBytes > 0 + ? maxQueuedBytes + : LatencyCapBytes(sampleRate, MacCoreAudioDevices.ControllerChannels, HostPcmFormat.Float32), + new MacAudioStreamTarget(device.Id, ReportsClock: false, DropOldest: true, RawChannels: true)); + } + catch + { + usbPad?.Dispose(); + throw; + } + + outputName = $"\"{device.Name}\""; + } + else + { + device = default; + if (MacDualSenseBluetooth.TryOpen(sampleRate, maxQueuedBytes, routeSpeaker) is not { } bluetooth) + { + return null; + } + + stream = bluetooth; + outputName = "DualSense over Bluetooth"; + } + + var route = new ControllerRoute(device.Id != 0, usbPad); + var routed = routeSpeaker && route.Send(MacDualSenseReports.AudioRoute(speaker: true)); + channels = MacCoreAudioDevices.ControllerChannels; + Console.Error.WriteLine( + $"[LOADER][INFO] Controller audio: {outputName} (speaker {(routed ? "routed" : "not routed")})"); + return new ControllerAudioStream(stream, route, routed); + } + + /// <summary> + /// Where the routing effects go: the wired pad's HID interface (none when it would not open), or the Bluetooth + /// link's. + /// </summary> + private sealed class ControllerRoute(bool wired, MacDualSenseHid? usbPad) : IDisposable + { + public bool Send(ReadOnlySpan<byte> effects) => + wired ? usbPad?.TrySendEffects(effects) == true : MacDualSenseBluetooth.TrySendEffects(effects); + + public void Dispose() => usbPad?.Dispose(); + } + + private sealed class ControllerAudioStream(IHostAudioStream inner, ControllerRoute route, bool speakerRouted) + : IHostAudioStream + { + private int _disposed; + + public int QueuedMilliseconds => inner.QueuedMilliseconds; + + public bool Submit(ReadOnlySpan<byte> pcm) => inner.Submit(pcm); + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + // Restore the route while the Bluetooth link is still open. + if (speakerRouted) + { + route.Send(MacDualSenseReports.AudioRoute(speaker: false)); + } + + inner.Dispose(); + route.Dispose(); + } + } + /// <summary> /// Queue cap in guest bytes for <see cref="TargetQueuedMilliseconds"/> of /// audio in the guest's own format. diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioStream.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioStream.cs index c5ba11e1b..a62b3df38 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioStream.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Audio/MacCoreAudioStream.cs @@ -22,6 +22,20 @@ namespace SharpEmu.Host.MacOS; /// it, because a gap in the stream is an audible click and a few extra /// milliseconds of latency is not. /// </summary> +/// <param name="DeviceId">The CoreAudio device to play on; 0 follows the user's default output.</param> +/// <param name="ReportsClock">Whether this stream's playback position is the guest audio clock.</param> +/// <param name="DropOldest"> +/// For a stream the guest is not paced by: Submit never waits, and audio past the cap drops the oldest queued frames. +/// </param> +/// <param name="RawChannels"> +/// The guest's channels go to the device's channels one to one, with no fold and no channel layout (the device must +/// have exactly the guest's channel count). +/// </param> +internal readonly record struct MacAudioStreamTarget(uint DeviceId, bool ReportsClock, bool DropOldest, bool RawChannels) +{ + public static MacAudioStreamTarget DefaultOutput => new(0, ReportsClock: true, DropOldest: false, RawChannels: false); +} + [SupportedOSPlatform("macos")] internal sealed unsafe class MacCoreAudioStream : IHostAudioStream { @@ -47,6 +61,7 @@ internal sealed unsafe class MacCoreAudioStream : IHostAudioStream private readonly float[]? _matrix; private readonly long _maximumQueuedFrames; private readonly MacAudioRingBuffer? _ring; + private readonly MacAudioStreamTarget _target; private GCHandle _selfHandle; private nint _unit; @@ -74,8 +89,10 @@ internal MacCoreAudioStream( uint sampleRate, int channels, HostPcmFormat format, - int maximumQueuedBytes) + int maximumQueuedBytes, + MacAudioStreamTarget? target = null) { + _target = target ?? MacAudioStreamTarget.DefaultOutput; _sampleRate = sampleRate; _guestChannels = channels; _format = format; @@ -85,7 +102,8 @@ internal MacCoreAudioStream( var description = new AudioComponentDescription { ComponentType = AudioUnitTypeOutput, - ComponentSubType = AudioUnitSubTypeDefaultOutput, + // A chosen device needs the HAL output unit; the default output unit follows the user's selection. + ComponentSubType = _target.DeviceId != 0 ? AudioUnitSubTypeHalOutput : AudioUnitSubTypeDefaultOutput, ComponentManufacturer = AudioUnitManufacturerApple, }; @@ -103,7 +121,27 @@ internal MacCoreAudioStream( // documents no downmix for a client format wider than the device, so // the stream renders at the device's channel count and the fold from // the guest's layout happens in MacAudioChannelMap. + if (_target.DeviceId != 0) + { + var device = _target.DeviceId; + Check( + AudioUnitSetProperty( + _unit, + PropertyCurrentDevice, + ScopeGlobal, + 0, + &device, + sizeof(uint)), + "AudioUnitSetProperty(CurrentDevice)"); + } + _renderChannels = QueryDeviceChannels(); + if (_target.RawChannels && _renderChannels != _guestChannels) + { + throw new InvalidOperationException( + $"CoreAudio device {_target.DeviceId} renders {_renderChannels} channels, not {_guestChannels}."); + } + _matrix = MacAudioChannelMap.Build(_guestChannels, _renderChannels); // The client format keeps the guest's sample rate: the output unit @@ -130,7 +168,10 @@ internal MacCoreAudioStream( (uint)sizeof(AudioStreamBasicDescription)), "AudioUnitSetProperty(StreamFormat)"); - TrySetChannelLayout(); + if (!_target.RawChannels) + { + TrySetChannelLayout(); + } var maximumFrames = MaximumFramesPerSlice; // Advisory (TN2321): only strictly needed when the device buffer is @@ -218,7 +259,7 @@ public bool Submit(ReadOnlySpan<byte> pcm) var framesPerMillisecond = _sampleRate / 1_000.0; long queued; var overrun = false; - while ((queued = _ring.QueuedFrames) > _maximumQueuedFrames) + while ((queued = _ring.QueuedFrames) > _maximumQueuedFrames && !_target.DropOldest) { if (Stopwatch.GetTimestamp() >= deadline) { @@ -263,12 +304,22 @@ public bool Submit(ReadOnlySpan<byte> pcm) } WriteToRing(_scratch.AsSpan(0, converted * _renderChannels)); + if (_target.DropOldest) + { + // Never wait for a device the guest is not paced by: past the cap + // the oldest audio goes, so a device stall leaves a short gap. + _ring.DiscardOldestBeyond(_maximumQueuedFrames); + } // Everything handed over minus what the device still holds is what // the player has actually heard; video decoded on the host follows // this clock rather than wall clock. - GuestAudioClock.Report( - Math.Max(0, _totalSubmittedFrames - queued) / (double)_sampleRate); + if (_target.ReportsClock) + { + GuestAudioClock.Report( + Math.Max(0, _totalSubmittedFrames - queued) / (double)_sampleRate); + } + _totalSubmittedFrames += converted; return true; } @@ -442,8 +493,10 @@ private void WriteToRing(ReadOnlySpan<float> samples) } var written = _ring.Write(samples); - if (written * _renderChannels >= samples.Length) + if (written * _renderChannels >= samples.Length || _target.DropOldest) { + // A stream that drops its oldest audio never waits for room: a ring + // this full means the device has stalled, and the tail goes instead. return; } diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/SharpEmu.Host.MacOS.csproj b/src/platforms/macos/SharpEmu.Host.MacOS/SharpEmu.Host.MacOS.csproj index 81bfab0dd..73bf28b26 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/SharpEmu.Host.MacOS.csproj +++ b/src/platforms/macos/SharpEmu.Host.MacOS/SharpEmu.Host.MacOS.csproj @@ -7,7 +7,8 @@ SPDX-License-Identifier: GPL-2.0-or-later <!-- macOS host services (BSD syscalls, Mach VM, pthread/TLS, dispatch). Referenced only by osx-* builds; see the conditional ProjectReference in SharpEmu.CLI.csproj. Deliberately does not reference SDL: macOS audio is - a native CoreAudio output. --> + a native CoreAudio output, and the DualSense's own audio goes through + CoreAudio (USB) and IOKit HID reports (Bluetooth). --> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <NoWarn>$(NoWarn);1591</NoWarn> @@ -22,6 +23,11 @@ SPDX-License-Identifier: GPL-2.0-or-later <ProjectReference Include="..\..\..\SharpEmu.HLE\SharpEmu.HLE.csproj" /> </ItemGroup> + <ItemGroup> + <!-- Managed Opus encoder for the DualSense speaker over Bluetooth (no native library, no SDL). --> + <PackageReference Include="Concentus" /> + </ItemGroup> + <ItemGroup> <!-- Shared by source, not by a Host.Posix assembly: only the parts that carry no OS-specific declaration, constant or ABI detail. --> diff --git a/tests/SharpEmu.Libs.Tests/Audio/MacDualSenseTests.cs b/tests/SharpEmu.Libs.Tests/Audio/MacDualSenseTests.cs new file mode 100644 index 000000000..b07bcf431 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Audio/MacDualSenseTests.cs @@ -0,0 +1,318 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using SharpEmu.HLE.Host; +#if SHARPEMU_HOST_MACOS +using SharpEmu.Host.MacOS; +#endif +using Xunit; + +namespace SharpEmu.Libs.Tests.Audio; + +#if SHARPEMU_HOST_MACOS + +/// <summary> +/// The DualSense controller stream on macOS without a pad: the output reports byte for byte as upstream's SDL host +/// builds them, the Opus framing, the channel mapping, the resampling lanes and the device and HID selection. Whether a +/// real pad accepts them is hardware-unverified. +/// </summary> +public class MacDualSenseReportTests +{ + [Fact] + public void TheSpeakerRouteIsUpstreamsEffectsState() + { + var on = MacDualSenseReports.AudioRoute(speaker: true); + Assert.Equal(MacDualSenseReports.RouteLength, on.Length); + Assert.Equal(0xA0, on[0]); + Assert.Equal(0x80, on[1]); + Assert.Equal(0x64, on[5]); + Assert.Equal(0x30, on[7]); + Assert.Equal(0x02, on[37]); + Assert.Equal(5, on.Count(value => value != 0)); + + var off = MacDualSenseReports.AudioRoute(speaker: false); + Assert.Equal(0x80, off[0]); + Assert.Equal(1, off.Count(value => value != 0)); + } + + [Fact] + public void UsbEffectsGoInReportTwoAfterItsId() + { + var effects = MacDualSenseReports.AudioRoute(speaker: true); + var report = new byte[MacDualSenseReports.BluetoothEffectsReportLength]; + Assert.Equal(48, MacDualSenseReports.BuildUsbEffectsReport(effects, report)); + Assert.Equal(0x02, report[0]); + Assert.Equal(effects, report[1..(1 + effects.Length)]); + Assert.All(report[(1 + effects.Length)..48], value => Assert.Equal(0, value)); + } + + [Fact] + public void BluetoothEffectsCarryTheFixedTagAndTheCrc() + { + var effects = MacDualSenseReports.AudioRoute(speaker: true); + var report = new byte[MacDualSenseReports.BluetoothEffectsReportLength]; + Assert.Equal(78, MacDualSenseReports.BuildBluetoothEffectsReport(effects, report)); + Assert.Equal(0x31, report[0]); + Assert.Equal(0x02, report[1]); + Assert.Equal(effects, report[2..(2 + effects.Length)]); + AssertCrc(report); + } + + [Fact] + public void TheCrcIsZlibsCrc32ChainedLikeSdl() + { + var data = Encoding.ASCII.GetBytes("123456789"); + Assert.Equal(0xCBF43926u, MacDualSenseReports.Crc32(0, data)); + Assert.Equal( + MacDualSenseReports.Crc32(0, data), + MacDualSenseReports.Crc32(MacDualSenseReports.Crc32(0, data[..4]), data[4..])); + } + + [Fact] + public void TheBluetoothAudioReportHoldsTheActuatorsAndTheSpeakerPackets() + { + var haptics = new float[MacDualSenseReports.HapticFrames * 2]; + haptics[0] = 1f; + haptics[1] = -1f; + haptics[2] = 0.5f; + haptics[3] = float.NaN; + haptics[4] = 4f; + var packets = new byte[MacDualSenseReports.OpusPackets * MacDualSenseReports.OpusPacketBytes]; + packets.AsSpan().Fill(0x5A); + var report = new byte[MacDualSenseReports.BluetoothAudioReportLength]; + + MacDualSenseReports.BuildBluetoothAudioReport(report, sequence: 3, counter: 8, haptics, packets); + + Assert.Equal(547, report.Length); + Assert.Equal(new byte[] { 0x39, 0x30, 0x91, 6, 0x7E, 48, 48, 48, 48, 8, 0xD2, 64 }, report[..12]); + Assert.Equal(127, (sbyte)report[12]); + Assert.Equal(-127, (sbyte)report[13]); + Assert.Equal(64, (sbyte)report[14]); + Assert.Equal(0, (sbyte)report[15]); + Assert.Equal(127, (sbyte)report[16]); + Assert.Equal(0xD3, report[140]); + Assert.Equal(200, report[141]); + Assert.All(report[142..542], value => Assert.Equal(0x5A, value)); + AssertCrc(report); + + MacDualSenseReports.BuildBluetoothAudioReport(report, sequence: 0, counter: 2, haptics, ReadOnlySpan<byte>.Empty); + Assert.Equal(0, report[140]); + Assert.All(report[142..543], value => Assert.Equal(0, value)); + AssertCrc(report); + } + + [Fact] + public void TheSpeakerEncodesToTwoConstantSizeOpusPackets() + { + var opus = new MacDualSenseOpus(); + var speaker = new float[MacDualSenseBluetooth.SpeakerFrames * 2]; + for (var frame = 0; frame < MacDualSenseBluetooth.SpeakerFrames; frame++) + { + speaker[2 * frame] = speaker[(2 * frame) + 1] = 0.25f * MathF.Sin(frame * 2f * MathF.PI * 440f / 45000f); + } + + var packets = new byte[MacDualSenseReports.OpusPackets * MacDualSenseReports.OpusPacketBytes]; + Assert.True(opus.TryEncode(speaker, packets)); + Assert.Contains(packets[..200], value => value != 0); + Assert.Contains(packets[200..], value => value != 0); + + Array.Clear(speaker); + Assert.True(opus.TryEncode(speaker, packets)); + } + + [Fact] + public void TheStreamSplitsItsFourChannelsIntoTheSpeakerAndActuatorPairs() + { + var client = new MacDualSenseBluetooth.Client(null, 48000, queueMilliseconds: 80, speaker: true); + const int frames = 4800; + var pcm = new float[frames * MacDualSenseBluetooth.InputChannels]; + for (var frame = 0; frame < frames; frame++) + { + pcm[(frame * 4) + 0] = 0.1f; + pcm[(frame * 4) + 1] = 0.2f; + pcm[(frame * 4) + 2] = 0.3f; + pcm[(frame * 4) + 3] = -0.4f; + } + + Assert.True(client.Submit(MemoryMarshal.AsBytes(pcm.AsSpan()))); + + var haptics = new float[MacDualSenseReports.HapticFrames * 2]; + Assert.True(client.Haptics.MixInto(haptics)); + Assert.All(Enumerable.Range(0, MacDualSenseReports.HapticFrames), frame => + { + Assert.Equal(0.3f, haptics[2 * frame], 4); + Assert.Equal(-0.4f, haptics[(2 * frame) + 1], 4); + }); + + var speaker = new float[MacDualSenseBluetooth.SpeakerFrames * 2]; + Assert.True(client.Speaker!.MixInto(speaker)); + Assert.Equal(0.1f, speaker[0], 4); + Assert.Equal(0.2f, speaker[1], 4); + Assert.Equal(0.1f, speaker[^2], 4); + Assert.Equal(0.2f, speaker[^1], 4); + + // A stream for the actuators alone has no speaker lane. + Assert.Null(new MacDualSenseBluetooth.Client(null, 48000, 80, speaker: false).Speaker); + } + + [Fact] + public void ALaneResamplesPrimesAndDropsItsOldestPastTheLimit() + { + var lane = new MacDualSenseLane(48000, 3000, MacDualSenseReports.HapticFrames, queueMilliseconds: 80); + var report = new float[MacDualSenseReports.HapticFrames * 2]; + + // 16 input frames per actuator frame; 1.5 reports must be queued before the first goes out. + lane.Put(Constant(16 * 95, 0.5f)); + Assert.Equal(95, lane.QueuedFrames); + Assert.False(lane.MixInto(report)); + lane.Put(Constant(16, 0.5f)); + Assert.True(lane.MixInto(report)); + Assert.All(report, value => Assert.Equal(0.5f, value, 5)); + Assert.Equal(32, lane.QueuedFrames); + + // 80 ms at 3 kHz is 240 frames: a second of audio keeps the newest 240. + lane.Put(Constant(48000, 0.25f)); + Assert.Equal(240, lane.QueuedFrames); + Assert.Equal(80, lane.QueuedMilliseconds); + } + + [Fact] + public void ADownsampledLaneAveragesWhatTheActuatorsCannotPlay() + { + var lane = new MacDualSenseLane(48000, 3000, MacDualSenseReports.HapticFrames, queueMilliseconds: 80); + // A tone at 12 kHz (four input frames a period) averages out over the 16-frame interval. + var tone = new float[48000 / 10 * 2]; + for (var frame = 0; frame < tone.Length / 2; frame++) + { + tone[2 * frame] = tone[(2 * frame) + 1] = (frame % 4) switch { 0 => 1f, 1 => 0f, 2 => -1f, _ => 0f }; + } + + lane.Put(tone); + var report = new float[MacDualSenseReports.HapticFrames * 2]; + Assert.True(lane.MixInto(report)); + Assert.All(report, value => Assert.Equal(0f, value, 5)); + } + + [Fact] + public void OnlyOneFourChannelDualSenseDeviceIsTheController() + { + var pad = new MacAudioDeviceInfo(70, "DualSense Wireless Controller", 4); + var speakers = new MacAudioDeviceInfo(60, "MacBook Air Speakers", 2); + Assert.True(MacCoreAudioDevices.TrySelectControllerDevice([speakers, pad], out var chosen)); + Assert.Equal(pad, chosen); + Assert.True(MacCoreAudioDevices.TrySelectControllerDevice( + [new MacAudioDeviceInfo(71, "Wireless Controller", 4)], out _)); + Assert.False(MacCoreAudioDevices.TrySelectControllerDevice([speakers], out _)); + Assert.False(MacCoreAudioDevices.TrySelectControllerDevice( + [new MacAudioDeviceInfo(72, "DualSense Wireless Controller", 2)], out _)); + Assert.False(MacCoreAudioDevices.TrySelectControllerDevice( + [pad, new MacAudioDeviceInfo(73, "DualSense Wireless Controller", 4)], out _)); + } + + [Fact] + public void OnlyADualSenseGamepadInterfaceHasATransport() + { + const int sony = MacDualSenseHid.SonyVendorId; + Assert.Equal(MacDualSenseTransport.Usb, MacDualSenseHid.Classify(sony, new(0x0CE6, "USB", 1, 5))); + Assert.Equal(MacDualSenseTransport.Bluetooth, MacDualSenseHid.Classify(sony, new(0x0CE6, "Bluetooth", 1, 5))); + Assert.Equal(MacDualSenseTransport.Usb, MacDualSenseHid.Classify(sony, new(0x0DF2, "USB", 0, 0))); + Assert.Null(MacDualSenseHid.Classify(0x045E, new(0x0CE6, "USB", 1, 5))); + Assert.Null(MacDualSenseHid.Classify(sony, new(0x09CC, "USB", 1, 5))); + Assert.Null(MacDualSenseHid.Classify(sony, new(0x0CE6, "USB", 12, 1))); + Assert.Null(MacDualSenseHid.Classify(sony, new(0x0CE6, null, 1, 5))); + } + + [Fact] + public void ARingDropsItsOldestFramesOnTheConsumerSide() + { + using var ring = new MacAudioRingBuffer(channels: 1, capacityFrames: 256); + var values = Enumerable.Range(0, 100).Select(value => (float)value).ToArray(); + Assert.Equal(100, ring.Write(values)); + + ring.DiscardOldestBeyond(10); + Assert.Equal(10, ring.QueuedFrames); + Assert.Equal(156, ring.FreeFrames); // the dropped frames hold their slots until the consumer skips them + + var read = new float[16]; + Assert.Equal(10, ring.Read(read)); + Assert.Equal(Enumerable.Range(90, 10).Select(value => (float)value), read[..10]); + Assert.Equal(0, ring.QueuedFrames); + Assert.Equal(256, ring.FreeFrames); + } + + private static float[] Constant(int frames, float value) + { + var samples = new float[frames * 2]; + samples.AsSpan().Fill(value); + return samples; + } + + private static void AssertCrc(byte[] report) + { + var expected = MacDualSenseReports.Crc32(MacDualSenseReports.Crc32(0, [0xA2]), report[..^4]); + Assert.Equal(expected, BinaryPrimitives.ReadUInt32LittleEndian(report.AsSpan(report.Length - 4))); + } +} + +/// <summary>The CoreAudio side of the controller stream and the AudioOut2 queue cap, on this Mac's devices.</summary> +public class MacControllerAudioDeviceTests +{ + [Fact] + public void ACallerChosenCapHoldsTheQueueDepthAudioOut2Expects() + { + if (!OperatingSystem.IsMacOS()) + { + return; + } + + IHostAudioStream stream; + try + { + stream = new MacCoreAudioOutput().OpenPcmStream(48000, 2, HostPcmFormat.Float32, 256 * 1024); + } + catch (InvalidOperationException) + { + return; // no output device on this host + } + + using (stream) + { + // 200 ms of silence: past the 60 ms default cap, well under the 682 ms this cap allows, so it queues + // without waiting. + var silence = new byte[48000 / 5 * 2 * sizeof(float)]; + var watch = Stopwatch.StartNew(); + Assert.True(stream.Submit(silence)); + Assert.True(stream.Submit(silence)); + Assert.True(watch.ElapsedMilliseconds < 150, $"submits waited {watch.ElapsedMilliseconds} ms"); + Assert.True(stream.QueuedMilliseconds > 150, $"queued {stream.QueuedMilliseconds} ms"); + } + } + + [Fact] + public void WithoutADualSenseThereIsNoControllerStream() + { + if (!OperatingSystem.IsMacOS()) + { + return; + } + + var stream = new MacCoreAudioOutput().TryOpenControllerStream(48000, 48000 * 16 * 80 / 1000, out var channels); + if (stream is null) + { + Assert.Equal(0, channels); + return; + } + + // A DualSense is connected to this Mac: the stream is the four-channel one. + using (stream) + { + Assert.Equal(4, channels); + Assert.True(stream.Submit(new byte[480 * 16])); + } + } +} +#endif From 3d41dd98feac43400ecc31dadff36f88b0d24ef6 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:41:29 +0000 Subject: [PATCH 59/64] [Memory] Name the native region and the macOS 27 GPU carveout in a failed guest map's log Port of upstream d364227d2. The shadow tables only know this process's own mappings, so the map-failure log now adds the kernel's regions over the range (mach_vm_region_recurse: base, size, protection, tag) and says when the range touches [0x10_0000_0000, 0x70_0000_0000) and whether it is virtual. --- src/SharpEmu.HLE/Host/IHostMemory.cs | 7 +++ .../Kernel/KernelMemoryCompatExports.cs | 14 +++++- .../Memory/MacHostMemory.cs | 3 ++ .../Memory/MacHostViews.cs | 46 +++++++++++++++++++ 4 files changed, 69 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.HLE/Host/IHostMemory.cs b/src/SharpEmu.HLE/Host/IHostMemory.cs index e5ddd4a2e..6c755ebe6 100644 --- a/src/SharpEmu.HLE/Host/IHostMemory.cs +++ b/src/SharpEmu.HLE/Host/IHostMemory.cs @@ -51,6 +51,13 @@ public interface IHostMemory bool Query(ulong address, out HostRegionInfo info); + /// <summary> + /// Diagnostic only: what the host OS itself has mapped in [<paramref name="address"/>, +<paramref name="size"/>), + /// including mappings no provider table records (the runtime's heaps, the translator's own memory, ranges the OS + /// keeps for itself). Null when the platform cannot tell; <see cref="Query"/> covers the providers' own tables. + /// </summary> + string? DescribeNativeRegion(ulong address, ulong size) => null; + // This reports allocation bounds, not page protection or commit state. bool TryQueryAllocation(ulong address, out HostAddressRange range) { diff --git a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs index a06ddead7..8ef119f23 100644 --- a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs @@ -245,8 +245,20 @@ private static void ReportMapFailure(string reason, ulong address, ulong length, var region = VirtualQuery((nint)address, out var info, 0) == 0 ? "unknown" : $"base=0x{info.BaseAddress:X} allocation_base=0x{info.AllocationBase:X} size=0x{info.RegionSize:X} state=0x{info.State:X} type=0x{info.Type:X} protect=0x{info.Protect:X}"; + // The provider tables above know only what this process mapped through them; the OS's own map names what + // else blocks the range (on macOS: the runtime, Rosetta, or the macOS 27 GPU carveout). + string? native; + try + { + native = SharpEmu.HLE.Host.HostMemoryAuthority.Current.DescribeNativeRegion(address, length); + } + catch (Exception exception) when (exception is InvalidOperationException or NotSupportedException) + { + native = null; + } + Console.Error.WriteLine($"[LOADER][WARN] map_direct failed={reason} address=0x{address:X} size=0x{length:X} offset=0x{directMemoryStart:X} " + - $"flags=0x{flags:X} host_region: {region}"); + $"flags=0x{flags:X} host_region: {region}{(native is null ? string.Empty : $" host_map: {native}")}"); } private static unsafe nuint VirtualQuery(nint lpAddress, out MemoryBasicInformation lpBuffer, nuint dwLength) diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostMemory.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostMemory.cs index c658ab5fc..42ea238f0 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostMemory.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostMemory.cs @@ -112,6 +112,9 @@ public bool ProtectRaw( out rawOldProtection); } + public string? DescribeNativeRegion(ulong address, ulong size) => + MacHostViews.DescribeNativeRegion(address, size); + public bool Query(ulong address, out HostRegionInfo info) { if (QueryRaw(address, out var nativeInfo) == 0) diff --git a/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostViews.cs b/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostViews.cs index 6122bc2df..6f068ce7b 100644 --- a/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostViews.cs +++ b/src/platforms/macos/SharpEmu.Host.MacOS/Memory/MacHostViews.cs @@ -454,6 +454,52 @@ public ulong FindUnmappedRange(ulong address, ulong size, ulong searchEnd) return 0; } + /// <summary> + /// The kernel's own map over a range, for a failed guest mapping: the shadow tables only know what this process + /// mapped through them, so a range blocked by the runtime, Rosetta or dyld, or by the GPU carveout macOS 27 keeps + /// at [0x10_0000_0000, 0x70_0000_0000), reads as free there. Lists the first few native regions that intersect the + /// range (base, size, current/maximum protection, user tag) and says when the range touches the carveout. + /// </summary> + internal static string DescribeNativeRegion(ulong address, ulong size) + { + var end = size > ulong.MaxValue - address ? ulong.MaxValue : address + size; + var parts = new List<string>(); + if (OperatingSystem.IsMacOSVersionAtLeast(27) && address < CarveoutEnd && end > CarveoutStart) + { + parts.Add($"macos27-carveout[0x{CarveoutStart:X},0x{CarveoutEnd:X}) {(CarveoutVirtual ? "virtual" : "unmappable")}"); + } + + var task = mach_task_self(); + var info = stackalloc uint[VM_REGION_SUBMAP_SHORT_INFO_COUNT_64]; + var cursor = address; + var listed = 0; + while (cursor < end && listed < 4) + { + var regionAddress = cursor; + ulong regionSize = 0; + uint depth = 0; + var count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; + if (mach_vm_region_recurse(task, ref regionAddress, ref regionSize, ref depth, info, ref count) != KERN_SUCCESS || + regionSize == 0 || regionAddress >= end) + { + break; + } + + // vm_region_submap_short_info_64 (pack 4): protection, max_protection, inheritance, offset (two words), + // user_tag. + parts.Add($"native[0x{regionAddress:X}+0x{regionSize:X} prot={info[0]}/{info[1]} tag={info[5]}]"); + listed++; + if (regionSize > ulong.MaxValue - regionAddress) + { + break; + } + + cursor = regionAddress + regionSize; + } + + return parts.Count == 0 ? "native[none]" : string.Join(' ', parts); + } + private static ulong AlignUp(ulong value, ulong alignment) { var remainder = value % alignment; From 01f4f594d20f86ac8b4e0c4fa6d5580e34ec021a Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:41:29 +0000 Subject: [PATCH 60/64] [Tests] Check macOS QueryAccess against the kernel's protection, page by page Guard (no access) and read-only watches on single pages and runs, a sub-range query, the unmapped tail, and the map-failure description inside and outside the macOS 27 carveout. --- .../MacQueryAccessTests.cs | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 tests/SharpEmu.Host.Memory.Tests/MacQueryAccessTests.cs diff --git a/tests/SharpEmu.Host.Memory.Tests/MacQueryAccessTests.cs b/tests/SharpEmu.Host.Memory.Tests/MacQueryAccessTests.cs new file mode 100644 index 000000000..e0a85174e --- /dev/null +++ b/tests/SharpEmu.Host.Memory.Tests/MacQueryAccessTests.cs @@ -0,0 +1,118 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#if SHARPEMU_HOST_MACOS +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using SharpEmu.HLE.Host; +using SharpEmu.Host.MacOS; +using Xunit; + +namespace SharpEmu.Host.Memory.Tests; + +/// <summary> +/// <see cref="IHostViewMemory.QueryAccess"/> on macOS answers from the region table, not the kernel. A partial unmap +/// maps the rest of a view again with what it reports, so it must say what the kernel enforces: page by page, after +/// page watches (no access, read-only) were set on single pages and runs, and nothing for a part that is unmapped. +/// </summary> +[SupportedOSPlatform("macos")] +public sealed unsafe class MacQueryAccessTests +{ + private const int VmRegionBasicInfo64 = 9; + + [Fact] + public void QueryAccessMatchesTheKernelPageByPage() + { + var views = MacOSHost.CreateViewMemory(); + var page = views.PageSize; + var size = 16 * page; + Assert.True(views.TryCreateBacking(size, out var backing, out _)); + using var owned = backing!; + var address = views.FindUnmappedRange(0xF0_0000_0000, size, 0xFC_0000_0000); + Assert.NotEqual(0UL, address); + Assert.Equal(address, views.ReserveHole(address, size)); + try + { + Assert.True(views.SplitHole(address, size)); + Assert.True(views.TryMapView(backing!, address, 0, 12 * page, HostPageProtection.ReadWrite, out _)); + // Page watches: a read watch on one page, a write watch on one page and on a run, a page made read-write + // again inside the run, and a read watch at the end of the view. + Assert.True(views.ChangeAccess(address + page, page, HostPageProtection.NoAccess)); + Assert.True(views.ChangeAccess(address + 2 * page, page, HostPageProtection.ReadOnly)); + Assert.True(views.ChangeAccess(address + 4 * page, 4 * page, HostPageProtection.ReadOnly)); + Assert.True(views.ChangeAccess(address + 6 * page, page, HostPageProtection.ReadWrite)); + Assert.True(views.ChangeAccess(address + 11 * page, page, HostPageProtection.NoAccess)); + + var runs = views.QueryAccess(address, size); + // The mapped part is described without gaps; the reserved tail past it is not described at all. + var cursor = address; + foreach (var run in runs) + { + Assert.Equal(cursor, run.Address); + cursor += run.Size; + } + + Assert.Equal(address + 12 * page, cursor); + for (var offset = 0UL; offset < 12 * page; offset += page) + { + var run = runs.Single(candidate => candidate.Address <= address + offset && + address + offset < candidate.Address + candidate.Size); + Assert.True( + KernelProtection(address + offset) == run.Protection, + $"page +0x{offset:X}: table says {run.Protection}, kernel enforces {KernelProtection(address + offset)}"); + } + + // A sub-range query starts at the asked address, inside a run. + var inner = views.QueryAccess(address + 5 * page, 2 * page); + Assert.Equal( + [new HostPageAccess(address + 5 * page, page, HostPageProtection.ReadOnly), + new HostPageAccess(address + 6 * page, page, HostPageProtection.ReadWrite)], + inner); + + // A map failure names the native region the kernel holds there on macOS, and inside the GPU carveout says so. + IHostMemory memory = MacOSHost.CreateMemory(); + Assert.Contains($"native[0x{address + page:X}+0x{page:X} prot=0/", memory.DescribeNativeRegion(address + page, page)); + if (OperatingSystem.IsMacOSVersionAtLeast(27)) + { + Assert.Contains("macos27-carveout[0x1000000000,0x7000000000)", memory.DescribeNativeRegion(0x10_0000_0000, page)); + } + + Assert.True(views.UnmapView(address, 12 * page)); + Assert.Empty(views.QueryAccess(address, size)); + } + finally + { + Assert.True(views.FreeHole(address, size)); + } + } + + private static HostPageProtection KernelProtection(ulong address) + { + var regionAddress = address; + ulong regionSize = 0; + uint count = 9; + var information = stackalloc int[9]; + var task = MachTaskSelf(); + Assert.Equal(0, MachVmRegion(task, ref regionAddress, ref regionSize, VmRegionBasicInfo64, information, ref count, out var objectName)); + if (objectName != 0) _ = MachPortDeallocate(task, objectName); + Assert.True(regionAddress <= address && address - regionAddress < regionSize, $"0x{address:X} is not mapped"); + return (information[0] & 7) switch + { + 0 => HostPageProtection.NoAccess, + 1 => HostPageProtection.ReadOnly, + 3 => HostPageProtection.ReadWrite, + var other => throw new InvalidOperationException($"unexpected protection {other}"), + }; + } + + [DllImport("libSystem.dylib", EntryPoint = "mach_task_self")] + private static extern uint MachTaskSelf(); + + [DllImport("libSystem.dylib", EntryPoint = "mach_vm_region")] + private static extern int MachVmRegion(uint task, ref ulong address, ref ulong size, int flavor, + int* information, ref uint informationCount, out uint objectName); + + [DllImport("libSystem.dylib", EntryPoint = "mach_port_deallocate")] + private static extern int MachPortDeallocate(uint task, uint name); +} +#endif From ddb0efda3517f51035b724dac278cbcecca18da8 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:41:41 +0000 Subject: [PATCH 61/64] [Cpu] Run POSIX signal handlers with the host's MXCSR and x87 control word Guests run with MXCSR 0x9FC0 (FTZ+DAZ) since the upstream sync. A macOS signal handler, Rosetta included, starts with the interrupted thread's state, so the managed recovery chain and the GPU page watches ran with the guest's flush-to-zero. The signal trampoline now saves the interrupted MXCSR and FPU control word, loads 0x1F80/0x037F, and puts the saved values back before returning or chaining. --- .../shared/PosixFaults/PosixFaultBridge.cs | 35 +++++++ .../Cpu/PosixSignalFloatingPointTests.cs | 97 +++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 tests/SharpEmu.Libs.Tests/Cpu/PosixSignalFloatingPointTests.cs diff --git a/src/platforms/shared/PosixFaults/PosixFaultBridge.cs b/src/platforms/shared/PosixFaults/PosixFaultBridge.cs index c70a2d4e3..249ced2ce 100644 --- a/src/platforms/shared/PosixFaults/PosixFaultBridge.cs +++ b/src/platforms/shared/PosixFaults/PosixFaultBridge.cs @@ -646,6 +646,39 @@ private static void ChainPreviousAction(int signal, nint siginfo, nint ucontext) } } + /// <summary>The host's MXCSR and x87 control word: the x86-64 System V initial state .NET code runs with.</summary> + internal const uint HostMxcsr = 0x1F80; + internal const ushort HostFpuControlWord = 0x037F; + + /// <summary> + /// Saves the interrupted MXCSR and x87 control word in 16 bytes it pushes and loads the host's. Guest code runs + /// with the console's (MXCSR 0x9FC0: flush-to-zero and denormals-are-zero; see EmitFloatingPointControlSwitch), + /// and a signal handler on macOS starts with the interrupted thread's, Rosetta included (Linux starts it with a + /// fresh state), so without this the managed recovery chain, the GPU page watches and a chained runtime handler + /// ran with the guest's flush-to-zero. Pair with <see cref="EmitLeaveHostFloatingPoint"/> at the same stack depth. + /// </summary> + internal static void EmitEnterHostFloatingPoint(Assembler a) + { + a.sub(rsp, 16); + a.stmxcsr(__dword_ptr[rsp]); + a.fnstcw(__word_ptr[rsp + 4]); + a.mov(__dword_ptr[rsp + 8], HostMxcsr); + a.ldmxcsr(__dword_ptr[rsp + 8]); + a.mov(__word_ptr[rsp + 12], HostFpuControlWord); + a.fldcw(__word_ptr[rsp + 12]); + } + + /// <summary> + /// Puts the interrupted MXCSR and x87 control word back (the signal return restores the frame's anyway; a chained + /// handler that returns does not go through it) and pops what <see cref="EmitEnterHostFloatingPoint"/> pushed. + /// </summary> + internal static void EmitLeaveHostFloatingPoint(Assembler a) + { + a.ldmxcsr(__dword_ptr[rsp]); + a.fldcw(__word_ptr[rsp + 4]); + a.add(rsp, 16); + } + // Guest faults are delivered on the guest stack. The runtime only knows the thread's own stack, // so managed code that runs on the guest stack can make a garbage collection misread the frames // of that thread. Windows swaps the stack bounds in the TEB while guest code runs; POSIX cannot, @@ -664,6 +697,7 @@ private static nint CreateSignalTrampoline() a.push(r13); a.push(r14); a.push(r15); + EmitEnterHostFloatingPoint(a); a.mov(r12d, edi); a.mov(r13, rsi); a.mov(r14, rdx); @@ -705,6 +739,7 @@ private static nint CreateSignalTrampoline() a.call(rax); a.Label(ref done); a.mov(rsp, rbx); + EmitLeaveHostFloatingPoint(a); a.pop(r15); a.pop(r14); a.pop(r13); diff --git a/tests/SharpEmu.Libs.Tests/Cpu/PosixSignalFloatingPointTests.cs b/tests/SharpEmu.Libs.Tests/Cpu/PosixSignalFloatingPointTests.cs new file mode 100644 index 000000000..a25c9eaa0 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Cpu/PosixSignalFloatingPointTests.cs @@ -0,0 +1,97 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#if SHARPEMU_CPU_MACOS_X64 || SHARPEMU_CPU_LINUX_X64 +using System.Runtime.InteropServices; +using Iced.Intel; +using SharpEmu.HLE; +using Xunit; +using static Iced.Intel.AssemblerRegisters; +#if SHARPEMU_CPU_MACOS_X64 +using Bridge = SharpEmu.Cpu.DirectExecution.MacOS.X64.PosixFaultBridge; +#else +using Bridge = SharpEmu.Cpu.DirectExecution.Linux.X64.PosixFaultBridge; +#endif + +namespace SharpEmu.Libs.Tests.Cpu; + +/// <summary> +/// The signal trampoline's floating-point switch: a guest that faults runs with the console's MXCSR (0x9FC0, +/// flush-to-zero and denormals-are-zero) and, on macOS and under Rosetta, the signal handler starts with it. The +/// trampoline's prologue must hand the managed handler the host's MXCSR and x87 control word and its epilogue must put +/// the interrupted ones back. Runs the exact emitted sequence around a probe, without a signal. +/// </summary> +public sealed unsafe class PosixSignalFloatingPointTests +{ + private const uint GuestMxcsr = CpuContext.InitialMxcsr; + private const ushort GuestFpuControlWord = 0x027F; + + [NativeX64Fact] + public void TheHandlerRunsWithTheHostFloatingPointControlAndTheGuestsComeBack() + { + if (RuntimeInformation.ProcessArchitecture != Architecture.X64) + { + return; + } + + var a = new Assembler(64); + // rdi: four results (inside MXCSR, inside control word, after MXCSR, after control word), 4 bytes each. + a.push(rbx); + a.mov(rbx, rdi); + a.sub(rsp, 16); + a.stmxcsr(__dword_ptr[rsp + 8]); + a.fnstcw(__word_ptr[rsp + 12]); + // The guest's state when it faults. + a.mov(__dword_ptr[rsp], GuestMxcsr); + a.ldmxcsr(__dword_ptr[rsp]); + a.mov(__word_ptr[rsp + 4], GuestFpuControlWord); + a.fldcw(__word_ptr[rsp + 4]); + + Bridge.EmitEnterHostFloatingPoint(a); + a.stmxcsr(__dword_ptr[rbx]); + a.fnstcw(__word_ptr[rbx + 4]); + Bridge.EmitLeaveHostFloatingPoint(a); + + a.stmxcsr(__dword_ptr[rbx + 8]); + a.fnstcw(__word_ptr[rbx + 12]); + // The test runner's own state back. + a.ldmxcsr(__dword_ptr[rsp + 8]); + a.fldcw(__word_ptr[rsp + 12]); + a.add(rsp, 16); + a.pop(rbx); + a.ret(); + + var size = (nuint)Environment.SystemPageSize; + var page = (byte*)HostMemory.Alloc(null, size, HostMemory.MEM_COMMIT | HostMemory.MEM_RESERVE, HostMemory.PAGE_EXECUTE_READWRITE); + Assert.True(page != null); + try + { + a.Assemble(new PointerCodeWriter(page, (int)size), (ulong)page); + var results = stackalloc uint[4]; + new Span<uint>(results, 4).Clear(); + ((delegate* unmanaged<uint*, void>)page)(results); + + // Status flags (bits 0-5) may be set by the probe itself; the control bits are what matter. + Assert.Equal(Bridge.HostMxcsr, results[0] & ~0x3Fu); + Assert.Equal(Bridge.HostFpuControlWord, (ushort)results[1]); + Assert.Equal(GuestMxcsr, results[2] & ~0x3Fu); + Assert.Equal(GuestFpuControlWord, (ushort)results[3]); + } + finally + { + Assert.True(HostMemory.Free(page, 0, HostMemory.MEM_RELEASE)); + } + } +} + +internal sealed unsafe class PointerCodeWriter(byte* target, int capacity) : CodeWriter +{ + private int _offset; + + public override void WriteByte(byte value) + { + Assert.True(_offset < capacity); + target[_offset++] = value; + } +} +#endif From 20e439cc0347fefa2705c52ff1ca522aee246012 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:45:54 +0000 Subject: [PATCH 62/64] [Tests] Allow the macOS host package CoreAudio, CoreFoundation and IOKit for the DualSense audio --- .../ArchitectureRules/HostPackageBoundaryTests.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/SharpEmu.Libs.Tests/ArchitectureRules/HostPackageBoundaryTests.cs b/tests/SharpEmu.Libs.Tests/ArchitectureRules/HostPackageBoundaryTests.cs index 8479d3fcf..8b9f8b6a0 100644 --- a/tests/SharpEmu.Libs.Tests/ArchitectureRules/HostPackageBoundaryTests.cs +++ b/tests/SharpEmu.Libs.Tests/ArchitectureRules/HostPackageBoundaryTests.cs @@ -154,6 +154,10 @@ public void HostPackagesDoNotUseASiblingOssNativeApi(string package, string[] fo "libc", "libSystem.B.dylib", "/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox", + // The DualSense's own audio: its CoreAudio device (USB) and its HID output reports (Bluetooth). + "/System/Library/Frameworks/CoreAudio.framework/CoreAudio", + "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", + "/System/Library/Frameworks/IOKit.framework/IOKit", })] [InlineData(Linux, new[] { "libc", "libasound.so.2" })] [InlineData(Windows, new[] { "kernel32.dll", "kernelbase.dll", "winmm.dll" })] From 965f0cd9441e7cc46ce0e20435f7d1b3e8e2d642 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:46:37 +0000 Subject: [PATCH 63/64] [Tests] Pin split protocol 11 after the overlay and pad orientation merges --- tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs index 2ec25da6f..c215ab9b4 100644 --- a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs @@ -96,7 +96,7 @@ public void CombinedLayoutRefusesEveryIndependentRecoveryProtocol(uint version) using var host = GpuRemoteChannel.Create(SharedMemoryRegion.CreateUniqueName("setest")); using (var raw = SharedMemoryRegion.Open(host.Name)) ((RegionHeader*)raw.Pointer)->Version = version; - Assert.Equal(10u, GpuRemoteProtocol.Version); + Assert.Equal(11u, GpuRemoteProtocol.Version); Assert.Throws<InvalidDataException>(() => GpuRemoteChannel.Attach(host.Name)); } From 97e6b87973239663c923227b89326dbf98e8ea77 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Thu, 26 Nov 2026 20:49:42 +0000 Subject: [PATCH 64/64] [Docs] Describe the switches the 1d2fa2a35 ports added --- docs/macos/configuration.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 4d22fb1e5..b66e14eb6 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -45,6 +45,17 @@ them for measurements or to isolate a problem. | `SHARPEMU_FLIP_AHEAD` | off | Experimental. `1` tells the game a GPU flip is done once the flip is recorded and the flip before it has really finished on the GPU, instead of when the frame is shown, so the game can build its next frame while the GPU draws this one (at most one flip ahead). Each such frame is copied in the GPU stream into a presenter-owned texture (up to 7 textures the size of the display buffer), so what is shown is unchanged; a flip whose frame cannot be copied keeps the usual timing, and the refusal is logged once. Pacing, interrupts and labels are unchanged. Counters: `[VIDEOOUT][FLIP-AHEAD]` and the `flip_copy*` fields of `[METAL-PRESENT]`. | | `SHARPEMU_METAL_V2_PRESENT_SNAPSHOT` | on | `0` presents a flipped display buffer directly instead of a copy of it. By default each flip's frame is copied in the GPU stream, at the flip, into a presenter-owned texture (one blit per flip; up to 7 textures the size of the display buffer, 4 in use on a 60 fps title), so a game that starts drawing its next frame into the buffer still on screen cannot show a half-drawn (black) frame. A frame that cannot be copied is presented directly and the refusal is logged once. | +## Input, audio and in-game overlays + +| Variable | Default | Effect | +| --- | --- | --- | +| `SHARPEMU_DUALSENSE_AUDIO` | on | With exactly one DualSense connected, the pad speaker and the vibration actuators play through the controller: over USB as its 4-channel CoreAudio device, over Bluetooth as HID output reports with Opus audio. With none or several connected the pad speaker plays on the Mac's output and vibration ports drive rumble. `0` never opens the controller stream. | +| `SHARPEMU_HAPTIC_RUMBLE_GAIN` | `1` | Gain applied to rumble made from vibration-port audio (timed, 250 ms after the last sample). `0` turns that rumble off. | +| `SHARPEMU_UI_PALETTE` | launcher theme | Colour palette of the in-game overlays (on-screen keyboard, save data list, notifications). The launcher sets it from its theme. | +| `SHARPEMU_UI_LANGUAGE` | launcher language | Language of the in-game overlays; the launcher also passes the translated strings in `SHARPEMU_UI_STRINGS`. | +| `SHARPEMU_DEFAULT_PROFILE` | launcher setting | Text the IME dialog offers when the title gives none. Set from the launcher's default profile name. | +| `SHARPEMU_IME_AUTOFILL` | off | `1` finishes an IME dialog with the title's own text instead of opening the on-screen keyboard. `SHARPEMU_IME_DEFAULT_TEXT` does the same with the given text. | + ## Metal memory | Variable | Default | Effect | @@ -54,6 +65,8 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_IMAGE_BUDGET_MB` | computed | Fixed byte budget for the detiled image cache, at least 256. By default the budget follows the memory the host has free. | | `SHARPEMU_METAL_V2_SINGLE_COPY` | on | `0` never releases guest memory that a clean texture's Metal copy duplicates. Requires the chunked guest backing. | | `SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD` | on | `0` restores the old refusal: a GPU-written image whose every byte an alias has since written keeps its older texels instead of reloading them, and writes them back over the alias's bytes. For A/B comparisons only. | +| `SHARPEMU_METAL_V2_SAMPLED_DEPTH_CLEAR` | on | A one-layer, one-level depth surface sampled while its HTILE holds a pending clear reads the cleared value: the sample clears depth (stencil untouched) and consumes the clear (upstream cb790c35e). `0` samples the stale depth bytes. | +| `SHARPEMU_METAL_V2_FRAME_ALIASES` | on | An overlapping alias that the current frame or each of the two frames before it used stays cached when an overlap would release it, instead of being written back and rebuilt from guest memory every frame (upstream c30081163). Before the first presented frame the older 32-submission rule applies. `0` uses that rule throughout. | | `SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS` | on | A streamed texture whose T# starts past mip 0 is described from that level (upstream's resident-mip textures, `ImageDescription.FirstLevel`). The image cache looks it up as its whole chain and, while the guest has not mapped that chain, never holds or reads a level before the binding's base level, whatever `SHARPEMU_METAL_V2_BASE_LEVEL` says. Image uploads read guest bytes as upstream does: every byte must be mapped (or partially resident PRT/AMM memory), else the GPU stops with `Could not read the mapped guest image backing`; `SHARPEMU_IMAGE_BACKING_HOLES=1` reads unmapped pages after a mapped first page as zero instead. `0` keeps whole-chain requests and reads image bytes as a binding does (the readable prefix, zeros after it). | | `SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL` | on | A bindless texture table entry whose image's first byte the guest has not mapped binds the null texture and is looked up again at every bind until the memory is mapped, as the Vulkan bindless heap skips such a record. The counter `BindlessUnmappedEntries` counts them. `0` uploads the entry, which stops the GPU with `Could not read the mapped guest image backing` unless the bytes are partially resident PRT/AMM memory. | | `SHARPEMU_MANAGED_WRITE_LEASE_GATE` | on | An emulator write into guest GPU memory takes the managed-write lease (`GuestWriteReservations`) only after a backend that makes GPU claims has registered. The Vulkan buffer cache registers when it is built; the Metal backend makes no claims, so on macOS a managed write marks its pages before and after the copy, as before the lease existed. `0` makes every managed write take the lease, as upstream does. | @@ -140,6 +153,10 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS` | on | A draw's stencil operations and compare functions come from its own dynamic state, not from the draw its pipeline was first built for. `0` takes them from the pipeline again. | | `SHARPEMU_DRAW_REPLAY` | on | A draw that repeats the command-thread item before it in all but its user data (same programs, descriptor words, vertex input and targets) binds what that draw bound, with its own user data patched into the push data, instead of preparing and binding again (`MetalRenderHost.Replay.cs`). The host refuses, and the draw takes the full path, when anything that binding stood on has moved: the command buffer, the render pass, the image cache's binding epoch or image set, a read-only buffer's or vertex stream's read-binding memo answer, or the stage object. Draws with written buffers, storage images, movie planes, bindless tables, device addresses or per-draw argument fields are never captured. The `[METAL-V2][TBDR]` line reports the engine's `draw_replays` / `replay_miss` and the host's `replay_host=(draws,captured,capture_refused=[...],miss=[...])`. Needs the command thread (`SHARPEMU_METAL_V2_COMMAND_THREAD`, on). `0` binds every draw in full. | | `SHARPEMU_DISPATCH_REPLAY` | on | The same for a compute dispatch that repeats the one before it in all but its user data and thread limits: its shader data is built again from its own snapshot, and a dispatch that writes takes its buffers' whole binding chain again (a range other than the captured one rewrites the argument buffer, counted as `rebound`). Reported as `dispatch_replay_host=(...)` on the same line. `0` binds every dispatch in full. | +| `SHARPEMU_METAL_V2_TABLE_REPLAY` | on | A replayed dispatch of a program that reads a flattened resource table may carry a new table: the host rewrites the argument buffer with the new table instead of binding the dispatch in full (upstream c30081163). Counted as `table=` in `dispatch_replay_host`. `0` binds such dispatches in full. | +| `SHARPEMU_METAL_V2_INDEXED_RUNS` | on | A run of up to 32 indexed draws that differ only in their index offsets is encoded with the bindings of its first draw where every stage can share them (upstream's indexed draw runs). Runs are refused while predication or an occlusion query is open. Counted as `indexed_runs=(taken,draws,shared_stages,refused_stages)` on the `[METAL-V2][TBDR]` line. `0` records each draw on its own. | +| `SHARPEMU_DEFERRED_DISPATCH_RUNS` | on | Upstream's deferred dispatch runs and their worker threads. Hosts that defer whole work items, Metal among them, never create them; the switch matters only for hosts that record on workers. `0` turns them off everywhere. | +| `SHARPEMU_COMPUTE_TICKETS` | on | Upstream's worker rebinds for direct dispatches ahead of the command thread (`verify` checks each ticket against the command thread's own rebind). Like deferred runs they are not created for hosts that defer whole work. `0` turns them off. | | `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is taken out of the dispatch path at its place in the stream. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,busy=...,host_store=...]`. `0` runs every such kernel as a dispatch. | | `SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE` | on | How a posted word copy is applied. Upstream's Vulkan host stores the words on the host, which is sound there because GPU readers take a copy of their bytes when recorded. Metal reads guest memory in place, so the store is taken only when no recorded or submitted GPU work remains (`host_store`); otherwise the copy is refused as `busy` and runs as its dispatch, which readers read through as a pending copy. `0` posts every copy as a held command-processor write instead, which costs Demon's Souls about 20 ms a frame. | | `SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS` | on | A look-ahead resolution, and the render thread's clean read, take words a pending command-processor write still owes from that write's overlay when it covers them whole, instead of abandoning the resolution or waiting for the GPU. Counted as `concurrent_overlay_reads` and `clean_overlay_reads`. `0` abandons and waits as before. |