foxygit / fake-08-xbox360 Log in
main xbox360 commits tags

/platform/xex/source/XexHost.cpp · 28.51 KB

raw
/*
 * Xbox 360 host for FAKE-08 as a native XEX (started from Aurora/FSD, runs
 * under the dashboard; no XDK). Shares its logic with the libxenon host
 * (platform/xenon/source/XenonHost.cpp); the hardware access goes through
 * this platform's runtime instead:
 *   - video: xex_video (own GPU ring, VdSwap, two tiled front buffers, the
 *     Guide shows over the game),
 *   - input: XamInputGetState for four controllers,
 *   - files: game:/ (the XEX's folder), usb0:-usb2:, hdd:,
 *   - time: the CPU time base (49.875 MHz).
 *   - audio: xex_audio (the kernel's render driver, 48 kHz), resampled
 *     from the core's 22050 Hz mono.
 *
 * Exit: Xbox button -> Xbox Home in the Guide, or Back+Start.
 */
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>

#include <string>
#include <vector>
#include <exception>
#include <typeinfo>
#include <cxxabi.h>

#include "../../../source/host.h"
#include "../../../source/hostVmShared.h"
#include "../../../source/nibblehelpers.h"
#include "../../../source/logger.h"
#include "../../../source/filehelpers.h"
#include "../../../source/Audio.h"

#include "xex_runtime.h"
#include "xex_video.h"
#include "xex_input.h"
#include "xex_audio.h"

// 8x16 console font from libxenon (headers of the free60/libxenon image)
#include <console/font_8x16.h>

using namespace std;

#ifndef BUILD_ID
#define BUILD_ID "dev"
#endif

static const int PicoScreenWidth = 128;
static const int PicoScreenHeight = 128;

// ---------------------------------------------------------------------------
// Video
// ---------------------------------------------------------------------------

static bool videoOk = false;
static int fbWidth = 0, fbHeight = 0;     // displayed window
static int fbPitch = 0;                   // surface width (tiled indexing)
static int fbOriginX = 0, fbOriginY = 0;  // window inside the surface

// Destination rectangle inside the window
static int destX = 0, destY = 0, destW = 0, destH = 0;
static std::vector<uint8_t> xMap, yMap;   // dest pixel -> source pixel
static int clearFrames = 2;               // both front buffers need clearing

static uint32_t frameRgb[PicoScreenWidth * PicoScreenHeight];
// Each source row scaled to the image's width (nearest neighbour)
static const int MaxDestWidth = 1920;
static uint32_t scaledRows[PicoScreenHeight * MaxDestWidth];

static const uint32_t OpaqueBlack = 0x000000ffu;   // opaque black (B, G, R, A)

static inline int tiledIndex(int x, int y) {
    return xex_video_tiled_index(fbOriginX + x, fbOriginY + y, fbPitch);
}

// Where each word of a 32x32 tile (4 KB, in address order) sits in the
// tile: the inverse of xex_video_tiled_index inside one tile. Writing a
// tile in address order keeps the write-combined stores sequential.
static uint8_t tileX[1024], tileY[1024];

static void initTileOrder() {
    for (int y = 0; y < 32; y++)
        for (int x = 0; x < 32; x++) {
            int m = xex_video_tiled_index(x, y, 32);
            tileX[m] = (uint8_t)x;
            tileY[m] = (uint8_t)y;
        }
}

static inline uint32_t fbColor(const Color &c) {
    return xex_video_rgb(c.Red, c.Green, c.Blue);
}

static void videoTrace(const char *fmt, ...) {
    char line[256];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(line, sizeof(line), fmt, ap);
    va_end(ap);
    Logger_Write("video: %s\n", line);
}

static bool fbInit() {
    xex_video_trace = videoTrace;
    int failed = xex_video_init();
    xex_video_trace = nullptr;   // init only; flips stay quiet
    if (failed) {
        Logger_Write("video init failed: %s\n", xex_video_error());
        return false;
    }
    // A frame tells the window; xex_video_begin also returns the back buffer.
    xex_frame f = xex_video_begin();
    fbWidth = f.window_width;
    fbHeight = f.window_height;
    fbPitch = f.pitch;
    fbOriginX = f.window_x;
    fbOriginY = f.window_y;
    Logger_Write("video: %dx%d window at %d,%d, pitch %d\n", fbWidth, fbHeight, fbOriginX, fbOriginY, fbPitch);
    initTileOrder();
    return true;
}

static void setDestRect(int w, int h) {
    if (w > MaxDestWidth) w = MaxDestWidth;
    if (w > fbWidth) w = fbWidth;
    if (h > fbHeight) h = fbHeight;
    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);
    clearFrames = 2;
}

static void _changeStretch(StretchOption s) {
    int intScale = fbHeight / PicoScreenHeight;
    if (intScale < 1) intScale = 1;

    switch (s) {
        case PixelPerfect:
            setDestRect(PicoScreenWidth, PicoScreenHeight);
            break;
        case StretchToFit:
            setDestRect(fbHeight, fbHeight);
            break;
        case StretchToFill:
            setDestRect(fbWidth, fbHeight);
            break;
        case FourByThreeVertPerfect:
            setDestRect(intScale * PicoScreenHeight * 4 / 3, intScale * PicoScreenHeight);
            break;
        case FourByThreeStretch:
            setDestRect(fbHeight * 4 / 3, fbHeight);
            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;
    }
}

// ---------------------------------------------------------------------------
// Timing: the CPU time base. At 60 fps the display paces the loop (one flip
// per refresh); other rates use the timer.
// ---------------------------------------------------------------------------

static uint64_t tbFreq = 49875000ull;
static uint64_t lastFrameTb = 0;
static uint64_t targetFrameTb = 49875000ull / 60;
static bool vsyncMode = true;

static inline uint64_t now() { return xex_timebase(); }

// ---------------------------------------------------------------------------
// Audio: 22050 Hz mono from the core -> 48 kHz float frames of 256 samples
// for the render driver, the same sample on front left and right.
// ---------------------------------------------------------------------------

static const int CoreRate = 22050;
static const int OutRate = XEX_AUDIO_RATE;
// The queue is topped up several times a frame (before the vblank wait,
// after the flip, during timer waits), so it only has to cover the longest
// gap between top-ups: 5 x 5.33 ms = ~27 ms ahead. Xbox 360 games have
// ~21 ms in XAudio2 itself; RetroArch defaults to 64 ms.
static const unsigned TargetQueuedFrames = 5;
static const int MaxCoreFrames = 2048;

static uint32_t coreBuf[MaxCoreFrames];
static size_t coreFrames = 0;
static float pendingOut[XEX_AUDIO_FRAME_SAMPLES];
static int pendingCount = 0;          // samples of the frame being built
static double resamplePos = 0.0;      // fractional position carried between chunks
static int16_t resamplePrev = 0;      // last core sample of the previous chunk
static bool audioOk = false;
static Audio *coreAudio = nullptr;
static unsigned audioDropped = 0;     // frames lost to a full ring

static void audioSetup() {
    audioOk = xex_audio_open() == 0;
    Logger_Write("audio: %s\n", audioOk ? "render driver client registered" : "XAudio registration failed");
}

static void pushOutSample(float v) {
    pendingOut[pendingCount++] = v;
    if (pendingCount < XEX_AUDIO_FRAME_SAMPLES) return;
    pendingCount = 0;
    float *frame = xex_audio_next();
    if (!frame) { audioDropped++; return; }
    memcpy(frame, pendingOut, sizeof(pendingOut));                              // front left
    memcpy(frame + XEX_AUDIO_FRAME_SAMPLES, pendingOut, sizeof(pendingOut));    // front right
    xex_audio_queue();
}

static void audioPlayChunk();

