Commit graph

4,790 commits

Author SHA1 Message Date
Lib
f2bb58e502 system: remove dead s_startup_cancelled atomic and its guards
s_startup_cancelled is an atomic_bool static that has been a dead
flag since the swanstation fork's first import. The codebase only
ever:

  - Reads it (3 sites: 2 error-report guards, 1 mid-boot bail-out)
  - Stores false to it once, in System::Boot()

It is never stored as true anywhere. The flag is therefore
permanently false, every IsStartupCancelled() call always returns
false, every '!IsStartupCancelled()' guard always evaluates true,
and the one positive guard ('if (IsStartupCancelled()) Shutdown()')
is unreachable.

The comment at the unreachable bail-out gives away the origin:
'shading compilers took too long and the user closed the
application'. That refers to upstream DuckStation's native UI,
where a GUI thread could set the flag while shader compilation
ran on the boot thread. swanstation is libretro-only - it has no
equivalent UI thread, no way for a frontend to interrupt boot
mid-flight, and no path that ever flips the flag to true.

Drop the lot:

  - s_startup_cancelled static
  - IsStartupCancelled() function and its system.h declaration
  - s_startup_cancelled.store(false) in Boot()
  - The three '!IsStartupCancelled()' / 'IsStartupCancelled()'
    guards. The two error-reporting guards become unconditional -
    if Boot() or CreateGPU() fails, we always want to surface the
    error to the user, which is the behaviour we already had since
    the guard was never satisfied. The mid-boot bail-out branch
    was unreachable and is removed entirely.

Linux x64 build still warning-clean. .so size drops from 8048544
to 8048432 bytes (-112) from removing the dead branches. 25
retro_* exports unchanged. Behaviour is identical.
2026-05-08 06:25:29 +02:00
Lib
9987a7cd74 cheats: reset the global scratch register file on cheat-lifecycle changes
cheats.cpp keeps a 256-entry global u32 scratch register file
(cht_register) that the GameShark v3+ instruction families D7 / 0x51 /
0x52 use for conditional writes and indirect memory operations
(load-from-address-into-register, write-register-to-address,
register-arithmetic, etc.).

cht_register is a TU-local static, so it has the lifetime of the
process. None of the existing cheat lifecycle paths reset it:

  - System::Shutdown() releases s_cheat_list directly via
    s_cheat_list.reset() but leaves cht_register holding whatever
    the previous game's cheats wrote.
  - System::SetCheatList(...) replaces the cheat list (libretro
    retro_cheat_reset takes this path with nullptr) without
    touching the registers.
  - System::Reset() leaves the registers alone, which is fine
    (in-game power cycle keeps cheat state) but only by accident.

The result: a register-using cheat from game A leaves state behind,
and a register-using cheat in the next game B that reads before
writing will pick up game A's bytes. The bug is rare in practice
because most cheats are simple ConstantWrite or compare-and-write
that don't touch the register file, but it is a real correctness
issue and trivial to fix.

Add CheatList::ResetSharedScratchRegisters() that fills the array
with zeros, and call it from both:

  - System::Shutdown after s_cheat_list.reset() - covers the
    standard 'core teardown between games' path.
  - System::SetCheatList - covers retro_cheat_reset and any other
    full-list replacement, so toggling cheats off mid-session
    also gets a clean register state for the next set.

Both calls are present (rather than picking one) because Shutdown
goes through .reset() directly, not through SetCheatList, so a
single-site fix would miss one of the two paths. The cost is a
1 KB fill on each call, neither of which is hot.

Linux x64 build still warning-clean. .so grew from 8048480 to
8048544 bytes (+64) for the new tiny function and two call sites.
25 retro_* exports unchanged.
2026-05-08 06:06:03 +02:00
Lib
06db81cf26 cpu_core: drop constexpr from GPRRegisterOffset / GTERegisterOffset
The previous attempt at fixing the macOS constexpr-offsetof failure
(commit 238a387) reformulated 'offsetof(State, regs.r)' as
'offsetof(State, regs) + offsetof(Registers, r)' on the theory that
breaking the compound member access into two direct-member offsetofs
would satisfy Apple Clang's stricter constexpr-offsetof check. It did
not - Apple Clang still rejects it with the same diagnostic:

  cpu_core.h:87: error: constexpr function never produces a constant
                 expression
    return offsetof(State, regs) + offsetof(Registers, r) + ...
  note: cannot access field of null pointer

The arrow points at offsetof(Registers, r). Even though r is the
first member of an anonymous union directly inside Registers (and
thus a direct member of Registers for member-name-lookup purposes),
Clang's constexpr evaluator implements offsetof as a walk from a null
pointer and refuses to walk through a union member - anonymous or
otherwise - because reading union members through a null pointer is
undefined per the C++ standard. GCC chooses to elide that check;
Clang chooses to enforce it. The same applies to GTE::Regs::r32,
which lives in a (named) union for the same reasons.

So the two-offsetof composition does not actually solve the macOS
build break that 238a387 advertised it as fixing. The real fix is to
admit that this is not a constexpr operation in standard C++ and stop
pretending it is.

Drop constexpr. Every call site (six in cpu_recompiler_code_generator
.cpp, two in _generator_generic.cpp) passes a runtime u32 to these
helpers - none use the result as a template argument, array size,
case label, or static_assert operand - so constexpr was decorative.

Verified the runtime cost is zero: the two inner offsetof calls are
compile-time constants regardless of the constexpr keyword on the
wrapper, the wrapper itself is a one-line static function the
compiler trivially inlines at -O3, and GCC -O3 codegen at every call
site is bit-for-bit identical with and without constexpr (sha256 of
cpu_recompiler_code_generator.o and cpu_recompiler_code_generator_
generic.o matches before and after the change). The comment block is
expanded to record exactly why this isn't constexpr so a future
maintainer doesn't 'fix' it back.

