Repository navigation
Conversation
… (#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.
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.
* 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 <root>/<title id>, 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.
* [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.
* [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.
…mage 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.
…eap (#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)
…raphics 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>
…old and the producer nap
…row it on repeated dropouts
…is below half its reserve
…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.
… instead of the dropout reserve
…r output takes it
… over presented frames
…localized text and controller prompts
…ncoded images in the overlay kit
…uts, typed text and localized layouts
* 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>
…s contraction test checks The Metal twin of upstream's Gen5FloatContractionTests (cb790c3): a vertex program keeps #pragma clang fp contract(off) even when SHARPEMU_MSL_CONTRACT=1 lets pixel and compute programs fuse.
…utput 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.
…rop 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.
… 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.
…ed branch-walk reads on MSL
Port of upstream c88d6b0'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.
Port of upstream 3cc24a9'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.
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.
…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.
Upstream 94d833d 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.
… allocating each copy Port of upstream c300811 (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.
…aced table Port of upstream c300811 (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.
… image each time Port of upstream 957d1dc. 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 cb790c3 (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.
…alue Port of upstream cb790c3 (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.
…e overlaps release images Port of upstream c300811 (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.
…nd across the split, IME typed text, launch variables
… pools for whole-work hosts Upstream c300811'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.
Port of upstream c300811/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.
…vice, Bluetooth Opus reports Port of upstream cb790c3 (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.
…iled guest map's log Port of upstream d364227. 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.
… 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.
… 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.
…rame aliases in the Metal image cache
…Kit for the DualSense audio
…, GCMotion orientation, one rumble path, signal FP control # Conflicts: # src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs
…ed posted copies, deferred dispatch run off-switch
📦 Build artifacts —
|
| Platform | Download |
|---|---|
| macOS (osx-x64) | sharpemu-osx-x64-3e9f2a0 |
| macOS app bundle (osx-x64) | sharpemu-osx-x64-app-3e9f2a0 |
From build run #474. Downloads require a GitHub login and expire after 90 days.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Before submitting
Please read our contribution guidelines before opening a pull request:
➡️ CONTRIBUTING.md
By opening this pull request, you confirm that you have read and agree to follow the contribution guidelines.
Summary
Merges upstream sharpemu/sharpemu main up to 1d2fa2a (35 commits past f1af467, including the 0.0.8-ember version bump) and ports what upstream wrote for its Vulkan, SDL and Windows/Linux hosts to Metal and macOS. After this PR
Directory.Build.propssays0.0.8-ember, so av0.0.8-embertag on main publishes the release.Upstream in this range: faster command stream, compute dispatches and render slices; the Demon's Souls PR #1172 (GPU, audio, pad and memory fixes, DualSense speaker and vibration); PS4 and PS5 PKG installers; the in-game overlay kit with the save data list, IME on-screen keyboard and notification cards; AudioOut2 device cushion and dropout reserve; pad rumble from vibration-port audio; the integer reciprocal fix; Xbox glyphs and "launch with variables" in the GUI.
What needed a port
Every item is on by default; the switches are described in
docs/macos/configuration.md.SHARPEMU_METAL_V2_SAMPLED_DEPTH_CLEAR). Aliases the current frame or the two before it used stay cached instead of being written back and rebuilt every frame (SHARPEMU_METAL_V2_FRAME_ALIASES).SHARPEMU_METAL_V2_TABLE_REPLAY); indexed draw runs share bindings on the Metal host (SHARPEMU_METAL_V2_INDEXED_RUNS); posted word copies rent their buffers from a pool. Upstream's deferred dispatch runs got an off-switch (SHARPEMU_DEFERRED_DISPATCH_RUNS) and, like compute tickets, are not created for hosts that defer whole work items.1.0f / xwas 1 ulp high on 708 of 8012 inputs on the device, now 0. Upstream's new compiled resource-branch walk read guarded words without marking them, which silently turned off the fork's refusal of words a pending GPU write still owns (the Demon's Souls stream-stall fix); the walk marks them again.PadHaptics, timed,SHARPEMU_HAPTIC_RUMBLE_GAIN); upstream's unusedHapticRumbleis removed.IHostViewMemory.QueryAccessreads the macOS region table and is tested against the kernel's protection. A failed direct map logs the host regions over the range and whether it touches the macOS 27 carveout.How conflicts were resolved
YieldsToOlderWork), dispatch chain lists and speculative program refusals added beside them.AGENTS.md(Vulkan/Windows oriented) is replaced by this fork's.SharpEmu.Libsinto the Vulkan project; SDL code stays insrc/adapters. SkiaSharp is now referenced bySharpEmu.Libsfor the overlay kit (it already ships in the bundle through Avalonia).No port needed
FlushSlice: Metal'sFlushis already the coalesced stream flush.Testing
Tip 97e6b87, base M4 with 24 GB.
uvx reuse lintclean; Release build 0 errors; Python build-tool tests pass.dotnet testper project, all pass: Libs 11838, ShaderCompiler.Metal 5066, ShaderCompiler 2979, Gpu.Metal 2229, Host.Memory 488, Application 124, GpuRemote 59, GpuSplit 45, SourceGenerators 36, LeakTests 19, Fonts 13.SHARPEMU_TEST_REQUIRE_DEVICE=1on this tip: ShaderCompiler.Metal 5066/0. Gpu.Metal 2225 pass, 4 fail: the threeMetalClearFoldingTeststhat fail the same way on main, andMetalImageBudgetTests.TheHostReadingIsLive, which asserts the test host's footprint is below physical memory and fails in a full device run on this machine. The new overlay, image, replay and indexed-run device tests pass.scripts/macos/build-app.shbuilds the bundle; the macOS output policy accepts SkiaSharp inSharpEmu.Libs.Not covered
Checklist
By submitting this pull request, you confirm that:
CONTRIBUTING.md.N/A.N/A).