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

/platform/xenon/source/XenonHost.cpp · 24.37 KB

raw
/*
 * 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 <xenon_smc/xenon_smc.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;
}

// ---------------------------------------------------------------------------
// Performance overlay (settings -> dev -> performance overlay). Drawn in the black border left of the
// game image; numbers are refreshed once per second.
// ---------------------------------------------------------------------------
#include <console/font_8x16.h>

static bool perfOverlay = false;   // mirrors the 'perfoverlay' setting
static uint64_t perfLastDrawEnd = 0;
static uint64_t perfSleepTb = 0;          // timer-mode sleep inside the frame
static uint64_t perfLastVblank = 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 inline uint32_t tbToUs(uint64_t tb) { return (uint32_t)(tb / (PPC_TIMEBASE_FREQ / 1000000)); }

static void drawText(int px, int py, const char *str) {
    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++) {
                fb[tiledIndex(px + gx, py + gy)] = (bits & (0x80 >> gx)) ? 0xFFFFFF00 : 0;
            }
        }
    }
}

static void drawPerfOverlay() {
    const int widthChars = 20, lines = 5;
    const int w = widthChars * 8;
    if (destX < w + 4) return;                   // no room beside the image
    const int x = (destX - w) / 2;               // centred in the left border
    const int y = 8 + safeY;
    char blank[widthChars + 1];
    memset(blank, ' ', widthChars); blank[widthChars] = 0;
    for (int i = 0; i < lines; i++) {
        drawText(x, y + i * 16, blank);
        if (perfOverlay) drawText(x, y + i * 16, perfLines[i]);
    }
    const size_t tileRowBytes = (size_t)fbPitchW * 32 * 4;
    int b0 = y >> 5, b1 = (y + lines * 16) >> 5;
    memdcbst((uint8_t *)fb + b0 * tileRowBytes, (b1 - b0 + 1) * tileRowBytes);
}

static void perfFrameDone(uint64_t emuTb, uint64_t waitTb, uint64_t blitTb, uint64_t now) {
    accEmu.add(emuTb); accWait.add(waitTb); accBlit.add(blitTb);
    perfFrames++;
    // a frame is "slow" if more than 1.5 refresh periods passed since the last one
    if (perfLastVblank && (now - perfLastVblank) > (PPC_TIMEBASE_FREQ / 60) * 3 / 2) perfSlow++;
    perfLastVblank = now;

    if (now - perfWindowStart >= PPC_TIMEBASE_FREQ) {
        int n = perfFrames ? perfFrames : 1;
        snprintf(perfLines[0], 24, "%s %dfps slow %d", vsyncMode ? "vsync" : "timer", perfFrames, perfSlow);
        snprintf(perfLines[1], 24, "emu  %5.1f/%5.1f", tbToUs(accEmu.sum / n) / 1000.0, tbToUs(accEmu.max) / 1000.0);
        snprintf(perfLines[2], 24, "blit %5.1f/%5.1f", tbToUs(accBlit.sum / n) / 1000.0, tbToUs(accBlit.max) / 1000.0);
        snprintf(perfLines[3], 24, "wait %5.1f/%5.1f", tbToUs(accWait.sum / n) / 1000.0, tbToUs(accWait.max) / 1000.0);
        snprintf(perfLines[4], 24, "%dx%d %dx%d", fbWidth, fbHeight, destW, destH);
        if (now - perfLogStart >= 5 * PPC_TIMEBASE_FREQ) {
            Logger_Write("perf: %s | %s | %s | %s | %s (avg/max ms)\n", perfLines[0], perfLines[1], perfLines[2], perfLines[3], perfLines[4]);
            perfLogStart = now;
        }
        accEmu = {0,0}; accBlit = {0,0}; accWait = {0,0};
        perfFrames = 0; perfSlow = 0;
        perfWindowStart = now;
    }
    drawPerfOverlay();
}

// ---------------------------------------------------------------------------
// 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;
    hasPerfOverlay = 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();

    // Exiting back to XeLL would just boot FAKE-08 again (XeLL autoboots
    // fake08.elf/xenon.elf), so reboot the console to the dashboard instead.
    xenon_smc_power_reboot();
    for (;;) {}
}

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

// Maps one controller to PICO-8 button bits (without the pause button).
static uint8_t padToButtons(const controller_data_s &c, int layout, int stickThreshold) {
    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 = layout == 1 ? P8_KEY_X : P8_KEY_O;
    uint8_t rightKey  = layout == 1 ? P8_KEY_O : P8_KEY_X;
    if (c.a || c.y) held |= bottomKey;
    if (c.b || c.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};

    usb_do_poll();

    // Player 1 (port 0) also drives the system buttons.
    controller_data_s c;
    memset(&c, 0, sizeof(c));
    get_controller_data(&c, 0);

    uint8_t held = padToButtons(c, btnlayout, stickThreshold);
    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;

    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++) {
        controller_data_s pc;
        memset(&pc, 0, sizeof(pc));
        get_controller_data(&pc, p + 1);
        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() {
    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);
        perfSleepTb += remainingUs * (PPC_TIMEBASE_FREQ / 1000000);
        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;

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

    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.
    uint64_t tbWaitStart = mftb();
    if (vsyncMode && !waitVBlankStart()) {
        // vblank stopped toggling (mode change?) - fall back to the timer
        if (++vsyncMisses > 10) vsyncMode = false;
    }

    uint64_t tbBlitStart = mftb();

    // 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);

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

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