Skip to content

About

Optimized build of px68k-libretro (X68000 emulator core) for Raspberry Pi 3B (Cortex-A53, 32-bit armhf). NEON compositing, LTO, strict-aliasing fixes, audio balance. Fork of uraraworks/px68k-libretro. Build script + docs included.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

15 Commits

Folders and files

Repository files navigation

px68k-libretro for Raspberry Pi 3B - Optimized Build

TL;DR: A fork of uraraworks/px68k-libretro, cross-compiled for the Raspberry Pi 3B (Cortex-A53) with LTO, microarchitectural tuning, NEON compositing, and audio-path tweaks. Build: ./build.sh advance → build/px68k_libretro.so.


1. Important before you start

  • You need a 32-bit OS (armhf). The core uses Cyclone — a 68000 dynamic recompiler written in ARM32 assembly. It will not build or load on a 64-bit (aarch64) OS. Use Raspberry Pi OS (32-bit).
  • You need X68000 BIOS files in RetroArch's system/keropi/ folder: iplrom.dat, iplromx.dat, cgrom.dat (and optionally human.x). Without them the core will not start.

2. Why this fork exists (RPi3B bottlenecks)

The Raspberry Pi 3B is a BCM2837: 4× Cortex-A53 (ARMv8, in-order, 1.2 GHz), with a very modest 32 KB L1 I-Cache per core and no out-of-order execution.

X68000 is emulated entirely in a single thread (retro_run() is synchronous):

  1. 68000 instruction execution (Cyclone),
  2. FM synthesis (YM2151/OPM) + ADPCM,
  3. software layer compositing into ScrBuf (all rendering is CPU-side, no GPU),
  4. frame hand-off to RetroArch.

This produces three classes of problems we addressed:

  • GLIBC mismatch: the cross GCC 12 pulls libstdc++/libgcc requiring GLIBC 2.33+, while the Pi runs an older OS (2.28) → the core would not load at all.
  • Render performance: branchy per-pixel compositing + compiler aliasing paranoia → millions of redundant memory round-trips per scanline.
  • Audio: summed OPM+ADPCM overloaded the 16-bit mixer (hard clipping).

3. What was optimized and why

Each change is split into Problem → Solution → Effect.