// Makes core audio up to the queue target, straight away (the core's own
// once-a-frame fill after the flip is turned off: shouldFillAudioBuff).
static void audioTopUp() {
    if (!audioOk || !coreAudio) return;
    unsigned queued = xex_audio_queued();
    if (queued >= TargetQueuedFrames) return;
    int missingOut = (int)(TargetQueuedFrames - queued) * XEX_AUDIO_FRAME_SAMPLES - pendingCount;
    if (missingOut <= 0) return;
    size_t frames = (size_t)missingOut * CoreRate / OutRate + 1;
    if (frames > (size_t)MaxCoreFrames) frames = MaxCoreFrames;
    coreAudio->FillAudioBuffer(coreBuf, 0, frames);
    coreFrames = frames;
    audioPlayChunk();
    coreFrames = 0;
}

static void audioPlayChunk() {
    if (!audioOk || coreFrames == 0) return;

    const double step = (double)CoreRate / OutRate;
    size_t n = coreFrames;
    double pos = resamplePos;   // index into [prev, s0, s1, ... s(n-1)]
    while (pos + 1.0 <= (double)n) {
        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);
        pushOutSample((float)(a + (b - a) * frac) * (1.0f / 32768.0f));
        pos += step;
    }
    resamplePos = pos - (double)n;
    resamplePrev = (int16_t)(coreBuf[n - 1] & 0xffff);
}

// ---------------------------------------------------------------------------
// Storage
// ---------------------------------------------------------------------------

static bool dirExists(const std::string &path) {
    DIR *d = opendir(path.c_str());
    if (d) { closedir(d); return true; }
    return false;
}

// Carts: the roms folder next to the XEX (created when missing). Settings,
// saves and the log stay next to the XEX too (game:/fake08).
static std::string findCartDirectory() {
    std::string dir = "game:/roms";
    if (!dirExists(dir)) mkdir(dir.c_str(), 0777);
    return dir;
}

// ---------------------------------------------------------------------------
// Performance overlay (settings -> dev -> performance overlay), drawn in the
// border left of the game image; numbers refresh once per second.
// ---------------------------------------------------------------------------

static bool perfOverlay = false;   // mirrors the 'perfoverlay' setting
static uint64_t perfLastDrawEnd = 0;
static uint64_t perfSleepTb = 0;
static uint64_t perfLastFrame = 0;
static uint64_t perfWindowStart = 0;
static uint64_t perfLogStart = 0;
struct PerfAcc { uint64_t sum, max; void add(uint64_t v){ sum += v; if (v > max) max = v; } };
static PerfAcc accEmu = {0,0}, accBlit = {0,0}, accWait = {0,0};
static int perfFrames = 0, perfSlow = 0;
static char perfLines[5][24] = {"", "", "", "", ""};
static int perfOverlayX = -1;        // where it was drawn, -1 when not on screen
static int perfOverlayCleared = 0;

static inline double tbToMs(uint64_t tb) { return (double)tb * 1000.0 / (double)tbFreq; }

static void drawText(uint32_t *pixels, int px, int py, const char *str) {
    const uint32_t white = xex_video_rgb(255, 255, 255);
    for (; *str; str++, px += 8) {
        const unsigned char *glyph = &fontdata_8x16[(unsigned char)*str * 16];
        for (int gy = 0; gy < 16; gy++) {
            unsigned char bits = glyph[gy];
            for (int gx = 0; gx < 8; gx++) {
                pixels[tiledIndex(px + gx, py + gy)] = (bits & (0x80 >> gx)) ? white : OpaqueBlack;
            }
        }
    }
}

// Drawn every frame: the two front buffers alternate. In the border left
// of the game image when it fits (15 characters = 120 px, the border is
// 128 px at 3x on 640x480), else over the top left corner of the image.
static const int PerfChars = 15;

