foxygit / fake-08-xbox360 Log in
commit f5ca7a9363f28b26d0c3c2dc40294db8bbb9469f
Author:     mrfox <jens.se@icloud.com>
AuthorDate: Tue Nov 24 20:49:59 2026 +0100
Commit:     mrfox <jens.se@icloud.com>
CommitDate: Tue Nov 24 20:49:59 2026 +0100

    Add Xbox 360 (libxenon / XeLL) platform

    New platform in platform/xenon, built with `make xenon` inside the
    free60/libxenon docker image. Produces FAKE-08_Xenon.elf32, which runs
    bare metal from XeLL (USB or TFTP).

    Platform layer (XenonHost.cpp):
    - Video: palette + drawMode transform, nearest-neighbour scaling straight
      into the tiled Xenos framebuffer. Frames are paced on vblank and written
      at the start of vblank (racing the beam) when the display runs at ~60 Hz,
      with a timer fallback otherwise.
    - Audio: 22050 Hz mono resampled to the 48 kHz stereo little-endian
      stream xenon_sound expects, with a self-regulating queue.
    - Input: USB controller via libxenon, release debounce, BACK cycles
      screen modes, BACK+START exits.
    - Storage: first FAT32 device with a p8carts folder; data, log and
      settings in <device>:/fake08/.
    - times() stub for newlib clock() / Lua os.clock().

    Core changes:
    - main.cpp: skip argv parsing on Xenon (XeLL passes garbage argv over
      TFTP, getopt crashed).
    - Controller settings (layout swap, stick deadzone) in the settings cart,
      shown only on platforms that set Host::hasControllerSettings.
    - Host::saveSettingsOnChange to write settings.ini on every change, for
      consoles that are switched off instead of exited.
    - hostCommonFunctions.cpp: open settings/cartdata files with fopen instead
      of freopen(..., stderr). freopen on stderr closed the logger's file.

    Build notes: no --gc-sections, since libxenon's app.lds does not KEEP
    .ctors and every C++ static constructor would be dropped.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 .gitignore                          |   4 +
 Makefile                            |   8 +-
 platform/xenon/Makefile             |  83 +++++
 platform/xenon/source/XenonHost.cpp | 599 ++++++++++++++++++++++++++++++++++++
 source/FakoSettings.h               |  15 +
 source/host.h                       |   9 +
 source/hostCommonFunctions.cpp      |  37 ++-
 source/main.cpp                     |   8 +-
 8 files changed, 757 insertions(+), 6 deletions(-)

diff --git a/.gitignore b/.gitignore
index 0032b41..ea14a87 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,3 +51,7 @@ platform/libretro/libs/
 platform/libretro/obj/
 .DS_Store

+
+# libxenon (Xbox 360) build output
+*.elf32
+*.d
diff --git a/Makefile b/Makefile
index 15d25cc..a4861e1 100644
--- a/Makefile
+++ b/Makefile
@@ -15,7 +15,7 @@ export APP_VERSION	= v$(V_MAJOR).$(V_MINOR).$(V_PATCH).$(V_BUILD)
 export SOURCES   = ../../source ../../libs/z8lua ../../libs/utf8-util ../../libs/lodepng ../../libs/simpleini ../../libs/miniz
 export INCLUDES  = ../../include ../../libs/z8lua ../../libs/utf8-util ../../libs/lodepng ../../libs/simpleini ../../libs/miniz

-.PHONY: all 3ds switch wiiu vita sdl2 sdl windows clean clean-3ds clean-switch clean-wiiu clean-vita clean-sdl2 clean-sdl clean-windows
+.PHONY: all 3ds switch wiiu vita sdl2 sdl windows clean clean-3ds clean-switch clean-wiiu clean-vita clean-sdl2 clean-sdl clean-windows xenon clean-xenon

 all: 3ds switch wiiu vita bittboy windows

@@ -27,6 +27,9 @@ clean-3ds:
 clean-switch:
 	@$(MAKE) -C platform/switch clean

+clean-xenon:
+	@$(MAKE) -C platform/xenon clean
+
 clean-wiiu:
 	@$(MAKE) -C platform/wiiu clean

@@ -69,6 +72,9 @@ switch:
 wiiu:
 	@$(MAKE) -C platform/wiiu

+xenon:
+	@$(MAKE) -C platform/xenon
+
 vita:
 	@$(MAKE) -C platform/vita