Linux GCC build still bit-for-bit identical (.so 8048480 bytes, 25
retro_* exports unchanged). The macOS Apple Clang build, which has
been broken since the static Makefile landed, should now compile.
2026-05-08 05:20:05 +02:00
Lib
06c0c666d8 core, common: silence Apple Clang warnings on the static-Makefile build
A pile of warnings turned up when the static Makefile build was run on
macOS with Apple Clang. None block compilation, but they are all real
and worth fixing:

  cdrom.cpp:1453: 'switch' on m_command_second_response (Command) only
    handles 6 of 27 enumeration values [-Wswitch]
  gpu.cpp:268,315: 'switch' on m_blitter_state does not handle the
    BlitterState::DrawingPolyLine case [-Wswitch]
  bios.cpp:123: missing braces around initialization of subobject -
    a bare 0 is being used to value-init a Hash struct [-Wmissing-braces]
  cdrom.cpp:1902,2050: unused variable 'pos' [-Wunused-variable]
  file_system.cpp:295: unused function 'FileSystemCharacterIsSane'
    [-Wunused-function]

For each:

  - ExecuteCommandSecondResponse: the unhandled commands deliberately
    have no second-response phase, or are cleared via
    ClearCommandSecondResponse before this fires. Add an explicit
    'default: break;' with a comment so a future reader knows the
    omission is on purpose.

  - GPU::UpdateDMARequest / GPU::UpdateGPUIdle: BlitterState::
    DrawingPolyLine is a real GPU state entered mid-command for
    polyline draws (set in gpu_commands.cpp). Without an explicit
    case, both functions fell through with the relevant GPUSTAT bits
    holding whatever values the previous state set - mostly correct
    by accident, since you reach DrawingPolyLine from Idle, but
    relying on that is fragile. Add explicit cases that match the
    semantics: DMA can keep delivering FIFO words (same as Idle), and
    the GPU is not idle.

  - BIOS GetImageInfo: openbios_info initialised the Hash subobject
    with a bare 0. Replace with {} to value-init the Hash explicitly.
    Same observable behaviour (zero-fills the 16 hash bytes), no
    warning, and clearer intent.

  - cdrom.cpp dead Position locals: both 'pos' variables have been
    dead since the swanstation fork's first import - they look like
    leftovers from log statements that were stripped before
    publication. CDImage::Position has no side-effecting constructor
    (it's a plain MSF triple), so removing them is safe. The second
    one was the entire body of an else branch, so the if-else
    collapses to a single-statement if.

  - FileSystemCharacterIsSane has been defined but never called
    since the same first import; just delete it.

Linux GCC build still bit-for-bit identical (.so 8048480 bytes,
25 retro_* exports unchanged).
2026-05-08 05:01:25 +02:00
Lib
238a38719c cpu_core: compose offsetof from direct members for constexpr correctness
Apple Clang fails the libretro build of the static Makefile path on
macOS:

  cpu_core.h:80:24: error: constexpr function never produces a constant
                    expression [-Winvalid-constexpr]
    static constexpr u32 GPRRegisterOffset(u32 index) {
      return offsetof(State, regs.r) + ...
    }
  note: cannot access field of null pointer

The compound member access form 'offsetof(State, regs.r)' is a GNU
extension that the C++ standard does not permit - per the standard,
the second argument to offsetof must be a direct (non-nested) member.
GCC accepts it as an extension and Apple Clang accepts it at runtime
too, but Apple Clang refuses it in a constexpr context, where the
implementation has to walk it as &((State*)nullptr)->regs.r and trips
the constexpr null-pointer check.

Compose the offset from two standard offsetof calls:

  offsetof(State, regs) + offsetof(Registers, r) + sizeof(u32) * index

Both 'regs' and 'r' (the latter being the first member of the
anonymous union directly inside Registers) are direct members of
their containing types, which is what the standard allows. The GTE
case is the same shape.

Verified the result is identical at runtime: x86_64 -O3 codegen for
the recompiler call sites is unchanged - the LEA still emits the
same '0xc(,%rdx,4),%ecx' pattern, where 0xc is offsetof(State, regs)
and offsetof(Registers, r) folds to 0 (it's the first member of the
first union). Linux GCC build is bit-for-bit identical (.so still
8048480 bytes, 25 retro_* exports). The fix unblocks the macOS
build without disturbing anyone else.
2026-05-08 05:01:20 +02:00
Lib
945e042d73 build: silence two long-standing build warnings
The libretro build emitted two warnings on every compile:

  dep/xxhash/src/xxhash.c:40: warning: "XXH_STATIC_LINKING_ONLY" redefined
  src/common/log.cpp:233:35: warning: ignoring return value of
    'ssize_t write(int, const void*, size_t)'
    declared with attribute 'warn_unused_result' [-Wunused-result]

Both are real, fixable, and unrelated to the rest of the audit, but
nice to clear out so a future regression actually shows up against a
clean baseline.

xxhash.c starts with its own '#define XXH_STATIC_LINKING_ONLY' to
unlock the advanced API for instantiation. Makefile.libretro was
already passing -DXXH_STATIC_LINKING_ONLY on the command line, so the
.c file's #define triggered a redefinition warning every time
xxhash.c was built. The flag in CFLAGS was unnecessary in the first
place: consumer code in this tree uses XXH64_state_t* opaquely and
calls only the public API (XXH64_createState, XXH64_reset,
XXH64_update, XXH64_digest), none of which require the advanced
declarations. Drop the -D from CFLAGS.

log.cpp's console-output path writes the formatted log line with a
bare write() and discards the return value. glibc declares write()
with the __wur (warn_unused_result) attribute, and a plain '(void)'
cast does NOT silence -Wunused-result on glibc - the compiler still
flags it (verified locally). The portable workaround that does
silence it is to capture into a named variable and then cast that to
void:

    const ssize_t written = write(outputFd, message, message_len);
    (void)written;

This is the right behaviour anyway: there is genuinely nowhere
meaningful to surface a write() failure from the log callback,
since the log callback IS the failure-reporting path. Add a comment
explaining why the assignment-then-discard form is used so a future
maintainer does not 'simplify' it back to a (void) cast.

Build is now warning-clean. .so size unchanged at 8048480 bytes,
25 retro_* exports unchanged.
2026-05-08 04:34:47 +02:00
Lib
46390d755d libretro: honour RETRO_ENVIRONMENT_GET_SAVESTATE_CONTEXT
Once the previous commit lit up RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE,
the frontend's single-instance runahead became functional with this
core - it no longer glitches audio or wastes GPU work on the discarded
frames. But the per-frame state restore was still going through the
slow path: every retro_unserialize ended up calling
CPU::CodeCache::Flush(), which deletes every JIT block, resets the
JIT code buffer, and recompiles the dispatcher from scratch. That is
the right thing for a state loaded from disk in a different session,
because the existing JIT cache might no longer match the loaded RAM.
But for runahead we know the state was produced moments ago by the
same binary in the same address space, so most of the JIT cache is
still valid - we just want to mark blocks as invalidated so
RevalidateBlock can re-link them lazily as they are dispatched.
System::DoState already has an is_memory_state=true codepath that
does exactly that (used by the in-core s_runahead_*/rewind machinery),
but the libretro retro_unserialize entry point had no way to reach it.

Wire it up:

  - System::LoadState gains an is_memory_state=false default
    parameter and threads it through DoLoadState to DoState. Existing
    callers (Boot::DoLoadState, internal LoadState path) are
    unchanged in behaviour.

  - retro_unserialize queries RETRO_ENVIRONMENT_GET_SAVESTATE_CONTEXT
    and sets is_memory_state=true when the context is one of the two
    runahead variants (RUNAHEAD_SAME_INSTANCE or RUNAHEAD_SAME_BINARY).
    Both guarantee 'same binary, same session' so reusing the JIT
    cache is safe.

  - ROLLBACK_NETPLAY is intentionally NOT routed through the memory
    state path. The spec says those states are loaded by a separate
    binary in a separate address space; conservative is safer.
    Frontends that don't implement the env call (or implement it but
    return NORMAL) take the existing slow path - no regression.