static void drawPerfOverlay(uint32_t *pixels) {
    const int lines = 5;
    const int w = PerfChars * 8;
    if (!perfOverlay && perfOverlayX < 0) return;
    int x = destX >= w + 4 ? (destX - w) / 2 : 0;
    const int y = 8;
    if (!perfOverlay) {
        // turned off: blank where it was, once per front buffer
        if (perfOverlayX >= 0) {
            for (int py = y; py < y + lines * 16; py++)
                for (int px = perfOverlayX; px < perfOverlayX + w; px++) pixels[tiledIndex(px, py)] = OpaqueBlack;
            if (++perfOverlayCleared >= 2) { perfOverlayX = -1; perfOverlayCleared = 0; clearFrames = 2; }
        }
        return;
    }
    perfOverlayX = x;
    perfOverlayCleared = 0;
    char padded[PerfChars + 1];
    for (int i = 0; i < lines; i++) {
        snprintf(padded, sizeof(padded), "%-*.*s", PerfChars, PerfChars, perfLines[i]);
        drawText(pixels, x, y + i * 16, padded);
    }
}

static void perfFrameDone(uint64_t emuTb, uint64_t waitTb, uint64_t blitTb, uint64_t t) {
    accEmu.add(emuTb); accWait.add(waitTb); accBlit.add(blitTb);
    perfFrames++;
    // "slow": more than 1.5 refresh periods since the last frame
    if (perfLastFrame && (t - perfLastFrame) > (tbFreq / 60) * 3 / 2) perfSlow++;
    perfLastFrame = t;

    if (t - perfWindowStart >= tbFreq) {
        int n = perfFrames ? perfFrames : 1;
        snprintf(perfLines[0], 24, "%s %dfps s%d", vsyncMode ? "vs" : "tm", perfFrames, perfSlow);
        snprintf(perfLines[1], 24, "emu  %4.1f/%4.1f", tbToMs(accEmu.sum / n), tbToMs(accEmu.max));
        snprintf(perfLines[2], 24, "blit %4.1f/%4.1f", tbToMs(accBlit.sum / n), tbToMs(accBlit.max));
        snprintf(perfLines[3], 24, "wait %4.1f/%4.1f", tbToMs(accWait.sum / n), tbToMs(accWait.max));
        snprintf(perfLines[4], 24, "%dx%d %d", fbWidth, fbHeight, destW);
        if (t - perfLogStart >= 5 * tbFreq) {
            Logger_Write("perf: %s | %s | %s | %s | %s (avg/max ms) | audio queued %u underruns %u dropped %u\n",
                         perfLines[0], perfLines[1], perfLines[2], perfLines[3], perfLines[4],
                         xex_audio_queued(), xex_audio_underruns(), audioDropped);
            perfLogStart = t;
        }
        accEmu = {0,0}; accBlit = {0,0}; accWait = {0,0};
        perfFrames = 0; perfSlow = 0;
        perfWindowStart = t;
    }
}

// ---------------------------------------------------------------------------
// Host
// ---------------------------------------------------------------------------

// An uncaught C++ exception ends up here: log it before the title dies.
static void logTerminate() {
    const char *what = "unknown";
    std::string type = "?";
    if (std::exception_ptr e = std::current_exception()) {
        if (std::type_info *t = abi::__cxa_current_exception_type()) type = t->name();
        try {
            std::rethrow_exception(e);
        } catch (const std::exception &ex) {
            Logger_Write("terminate: uncaught %s: %s\n", type.c_str(), ex.what());
            what = nullptr;
        } catch (...) {
        }
    }
    if (what) Logger_Write("terminate: uncaught exception of type %s\n", type.c_str());
    xex_notify("FAKE-08 crashed (see fake08/pico.log)");
    xex_sleep_ms(3000);
    abort();
}