diff --git a/platform/xenon/Makefile b/platform/xenon/Makefile
new file mode 100644
index 0000000..153dbff
--- /dev/null
+++ b/platform/xenon/Makefile
@@ -0,0 +1,83 @@
+#---------------------------------------------------------------------------------
+# FAKE-08 for Xbox 360 (libxenon / XeLL)
+#
+# Build from the repository root with `make xenon`, inside the free60/libxenon
+# docker image (see .github/workflows/buildXenon.sh).
+#---------------------------------------------------------------------------------
+.SUFFIXES:
+
+ifeq ($(strip $(DEVKITXENON)),)
+$(error "Please set DEVKITXENON in your environment. export DEVKITXENON=<path to>/xenon")
+endif
+
+include $(DEVKITXENON)/rules
+
+TARGET		:=	FAKE-08_Xenon
+BUILD		:=	build
+SOURCES		:=	${SOURCES} source
+INCLUDES	:=	${INCLUDES}
+
+#---------------------------------------------------------------------------------
+# options for code generation
+#---------------------------------------------------------------------------------
+# z8lua's .c files are C++ (fix32 math, throw/catch for Lua errors)
+CC		:=	$(CXX)
+
+CFLAGS		=	-g -O2 -Wall -Wno-sign-compare \
+			$(MACHDEP) $(INCLUDE) \
+			-D__XENON__ -DMINIZ_NO_TIME -DVER_STR=\"$(APP_VERSION)\"
+CXXFLAGS	=	$(CFLAGS) -std=gnu++17
+# No --gc-sections: libxenon's app.lds does not KEEP(.ctors), so the linker
+# would drop every C++ static constructor.
+LDFLAGS		=	-g $(MACHDEP) -Wl,-Map,$(notdir $@).map
+
+# libfat must come before libxenon (libfat uses libxenon's disc drivers)
+LIBS		:=	-lfat -lxenon -lm
+LIBDIRS		:=
+
+#---------------------------------------------------------------------------------
+ifneq ($(BUILD),$(notdir $(CURDIR)))
+#---------------------------------------------------------------------------------
+
+export OUTPUT	:=	$(CURDIR)/$(TARGET)
+export VPATH	:=	$(foreach dir,$(SOURCES),$(CURDIR)/$(dir))
+export DEPSDIR	:=	$(CURDIR)/$(BUILD)
+
+CFILES		:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
+CPPFILES	:=	$(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
+
+export LD	:=	$(CXX)
+
+export OFILES	:=	$(CPPFILES:.cpp=.o) $(CFILES:.c=.o)
+
+export INCLUDE	:=	$(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
+			$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
+			-I$(CURDIR)/$(BUILD) \
+			-I$(LIBXENON_INC)
+
+export LIBPATHS	:=	$(foreach dir,$(LIBDIRS),-L$(dir)/lib) \
+			-L$(LIBXENON_LIB)
+
+.PHONY: $(BUILD) clean
+
+$(BUILD):
+	@[ -d $@ ] || mkdir -p $@
+	@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
+
+clean:
+	@echo clean ...
+	@rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).elf32 $(OUTPUT).elf.map
+
+#---------------------------------------------------------------------------------
+else
+
+DEPENDS	:=	$(OFILES:.o=.d)
+
+$(OUTPUT).elf32: $(OUTPUT).elf
+$(OUTPUT).elf: $(OFILES)
+
+-include $(DEPENDS)
+
+#---------------------------------------------------------------------------------
+endif
+#---------------------------------------------------------------------------------
diff --git a/platform/xenon/source/XenonHost.cpp b/platform/xenon/source/XenonHost.cpp
new file mode 100644
index 0000000..f32b9e1
--- /dev/null
+++ b/platform/xenon/source/XenonHost.cpp
@@ -0,0 +1,599 @@
+/*
+ * Xbox 360 (libxenon) host for FAKE-08.
+ *
+ * Runs bare metal from XeLL. Video is drawn in software straight into the
+ * Xenos framebuffer (tiled 32x32 layout, same as libxenon's console), audio is
+ * resampled from 22050 Hz mono to the 48 kHz stereo little-endian stream that
+ * xenon_sound expects, input comes from libxenon's USB controller driver and
+ * carts are read from the first FAT32 USB device that has a p8carts folder.
+ */
+#include <stdio.h>
+#include <string.h>
+#include <dirent.h>
+#include <sys/stat.h>
+
+#include <string>
+#include <vector>
+
+#include "../../../source/host.h"
+#include "../../../source/hostVmShared.h"
+#include "../../../source/nibblehelpers.h"
+#include "../../../source/logger.h"
+#include "../../../source/filehelpers.h"
+
+extern "C" {
+#include <xenos/xenos.h>
+#include <console/console.h>
+#include <input/input.h>
+#include <usb/usbmain.h>
+#include <time/time.h>
+#include <ppc/timebase.h>
+#include <ppc/cache.h>
+#include <xenon_soc/xenon_power.h>
+#include <xenon_sound/sound.h>
+#include <libfat/fat.h>
+int bdev_enum(int handle, const char **name);
+extern void (*stdout_hook)(const char *buf, int len);
+}
+
+using namespace std;
+
+static const int PicoScreenWidth = 128;
+static const int PicoScreenHeight = 128;
+
+// ---------------------------------------------------------------------------
+// Framebuffer
+// ---------------------------------------------------------------------------
+
+// Register block describing the scanout surface (same as libxenon console.c)
+struct ati_info {
+    uint32_t unknown1[4];
+    uint32_t base;
+    uint32_t unknown2[8];
+    uint32_t width;
+    uint32_t height;
+} __attribute__((__packed__));
+
+static uint32_t *fb = nullptr;
+static int fbWidth = 0, fbHeight = 0;      // visible size
+static int fbPitchW = 0, fbPitchH = 0;     // rounded up to 32x32 tiles
+static int safeX = 0, safeY = 0;           // overscan margin (composite/analog)
+
+// Destination rectangle on screen
+static int destX = 0, destY = 0, destW = 0, destH = 0;
+static std::vector<uint8_t> xMap, yMap;    // dest pixel -> source pixel
+static bool needClear = true;
+
+static uint32_t frameRgb[PicoScreenWidth * PicoScreenHeight];
+
+static inline int tiledIndex(int x, int y) {
+    return (((y >> 5) * 32 * fbPitchW + ((x >> 5) << 10)
+            + (x & 3) + ((y & 1) << 2) + (((x & 31) >> 2) << 3) + (((y & 31) >> 1) << 6))
+            ^ ((y & 8) << 2));
+}
+
+static inline uint32_t fbColor(const Color &c) {
+    // Xenos scanout format as used by libxenon's console (BGRX, big-endian word)
+    return ((uint32_t)c.Blue << 24) | ((uint32_t)c.Green << 16) | ((uint32_t)c.Red << 8);
+}
+
+static void fbInit() {
+    volatile ati_info *ai = (volatile ati_info *)0xec806100ULL;
+    fb = (uint32_t *)(long)(ai->base | 0x80000000);
+    fbWidth = ai->width;
+    fbHeight = ai->height;
+    fbPitchW = ((fbWidth + 31) >> 5) << 5;
+    fbPitchH = ((fbHeight + 31) >> 5) << 5;
+    if (xenos_is_overscan()) {
+        safeX = fbWidth / 28;
+        safeY = fbHeight / 28;
+    }
+}
+
+static void fbClear() {
+    size_t words = (size_t)fbPitchW * fbPitchH;
+    for (size_t i = 0; i < words; i++) fb[i] = 0;
+    memdcbst(fb, words * 4);
+}
+
+static void setDestRect(int w, int h) {
+    int availW = fbWidth - safeX * 2;
+    int availH = fbHeight - safeY * 2;
+    if (w > availW) w = availW;
+    if (h > availH) h = availH;
+    destW = w;
+    destH = h;
+    destX = (fbWidth - w) / 2;
+    destY = (fbHeight - h) / 2;
+
+    xMap.resize(destW);
+    yMap.resize(destH);
+    for (int i = 0; i < destW; i++) xMap[i] = (uint8_t)(i * PicoScreenWidth / destW);
+    for (int i = 0; i < destH; i++) yMap[i] = (uint8_t)(i * PicoScreenHeight / destH);
+    needClear = true;
+}
+
+static void _changeStretch(StretchOption s) {
+    int availH = fbHeight - safeY * 2;
+    int availW = fbWidth - safeX * 2;
+    int intScale = availH / PicoScreenHeight;
+    if (intScale < 1) intScale = 1;
+
+    switch (s) {
+        case PixelPerfect:
+            setDestRect(PicoScreenWidth, PicoScreenHeight);
+            break;
+        case StretchToFit:
+            setDestRect(availH, availH);
+            break;
+        case StretchToFill:
+            setDestRect(availW, availH);
+            break;
+        case FourByThreeVertPerfect:
+            setDestRect(intScale * PicoScreenHeight * 4 / 3, intScale * PicoScreenHeight);
+            break;
+        case FourByThreeStretch:
+            setDestRect(availH * 4 / 3, availH);
+            break;
+        case PixelPerfectStretch:
+        default:
+            setDestRect(intScale * PicoScreenWidth, intScale * PicoScreenHeight);
+            break;
+    }
+}
+
+// Applies drawMode (screen stretch/flip/rotate pokes) while converting to fb colors.
+static inline void srcCoord(uint8_t drawMode, int x, int y, int &sx, int &sy) {
+    switch (drawMode) {
+        case 1:   sx = x >> 1; sy = y; break;                 // horizontal stretch
+        case 2:   sx = x; sy = y >> 1; break;                 // vertical stretch
+        case 3:   sx = x >> 1; sy = y >> 1; break;            // both
+        case 129: sx = 127 - x; sy = y; break;                // flip h
+        case 130: sx = x; sy = 127 - y; break;                // flip v
+        case 131: sx = 127 - x; sy = 127 - y; break;          // flip both
+        case 133: sx = y; sy = 127 - x; break;                // rotate 90 cw
+        case 134: sx = 127 - x; sy = 127 - y; break;          // rotate 180
+        case 135: sx = 127 - y; sy = x; break;                // rotate 270 cw
+        default:  sx = x; sy = y; break;
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Audio: 22050 Hz mono (packed as 32-bit L/R pairs) -> 48 kHz stereo LE
+// ---------------------------------------------------------------------------
+
+static const int CoreRate = 22050;
+static const int OutRate = 48000;
+static const int TargetQueuedBytes = OutRate * 4 * 70 / 1000;  // ~70 ms queued
+static const int MaxCoreFrames = 2048;
+
+static uint32_t coreBuf[MaxCoreFrames];
+static size_t coreFrames = 0;
+static uint32_t outBuf[MaxCoreFrames * OutRate / CoreRate + 16];
+static double resamplePos = 0.0;      // fractional position carried between chunks
+static int16_t resamplePrev = 0;      // last core sample of previous chunk
+static bool audioInitialized = false;
+
+static inline uint16_t bswap16(uint16_t v) { return (uint16_t)((v >> 8) | (v << 8)); }
+
+static void audioSetup() {
+    xenon_sound_init();
+    audioInitialized = true;
+}
+
+static void audioPlayChunk() {
+    if (!audioInitialized || coreFrames == 0) return;
+
+    const double step = (double)CoreRate / OutRate;
+    size_t n = coreFrames;
+    size_t outCount = 0;
+    double pos = resamplePos;   // index into [prev, s0, s1, ... s(n-1)]
+
+    while (pos + 1.0 <= (double)n && outCount < sizeof(outBuf) / sizeof(outBuf[0])) {
+        int i = (int)pos;
+        double frac = pos - i;
+        int16_t a = (i == 0) ? resamplePrev : (int16_t)(coreBuf[i - 1] & 0xffff);
+        int16_t b = (int16_t)(coreBuf[i] & 0xffff);
+        int16_t s = (int16_t)(a + (b - a) * frac);
+        uint16_t le = bswap16((uint16_t)s);
+        outBuf[outCount++] = ((uint32_t)le << 16) | le;
+        pos += step;
+    }
+    resamplePos = pos - (double)n;
+    resamplePrev = (int16_t)(coreBuf[n - 1] & 0xffff);
+
+    int bytes = (int)(outCount * 4);
+    int freeBytes = xenon_sound_get_free();
+    if (bytes > freeBytes) bytes = freeBytes & ~3;
+    if (bytes > 0) xenon_sound_submit(outBuf, bytes);
+}
+
+// ---------------------------------------------------------------------------
+// Timing
+// ---------------------------------------------------------------------------
+
+static uint64_t lastFrameTb = 0;
+static uint64_t targetFrameTb = PPC_TIMEBASE_FREQ / 60;
+
+// --- vsync --------------------------------------------------------------
+// Same register/bit libxenon's Xe_IsVBlank() reads (GPU regs at 0xec800000).
+static inline bool inVBlank() {
+    return (*(volatile uint32_t *)(0xec800000 + 0x6534)) & 0x1000;
+}
+
+static const uint64_t TbPerMs = PPC_TIMEBASE_FREQ / 1000;
+static bool vsyncMode = false;     // pace frames on vblank instead of the timer
+static int vsyncMisses = 0;
+
+// Waits for the start of the next vblank. Returns false on timeout.
+static bool waitVBlankStart() {
+    uint64_t start = mftb();
+    const uint64_t timeout = 25 * TbPerMs;
+    while (inVBlank()) {                       // leave a vblank we're already in
+        if (mftb() - start > timeout) return false;
+    }
+    while (!inVBlank()) {                      // wait for the next one to begin
+        if (mftb() - start > timeout) return false;
+    }
+    return true;
+}
+
+// Uses vsync only if the display really refreshes at ~60 Hz (PICO-8 speed).
+static void calibrateVsync() {
+    vsyncMode = false;
+    if (!waitVBlankStart()) return;
+    uint64_t t0 = mftb();
+    const int samples = 10;
+    for (int i = 0; i < samples; i++) {
+        if (!waitVBlankStart()) return;
+    }
+    uint64_t avgUs = (mftb() - t0) / samples / (PPC_TIMEBASE_FREQ / 1000000);
+    printf(" * vblank interval: %llu us\n", (unsigned long long)avgUs);
+    vsyncMode = avgUs > 16000 && avgUs < 17400;   // 57.5 - 62.5 Hz
+    printf(" * frame pacing: %s\n", vsyncMode ? "vsync" : "timer");
+}
+
+// newlib's clock() (used by Lua's os.clock) needs times(), which libxenon
+// does not provide. Report CPU time as time since boot, in CLOCKS_PER_SEC.
+#include <sys/times.h>
+#include <time.h>
+extern "C" clock_t times(struct tms *buf) {
+    clock_t t = (clock_t)(mftb() / (PPC_TIMEBASE_FREQ / CLOCKS_PER_SEC));
+    if (buf) {
+        buf->tms_utime = t;
+        buf->tms_stime = 0;
+        buf->tms_cutime = 0;
+        buf->tms_cstime = 0;
+    }
+    return t;
+}
+
+// ---------------------------------------------------------------------------
+// Storage
+// ---------------------------------------------------------------------------
+
+static std::string deviceRoot = "uda0:/";
+
+static bool dirExists(const std::string &path) {
+    DIR *d = opendir(path.c_str());
+    if (d) { closedir(d); return true; }
+    return false;
+}
+
+static void findStorage() {
+    const char *name = nullptr;
+    int handle = -1;
+    std::string first;
+    for (int i = 0; i < 16; i++) {
+        handle = bdev_enum(handle, &name);
+        if (handle < 0) break;
+        std::string root = std::string(name) + ":/";
+        if (first.empty()) first = root;
+        if (dirExists(root + "p8carts")) {
+            deviceRoot = root;
+            return;
+        }
+    }
+    if (!first.empty()) deviceRoot = first;
+}
+
+// ---------------------------------------------------------------------------
+// Host
+// ---------------------------------------------------------------------------
+
+Host::Host(int windowWidth, int windowHeight) {
+    xenos_init(VIDEO_MODE_AUTO);
+    console_init();
+    xenon_make_it_faster(XENON_SPEED_FULL);
+
+    printf("FAKE-08 for Xbox 360 (libxenon)\n");
+    printf(" * usb init\n");
+    usb_init();
+    usb_do_poll();
+
+    printf(" * mounting storage\n");
+    fatInitDefault();
+    findStorage();
+    printf(" * using %s\n", deviceRoot.c_str());
+
+    std::string base = deviceRoot + "fake08";
+    mkdir(base.c_str(), 0777);
+    mkdir((base + "/cdata").c_str(), 0777);
+
+    hasControllerSettings = true;
+    saveSettingsOnChange = true;
+
+    _logFilePrefix = base + "/";
+    _cartDirectory = deviceRoot + "p8carts";
+}
+
+void Host::setPlatformParams(
+    int windowWidth,
+    int windowHeight,
+    uint32_t sdlWindowFlags,
+    uint32_t sdlRendererFlags,
+    uint32_t sdlPixelFormat,
+    std::string logFilePrefix,
+    std::string customBiosLua,
+    std::string cartDirectory) {}
+
+void Host::oneTimeSetup(Audio *audio) {
+    fbInit();
+
+    audioSetup();
+
+    stretch = PixelPerfectStretch;
+    currKDown = 0;
+    currKHeld = 0;
+
+    loadSettingsIni();
+    _changeStretch(stretch);
+
+    scaleX = destW / (float)PicoScreenWidth;
+    scaleY = destH / (float)PicoScreenHeight;
+    mouseOffsetX = destX;
+    mouseOffsetY = destY;
+
+    calibrateVsync();
+    lastFrameTb = mftb();
+}
+
+void Host::oneTimeCleanup() {
+    saveSettingsIni();
+}
+
+void Host::setTargetFps(int targetFps) {
+    if (targetFps <= 0) targetFps = 60;
+    targetFrameTb = PPC_TIMEBASE_FREQ / targetFps;
+}
+
+void Host::changeStretch() {
+    if (stretchKeyPressed && resizekey == YesResize) {
+        switch (stretch) {
+            case PixelPerfectStretch:    stretch = PixelPerfect; break;
+            case PixelPerfect:           stretch = StretchToFit; break;
+            case StretchToFit:           stretch = StretchToFill; break;
+            case StretchToFill:          stretch = FourByThreeVertPerfect; break;
+            case FourByThreeVertPerfect: stretch = FourByThreeStretch; break;
+            default:                     stretch = PixelPerfectStretch; break;
+        }
+        forceStretch(stretch);
+    }
+}
+
+void Host::forceStretch(StretchOption newStretch) {
+    _changeStretch(newStretch);
+    stretch = newStretch;
+    scaleX = destW / (float)PicoScreenWidth;
+    scaleY = destH / (float)PicoScreenHeight;
+    mouseOffsetX = destX;
+    mouseOffsetY = destY;
+}
+
+InputState_t Host::scanInput() {
+    static const int DeadzoneThresholds[3] = {8000, 16000, 24000};
+    const int StickThreshold = DeadzoneThresholds[(deadzone >= 0 && deadzone <= 2) ? deadzone : 1];
+
+    usb_do_poll();
+    controller_data_s c;
+    memset(&c, 0, sizeof(c));
+    get_controller_data(&c, 0);
+
+    uint8_t held = 0;
+    if (c.left  || c.s1_x < -StickThreshold) held |= P8_KEY_LEFT;
+    if (c.right || c.s1_x >  StickThreshold) held |= P8_KEY_RIGHT;
+    if (c.up    || c.s1_y >  StickThreshold) held |= P8_KEY_UP;
+    if (c.down  || c.s1_y < -StickThreshold) held |= P8_KEY_DOWN;
+    // Layout 0 (PICO-8 default): A/Y = O, B/X = X. Layout 1 swaps them.
+    uint8_t bottomKey = btnlayout == 1 ? P8_KEY_X : P8_KEY_O;
+    uint8_t rightKey  = btnlayout == 1 ? P8_KEY_O : P8_KEY_X;
+    if (c.a || c.y) held |= bottomKey;
+    if (c.b || c.x) held |= rightKey;
+    if (c.start)    held |= P8_KEY_PAUSE;
+
+    static bool backWasDown = false;
+    stretchKeyPressed = c.back && !backWasDown && !c.start;
+    backWasDown = c.back;
+
+    // BACK + START quits back to XeLL
+    if (c.back && c.start) quit = 1;
+
+    // Debounce releases: a button only counts as released after it has read
+    // "up" for ReleaseFrames consecutive polls. Presses register immediately.
+    // Stops one physical press from being seen as several (menu skipping).
+    const int ReleaseFrames = 3;
+    static uint8_t upCount[8] = {0};
+    uint8_t debounced = 0;
+    for (int i = 0; i < 8; i++) {
+        uint8_t bit = (uint8_t)(1 << i);
+        if (held & bit) {
+            upCount[i] = 0;
+            debounced |= bit;
+        } else if ((currKHeld & bit) && ++upCount[i] < ReleaseFrames) {
+            debounced |= bit;   // still treat as held until release is stable
+        }
+    }
+
+    currKDown = debounced & ~currKHeld;
+    currKHeld = debounced;
+
+    return InputState_t{
+        currKDown,
+        currKHeld,
+        0, 0, 0
+    };
+}
+
+bool Host::shouldQuit() {
+    return quit > 0;
+}
+
+void Host::waitForTargetFps() {
+    // In vsync mode drawFrame() blocks on vblank, which paces the loop.
+    if (vsyncMode) return;
+
+    uint64_t now = mftb();
+    uint64_t elapsed = now - lastFrameTb;
+    if (elapsed < targetFrameTb) {
+        uint64_t remainingUs = (targetFrameTb - elapsed) / (PPC_TIMEBASE_FREQ / 1000000);
+        if (remainingUs > 0) udelay((int)remainingUs);
+        lastFrameTb += targetFrameTb;
+    } else {
+        // Running behind: don't try to catch up with a burst of frames
+        lastFrameTb = now;
+    }
+}
+
+void Host::drawFrame(uint8_t *picoFb, uint8_t *screenPaletteMap, uint8_t drawMode) {
+    if (!fb) return;
+
+    // Keep console/log output visible until the first frame, which makes early
+    // crashes easy to diagnose. From here on the screen belongs to the game.
+    if (stdout_hook) stdout_hook = nullptr;
+
+    if (needClear) {
+        fbClear();
+        needClear = false;
+    }
+
+    // 1. palette lookup + drawMode transform into a 128x128 RGB buffer
+    uint32_t pal[16];
+    for (int i = 0; i < 16; i++) {
+        pal[i] = fbColor(_paletteColors[screenPaletteMap[i] & 0x8f]);
+    }
+    for (int y = 0; y < PicoScreenHeight; y++) {
+        for (int x = 0; x < PicoScreenWidth; x++) {
+            int sx, sy;
+            srcCoord(drawMode, x, y, sx, sy);
+            frameRgb[y * PicoScreenWidth + x] = pal[getPixelNibble(sx, sy, picoFb)];
+        }
+    }
+
+    // 2. In vsync mode start writing at the beginning of vblank. The blit is
+    //    much faster than scanout, so we stay ahead of the beam: no tearing.
+    if (vsyncMode && !waitVBlankStart()) {
+        // vblank stopped toggling (mode change?) - fall back to the timer
+        if (++vsyncMisses > 10) vsyncMode = false;
+    }
+
+    // 3. nearest-neighbour scale into the tiled framebuffer, flushing each
+    //    32-line tile band from the CPU cache as soon as it is complete.
+    const size_t tileRowBytes = (size_t)fbPitchW * 32 * 4;
+    int band = destY >> 5;
+    for (int dy = 0; dy < destH; dy++) {
+        const uint32_t *srcRow = &frameRgb[yMap[dy] * PicoScreenWidth];
+        int y = destY + dy;
+        if ((y >> 5) != band) {
+            memdcbst((uint8_t *)fb + band * tileRowBytes, tileRowBytes);
+            band = y >> 5;
+        }
+        for (int dx = 0; dx < destW; dx++) {
+            fb[tiledIndex(destX + dx, y)] = srcRow[xMap[dx]];
+        }
+    }
+    memdcbst((uint8_t *)fb + band * tileRowBytes, tileRowBytes);
+}
+
+bool Host::shouldFillAudioBuff() {
+    if (!audioInitialized) return false;
+
+    int queuedBytes = xenon_sound_get_unplayed();
+    int missingBytes = TargetQueuedBytes - queuedBytes;
+    if (missingBytes <= 0) {
+        coreFrames = 0;
+        return false;
+    }
+    size_t outFrames = (size_t)missingBytes / 4;
+    size_t frames = outFrames * CoreRate / OutRate + 1;
+    if (frames > (size_t)MaxCoreFrames) frames = MaxCoreFrames;
+    coreFrames = frames;
+    return true;
+}
+
+void *Host::getAudioBufferPointer() {
+    return coreBuf;
+}
+
+size_t Host::getAudioBufferSize() {
+    return coreFrames;
+}
+
+void Host::playFilledAudioBuffer() {
+    audioPlayChunk();
+    coreFrames = 0;
+}
+
+bool Host::shouldRunMainLoop() {
+    return !quit;
+}
+
+vector<string> Host::listcarts() {
+    vector<string> carts;
+
+    DIR *dir = opendir(_cartDirectory.c_str());
+    if (dir != NULL) {
+        struct dirent *ent;
+        while ((ent = readdir(dir)) != NULL) {
+            if (isCartFile(ent->d_name)) {
+                carts.push_back(_cartDirectory + "/" + ent->d_name);
+            }
+        }
+        closedir(dir);
+    }
+
+    return carts;
+}
+
+const char *Host::logFilePrefix() {
+    return _logFilePrefix.c_str();
+}
+
+std::string Host::customBiosLua() {
+    // The BIOS runs a cart with X: that is B in layout 0 and A in layout 1.
+    return "cartpath = \"" + _cartDirectory + "/\"\n"
+           "selectbtn = \"" + std::string(btnlayout == 1 ? "a" : "b") + "\"\n"
+           "pausebtn = \"start\"\n"
+           "exitbtn = \"back + start\"\n"
+           "sizebtn = \"back to cycle screen sizes\"";
+}
+
+std::string Host::getCartDirectory() {
+    return _cartDirectory;
+}
+
+std::vector<std::string> Host::listdirs() {
+    std::vector<std::string> dirs;
+
+    DIR *dir = opendir(_cartDirectory.c_str());
+    if (dir != NULL) {
+        struct dirent *ent;
+        while ((ent = readdir(dir)) != NULL) {
+            if (ent->d_name[0] == '.') continue;
+            std::string fullPath = _cartDirectory + "/" + ent->d_name;
+            if (dirExists(fullPath)) dirs.push_back(ent->d_name);
+        }
+        closedir(dir);
+    }
+
+    return dirs;
+}
diff --git a/source/FakoSettings.h b/source/FakoSettings.h
index 13d6bcc..0aa55fa 100644
--- a/source/FakoSettings.h
+++ b/source/FakoSettings.h
@@ -83,6 +83,21 @@ function _init()
 	}


+	if __getsetting('hascontroller') == 1 then
+		settings['btnlayout'] = __getsetting('btnlayout') + 1
+		settings['deadzone'] = __getsetting('deadzone') + 1
+		add(list[1].ops, {
+			name = 'controller layout',
+			vn = 'btnlayout',
+			ch ={'a=🅾️ b=❎','a=❎ b=🅾️'}
+		})
+		add(list[1].ops, {
+			name = 'stick deadzone',
+			vn = 'deadzone',
+			ch ={'low','medium','high'}
+		})
+	end
+
 	if showpackinoptions then
 		add(list,
 			{name='pack-in carts',ops = {
diff --git a/source/host.h b/source/host.h
index 6aceffb..d19abd6 100644
--- a/source/host.h
+++ b/source/host.h
@@ -78,6 +78,14 @@ class Host {
     ResizekeyOption resizekey = YesResize;
     MenuStyleOption menustyle = Classic;
     BgColorOption bgcolor = Gray;
+    // controller settings (only shown in the settings cart when the platform
+    // sets hasControllerSettings)
+    bool hasControllerSettings = false;
+    int btnlayout = 0;   // 0: confirm/jump on bottom face button, 1: swapped
+    int deadzone = 1;    // 0: low, 1: medium, 2: high
+    // write settings.ini on every change (for consoles that are usually just
+    // switched off instead of exited cleanly)
+    bool saveSettingsOnChange = false;

     float scaleX = 1.0;
     float scaleY = 1.0;
@@ -91,6 +99,7 @@ class Host {

     void loadSettingsIni();
     void saveSettingsIni();
+    void setSettingValue(std::string sname, int sval);

     std::string getCartDataFile(std::string cartDataKey);

diff --git a/source/hostCommonFunctions.cpp b/source/hostCommonFunctions.cpp
index 96b255f..ff19c61 100644
--- a/source/hostCommonFunctions.cpp
+++ b/source/hostCommonFunctions.cpp
@@ -164,6 +164,10 @@ void Host::loadSettingsIni(){
 	//bgcolor
 	long bgcolorSetting = settingsIni.GetLongValue("settings", "bgcolor", (long)Gray);
 	bgcolor = (BgColorOption) bgcolorSetting;
+
+	//controller
+	btnlayout = (int)settingsIni.GetLongValue("settings", "btnlayout", 0);
+	deadzone = (int)settingsIni.GetLongValue("settings", "deadzone", 1);
 }

 void Host::saveSettingsIni(){
@@ -180,13 +184,18 @@ void Host::saveSettingsIni(){
     settingsIni.SetLongValue("settings", "kbmode", kbmode);
     settingsIni.SetLongValue("settings", "menustyle", menustyle);
     settingsIni.SetLongValue("settings", "bgcolor", bgcolor);
+
+    if (hasControllerSettings) {
+        settingsIni.SetLongValue("settings", "btnlayout", btnlayout);
+        settingsIni.SetLongValue("settings", "deadzone", deadzone);
+    }

     std::string settingsIniStr = "";
     settingsIni.Save(settingsIniStr, false);

     std::string iniPath = _logFilePrefix + "settings.ini";

-    FILE * file = freopen(iniPath.c_str(), "w", stderr);
+    FILE * file = fopen(iniPath.c_str(), "w");
     if( file != NULL ) {
 		//Initialize data
         fprintf(file, "%s", settingsIniStr.c_str());
@@ -206,7 +215,7 @@ std::string Host::getCartDataFileContents(std::string cartDataKey) {
 }

 void Host::saveCartData(std::string cartDataKey, std::string contents) {
-    FILE * file = freopen(getCartDataFile(cartDataKey).c_str(), "w", stderr);
+    FILE * file = fopen(getCartDataFile(cartDataKey).c_str(), "w");
     if( file != NULL ) {
 		//Initialize data
         fprintf(file, "%s", contents.c_str());
@@ -220,7 +229,7 @@ void Host::saveCartData(std::string cartDataKey, std::string contents) {
 size_t Host::getFileContents(std::string fileName, char* buffer) {
 	std::string absPath = _logFilePrefix + "cdata/" + fileName;
     //get_file_bin_contents(absPath, buffer, length);
-	FILE * file = freopen(absPath.c_str(), "rb", stderr);
+	FILE * file = fopen(absPath.c_str(), "rb");
     if( file != NULL ) {
 		//Initialize data
 		size_t len;
@@ -237,7 +246,7 @@ size_t Host::getFileContents(std::string fileName, char* buffer) {

 void Host::writeBufferToFile(std::string fileName, char* buffer, size_t length) {
 	std::string absPath = _logFilePrefix + "cdata/" + fileName;
-    FILE * file = freopen(absPath.c_str(), "w", stderr);
+    FILE * file = fopen(absPath.c_str(), "wb");
     if( file != NULL ) {
 		//Initialize data
 		fwrite(&length, sizeof(length), 1, file);
@@ -266,6 +275,12 @@ int Host::getSetting(std::string sname) {
 	}else if(sname == "bgcolor"){
 		Logger_Write("Returning bg color setting\n");
 		return bgcolor;
+	}else if(sname == "hascontroller"){
+		return hasControllerSettings ? 1 : 0;
+	}else if(sname == "btnlayout"){
+		return btnlayout;
+	}else if(sname == "deadzone"){
+		return deadzone;
 	}else if(sname == "p8_bgcolor"){

 		Logger_Write("Returning pico 8 bg color setting\n");
@@ -302,6 +317,14 @@ void Host::setCartDirectory(std::string cartDirectory) {
 }

 void Host::setSetting(std::string sname, int sval) {
+	setSettingValue(sname, sval);
+
+	if (saveSettingsOnChange) {
+		saveSettingsIni();
+	}
+}
+
+void Host::setSettingValue(std::string sname, int sval) {
 	if(sname == "kbmode"){ //why cant you use strings in switch statements in c++ :(
 		Logger_Write("setting KB mode\n");
 		kbmode = (KeyboardOption) sval;
@@ -327,6 +350,12 @@ void Host::setSetting(std::string sname, int sval) {
 		Logger_Write("setting bgcolor\n");
 		bgcolor = (BgColorOption) sval;

+	}else if(sname == "btnlayout"){
+		Logger_Write("setting btnlayout\n");
+		btnlayout = sval;
+	}else if(sname == "deadzone"){
+		Logger_Write("setting deadzone\n");
+		deadzone = sval;
 	}else if(sname == "packinloaded"){
 		Logger_Write("setting packinloaded\n");

diff --git a/source/main.cpp b/source/main.cpp
index b093c1e..4e8c01c 100644
--- a/source/main.cpp
+++ b/source/main.cpp
@@ -26,7 +26,13 @@ int main(int argc, char* argv[])
 	int windowHeight = 0;
 	int opt;

-	while ((opt = getopt(argc, argv, "w:h:")) != -1) {
+#if __XENON__
+	// XeLL does not pass a usable argv (garbage pointers when loaded over TFTP)
+	argc = 0;
+	optind = 0;
+#endif
+
+	while (argc > 0 && (opt = getopt(argc, argv, "w:h:")) != -1) {
     	switch (opt) {
     		case 'w': windowWidth = (int)strtol(optarg, NULL, 10); break;
     		case 'h': windowHeight = (int)strtol(optarg, NULL, 10); break;