The win compounds: with single-instance runahead at, say, 4 frames,
every replay used to do four state loads each tossing the JIT cache.
Now the cache stays warm across the whole runahead window, and only
blocks whose RAM actually changed during the window need
recompilation. RevalidateBlock's existing hash check picks that up
correctly.
2026-05-08 04:02:38 +02:00
Lib
b80e337afe libretro: document Internal Run-Ahead redundancy with frontend run-ahead
The previous commit wired RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE,
which means the frontend's own single-instance run-ahead now works
correctly with this core. The frontend's implementation is generally
more efficient (it does not have to keep its own audio stream
redirected, save state, etc.) and supports both single- and second-
instance modes; the core's internal s_runahead_* machinery only
supports single-instance.

If a user has the frontend's run-ahead enabled and also leaves
Internal Run-Ahead at >0, both engines run, doubling the cost for
no benefit (and giving slightly worse latency, since the two
windows compose).

Update the option's info string to point users at the frontend's
run-ahead and explain when to use the internal version. Don't
remove the internal version yet - some libretro frontends do not
implement run-ahead, and existing user configs reference this
option, so deletion is its own future commit. This is purely a
description change to head off the foot-gun.
2026-05-08 03:45:29 +02:00
Lib
b5b5687f85 libretro: honour RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE
The libretro spec exposes a per-frame hint that lets the frontend
tell a core 'skip your audio and/or video output for this run, the
result will be discarded'. The frontend uses this for single-
instance runahead (serialise -> retro_run with AV cleared ->
unserialise to restore), fast-forward past audio, and a few other
skip-frame mechanisms. The contract is:

  - simulation must still run (state must remain identical to a
    not-skipped frame at the end of retro_run, so the frontend can
    unserialise back to the same point cleanly)
  - the audio and video output callbacks should be suppressed for
    that frame so the user does not hear a one-frame glitch and
    the host does not waste GPU work uploading a frame that will
    be thrown away

This core never queried that callback, so the frontend's single-
instance runahead with this core has always produced an audible
audio glitch on every replay (the discarded frames' audio still
made it to the output buffer) and wasted GPU bandwidth on video
frames the frontend immediately discarded.

Wire it up:

  - libretro_host_interface.cpp: at the top of retro_run_frame(),
    query GET_AUDIO_VIDEO_ENABLE and cache the two skip flags. If
    the env call returns false (old frontend, callback not
    supported) default to 'don't skip', matching the spec.

  - libretro_audio_stream.cpp: in both UploadToFrontend (fast-hook)
    and FramesAvailable (slow-hook), gate the
    g_retro_audio_sample_batch_callback call on the audio-skip
    flag. We still drain the FIFO either way so the SPU side does
    not accumulate backpressure across the runahead window.

  - libretro_host_display.cpp: in Render(), gate the
    g_retro_video_refresh_callback call on the video-skip flag,
    and gate the nullptr-frame branch as well. The HW renderers'
    GPU state has already been produced by the time Render() is
    reached and remains intact for the next live frame; the SW
    renderer's framebuffer is frontend-owned, so we still
    ClearDisplayTexture() on the SW path to keep the next frame's
    SetDisplayTexture() replacing the handle cleanly.

This does not affect the core's internal s_runahead_* runahead
machinery (that still works as before, gated on
g_settings.runahead_frames). It only enables the frontend-side
runahead to actually function correctly with this core, which it
never did. The two are still redundant when both enabled - that
will be addressed separately.
2026-05-08 03:45:25 +02:00
Lib
6e31230b1e controllers: cover remaining runahead-replay-flag gaps for axes and lightgun position
Three input paths still left runahead unaware of changes after
last session's button-state fix:

- NeGcon::SetAxisState. The NeGcon's steering axis is the primary
  input for the racing games it ships with; NeGconRumble's
  equivalent setter does signal replay, but the older NeGcon was
  forgotten when SetRunaheadReplayFlag was originally added. Without
  the signal, every twist of the wheel during a runahead window
  replays with stale steering for one frame.

- LibretroHostInterface::UpdateControllersGunCon. The cached
  m_display mouse position is what NamcoGunCon::UpdatePosition
  reads during a SIO Transfer to compute the gun's beam-tick /
  scanline pair, so the host position is part of the PSX-visible
  input fingerprint that runahead has to track. A position change
  with no button change would otherwise leave s_runahead_replay_pending
  false and the replayed simulation aimed at last frame's pixel.

- LibretroHostInterface::UpdateControllersPlayStationMouse. The
  raw libretro mouse delta is non-zero whenever the user moved the
  mouse this frame, and PlayStationMouse::UpdatePosition reads the
  cached display position during Transfer to derive the per-frame
  delta the PSX sees. Same runahead-flag issue: without a signal,
  replays use the previous frame's mouse motion instead of the
  current one.

The negcon axis fix uses the same compute-then-compare pattern as
the existing axis setters in AnalogController, AnalogJoystick and
NeGconRumble. The two libretro-side fixes do the comparison
inline against the already-cached display position rather than
adding system.h to host_display.h's transitive include set, which
would be a non-trivial compile-time hit on every TU that pulls in
the display interface.
2026-05-08 03:23:22 +02:00
Lib
2d95d8490a libretro: rename Audio_FastHook option to be self-explanatory
The option was labelled "Use Alternative Audio Hook", which gives
the user no way to know what's alternative to what, what the
default is, what the toggle changes, or which way to flip it if
something breaks. The description was also slightly broken
grammatically ("a faster and more efficient to submit audio
samples" is missing a word) and vague about the failure mode
("may hang for a select few games").

Rename to "Use Per-Frame Audio Batching" so the label describes
what the option actually controls (batched per-frame submission via
LibretroAudioStream::UploadToFrontend, vs the slow path where
FramesAvailable forwards each SPU chunk to the frontend as it's
produced). Rewrite the description to:

  - explain both modes structurally so the user can decide
  - name the actual symptom (hangs at boot)
  - name the known-affected games (Formula 1, Formula 1 '97)
  - point out that the auto-fix table at libretro_game_settings.cpp
    already disables this option for those titles, so the user
    rarely needs to touch it manually.

No behaviour change. Same key, same default, same Enabled/Disabled
values - this is purely the user-facing label and info string.
2026-05-08 03:23:08 +02:00
Lib
e0dca36f10 controllers: fix runahead-replay flag for non-pad input devices
Runahead works by speculatively running the simulation N frames ahead
of what the user sees, then if input changes between when a frame was
originally polled and when it would actually be displayed, replaying
from a save state with the corrected input. The replay decision is
driven by System::SetRunaheadReplayFlag(), which controllers are
expected to call from their input setters whenever a stored input
value actually changes.

DigitalController, AnalogController, AnalogJoystick, and NeGconRumble
all do this correctly in their SetButtonState handlers. Three
controllers did not, and one had a subtle bit-mismatch bug:

- NeGcon::SetButtonState ignored the runahead system entirely, so any
  NeGcon button press during a runahead window was silently lost
  (the replay would re-run with the original, stale m_button_state).

- PlayStationMouse::SetButtonState had the same omission.

- NamcoGunCon::SetButtonState had the same omission, with the extra
  twist that ShootOffscreen recursively calls SetButtonState for the
  Trigger, so an offscreen-shot input change would also be missed by
  runahead.

- NeGconRumble::SetButtonState did call SetRunaheadReplayFlag, but
  the flag check ran against (1u << button) - the raw enum value -
  while the actual flip was against (1u << indices[button]), where
  indices remaps the button to non-contiguous bit positions
  {3,4,5,6,7,11,12,13}. The two bits never coincide, so the flag
  fired on whatever happened to live at indices[0..7] in
  m_button_state instead of the bit being changed: simultaneously
  flagging unrelated changes and missing real ones.

All four are fixed using the same pattern that's now consistent across
all controllers: compute the new state, signal replay only if the
state actually changed, then commit. The cleaner write-once formulation
also incidentally guards against the bit-mismatch class of bug for
future maintainers.
2026-05-08 02:48:21 +02:00
Lib
66ee835d3f core: mark TU-local globals static
Three file-scope variables had external linkage by accident:

- bus.cpp m_ram_code_page_count (set in 2 places, read from a hot
  loop in a 3rd). Mirror file declares m_ram_code_bits as extern
  for cross-TU use by cpu_code_cache, but m_ram_code_page_count
  has no header counterpart and zero references outside bus.cpp.

- cpu_code_cache.cpp s_asm_dispatcher and
  s_single_block_asm_dispatcher. Six references total, all in the
  same TU. The 's_' prefix already signals "static" in this
  codebase's convention; the missing static keyword was an
  oversight, since the file's other s_-prefixed globals
  (s_code_buffer, s_fast_map, s_fast_map_pointers, s_blocks) all
  have the keyword.

Internalising these gives the compiler license to keep the values
in a register across the loops that read them (the storage no
longer might be modified by another TU between iterations) and
removes three weak symbols from the .so's symbol table. nm before
the change reports them with a capital B (BSS, external); after,
lowercase b (BSS, local).

The .so is +8 bytes (8048368 vs 8048360) - probably alignment
shuffle in .bss between the now-internal symbols and the rest.
25 retro_* exports unchanged.
2026-05-08 02:33:05 +02:00
Lib
449c6bd2c3 cd_xa: read 32-bit ADPCM word in a byte-order-independent way
The XA-ADPCM decode path read each 32-bit packed-nibble word from
the raw sector with std::memcpy into a u32 and then shifted it by
(block * 4) or (block * 8) to extract the right nibble. The
existing comment was "NOTE: assumes LE" and that note was correct:
on disc the words are little-endian, so on a little-endian host the
memcpy gives the host-order value the shift expects, but on a
big-endian host the same memcpy gives a byte-reversed value and the
subsequent shift selects the wrong nibble - every XA-ADPCM block
on big-endian would produce nonsense audio.

Build the u32 explicitly from the four constituent bytes so the
result matches the on-disc little-endian layout regardless of host
byte order. The shift indexes the same logical nibble on every host.

The compiler still recognises the byte-by-byte assembly as a
4-byte unaligned little-endian load and folds it accordingly: the
LE codegen is bit-for-bit identical to the previous memcpy version
(same .o size, same instruction count, same number of movzbl
loads). On big-endian, the source now does the right thing without
needing an MSB_FIRST branch - the byte-reassembly is what
big-endian builds would have to write anyway.
2026-05-08 02:20:16 +02:00
Lib
494206601a common: wire MSB_FIRST through to actual byte-order-dependent code
The MSB_FIRST opt-in flag was introduced in 46b57e3 as a build-system
gate but no source files were converted to use it. This commit wires
two genuinely byte-order-dependent paths through the new gate:

- CDImageCHD::CopyAndSwap: CHD stores CD audio sectors in big-endian
  byte order. The previous implementation always swapped, gated only
  by an architecture (CPU_X64 / CPU_AARCH64 / CPU_X86 / CPU_ARM) ladder
  that selected the swap width but had no big-endian fallback. On a
  hypothetical big-endian host this would corrupt every CHD audio
  sector by swapping data that was already in host order. Now the
  whole swap is bracketed by #ifdef MSB_FIRST: on big-endian hosts the
  function reduces to a plain std::memcpy (the disassembly under
  -DMSB_FIRST=1 confirms this - the inlined byte-swap loop is replaced
  with a single rep movsq), on little-endian hosts the existing
  width-tiered swap is unchanged. The architecture macros now select
  width within the LE branch, which is what they were always actually
  testing for.

- md5_digest.cpp: the bundled Plumb MD5 reference uses HIGHFIRST as
  its compile-time gate for the per-block byte-reverse pass. Nothing
  in the build defined HIGHFIRST, so on a real big-endian host MD5
  would silently produce wrong digests. Wrong digests break BIOS
  recognition (bios.cpp), GL shader cache lookups
  (gl/shader_cache.cpp), Vulkan shader cache lookups
  (vulkan/shader_cache.cpp) and the D3D11/D3D12 shader caches. Map
  MSB_FIRST to HIGHFIRST so the byte-reverse pass activates exactly
  when the rest of the codebase expects big-endian behaviour.

Verified that both default (LE) and -DMSB_FIRST=1 builds compile
cleanly with no warnings and produce 8048360-byte .so files with
25 retro_* exports each. The LE .so is bit-for-bit identical to the
pre-change LE .so since neither change has any effect on the LE path.
2026-05-08 02:04:41 +02:00
Lib
9dcc2ee222 gpu_backend: remove unused g_gpu_backend global
The translation unit defined a file-scope std::unique_ptr<GPUBackend>
named g_gpu_backend, but no code anywhere in the tree references
it - it is not declared in any header, not assigned, not read, and
not extern'd. It is purely a leftover from an older design where
the GPU backend was a top-level global rather than a member of
GPU_SW (where it now lives as GPU_SW::m_backend, by value).

Removing the global drops 248 bytes from the .so (the static
unique_ptr storage in .bss plus the .fini_array entry registered
to destroy it on library unload). 25 retro_* exports unchanged.
2026-05-08 02:04:35 +02:00
Lib
1ff0911dc8 libretro: clean up after BootSystem if disk-control parse fails
retro_load_game has five early-return paths after BootSystem
succeeds: GetMediaFileName empty (twice, once for the parent of
sub-images and once for the simple-image case), GetMediaSubImagePath
or GetMediaSubImageTitle empty inside the sub-image enumeration
loop, and FileSystem::GetFileTitleFromPath empty for the simple
image. Each of these returned false directly, leaving a fully
booted system - audio stream up, GPU thread running, recompiler
buffers allocated, CDROM async reader thread spinning - while the
frontend was told the load failed.

The leak is bounded by retro_deinit eventually calling
HostInterface::Shutdown -> System::Shutdown, but the libretro
contract permits a frontend to call retro_load_game again after a
prior call returned false (treating it as a fresh attempt with no
prior state). In that scenario the second BootSystem would step
on the still-running first system, since System::Boot
unconditionally sets s_state=Starting without first tearing down
an existing system.

In practice these returns are reachable when a CD image's metadata
is malformed: GetSubImageMetadata can return an empty string for
either the file_path or title field, which is then caught here
and turned into a load failure. Calling DestroySystem on each of
those paths releases everything the BootSystem call acquired
before propagating the failure to the frontend.

No build / exports changes (8048608 bytes, 25 retro_* exports).
2026-05-08 01:15:27 +02:00
Lib
7237a6bf00 core, libretro: replace auto with explicit types where it improves clarity
Four sites where the type is short and meaningful, and the auto
deduction was actively obscuring what was being declared:

- analog_joystick.cpp DoState: the local copy of m_axis_state is
  now declared with its real type
  std::array<u8, static_cast<u8>(Axis::Count)>, matching the
  declaration in the header.

- psf_loader.cpp (3 sites): TagMap is a typedef defined in the
  same file as the consumers, and TagMap::const_iterator is the
  natural way to spell what these locals hold. The auto added
  nothing.

- libretro_host_interface.cpp retro_get_memory_data: the memory
  card and its data array are pulled out of g_pad. Spelling them
  as MemoryCard* const card and MemoryCardImage::DataArray& data
  makes the lifetime and ownership of the returned pointer
  immediately legible at the call site.

- cpu_code_cache.cpp: the pagefault handler dispatch table uses
  Common::PageFaultHandler::Callback, the named function-pointer
  typedef from page_fault_handler.h. Using the typedef ties the
  declaration to the InstallHandler signature it is fed into,
  which is the whole point of the typedef existing.

Other auto sites in the tree were left alone because removing
them would either be impossible (structured bindings, lambda
declarations, std::tie results), redundant (DRY rule for
make_shared/make_unique/static_cast where the type is in the
RHS), or actively worse (verbose STL iterator spellings,
xbyak/vixl operand expression types).

Build and exports unchanged.
2026-05-08 00:54:25 +02:00
Lib
46b57e3486 build: add MSB_FIRST opt-in flag for big-endian hosts
All currently-supported swanstation targets - x86, x64, AArch32 LE,
AArch64 LE - are little-endian, and there is no plan to ship a
big-endian build today. To make endian-conditional code possible
without paying a runtime cost on the LE targets, add a single
opt-in compile flag rather than autodetecting at configure time:

- src/common/types.h is a universally-included header. It now
  documents the convention and reserves the macro name. There is
  deliberately no LSB_FIRST counterpart - little-endian is the
  unmarked default. Code that needs byte-order-conditional behaviour
  branches on  only, so the LE path is the
  unconditional default.

- Makefile.libretro forwards MSB_FIRST=1 from the make command line
  to -DMSB_FIRST=1 on the compiler.

- CMakeLists.txt exposes a CMake option(MSB_FIRST OFF) that does
  the same via add_definitions(-DMSB_FIRST=1).

No source files use the macro yet; this commit only puts the gate
in place. Existing endian-dependent code (e.g. CDImageCHD's audio
sector byte-swap) can be converted in follow-up patches once the
flag is available.

Verified: builds clean both with and without MSB_FIRST=1; .so
size, exports unchanged on the default LE path.
2026-05-08 00:32:03 +02:00
Lib
9640ed12a6 core: make hot-path lookup tables constexpr
Several function-local lookup tables in the SPU, MDEC and GTE were
declared as plain "static" rather than "static constexpr". Under
C++11 every function entry to a function with a non-constexpr
function-local static must check (and on first entry initialize) a
hidden guard variable - one acquire-load plus a conditional branch
on every call, even after initialization is complete. nm confirms
the guard symbols (_ZGV...) were emitted for each of these tables
in the previous build; making them constexpr places the data in
.rodata directly and removes the guards entirely.

The four tables touched are all on hot paths:

- SPU::Voice::DecodeBlock filter_table_pos / filter_table_neg:
  hit once per ADPCM block per active voice (~200/sec per voice
  across 24 voices)

- SPU::Voice::Interpolate gauss[0x200]: hit once per output sample
  per voice (44100 Hz x 24 voices ≈ 1M calls/sec)

- SPU::UpdateNoise noise_wave_add / noise_freq_add: hit once per
  SPU tick (44100 Hz)

- MDEC::DecodeRLE_Old zagzig: hit per macroblock during MDEC video
  decode (FMV path)

- GTE UNRDivide unr_table[257]: hit on every RTPS / RTPT / DPCS /
  DPCT / DCPL / GPF / GPL / SQR instruction - effectively the
  entire 3D transform path

After the change, nm src/core/{spu,mdec,gte}.o reports zero _ZGV*
guard symbols. .so size unchanged, exports unchanged.
2026-05-08 00:31:59 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre
3d0c32d22d Hope this fixes the GTE timing somewhat 2026-05-07 23:51:55 +02:00
Lib
90b43bfd3b host_display: drop unused m_display_changed flag
m_display_changed was being set in three places (ClearDisplayTexture,
SetDisplayTexture, SetDisplayParameters) but read in none. Pure dead
code - the change-detection it would have supported is handled
elsewhere: aspect-ratio and throttle-frequency tracking lives in
LibretroHostInterface, and the libretro frame-dupe path is gated on
HasDisplayTexture() directly.

Drop the field and the three writes.
2026-05-07 23:50:24 +02:00
Lib
eddd6a8db8 audio_stream: drop unused m_max_samples field
m_max_samples was used by the back-pressure CV-wait predicate that
was removed in commit 8bebcfb ("audio_stream: remove unreachable
wait on never-notified condvar"). Nothing reads it any more; it
was being computed and stored on every Reconfigure() and never
consulted again.

Drop the field. The capacity check inside SetBufferSize() now uses
the temporary directly, and a comment documents why the 2x headroom
is still being enforced (defensive: core options can request larger
audio_buffer_size values, and a misconfigured request needs to
fail rather than silently overflow the FIFO).
2026-05-07 23:50:20 +02:00
Lib
a8e4ba0818 libretro: align HW renderers with SW path on no-display-texture frames
When the PSX has no display to scan out (display-disabled, mid-mode-
change gap, just-after-reset, etc.), HasDisplayTexture() returns
false. Pre-existing behavior diverged sharply between renderers:

  SW path  (libretro_host_display.cpp::Render):
    g_retro_video_refresh_callback(nullptr, 0, 0, 0);     // frame dupe

  HW paths (gpu_hw_{opengl,d3d11,vulkan}.cpp::Render):
    glClear / vkCmdBeginRenderPass(clear) / D3D ClearRT
    g_retro_video_refresh_callback(RETRO_HW_FRAME_BUFFER_VALID, ...);

The HW paths sent a black-cleared FBO every time the display was
disabled. From the libretro frontend's perspective these are two
completely different signals - frame-dupe means "hold the previous
frame on screen" (visually a freeze), while a black FBO is a
distinct new frame (visually a flash). For identical emulation
state, switching backends therefore changed the kind of output the
core produces.

Have all three HW backends short-circuit to the same nullptr
frame-dupe call the SW path uses. The cursor-overlay branch
collapses with this change since it was guarded by HasDisplayTexture()
anyway; the early return makes that explicit.
2026-05-07 23:13:32 +02:00
Lib
3819add7c0 libretro: re-issue SET_SYSTEM_AV_INFO when PSX vertical refresh changes
retro_run_frame() was watching the display aspect ratio for changes
and calling UpdateGeometry() (RETRO_ENVIRONMENT_SET_GEOMETRY) when
it shifted, but it was not watching System::GetThrottleFrequency().
The PSX CRTC config can change mid-game (NTSC <-> PAL detection,
interlace toggle, overclock change), and that updates the vertical
refresh that the libretro frontend uses to drive its audio
resampler.

SET_GEOMETRY only carries the geometry struct - the timing struct,
which holds .fps and .sample_rate, is only delivered via
SET_SYSTEM_AV_INFO. Without re-issuing the latter, the frontend
keeps resampling audio at whatever fps it learned at boot, and the
audio gradually desyncs from video after any mode change.

Track the last advertised throttle frequency in
m_last_throttle_frequency and compare it post-RunFrame. When fps
has changed, call UpdateSystemAVInfo() (full av_info update);
otherwise fall back to UpdateGeometry() for aspect-only changes,
which is much cheaper on most frontends because it doesn't tear
down the rendering pipeline.

The new field is initialized in retro_get_system_av_info() and
kept in sync from UpdateSystemAVInfo() so its baseline matches what
the frontend was last told.
2026-05-07 22:54:02 +02:00
Lib
bbde546dfd audio_stream: remove uncontended mutex from FIFO path
The libretro core is single-threaded by design: the SPU is driven by
TimingEvents from the same thread that runs retro_run_frame(), and
both AudioStream subclasses (LibretroAudioStream, NullAudioStream)
are libretro-only - no separate audio output thread exists. There
is no producer/consumer scenario that requires synchronization on
this FIFO; the mutex was always uncontended.

Even an uncontended std::mutex is not free: each lock/unlock pair
issues an atomic CAS plus the indirect call through libpthread.
With the SPU calling BeginWrite/EndWrite roughly 300 times per
frame (one per scheduled audio slice), that's ~600 atomic ops and
~15 us of pure overhead on every retro_run.

Drop the mutex, the std::unique_lock wrappers in Reconfigure() and
Shutdown(), the surrounding #include <mutex>, and the redundant
lock in NullAudioStream::FramesAvailable(). The header now matches
its actual constraints: a single-threaded FIFO.

If anyone ever reintroduces a threaded audio path, they will need
to add synchronization back. The comment in audio_stream.h
documents that requirement explicitly so the choice is not silently
forgotten.
2026-05-07 22:53:58 +02:00
Lib
8bebcfb6d9 audio_stream: remove unreachable wait on never-notified condvar
AudioStream::BeginWrite() used to wait on m_buffer_draining_cv when
the FIFO didn't have enough free space for the requested batch.
Nothing in the codebase ever calls notify_one()/notify_all() on that
condition variable, so the wait could only return spuriously, and on
implementations without spurious wakeups the SPU would deadlock the
moment the buffer truly filled up.

It does not fill up in practice today - the libretro path drains
the buffer in full once per retro_run via UploadToFrontend(), and
m_max_samples is set to 2 * audio_buffer_size (default 4096),
several times smaller than the FIFO capacity (32 768). But 'cannot
happen today' is not a safe contract to leave in production code,
especially when the failure mode is a hard hang.

Drop the CV entirely and rewrite BeginWrite() to be non-blocking.
It now hands the SPU whatever contiguous space the FIFO currently
exposes (capped at m_buffer_size); EndWrite() records the count
the caller actually used, exactly as before. The SPU's outer loop
in spu.cpp already calls BeginWrite/EndWrite repeatedly until all
generated frames are consumed, so a short return is benign.

The mutex is kept: in libretro mode producer and consumer run on
the same thread (retro_run_frame), so it's always uncontended and
near-free, but other hosts that drive audio output from a separate
thread still rely on it for safety. Comment added accordingly.

Also drops the now-unused #include <condition_variable> and the
m_buffer_draining_cv member.
2026-05-07 22:22:59 +02:00
Lib
5e17e70de0 libretro: drop bounce-copy and dynamic_cast from audio upload path
Two micro-optimizations to retro_run_frame()'s audio drain.

LibretroAudioStream::UploadToFrontend() previously declared a 32 768-
sample (65 KiB) std::array on the stack every frame, copied the FIFO
contents into it across one or two iterations to flatten any wrap,
and then made a single g_retro_audio_sample_batch_callback() with the
flat buffer.

The intermediate copy is unnecessary: the libretro frontend reads
samples synchronously from the pointer we hand it, and the FIFO
storage stays valid until Remove(). Skip the bounce buffer and feed
the FIFO read pointer to the frontend directly. When the FIFO is in
one contiguous region (the common case) this is a single batch call;
when the FIFO has wrapped, it is two. Either way the per-frame stack
footprint drops by 65 KiB and one whole pass over every audio sample
is gone.

Separately, retro_run_frame() was using dynamic_cast to recover the
LibretroAudioStream pointer from the AudioStream member. The audio
stream is created by CreateAudioStream() as a LibretroAudioStream
and is type-invariant for the lifetime of the host interface; switch
to static_cast so the per-frame RTTI lookup goes away too.
2026-05-07 22:22:55 +02:00
Lib
0a862165ce libretro: cache lightgun state to avoid double input_state poll
The HW renderers (OpenGL, D3D11, Vulkan) were calling
g_retro_input_state_callback() from inside Render() to compute the
lightgun cursor overlay position - six calls per frame, after the
controller-update path had already polled the same values at the
start of retro_run_frame().

Per the libretro spec, input_state values are only well-defined
between retro_input_poll_callback() and the next host turn; the
frontend is not required to keep them fresh outside that window.
Calling input_state at two different points in the same retro_run
without an intervening poll is undefined behavior - frontends may
return cached, stale, or fresh values, and the result varies across
frontend implementations. That hurts cross-frontend determinism,
even when the actual gun coordinates fed to the PSX are
deterministic.

Cache the normalized 16-bit lightgun state on HostDisplay during
UpdateControllersNamcoGunCon (the one canonical poll site) and have
each HW renderer read from there. The cache is in libretro's raw
[-0x7FFF, 0x7FFF] coordinate space, so each renderer can scale to
its own render-target dimensions without sharing window/render
conventions.

Also drops the redundant offscreen-flag re-poll in the controller
path itself: the flag is now read once per frame instead of three
times.
2026-05-07 22:22:36 +02:00
LibretroAdmin
9498be27f8
Merge pull request #162 from Clownacy/assorted-compiler-warnings
Silence various compiler warnings.
2026-03-28 21:21:33 +01:00
Clownacy
7bd9645251 Make OpenBIOS a built-in fallback.
Previously, the emulator would mysteriously fail if the user did not
know beforehand to provide a copy of the BIOS. This avoids that
problem, silently and automatically loading a built-in copy of
OpenBIOS, so that the emulator will always do what the user wants:
boot the game.

Closes #153. Requested in #158.
2026-03-28 10:43:30 +00:00
Clownacy
ebd60bc998 Silence various compiler warnings.
Tested with GCC, Clang, and MSVC. All seem to build and run fine.
2026-03-28 10:35:53 +00:00
LibretroAdmin
5b9f9f6cbc
Merge pull request #154 from Clownacy/patch-1
Add missing `#include` to `string_util.h`.
2026-03-28 03:15:06 +01:00
LibretroAdmin
182e563381
Merge pull request #158 from Clownacy/openbios
Add support for OpenBIOS.
2026-03-28 03:14:57 +01:00
LibretroAdmin
0896a9177f
Merge pull request #160 from Clownacy/default-axis-scaling
Change default axis scaling to 1.33x.
2026-03-28 03:14:21 +01:00
Clownacy
8f026d3154 Change default axis scaling to 1.33x.
See #138.
2026-03-12 23:29:25 +00:00
Clownacy
651bc09dbd Remove VRAM dumping.
Completely unused, and pulls-in needless dependencies.
2026-03-12 21:54:32 +00:00
Clownacy
38fe600d3b Use miniz for everything instead of using both miniz and zlib.
Should reduce the size of the executable.
2026-03-12 21:40:45 +00:00
Clownacy
a0656611c9 Update libchdr.
Now uses libchdr's own CMake script instead of a custom one, which
allows for assembly-optimised LZMA decoding on some platforms.

This update also introduces support for Zstandard compression.
2026-03-12 21:17:40 +00:00
Clownacy
71c5f18b15 Add support for OpenBIOS.
Closes libretro#156.
2026-03-12 20:59:28 +00:00
Clownacy
084e4627cd
Add missing #include to string_util.h.
The lack of this was causing a build error when compiling with MSYS2 MinGW Clang x64.

There were other build errors too, but those were caused by `offsetof` somehow not being constexpr, which I imagine is a Clang/MSYS2 bug.
2026-02-08 01:54:45 +00:00
hizzlekizzle
4d309c05fd
reword core option, remove ifdef (#142)
there was an escape character problem before, but I just reworded the whole thing to get rid of the ifdef in the process
2025-08-02 13:58:57 +02:00
Guilherme Janczak
37cd87e14c
only look for BIOS files in the libretro system directory (#122)
Don't look for BIOS files in the same directory as the executable,
instead obey the libretro system directory.

```cpp
 if (!g_retro_environment_callback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &system_directory) || !system_directory)
   return GetProgramDirectoryRelativePath("system");
```
The code above reads "If we can't get the system directory from
libretro, return a directory named `system` located in the same
directory as the executable containing main()". This code is only used
to look for the path with the BIOS files.

On Unix, If RetroArch is /usr/bin/retroarch (or equivalent), it will try
to look for BIOS files at /usr/bin/system. On Android, non-root programs
will always be unable to look at that directory. Other platforms will
display similarly strange behavior.

This behavior feels more like an accident than an intentional design
choice. This commit removes it and all the code that implements it.
2024-07-24 17:35:00 +02:00
libretroadmin
bc54533f85 Backport cpu_recompiler_code_generator.cpp commit 2024-07-22 02:45:43 +02:00
DarthMew
b17b0e4348 NeGconRumble: Map the analog toggle to the RetroPad select button 2024-07-15 17:13:47 +02:00
DarthMew
b9bbf87254 Backport MDEC: Increase intermediate IDCT precision 2024-07-09 20:25:10 +02:00
DarthMew
db6659b1e9 Merge display hlsl helper files 2024-07-09 16:30:14 +02:00
DarthMew
365e29cf58
Merge pull request #123 from guijan/openbsd
only #include <malloc.h> if it exists
2024-07-08 03:08:13 +02:00
Guilherme Janczak
ef2689f996
only #include <malloc.h> if it exists
This makes more of the compilation process succeed on OpenBSD, but it
still fails.
2024-07-07 23:17:16 +00:00
DarthMew
62e2c5f265 file_system: Remove unused logchannel 2024-07-07 22:57:48 +02:00