Host::Host(int windowWidth, int windowHeight) {
    std::set_terminate(logTerminate);
    // Settings, saves and the log next to the XEX; the hard disk when that
    // folder can't be written (read-only media; Xenia: cache:).
    std::string base = "game:/fake08";
    for (const char *candidate : {"game:/fake08", "hdd:/fake08", "cache:/fake08"}) {
        mkdir(candidate, 0777);
        std::string probe = std::string(candidate) + "/.write-test";
        if (FILE *f = fopen(probe.c_str(), "w")) {
            fclose(f);
            remove(probe.c_str());
            base = candidate;
            break;
        }
    }
    mkdir((base + "/cdata").c_str(), 0777);

    hasControllerSettings = true;
    saveSettingsOnChange = true;
    hasPerfOverlay = true;

    _logFilePrefix = base + "/";
    _cartDirectory = findCartDirectory();
}

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) {
    Logger_Write("FAKE-08 for Xbox 360 (XEX) %s, built %s %s, carts in %s\n", BUILD_ID, __DATE__, __TIME__,
                 _cartDirectory.c_str());
    videoOk = fbInit();
    if (!videoOk) {
        xex_notify("FAKE-08: video init failed");
        quit = 1;
        return;
    }

    stretch = PixelPerfectStretch;
    currKDown = 0;
    currKHeld = 0;

    loadSettingsIni();
    _changeStretch(stretch);

    scaleX = destW / (float)PicoScreenWidth;
    scaleY = destH / (float)PicoScreenHeight;
    mouseOffsetX = destX;
    mouseOffsetY = destY;

    coreAudio = audio;
    audioSetup();
    lastFrameTb = now();
}

void Host::oneTimeCleanup() {
    saveSettingsIni();
    // Returning from main ends the title (XamLoaderTerminateTitle), which
    // goes back to Aurora; the video runtime gives the GPU back at exit.
}

void Host::setTargetFps(int targetFps) {
    if (targetFps <= 0) targetFps = 60;
    targetFrameTb = tbFreq / targetFps;
    vsyncMode = targetFps == 60;
}

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;
}

// Maps one controller to PICO-8 button bits (without the pause button).
static uint8_t padToButtons(const xex_pad &c, int layout, int stickThreshold) {
    uint8_t held = 0;
    if ((c.buttons & XEX_PAD_LEFT)  || c.lx < -stickThreshold) held |= P8_KEY_LEFT;
    if ((c.buttons & XEX_PAD_RIGHT) || c.lx >  stickThreshold) held |= P8_KEY_RIGHT;
    if ((c.buttons & XEX_PAD_UP)    || c.ly >  stickThreshold) held |= P8_KEY_UP;
    if ((c.buttons & XEX_PAD_DOWN)  || c.ly < -stickThreshold) held |= P8_KEY_DOWN;
    // Layout 0 (PICO-8 default): A/Y = O, B/X = X. Layout 1 swaps them.
    uint8_t bottomKey = layout == 1 ? P8_KEY_X : P8_KEY_O;
    uint8_t rightKey  = layout == 1 ? P8_KEY_O : P8_KEY_X;
    if (c.buttons & (XEX_PAD_A | XEX_PAD_Y)) held |= bottomKey;
    if (c.buttons & (XEX_PAD_B | XEX_PAD_X)) held |= rightKey;
    return held;
}

// Debounce releases (setting "button debounce"): a button only counts as
// released after it has read "up" for releaseFrames consecutive polls.
// Presses register immediately.
static uint8_t debounceButtons(uint8_t held, uint8_t prevHeld, uint8_t upCount[8], int releaseFrames) {
    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 ((prevHeld & bit) && ++upCount[i] < releaseFrames) {
            debounced |= bit;   // still treat as held until release is stable
        }
    }
    return debounced;
}

InputState_t Host::scanInput() {
    static const int DeadzoneThresholds[3] = {8000, 16000, 24000};
    const int stickThreshold = DeadzoneThresholds[(deadzone >= 0 && deadzone <= 2) ? deadzone : 1];
    const int releaseFrames = ((debounce >= 0 && debounce <= 3) ? debounce : 1) + 1;

    static uint8_t upCount[4][8] = {};
    static uint8_t extraHeld[3] = {0, 0, 0};

    // Player 1 (port 0) also drives the system buttons. While the Guide is
    // open XAM keeps the controllers, which then read as released.
    xex_pad c;
    xex_input_get(0, &c);

    uint8_t held = padToButtons(c, btnlayout, stickThreshold);
    bool start = c.buttons & XEX_PAD_START;
    bool back = c.buttons & XEX_PAD_BACK;
    if (start) held |= P8_KEY_PAUSE;

    static bool backWasDown = false;
    stretchKeyPressed = back && !backWasDown && !start;
    backWasDown = back;

    // BACK + START quits to Aurora (some dashboard plugins take this combo
    // for screenshots; the Guide's Xbox Home always works)
    if (back && start) quit = 1;

    uint8_t debounced = debounceButtons(held, currKHeld, upCount[0], releaseFrames);
    currKDown = debounced & ~currKHeld;
    currKHeld = debounced;

    InputState_t state{
        currKDown,
        currKHeld,
        0, 0, 0
    };

    // Players 2-4 (ports 1-3). Disconnected controllers read as all zero.
    for (int p = 0; p < 3; p++) {
        xex_pad pc;
        xex_input_get(p + 1, &pc);
        uint8_t ph = debounceButtons(padToButtons(pc, btnlayout, stickThreshold),
                                     extraHeld[p], upCount[p + 1], releaseFrames);
        state.extraKDown[p] = ph & ~extraHeld[p];
        state.extraKHeld[p] = ph;
        extraHeld[p] = ph;
    }

    return state;
}

bool Host::shouldQuit() {
    // never end by ourselves while the Guide shows (XAM would wait for a
    // swap that never comes); Xbox Home ends the title from there anyway
    return quit > 0 && !xex_video_guide_visible();
}

void Host::waitForTargetFps() {
    // At 60 fps drawFrame() waits for the previous flip, which paces the loop.
    if (vsyncMode) return;

    uint64_t t = now();
    uint64_t elapsed = t - lastFrameTb;
    if (elapsed < targetFrameTb) {
        uint64_t remaining = targetFrameTb - elapsed;
        // sleep in slices of up to 4 ms, keeping the audio queue topped up
        for (;;) {
            audioTopUp();
            uint64_t left = targetFrameTb - (now() - lastFrameTb);
            if ((int64_t)left <= 0) break;
            unsigned ms = (unsigned)(left * 1000 / tbFreq);
            if (ms <= 1) break;
            xex_sleep_ms(ms - 1 > 4 ? 4 : ms - 1);
        }
        while (now() - lastFrameTb < targetFrameTb) {}
        perfSleepTb += remaining;
        lastFrameTb += targetFrameTb;
    } else {
        // Running behind: don't try to catch up with a burst of frames
        lastFrameTb = t;
    }
}

void Host::drawFrame(uint8_t *picoFb, uint8_t *screenPaletteMap, uint8_t drawMode) {
    if (!videoOk) return;

    perfOverlay = perfoverlay == 1;
    uint64_t tbStart = now();
    uint64_t emuTb = perfLastDrawEnd ? (tbStart - perfLastDrawEnd - perfSleepTb) : 0;
    perfSleepTb = 0;

    // 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. the back buffer, once the previous flip is on screen (at 60 fps
    //    this wait is the frame pacing)
    audioTopUp();   // before the wait for the previous flip
    uint64_t tbWaitStart = now();
    xex_frame f = xex_video_begin();
    uint32_t *pixels = f.pixels;
    uint64_t tbBlitStart = now();

    if (clearFrames > 0) {
        // the whole surface, in address order
        size_t words = (size_t)fbPitch * (size_t)((fbOriginY + fbHeight + 31) & ~31);
        for (size_t i = 0; i < words; i++) pixels[i] = OpaqueBlack;
        clearFrames--;
    }

    // 3. nearest-neighbour scale into the tiled back buffer.
    //    a) each source row scaled across into cached memory
    for (int sy = 0; sy < PicoScreenHeight; sy++) {
        const uint32_t *src = &frameRgb[sy * PicoScreenWidth];
        uint32_t *row = &scaledRows[sy * MaxDestWidth];
        for (int dx = 0; dx < destW; dx++) row[dx] = src[xMap[dx]];
    }
    //    b) tiles in address order: in a 32x32 tile each pair of rows is 64
    //       words, eight groups of 4 pixels of the even row then 4 of the
    //       odd row; the group order flips (xor 4) when y & 8.
    const int x0 = fbOriginX + destX, y0 = fbOriginY + destY;
    const int x1 = x0 + destW, y1 = y0 + destH;
    for (int ty = y0 & ~31; ty < y1; ty += 32) {
        for (int tx = x0 & ~31; tx < x1; tx += 32) {
            uint32_t *tile = pixels + xex_video_tiled_index(tx, ty, fbPitch);
            if (tx >= x0 && tx + 32 <= x1 && ty >= y0 && ty + 32 <= y1) {
                const int cx = tx - x0;
                for (int pair = 0; pair < 16; pair++) {
                    const int y = ty + pair * 2 - y0;
                    const uint32_t *even = &scaledRows[yMap[y] * MaxDestWidth + cx];
                    const uint32_t *odd = &scaledRows[yMap[y + 1] * MaxDestWidth + cx];
                    uint32_t *out = tile + pair * 64;
                    const int flip = (pair & 4) ? 4 : 0;
                    for (int g = 0; g < 8; g++) {
                        const int xg = (g ^ flip) * 4;
                        uint32_t *o = out + g * 8;
                        o[0] = even[xg]; o[1] = even[xg + 1]; o[2] = even[xg + 2]; o[3] = even[xg + 3];
                        o[4] = odd[xg];  o[5] = odd[xg + 1];  o[6] = odd[xg + 2];  o[7] = odd[xg + 3];
                    }
                }
            } else {
                // edge tile: only the words inside the image
                for (int m = 0; m < 1024; m++) {
                    int x = tx + tileX[m], y = ty + tileY[m];
                    if (x < x0 || x >= x1 || y < y0 || y >= y1) continue;
                    tile[m] = scaledRows[yMap[y - y0] * MaxDestWidth + (x - x0)];
                }
            }
        }
    }
    drawPerfOverlay(pixels);

    // 4. flip at the next vertical blank
    xex_video_present();
    audioTopUp();

    uint64_t tbEnd = now();
    perfFrameDone(emuTb + (tbWaitStart - tbStart), tbBlitStart - tbWaitStart, tbEnd - tbBlitStart, tbBlitStart);
    perfLastDrawEnd = now();
}

bool Host::shouldFillAudioBuff() {
    // the host fills audio itself (audioTopUp), several times a frame
    return false;
}

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;

    Logger_Write("listing carts in %s\n", _cartDirectory.c_str());
    DIR *dir = opendir(_cartDirectory.c_str());
    if (dir != NULL) {
        struct dirent *ent;
        int entries = 0;
        while ((ent = readdir(dir)) != NULL) {
            entries++;
            bool cart = isCartFile(ent->d_name);
            Logger_Write("  %s%s\n", ent->d_name, cart ? "" : " (skipped)");
            if (cart) {
                carts.push_back(_cartDirectory + "/" + ent->d_name);
            }
        }
        closedir(dir);
        Logger_Write("%d entries, %d carts\n", entries, (int)carts.size());
    } else {
        Logger_Write("opendir failed (errno %d)\n", errno);
    }

    return carts;
}

const char *Host::logFilePrefix() {
    return _logFilePrefix.c_str();
}

std::string Host::customBiosLua() {
    return "cartpath = \"" + _cartDirectory + "/\"\n"
           // file browser: A opens and B goes up a folder in either layout
           // (layout 0: A is O, layout 1: A is X)
           "selectbtn = \"a\"\n"
           "backbtn = \"b\"\n"
           "openkey = " + std::string(btnlayout == 1 ? "5" : "4") + "\n"
           "pausebtn = \"start\"\n"
           "exitbtn = \"xbox button > home\"\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;
}