3.1 Build: GLIBC compatibility (build.sh, sysroot/)

  • Problem. Cross GCC 12.2.0 links its own libstdc++/libgcc needing GLIBC_2.33–2.36. On the Pi (RPi OS Buster) the max is GLIBC_2.28 → the loader could not resolve symbols and the core failed with "Failed to load core". Even standard would not load.
  • Solution. Build against the Pi's own sysroot (--sysroot=sysroot, glibc 2.28) plus -static-libgcc -static-libstdc++. Important detail: --sysroot alone did not work because GCC prepends its own absolute -L to its libc before our flags; therefore the sysroot paths are placed at the start of the compiler invocation (-L sysroot/lib/arm-linux-gnueabihf …).
  • Effect. The binary requires only GLIBC_2.27 and loads on a stock OS. Runtime libs are baked in (the Pi's libstdc++ version no longer matters).

3.2 Build: LTO — Link-Time Optimization (build.sh)

  • Problem. The emulator is hundreds of tiny functions (memory r/w, register shifts, FM operator ticks) spread across .c files. A normal compiler cannot inline them across translation units.
  • Solution. -flto=4 -fuse-linker-plugin (linking goes through $(CXX), so LTO works).
  • Effect. The main audio win: FM synthesis (OPM::Mix, Calc, CalcL, LogToLin) is inlined directly into the mixing loop — no call overhead, fewer I-cache misses. ~10–15% faster audio.

3.3 Build: Cortex-A53 tuning (build.sh)

  • Solution. -mcpu=cortex-a53 -mfpu=neon-fp-armv8 -mfloat-abi=hard -O3 -ffast-math -fomit-frame-pointer, function alignment -falign-functions=16.
  • Why. The A53 fetches 2 instructions per cycle (64 bits); 16-byte alignment avoids decoder stalls. NEON/VFPv4 are used in hardware. -ffast-math speeds up FM FP math.

3.4 Source: per-file strict-aliasing — FIX for menu stutter (build.sh, 4 files)

  • Problem. In libretro.c the hot render loop ScrBuf[adr] = w under a global -fno-strict-aliasing made the compiler suspect that a pointer write would clobber globals (TextDotX, VLINE, palette masks). On every pixel the A53 reloaded globals from memory → millions of redundant accesses → stutter in menus and attract screens.
  • But files tvram.c, gvram.c, bg.c, libretro.c perform type-punning (*(uint32_t*)&TextDrawWork, *(uint16_t*)(GVRAM+...)) — that is UB under strict-aliasing. Under LTO the compiler sees all code at once and could "optimize" those accesses as undefined behaviour → broken rendering.
  • Solution. Removed -fno-strict-aliasing globally (so windraw.c gets strict-aliasing → globals live in registers r4–r11, no reloads), and added a local pragma #pragma GCC optimize ("no-strict-aliasing") only in the 4 "dirty" files.
  • Effect. Menus/attract screens run smoothly, type-punning stays correct. This was the key fix for stutter.

3.5 Source: NEON compositing (libretro/windraw.c)

  • Problem. Transparent layer blit if (w != 0) ScrBuf[adr] = w — a branch on every pixel of every layer (text + BG + sprites + grp) × 512 scanlines. On the in-order A53 branches stall the pipeline.
  • Solution. Three NEON routines processing 8 pixels per iteration, branchless:
    • neon_blit_transparent — mask = vtstq_u16(s,s); res = vbslq_u16(mask,s,d).
    • neon_blit_transparent_flagged — blit gated by Text_TrFlag. Correctness detail: first vmovl_u8 widens the flag bytes to 16-bit, then vtstq_u16 fills the mask with 0xFFFF per pixel. A naive vmovl_u8 of an already-tested 8-bit mask would yield 0x00FF and corrupt RGB565 across half-pixels.
    • neon_blit_half_aquales — special half-transparency mode (AQUALES).
    • All guarded by #if defined(__ARM_NEON) — full backward compatibility.
    • ScrBuf via posix_memalign(16,…); sources (Grp_LineBuf, Grp_LineBufSP, Grp_LineBufSP2, BG_LineBuf, Text_TrFlag) marked __attribute__((aligned(16))).
  • Effect. Faster compositing, no branch stalls. Does not speed up Cyclone (68000 emulation) — that remains the dominant load.

3.6 Source: adpcm.c — INTERPOLATE (x68k/adpcm.c)

  • Problem. INTERPOLATE(OutsIpR, 0) — cubic interpolation, called per sample (44100/sec/channel). At x=0 it mathematically reduces to y[1], but the compiler computed ~6 mul/div.
  • Solution. Replace with a direct read OutsIpR[1] / OutsIpL[1].
  • Effect. Bit-exact equivalent (no quality loss), removes ~6 mul/div per sample (~530k ops/sec). (Note: A53 has hardware SDIV/UDIV, so divisions are not catastrophic — this is cleanup, not a breakthrough.)

3.7 Source: libretro.c — DMA guard (libretro.c)

  • Problem. DMA_Exec(0..2) ran every slice; if the channel was off (!(CSR&0x08)) the function did nothing yet saved/restored registers ~150k–300k times/sec.
  • Solution. Wrap the calls: if (DMA[ch].CSR & 0x08) DMA_Exec(ch);
  • Effect. Idle calls are skipped. (Honestly: ~0.3% CPU win — marginal, but cleaner code.)

3.8 Source: default volume balance (libretro_core_options.h, prop.c)

  • Problem. OPM (music) + ADPCM (explosions) are summed and saturated (StoreSample does dest = Limit(dest+data, …)). At adpcm=15 / opm=12 loud explosions overloaded the 16-bit mixer → FM music was "squashed", distorted and pushed to the background (Cho-Ren-Sha 68k, Gradius II, Akumajou Dracula, Thunder Force II).
  • Solution. Default px68k_adpcm_vol 15 → 11, px68k_opm_vol 12 → 13.
  • Effect. Hard clipping gone, music stays clean even in dense scenes.
  • ⚠️ Important: RetroArch persists core options to an .opt file. If you previously set volume via the GUI, the saved value overrides the in-code default. To apply the new default: Quick Menu → Core Options → Reset to Defaults (then restart the core), or delete ~/.config/retroarch/config/px68k_libretro/px68k_libretro.opt.

4. Build requirements (cross-compilation on x86_64 Linux)

Only sources, build.sh and README.md go into git. The heavy build environment (sysroot/, vc/, build/, *.o, *.so) is not committed — it is reproduced locally per the steps below (see .gitignore). sysroot/ is ~2 GB and specific to your Pi.

4.1 armhf toolchain

sudo apt-get install gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf

4.2 Pi sysroot (glibc 2.28) — copy from your Raspberry Pi

The binary is built against your Pi's sysroot so it only needs GLIBC_2.27 and loads on a stock OS. Copy the system paths from the Pi to the host (replace pi@192.168.5.186 with your address):

# On the host, create sysroot next to build.sh
mkdir -p sysroot

# Copy system libraries and headers from the Pi
rsync -avz --copy-links pi@192.168.5.186:/lib/          sysroot/lib/
rsync -avz --copy-links pi@192.168.5.186:/usr/lib/      sysroot/usr/lib/
rsync -avz --copy-links pi@192.168.5.186:/usr/include/  sysroot/usr/include/

# Triplet paths (if present on the Pi)
rsync -avz --copy-links pi@192.168.5.186:/usr/lib/arm-linux-gnueabihf/ \
                                  sysroot/usr/lib/arm-linux-gnueabihf/
rsync -avz --copy-links pi@192.168.5.186:/lib/arm-linux-gnueabihf/ \
                                  sysroot/lib/arm-linux-gnueabihf/

build.sh already prepends these paths to the compiler invocation (-L sysroot/lib/arm-linux-gnueabihf -L sysroot/usr/lib/arm-linux-gnueabihf) and adds -static-libgcc -static-libstdc++, so runtime libs are baked into the .so and the Pi's libstdc++ version does not matter.

Alternative without a Pi handy: copy sysroot/ from an already-prepared environment (e.g. from a friend / an archive). The key is glibc 2.28 (RPi OS Buster) or newer.

4.3 Source tree

Clone this fork (all §3 changes are already inside):

git clone <URL-of-this-fork> px68k-libretro
cd px68k-libretro
# build.sh and sysroot/ must sit alongside (see layout below)

4.4 Expected working-folder layout

px68k-build/                  # your local folder (NOT in git)
├── build.sh                  # build script (in git)
├── README.md                 # this guide (in git)
├── sysroot/                  # ~2 GB, copied from Pi (NOT in git, .gitignore)
├── vc/                       # VideoCore SDK if needed (NOT in git)
├── build/                    # output: px68k_libretro.so (NOT in git)
└── px68k-libretro/           # clone of the fork (in git: sources only)
    ├── build.sh -> ../build.sh  (or a copy)
    ├── libretro/windraw.c    # NEON changes
    ├── x68k/adpcm.c          # INTERPOLATE changes
    ├── x68k/tvram.c ...      # strict-aliasing changes
    └── ...

The .gitignore in the source tree already excludes *.o, *.so and other build artifacts.


5. Building

# standard  : -O3, Cyclone, no LTO               (safe baseline)
./build.sh standard

# advance   : LTO + A53 tuning + NEON            (recommended, always stripped)
./build.sh advance

# pgo       : instrumented build to generate a PGO profile on the Pi
./build.sh pgo

# pgo-use DIR : final LTO+PGO build from profile in DIR
./build.sh pgo-use /path/to/pgo_profile

# clang     : experimental (needs clang + Pi sysroot)
./build.sh clang

Result: build/px68k_libretro.so (ELF 32-bit LSB shared object, ARM, EABI5, stripped). advance/pgo-use are always stripped; standard keeps debug info unless --strip is passed. The binary targets GLIBC_2.27.


6. Installation on RetroPie

  1. Copy the built file to the Pi (example over SSH):
    # 1. Copy to a temp folder on the Pi
    scp ./build/px68k_libretro.so pi@192.168.5.186:/tmp/
    # 2. Move with sudo into the cores folder
    ssh pi@192.168.5.186 "sudo mv /tmp/px68k_libretro.so /opt/retropie/libretrocores/lr-px68k/px68k_libretro.so"
    (Substitute your own IP and path, e.g. ~/.config/retroarch/cores/.)
  2. Place X68000 BIOS files in RetroArch's system/keropi/: iplrom.dat, iplromx.dat, cgrom.dat (opt. human.x).

6.3 Cleaning px68k state files (RetroPie)

The emulator creates config and sram.dat in system/keropi/ on every launch. An old config can prevent the emulator from starting with the correct floppy.

To always start clean, add to /opt/retropie/configs/all/runcommand-onend.sh:

if [ "\$1" = "x68000" ]; then
    rm -f /home/pi/RetroPie/BIOS/keropi/config
fi

⚠️ Note: sram.dat contains battery-backed RAM (game saves). Do NOT delete it if you want to preserve saves between sessions.


7. RetroArch / core options for weak SoCs

If a specific game still drops frames:

  • px68k_midi_output = disabled — with built-in FM/ADPCM, the software MIDI stack is disabled and stops wasting cycles.
  • px68k_cpuspeed = 10Mhz — do not set 16/25 MHz unless needed: it proportionally increases emulated 68000 instructions per frame.
  • px68k_audio_desync_hack = enabled — on FPS drops, audio resyncs smoothly instead of lagging the buffer.
  • px68k_ramsize = 2MB — enough for 95% of diskette games, less L2 cache use.

Volume balance (already the default in this build): px68k_adpcm_vol = 11 (was 15), px68k_opm_vol = 13 (was 12). If you saved via GUI before, see §3.8 (Reset to Defaults).

RetroArch host settings:

  • Core options → Advanced → Audio Desync Hack = On
  • Output → Video → Threaded Video = ON
  • Output → Audio → Audio Latency = 92
  • Latency → Run-Ahead to Reduce Latency = ON

8. Troubleshooting

  • Core will not load ("Failed to load core"). Almost always GLIBC: the binary was built against a newer libc than on the Pi. Make sure you built with this build.sh (it targets GLIBC_2.27 via sysroot). Check requirements: arm-linux-gnueabihf-readelf -V build/px68k_libretro.so | grep GLIBC.
  • Build/load fails on 64-bit OS. Cyclone is ARM32 assembly; use 32-bit Raspberry Pi OS.
  • Volume changes "did nothing". RetroArch overrides the default with a saved option (§3.8). Reset via Reset to Defaults or delete the .opt file.
  • Stutter in menus after an advance build. Verify there is NO global -fno-strict-aliasing in build.sh (it should be per-file only, see §3.4).

P.S. Practical takeaway

Why Cortex-A53. This board (Raspberry Pi 3B) is what I have on hand. I optimized for it, debugged on it, and verified on it. There is no other reason.

What this means for other platforms:

  • Cortex-A53 (Pi 3B/3B+/3A+, Orange Pi PC/One, NanoPi, and clones) — works as-is. This is the largest segment of weak SBCs, and the build targets exactly that.
  • Pi 4 / Cortex-A72 — the binary will run, but won't unlock the core's full potential. The NEON/LTO/aliasing fixes carry over unchanged; only the tuning flag needs to change (-mcpu=cortex-a72).
  • Pi 1/Zero (ARM11) — won't work: no NEON, different instruction set. Needs a separate target (-mcpu=arm1176jzf-s) and a plain C fallback instead of the NEON paths.
  • x86 / other architectures — the NEON code doesn't port over (needs SIMD via SSE/AVX), but the aliasing fix and LTO are useful there too.

On portability. Technically, nothing prevents extending build.sh with a target parameter (TARGET_CPU=...) and wrapping the NEON paths in #ifdef __ARM_NEON with a plain C fallback. That would let a single repository cover the entire Raspberry Pi lineup and clones. But I haven't done that - there's no concrete need on my end, and more importantly: I haven't tested or debugged those configurations. So if you take it on - verify it yourself.


9. Acknowledgements and upstream

License

This project is a modified version of px68k-libretro (uraraworks et al.), licensed under GPL-2.0. The original code, copyright notices and the full GPL text are preserved in COPYING. All modifications listed in CHANGES are released under the same GPL-2.0 license. Source code for any distributed binary is available in this repository.

About

Optimized build of px68k-libretro (X68000 emulator core) for Raspberry Pi 3B (Cortex-A53, 32-bit armhf). NEON compositing, LTO, strict-aliasing fixes, audio balance. Fork of uraraworks/px68k-libretro. Build script + docs included.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages