#include <stdint.h>
#include <stddef.h>
#include "gba_base.h"
#include "ff.h"
#include "diskio.h"

#define REG_DISPCNT   (*(volatile uint16_t*)0x04000000)
#define REG_DISPSTAT  (*(volatile uint16_t*)0x04000004)
#define REG_VCOUNT    (*(volatile uint16_t*)0x04000006)
#define REG_KEYINPUT  (*(volatile uint16_t*)0x04000130)
#define REG_WAITCNT   (*(volatile uint16_t*)0x04000204)

#define REG_SOUNDCNT_L (*(volatile uint16_t*)0x04000080)
#define REG_SOUNDCNT_H (*(volatile uint16_t*)0x04000082)
#define REG_SOUNDCNT_X (*(volatile uint16_t*)0x04000084)
#define REG_SOUNDBIAS  (*(volatile uint16_t*)0x04000088)
#define REG_FIFO_A     (*(volatile uint32_t*)0x040000A0)

#define REG_DMA1SAD   (*(volatile uint32_t*)0x040000BC)
#define REG_DMA1DAD   (*(volatile uint32_t*)0x040000C0)
#define REG_DMA1CNT   (*(volatile uint32_t*)0x040000C4)

#define REG_TM0CNT_L  (*(volatile uint16_t*)0x04000100)
#define REG_TM0CNT_H  (*(volatile uint16_t*)0x04000102)
#define REG_TM1CNT_L  (*(volatile uint16_t*)0x04000104)
#define REG_TM1CNT_H  (*(volatile uint16_t*)0x04000106)

#define VRAM_FB       ((uint16_t*)0x06000000)
#define SRAM_BASE     ((volatile uint8_t*)0x0E000000)
#define PSRAM_WINDOW  ((volatile uint8_t*)0x08800000)

#define KEY_A      (1 << 0)
#define KEY_B      (1 << 1)
#define KEY_SELECT (1 << 2)
#define KEY_START  (1 << 3)
#define KEY_RIGHT  (1 << 4)
#define KEY_LEFT   (1 << 5)
#define KEY_UP     (1 << 6)
#define KEY_DOWN   (1 << 7)
#define KEY_R      (1 << 8)
#define KEY_L      (1 << 9)

#define RGB15(r,g,b) ((uint16_t)((r) | ((g) << 5) | ((b) << 10)))

extern int g_use_rom_vfat;
extern u32 g_sd_sectors_read_total;
extern DWORD Get_NextCluster(FFOBJID* obj, DWORD clst);
extern DWORD ClustToSect(FATFS* fs, DWORD clst);

#define REG_DMA3SAD   (*(volatile uint32_t*)0x040000D4)
#define REG_DMA3DAD   (*(volatile uint32_t*)0x040000D8)
#define REG_DMA3CNT   (*(volatile uint32_t*)0x040000DC)

/* Minimal freestanding string/memory functions required by FatFs */
void *memcpy(void *dst, const void *src, size_t n) {
    uint8_t *d = (uint8_t *)dst;
    const uint8_t *s = (const uint8_t *)src;
    if ((((uintptr_t)d | (uintptr_t)s) & 3) == 0) {
        while (n >= 4) {
            *(uint32_t *)d = *(const uint32_t *)s;
            d += 4; s += 4; n -= 4;
        }
    } else if ((((uintptr_t)d | (uintptr_t)s) & 1) == 0) {
        while (n >= 2) {
            *(uint16_t *)d = *(const uint16_t *)s;
            d += 2; s += 2; n -= 2;
        }
    }
    while (n--) *d++ = *s++;
    return dst;
}

void *memset(void *dst, int c, size_t n) {
    uint8_t *d = (uint8_t *)dst;
    uint8_t v = (uint8_t)c;
    while (n--) *d++ = v;
    return dst;
}

int memcmp(const void *s1, const void *s2, size_t n) {
    const uint8_t *p1 = (const uint8_t *)s1;
    const uint8_t *p2 = (const uint8_t *)s2;
    while (n--) {
        if (*p1 != *p2) return (int)*p1 - (int)*p2;
        p1++; p2++;
    }
    return 0;
}

char *strchr(const char *s, int c) {
    char ch = (char)c;
    while (*s) {
        if (*s == ch) return (char *)s;
        s++;
    }
    return (ch == 0) ? (char *)s : NULL;
}

size_t strlen(const char *s) {
    size_t n = 0;
    while (s[n]) n++;
    return n;
}

typedef struct {
    uint32_t magic;               // "AGV1" = 0x31564741
    uint32_t total_frames;
    uint32_t vblanks_per_frame;
    uint32_t audio_rate;
    uint32_t audio_per_vblank;
    uint32_t audio_offset;
    uint32_t keyframe_interval;
    uint32_t seek_15s_frames;
    uint32_t seek_30s_frames;
    uint32_t timer0_reload;
} AgvHeaderFixed;

typedef struct {
    char path[116];               // Full LFN path (up to 115 chars + NUL; fits all 157 Meteo music videos!)
    char name[36];                // Clean display title (release/codec/CRC32 tags stripped)
    uint32_t file_size;
    uint32_t hdr_offset;
    uint32_t total_frames;
    uint32_t audio_offset;
    uint32_t file_hash;           // FNV-1a hash of path ^ file_size ^ total_frames
    uint16_t fps;
    uint8_t  is_rom_demo;
    uint8_t  is_agv;
    uint8_t  is_dir;              // 0 = video file, 1 = subdirectory [DIR], 2 = parent directory [..]
    uint8_t  is_meteo;            // 0 = AGV1, 1 = Meteo 1.3.1 .GBA, 2 = Meteo 1.4.0/1.5.0 .GBA
    uint8_t  probed;              // 0 = lazy unprobed, 1 = probed valid video, 2 = non-video GBA
} SdVideoEntry;

typedef char assert_sd_video_entry_180_bytes[(sizeof(SdVideoEntry) == 180) ? 1 : -1];
#define MAX_VIDEOS           400
#define LOAD_BAR_HIDE        0
#define LOAD_BAR_SHOW        1
#define LOAD_BAR_FILE        2
#define CHAIN_OFF            0
#define CHAIN_NEXT           1
#define CHAIN_RANDOM         2
#define AUDIO_RING_PERIOD    65536
#define AUDIO_MIRROR_SIZE    8192
#define IDX_CACHE_SIZE       1024
#define EWRAM_VID_CACHE_SIZE 30720

/* Buffer modes:
 * 0 = EWRAM 80KB Burst (works on all carts & emulators; reads 96KB video + 32KB audio bursts, then SD_Disable)
 * 1 = PSRAM 4MB Burst  (uses EZ-FLASH 32MB PSRAM at 0x08800000 for 4MB video + 1MB audio bursts, then SD_Disable)
 * 2 = PSRAM 24MB Full  (caches up to 24MB video across PSRAM pages 0x1000..0x3000 + 6MB audio in page 0x0000)
 */
#define BUF_MODE_PSRAM_32M  0
#define BUF_MODE_DIRECT_SD  1
#define BUF_MODE_EWRAM_96K  2

static FATFS g_fs;
static FIL   g_file;
static __attribute__((aligned(4))) DWORD g_clmt[1024];
static __attribute__((aligned(16))) u32 g_fat_table_buf[256]; /* 0x400-byte EZ-FLASH Omega DE FAT DMA buffer */
static __attribute__((aligned(16))) int8_t g_audio_ring[AUDIO_RING_PERIOD + AUDIO_MIRROR_SIZE];
static __attribute__((aligned(4))) uint8_t g_video_chunk_buf[EWRAM_VID_CACHE_SIZE];
static __attribute__((aligned(4))) uint8_t g_frame_buf[10240];
static __attribute__((aligned(4))) uint32_t g_frame_idx_cache[IDX_CACHE_SIZE];
extern const uint8_t __iwram_lma[];
extern const uint8_t __iwram_start[];
extern const uint8_t __iwram_end[];
extern const uint8_t __ewram_code_lma[];
extern const uint8_t __ewram_code_start[];
extern const uint8_t __ewram_code_end[];
__attribute__((aligned(4))) uint8_t g_boot_hdr_backup[640];

static uint32_t g_idx_cache_base = 0;

static uint32_t g_ewram_vid_start = 0;
static uint32_t g_ewram_vid_end   = 0;

static int      g_has_psram          = 0;
static int      g_buf_mode           = BUF_MODE_PSRAM_32M;
#define CHAP_VID_MAX_BYTES  0x018F0000u /* 25 MiB compressed video slice per chapter */
#define CHAP_AUD_MAX_BYTES  0x00600000u /* 6 MiB PCM audio slice per chapter (~6.4 min @ 16.384 kHz) */

static int      g_linear_psram_mode  = 0; /* 1 = linear <=32MB, 2 = banked <=32MB, 3 = linear >32MB chapter, 4 = banked >32MB chapter */
static const uint8_t *g_linear_psram_ptr = 0;
static uint32_t g_loaded_psram_hash     = 0;
static uint32_t g_loaded_psram_aud_word = 0;
static uint32_t g_chap_loaded_hash      = 0;
static uint32_t g_chap_clmt_hash        = 0;
static uint32_t g_chap_start_frame      = 0;
static uint32_t g_chap_end_frame        = 0;
static uint32_t g_chap_vid_psram_off    = 0;
static uint32_t g_chap_aud_psram_off    = 0;
static uint32_t g_chap_vid_base         = 0;
static uint32_t g_chap_vid_end          = 0;
static uint32_t g_chap_aud_base         = 0;
static uint32_t g_chap_aud_end          = 0;
static uint32_t g_chap_exp_vid_first    = 0;
static uint32_t g_chap_exp_aud_first    = 0;
static uint32_t g_ram_bookmarks[MAX_VIDEOS];
static int      g_psram_idx_valid       = 0;
#define g_recent_items ((RecentVideoItem *)(&g_video_chunk_buf[28672]))
static uint32_t g_psram_aud_start    = 0;
static uint32_t g_psram_aud_end      = 0;
static uint32_t g_psram_vid_start    = 0;
static uint32_t g_psram_vid_end      = 0;

static SdVideoEntry g_entries[MAX_VIDEOS];
static int g_entry_count = 0;
static int g_sd_mounted = 0;
static int g_auto_chain = CHAIN_NEXT; /* 0 = OFF, 1 = NEXT, 2 = RANDOM (current dir) */
static int g_show_load_bar = 0; /* 0 = HIDE, 1 = SHOW, 2 = FILE (show on file open, hide on chapter transition) */
static int g_clean_names = 1;   /* 1 = ON (strip CRC32/720p/x264/release tags), 0 = OFF (show full raw filename) */
static int g_lr_jump_idx = 1;   /* 0=15s, 1=30s (default), 2=1m, 3=2m, 4=3m, 5=5m, 6=10m */
static const uint8_t __attribute__((aligned(4))) g_lr_jump_mults[8] = { 1, 2, 4, 8, 12, 20, 40, 40 };
static const char * const g_lr_jump_labels[7] = {
    "< +/- 15 SEC  >",
    "< +/- 30 SEC  >",
    "< +/- 1 MIN   >",
    "< +/- 2 MIN   >",
    "< +/- 3 MIN   >",
    "< +/- 5 MIN   >",
    "< +/- 10 MIN  >"
};
static int g_show_hud = 0;
static uint32_t g_rng_state = 0x9E3779B9u;
static char g_cur_dir[192];

/* Compact 5x7 ASCII font (chars 32..95, uppercase + digits + punctuation) */
static const uint8_t font5x7[64][5] = {
    {0x00,0x00,0x00,0x00,0x00}, // ' '
    {0x00,0x00,0x5F,0x00,0x00}, // '!'
    {0x00,0x07,0x00,0x07,0x00}, // '"'
    {0x14,0x7F,0x14,0x7F,0x14}, // '#'
    {0x24,0x2A,0x7F,0x2A,0x12}, // '$'
    {0x23,0x13,0x08,0x64,0x62}, // '%'
    {0x36,0x49,0x55,0x22,0x50}, // '&'
    {0x00,0x05,0x03,0x00,0x00}, // '\''
    {0x00,0x1C,0x22,0x41,0x00}, // '('
    {0x00,0x41,0x22,0x1C,0x00}, // ')'
    {0x14,0x08,0x3E,0x08,0x14}, // '*'
    {0x08,0x08,0x3E,0x08,0x08}, // '+'
    {0x00,0x50,0x30,0x00,0x00}, // ','
    {0x08,0x08,0x08,0x08,0x08}, // '-'
    {0x00,0x60,0x60,0x00,0x00}, // '.'
    {0x20,0x10,0x08,0x04,0x02}, // '/'
    {0x3E,0x51,0x49,0x45,0x3E}, // '0'
    {0x00,0x42,0x7F,0x40,0x00}, // '1'
    {0x42,0x61,0x51,0x49,0x46}, // '2'
    {0x21,0x41,0x45,0x4B,0x31}, // '3'
    {0x18,0x14,0x12,0x7F,0x10}, // '4'
    {0x27,0x45,0x45,0x45,0x39}, // '5'
    {0x3C,0x4A,0x49,0x49,0x30}, // '6'
    {0x01,0x71,0x09,0x05,0x03}, // '7'
    {0x36,0x49,0x49,0x49,0x36}, // '8'
    {0x06,0x49,0x49,0x29,0x1E}, // '9'
    {0x00,0x36,0x36,0x00,0x00}, // ':'
    {0x00,0x56,0x36,0x00,0x00}, // ';'
    {0x08,0x14,0x22,0x41,0x00}, // '<'
    {0x14,0x14,0x14,0x14,0x14}, // '='
    {0x00,0x41,0x22,0x14,0x08}, // '>'
    {0x02,0x01,0x51,0x09,0x06}, // '?'
    {0x32,0x49,0x79,0x41,0x3E}, // '@'
    {0x7E,0x11,0x11,0x11,0x7E}, // 'A'
    {0x7F,0x49,0x49,0x49,0x36}, // 'B'
    {0x3E,0x41,0x41,0x41,0x22}, // 'C'
    {0x7F,0x41,0x41,0x22,0x1C}, // 'D'
    {0x7F,0x49,0x49,0x49,0x41}, // 'E'
    {0x7F,0x09,0x09,0x09,0x01}, // 'F'
    {0x3E,0x41,0x49,0x49,0x7A}, // 'G'
    {0x7F,0x08,0x08,0x08,0x7F}, // 'H'
    {0x00,0x41,0x7F,0x41,0x00}, // 'I'
    {0x20,0x40,0x41,0x3F,0x01}, // 'J'
    {0x7F,0x08,0x14,0x22,0x41}, // 'K'
    {0x7F,0x40,0x40,0x40,0x40}, // 'L'
    {0x7F,0x02,0x0C,0x02,0x7F}, // 'M'
    {0x7F,0x04,0x08,0x10,0x7F}, // 'N'
    {0x3E,0x41,0x41,0x41,0x3E}, // 'O'
    {0x7F,0x09,0x09,0x09,0x06}, // 'P'
    {0x3E,0x41,0x51,0x21,0x5E}, // 'Q'
    {0x7F,0x09,0x19,0x29,0x46}, // 'R'
    {0x46,0x49,0x49,0x49,0x31}, // 'S'
    {0x01,0x01,0x7F,0x01,0x01}, // 'T'
    {0x3F,0x40,0x40,0x40,0x3F}, // 'U'
    {0x1F,0x20,0x40,0x20,0x1F}, // 'V'
    {0x3F,0x40,0x38,0x40,0x3F}, // 'W'
    {0x63,0x14,0x08,0x14,0x63}, // 'X'
    {0x07,0x08,0x70,0x08,0x07}, // 'Y'
    {0x61,0x51,0x49,0x45,0x43}, // 'Z'
    {0x00,0x7F,0x41,0x41,0x00}, // '['
    {0x02,0x04,0x08,0x10,0x20}, // '\\'
    {0x00,0x41,0x41,0x7F,0x00}, // ']'
    {0x18,0x30,0x60,0x18,0x06}, // '^' (5x7 checkmark)
    {0x40,0x40,0x40,0x40,0x40}, // '_'
};

static inline void wait_vblank(void) {
    while (REG_VCOUNT >= 160) {}
    while (REG_VCOUNT < 160) {}
}

static char to_upper(char c) {
    return (c >= 'a' && c <= 'z') ? (char)(c - 32) : c;
}

static uint32_t fnv1a_hash_ci(const char *s, uint32_t fsize, uint32_t frames) {
    uint32_t h = 2166136261u;
    while (*s) {
        h ^= (uint8_t)to_upper(*s++);
        h *= 16777619u;
    }
    h ^= fsize;
    h *= 16777619u;
    h ^= frames;
    h *= 16777619u;
    if (h == 0 || h == 0xFFFFFFFFu) h = 0x5A5A5A5Au;
    return h;
}

/* 8-Slot Per-File SRAM Bookmark Table at 0x0E000000:
 * Offset 0:  0x53445632 ("SDV2")
 * Offset 4:  last_played_hash
 * Offset 8:  last_played_frame
 * Offset 12: last_played_hash ^ last_played_frame ^ 0xA5A5A5A5
 * Offset 16..143: 8 slots x 16 bytes { hash, frame, seq, checksum }
 */
#define SRAM_PLAYER_OFF 0x6000u    /* Relocated to 24 KB offset so Meteo SRAM (0x0E000000..0x0E001073) coexists cleanly! */
#define SRAM_MAGIC_V2   0x53445632u
#define SRAM_CFG_MAGIC  0x53444332u
#define SRAM_DIR_MAGIC  0x53444431u
#define BOOKMARK_SLOTS  128
#define BOOKMARK_PLAYED 0xFFFFFFFEu

static uint32_t g_bookmark_seq = 0;
static uint8_t g_shuffle_visited[MAX_VIDEOS];

static __attribute__((section(".iwram"), noinline))
void sram_write_u32_raw(uint32_t raw_offset, uint32_t val) {
    volatile uint8_t *p = SRAM_BASE + raw_offset;
    p[0] = (uint8_t)(val & 0xFF);
    p[1] = (uint8_t)((val >> 8) & 0xFF);
    p[2] = (uint8_t)((val >> 16) & 0xFF);
    p[3] = (uint8_t)((val >> 24) & 0xFF);
}

static __attribute__((section(".iwram"), noinline))
uint32_t sram_read_u32_raw(uint32_t raw_offset) {
    volatile uint8_t *p = SRAM_BASE + raw_offset;
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

static void sram_write_u32(uint32_t offset, uint32_t val) {
    sram_write_u32_raw(SRAM_PLAYER_OFF + offset, val);
}

static uint32_t sram_read_u32(uint32_t offset) {
    return sram_read_u32_raw(SRAM_PLAYER_OFF + offset);
}

static void begin_sram_access(void) {
    if (!g_use_rom_vfat) {
        if (g_linear_psram_mode == 1 || g_linear_psram_mode == 3) {
            SetRompage(0x8002);
        }
        SetRampage(0);
    }
}

static void end_sram_access(void) {
    if (!g_use_rom_vfat && (g_linear_psram_mode == 1 || g_linear_psram_mode == 3)) {
        SetPSRampage(0);
        Set_RTC_status(0);
        SetRompage(0x200);
    }
}

static void save_sram_cur_dir(void) {
    begin_sram_access();
    sram_write_u32(256, SRAM_DIR_MAGIC);
    volatile uint8_t *p = SRAM_BASE + SRAM_PLAYER_OFF + 260;
    for (int i = 0; i < 188; i++) {
        uint8_t ch = (uint8_t)g_cur_dir[i];
        p[i] = ch;
        if (ch == 0) break;
    }
    p[187] = 0;
    end_sram_access();
}

static void load_sram_cur_dir(void) {
    begin_sram_access();
    if (sram_read_u32(256) == SRAM_DIR_MAGIC) {
        volatile uint8_t *p = SRAM_BASE + SRAM_PLAYER_OFF + 260;
        if (p[0] == '/') {
            for (int i = 0; i < 187; i++) {
                char ch = (char)p[i];
                g_cur_dir[i] = ch;
                if (ch == 0) break;
            }
            g_cur_dir[187] = 0;
        }
    }
    end_sram_access();
}

static uint32_t step_rng(uint32_t entropy) {
    uint32_t x = g_rng_state ^ entropy ^ ((uint32_t)REG_VCOUNT << 16) ^ REG_TM0CNT_L ^ ((uint32_t)REG_TM1CNT_L << 8);
    if (x == 0) x = 0x9E3779B9u;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    g_rng_state = x ? x : 0x9E3779B9u;
    return g_rng_state;
}

/* Save Player v3.8 settings (g_buf_mode, 3-way g_auto_chain, 3-way g_show_load_bar, g_rng_state) to SRAM */
static void save_sram_settings(void) {
    uint32_t flags = ((uint32_t)(g_buf_mode & 3)) |
                     ((g_auto_chain ? 1u : 0u) << 2) |
                     (((uint32_t)(g_show_load_bar & 3)) << 3) |
                     (((g_auto_chain == CHAIN_RANDOM) ? 1u : 0u) << 5) |
                     (((g_clean_names == 0) ? 1u : 0u) << 6) |
                     (((uint32_t)((g_lr_jump_idx ^ 1) & 7)) << 7);
    step_rng(flags ^ 0xA55A5AA5u);
    begin_sram_access();
    sram_write_u32(144, SRAM_CFG_MAGIC);
    sram_write_u32(148, flags);
    sram_write_u32(152, SRAM_CFG_MAGIC ^ flags ^ 0xC3C3C3C3u);
    sram_write_u32(172, g_rng_state);
    end_sram_access();
}

static void load_sram_settings(void) {
    begin_sram_access();
    /* One-time migration from v2.9 (0x0E000000) to v3.0 (0x0E006000) if needed */
    if (sram_read_u32(0) != SRAM_MAGIC_V2 && sram_read_u32_raw(0) == SRAM_MAGIC_V2) {
        for (uint32_t off = 0; off < 160; off += 4) {
            sram_write_u32(off, sram_read_u32_raw(off));
        }
    }
    uint32_t mg = sram_read_u32(144);
    uint32_t fl = sram_read_u32(148);
    uint32_t ck = sram_read_u32(152);
    uint32_t saved_rng = sram_read_u32(172);
    if (saved_rng != 0 && saved_rng != 0xFFFFFFFFu) {
        g_rng_state ^= saved_rng;
        step_rng(0x13579BDFu);
        sram_write_u32(172, g_rng_state);
    }
    end_sram_access();
    if (mg == SRAM_CFG_MAGIC && (mg ^ fl ^ 0xC3C3C3C3u) == ck) {
        int bm = (int)(fl & 3u);
        if (!g_has_psram && bm == BUF_MODE_PSRAM_32M) bm = BUF_MODE_DIRECT_SD;
        if (bm > BUF_MODE_EWRAM_96K) bm = BUF_MODE_PSRAM_32M;
        g_buf_mode = bm;
        if (fl & 32u) g_auto_chain = CHAIN_RANDOM;
        else g_auto_chain = (fl & 4u) ? CHAIN_NEXT : CHAIN_OFF;
        int lb = (int)((fl >> 3) & 3u);
        if (lb > LOAD_BAR_FILE) lb = LOAD_BAR_FILE;
        g_show_load_bar = lb;
        g_clean_names = (fl & 64u) ? 0 : 1;
        int lj = (int)(((fl >> 7) & 7u) ^ 1u);
        if (lj < 0 || lj > 6) lj = 1;
        g_lr_jump_idx = lj;
    } else if (mg == 0x53444331u && (mg ^ fl ^ 0xC3C3C3C3u) == ck) {
        int bm = (int)(fl & 3u);
        if (!g_has_psram && bm == BUF_MODE_PSRAM_32M) bm = BUF_MODE_DIRECT_SD;
        if (bm > BUF_MODE_EWRAM_96K) bm = BUF_MODE_PSRAM_32M;
        g_buf_mode = bm;
        g_auto_chain = (fl & 4u) ? CHAIN_NEXT : CHAIN_OFF;
        g_show_load_bar = (fl & 8u) ? LOAD_BAR_FILE : LOAD_BAR_HIDE;
    }
}

static uint32_t g_sram_bmk_hash[BOOKMARK_SLOTS];
static uint32_t g_sram_bmk_frame[BOOKMARK_SLOTS];
static uint32_t g_sram_bmk_seq[BOOKMARK_SLOTS];
static uint8_t  g_sram_bmk_cached = 0;

static inline uint32_t bookmark_slot_offset(int s) {
    return (s < 8) ? (16u + (uint32_t)s * 16u) : (512u + (uint32_t)(s - 8) * 16u);
}

static void refresh_sram_bookmark_cache(void) {
    for (int s = 0; s < BOOKMARK_SLOTS; s++) {
        g_sram_bmk_hash[s] = 0;
        g_sram_bmk_frame[s] = 0;
        g_sram_bmk_seq[s] = 0;
    }
    begin_sram_access();
    if (sram_read_u32(0) == SRAM_MAGIC_V2) {
        for (int s = 0; s < BOOKMARK_SLOTS; s++) {
            uint32_t base = bookmark_slot_offset(s);
            uint32_t sh = sram_read_u32(base + 0);
            uint32_t sf = sram_read_u32(base + 4);
            uint32_t sq = sram_read_u32(base + 8);
            uint32_t sc = sram_read_u32(base + 12);
            if (sh != 0 && (sh ^ sf ^ sq ^ 0x5A5A5A5Au) == sc) {
                g_sram_bmk_hash[s]  = sh;
                g_sram_bmk_frame[s] = sf;
                g_sram_bmk_seq[s]   = sq;
            }
        }
    }
    end_sram_access();
    g_sram_bmk_cached = 1;
}

static void save_sd_bookmark_by_hash(uint32_t h, uint32_t frame) {
    if (h == 0) return;
    if (!g_sram_bmk_cached) refresh_sram_bookmark_cache();

    int target_slot = -1;
    uint32_t oldest_seq = 0xFFFFFFFFu;
    int oldest_slot = 0;

    for (int s = 0; s < BOOKMARK_SLOTS; s++) {
        uint32_t sh = g_sram_bmk_hash[s];
        uint32_t sq = g_sram_bmk_seq[s];
        if (sh != 0) {
            if (sh == h) {
                target_slot = s;
                break;
            }
            if (sq < oldest_seq) {
                oldest_seq = sq;
                oldest_slot = s;
            }
        } else if (target_slot < 0) {
            target_slot = s;
        }
    }
    if (target_slot < 0) target_slot = oldest_slot;

    uint32_t seq = ++g_bookmark_seq;
    g_sram_bmk_hash[target_slot]  = h;
    g_sram_bmk_frame[target_slot] = frame;
    g_sram_bmk_seq[target_slot]   = seq;

    begin_sram_access();
    sram_write_u32(0, SRAM_MAGIC_V2);
    sram_write_u32(4, h);
    sram_write_u32(8, frame);
    sram_write_u32(12, h ^ frame ^ 0xA5A5A5A5u);

    uint32_t base = bookmark_slot_offset(target_slot);
    sram_write_u32(base + 0, h);
    sram_write_u32(base + 4, frame);
    sram_write_u32(base + 8, seq);
    sram_write_u32(base + 12, h ^ frame ^ seq ^ 0x5A5A5A5Au);
    end_sram_access();
}

static void save_sd_bookmark(int entry_idx, uint32_t frame) {
    if (entry_idx < 0 || entry_idx >= g_entry_count) return;
    g_ram_bookmarks[entry_idx] = frame;
    save_sd_bookmark_by_hash(g_entries[entry_idx].file_hash, frame);
}

/* Harvest Meteo 1.3.1 / 1.4.0 return bookmark, EOF, or UP/DOWN Prev/Next state from 0x0E000000..0x0E000010.
 * Sets *out_action: 0 = return to browser, 1 = natural EOF, 2 = DOWN (Next/Random), 3 = UP (Prev). */
static uint32_t sync_meteo_return_bookmark(int *out_action) {
    uint32_t nav_hash = 0;
    if (out_action) *out_action = 0;
    begin_sram_access();
    uint32_t m_owner = sram_read_u32(160);
    uint32_t m_total = sram_read_u32(164);
    uint32_t m_type  = sram_read_u32(168);
    uint32_t m_magic = sram_read_u32_raw(0);
    uint32_t m_frame = (m_type == 2) ? sram_read_u32_raw(4) : sram_read_u32_raw(12);
    uint8_t  m_btn   = SRAM_BASE[16];
    SRAM_BASE[16]    = 0;
    end_sram_access();

    if (m_owner != 0 && m_total > 0 && (m_magic == ~m_total || m_magic == (m_total ^ 0x53000000u))) {
        int b_held = ((~REG_KEYINPUT) & KEY_B) ? 1 : 0;
        if (m_btn == 0x80u) {
            /* DOWN pressed inside Meteo -> Next / Random video in directory! */
            if (m_frame > 0 && (m_frame + 5u) < m_total) save_sd_bookmark_by_hash(m_owner, m_frame);
            if (out_action) *out_action = 2;
            nav_hash = m_owner;
        } else if (m_btn == 0x40u) {
            /* UP pressed inside Meteo -> Previous video in directory! */
            if (m_frame > 0 && (m_frame + 5u) < m_total) save_sd_bookmark_by_hash(m_owner, m_frame);
            if (out_action) *out_action = 3;
            nav_hash = m_owner;
        } else if (m_frame == 0 && !b_held) {
            save_sd_bookmark_by_hash(m_owner, BOOKMARK_PLAYED);
            if (out_action) *out_action = 1;
            nav_hash = m_owner;
        } else if (m_frame == 0 || (m_frame + 5u) >= m_total) {
            save_sd_bookmark_by_hash(m_owner, BOOKMARK_PLAYED);
        } else {
            save_sd_bookmark_by_hash(m_owner, m_frame);
        }
        begin_sram_access();
        sram_write_u32(160, 0);
        end_sram_access();
    }
    return nav_hash;
}

static uint32_t load_sd_bookmark_for_entry(int entry_idx) {
    if (entry_idx < 0 || entry_idx >= g_entry_count) return 0;
    if (g_entries[entry_idx].is_dir) return 0;
    if (!g_sram_bmk_cached) refresh_sram_bookmark_cache();
    uint32_t total_f = g_entries[entry_idx].total_frames;
    uint32_t h = g_entries[entry_idx].file_hash;
    uint32_t h_legacy = (total_f > 0) ? fnv1a_hash_ci(g_entries[entry_idx].path, g_entries[entry_idx].file_size, total_f) : 0;
    for (int s = 0; s < BOOKMARK_SLOTS; s++) {
        uint32_t sh = g_sram_bmk_hash[s];
        if (sh != 0 && (sh == h || (h_legacy != 0 && sh == h_legacy))) {
            uint32_t sf = g_sram_bmk_frame[s];
            if (sf == BOOKMARK_PLAYED || total_f == 0 || sf < total_f) {
                g_ram_bookmarks[entry_idx] = sf;
                return sf;
            }
            return 0;
        }
    }
    if (g_ram_bookmarks[entry_idx] == BOOKMARK_PLAYED || (g_ram_bookmarks[entry_idx] > 0 && (total_f == 0 || g_ram_bookmarks[entry_idx] < total_f))) {
        return g_ram_bookmarks[entry_idx];
    }
    return 0;
}

#define SRAM_RECENT_MAGIC 0x52434E31u
#define SRAM_RECENT_OFF   2048u
#define RECENT_MAX        10

typedef struct {
    uint32_t file_hash;
    uint32_t total_frames;
    uint16_t fps;
    char     path[156];
} RecentVideoItem;

#define g_recent_items ((RecentVideoItem *)(&g_video_chunk_buf[28672]))

static uint32_t load_sd_bookmark_by_hash(uint32_t h, uint32_t total_f) {
    if (h == 0) return 0;
    if (!g_sram_bmk_cached) refresh_sram_bookmark_cache();
    for (int s = 0; s < BOOKMARK_SLOTS; s++) {
        if (g_sram_bmk_hash[s] == h) {
            uint32_t sf = g_sram_bmk_frame[s];
            if (sf == BOOKMARK_PLAYED || total_f == 0 || sf < total_f) return sf;
            return 0;
        }
    }
    return 0;
}

static int load_recent_videos_from_sram(void) {
    begin_sram_access();
    if (sram_read_u32(SRAM_RECENT_OFF) != SRAM_RECENT_MAGIC) {
        end_sram_access();
        return 0;
    }
    uint32_t cnt = sram_read_u32(SRAM_RECENT_OFF + 4u);
    if (cnt > RECENT_MAX) cnt = 0;
    int valid_cnt = 0;
    for (uint32_t i = 0; i < cnt; i++) {
        uint32_t base = SRAM_RECENT_OFF + 8u + i * 164u;
        uint32_t h = sram_read_u32(base + 0u);
        uint32_t tf_fps = sram_read_u32(base + 4u);
        volatile uint8_t *sp = SRAM_BASE + SRAM_PLAYER_OFF + base + 8u;
        if (h == 0 || sp[0] != '/') continue;
        g_recent_items[valid_cnt].file_hash = h;
        g_recent_items[valid_cnt].total_frames = tf_fps & 0x00FFFFFFu;
        uint16_t fps = (uint16_t)(tf_fps >> 24);
        g_recent_items[valid_cnt].fps = fps ? fps : 20;
        for (int c = 0; c < 155; c++) {
            char ch = (char)sp[c];
            g_recent_items[valid_cnt].path[c] = ch;
            if (ch == 0) break;
        }
        g_recent_items[valid_cnt].path[155] = 0;
        valid_cnt++;
    }
    end_sram_access();
    return valid_cnt;
}

static int str_cmp_ci(const char *a, const char *b);

static void record_recent_video(const SdVideoEntry *e) {
    if (!e || e->is_dir || e->is_rom_demo || e->path[0] != '/') return;
    int cnt = load_recent_videos_from_sram();
    int match_idx = -1;
    for (int i = 0; i < cnt; i++) {
        if (str_cmp_ci(g_recent_items[i].path, e->path) == 0) {
            match_idx = i;
            break;
        }
    }
    if (match_idx >= 0) {
        for (int j = match_idx; j > 0; j--) {
            g_recent_items[j] = g_recent_items[j - 1];
        }
    } else {
        int limit = (cnt < RECENT_MAX) ? cnt : (RECENT_MAX - 1);
        for (int j = limit; j > 0; j--) {
            g_recent_items[j] = g_recent_items[j - 1];
        }
        if (cnt < RECENT_MAX) cnt++;
    }
    g_recent_items[0].file_hash = e->file_hash;
    g_recent_items[0].total_frames = e->total_frames;
    g_recent_items[0].fps = e->fps ? e->fps : 20;
    for (int c = 0; c < (int)sizeof(e->path) - 1; c++) {
        g_recent_items[0].path[c] = e->path[c];
        if (e->path[c] == 0) break;
    }
    g_recent_items[0].path[sizeof(e->path) - 1] = 0;

    begin_sram_access();
    sram_write_u32(SRAM_RECENT_OFF, SRAM_RECENT_MAGIC);
    sram_write_u32(SRAM_RECENT_OFF + 4u, (uint32_t)cnt);
    for (int i = 0; i < cnt; i++) {
        uint32_t base = SRAM_RECENT_OFF + 8u + (uint32_t)i * 164u;
        uint32_t tf_fps = (g_recent_items[i].total_frames & 0x00FFFFFFu) | ((uint32_t)(g_recent_items[i].fps & 0xFFu) << 24);
        sram_write_u32(base + 0u, g_recent_items[i].file_hash);
        sram_write_u32(base + 4u, tf_fps);
        volatile uint8_t *sp = SRAM_BASE + SRAM_PLAYER_OFF + base + 8u;
        for (int c = 0; c < 155; c++) {
            uint8_t ch = (uint8_t)g_recent_items[i].path[c];
            sp[c] = ch;
            if (ch == 0) break;
        }
        sp[155] = 0;
    }
    end_sram_access();
}

/* Probe if 0x08800000 (PSRAMBase_S98) is writable while Rompage == 0x8002 */
static __attribute__((section(".iwram"), noinline))
int probe_psram_hardware(void) {
    if (g_use_rom_vfat) return 0;
    SetRompage(0x8002);
    SetPSRampage(0);
    volatile uint16_t *p = (volatile uint16_t *)0x08800000u;
    uint16_t old0 = p[0];
    uint16_t old1 = p[1];
    p[0] = 0x5AA5u;
    p[1] = 0xA55Au;
    int ok = (p[0] == 0x5AA5u && p[1] == 0xA55Au);
    p[0] = old0;
    p[1] = old1;
    return ok;
}

static __attribute__((section(".iwram"), noinline))
void psram_write_window(uint16_t page, uint32_t win_off, const void *src, uint32_t len) {
    if (!g_use_rom_vfat) SetRompage(0x8002);
    SetPSRampage(page);
    const uint16_t *s16 = (const uint16_t *)src;
    volatile uint16_t *d16 = (volatile uint16_t *)(0x08800000u + win_off);
    uint32_t hwords = (len + 1u) >> 1;
    if ((((uintptr_t)s16 | (uintptr_t)d16) & 1u) == 0 && hwords >= 32) {
        REG_DMA3SAD = (uint32_t)s16;
        REG_DMA3DAD = (uint32_t)d16;
        REG_DMA3CNT = hwords | 0x80000000u;
        __asm__ volatile("nop; nop; nop; nop");
    } else if (((uintptr_t)s16 & 1u) == 0) {
        for (uint32_t i = 0; i < hwords; i++) d16[i] = s16[i];
    } else {
        /* ARM7TDMI unaligned ldrh from an odd address rotates right by 8 bits! Always assemble from bytes if odd-aligned. */
        const uint8_t *s8 = (const uint8_t *)src;
        for (uint32_t i = 0; i < hwords; i++) {
            d16[i] = (uint16_t)s8[i * 2u] | ((uint16_t)s8[i * 2u + 1u] << 8);
        }
    }
    SetPSRampage(0);
}

static __attribute__((section(".iwram"), noinline))
void psram_read_window(uint16_t page, uint32_t win_off, void *dst, uint32_t len) {
    if (!g_use_rom_vfat) SetRompage(0x8002);
    SetPSRampage(page);
    memcpy(dst, (const void *)(0x08800000u + win_off), len);
    SetPSRampage(0);
}

static void fill_rect(int x, int y, int w, int h, uint16_t color) {
    if (x < 0) { w += x; x = 0; }
    if (y < 0) { h += y; y = 0; }
    if (x + w > 240) w = 240 - x;
    if (y + h > 160) h = 160 - y;
    if (w <= 0 || h <= 0) return;
    for (int ry = y; ry < y + h; ry++) {
        uint16_t *row = &VRAM_FB[ry * 240 + x];
        for (int rx = 0; rx < w; rx++) row[rx] = color;
    }
}

static void draw_char(int x, int y, char c, uint16_t fg) {
    if (c >= 'a' && c <= 'z') c -= 32;
    if (c < 32 || c > 95) c = '?';
    const uint8_t *glyph = font5x7[c - 32];
    for (int col = 0; col < 5; col++) {
        uint8_t bits = glyph[col];
        int px = x + col;
        if (px < 0 || px >= 240) continue;
        for (int row = 0; row < 7; row++) {
            if (bits & (1 << row)) {
                int py = y + row;
                if (py >= 0 && py < 160) VRAM_FB[py * 240 + px] = fg;
            }
        }
    }
}

static void draw_str(int x, int y, const char *s, uint16_t fg, int max_chars) {
    int count = 0;
    while (*s && (max_chars <= 0 || count < max_chars)) {
        draw_char(x, y, *s++, fg);
        x += 6;
        count++;
    }
}

static void format_u32(char *out, uint32_t val) {
    char tmp[12];
    int n = 0;
    if (val == 0) {
        out[0] = '0'; out[1] = 0;
        return;
    }
    while (val > 0 && n < 10) {
        tmp[n++] = (char)('0' + (val % 10));
        val /= 10;
    }
    for (int i = 0; i < n; i++) out[i] = tmp[n - 1 - i];
    out[n] = 0;
}

static void format_mmss(char *out, uint32_t sec) {
    uint32_t m = sec / 60;
    uint32_t s = sec % 60;
    if (m >= 100) {
        out[0] = (char)('0' + ((m / 100) % 10));
        out[1] = (char)('0' + ((m / 10) % 10));
        out[2] = (char)('0' + (m % 10));
        out[3] = ':';
        out[4] = (char)('0' + (s / 10));
        out[5] = (char)('0' + (s % 10));
        out[6] = 0;
    } else {
        out[0] = (char)('0' + (m / 10));
        out[1] = (char)('0' + (m % 10));
        out[2] = ':';
        out[3] = (char)('0' + (s / 10));
        out[4] = (char)('0' + (s % 10));
        out[5] = 0;
    }
}

static void format_size_mb(char *out, uint32_t bytes) {
    uint32_t tenths = (uint32_t)(((uint64_t)bytes * 10 + 524288) >> 20);
    uint32_t whole = tenths / 10;
    uint32_t frac = tenths % 10;
    char wbuf[12];
    format_u32(wbuf, whole);
    int i = 0;
    while (wbuf[i]) { out[i] = wbuf[i]; i++; }
    out[i++] = '.';
    out[i++] = (char)('0' + frac);
    out[i++] = 'M';
    out[i++] = 'B';
    out[i] = 0;
}

/* Fast IWRAM decoder writing 32-bit pixel pairs directly to 0-waitstate VRAM (0x06000000) */
__attribute__((section(".iwram"), noinline))
void decode_agv_frame(const uint8_t *frame_ptr, int is_keyframe) {
    const uint8_t *modes = frame_ptr;
    const uint16_t *payload = (const uint16_t *)(frame_ptr + 600);
    uint16_t last_color = 0;

    int mode_idx = 0;
    for (int cy = 0; cy < 160; cy += 4) {
        uint16_t *row_base = &VRAM_FB[cy * 240];
        for (int cx = 0; cx < 240; cx += 4, mode_idx++) {
            uint8_t m = (modes[mode_idx >> 2] >> ((mode_idx & 3) << 1)) & 3;
            uint32_t *dst32 = (uint32_t *)(row_base + cx);
            if (m == 0) {
                if (is_keyframe) {
                    uint32_t pair = (uint32_t)last_color | ((uint32_t)last_color << 16);
                    dst32[0]   = pair; dst32[1]   = pair;
                    dst32[120] = pair; dst32[121] = pair;
                    dst32[240] = pair; dst32[241] = pair;
                    dst32[360] = pair; dst32[361] = pair;
                }
                continue;
            } else if (m == 1) {
                uint16_t c = *payload++;
                last_color = c;
                uint32_t pair = (uint32_t)c | ((uint32_t)c << 16);
                dst32[0]   = pair; dst32[1]   = pair;
                dst32[120] = pair; dst32[121] = pair;
                dst32[240] = pair; dst32[241] = pair;
                dst32[360] = pair; dst32[361] = pair;
            } else if (m == 2) {
                uint32_t c0 = payload[0];
                uint32_t c1 = payload[1];
                uint32_t mask = payload[2];
                payload += 3;
                last_color = (uint16_t)c0;
                uint32_t lut[4] = {
                    c0 | (c0 << 16),
                    c1 | (c0 << 16),
                    c0 | (c1 << 16),
                    c1 | (c1 << 16)
                };
                dst32[0]   = lut[mask & 3];         dst32[1]   = lut[(mask >> 2) & 3];
                dst32[120] = lut[(mask >> 4) & 3];  dst32[121] = lut[(mask >> 6) & 3];
                dst32[240] = lut[(mask >> 8) & 3];  dst32[241] = lut[(mask >> 10) & 3];
                dst32[360] = lut[(mask >> 12) & 3]; dst32[361] = lut[(mask >> 14) & 3];
            } else {
                uint32_t c4[4];
                c4[0] = payload[0];
                c4[1] = payload[1];
                c4[2] = payload[2];
                c4[3] = payload[3];
                uint32_t m0 = payload[4];
                uint32_t m1 = payload[5];
                payload += 6;
                last_color = (uint16_t)c4[3];
                dst32[0]   = c4[m0 & 3]         | (c4[(m0 >> 2) & 3] << 16);
                dst32[1]   = c4[(m0 >> 4) & 3]  | (c4[(m0 >> 6) & 3] << 16);
                dst32[120] = c4[(m0 >> 8) & 3]  | (c4[(m0 >> 10) & 3] << 16);
                dst32[121] = c4[(m0 >> 12) & 3] | (c4[(m0 >> 14) & 3] << 16);
                dst32[240] = c4[m1 & 3]         | (c4[(m1 >> 2) & 3] << 16);
                dst32[241] = c4[(m1 >> 4) & 3]  | (c4[(m1 >> 6) & 3] << 16);
                dst32[360] = c4[m1 >> 8 & 3]    | (c4[(m1 >> 10) & 3] << 16);
                dst32[361] = c4[(m1 >> 12) & 3] | (c4[(m1 >> 14) & 3] << 16);
            }
        }
    }
}

/* Render a 60x40 thumbnail (1 pixel per 4x4 cell) of an I-frame at (tx, ty) */
static void decode_agv_thumbnail_60x40(const uint8_t *frame_ptr, int tx, int ty) {
    const uint8_t *modes = frame_ptr;
    const uint16_t *payload = (const uint16_t *)(frame_ptr + 600);
    uint16_t last_color = 0;
    int mode_idx = 0;
    for (int cy = 0; cy < 40; cy++) {
        uint16_t *row = &VRAM_FB[(ty + cy) * 240 + tx];
        for (int cx = 0; cx < 60; cx++, mode_idx++) {
            uint8_t m = (modes[mode_idx >> 2] >> ((mode_idx & 3) << 1)) & 3;
            uint16_t col = last_color;
            if (m == 1) {
                col = *payload++;
                last_color = col;
            } else if (m == 2) {
                col = payload[0];
                payload += 3;
                last_color = col;
            } else if (m == 3) {
                col = payload[0];
                last_color = payload[3];
                payload += 6;
            }
            row[cx] = col;
        }
    }
}

static int str_ends_with_ci(const char *s, const char *ext) {
    int sl = (int)strlen(s);
    int el = (int)strlen(ext);
    if (sl < el) return 0;
    for (int i = 0; i < el; i++) {
        if (to_upper(s[sl - el + i]) != to_upper(ext[i])) return 0;
    }
    return 1;
}

static int str_cmp_ci(const char *a, const char *b) {
    while (*a && *b) {
        char ca = to_upper(*a);
        char cb = to_upper(*b);
        if (ca != cb) return (int)ca - (int)cb;
        a++; b++;
    }
    return (int)to_upper(*a) - (int)to_upper(*b);
}

static void fit_display_46(char *out, const char *src) {
    int len = (int)strlen(src);
    if (len <= 34) {
        memcpy(out, src, (size_t)len + 1);
    } else {
        memcpy(out, src, 20);
        out[20] = '.';
        out[21] = '.';
        memcpy(out + 22, src + len - 12, 13);
        out[35] = 0;
    }
}

static int is_hex_crc32_token(const char *s, int len) {
    if (len != 8) return 0;
    int has_digit = 0;
    for (int i = 0; i < 8; i++) {
        char c = to_upper(s[i]);
        if (c >= '0' && c <= '9') has_digit = 1;
        else if (!(c >= 'A' && c <= 'F')) return 0;
    }
    return has_digit;
}

static int is_pure_ep_bracket(const char *s, int len) {
    if (len <= 0 || len > 6) return 0;
    int i = 0;
    if (to_upper(s[0]) == 'E' && len >= 2) {
        i = (to_upper(s[1]) == 'P') ? 2 : 1;
    }
    if (i >= len) return 0;
    int digits = 0;
    while (i < len && s[i] >= '0' && s[i] <= '9') { digits++; i++; }
    if (digits == 0 || digits > 3) return 0;
    if (i < len && to_upper(s[i]) == 'V') {
        i++;
        while (i < len && s[i] >= '0' && s[i] <= '9') i++;
    }
    return (i == len);
}

static int token_eq_ci(const char *s, int len, const char *pat) {
    int plen = (int)strlen(pat);
    if (len != plen) return 0;
    for (int i = 0; i < len; i++) {
        if (to_upper(s[i]) != to_upper(pat[i])) return 0;
    }
    return 1;
}

static int token_starts_ci(const char *s, int len, const char *pat) {
    int plen = (int)strlen(pat);
    if (len < plen) return 0;
    for (int i = 0; i < plen; i++) {
        if (to_upper(s[i]) != to_upper(pat[i])) return 0;
    }
    return 1;
}

static int is_noise_word(const char *w, int len) {
    if (len <= 0) return 0;
    if (is_hex_crc32_token(w, len)) return 1;
    /* Resolution tags like 720p, 1080p, 480p, 2160p, 1080i, 4K, 1280x720 */
    if (len >= 3 && len <= 5 && (to_upper(w[len - 1]) == 'P' || to_upper(w[len - 1]) == 'I')) {
        int all_num = 1;
        for (int i = 0; i < len - 1; i++) {
            if (w[i] < '0' || w[i] > '9') { all_num = 0; break; }
        }
        if (all_num) return 1;
    }
    if (len >= 7 && len <= 9) {
        int x_pos = -1;
        for (int i = 2; i < len - 2; i++) {
            if (to_upper(w[i]) == 'X') { x_pos = i; break; }
        }
        if (x_pos > 0) {
            int all_num = 1;
            for (int i = 0; i < len; i++) {
                if (i != x_pos && (w[i] < '0' || w[i] > '9')) { all_num = 0; break; }
            }
            if (all_num) return 1;
        }
    }
    static const char * const k_noise[] = {
        "4K", "UHD", "FHD", "HD", "SD",
        "X264", "X265", "H264", "H.264", "H265", "H.265", "HEVC", "AV1", "XVID", "DIVX", "MPEG4",
        "10BIT", "10-BIT", "8BIT", "8-BIT", "HI10P", "HI10", "YUV420P", "YUV420P10LE", "HDR", "HDR10", "DV",
        "AAC", "AAC2.0", "AAC2", "EAC3", "E-AC-3", "AC3", "DDP5.1", "DDP2.0", "DD5.1",
        "FLAC", "MP3", "OPUS", "VORBIS", "DTS", "TRUEHD", "ATMOS", "5.1", "2.0",
        "DUAL-AUDIO", "DUALAUDIO", "MULTI-AUDIO", "MULTI-SUBS", "MULTISUBS", "MULTI-SUB", "MULTISUB",
        "BLURAY", "BLU-RAY", "BDRIP", "BDREMUX", "BRRIP", "BD", "BDR",
        "WEBRIP", "WEB-DL", "WEBDL", "WEB", "HDTV", "PDTV", "DVDRIP", "DVD", "REMUX",
        "PROPER", "REPACK", "RERIP", "INTERNAL", "SUB", "SUBS", "HARDSUB", "SOFTSUB", "RAW",
        "MKV", "MP4", "AVI", "WEBM", "MPG", "MPEG", "MOV", "M4V", "WMV", "FLV", "TS", "VOB", "3GP"
    };
    for (unsigned k = 0; k < sizeof(k_noise) / sizeof(k_noise[0]); k++) {
        if (token_eq_ci(w, len, k_noise[k])) return 1;
    }
    /* Match codec-group hyphenations like x264-GROUP, x265-GROUP, H264-GROUP, HEVC-GROUP, WEB-DL-GROUP */
    static const char * const k_CodecPfx[] = {
        "X264-", "X265-", "H264-", "H.264-", "H265-", "H.265-", "HEVC-", "AV1-", "XVID-", "WEBRIP-", "WEBDL-"
    };
    for (unsigned k = 0; k < sizeof(k_CodecPfx) / sizeof(k_CodecPfx[0]); k++) {
        if (token_starts_ci(w, len, k_CodecPfx[k])) return 1;
    }
    return 0;
}

static int paren_has_noise(const char *s, int len) {
    int i = 0;
    while (i < len) {
        while (i < len && (s[i] == ' ' || s[i] == '_' || s[i] == ',' || s[i] == '.')) i++;
        int start = i;
        while (i < len && s[i] != ' ' && s[i] != '_' && s[i] != ',' && s[i] != '.') i++;
        if (i > start && is_noise_word(s + start, i - start)) return 1;
    }
    return 0;
}

static void make_display_names(char *out_clean, char *out_raw, const char *fname) {
    fit_display_46(out_raw, fname);

    /* Copy up to 240 chars and strip trailing .agv / .gba + any preceding .mkv / .mp4 / .avi */
    char buf[248];
    int flen = (int)strlen(fname);
    if (flen > 240) flen = 240;
    memcpy(buf, fname, (size_t)flen);
    buf[flen] = 0;

    static const char * const k_exts[] = { ".AGV", ".GBA", ".MKV", ".MP4", ".AVI", ".WEBM", ".MOV", ".MPG", ".MPEG", ".M4V", ".WMV", ".FLV", ".TS", ".VOB", ".3GP", ".OGM" };
    for (int pass = 0; pass < 2; pass++) {
        for (unsigned k = 0; k < sizeof(k_exts) / sizeof(k_exts[0]); k++) {
            int el = (int)strlen(k_exts[k]);
            if (flen > el && str_ends_with_ci(buf, k_exts[k])) {
                flen -= el;
                buf[flen] = 0;
                break;
            }
        }
    }

    /* Pass 1: Strip [...] release/codec/CRC32 brackets (preserving pure episode brackets like [01])
     * and strip (...) parenthesized blocks if they contain resolution/codec/CRC32 tags.
     */
    char step1[248];
    int p1 = 0;
    for (int i = 0; i < flen && p1 < 240; ) {
        if (buf[i] == '[') {
            const char *close = strchr(buf + i, ']');
            if (close) {
                int blen = (int)(close - (buf + i + 1));
                if (is_pure_ep_bracket(buf + i + 1, blen)) {
                    if (p1 > 0 && step1[p1 - 1] != ' ') step1[p1++] = ' ';
                    for (int j = 0; j < blen && p1 < 240; j++) step1[p1++] = buf[i + 1 + j];
                    if (p1 < 240) step1[p1++] = ' ';
                }
                i = (int)(close - buf) + 1;
                continue;
            }
        } else if (buf[i] == '(') {
            const char *close = strchr(buf + i, ')');
            if (close) {
                int plen = (int)(close - (buf + i + 1));
                if (paren_has_noise(buf + i + 1, plen)) {
                    i = (int)(close - buf) + 1;
                    continue;
                }
            }
        }
        char ch = buf[i++];
        if (ch == '_') ch = ' ';
        step1[p1++] = ch;
    }
    step1[p1] = 0;

    /* If dots are used as word separators (e.g. Show.Name.S01E01.720p), convert dots to spaces */
    int space_cnt = 0, dot_cnt = 0;
    for (int i = 0; i < p1; i++) {
        if (step1[i] == ' ') space_cnt++;
        else if (step1[i] == '.') dot_cnt++;
    }
    if (dot_cnt >= 2 && space_cnt <= 1) {
        for (int i = 0; i < p1; i++) {
            if (step1[i] == '.') step1[i] = ' ';
        }
    }

    /* Pass 2: Tokenize by space and filter out unbracketed noise words (720p, x264, AAC, BluRay, CRC32, etc.) */
    char step2[248];
    int p2 = 0;
    int idx = 0;
    int stripped_tech = 0;
    while (idx < p1) {
        while (idx < p1 && step1[idx] == ' ') idx++;
        if (idx >= p1) break;
        int start = idx;
        while (idx < p1 && step1[idx] != ' ') idx++;
        int wlen = idx - start;
        const char *w = step1 + start;

        if (is_noise_word(w, wlen)) {
            stripped_tech = 1;
            continue;
        }
        /* If immediately following stripped tech tags we have "-GROUP" or "- THORA", drop the trailing group tag */
        if (stripped_tech && w[0] == '-' && idx >= p1) {
            continue;
        }
        if (p2 > 0 && step2[p2 - 1] != ' ') step2[p2++] = ' ';
        for (int j = 0; j < wlen && p2 < 240; j++) step2[p2++] = w[j];
    }
    step2[p2] = 0;

    /* Trim trailing spaces, hyphens, or underscores left at the end */
    while (p2 > 0 && (step2[p2 - 1] == ' ' || step2[p2 - 1] == '-' || step2[p2 - 1] == '_')) {
        step2[--p2] = 0;
    }
    /* Also collapse "- -" if any tag sat between dashes */
    char step3[248];
    int p3 = 0;
    for (int i = 0; i < p2 && p3 < 240; i++) {
        if (step2[i] == '-' && i + 2 < p2 && step2[i + 1] == ' ' && step2[i + 2] == '-') {
            i += 1;
            continue;
        }
        step3[p3++] = step2[i];
    }
    while (p3 > 0 && (step3[p3 - 1] == ' ' || step3[p3 - 1] == '-')) p3--;
    step3[p3] = 0;

    if (p3 == 0) {
        fit_display_46(out_clean, fname);
    } else {
        fit_display_46(out_clean, step3);
    }
}

static void get_entry_raw_name(const SdVideoEntry *e, char *out_raw) {
    if (e->is_dir) {
        int i = 0;
        while (e->name[i] && i < 35) { out_raw[i] = e->name[i]; i++; }
        out_raw[i] = 0;
        return;
    }
    const char *fname = e->path;
    for (const char *p = e->path; *p; p++) {
        if (*p == '/') fname = p + 1;
    }
    char dummy_clean[36];
    make_display_names(dummy_clean, out_raw, fname);
}

static const char *get_entry_display_name(const SdVideoEntry *e) {
    static char s_raw_buf[4][36];
    static uint8_t s_raw_slot = 0;
    if (e->is_dir || g_clean_names) return e->name;
    char *buf = s_raw_buf[s_raw_slot++ & 3u];
    get_entry_raw_name(e, buf);
    return buf[0] ? buf : e->name;
}

/* Meteo 1.3.1 & 1.4.0/1.5.0 live in-PSRAM patch payloads (v3.3: 240-frame warmup + exact B/EOF return) */
static const uint8_t __attribute__((aligned(4))) g_meteo_patch131_0148[20] = {
    0x38,0x0e,0x00,0x00,0x38,0x0e,0x00,0x03,0xb4,0x0f,0x00,0x03,0x00,0x7f,0x00,0x03,0x18,0x0e,0x00,0x03
};
static const uint8_t __attribute__((aligned(4))) g_meteo_patch131_A8C8[544] = {
    0x23,0x00,0x00,0xeb,0x00,0x00,0x56,0xe3,0x1b,0x00,0x00,0x9a,0x04,0x00,0xa0,0xe1,
    0xcb,0xfd,0xff,0xeb,0x8c,0xe0,0x1f,0xe5,0x00,0x40,0xa0,0xe1,0x04,0x00,0x9e,0xe5,
    0x01,0x08,0x50,0xe3,0x00,0x00,0x02,0x3f,0xfb,0xff,0xff,0x3a,0x01,0x08,0x40,0xe2,
    0x04,0x00,0x8e,0xe5,0x01,0x03,0xa0,0xe3,0xd4,0x30,0x80,0xe2,0x02,0x14,0xa0,0xe3,
    0x06,0x24,0xa0,0xe3,0x21,0xe3,0xa0,0xe3,0x4b,0xec,0x8e,0xe2,0x06,0x40,0x83,0xe8,
    0x01,0x70,0x87,0xe2,0x01,0x3c,0x80,0xe2,0xb0,0x03,0xd3,0xe1,0x00,0x10,0x28,0xe0,
    0x00,0x10,0x01,0xe0,0x00,0x80,0xa0,0xe1,0x01,0x2b,0xb0,0xe1,0x2c,0x20,0x9f,0x15,
    0x12,0xff,0x2f,0x11,0x06,0x00,0x57,0xe1,0xe3,0xff,0xff,0x3a,0x02,0x10,0xb0,0xe3,
    0xf9,0xff,0xff,0xea,0x02,0x3c,0x80,0xe2,0x01,0x00,0xa0,0xe3,0xb2,0x00,0xc3,0xe1,
    0xb5,0xff,0xff,0xea,0x00,0x00,0x9f,0xe5,0x10,0xff,0x2f,0xe1,0x6d,0xa9,0x00,0x08,
    0x9d,0xa9,0x00,0x08,0x00,0x27,0x40,0x46,0x80,0x08,0x00,0xd2,0x70,0x47,0xf2,0x43,
    0xb4,0xb4,0x84,0xb0,0x00,0x21,0x00,0xf0,0x88,0xf8,0x09,0xd1,0x03,0x9b,0x04,0xb0,
    0x52,0x4a,0x00,0x20,0x50,0x80,0xff,0x32,0x01,0x32,0x10,0x80,0x50,0x4d,0x4c,0xe0,
    0x08,0xb0,0x78,0xe0,0x03,0x22,0x12,0x02,0xfb,0x32,0x11,0x42,0x73,0xd0,0xf2,0x43,
    0xb4,0xb4,0x00,0x22,0x5a,0x80,0xff,0x33,0x01,0x33,0x1a,0x80,0xcb,0x22,0x11,0x42,
    0x17,0xd0,0xb7,0x42,0x01,0xd3,0x00,0x22,0x03,0x92,0x00,0xf0,0x66,0xf8,0x7c,0xe0,
    0x42,0x4b,0x18,0x8e,0x41,0x46,0x41,0x40,0x01,0x40,0x80,0x46,0xc2,0x22,0x11,0x42,
    0xf3,0xd1,0x09,0x22,0x11,0x42,0x04,0xd0,0xb7,0x42,0x4d,0xd3,0x3c,0x4d,0x00,0x23,
    0x15,0xe0,0xe1,0x20,0x30,0x22,0x11,0x42,0x04,0xd1,0x12,0x01,0x11,0x42,0xe8,0xd0,
    0x02,0x22,0x50,0x43,0x36,0x4d,0x6a,0x6a,0x50,0x43,0x83,0x0b,0x00,0xd1,0x01,0x23,
    0x11,0x20,0x00,0x01,0x01,0x42,0x0b,0xd1,0xfb,0x1a,0x00,0xd2,0x00,0x23,0x00,0x27,
    0x4c,0x46,0x50,0x46,0x59,0x46,0x03,0xc5,0x08,0x3d,0x00,0x20,0xa8,0x62,0x04,0xe0,
    0xfb,0x18,0x70,0x1e,0x83,0x42,0x00,0xd3,0x03,0x00,0x98,0x46,0x47,0x45,0x1e,0xd2,
    0x28,0x68,0x69,0x68,0xab,0x6a,0x1a,0x0c,0x06,0xd1,0x01,0x29,0x01,0xd9,0xb0,0x30,
    0x01,0x39,0x6a,0x6a,0x9b,0x18,0xf6,0xe7,0x12,0x04,0x9b,0x1a,0x03,0xc5,0x08,0x3d,
    0xab,0x62,0x43,0x46,0xd8,0x1b,0x40,0x28,0x02,0xd9,0x20,0x88,0x24,0x18,0x04,0xe0,
    0x20,0x00,0x1c,0x4a,0x00,0xf0,0x10,0xf8,0x04,0x00,0x01,0x37,0xde,0xe7,0x00,0x20,
    0xa8,0x60,0x16,0x4b,0x18,0x8e,0x80,0x46,0x02,0x9d,0x04,0xb0,0x80,0x21,0x59,0x80,
    0x01,0x21,0x0a,0x02,0x99,0x52,0x14,0x4a,0x10,0x47,0x02,0xb5,0x0e,0x20,0x00,0x06,
    0x02,0xaa,0x0f,0x23,0x00,0xf0,0x04,0xf8,0xf1,0x43,0x13,0x68,0x8b,0x42,0x04,0xbd,
    0x00,0x29,0x04,0xd1,0xc1,0x5c,0xd1,0x54,0x01,0x3b,0xfb,0xd5,0x70,0x47,0x01,0x74,
    0xd1,0x5c,0xc1,0x54,0x01,0x3b,0xfb,0xd5,0x70,0x47,0xc2,0x23,0x1a,0x42,0x04,0xd0,
    0x06,0x48,0xc1,0x78,0xea,0x29,0x00,0xd1,0x00,0x47,0x79,0xe7,0x00,0x01,0x00,0x04,
    0x54,0x0f,0x00,0x03,0xd8,0x04,0x00,0x03,0x08,0x0e,0x00,0x03,0x00,0x00,0xff,0x09
};
static const uint8_t __attribute__((aligned(4))) g_meteo_patch140_A8E4[4] = { 0xb0,0x93,0xd0,0xe1 };
static const uint8_t __attribute__((aligned(4))) g_meteo_patch140_A90C[4] = { 0x8a,0x00,0x00,0xeb };
static const uint8_t __attribute__((aligned(4))) g_meteo_patch140_A960[36] = {
    0x01,0x80,0x88,0xe2,0x40,0x09,0x80,0xe1,0xb0,0x03,0xd0,0xe1,0x00,0x10,0x29,0xe0,
    0x00,0x10,0x01,0xe0,0x00,0x90,0xa0,0xe1,0x01,0x2b,0xb0,0xe1,0x70,0x00,0x00,0x1a,
    0x30,0x00,0x00,0xea
};
static const uint8_t __attribute__((aligned(4))) g_meteo_patch140_AA50[8] = { 0x02,0x10,0xa0,0xe3,0x3a,0x00,0x00,0xea };
static const uint8_t __attribute__((aligned(4))) g_meteo_patch140_AB3C[436] = {
    0x08,0x00,0x9f,0xe5,0x10,0xff,0x2f,0xe1,0x04,0x20,0x9f,0xe5,0x12,0xff,0x2f,0xe1,
    0x19,0x10,0x00,0x03,0x4f,0x10,0x00,0x03,0x00,0x20,0x80,0x46,0x48,0x46,0x02,0x21,
    0x08,0x42,0x00,0xd1,0x70,0x47,0xfa,0x43,0x43,0x46,0x3c,0xb4,0x84,0xb0,0x00,0x21,
    0x00,0xf0,0x92,0xf8,0x09,0xd1,0x01,0x9b,0x04,0xb0,0x54,0x4a,0x00,0x20,0x50,0x80,
    0xff,0x32,0x01,0x32,0x10,0x80,0x52,0x4d,0x53,0xe0,0x08,0xb0,0x82,0xe0,0x03,0x22,
    0x12,0x02,0xfb,0x32,0x11,0x42,0x7d,0xd0,0xfa,0x43,0x43,0x46,0x3c,0xb4,0x4b,0x4b,
    0x00,0x22,0x5a,0x80,0x01,0x24,0x24,0x02,0x1a,0x53,0xcb,0x22,0x11,0x42,0x18,0xd0,
    0xb8,0x45,0x01,0xd3,0x00,0x22,0x01,0x92,0x00,0xf0,0x6e,0xf8,0x8e,0xe0,0x43,0x4b,
    0x18,0x8e,0x49,0x46,0x41,0x40,0x01,0x40,0x81,0x46,0xcb,0x22,0x11,0x42,0x08,0xd0,
    0x02,0x9c,0xc2,0x22,0x11,0x42,0xef,0xd1,0xb8,0x45,0x53,0xd3,0x3c,0x4d,0x00,0x23,
    0x18,0xe0,0xe1,0x20,0x30,0x22,0x11,0x42,0x04,0xd1,0x12,0x01,0x11,0x42,0xe7,0xd0,
    0x02,0x22,0x50,0x43,0x02,0x9c,0x36,0x4d,0x6a,0x6a,0x50,0x43,0x83,0x0b,0x00,0xd1,
    0x01,0x23,0x0a,0x00,0x41,0x46,0x11,0x20,0x00,0x01,0x02,0x42,0x0c,0xd1,0xcb,0x1a,
    0x00,0xd2,0x00,0x23,0x00,0x21,0x88,0x46,0x05,0x9c,0x04,0x98,0x59,0x46,0x03,0xc5,
    0x08,0x3d,0x00,0x20,0xa8,0x62,0x04,0xe0,0xcb,0x18,0x78,0x1e,0x83,0x42,0x00,0xd3,
    0x03,0x00,0x99,0x46,0xc8,0x45,0x20,0xd2,0x28,0x68,0x69,0x68,0xab,0x6a,0x1a,0x0c,
    0x06,0xd1,0x01,0x29,0x01,0xd9,0xb0,0x30,0x01,0x39,0x6a,0x6a,0x9b,0x18,0xf6,0xe7,
    0x12,0x04,0x9b,0x1a,0x03,0xc5,0x08,0x3d,0xab,0x62,0x4b,0x46,0x41,0x46,0x58,0x1a,
    0x40,0x28,0x02,0xd9,0x20,0x88,0x24,0x18,0x04,0xe0,0x20,0x00,0x19,0x4a,0x00,0xf0,
    0x12,0xf8,0x04,0x00,0x01,0x20,0x80,0x44,0xdc,0xe7,0x00,0x20,0xa8,0x60,0x13,0x4b,
    0x18,0x8e,0x81,0x46,0x03,0x9d,0x04,0xb0,0x80,0x21,0x59,0x80,0x01,0x22,0x12,0x02,
    0x01,0x21,0x99,0x52,0x10,0x4a,0x10,0x47,0x02,0xb5,0x0e,0x20,0x00,0x06,0x02,0xaa,
    0x0f,0x23,0x00,0xf0,0x05,0xf8,0x02,0xaa,0xf9,0x43,0x13,0x68,0x8b,0x42,0x04,0xbd,
    0x00,0x29,0x04,0xd1,0xc1,0x5c,0xd1,0x54,0x01,0x3b,0xfb,0xd5,0x70,0x47,0x01,0x74,
    0xd1,0x5c,0xc1,0x54,0x01,0x3b,0xfb,0xd5,0x70,0x47,0xc0,0x46,0x00,0x01,0x00,0x04,
    0xd8,0x11,0x00,0x03,0xd8,0x04,0x00,0x03,0x0c,0x0f,0x00,0x03,0xc2,0x23,0x1a,0x42,
    0x04,0xd0,0x03,0x48,0xc1,0x78,0xea,0x29,0x00,0xd1,0x00,0x47,0x67,0xe7,0xc0,0x46,
    0x00,0x00,0xff,0x09
};

static void add_dir_entry(const char *full_path, const char *folder_name, uint8_t dir_type) {
    if (g_entry_count >= MAX_VIDEOS) return;
    for (int i = 0; i < g_entry_count; i++) {
        if (g_entries[i].is_dir && str_cmp_ci(g_entries[i].path, full_path) == 0) return;
    }
    SdVideoEntry *e = &g_entries[g_entry_count++];
    memset(e, 0, sizeof(SdVideoEntry));
    int p = 0;
    while (full_path[p] && p < (int)sizeof(e->path) - 1) { e->path[p] = full_path[p]; p++; }
    e->path[p] = 0;
    if (dir_type == 2) {
        const char *up = "[..] (UP TO PARENT DIR)";
        int k = 0;
        while (up[k]) { e->name[k] = up[k]; k++; }
        e->name[k] = 0;
    } else {
        const char *pfx = "[DIR] ";
        int k = 0;
        while (pfx[k]) { e->name[k] = pfx[k]; k++; }
        int j = 0;
        while (folder_name[j] && k < 35) { e->name[k++] = folder_name[j++]; }
        e->name[k] = 0;
    }
    e->is_dir = dir_type;
    e->file_hash = fnv1a_hash_ci(e->path, dir_type, 0);
}

/* Fast O(1) directory registration WITHOUT calling f_open!
 * Header inspection is deferred lazily to ensure_entry_probed(idx) when highlighted or played,
 * turning a 3-minute 378-file FAT32 scan into an instant <0.1s sequential f_readdir pass! */
static void probe_and_add_video_file(const char *dir_prefix, const char *fname, uint32_t fsize) {
    if (g_entry_count >= MAX_VIDEOS) return;
    int is_agv = str_ends_with_ci(fname, ".AGV") || str_ends_with_ci(fname, ".GV3");
    int is_gba = str_ends_with_ci(fname, ".GBA");
    if (!is_agv && !is_gba) return;
    if (fsize < 1024) return;
    int fn_len = (int)strlen(fname);
    if (is_gba && (token_starts_ci(fname, fn_len, "ARGIE_EZFLASH_SD_PLAYER") ||
                   token_starts_ci(fname, fn_len, "EZKERNEL"))) {
        return;
    }

    char full_path[256];
    int p = 0;
    if (dir_prefix[0] && !(dir_prefix[0] == '/' && dir_prefix[1] == 0)) {
        const char *dp = dir_prefix;
        while (*dp && p < 180) full_path[p++] = *dp++;
    }
    full_path[p++] = '/';
    const char *fp = fname;
    while (*fp && p < 254) full_path[p++] = *fp++;
    full_path[p] = 0;

    if (p >= (int)sizeof(g_entries[0].path)) return;

    SdVideoEntry *e = &g_entries[g_entry_count++];
    memset(e, 0, sizeof(SdVideoEntry));
    memcpy(e->path, full_path, sizeof(e->path) - 1);
    e->path[sizeof(e->path) - 1] = 0;
    { char tmp_raw[36]; make_display_names(e->name, tmp_raw, fname); }
    e->file_size = fsize;
    e->file_hash = fnv1a_hash_ci(e->path, fsize, 0);
    e->fps = is_gba ? 10 : 20;
    e->is_rom_demo = 0;
    e->is_agv = is_agv ? 1 : 0;
    e->is_dir = 0;
    e->is_meteo = is_gba ? 1 : 0;
    e->probed = 0;
}

static int ensure_entry_probed(int idx) {
    if (idx < 0 || idx >= g_entry_count) return 0;
    SdVideoEntry *e = &g_entries[idx];
    if (e->is_dir || e->is_rom_demo) {
        e->probed = 1;
        return 1;
    }
    if (e->probed != 0) {
        return (e->probed == 1) ? 1 : 0;
    }

    if (!g_use_rom_vfat) SetRompage(0x8002);
    if (f_open(&g_file, e->path, FA_READ) != FR_OK) {
        SD_Disable();
        e->probed = 2;
        return 0;
    }

    static const uint32_t candidate_offsets[3] = { 0, 0x2000, 0x10000 };
    AgvHeaderFixed hdr;
    UINT br = 0;
    int found = 0;
    uint32_t found_off = 0;
    uint8_t meteo_type = 0;
    uint32_t meteo_frames = 0;
    uint16_t meteo_fps = 10;
    uint32_t fsize = e->file_size;
    int is_gba = str_ends_with_ci(e->path, ".GBA");

    for (int c = 0; c < 3; c++) {
        uint32_t off = candidate_offsets[c];
        if (off + sizeof(AgvHeaderFixed) > fsize) continue;
        if (f_lseek(&g_file, off) == FR_OK && f_read(&g_file, &hdr, sizeof(AgvHeaderFixed), &br) == FR_OK && br == sizeof(AgvHeaderFixed)) {
            if (hdr.magic == 0x31564741 && hdr.total_frames > 0 && hdr.total_frames < 2000000) {
                found = 1;
                found_off = off;
                break;
            }
        }
    }

    if (!found && is_gba && fsize >= 0xB000u) {
        uint32_t sig_words[2] = {0, 0};
        if (f_lseek(&g_file, 0xA858u) == FR_OK && f_read(&g_file, sig_words, 8, &br) == FR_OK && br == 8 &&
            sig_words[0] == 0x03000F78u && sig_words[1] == 0xE92D4FF3u) {
            uint32_t mhdr[2] = {0, 0};
            if (f_lseek(&g_file, 0xAAE8u) == FR_OK && f_read(&g_file, mhdr, 8, &br) == FR_OK && br == 8) {
                meteo_type = 1;
                meteo_frames = (mhdr[0] > 0 && mhdr[0] < 500000u) ? mhdr[0] : 1800u;
                uint32_t fps_calc = (60u * mhdr[1] + 32768u) >> 16;
                if (fps_calc < 4u || fps_calc > 60u) fps_calc = 10u;
                meteo_fps = (uint16_t)fps_calc;
                found = 1;
            }
        } else if (f_lseek(&g_file, 0xA890u) == FR_OK && f_read(&g_file, sig_words, 8, &br) == FR_OK && br == 8 &&
                   sig_words[0] == 0x030011FCu && sig_words[1] == 0xE92D4FF3u) {
            uint32_t mhdr[2] = {0, 0};
            if (f_lseek(&g_file, 0xAD78u) == FR_OK && f_read(&g_file, mhdr, 8, &br) == FR_OK && br == 8) {
                meteo_type = 2;
                meteo_frames = (mhdr[0] > 0 && mhdr[0] < 500000u) ? mhdr[0] : 1800u;
                uint32_t fps_calc = (60u * mhdr[1] + 32768u) >> 16;
                if (fps_calc < 4u || fps_calc > 60u) fps_calc = 10u;
                meteo_fps = (uint16_t)fps_calc;
                found = 1;
            }
        } else {
            uint8_t gba_fixed = 0;
            if (f_lseek(&g_file, 0xB2u) == FR_OK && f_read(&g_file, &gba_fixed, 1, &br) == FR_OK && br == 1 && gba_fixed == 0x96u) {
                meteo_type = 3;
                meteo_frames = 1800u;
                meteo_fps = 10u;
                found = 1;
            }
        }
    }

    f_close(&g_file);
    SD_Disable();

    if (!found) {
        e->probed = 2;
        return 0;
    }

    if (meteo_type > 0) {
        e->hdr_offset = 0;
        e->total_frames = meteo_frames;
        e->audio_offset = 0;
        e->fps = meteo_fps;
        e->is_agv = 0;
        e->is_meteo = meteo_type;
    } else {
        e->hdr_offset = found_off;
        e->total_frames = hdr.total_frames;
        e->audio_offset = hdr.audio_offset;
        uint32_t vpf = hdr.vblanks_per_frame ? hdr.vblanks_per_frame : 3;
        uint32_t fps = (hdr.seek_15s_frames >= 75) ? (hdr.seek_15s_frames / 15) : (60 / vpf);
        if (fps == 0) fps = 20;
        e->fps = (uint16_t)fps;
        e->is_agv = (found_off == 0) ? 1 : 0;
        e->is_meteo = 0;
    }
    e->probed = 1;
    return 1;
}

static void get_parent_dir(const char *cur, char *out_parent) {
    int len = (int)strlen(cur);
    while (len > 1 && cur[len - 1] == '/') len--;
    int last_slash = 0;
    for (int i = 0; i < len; i++) {
        if (cur[i] == '/') last_slash = i;
    }
    if (last_slash <= 0) {
        out_parent[0] = '/';
        out_parent[1] = 0;
    } else {
        for (int i = 0; i < last_slash; i++) out_parent[i] = cur[i];
        out_parent[last_slash] = 0;
    }
}

static void scan_directory_explorer(const char *dir_path) {
    DIR dir;
    static FILINFO fno;
    if (dir_path[0] == '/' && dir_path[1] != 0) {
        char parent_path[192];
        get_parent_dir(dir_path, parent_path);
        add_dir_entry(parent_path, "..", 2);
    }
    if (f_opendir(&dir, dir_path) != FR_OK) {
        /* If saved directory no longer exists on SD, fall back to root "/" */
        if (dir_path[0] == '/' && dir_path[1] != 0) {
            g_cur_dir[0] = '/';
            g_cur_dir[1] = 0;
            g_entry_count = 0;
            if (f_opendir(&dir, "/") != FR_OK) return;
            dir_path = "/";
        } else {
            return;
        }
    }
    while (1) {
        if (f_readdir(&dir, &fno) != FR_OK || fno.fname[0] == 0) break;
        if (fno.fname[0] == '.') continue;
        if (fno.fattrib & (AM_HID | AM_SYS)) continue;
        if (fno.fattrib & AM_DIR) {
            /* Skip system saver folder */
            if (str_cmp_ci(fno.fname, "SAVER") == 0 || str_cmp_ci(fno.fname, "SYSTEM~1") == 0) continue;
            char sub_path[256];
            int p = 0;
            if (dir_path[0] && !(dir_path[0] == '/' && dir_path[1] == 0)) {
                const char *dp = dir_path;
                while (*dp && p < 180) sub_path[p++] = *dp++;
            }
            sub_path[p++] = '/';
            int j = 0;
            while (fno.fname[j] && p < 254) sub_path[p++] = fno.fname[j++];
            sub_path[p] = 0;
            /* Always preserve subdirectories even if folder has > MAX_VIDEOS files */
            if (g_entry_count >= MAX_VIDEOS) {
                for (int k = g_entry_count - 1; k >= 0; k--) {
                    if (g_entries[k].is_dir == 0) {
                        for (int m = k; m < g_entry_count - 1; m++) g_entries[m] = g_entries[m + 1];
                        g_entry_count--;
                        break;
                    }
                }
            }
            if (g_entry_count < MAX_VIDEOS) {
                add_dir_entry(sub_path, fno.fname, 1);
            }
        } else if (g_entry_count < MAX_VIDEOS) {
            probe_and_add_video_file(dir_path, fno.fname, (uint32_t)fno.fsize);
        }
    }
    f_closedir(&dir);
}

static int entry_rank(const SdVideoEntry *e) {
    if (e->is_dir == 2) return 0; /* [..] always first */
    if (e->is_dir == 1) return 1; /* [DIR] folders next */
    return 2;                     /* Video files sorted alphabetically after folders */
}

static void sort_entries(void) {
    /* If two video files in the same folder share the exact same stripped clean title e->name,
     * promote their clean title to raw_name so both versions remain distinct in the browser list! */
    for (int i = 0; i < g_entry_count - 1; i++) {
        if (g_entries[i].is_dir) continue;
        int dup = 0;
        for (int j = i + 1; j < g_entry_count; j++) {
            if (!g_entries[j].is_dir && str_cmp_ci(g_entries[i].name, g_entries[j].name) == 0) {
                char rbuf[36];
                get_entry_raw_name(&g_entries[j], rbuf);
                if (rbuf[0]) memcpy(g_entries[j].name, rbuf, sizeof(g_entries[j].name));
                dup = 1;
            }
        }
        if (dup) {
            char rbuf[36];
            get_entry_raw_name(&g_entries[i], rbuf);
            if (rbuf[0]) memcpy(g_entries[i].name, rbuf, sizeof(g_entries[i].name));
        }
    }
    for (int i = 0; i < g_entry_count - 1; i++) {
        for (int j = i + 1; j < g_entry_count; j++) {
            int ri = entry_rank(&g_entries[i]);
            int rj = entry_rank(&g_entries[j]);
            int cmp = 0;
            if (ri == rj) {
                cmp = str_cmp_ci(get_entry_display_name(&g_entries[i]), get_entry_display_name(&g_entries[j]));
                if (cmp == 0) {
                    cmp = str_cmp_ci(g_entries[i].path, g_entries[j].path);
                }
            }
            if (ri > rj || (ri == rj && cmp > 0)) {
                SdVideoEntry tmp = g_entries[i];
                g_entries[i] = g_entries[j];
                g_entries[j] = tmp;
            }
        }
    }
}

static void draw_scanning_banner(const char *dir_path) {
    fill_rect(0, 0, 240, 160, RGB15(3, 3, 3));
    fill_rect(0, 0, 240, 18, RGB15(5, 5, 6));
    draw_str(6, 5, "ARGON EZ-FLASH SD PLAYER V4.6", RGB15(29, 28, 27), 30);
    fill_rect(24, 58, 192, 44, RGB15(5, 8, 6));
    draw_str(36, 68, "LOADING SD FOLDER...", RGB15(18, 30, 19), 26);
    draw_str(36, 84, (dir_path && dir_path[0]) ? dir_path : "/", RGB15(23, 25, 23), 26);
}

static void scan_all_videos(void) {
    g_entry_count = 0;
    g_sd_mounted = 0;
    for (int i = 0; i < MAX_VIDEOS; i++) {
        g_shuffle_visited[i] = 0;
        g_ram_bookmarks[i] = 0;
    }
    draw_scanning_banner(g_cur_dir);

    /* Check if a virtual FAT image is attached in ROM at 0x08040000 ("VFAT" tag at 0x0803FFF0) */
    if (*(const volatile uint32_t *)0x0803FFF0 == 0x54414656) {
        g_use_rom_vfat = 1;
    } else {
        g_use_rom_vfat = 0;
        SetRompage(0x8002);
    }

    if (f_mount(&g_fs, "", 1) == FR_OK) {
        g_sd_mounted = 1;
        g_has_psram = probe_psram_hardware();
        if (g_has_psram) {
            /* Reconstruct pristine 64KB Player v4.6 ROM image at top of 32 MiB PSRAM (0x09FF0000) directly from RAM! */
            uint32_t hdr_len   = (uint32_t)((uintptr_t)__iwram_lma - 0x08000000u);
            uint32_t iwram_off = hdr_len;
            uint32_t iwram_len = (uint32_t)(__iwram_end - __iwram_start);
            uint32_t ewram_off = (uint32_t)((uintptr_t)__ewram_code_lma - 0x08000000u);
            uint32_t ewram_len = (uint32_t)(__ewram_code_end - __ewram_code_start);
            if (hdr_len <= sizeof(g_boot_hdr_backup) && (ewram_off + ewram_len) <= 65536u) {
                psram_write_window(0x3000u, 0x007F0000u, g_boot_hdr_backup, hdr_len);
                psram_write_window(0x3000u, 0x007F0000u + iwram_off, __iwram_start, iwram_len);
                psram_write_window(0x3000u, 0x007F0000u + ewram_off, __ewram_code_start, ewram_len);
            }
            SetRompage(0x8002);
            SetPSRampage(0);
        }
        scan_directory_explorer(g_cur_dir);
        sort_entries();
        SD_Disable();
    } else {
        g_has_psram = 0;
        if (!g_use_rom_vfat) {
            SD_Disable();
            SetRompage(0x200);
        }
    }

    /* Only fall back to embedded demo AGV1 stream at 0x08010000 if no SD videos were found */
    const AgvHeaderFixed *rom_hdr = (const AgvHeaderFixed *)0x08010000;
    if (g_entry_count == 0 && rom_hdr->magic == 0x31564741 && g_entry_count < MAX_VIDEOS) {
        SdVideoEntry *e = &g_entries[g_entry_count++];
        const char *custom_name = (const char *)0x0800FFD0;
        const char *dname = "Argie_SD_Demo.agv";
        char rom_title_buf[24];
        if (custom_name[0] >= 0x21 && custom_name[0] < 0x7F) {
            dname = custom_name;
        } else if (*(const volatile uint32_t *)0x0800FFFC == 0x4155544Fu || *(const volatile uint32_t *)0x0800FFFC == 0x4F545541u) {
            const char *hdr_t = (const char *)0x080000A0;
            int ti = 0;
            for (int k = 0; k < 12 && hdr_t[k] >= 0x20 && hdr_t[k] < 0x7F; k++) {
                if (hdr_t[k] != ' ') rom_title_buf[ti++] = hdr_t[k];
            }
            if (ti == 0) { rom_title_buf[ti++] = 'V'; rom_title_buf[ti++] = 'I'; rom_title_buf[ti++] = 'D'; }
            rom_title_buf[ti++] = '.'; rom_title_buf[ti++] = 'g'; rom_title_buf[ti++] = 'b'; rom_title_buf[ti++] = 'a';
            rom_title_buf[ti] = 0;
            dname = rom_title_buf;
        }
        int i = 0;
        while (dname[i] && i < 35) { e->name[i] = dname[i]; e->path[i] = dname[i]; i++; }
        e->name[i] = 0; e->path[i] = 0;
        e->hdr_offset = 0x08010000;
        e->total_frames = rom_hdr->total_frames;
        e->audio_offset = rom_hdr->audio_offset;
        uint32_t vpf = rom_hdr->vblanks_per_frame ? rom_hdr->vblanks_per_frame : 3;
        uint32_t fps = (rom_hdr->seek_15s_frames >= 75) ? (rom_hdr->seek_15s_frames / 15) : (60 / vpf);
        if (fps == 0) fps = 20;
        e->fps = (uint16_t)fps;
        e->file_size = rom_hdr->audio_offset + ((rom_hdr->total_frames * (rom_hdr->audio_rate ? rom_hdr->audio_rate : 10512u)) / fps);
        e->file_hash = fnv1a_hash_ci(e->path, e->file_size, e->total_frames);
        e->is_rom_demo = 1;
        e->is_agv = 1;
    }
}

/* Read/Write across 32MB banked PSRAM window (0x08800000 across pages 0x0000..0x3000) */
static void read_from_banked_psram_32m(uint32_t psram_off, void *dst, uint32_t len) {
    uint8_t *d8 = (uint8_t *)dst;
    uint32_t rem = len;
    uint32_t cur = psram_off;
    while (rem > 0) {
        uint16_t page = (uint16_t)((cur >> 23) << 12); /* 0x0000, 0x1000, 0x2000, 0x3000 */
        uint32_t page_off = cur & 0x7FFFFFu;
        uint32_t page_rem = 0x800000u - page_off;
        uint32_t step = (rem < page_rem) ? rem : page_rem;
        psram_read_window(page, page_off, d8, step);
        d8  += step;
        cur += step;
        rem -= step;
    }
}

static void write_to_banked_psram_32m(uint32_t psram_off, const void *src, uint32_t len) {
    const uint8_t *s8 = (const uint8_t *)src;
    uint32_t rem = len;
    uint32_t cur = psram_off;
    while (rem > 0) {
        uint16_t page = (uint16_t)((cur >> 23) << 12);
        uint32_t page_off = cur & 0x7FFFFFu;
        uint32_t page_rem = 0x800000u - page_off;
        uint32_t step = (rem < page_rem) ? rem : page_rem;
        psram_write_window(page, page_off, s8, step);
        s8  += step;
        cur += step;
        rem -= step;
    }
}

static uint32_t read_u32_banked_psram_32m(uint32_t psram_off) {
    uint32_t val = 0;
    read_from_banked_psram_32m(psram_off, &val, 4);
    return val;
}

static void write_u32_banked_psram_32m(uint32_t psram_off, uint32_t val) {
    write_to_banked_psram_32m(psram_off, &val, 4);
}

/* Raw read from Linear PSRAM (0x08000000, Rompage 0x200), Banked PSRAM (0x08800000), ROM Demo, or SD file */
static int raw_stream_read_at(const SdVideoEntry *e, uint32_t file_off, void *dst, uint32_t len) {
    if (e->is_rom_demo) {
        memcpy(dst, (const void *)(0x08010000u + file_off), len);
        return 0;
    }
    if (g_linear_psram_mode == 1) {
        memcpy(dst, (const void *)(g_linear_psram_ptr + file_off), len);
        return 0;
    }
    if (g_linear_psram_mode == 2) {
        read_from_banked_psram_32m(file_off, dst, len);
        return 0;
    }
    if (f_lseek(&g_file, file_off) != FR_OK) {
        SD_Disable();
        return -1;
    }
    UINT br = 0;
    FRESULT res = f_read(&g_file, dst, len, &br);
    SD_Disable();
    if (res != FR_OK || br == 0) return -1;
    if (br < len) {
        memset((uint8_t *)dst + br, 0, len - br);
    }
    return 0;
}

/* Load an entire .GBA or .AGV file (<= 32 MiB) into 32 MiB PSRAM while audio is muted,
 * then call f_close(&g_file) + SD_Disable() + SetRompage(0x200) so the entire video/part
 * plays 100% from linear PSRAM (0x08000000..0x09FFFFFF) with ZERO SD card access and ZERO speaker noise!
 */
static uint32_t read_file_u32_at(uint32_t file_off) {
    uint32_t val = 0;
    if (f_lseek(&g_file, file_off) == FR_OK) {
        UINT br = 0;
        f_read(&g_file, &val, 4, &br);
    }
    SD_Disable();
    return val;
}

static int load_entry_to_linear_psram(const SdVideoEntry *e) {
    int show_bar = (g_show_load_bar != LOAD_BAR_HIDE);
    g_linear_psram_mode = 0;
    if (e->is_rom_demo) {
        if (!g_use_rom_vfat && g_sd_mounted) {
            SD_Disable();
            Set_RTC_status(0);
            SetRompage(0x200);
        }
        return 1;
    }
    if (g_use_rom_vfat || !g_has_psram || g_buf_mode != BUF_MODE_PSRAM_32M) {
        return 0;
    }
    if (e->file_size == 0 || e->file_size > 0x02000000u) {
        /* Files > 32 MiB automatically stream via SD DIRECT */
        return 0;
    }

    /* Fast path: if this exact file is ALREADY in 32 MiB PSRAM (e.g. Part 1 at boot or re-selected from menu),
     * switch straight to SetRompage(0x200) + SD_Disable() without re-reading the SD card! */
    if (g_loaded_psram_hash == e->file_hash && e->file_hash != 0) {
        f_close(&g_file);
        SD_Disable();
        SetPSRampage(0);
        Set_RTC_status(0);
        SetRompage(0x200);
        const volatile AgvHeaderFixed *lhdr = (const volatile AgvHeaderFixed *)(0x08000000u + e->hdr_offset);
        uint32_t aud_probe_off = e->hdr_offset + e->audio_offset;
        uint32_t cur_aud_word = (aud_probe_off + 4u <= 0x02000000u) ? *(const volatile uint32_t *)(0x08000000u + aud_probe_off) : 0u;
        if (lhdr->magic == 0x31564741u &&
            lhdr->total_frames == e->total_frames &&
            lhdr->audio_offset == e->audio_offset &&
            cur_aud_word == g_loaded_psram_aud_word) {
            g_linear_psram_mode = 1;
            g_linear_psram_ptr  = (const uint8_t *)0x08000000u;
            return 1;
        }
        /* Re-open file in kernel mode if PSRAM contents changed */
        SetRompage(0x8002);
        if (f_open(&g_file, e->path, FA_READ) != FR_OK) {
            SD_Disable();
            return -1;
        }
        g_clmt[0] = 1024;
        g_file.cltbl = g_clmt;
        if (f_lseek(&g_file, CREATE_LINKMAP) != FR_OK) g_file.cltbl = NULL;
    }

    /* Ensure kernel mode (0x8002) and PSRAM page 0 before DMA/CPU load */
    SetRompage(0x8002);
    SetPSRampage(0);
    SD_Disable();

    /* Draw sleek progress bar while audio is completely muted (if g_show_load_bar is enabled) */
    if (show_bar) {
        fill_rect(12, 132, 216, 20, RGB15(3, 3, 4));
        draw_str(20, 136, "LOADING TO PSRAM (0-NOISE)...", RGB15(18, 29, 18), 32);
        fill_rect(20, 146, 200, 3, RGB15(7, 7, 9));
    }

    /* Clear magic word in PSRAM at hdr_offset so stale data cannot cause a false match */
    *(volatile uint16_t *)(0x08800000u + e->hdr_offset) = 0x0000u;
    *(volatile uint16_t *)(0x08800000u + e->hdr_offset + 2u) = 0x0000u;

    /* 1. Try EZ-FLASH Omega DE hardware FPGA SD->PSRAM DMA (Send_FATbuffer mode 0, exact ezkernelnew.c protocol) */
    memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
    g_fat_table_buf[2] = 0xFFFFFFFFu;
    u32 *fat_p = g_fat_table_buf;
    u32 cluster_num = 0;
    u32 lastest_cluster = (g_fs.fs_type == FS_FAT16) ? 0xFFFFu : 0xFFFFFF7u;
    u32 getcluster = g_file.obj.sclust;
    u32 getcluster_old = getcluster;
    int fat_table_ok = (getcluster >= 2);

    if (fat_table_ok) {
        *fat_p++ = 0x00000000u;
        *fat_p++ = ClustToSect(&g_fs, getcluster);
        do {
            getcluster = Get_NextCluster(&g_file.obj, getcluster);
            cluster_num++;
            if (getcluster == 0xFFFFFFFFu || getcluster <= 1u) {
                fat_table_ok = 0;
                break;
            }
            if (getcluster != (getcluster_old + 1u)) {
                if ((fat_p - g_fat_table_buf) >= 120) {
                    fat_table_ok = 0;
                    break;
                }
                *fat_p++ = cluster_num * (u32)g_fs.csize;
                *fat_p++ = ClustToSect(&g_fs, getcluster);
            }
            getcluster_old = getcluster;
        } while (getcluster < lastest_cluster);
    }

    uint32_t load_limit = (e->file_size > 0x01FF0000u) ? 0x01FF0000u : e->file_size;
    uint32_t mid_off    = (load_limit >> 1) & ~3u;
    uint32_t last_off   = (load_limit >= 16u) ? ((load_limit - 4u) & ~3u) : e->hdr_offset;
    uint32_t exp_mid    = read_file_u32_at(mid_off);
    uint32_t exp_last   = read_file_u32_at(last_off);
    SetRompage(0x8002);
    write_u32_banked_psram_32m(e->hdr_offset, 0u);
    write_u32_banked_psram_32m(mid_off, ~exp_mid);
    write_u32_banked_psram_32m(last_off, ~exp_last);

    if (fat_table_ok) {
        uint32_t cluster_bytes = (uint32_t)g_fs.csize * 512u;
        uint32_t dma_bytes = load_limit;
        if (cluster_bytes > 0) {
            dma_bytes = ((load_limit + cluster_bytes - 1u) / cluster_bytes) * cluster_bytes;
            if (dma_bytes > 0x01FF0000u) dma_bytes = 0x01FF0000u;
        }
        *--fat_p = 0x00000000u;
        *--fat_p = 0xFFFFFFFFu;
        g_fat_table_buf[0x1F0 / 4] = dma_bytes;
        g_fat_table_buf[0x1F4 / 4] = 1u; /* DMA_COPY_MODE */
        g_fat_table_buf[0x1F8 / 4] = (u32)g_fs.csize;
        g_fat_table_buf[0x1FC / 4] = 0x10010000u; /* Keep homebrew SRAM saveMODE (0x10) + 64KB save size active! */

        SD_Disable();
        SetRompage(0x8002);
        SetPSRampage(0);
        Send_FATbuffer(g_fat_table_buf, 0);
        if (show_bar) fill_rect(20, 146, 200, 3, RGB15(12, 26, 14));
    }

    SetRompage(0x8002);
    SetPSRampage(0);
    const volatile AgvHeaderFixed *ps_hdr = (const volatile AgvHeaderFixed *)(0x08800000u + e->hdr_offset);
    int loaded_ok = (ps_hdr->magic == 0x31564741u &&
                     ps_hdr->total_frames == e->total_frames &&
                     ps_hdr->audio_offset == e->audio_offset &&
                     read_u32_banked_psram_32m(mid_off) == exp_mid &&
                     read_u32_banked_psram_32m(last_off) == exp_last);

    /* 2. Automatic fallback to CPU+DMA3 Loadfile2PSRAM (works on regular EZ-FLASH Omega and fragmented/exFAT files) */
    if (!loaded_ok) {
        memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
        g_fat_table_buf[2] = 0xFFFFFFFFu;
        g_fat_table_buf[0x1F4 / 4] = 2u; /* SET_PARAMETER_MODE */
        g_fat_table_buf[0x1FC / 4] = 0x10010000u; /* Keep homebrew SRAM saveMODE (0x10) + 64KB save size active! */
        Send_FATbuffer(g_fat_table_buf, 1);

        if (f_lseek(&g_file, 0) == FR_OK) {
            uint32_t offset = 0;
            while (offset < e->file_size) {
                uint32_t rem = e->file_size - offset;
                uint32_t step = (rem > 16384u) ? 16384u : rem;
                uint32_t page_off = offset & 0x7FFFFFu;
                if (page_off + step > 0x800000u) step = 0x800000u - page_off;
                UINT br = 0;
                if (f_read(&g_file, g_video_chunk_buf, step, &br) != FR_OK || br == 0) break;
                uint16_t page = (uint16_t)((offset >> 23) << 12);
                psram_write_window(page, page_off, g_video_chunk_buf, (uint32_t)br);
                offset += (uint32_t)br;
                if (show_bar) {
                    uint32_t bw = (uint32_t)(((uint64_t)offset * 200u) / (e->file_size ? e->file_size : 1u));
                    fill_rect(20, 146, (int)bw, 3, RGB15(12, 26, 14));
                }
            }
            SetPSRampage(0);
            loaded_ok = (ps_hdr->magic == 0x31564741u &&
                         ps_hdr->total_frames == e->total_frames &&
                         ps_hdr->audio_offset == e->audio_offset);
        }
    }

    if (loaded_ok) {
        /* Close SD file and disable SD controller completely BEFORE playback starts! */
        f_close(&g_file);
        SD_Disable();
        SetPSRampage(0);
        Set_RTC_status(0);
        SetRompage(0x200);

        const volatile AgvHeaderFixed *lin_hdr = (const volatile AgvHeaderFixed *)(0x08000000u + e->hdr_offset);
        if (lin_hdr->magic == 0x31564741u &&
            lin_hdr->total_frames == e->total_frames &&
            lin_hdr->audio_offset == e->audio_offset) {
            uint32_t aud_probe_off = e->hdr_offset + e->audio_offset;
            g_loaded_psram_aud_word = (aud_probe_off + 4u <= 0x02000000u) ? *(const volatile uint32_t *)(0x08000000u + aud_probe_off) : 0u;
            g_linear_psram_mode = 1;
            g_linear_psram_ptr  = (const uint8_t *)0x08000000u;
            g_loaded_psram_hash = e->file_hash;
            g_chap_loaded_hash  = 0;
            return 1;
        }

        /* Secondary 0-noise path if cart keeps 0x08800000 banked in Rompage 0x8002 */
        SetRompage(0x8002);
        SetPSRampage(0);
        if (ps_hdr->magic == 0x31564741u &&
            ps_hdr->total_frames == e->total_frames &&
            ps_hdr->audio_offset == e->audio_offset) {
            g_linear_psram_mode = 2;
            g_loaded_psram_hash = e->file_hash;
            g_chap_loaded_hash  = 0;
            return 1;
        }
    }

    /* Fallback to SD DIRECT if PSRAM load did not verify */
    SetRompage(0x8002);
    f_lseek(&g_file, 0);
    SD_Disable();
    g_linear_psram_mode = 0;
    return 0;
}

/* Append a cluster-aligned file slice [file_byte_off .. file_byte_off + byte_len)
 * into g_fat_table_buf using the in-memory FatFs CLMT (g_clmt) with zero SD reads. */
static int append_clmt_slice_to_fat_table(uint32_t file_byte_off, uint32_t byte_len, uint32_t *io_psram_sect, uint32_t *io_prev_next_cl, u32 **io_fat_p) {
    uint32_t csize = (uint32_t)g_fs.csize;
    if (csize == 0 || g_file.cltbl == NULL) return 0;
    uint32_t cluster_bytes = csize * 512u;
    uint32_t start_cl = file_byte_off / cluster_bytes;
    uint32_t rem_cl = (byte_len + cluster_bytes - 1u) / cluster_bytes;
    if (rem_cl == 0) return 1;

    const DWORD *tbl = g_file.cltbl + 1;
    DWORD ncl = 0, tcl = 0;
    for (;;) {
        ncl = *tbl++;
        if (ncl == 0) return 0;
        tcl = *tbl++;
        if (start_cl < (uint32_t)ncl) break;
        start_cl -= (uint32_t)ncl;
    }

    uint32_t cur_tcl = (uint32_t)tcl + start_cl;
    uint32_t avail_cl = (uint32_t)ncl - start_cl;
    u32 *fat_p = *io_fat_p;
    uint32_t psram_sect = *io_psram_sect;
    uint32_t prev_next_cl = *io_prev_next_cl;

    while (rem_cl > 0) {
        if (fat_p == g_fat_table_buf || cur_tcl != prev_next_cl) {
            if ((fat_p - g_fat_table_buf) >= 120) return 0;
            *fat_p++ = psram_sect;
            *fat_p++ = ClustToSect(&g_fs, cur_tcl);
        }
        uint32_t step_cl = (rem_cl < avail_cl) ? rem_cl : avail_cl;
        psram_sect += step_cl * csize;
        prev_next_cl = cur_tcl + step_cl;
        rem_cl -= step_cl;
        if (rem_cl > 0) {
            avail_cl = (uint32_t)(*tbl++);
            if (avail_cl == 0) return 0;
            cur_tcl = (uint32_t)(*tbl++);
        }
    }

    *io_fat_p = fat_p;
    *io_psram_sect = psram_sect;
    *io_prev_next_cl = prev_next_cl;
    return 1;
}

static int load_slice_to_psram_cpu(uint32_t file_off, uint32_t psram_off, uint32_t byte_len, uint32_t prog_done_base, uint32_t prog_total) {
    if (f_lseek(&g_file, file_off) != FR_OK) {
        SD_Disable();
        return 0;
    }
    uint32_t done = 0;
    while (done < byte_len) {
        uint32_t rem = byte_len - done;
        uint32_t step = (rem > 16384u) ? 16384u : rem;
        UINT br = 0;
        if (f_read(&g_file, g_video_chunk_buf, step, &br) != FR_OK || br == 0) break;
        write_to_banked_psram_32m(psram_off + done, g_video_chunk_buf, (uint32_t)br);
        done += (uint32_t)br;
        if (prog_total > 0 && (g_show_load_bar != LOAD_BAR_HIDE)) {
            uint32_t cur_prog = prog_done_base + done;
            if (cur_prog > prog_total) cur_prog = prog_total;
            uint32_t bw = (uint32_t)(((uint64_t)cur_prog * 200u) / prog_total);
            fill_rect(20, 146, (int)bw, 3, RGB15(12, 26, 14));
        }
    }
    SD_Disable();
    return (done > 0) ? 1 : 0;
}

/* Player v2.7: 32 MiB Chaptered Zero-Noise PSRAM Mode for > 32 MiB .AGV files!
 * Partitions 32 MiB PSRAM into:
 *  - Slice 0 [0 .. g_chap_vid_psram_off): AgvHeaderFixed + full frame offset index table (up to 1 MiB)
 *  - Slice 1 [g_chap_vid_psram_off .. g_chap_aud_psram_off): up to 25 MiB of compressed video frames
 *  - Slice 2 [g_chap_aud_psram_off .. +aud_load_len): up to 6 MiB of PCM audio (~6.4 min @ 16.384 kHz)
 * Then closes g_file, calls SD_Disable() + SetRompage(0x200), and plays the entire chapter from
 * linear 0x08000000 PSRAM with ZERO speaker noise and instant (0ms) in-chapter seeking!
 */
static int load_psram_chapter_for_frame(
    const SdVideoEntry *e,
    uint32_t target_frame,
    uint32_t offset_base,
    uint32_t audio_file_base,
    uint32_t total_frames,
    uint32_t kf_int,
    uint32_t audio_rate,
    uint32_t fps,
    int is_chapter_transition
) {
    int show_bar = (g_show_load_bar == LOAD_BAR_SHOW) || (g_show_load_bar == LOAD_BAR_FILE && !is_chapter_transition);
    if (e->is_rom_demo || g_use_rom_vfat || !g_has_psram || g_buf_mode != BUF_MODE_PSRAM_32M) {
        return 0;
    }
    if (e->file_size <= 0x02000000u) {
        return 0;
    }

    REG_DMA1CNT = 0;
    REG_TM0CNT_H = 0;
    REG_TM1CNT_H = 0;

    /* Fast path: if this exact chapter is ALREADY in 32 MiB PSRAM (e.g. resuming from SD menu),
     * switch straight to SetRompage(0x200) + SD_Disable() with zero SD reads! */
    if (g_chap_loaded_hash == e->file_hash && e->file_hash != 0 &&
        target_frame >= g_chap_start_frame && target_frame < g_chap_end_frame) {
        if (g_file.obj.fs != NULL) f_close(&g_file);
        SD_Disable();
        SetPSRampage(0);
        Set_RTC_status(0);
        SetRompage(0x200);
        const volatile AgvHeaderFixed *lhdr = (const volatile AgvHeaderFixed *)(0x08000000u + e->hdr_offset);
        uint32_t cur_vf = *(const volatile uint32_t *)(0x08000000u + g_chap_vid_psram_off);
        uint32_t cur_af = *(const volatile uint32_t *)(0x08000000u + g_chap_aud_psram_off);
        if (lhdr->magic == 0x31564741u &&
            lhdr->total_frames == e->total_frames &&
            cur_vf == g_chap_exp_vid_first &&
            cur_af == g_chap_exp_aud_first) {
            g_linear_psram_mode = 3;
            g_linear_psram_ptr  = (const uint8_t *)0x08000000u;
            return 1;
        }
    }

    SetRompage(0x8002);
    SetPSRampage(0);
    SD_Disable();

    if (g_file.obj.fs == NULL) {
        if (f_open(&g_file, e->path, FA_READ) != FR_OK) {
            SD_Disable();
            g_linear_psram_mode = 0;
            return -1;
        }
    }
    if (g_chap_clmt_hash == e->file_hash && g_clmt[0] == 2048 && g_clmt[1] > 0) {
        g_file.cltbl = g_clmt;
    } else {
        g_clmt[0] = 1024;
        g_file.cltbl = g_clmt;
        if (f_lseek(&g_file, CREATE_LINKMAP) == FR_OK) {
            g_chap_clmt_hash = e->file_hash;
        } else {
            g_file.cltbl = NULL;
        }
        SD_Disable();
    }

    uint32_t csize = (uint32_t)g_fs.csize;
    if (csize == 0) csize = 64u;
    uint32_t cluster_bytes = csize * 512u;

    uint32_t idx_end = e->hdr_offset + 40u + total_frames * 4u;
    uint32_t idx_slice_bytes = (idx_end + cluster_bytes - 1u) & ~(cluster_bytes - 1u);
    if (idx_slice_bytes < cluster_bytes) idx_slice_bytes = cluster_bytes;
    if (idx_slice_bytes > 0x00100000u) idx_slice_bytes = 0x00100000u;
    g_chap_vid_psram_off = idx_slice_bytes;

    /* Save bottom 30 rows of VRAM (y=130..159, 14,400 bytes) into upper g_video_chunk_buf[65536..79935] */
    if (show_bar) {
        memcpy(&g_video_chunk_buf[14336], (const void *)(VRAM_FB + 130 * 240), 240 * 30 * 2);
        fill_rect(12, 132, 216, 20, RGB15(3, 3, 4));
        draw_str(20, 136, "LOADING CHAPTER (0-NOISE)...", RGB15(18, 29, 18), 32);
        fill_rect(20, 146, 200, 3, RGB15(7, 7, 9));
    }

    /* Ensure Slice 0 (Header + Frame Offset Table) is in PSRAM[0 .. idx_slice_bytes) */
    int s0_ok = (g_chap_loaded_hash == e->file_hash && e->file_hash != 0 &&
                 read_u32_banked_psram_32m(e->hdr_offset) == 0x31564741u &&
                 read_u32_banked_psram_32m(e->hdr_offset + 4u) == e->total_frames &&
                 read_u32_banked_psram_32m(e->hdr_offset + 20u) == e->audio_offset);
    if (!s0_ok) {
        memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
        g_fat_table_buf[2] = 0xFFFFFFFFu;
        g_fat_table_buf[0x1F4 / 4] = 2u; /* SET_PARAMETER_MODE */
        g_fat_table_buf[0x1FC / 4] = 0x10010000u;
        Send_FATbuffer(g_fat_table_buf, 1);

        load_slice_to_psram_cpu(0, 0, idx_slice_bytes, 0, 0);
        s0_ok = (read_u32_banked_psram_32m(e->hdr_offset) == 0x31564741u &&
                 read_u32_banked_psram_32m(e->hdr_offset + 4u) == e->total_frames &&
                 read_u32_banked_psram_32m(e->hdr_offset + 20u) == e->audio_offset);
        if (!s0_ok) {
            /* Running in an emulator without writable 0x08800000 PSRAM: restore VRAM & fallback to SD stream */
            if (show_bar) memcpy((void *)(VRAM_FB + 130 * 240), &g_video_chunk_buf[14336], 240 * 30 * 2);
            g_ewram_vid_start = 0xFFFFFFFFu;
            g_ewram_vid_end   = 0;
            f_lseek(&g_file, 0);
            SD_Disable();
            g_linear_psram_mode = 0;
            return 0;
        }
    }

    /* Compute chapter frame window [g_chap_start_frame, g_chap_end_frame) from PSRAM Slice 0 frame table */
    uint32_t f0_raw = read_u32_banked_psram_32m(e->hdr_offset + 40u + target_frame * 4u) & 0x7FFFFFFFu;
    uint32_t f0_start = offset_base + f0_raw;
    g_chap_vid_base = f0_start & ~(cluster_bytes - 1u);
    g_chap_vid_psram_off = idx_slice_bytes;

    uint32_t aud0_abs = audio_file_base + (((uint32_t)(((uint64_t)target_frame * audio_rate) / fps)) & ~15u);
    if (aud0_abs > e->file_size) aud0_abs = e->file_size;
    g_chap_aud_base = aud0_abs & ~(cluster_bytes - 1u);

    uint32_t lo = target_frame + 1u;
    uint32_t hi = total_frames;
    uint32_t best_end = (lo <= total_frames) ? lo : total_frames;
    while (lo <= hi) {
        uint32_t mid = lo + ((hi - lo) >> 1);
        uint32_t v_end = (mid < total_frames)
            ? (offset_base + (read_u32_banked_psram_32m(e->hdr_offset + 40u + mid * 4u) & 0x7FFFFFFFu))
            : audio_file_base;
        uint32_t a_end = audio_file_base + (uint32_t)(((uint64_t)mid * audio_rate) / fps) + 65536u;
        if (a_end > e->file_size) a_end = e->file_size;
        uint32_t v_span = (v_end > g_chap_vid_base) ? (v_end - g_chap_vid_base) : 0u;
        uint32_t a_span = (a_end > g_chap_aud_base) ? (a_end - g_chap_aud_base) : 0u;
        if (v_span <= CHAP_VID_MAX_BYTES && a_span <= CHAP_AUD_MAX_BYTES) {
            best_end = mid;
            lo = mid + 1u;
        } else {
            if (mid == 0) break;
            hi = mid - 1u;
        }
    }
    if (best_end < total_frames && kf_int > 1u && best_end > target_frame + kf_int) {
        uint32_t aligned_end = (best_end / kf_int) * kf_int;
        if (aligned_end > target_frame) best_end = aligned_end;
    }
    g_chap_start_frame = target_frame;
    g_chap_end_frame   = best_end;

    uint32_t v_end_byte = (best_end < total_frames)
        ? (offset_base + (read_u32_banked_psram_32m(e->hdr_offset + 40u + best_end * 4u) & 0x7FFFFFFFu))
        : audio_file_base;
    if (v_end_byte <= g_chap_vid_base) v_end_byte = g_chap_vid_base + cluster_bytes;
    uint32_t vid_load_len = ((v_end_byte - g_chap_vid_base) + cluster_bytes - 1u) & ~(cluster_bytes - 1u);
    if (vid_load_len > CHAP_VID_MAX_BYTES) vid_load_len = CHAP_VID_MAX_BYTES & ~(cluster_bytes - 1u);
    if (g_chap_vid_base + vid_load_len > e->file_size) {
        vid_load_len = e->file_size - g_chap_vid_base;
    }
    g_chap_vid_end = g_chap_vid_base + vid_load_len;

    uint32_t vid_psram_span = (vid_load_len + cluster_bytes - 1u) & ~(cluster_bytes - 1u);
    g_chap_aud_psram_off = g_chap_vid_psram_off + vid_psram_span;

    uint32_t a_end_byte = audio_file_base + (uint32_t)(((uint64_t)best_end * audio_rate) / fps) + 65536u;
    if (a_end_byte > e->file_size) a_end_byte = e->file_size;
    if (a_end_byte <= g_chap_aud_base) {
        a_end_byte = (g_chap_aud_base + cluster_bytes <= e->file_size) ? (g_chap_aud_base + cluster_bytes) : e->file_size;
    }
    uint32_t aud_load_len = ((a_end_byte - g_chap_aud_base) + cluster_bytes - 1u) & ~(cluster_bytes - 1u);
    if (aud_load_len > CHAP_AUD_MAX_BYTES) aud_load_len = CHAP_AUD_MAX_BYTES & ~(cluster_bytes - 1u);
    if (g_chap_aud_base + aud_load_len > e->file_size) {
        aud_load_len = e->file_size - g_chap_aud_base;
    }
    g_chap_aud_end = g_chap_aud_base + aud_load_len;

    uint32_t v_last_off = (vid_load_len >= 4u) ? (vid_load_len - 4u) : 0u;
    uint32_t a_last_off = (aud_load_len >= 4u) ? (aud_load_len - 4u) : 0u;
    uint32_t exp_vf = read_file_u32_at(g_chap_vid_base);
    uint32_t exp_vl = read_file_u32_at(g_chap_vid_base + v_last_off);
    uint32_t exp_af = read_file_u32_at(g_chap_aud_base);
    uint32_t exp_al = read_file_u32_at(g_chap_aud_base + a_last_off);

    /* Poison target probe offsets in PSRAM so stale data cannot cause a false match */
    write_u32_banked_psram_32m(g_chap_vid_psram_off, ~exp_vf);
    write_u32_banked_psram_32m(g_chap_vid_psram_off + v_last_off, ~exp_vl);
    write_u32_banked_psram_32m(g_chap_aud_psram_off, ~exp_af);
    write_u32_banked_psram_32m(g_chap_aud_psram_off + a_last_off, ~exp_al);

    /* 1. Try EZ-FLASH Omega DE hardware FPGA scatter-gather SD->PSRAM DMA across all 3 slices */
    memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
    g_fat_table_buf[2] = 0xFFFFFFFFu;
    u32 *fat_p = g_fat_table_buf;
    uint32_t psram_sect = 0;
    uint32_t prev_next_cl = 0xFFFFFFFFu;
    int fat_ok = 1;
    if (g_chap_vid_base + vid_psram_span > e->file_size) {
        fat_ok = 0;
    }
    if (fat_ok && g_chap_vid_psram_off > 0) {
        fat_ok = append_clmt_slice_to_fat_table(0, g_chap_vid_psram_off, &psram_sect, &prev_next_cl, &fat_p);
    }
    if (fat_ok) fat_ok = append_clmt_slice_to_fat_table(g_chap_vid_base, vid_psram_span, &psram_sect, &prev_next_cl, &fat_p);
    if (fat_ok) fat_ok = append_clmt_slice_to_fat_table(g_chap_aud_base, aud_load_len, &psram_sect, &prev_next_cl, &fat_p);

    if (fat_ok && (fat_p - g_fat_table_buf) <= 122) {
        *fat_p++ = 0xFFFFFFFFu;
        *fat_p++ = 0x00000000u;
        uint32_t total_dma_bytes = g_chap_aud_psram_off + ((aud_load_len + 511u) & ~511u);
        if (total_dma_bytes > 0x01FF0000u) total_dma_bytes = 0x01FF0000u;
        g_fat_table_buf[0x1F0 / 4] = total_dma_bytes;
        g_fat_table_buf[0x1F4 / 4] = 1u; /* DMA_COPY_MODE */
        g_fat_table_buf[0x1F8 / 4] = csize;
        g_fat_table_buf[0x1FC / 4] = 0x10010000u; /* Keep homebrew SRAM saveMODE (0x10) + 64KB save size active! */

        SD_Disable();
        SetPSRampage(0);
        Send_FATbuffer(g_fat_table_buf, 0);
        if (show_bar) fill_rect(20, 146, 200, 3, RGB15(12, 26, 14));
    }

    s0_ok = (read_u32_banked_psram_32m(e->hdr_offset) == 0x31564741u &&
             read_u32_banked_psram_32m(e->hdr_offset + 4u) == e->total_frames &&
             read_u32_banked_psram_32m(e->hdr_offset + 20u) == e->audio_offset);
    int s1_ok = (read_u32_banked_psram_32m(g_chap_vid_psram_off) == exp_vf &&
                 read_u32_banked_psram_32m(g_chap_vid_psram_off + v_last_off) == exp_vl);
    int s2_ok = (read_u32_banked_psram_32m(g_chap_aud_psram_off) == exp_af &&
                 read_u32_banked_psram_32m(g_chap_aud_psram_off + a_last_off) == exp_al);

    /* 2. Automatic CPU+DMA3 fallback for any slice not already verified in PSRAM */
    if (!s0_ok || !s1_ok || !s2_ok) {
        memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
        g_fat_table_buf[2] = 0xFFFFFFFFu;
        g_fat_table_buf[0x1F4 / 4] = 2u; /* SET_PARAMETER_MODE */
        g_fat_table_buf[0x1FC / 4] = 0x10010000u;
        Send_FATbuffer(g_fat_table_buf, 1);

        uint32_t prog_tot = show_bar ? ((s1_ok ? 0u : vid_load_len) + (s2_ok ? 0u : aud_load_len)) : 0u;
        uint32_t prog_cur = 0;

        if (!s0_ok) {
            load_slice_to_psram_cpu(0, 0, idx_slice_bytes, 0, prog_tot);
        }
        if (!s1_ok) {
            load_slice_to_psram_cpu(g_chap_vid_base, g_chap_vid_psram_off, vid_load_len, prog_cur, prog_tot);
            prog_cur += vid_load_len;
        }
        if (!s2_ok) {
            load_slice_to_psram_cpu(g_chap_aud_base, g_chap_aud_psram_off, aud_load_len, prog_cur, prog_tot);
        }
        s0_ok = (read_u32_banked_psram_32m(e->hdr_offset) == 0x31564741u &&
                 read_u32_banked_psram_32m(e->hdr_offset + 4u) == e->total_frames &&
                 read_u32_banked_psram_32m(e->hdr_offset + 20u) == e->audio_offset);
        s1_ok = (read_u32_banked_psram_32m(g_chap_vid_psram_off) == exp_vf &&
                 read_u32_banked_psram_32m(g_chap_vid_psram_off + v_last_off) == exp_vl);
        s2_ok = (read_u32_banked_psram_32m(g_chap_aud_psram_off) == exp_af &&
                 read_u32_banked_psram_32m(g_chap_aud_psram_off + a_last_off) == exp_al);
    }

    /* Restore bottom 30 rows of VRAM and invalidate EWRAM cache */
    if (show_bar) memcpy((void *)(VRAM_FB + 130 * 240), &g_video_chunk_buf[14336], 240 * 30 * 2);
    g_ewram_vid_start = 0xFFFFFFFFu;
    g_ewram_vid_end   = 0;

    if (s0_ok && s1_ok && s2_ok) {
        f_close(&g_file);
        SD_Disable();
        SetPSRampage(0);
        Set_RTC_status(0);
        SetRompage(0x200);

        const volatile AgvHeaderFixed *lin_hdr = (const volatile AgvHeaderFixed *)(0x08000000u + e->hdr_offset);
        if (lin_hdr->magic == 0x31564741u &&
            lin_hdr->total_frames == e->total_frames &&
            *(const volatile uint32_t *)(0x08000000u + g_chap_vid_psram_off) == exp_vf &&
            *(const volatile uint32_t *)(0x08000000u + g_chap_aud_psram_off) == exp_af) {
            g_linear_psram_mode  = 3;
            g_linear_psram_ptr   = (const uint8_t *)0x08000000u;
            g_chap_loaded_hash   = e->file_hash;
            g_loaded_psram_hash  = 0;
            g_chap_exp_vid_first = exp_vf;
            g_chap_exp_aud_first = exp_af;
            return 1;
        }

        SetRompage(0x8002);
        SetPSRampage(0);
        g_linear_psram_mode  = 4;
        g_chap_loaded_hash   = e->file_hash;
        g_loaded_psram_hash  = 0;
        g_chap_exp_vid_first = exp_vf;
        g_chap_exp_aud_first = exp_af;
        return 1;
    }

    SetRompage(0x8002);
    f_lseek(&g_file, 0);
    SD_Disable();
    g_linear_psram_mode = 0;
    return 0;
}

static uint32_t get_cached_frame_offset(const SdVideoEntry *e, uint32_t hdr_off, uint32_t total_frames, uint32_t frame_idx) {
    if (frame_idx >= total_frames) frame_idx = total_frames - 1;
    if (e->is_rom_demo) {
        return *(const uint32_t *)(0x08010000u + 40u + frame_idx * 4u);
    }
    if (g_linear_psram_mode == 1 || g_linear_psram_mode == 3) {
        return *(const uint32_t *)(g_linear_psram_ptr + hdr_off + 40u + frame_idx * 4u);
    }
    if (g_linear_psram_mode == 2 || g_linear_psram_mode == 4) {
        uint32_t val = 0;
        read_from_banked_psram_32m(hdr_off + 40u + frame_idx * 4u, &val, 4);
        return val;
    }
    if (g_idx_cache_base == 0xFFFFFFFF || frame_idx < g_idx_cache_base || frame_idx >= g_idx_cache_base + IDX_CACHE_SIZE) {
        uint32_t new_base = frame_idx & ~511u;
        uint32_t count = total_frames - new_base;
        if (count > IDX_CACHE_SIZE) count = IDX_CACHE_SIZE;
        uint32_t byte_off = (e->is_rom_demo ? 0 : hdr_off) + 40 + (new_base * 4);
        raw_stream_read_at(e, byte_off, g_frame_idx_cache, count * 4);
        g_idx_cache_base = new_base;
    }
    return g_frame_idx_cache[frame_idx - g_idx_cache_base];
}

/* Read compressed video frame from Linear 32MB PSRAM (0-noise), Chapter PSRAM, Banked PSRAM, EWRAM 80KB Cache, or Direct SD */
static int read_video_frame_cached(const SdVideoEntry *e, uint32_t f_start, void *dst, uint32_t f_len,
                                   uint32_t audio_file_base, uint32_t cur_aud_off, uint32_t total_audio_bytes) {
    (void)cur_aud_off; (void)total_audio_bytes;
    if (e->is_rom_demo) {
        memcpy(dst, (const void *)(0x08010000u + f_start), f_len);
        return 0;
    }
    if (g_linear_psram_mode == 1) {
        memcpy(dst, (const void *)(g_linear_psram_ptr + f_start), f_len);
        return 0;
    }
    if (g_linear_psram_mode == 2) {
        read_from_banked_psram_32m(f_start, dst, f_len);
        return 0;
    }
    if (g_linear_psram_mode == 3 && f_start >= g_chap_vid_base && (f_start + f_len) <= g_chap_vid_end) {
        memcpy(dst, (const void *)(g_linear_psram_ptr + g_chap_vid_psram_off + (f_start - g_chap_vid_base)), f_len);
        return 0;
    }
    if (g_linear_psram_mode == 4 && f_start >= g_chap_vid_base && (f_start + f_len) <= g_chap_vid_end) {
        read_from_banked_psram_32m(g_chap_vid_psram_off + (f_start - g_chap_vid_base), dst, f_len);
        return 0;
    }

    /* Mode 2: 80 KB EWRAM Video Burst Cache */
    if (g_buf_mode == BUF_MODE_EWRAM_96K) {
        if (g_ewram_vid_start == 0xFFFFFFFFu || f_start < g_ewram_vid_start || (f_start + f_len) > g_ewram_vid_end) {
            uint32_t chunk_base = f_start & ~511u;
            uint32_t avail = (audio_file_base > chunk_base) ? (audio_file_base - chunk_base) : EWRAM_VID_CACHE_SIZE;
            if (avail > EWRAM_VID_CACHE_SIZE) avail = EWRAM_VID_CACHE_SIZE;
            if (avail < f_len + 512u) avail = EWRAM_VID_CACHE_SIZE;
            if (raw_stream_read_at(e, chunk_base, g_video_chunk_buf, avail) == 0) {
                g_ewram_vid_start = chunk_base;
                g_ewram_vid_end   = chunk_base + avail;
            } else {
                return raw_stream_read_at(e, f_start, dst, f_len);
            }
        }
        memcpy(dst, &g_video_chunk_buf[f_start - g_ewram_vid_start], f_len);
        return 0;
    }

    /* Direct SD Stream */
    return raw_stream_read_at(e, f_start, dst, f_len);
}

static void read_audio_bytes_cached(const SdVideoEntry *e, uint32_t audio_file_base, uint32_t stream_pos, void *dst, uint32_t len) {
    if (e->is_rom_demo) {
        memcpy(dst, (const void *)(0x08010000u + audio_file_base + stream_pos), len);
        return;
    }
    if (g_linear_psram_mode == 1) {
        memcpy(dst, (const void *)(g_linear_psram_ptr + audio_file_base + stream_pos), len);
        return;
    }
    if (g_linear_psram_mode == 2) {
        read_from_banked_psram_32m(audio_file_base + stream_pos, dst, len);
        return;
    }
    if (g_linear_psram_mode == 3) {
        uint32_t abs_off = audio_file_base + stream_pos;
        if (abs_off >= g_chap_aud_base && (abs_off + len) <= g_chap_aud_end) {
            memcpy(dst, (const void *)(g_linear_psram_ptr + g_chap_aud_psram_off + (abs_off - g_chap_aud_base)), len);
            return;
        }
    }
    if (g_linear_psram_mode == 4) {
        uint32_t abs_off = audio_file_base + stream_pos;
        if (abs_off >= g_chap_aud_base && (abs_off + len) <= g_chap_aud_end) {
            read_from_banked_psram_32m(g_chap_aud_psram_off + (abs_off - g_chap_aud_base), dst, len);
            return;
        }
    }
    raw_stream_read_at(e, audio_file_base + stream_pos, dst, len);
}

static void close_video_entry_stream(const SdVideoEntry *e) {
    REG_DMA1CNT = 0;
    REG_TM0CNT_H = 0;
    REG_TM1CNT_H = 0;
    if (g_linear_psram_mode != 0) {
        g_linear_psram_mode = 0;
        if (!g_use_rom_vfat) {
            SetRompage(0x8002);
            SetPSRampage(0);
        }
        SD_Disable();
    } else {
        if (!e->is_rom_demo) f_close(&g_file);
        if (!g_use_rom_vfat) {
            SetRompage(0x8002);
        }
        SD_Disable();
    }
}

/* Fill a chunk of the circular 64KB audio ring buffer (and its 8KB mirror zone)
 * IMPORTANT: ring_off MUST be derived from ring_write_pos (0 at start_ring_audio),
 * NOT stream_pos (which includes aligned_off after a seek/unpause)!
 */
static void fill_audio_ring_chunk(const SdVideoEntry *e, uint32_t audio_file_base, uint32_t total_audio_bytes, uint32_t ring_write_pos, uint32_t stream_pos, uint32_t chunk_len) {
    uint32_t ring_off = ring_write_pos & (AUDIO_RING_PERIOD - 1);
    while (chunk_len > 0) {
        uint32_t step = AUDIO_RING_PERIOD - ring_off;
        if (step > chunk_len) step = chunk_len;

        if (stream_pos < total_audio_bytes) {
            uint32_t avail = total_audio_bytes - stream_pos;
            uint32_t to_read = (step <= avail) ? step : avail;
            read_audio_bytes_cached(e, audio_file_base, stream_pos, &g_audio_ring[ring_off], to_read);
            if (to_read < step) {
                memset(&g_audio_ring[ring_off + to_read], 0, step - to_read);
            }
        } else {
            memset(&g_audio_ring[ring_off], 0, step);
        }

        /* Mirror [0 .. AUDIO_MIRROR_SIZE - 1] into [AUDIO_RING_PERIOD .. AUDIO_RING_PERIOD + AUDIO_MIRROR_SIZE - 1] */
        if (ring_off < AUDIO_MIRROR_SIZE) {
            uint32_t mlen = AUDIO_MIRROR_SIZE - ring_off;
            if (mlen > step) mlen = step;
            memcpy(&g_audio_ring[AUDIO_RING_PERIOD + ring_off], &g_audio_ring[ring_off], mlen);
        }

        ring_off = (ring_off + step) & (AUDIO_RING_PERIOD - 1);
        stream_pos += step;
        chunk_len -= step;
    }
}

static uint32_t start_ring_audio(const SdVideoEntry *e, uint32_t audio_file_base, uint32_t total_audio_bytes,
                                 uint32_t frame, uint32_t audio_rate, uint32_t fps, uint16_t tm0_reload,
                                 uint32_t *out_stream_start, uint32_t *out_write_head, uint32_t *out_dma_base) {
    REG_DMA1CNT = 0;
    REG_TM0CNT_H = 0;
    REG_TM1CNT_H = 0;
    REG_SOUNDCNT_X = 0x0000;
    __asm__ volatile("nop; nop; nop; nop");

    uint32_t sample_off = (uint32_t)(((uint64_t)frame * audio_rate) / fps);
    uint32_t aligned_off = sample_off & ~15u;

    *out_stream_start = aligned_off;
    *out_write_head = 0;
    *out_dma_base = 0;

    /* Pre-fill 48 KB (~4.6 seconds) of audio into the 64 KB ring buffer starting at g_audio_ring[0] (ring_write_pos = 0) */
    fill_audio_ring_chunk(e, audio_file_base, total_audio_bytes, 0, aligned_off, 49152);
    *out_write_head = 49152;

    REG_SOUNDCNT_X = 0x0080;
    REG_SOUNDCNT_L = 0;
    REG_SOUNDCNT_H = 0x0B0E; /* DirectSound A 100%, L+R, Timer 0, FIFO reset */
    REG_DMA1SAD = (uint32_t)&g_audio_ring[0];
    REG_DMA1DAD = 0x040000A0;
    REG_DMA1CNT = 0xB6400004;

    REG_TM1CNT_L = 0;
    REG_TM1CNT_H = 0x0084;   /* Timer 1 Cascade: counts exact audio samples played */
    REG_TM0CNT_L = tm0_reload;
    REG_TM0CNT_H = 0x0080;   /* Start Timer 0 sample clock */
    return aligned_off;
}

/* Pick next playable video in the current directory according to g_auto_chain (or force_random).
 * In CHAIN_RANDOM mode, prefers unwatched (!BOOKMARK_PLAYED) videos in the current directory first;
 * once all videos in the folder are marked PLAYED, picks any other video (i != cur_idx) at random. */
static int pick_next_video_in_dir(int cur_idx, int force_random) {
    int mode = force_random ? CHAIN_RANDOM : g_auto_chain;
    if (mode == CHAIN_OFF) return -1;
    if (mode == CHAIN_NEXT) {
        if ((cur_idx + 1) < g_entry_count && !g_entries[cur_idx + 1].is_dir) {
            return cur_idx + 1;
        }
        return -1;
    }

    static uint16_t unwatched[MAX_VIDEOS];
    static uint16_t others[MAX_VIDEOS];
    static uint16_t all_vids[MAX_VIDEOS];
    int n_unwatched = 0;
    int n_others = 0;
    int n_all = 0;

    if (cur_idx >= 0 && cur_idx < MAX_VIDEOS) g_shuffle_visited[cur_idx] = 1;
    for (int i = 0; i < g_entry_count; i++) {
        if (g_entries[i].is_dir || g_entries[i].probed == 2) continue;
        all_vids[n_all++] = (uint16_t)i;
        if (i != cur_idx) {
            others[n_others++] = (uint16_t)i;
            if (!g_shuffle_visited[i] && load_sd_bookmark_for_entry(i) != BOOKMARK_PLAYED) {
                unwatched[n_unwatched++] = (uint16_t)i;
            }
        }
    }
    if (n_unwatched == 0) {
        for (int i = 0; i < g_entry_count; i++) {
            if (g_entries[i].is_dir || g_entries[i].probed == 2 || i == cur_idx) continue;
            if (!g_shuffle_visited[i]) unwatched[n_unwatched++] = (uint16_t)i;
        }
    }
    if (n_unwatched == 0 && n_others > 0) {
        for (int i = 0; i < MAX_VIDEOS; i++) g_shuffle_visited[i] = 0;
        if (cur_idx >= 0 && cur_idx < MAX_VIDEOS) g_shuffle_visited[cur_idx] = 1;
        for (int i = 0; i < n_others; i++) unwatched[n_unwatched++] = others[i];
    }

    uint32_t r = step_rng((uint32_t)(cur_idx + 1) * 0x45D9F3Bu);
    begin_sram_access();
    sram_write_u32(172, g_rng_state);
    end_sram_access();

    if (n_unwatched > 0) {
        int chosen = (int)unwatched[r % (uint32_t)n_unwatched];
        if (chosen >= 0 && chosen < MAX_VIDEOS) g_shuffle_visited[chosen] = 1;
        return chosen;
    }
    if (n_others > 0) {
        int chosen = (int)others[r % (uint32_t)n_others];
        if (chosen >= 0 && chosen < MAX_VIDEOS) g_shuffle_visited[chosen] = 1;
        return chosen;
    }
    if (n_all > 0 && force_random) {
        return (int)all_vids[r % (uint32_t)n_all];
    }
    return -1;
}

/* Manual DOWN button during playback: if CHAIN_RANDOM, pick a random video in dir;
 * otherwise advance to the next playable video in the current folder (wrapping to first video if at end). */
static int pick_manual_next_video_in_dir(int cur_idx) {
    if (g_auto_chain == CHAIN_RANDOM) {
        return pick_next_video_in_dir(cur_idx, 1);
    }
    for (int step = 1; step <= g_entry_count; step++) {
        int idx = (cur_idx + step) % g_entry_count;
        if (!g_entries[idx].is_dir) return idx;
    }
    return -1;
}

/* Manual UP button during playback: jump to the previous playable video in the current folder
 * (wrapping around to the last video in the folder if at the first video). */
static int pick_prev_video_in_dir(int cur_idx) {
    for (int step = 1; step <= g_entry_count; step++) {
        int idx = (cur_idx - step + g_entry_count) % g_entry_count;
        if (!g_entries[idx].is_dir) return idx;
    }
    return -1;
}

static int clear_dir_played_marks(void) {
    int cleared = 0;
    for (int i = 0; i < g_entry_count; i++) {
        if (!g_entries[i].is_dir && load_sd_bookmark_for_entry(i) == BOOKMARK_PLAYED) {
            save_sd_bookmark(i, 0);
            cleared++;
        }
    }
    return cleared;
}

static int run_settings_modal(int cur_sel_idx, uint16_t *io_prev_keys);

static void draw_playback_hud(const SdVideoEntry *e, int entry_idx, uint32_t cur_frame, uint32_t total_frames, uint32_t fps) {
    fill_rect(0, 148, 240, 12, RGB15(2, 2, 3));
    uint32_t bar_w = (total_frames > 1) ? ((cur_frame * 236) / (total_frames - 1)) : 236;
    if (bar_w > 236) bar_w = 236;
    fill_rect(2, 149, 236, 2, RGB15(7, 7, 9));
    fill_rect(2, 149, (int)bar_w, 2, RGB15(12, 24, 14));

    char cur_str[10], tot_str[10], line[44];
    format_mmss(cur_str, cur_frame / fps);
    format_mmss(tot_str, total_frames / fps);
    int p = 0;
    for (int i = 0; cur_str[i]; i++) line[p++] = cur_str[i];
    line[p++] = '/';
    for (int i = 0; tot_str[i]; i++) line[p++] = tot_str[i];
    line[p++] = ' ';
    if (g_sd_mounted && g_entry_count > 1) {
        line[p++] = '[';
        char idx_s[8];
        format_u32(idx_s, (uint32_t)(entry_idx + 1));
        for (int i = 0; idx_s[i]; i++) line[p++] = idx_s[i];
        line[p++] = '/';
        format_u32(idx_s, (uint32_t)g_entry_count);
        for (int i = 0; idx_s[i]; i++) line[p++] = idx_s[i];
        line[p++] = ']';
        line[p++] = ' ';
    }
    const char *ename = get_entry_display_name(e);
    for (int i = 0; ename[i] && p < 39; i++) line[p++] = ename[i];
    line[p] = 0;
    draw_str(4, 152, line, RGB15(28, 28, 26), 39);
}

/* Returns: -1 = back to browser, >= 0 = auto-chain to returned entry index */
static int play_video_entry(int entry_idx, uint32_t initial_frame, uint16_t *io_prev_keys) {
    const SdVideoEntry *e = &g_entries[entry_idx];
    g_linear_psram_mode = 0;
    REG_DMA1CNT = 0;
    REG_TM0CNT_H = 0;
    REG_TM1CNT_H = 0;

    if (!e->is_rom_demo) {
        if (!g_use_rom_vfat) SetRompage(0x8002);
        if (f_open(&g_file, e->path, FA_READ) != FR_OK) {
            SD_Disable();
            return -1;
        }
        /* Initialize Fast-Seek Cluster Link Map Table (CLMT) for O(1) cluster seeks */
        g_clmt[0] = 1024;
        g_file.cltbl = g_clmt;
        if (f_lseek(&g_file, CREATE_LINKMAP) != FR_OK) {
            g_file.cltbl = NULL;
        }
    }

    /* If PSRAM 0-NOISE mode is active and file <= 32 MiB, preload entire file into 32 MiB PSRAM
     * while audio is muted, then call f_close(&g_file) + SD_Disable() + SetRompage(0x200)! */
    if (load_entry_to_linear_psram(e) < 0) {
        return -1;
    }

    AgvHeaderFixed hdr;
    uint32_t hdr_read_off = e->is_rom_demo ? 0 : e->hdr_offset;
    if (raw_stream_read_at(e, hdr_read_off, &hdr, sizeof(AgvHeaderFixed)) != 0 || hdr.magic != 0x31564741) {
        close_video_entry_stream(e);
        return -1;
    }

    g_idx_cache_base  = 0xFFFFFFFFu;
    g_ewram_vid_start = 0xFFFFFFFFu;
    g_ewram_vid_end   = 0;
    g_psram_vid_start = 0xFFFFFFFFu;
    g_psram_vid_end   = 0;
    g_psram_aud_start = 0xFFFFFFFFu;
    g_psram_aud_end   = 0;
    g_psram_idx_valid = 0;

    uint32_t total_frames = hdr.total_frames ? hdr.total_frames : 1;
    uint32_t vpf = hdr.vblanks_per_frame ? hdr.vblanks_per_frame : 3;
    uint32_t audio_rate = hdr.audio_rate ? hdr.audio_rate : 10512;
    uint32_t kf_int = hdr.keyframe_interval ? hdr.keyframe_interval : 20;
    uint32_t seek15 = hdr.seek_15s_frames ? hdr.seek_15s_frames : 300;
    uint32_t seek30 = seek15 * (uint32_t)g_lr_jump_mults[(g_lr_jump_idx >= 0 && g_lr_jump_idx <= 6) ? g_lr_jump_idx : 1];
    uint32_t fps = (seek15 >= 75) ? (seek15 / 15) : (60 / vpf);
    if (fps == 0) fps = 20;
    uint16_t tm0_reload = (uint16_t)(hdr.timer0_reload ? hdr.timer0_reload : 0xF9C4);

    /* Determine whether frame/audio offsets in header are relative to 0 or hdr_offset */
    uint32_t first_raw = get_cached_frame_offset(e, e->hdr_offset, total_frames, 0) & 0x7FFFFFFF;
    uint32_t expected_rel_first = ((40u + total_frames * 4u) + 15u) & ~15u;
    uint32_t offset_base = 0;
    if (!e->is_rom_demo && e->hdr_offset > 0 && first_raw <= expected_rel_first + 32u) {
        offset_base = e->hdr_offset;
    } else if (e->is_rom_demo && first_raw > expected_rel_first + 32u) {
        offset_base = (uint32_t)(-(int32_t)(first_raw - expected_rel_first));
    }

    uint32_t audio_file_base = offset_base + hdr.audio_offset;
    uint32_t total_audio_bytes = (uint32_t)(((uint64_t)total_frames * audio_rate) / fps) + 4096;

    REG_SOUNDCNT_X = 0x0080;
    REG_SOUNDCNT_L = 0;
    REG_SOUNDBIAS = (uint16_t)((REG_SOUNDBIAS & 0x3FFFu) | 0x4000u); /* 8-bit / 65.536 kHz PWM (matches Meteo 1.3.1) */

    uint32_t cur_frame = (initial_frame < total_frames) ? ((initial_frame / kf_int) * kf_int) : 0;
    uint32_t audio_stream_start = 0;
    uint32_t audio_write_head = 0;
    uint32_t audio_dma_base = 0;

    /* For > 32 MiB .AGV files in PSRAM 0-NOISE mode, preload the first ~6-minute 32 MiB chapter! */
    if (!e->is_rom_demo && !g_use_rom_vfat && g_has_psram &&
        g_buf_mode == BUF_MODE_PSRAM_32M && g_linear_psram_mode == 0 &&
        e->file_size > 0x02000000u) {
        if (load_psram_chapter_for_frame(e, cur_frame, offset_base, audio_file_base, total_frames, kf_int, audio_rate, fps, 0) < 0) {
            close_video_entry_stream(e);
            return -1;
        }
    }

    while ((~REG_KEYINPUT) & (KEY_UP | KEY_DOWN)) {
        wait_vblank();
    }
    *io_prev_keys = ~REG_KEYINPUT & 0x03FF;
    wait_vblank();
    uint32_t samples_played = start_ring_audio(
        e, audio_file_base, total_audio_bytes,
        cur_frame, audio_rate, fps, tm0_reload,
        &audio_stream_start, &audio_write_head, &audio_dma_base
    );
    uint16_t prev_tm1 = REG_TM1CNT_L;
    uint16_t newly_pressed = 0;
    int paused = 0;

    while (1) {
        /* If playing a > 32 MiB .AGV in 32 MiB PSRAM Chapter Mode and cur_frame reached the end of the chapter,
         * seamlessly load the next 32 MiB PSRAM chapter while audio is muted, then call SD_Disable()! */
        if ((g_linear_psram_mode == 3 || g_linear_psram_mode == 4) &&
            (cur_frame < g_chap_start_frame || cur_frame >= g_chap_end_frame)) {
            if (load_psram_chapter_for_frame(e, cur_frame, offset_base, audio_file_base, total_frames, kf_int, audio_rate, fps, 1) < 0) {
                close_video_entry_stream(e);
                return -1;
            }
            wait_vblank();
            samples_played = start_ring_audio(
                e, audio_file_base, total_audio_bytes,
                cur_frame, audio_rate, fps, tm0_reload,
                &audio_stream_start, &audio_write_head, &audio_dma_base
            );
            prev_tm1 = REG_TM1CNT_L;
        }

        /* 1. Fetch current compressed video frame from Linear PSRAM (<=32MB or Chapter Mode) or Cache */
        uint32_t raw_off = get_cached_frame_offset(e, e->hdr_offset, total_frames, cur_frame);
        int is_kf = (raw_off & 0x80000000) ? 1 : 0;
        uint32_t f_start = offset_base + (raw_off & 0x7FFFFFFF);
        uint32_t f_end;
        if (cur_frame + 1 < total_frames) {
            uint32_t next_raw = get_cached_frame_offset(e, e->hdr_offset, total_frames, cur_frame + 1);
            f_end = offset_base + (next_raw & 0x7FFFFFFF);
        } else {
            f_end = audio_file_base;
        }
        uint32_t f_len = (f_end > f_start) ? (f_end - f_start) : 8192;
        if (f_len < 600) f_len = 600;
        if (f_len > sizeof(g_frame_buf)) f_len = sizeof(g_frame_buf);

        const uint8_t *frame_decode_ptr = g_frame_buf;
        if (e->is_rom_demo) {
            frame_decode_ptr = (const uint8_t *)(0x08010000u + f_start);
        } else if (g_linear_psram_mode == 1) {
            frame_decode_ptr = g_linear_psram_ptr + f_start;
        } else if (g_linear_psram_mode == 3 && f_start >= g_chap_vid_base && (f_start + f_len) <= g_chap_vid_end) {
            frame_decode_ptr = g_linear_psram_ptr + g_chap_vid_psram_off + (f_start - g_chap_vid_base);
        } else {
            read_video_frame_cached(e, f_start, g_frame_buf, f_len, audio_file_base, audio_stream_start + audio_write_head, total_audio_bytes);
        }

        /* 2. Refill 64KB circular audio ring buffer in large 32KB bursts (instead of every frame!) */
        uint16_t now_tm1 = REG_TM1CNT_L;
        samples_played += (uint16_t)(now_tm1 - prev_tm1);
        prev_tm1 = now_tm1;

        uint32_t samples_since_start = samples_played - audio_stream_start;
        if (g_buf_mode == BUF_MODE_DIRECT_SD) {
            if (audio_write_head - samples_since_start < 24576) {
                fill_audio_ring_chunk(e, audio_file_base, total_audio_bytes, audio_write_head, audio_stream_start + audio_write_head, 16384);
                audio_write_head += 16384;
            }
        } else if (audio_write_head - samples_since_start < 16384) {
            fill_audio_ring_chunk(e, audio_file_base, total_audio_bytes, audio_write_head, audio_stream_start + audio_write_head, 32768);
            audio_write_head += 32768;
        }

        /* Seamless DMA1 wrap inside the 8KB mirror zone [65536 .. 73727] */
        if (samples_since_start - audio_dma_base >= AUDIO_RING_PERIOD + 128) {
            now_tm1 = REG_TM1CNT_L;
            samples_played += (uint16_t)(now_tm1 - prev_tm1);
            prev_tm1 = now_tm1;
            samples_since_start = samples_played - audio_stream_start;
            uint32_t ring_pos = ((samples_since_start + 16) & ~15u) - audio_dma_base;
            uint32_t wrapped_off = ring_pos & (AUDIO_RING_PERIOD - 1u);
            REG_TM0CNT_H = 0;
            REG_DMA1CNT = 0;
            REG_SOUNDCNT_H = 0x0B0E;
            REG_DMA1SAD = (uint32_t)&g_audio_ring[wrapped_off];
            REG_DMA1DAD = 0x040000A0;
            REG_DMA1CNT = 0xB6400004;
            REG_TM0CNT_H = 0x0080;
            audio_dma_base = samples_since_start - wrapped_off;
        }

        /* 3. Wait until hardware audio clock reaches current frame display time */
        uint32_t next_frame_sample = (uint32_t)(((uint64_t)(cur_frame + 1) * audio_rate) / fps);
        do {
            wait_vblank();

            uint16_t cur_tm1 = REG_TM1CNT_L;
            samples_played += (uint16_t)(cur_tm1 - prev_tm1);
            prev_tm1 = cur_tm1;

            uint16_t keys = ~REG_KEYINPUT & 0x03FF;
            newly_pressed = keys & ~(*io_prev_keys);
            *io_prev_keys = keys;

            if (newly_pressed & KEY_SELECT) {
                g_show_hud = !g_show_hud;
            }

            /* DOWN (or SELECT + R) jumps immediately to Next (or Random) video in directory (SD mode only)! */
            if (g_sd_mounted && g_entry_count > 1 && ((newly_pressed & KEY_DOWN) || ((keys & KEY_SELECT) && (newly_pressed & KEY_R)))) {
                close_video_entry_stream(e);
                if (cur_frame > 0 && (cur_frame + 5u) < total_frames) save_sd_bookmark(entry_idx, cur_frame);
                return pick_manual_next_video_in_dir(entry_idx);
            }
            /* UP (or SELECT + L) jumps immediately to Previous video in directory (SD mode only)! */
            if (g_sd_mounted && g_entry_count > 1 && ((newly_pressed & KEY_UP) || ((keys & KEY_SELECT) && (newly_pressed & KEY_L)))) {
                close_video_entry_stream(e);
                if (cur_frame > 0 && (cur_frame + 5u) < total_frames) save_sd_bookmark(entry_idx, cur_frame);
                return pick_prev_video_in_dir(entry_idx);
            }

            if (newly_pressed & (KEY_START | KEY_A)) {
                g_ram_bookmarks[entry_idx] = cur_frame;
                goto enter_pause;
            }
            if (newly_pressed & KEY_B) {
                close_video_entry_stream(e);
                save_sd_bookmark(entry_idx, cur_frame);
                return -1;
            }
            if (newly_pressed & (KEY_RIGHT | KEY_LEFT | KEY_R | KEY_L)) {
                goto handle_seek;
            }
        } while (samples_played < next_frame_sample);

        /* 4. Decode pre-fetched frame from RAM into 0-waitstate VRAM right at VBlank */
        decode_agv_frame(frame_decode_ptr, is_kf);
        if (g_show_hud) {
            draw_playback_hud(e, entry_idx, cur_frame, total_frames, fps);
        }

        if (is_kf && cur_frame > 0) {
            g_ram_bookmarks[entry_idx] = cur_frame;
        }

        cur_frame++;
        if (cur_frame >= total_frames) {
            g_ram_bookmarks[entry_idx] = BOOKMARK_PLAYED;
            if (!g_sd_mounted) {
                if (g_auto_chain != CHAIN_OFF) {
                    cur_frame = 0;
                    g_ram_bookmarks[entry_idx] = 0;
                    samples_played = start_ring_audio(
                        e, audio_file_base, total_audio_bytes,
                        cur_frame, audio_rate, fps, tm0_reload,
                        &audio_stream_start, &audio_write_head, &audio_dma_base
                    );
                    prev_tm1 = REG_TM1CNT_L;
                    goto next_frame_immediate;
                }
                cur_frame = total_frames - 1;
                goto enter_pause;
            }
            close_video_entry_stream(e);
            save_sd_bookmark(entry_idx, BOOKMARK_PLAYED);
            int next_auto = pick_next_video_in_dir(entry_idx, 0);
            if (next_auto >= 0) {
                return next_auto;
            }
            return -1;
        }
        goto next_frame_immediate;

enter_pause:
        paused = 1;
        REG_DMA1CNT = 0;
        REG_TM0CNT_H = 0;
        REG_TM1CNT_H = 0;
        SD_Disable();
        /* Save pause box (y=64..93, 14,400 bytes) & HUD rows (y=130..159, 14,400 bytes) into 30KB g_video_chunk_buf */
        g_ewram_vid_start = 0xFFFFFFFFu;
        g_ewram_vid_end   = 0;
        memcpy(&g_video_chunk_buf[0], (const void *)(VRAM_FB + 64 * 240), 240 * 30 * 2);
        memcpy(&g_video_chunk_buf[14400], (const void *)(VRAM_FB + 130 * 240), 240 * 30 * 2);
        draw_playback_hud(e, entry_idx, cur_frame, total_frames, fps);
        fill_rect(64, 66, 112, 26, RGB15(3, 3, 4));
        draw_str(74, 71, "PAUSED (A:PLAY)", RGB15(30, 30, 28), 16);
        draw_str(70, 81, g_sd_mounted ? "B:SD MENU SEL:SET" : "B:INFO  SEL:SET", RGB15(18, 28, 18), 17);

        while (paused) {
            wait_vblank();
            uint16_t pk = ~REG_KEYINPUT & 0x03FF;
            uint16_t pnew = pk & ~(*io_prev_keys);
            *io_prev_keys = pk;
            if (pnew & KEY_B) {
                close_video_entry_stream(e);
                save_sd_bookmark(entry_idx, (cur_frame >= total_frames - 1) ? BOOKMARK_PLAYED : cur_frame);
                return -1;
            }
            if (pnew & KEY_SELECT) {
                run_settings_modal(entry_idx, io_prev_keys);
                seek30 = seek15 * (uint32_t)g_lr_jump_mults[(g_lr_jump_idx >= 0 && g_lr_jump_idx <= 6) ? g_lr_jump_idx : 1];
                wait_vblank();
                decode_agv_frame(frame_decode_ptr, is_kf);
                memcpy(&g_video_chunk_buf[0], (const void *)(VRAM_FB + 64 * 240), 240 * 30 * 2);
                memcpy(&g_video_chunk_buf[14400], (const void *)(VRAM_FB + 130 * 240), 240 * 30 * 2);
                draw_playback_hud(e, entry_idx, cur_frame, total_frames, fps);
                fill_rect(64, 66, 112, 26, RGB15(3, 3, 4));
                draw_str(74, 71, "PAUSED (A:PLAY)", RGB15(30, 30, 28), 16);
                draw_str(70, 81, g_sd_mounted ? "B:SD MENU SEL:SET" : "B:INFO  SEL:SET", RGB15(18, 28, 18), 17);
                continue;
            }
            if (g_sd_mounted && g_entry_count > 1 && (pnew & KEY_DOWN)) {
                close_video_entry_stream(e);
                save_sd_bookmark(entry_idx, (cur_frame >= total_frames - 1) ? BOOKMARK_PLAYED : cur_frame);
                return pick_manual_next_video_in_dir(entry_idx);
            }
            if (g_sd_mounted && g_entry_count > 1 && (pnew & KEY_UP)) {
                close_video_entry_stream(e);
                save_sd_bookmark(entry_idx, (cur_frame >= total_frames - 1) ? BOOKMARK_PLAYED : cur_frame);
                return pick_prev_video_in_dir(entry_idx);
            }
            if (pnew & (KEY_START | KEY_A)) {
                paused = 0;
                if (cur_frame >= total_frames - 1) {
                    cur_frame = 0;
                } else {
                    /* Restore exact paused P-frame/keyframe pixels to VRAM so we resume on cur_frame with zero jump! */
                    wait_vblank();
                    memcpy((void *)(VRAM_FB + 64 * 240), &g_video_chunk_buf[0], 240 * 30 * 2);
                    memcpy((void *)(VRAM_FB + 130 * 240), &g_video_chunk_buf[14400], 240 * 30 * 2);
                    if (g_show_hud) {
                        draw_playback_hud(e, entry_idx, cur_frame, total_frames, fps);
                    }
                }
                samples_played = start_ring_audio(
                    e, audio_file_base, total_audio_bytes,
                    cur_frame, audio_rate, fps, tm0_reload,
                    &audio_stream_start, &audio_write_head, &audio_dma_base
                );
                prev_tm1 = REG_TM1CNT_L;
                goto next_frame_immediate;
            }
            if (pnew & (KEY_RIGHT | KEY_LEFT | KEY_R | KEY_L)) {
                newly_pressed = pnew;
                paused = 0;
                goto handle_seek;
            }
        }

handle_seek:
        {
            REG_DMA1CNT = 0; REG_TM0CNT_H = 0; REG_TM1CNT_H = 0;
            int32_t target = (int32_t)cur_frame;
            if (newly_pressed & KEY_RIGHT) target += (int32_t)seek15;
            else if (newly_pressed & KEY_R) target += (int32_t)seek30;
            else if (newly_pressed & KEY_LEFT) target -= (int32_t)seek15;
            else if (newly_pressed & KEY_L) target -= (int32_t)seek30;

            if (target < 0) target = 0;
            if ((uint32_t)target >= total_frames - 1) {
                g_ram_bookmarks[entry_idx] = BOOKMARK_PLAYED;
                if (g_sd_mounted && g_auto_chain != CHAIN_OFF) {
                    close_video_entry_stream(e);
                    save_sd_bookmark(entry_idx, BOOKMARK_PLAYED);
                    int next_auto = pick_next_video_in_dir(entry_idx, 0);
                    if (next_auto >= 0) {
                        return next_auto;
                    }
                    return -1;
                }
                cur_frame = ((total_frames - 1) / kf_int) * kf_int;
                if ((g_linear_psram_mode == 3 || g_linear_psram_mode == 4) &&
                    (cur_frame < g_chap_start_frame || cur_frame >= g_chap_end_frame)) {
                    load_psram_chapter_for_frame(e, cur_frame, offset_base, audio_file_base, total_frames, kf_int, audio_rate, fps, 1);
                }
                goto enter_pause;
            }
            cur_frame = ((uint32_t)target / kf_int) * kf_int;
            g_ram_bookmarks[entry_idx] = cur_frame;
            g_ewram_vid_start = 0xFFFFFFFFu;
            g_ewram_vid_end   = 0;
            if ((g_linear_psram_mode == 3 || g_linear_psram_mode == 4) &&
                (cur_frame < g_chap_start_frame || cur_frame >= g_chap_end_frame)) {
                if (load_psram_chapter_for_frame(e, cur_frame, offset_base, audio_file_base, total_frames, kf_int, audio_rate, fps, 1) < 0) {
                    close_video_entry_stream(e);
                    return -1;
                }
            }
            wait_vblank();
            samples_played = start_ring_audio(
                e, audio_file_base, total_audio_bytes,
                cur_frame, audio_rate, fps, tm0_reload,
                &audio_stream_start, &audio_write_head, &audio_dma_base
            );
            prev_tm1 = REG_TM1CNT_L;
            goto next_frame_immediate;
        }

next_frame_immediate:;
    }
}

/* Live-patch an unpatched or patched Meteo 1.3.1 / 1.4.0 .GBA ROM in 32 MiB PSRAM and launch it! */
static void restore_player_stub_to_top_psram(void) {
    if (g_use_rom_vfat || !g_has_psram) return;
    uint32_t hdr_len   = (uint32_t)((uintptr_t)__iwram_lma - 0x08000000u);
    uint32_t iwram_off = hdr_len;
    uint32_t iwram_len = (uint32_t)(__iwram_end - __iwram_start);
    uint32_t ewram_off = (uint32_t)((uintptr_t)__ewram_code_lma - 0x08000000u);
    uint32_t ewram_len = (uint32_t)(__ewram_code_end - __ewram_code_start);
    if (hdr_len > sizeof(g_boot_hdr_backup) || (ewram_off + ewram_len) > 65536u) return;

    SD_Disable();
    SetRompage(0x8002);
    psram_write_window(0x3000u, 0x007F0000u, g_boot_hdr_backup, hdr_len);
    psram_write_window(0x3000u, 0x007F0000u + iwram_off, __iwram_start, iwram_len);
    psram_write_window(0x3000u, 0x007F0000u + ewram_off, __ewram_code_start, ewram_len);
    SetPSRampage(0);
}

static __attribute__((section(".iwram"), noinline, noreturn))
void boot_patched_meteo_psram_rom(void) {
    /* Wait until menu launch buttons (A / B / START / SELECT) are released so release-edge doesn't fire inside Meteo */
    while ((~REG_KEYINPUT) & (KEY_A | KEY_B | KEY_START | KEY_SELECT | KEY_UP | KEY_DOWN)) {}
    REG_DMA1CNT = 0;
    REG_DMA3CNT = 0;
    REG_TM0CNT_H = 0;
    REG_TM1CNT_H = 0;
    REG_SOUNDCNT_X = 0;
    *(volatile uint32_t *)0x04000208u = 0; /* REG_IME = 0 */
    SetPSRampage(0);
    SetRampage(0);
    Set_RTC_status(0);
    SetRompage(0x200);
    __asm__ volatile(
        "mov r0, #0xFD\n"
        "swi 0x010000\n"
        "ldr r1, =0x04000204\n"
        "ldr r0, =0x4317\n"
        "strh r0, [r1]\n"
        "ldr r1, =0x03007FFA\n"
        "mov r0, #0\n"
        "strb r0, [r1]\n"
        "ldr sp, =0x03007F00\n"
        "swi 0x000000\n"
        ::: "r0", "r1", "memory"
    );
    while (1) {}
}

static int launch_meteo_rom_live_patched(int entry_idx, int force_from_zero) {
    if (entry_idx < 0 || entry_idx >= g_entry_count) return -1;
    const SdVideoEntry *e = &g_entries[entry_idx];
    if (!e->is_meteo) return -1;

    /* Save current folder and check existing per-file bookmark in 48-slot table */
    save_sram_cur_dir();
    uint32_t existing_bmk = load_sd_bookmark_for_entry(entry_idx);
    uint32_t resume_frm = (!force_from_zero && existing_bmk > 0 && existing_bmk != BOOKMARK_PLAYED && (existing_bmk + 5u) < e->total_frames)
                          ? existing_bmk : 0u;
    save_sd_bookmark(entry_idx, existing_bmk);

    /* Populate 0x0E000000..0x0E00000F for Meteo 1.3.1 (offset 12) and Meteo 1.4.0 (offset 4) */
    begin_sram_access();
    if (resume_frm > 0) {
        sram_write_u32_raw(0, ~e->total_frames);
        sram_write_u32_raw(4, resume_frm);
        sram_write_u32_raw(8, 0);
        sram_write_u32_raw(12, resume_frm);
    } else {
        sram_write_u32_raw(0, 0);
        sram_write_u32_raw(4, 0);
        sram_write_u32_raw(8, 0);
        sram_write_u32_raw(12, 0);
    }
    SRAM_BASE[16] = 0;
    sram_write_u32(160, e->file_hash);
    sram_write_u32(164, e->total_frames);
    sram_write_u32(168, (uint32_t)e->is_meteo);
    end_sram_access();

    if (g_use_rom_vfat || !g_has_psram || e->file_size > 0x02000000u) {
        fill_rect(24, 62, 192, 34, RGB15(6, 4, 4));
        draw_str(32, 68, "METEO LIVE-PATCH REQUIRES", RGB15(30, 22, 16), 28);
        draw_str(32, 80, "32MB EZ-FLASH PSRAM CART", RGB15(28, 28, 24), 28);
        for (int w = 0; w < 90; w++) wait_vblank();
        return -1;
    }

    uint32_t hdr_tf_off = (e->is_meteo == 1) ? 0xAAE8u : ((e->is_meteo == 2) ? 0xAD78u : 0x00A0u);
    uint32_t pro_off    = (e->is_meteo == 1) ? 0xA858u : ((e->is_meteo == 2) ? 0xA890u : 0x0000u);
    uint32_t exp_pro0   = (e->is_meteo == 1) ? 0x03000F78u : 0x030011FCu;
    begin_sram_access();
    uint32_t prev_meteo_hash = sram_read_u32(156);
    end_sram_access();

    SetRompage(0x8002);
    SetPSRampage(0);
    SD_Disable();
    SetRompage(0x8002);

    /* Fast path: if this exact Meteo .GBA ROM is ALREADY intact in PSRAM (e.g. returned via B and re-selected), skip SD load! */
    int already_in_psram = (e->is_meteo == 1 && prev_meteo_hash == e->file_hash && e->file_hash != 0 &&
                            read_u32_banked_psram_32m(pro_off) == exp_pro0 &&
                            read_u32_banked_psram_32m(hdr_tf_off) == e->total_frames);

    if (!already_in_psram) {
        if (f_open(&g_file, e->path, FA_READ) != FR_OK) {
            SD_Disable();
            return -1;
        }

        fill_rect(12, 132, 216, 20, RGB15(3, 3, 4));
        draw_str(18, 136, "LOADING & PATCHING METEO...", RGB15(18, 29, 18), 32);
        fill_rect(20, 146, 200, 3, RGB15(7, 7, 9));

        uint32_t load_limit = (e->file_size > 0x01FF0000u) ? 0x01FF0000u : e->file_size;
        uint32_t mid_off    = (load_limit >> 1) & ~3u;
        uint32_t last_off   = (load_limit >= 16u) ? ((load_limit - 4u) & ~3u) : hdr_tf_off;

        exp_pro0          = read_file_u32_at(pro_off);
        uint32_t exp_tf   = read_file_u32_at(hdr_tf_off);
        uint32_t exp_mid  = read_file_u32_at(mid_off);
        uint32_t exp_last = read_file_u32_at(last_off);
        SetRompage(0x8002);
        write_u32_banked_psram_32m(pro_off, 0u);
        write_u32_banked_psram_32m(hdr_tf_off, ~exp_tf);
        write_u32_banked_psram_32m(last_off, ~exp_last);

        /* 1. Try EZ-FLASH Omega DE hardware FPGA SD->PSRAM DMA (exact Check_game_RTS_FAT protocol) */
        int hw_dma_done = 0;
        memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
        g_fat_table_buf[2] = 0xFFFFFFFFu;
        u32 *fat_p = g_fat_table_buf;
        u32 cluster_num = 0;
        u32 lastest_cluster = (g_fs.fs_type == FS_FAT16) ? 0xFFFFu : 0xFFFFFF7u;
        u32 getcluster = g_file.obj.sclust;
        u32 getcluster_old = getcluster;
        int fat_table_ok = (getcluster >= 2);

        if (fat_table_ok) {
            *fat_p++ = 0x00000000u;
            *fat_p++ = ClustToSect(&g_fs, getcluster);
            do {
                getcluster = Get_NextCluster(&g_file.obj, getcluster);
                cluster_num++;
                if (getcluster == 0xFFFFFFFFu || getcluster <= 1u) {
                    fat_table_ok = 0;
                    break;
                }
                if (getcluster != (getcluster_old + 1u)) {
                    if ((fat_p - g_fat_table_buf) >= 120) {
                        fat_table_ok = 0;
                        break;
                    }
                    *fat_p++ = cluster_num * (u32)g_fs.csize;
                    *fat_p++ = ClustToSect(&g_fs, getcluster);
                }
                getcluster_old = getcluster;
            } while (getcluster < lastest_cluster);
        }

        if (fat_table_ok) {
            uint32_t cluster_bytes = (uint32_t)g_fs.csize * 512u;
            uint32_t dma_bytes = load_limit;
            if (cluster_bytes > 0) {
                dma_bytes = ((load_limit + cluster_bytes - 1u) / cluster_bytes) * cluster_bytes;
                if (dma_bytes > 0x01FF0000u) dma_bytes = 0x01FF0000u;
            }
            *--fat_p = 0x00000000u;
            *--fat_p = 0xFFFFFFFFu;
            g_fat_table_buf[0x1F0 / 4] = dma_bytes;
            g_fat_table_buf[0x1F4 / 4] = 1u; /* DMA_COPY_MODE */
            g_fat_table_buf[0x1F8 / 4] = (u32)g_fs.csize; /* CRITICAL: sectors per cluster! */
            g_fat_table_buf[0x1FC / 4] = 0x10010000u; /* Keep homebrew SRAM saveMODE (0x10) + 64KB save size active! */

            fill_rect(20, 146, 100, 3, RGB15(12, 26, 14));
            SD_Disable();
            SetRompage(0x8002);
            SetPSRampage(0);
            Send_FATbuffer(g_fat_table_buf, 0);
            SetRompage(0x8002);
            SetPSRampage(0);
            if (read_u32_banked_psram_32m(pro_off) == exp_pro0 &&
                read_u32_banked_psram_32m(hdr_tf_off) == exp_tf &&
                read_u32_banked_psram_32m(mid_off) == exp_mid &&
                read_u32_banked_psram_32m(last_off) == exp_last) {
                hw_dma_done = 1;
                fill_rect(20, 146, 200, 3, RGB15(12, 26, 14));
            }
        }

        /* 2. Fallback to CPU 64KB chunked copy if FPGA DMA was not used */
        if (!hw_dma_done) {
            memset(g_fat_table_buf, 0, sizeof(g_fat_table_buf));
            g_fat_table_buf[2] = 0xFFFFFFFFu;
            g_fat_table_buf[0x1F4 / 4] = 2u; /* SET_PARAMETER_MODE */
            g_fat_table_buf[0x1FC / 4] = 0x10010000u;
            Send_FATbuffer(g_fat_table_buf, 1);
            f_lseek(&g_file, 0);
            uint32_t offset = 0;
            while (offset < load_limit) {
                uint32_t rem = load_limit - offset;
                uint32_t step = (rem > 16384u) ? 16384u : rem;
                uint32_t page_off = offset & 0x7FFFFFu;
                if (page_off + step > 0x800000u) step = 0x800000u - page_off;
                UINT br = 0;
                if (f_read(&g_file, g_video_chunk_buf, step, &br) != FR_OK || br == 0) break;
                uint16_t page = (uint16_t)((offset >> 23) << 12);
                psram_write_window(page, page_off, g_video_chunk_buf, (uint32_t)br);
                offset += (uint32_t)br;
                uint32_t bw = (uint32_t)(((uint64_t)offset * 200u) / (load_limit ? load_limit : 1u));
                fill_rect(20, 146, (int)bw, 3, RGB15(12, 26, 14));
            }
        }
        f_close(&g_file);
        SD_Disable();

        begin_sram_access();
        sram_write_u32(156, e->file_hash);
        end_sram_access();
    }

    /* Apply live in-PSRAM 15s/30s Seek + Pause + SRAM Bookmark patches! */
    SD_Disable();
    SetRompage(0x8002);
    uint16_t lr_mult_insn = (uint16_t)(0x2200u | (uint32_t)g_lr_jump_mults[(g_lr_jump_idx >= 0 && g_lr_jump_idx <= 6) ? g_lr_jump_idx : 1]);
    if (e->is_meteo == 1) {
        write_to_banked_psram_32m(0x0148u, g_meteo_patch131_0148, sizeof(g_meteo_patch131_0148));
        write_to_banked_psram_32m(0xA8C8u, g_meteo_patch131_A8C8, sizeof(g_meteo_patch131_A8C8));
        write_to_banked_psram_32m(0xA9F8u, &lr_mult_insn, 2);
    } else if (e->is_meteo == 2) {
        write_to_banked_psram_32m(0xA8E4u, g_meteo_patch140_A8E4, sizeof(g_meteo_patch140_A8E4));
        write_to_banked_psram_32m(0xA90Cu, g_meteo_patch140_A90C, sizeof(g_meteo_patch140_A90C));
        write_to_banked_psram_32m(0xA960u, g_meteo_patch140_A960, sizeof(g_meteo_patch140_A960));
        write_to_banked_psram_32m(0xAA50u, g_meteo_patch140_AA50, sizeof(g_meteo_patch140_AA50));
        write_to_banked_psram_32m(0xAB3Cu, g_meteo_patch140_AB3C, sizeof(g_meteo_patch140_AB3C));
        write_to_banked_psram_32m(0xABECu, &lr_mult_insn, 2);
    }

    /* Always write fresh, immutable 64 KB Player v3.3 ROM stub to 0x09FF0000 right before booting Meteo! */
    restore_player_stub_to_top_psram();

    boot_patched_meteo_psram_rom();
    return 0;
}

static void render_browser_thumbnail(int idx) {
    fill_rect(166, 26, 66, 44, RGB15(4, 4, 5));
    if (idx < 0 || idx >= g_entry_count) return;
    const SdVideoEntry *e = &g_entries[idx];
    if (e->is_dir) {
        fill_rect(176, 34, 46, 28, RGB15(7, 12, 9));
        fill_rect(176, 31, 20, 4, RGB15(12, 20, 14));
        draw_str(181, 44, e->is_dir == 2 ? "UP DIR" : "FOLDER", RGB15(24, 30, 24), 6);
        return;
    }
    if (e->is_meteo) {
        fill_rect(169, 28, 60, 40, RGB15(6, 9, 13));
        draw_str(172, 34, e->is_meteo == 1 ? "METEO 131" : "METEO 140", RGB15(20, 29, 30), 9);
        draw_str(172, 46, "LIVE SRAM", RGB15(18, 28, 19), 9);
        draw_str(172, 56, "+15S/+30S", RGB15(28, 26, 18), 9);
        return;
    }
    if (!e->is_rom_demo) {
        if (f_open(&g_file, e->path, FA_READ) != FR_OK) {
            SD_Disable();
            return;
        }
    }
    g_idx_cache_base = 0xFFFFFFFFu;
    g_psram_idx_valid = 0;
    uint32_t preview_f = 0;
    uint32_t raw0 = get_cached_frame_offset(e, e->hdr_offset, e->total_frames, preview_f) & 0x7FFFFFFF;
    uint32_t exp_rel0 = ((40u + e->total_frames * 4u) + 15u) & ~15u;
    uint32_t offset_base = 0;
    if (!e->is_rom_demo && e->hdr_offset > 0 && raw0 <= exp_rel0 + 32u) offset_base = e->hdr_offset;
    else if (e->is_rom_demo && raw0 > exp_rel0 + 32u) offset_base = (uint32_t)(-(int32_t)(raw0 - exp_rel0));

    uint32_t f_start = offset_base + raw0;
    if (raw_stream_read_at(e, f_start, g_frame_buf, sizeof(g_frame_buf)) == 0) {
        decode_agv_thumbnail_60x40(g_frame_buf, 169, 28);
    }
    if (!e->is_rom_demo) f_close(&g_file);
    SD_Disable();
}

static void draw_browser_ui(int sel_idx, int scroll_top) {
    /* Matte dark background #161618 -> RGB15(3,3,3) */
    fill_rect(0, 0, 240, 160, RGB15(3, 3, 3));

    /* Top header bar */
    fill_rect(0, 0, 240, 18, RGB15(5, 5, 6));
    draw_str(6, 5, g_sd_mounted ? "ARGON EZ-FLASH SD PLAYER V4.6" : "ARGON GBA VIDEO PLAYER V4.6", RGB15(29, 28, 27), 30);
    if (g_sd_mounted) {
        fill_rect(190, 3, 46, 12, RGB15(5, 11, 6));
        draw_str(194, 6, g_use_rom_vfat ? "VFAT OK" : "SD READY", RGB15(18, 29, 18), 8);
    } else {
        fill_rect(190, 3, 46, 12, RGB15(5, 11, 6));
        draw_str(197, 6, "GBA ROM", RGB15(18, 29, 18), 7);
    }

    /* Left list panel (x=4..158, y=22..126) */
    fill_rect(4, 22, 154, 104, RGB15(4, 4, 5));
    if (g_entry_count == 0) {
        draw_str(10, 36, "NO .AGV OR .GBA VIDEOS", RGB15(28, 20, 14), 24);
        draw_str(10, 50, "SCANNED FOLDERS:", RGB15(20, 20, 19), 24);
        draw_str(10, 62, " /  /V  /AV  /VID", RGB15(16, 24, 16), 24);
        draw_str(10, 74, " /VIDEO /VIDEOS /ANIME", RGB15(16, 24, 16), 24);
        draw_str(10, 88, "255-CHAR LFN SUPPORTED", RGB15(24, 24, 22), 24);
    } else {
        int visible_rows = 7;
        for (int r = 0; r < visible_rows; r++) {
            int idx = scroll_top + r;
            if (idx >= g_entry_count) break;
            int ry = 25 + r * 14;
            uint32_t bframe = load_sd_bookmark_for_entry(idx);
            char mark_ch = (bframe == BOOKMARK_PLAYED) ? '^' : ((bframe > 0) ? '*' : ' ');
            if (idx == sel_idx) {
                fill_rect(6, ry - 1, 150, 12, RGB15(7, 13, 8));
                uint16_t mcol = (bframe == BOOKMARK_PLAYED) ? RGB15(16, 29, 31) : RGB15(18, 30, 18);
                draw_char(8, ry + 1, (mark_ch != ' ') ? mark_ch : '>', mcol);
                draw_str(16, ry + 1, get_entry_display_name(&g_entries[idx]), RGB15(30, 30, 29), 23);
            } else {
                if (mark_ch != ' ') {
                    uint16_t mcol = (bframe == BOOKMARK_PLAYED) ? RGB15(12, 24, 28) : RGB15(14, 24, 15);
                    draw_char(8, ry + 1, mark_ch, mcol);
                }
                draw_str(16, ry + 1, get_entry_display_name(&g_entries[idx]), RGB15(21, 20, 19), 23);
            }
        }
    }

    /* Full-width LFN banner for selected file (x=4..158, y=128..140) */
    fill_rect(4, 128, 154, 12, RGB15(5, 5, 7));
    if (sel_idx >= 0 && sel_idx < g_entry_count) {
        const char *full = get_entry_display_name(&g_entries[sel_idx]);
        int flen = (int)strlen(full);
        /* Show tail of filename if > 24 chars so episode number & tags are always visible */
        const char *tail = (flen > 24) ? (full + flen - 24) : full;
        draw_str(8, 131, tail, RGB15(22, 26, 22), 24);
    }

    /* Right inspector + live thumbnail panel (x=162..236, y=22..140) */
    fill_rect(162, 22, 74, 118, RGB15(4, 4, 5));
    if (sel_idx >= 0 && sel_idx < g_entry_count) {
        SdVideoEntry *e = &g_entries[sel_idx];
        uint16_t held_nav = (~REG_KEYINPUT) & (KEY_UP | KEY_DOWN | KEY_L | KEY_R);
        if (!e->is_dir && e->probed == 0 && !held_nav) {
            ensure_entry_probed(sel_idx);
        }
        if (e->is_dir || e->probed == 1) {
            render_browser_thumbnail(sel_idx);
        } else {
            fill_rect(169, 28, 60, 40, RGB15(6, 9, 13));
            draw_str(172, 38, e->is_meteo ? "GBA VIDEO" : "AGV VIDEO", RGB15(20, 29, 30), 9);
            draw_str(172, 50, "A: LAUNCH", RGB15(18, 28, 19), 9);
        }

        if (e->is_dir) {
            draw_str(166, 73, e->is_dir == 2 ? "PARENT DIR" : "SUBFOLDER", RGB15(24, 29, 24), 11);
            draw_str(166, 84, "A:OPEN DIR", RGB15(18, 26, 20), 11);
            draw_str(166, 96, "B:UP LEVEL", RGB15(18, 22, 26), 11);
        } else {
            char mb_str[16], dur_str[12], fps_str[12];
            format_size_mb(mb_str, e->file_size);
            format_mmss(dur_str, e->total_frames / (e->fps ? e->fps : 20));
            format_u32(fps_str, e->fps);
            int fl = (int)strlen(fps_str);
            fps_str[fl] = 'F'; fps_str[fl+1] = 'P'; fps_str[fl+2] = 'S'; fps_str[fl+3] = 0;

            draw_str(166, 73, mb_str, RGB15(28, 28, 26), 11);
            draw_str(166, 84, dur_str, RGB15(22, 22, 20), 6);
            draw_str(204, 84, fps_str, RGB15(18, 22, 26), 5);

            uint32_t saved_frm = load_sd_bookmark_for_entry(sel_idx);
            if (saved_frm == BOOKMARK_PLAYED) {
                draw_str(166, 96, "^ PLAYED", RGB15(14, 28, 31), 11);
            } else if (saved_frm > 0) {
                char res_line[14] = "RES ";
                format_mmss(res_line + 4, saved_frm / (e->fps ? e->fps : 20));
                draw_str(166, 96, res_line, RGB15(16, 29, 18), 11);
            } else {
                draw_str(166, 96, e->is_meteo ? "METEO PATCH" : "START 00:00", RGB15(17, 22, 20), 11);
            }
        }

        if (g_sd_mounted) {
            const char *cstr = (g_auto_chain == CHAIN_RANDOM) ? "CHAIN: RAND" :
                               ((g_auto_chain == CHAIN_NEXT) ? "CHAIN: NEXT" : "CHAIN: OFF");
            uint16_t ccol = (g_auto_chain == CHAIN_RANDOM) ? RGB15(29, 25, 14) :
                            ((g_auto_chain == CHAIN_NEXT) ? RGB15(16, 27, 17) : RGB15(24, 16, 14));
            draw_str(166, 107, cstr, ccol, 11);

            const char *mstr = (g_buf_mode == BUF_MODE_PSRAM_32M) ? "PSRAM 0-NOI" :
                               ((g_buf_mode == BUF_MODE_EWRAM_96K) ? "EWRAM 80KB" : "SD STREAM");
            draw_str(166, 118, mstr, RGB15(18, 25, 29), 11);

            const char *bstr = (g_show_load_bar == LOAD_BAR_FILE) ? "BAR: FILE" :
                               ((g_show_load_bar == LOAD_BAR_SHOW) ? "BAR: SHOW" : "BAR: HIDE");
            uint16_t bcol = (g_show_load_bar == LOAD_BAR_FILE) ? RGB15(16, 28, 26) :
                            ((g_show_load_bar == LOAD_BAR_SHOW) ? RGB15(18, 28, 20) : RGB15(26, 23, 14));
            draw_str(166, 129, bstr, bcol, 11);
        } else {
            static const char * const s_short_jump[7] = {
                "L/R: +/-15S", "L/R: +/-30S", "L/R: +/-1M", "L/R: +/-2M",
                "L/R: +/-3M",  "L/R: +/-5M",  "L/R: +/-10M"
            };
            int lj = (g_lr_jump_idx >= 0 && g_lr_jump_idx <= 6) ? g_lr_jump_idx : 1;
            draw_str(166, 107, s_short_jump[lj], RGB15(29, 26, 14), 11);
            draw_str(166, 118, (g_auto_chain != CHAIN_OFF) ? "END: LOOP" : "END: PAUSE", RGB15(17, 28, 19), 11);
            draw_str(166, 129, "SEL:OPTIONS", RGB15(18, 25, 29), 11);
        }
    }

    /* Bottom controls bar */
    fill_rect(0, 142, 240, 18, RGB15(5, 5, 6));
    if (g_sd_mounted) {
        draw_str(4, 147, "A:PLAY B:UP ST:RECENT L/R:PG SEL:SET", RGB15(21, 21, 19), 39);
    } else {
        draw_str(6, 147, "A:PLAY   START:00:00   SELECT:SETTINGS", RGB15(21, 21, 19), 38);
    }
}

static void draw_settings_modal(int s_row, const char *status_msg) {
    /* Outer border & dark matte card (x=14..226, y=10..148) */
    fill_rect(12, 8, 216, 142, RGB15(10, 14, 11));
    fill_rect(14, 10, 212, 138, RGB15(4, 4, 5));

    /* Header bar */
    fill_rect(14, 10, 212, 15, RGB15(6, 10, 7));

    int lj = (g_lr_jump_idx >= 0 && g_lr_jump_idx <= 6) ? g_lr_jump_idx : 1;

    if (!g_sd_mounted) {
        draw_str(22, 14, "STANDALONE ROM SETTINGS (V4.6)", RGB15(29, 29, 27), 32);

        const char *rom_labels[3] = {
            "L/R JUMP",
            "AT VIDEO END",
            "SAVED RESUME"
        };
        const char *rval0 = g_lr_jump_labels[lj];
        uint16_t rcol0 = RGB15(29, 26, 14);

        const char *rval1 = (g_auto_chain != CHAIN_OFF) ? "< LOOP VIDEO   >" : "< PAUSE AT END >";
        uint16_t rcol1 = (g_auto_chain != CHAIN_OFF) ? RGB15(17, 29, 18) : RGB15(26, 21, 15);

        const char *rval2 = status_msg ? status_msg : "[A: RESET 00:00]";
        uint16_t rcol2 = status_msg ? RGB15(18, 30, 20) : RGB15(22, 25, 28);

        const char *rvals[3] = { rval0, rval1, rval2 };
        uint16_t rvcols[3]   = { rcol0, rcol1, rcol2 };

        for (int r = 0; r < 3; r++) {
            int ry = 36 + r * 22;
            if (r == s_row) {
                fill_rect(18, ry - 2, 204, 14, RGB15(7, 13, 8));
                draw_char(21, ry + 1, '>', RGB15(18, 30, 18));
                draw_str(29, ry + 1, rom_labels[r], RGB15(30, 30, 29), 13);
            } else {
                draw_str(29, ry + 1, rom_labels[r], RGB15(21, 21, 19), 13);
            }
            draw_str(116, ry + 1, rvals[r], rvcols[r], 17);
        }

        draw_str(22, 108, "D-PAD LEFT/RIGHT: +/- 15S SEEK", RGB15(17, 20, 18), 32);
        draw_str(22, 118, "SHOULDER L/R: CUSTOM JUMP STEP", RGB15(17, 20, 18), 32);

        fill_rect(14, 132, 212, 16, RGB15(5, 6, 7));
        draw_str(22, 136, "LEFT/RIGHT/A:CHANGE   B/SEL:CLOSE", RGB15(20, 22, 20), 34);
        return;
    }

    draw_str(22, 14, "PLAYER V4.6 SETTINGS (SELECT)", RGB15(29, 29, 27), 32);

    const char *labels[7] = {
        "AUTO PLAY",
        "L/R JUMP",
        "BUFFER MODE",
        "LOADING BAR",
        "CLEAN NAMES",
        "SHUFFLE DIR",
        "WATCHED MARKS"
    };

    const char *val0 = (g_auto_chain == CHAIN_RANDOM) ? "< RANDOM DIR >" :
                       ((g_auto_chain == CHAIN_NEXT) ? "< NEXT IN DIR >" : "< OFF (1 VID) >");
    uint16_t col0 = (g_auto_chain == CHAIN_RANDOM) ? RGB15(30, 26, 14) :
                    ((g_auto_chain == CHAIN_NEXT) ? RGB15(17, 29, 18) : RGB15(26, 17, 15));

    const char *val1 = g_lr_jump_labels[lj];
    uint16_t col1 = RGB15(29, 26, 14);

    const char *val2 = (g_buf_mode == BUF_MODE_PSRAM_32M) ? "< PSRAM 0-NOI >" :
                       ((g_buf_mode == BUF_MODE_EWRAM_96K) ? "< EWRAM 80KB  >" : "< SD STREAM   >");
    uint16_t col2 = RGB15(18, 26, 30);

    const char *val3 = (g_show_load_bar == LOAD_BAR_FILE) ? "< FILE ONLY   >" :
                       ((g_show_load_bar == LOAD_BAR_SHOW) ? "< SHOW ALL    >" : "< HIDE ALL    >");
    uint16_t col3 = (g_show_load_bar == LOAD_BAR_FILE) ? RGB15(16, 28, 26) :
                    ((g_show_load_bar == LOAD_BAR_SHOW) ? RGB15(18, 28, 20) : RGB15(26, 23, 14));

    const char *val4 = g_clean_names ? "< ON (CLEAN)  >" : "< OFF (RAW)   >";
    uint16_t col4 = g_clean_names ? RGB15(17, 29, 18) : RGB15(27, 22, 15);

    const char *val5 = "[A: PLAY RANDOM]";
    uint16_t col5 = RGB15(29, 26, 15);

    const char *val6 = status_msg ? status_msg : "[A: RESET WATCHED]";
    uint16_t col6 = status_msg ? RGB15(18, 30, 20) : RGB15(22, 24, 26);

    const char *vals[7] = { val0, val1, val2, val3, val4, val5, val6 };
    uint16_t vcols[7]   = { col0, col1, col2, col3, col4, col5, col6 };

    for (int r = 0; r < 7; r++) {
        int ry = 29 + r * 14;
        if (r == s_row) {
            fill_rect(18, ry - 1, 204, 12, RGB15(7, 13, 8));
            draw_char(21, ry + 1, '>', RGB15(18, 30, 18));
            draw_str(29, ry + 1, labels[r], RGB15(30, 30, 29), 13);
        } else {
            draw_str(29, ry + 1, labels[r], RGB15(21, 21, 19), 13);
        }
        draw_str(116, ry + 1, vals[r], vcols[r], 17);
    }

    /* Footer bar inside modal */
    fill_rect(14, 132, 212, 16, RGB15(5, 6, 7));
    draw_str(20, 136, "L/R/A:CHANGE   B/SELECT:CLOSE", RGB15(20, 22, 20), 35);
}

/* Returns >= 0 if user selected "SHUFFLE DIR -> [A: PLAY RANDOM]" to launch immediately, or -1 to return to browser */
static int run_settings_modal(int cur_sel_idx, uint16_t *io_prev_keys) {
    int s_row = 0;
    int num_rows = g_sd_mounted ? 7 : 3;
    const char *status_msg = NULL;
    draw_settings_modal(s_row, status_msg);

    while (1) {
        wait_vblank();
        uint16_t keys = ~REG_KEYINPUT & 0x03FF;
        uint16_t newly = keys & ~(*io_prev_keys);
        *io_prev_keys = keys;
        step_rng(keys);

        if (!newly) continue;
        int redraw = 0;

        if (newly & (KEY_B | KEY_SELECT | KEY_START)) {
            return -1;
        }
        if (newly & KEY_DOWN) {
            s_row = (s_row + 1) % num_rows;
            status_msg = NULL;
            redraw = 1;
        }
        if (newly & KEY_UP) {
            s_row = (s_row + num_rows - 1) % num_rows;
            status_msg = NULL;
            redraw = 1;
        }
        if (newly & (KEY_LEFT | KEY_RIGHT | KEY_A)) {
            int dir = (newly & KEY_LEFT) ? -1 : 1;
            if (!g_sd_mounted) {
                if (s_row == 0) {
                    g_lr_jump_idx = (g_lr_jump_idx + 7 + dir) % 7;
                    save_sram_settings();
                    redraw = 1;
                } else if (s_row == 1) {
                    g_auto_chain = (g_auto_chain == CHAIN_OFF) ? CHAIN_NEXT : CHAIN_OFF;
                    save_sram_settings();
                    redraw = 1;
                } else if (s_row == 2 && (newly & KEY_A)) {
                    save_sd_bookmark(0, 0);
                    status_msg = "RESET TO 00:00!";
                    redraw = 1;
                }
            } else {
                if (s_row == 0) {
                    g_auto_chain = (g_auto_chain + 3 + dir) % 3;
                    save_sram_settings();
                    redraw = 1;
                } else if (s_row == 1) {
                    g_lr_jump_idx = (g_lr_jump_idx + 7 + dir) % 7;
                    save_sram_settings();
                    redraw = 1;
                } else if (s_row == 2) {
                    if (g_has_psram) {
                        g_buf_mode = (g_buf_mode + 3 + dir) % 3;
                    } else {
                        g_buf_mode = (g_buf_mode == BUF_MODE_DIRECT_SD) ? BUF_MODE_EWRAM_96K : BUF_MODE_DIRECT_SD;
                    }
                    save_sram_settings();
                    redraw = 1;
                } else if (s_row == 3) {
                    if (dir > 0) {
                        if (g_show_load_bar == LOAD_BAR_FILE) g_show_load_bar = LOAD_BAR_HIDE;
                        else if (g_show_load_bar == LOAD_BAR_HIDE) g_show_load_bar = LOAD_BAR_SHOW;
                        else g_show_load_bar = LOAD_BAR_FILE;
                    } else {
                        if (g_show_load_bar == LOAD_BAR_FILE) g_show_load_bar = LOAD_BAR_SHOW;
                        else if (g_show_load_bar == LOAD_BAR_SHOW) g_show_load_bar = LOAD_BAR_HIDE;
                        else g_show_load_bar = LOAD_BAR_FILE;
                    }
                    save_sram_settings();
                    redraw = 1;
                } else if (s_row == 4) {
                    g_clean_names = !g_clean_names;
                    save_sram_settings();
                    sort_entries();
                    redraw = 1;
                } else if (s_row == 5 && (newly & KEY_A)) {
                    g_auto_chain = CHAIN_RANDOM;
                    save_sram_settings();
                    int rnd_idx = pick_next_video_in_dir(cur_sel_idx, 1);
                    return (rnd_idx >= 0) ? rnd_idx : -1;
                } else if (s_row == 6 && (newly & KEY_A)) {
                    clear_dir_played_marks();
                    status_msg = "WATCHED RESET!";
                    redraw = 1;
                }
            }
        }

        if (redraw) {
            draw_settings_modal(s_row, status_msg);
        }
    }
}

static void draw_recent_modal(int r_cnt, int r_sel, int r_scroll, const char *err_msg) {
    fill_rect(8, 12, 224, 136, RGB15(10, 14, 11));
    fill_rect(10, 14, 220, 132, RGB15(4, 4, 5));

    fill_rect(10, 14, 220, 15, RGB15(6, 10, 7));
    draw_str(16, 18, "RECENTLY PLAYED (LAST 10 VIDEOS)", RGB15(29, 29, 27), 34);

    if (r_cnt <= 0) {
        draw_str(28, 56, "NO RECENT VIDEOS IN SRAM YET.", RGB15(26, 22, 16), 31);
        draw_str(28, 72, "START ANY .AGV OR .GBA VIDEO", RGB15(20, 22, 20), 31);
        draw_str(28, 86, "TO RECORD IT IN THIS LIST!", RGB15(20, 22, 20), 31);
    } else {
        int vis = 6;
        for (int r = 0; r < vis; r++) {
            int idx = r_scroll + r;
            if (idx >= r_cnt) break;
            int ry = 33 + r * 14;
            const RecentVideoItem *it = &g_recent_items[idx];

            const char *fname = it->path;
            for (int k = 0; it->path[k]; k++) {
                if (it->path[k] == '/') fname = &it->path[k + 1];
            }
            char clean_n[56], raw_n[56];
            make_display_names(clean_n, raw_n, fname);
            const char *disp = (g_clean_names && clean_n[0]) ? clean_n : raw_n;

            uint32_t bmk = load_sd_bookmark_by_hash(it->file_hash, it->total_frames);
            char status_s[10];
            uint16_t scol = RGB15(17, 22, 20);
            if (bmk == BOOKMARK_PLAYED) {
                status_s[0] = '^'; status_s[1] = 'D'; status_s[2] = 'O'; status_s[3] = 'N'; status_s[4] = 'E'; status_s[5] = 0;
                scol = RGB15(14, 28, 31);
            } else if (bmk > 0) {
                status_s[0] = '*';
                format_mmss(status_s + 1, bmk / (it->fps ? it->fps : 20));
                scol = RGB15(16, 29, 18);
            } else {
                format_mmss(status_s, it->total_frames / (it->fps ? it->fps : 20));
            }

            if (idx == r_sel) {
                fill_rect(14, ry - 1, 212, 12, RGB15(7, 13, 8));
                draw_char(16, ry + 1, '>', RGB15(18, 30, 18));
                draw_str(24, ry + 1, disp, RGB15(30, 30, 29), 25);
            } else {
                draw_str(24, ry + 1, disp, RGB15(21, 20, 19), 25);
            }
            draw_str(182, ry + 1, status_s, scol, 7);
        }

        fill_rect(12, 118, 216, 12, RGB15(5, 5, 7));
        if (err_msg) {
            draw_str(16, 121, err_msg, RGB15(31, 18, 16), 34);
        } else if (r_sel >= 0 && r_sel < r_cnt) {
            const char *full_p = g_recent_items[r_sel].path;
            int plen = (int)strlen(full_p);
            const char *tail_p = (plen > 34) ? (full_p + plen - 34) : full_p;
            draw_str(16, 121, tail_p, RGB15(22, 26, 22), 34);
        }
    }

    fill_rect(10, 131, 220, 15, RGB15(5, 6, 7));
    draw_str(15, 135, "A:RESUME  L+A:0:00  B/START:CLOSE", RGB15(20, 22, 20), 35);
}

static int run_recent_modal(int *io_sel_idx, int *io_scroll_top, int *out_force_zero, uint16_t *io_prev_keys) {
    int r_cnt = load_recent_videos_from_sram();
    int r_sel = 0;
    int r_scroll = 0;
    const char *err_msg = NULL;
    if (out_force_zero) *out_force_zero = 0;
    draw_recent_modal(r_cnt, r_sel, r_scroll, err_msg);

    while (1) {
        wait_vblank();
        uint16_t keys = ~REG_KEYINPUT & 0x03FF;
        uint16_t newly = keys & ~(*io_prev_keys);
        *io_prev_keys = keys;
        step_rng(keys);

        if (!newly) continue;
        int redraw = 0;

        if (newly & (KEY_B | KEY_START | KEY_SELECT)) {
            return -1;
        }
        if ((newly & KEY_DOWN) && r_cnt > 0) {
            r_sel = (r_sel + 1) % r_cnt;
            if (r_sel < r_scroll) r_scroll = r_sel;
            if (r_sel >= r_scroll + 6) r_scroll = r_sel - 5;
            err_msg = NULL;
            redraw = 1;
        }
        if ((newly & KEY_UP) && r_cnt > 0) {
            r_sel = (r_sel - 1 + r_cnt) % r_cnt;
            if (r_sel < r_scroll) r_scroll = r_sel;
            if (r_sel >= r_scroll + 6) r_scroll = r_sel - 5;
            err_msg = NULL;
            redraw = 1;
        }
        if ((newly & KEY_A) && r_cnt > 0) {
            char target_path[160];
            for (int c = 0; c < 156; c++) {
                target_path[c] = g_recent_items[r_sel].path[c];
                if (target_path[c] == 0) break;
            }
            target_path[155] = 0;
            char target_dir[192];
            get_parent_dir(target_path, target_dir);
            if (str_cmp_ci(target_dir, g_cur_dir) != 0) {
                memcpy(g_cur_dir, target_dir, 192);
                save_sram_cur_dir();
                scan_all_videos();
            }
            int found_idx = -1;
            for (int i = 0; i < g_entry_count; i++) {
                if (!g_entries[i].is_dir && str_cmp_ci(g_entries[i].path, target_path) == 0) {
                    found_idx = i;
                    break;
                }
            }
            if (found_idx >= 0) {
                *io_sel_idx = found_idx;
                if (*io_sel_idx < *io_scroll_top) *io_scroll_top = *io_sel_idx;
                if (*io_sel_idx >= *io_scroll_top + 7) *io_scroll_top = *io_sel_idx - 6;
                if (out_force_zero) *out_force_zero = (keys & KEY_L) ? 1 : 0;
                return found_idx;
            } else {
                err_msg = "FILE NOT FOUND ON SD CARD!";
                redraw = 1;
            }
        }
        if (redraw) {
            draw_recent_modal(r_cnt, r_sel, r_scroll, err_msg);
        }
    }
}

static void run_playback_chain(int start_idx, int force_zero, uint16_t *io_prev_keys, int *io_sel_idx, int *io_scroll_top) {
    int next_idx = start_idx;
    int first_iter = 1;
    int skip_tries = 0;
    while (next_idx >= 0 && next_idx < g_entry_count && !g_entries[next_idx].is_dir) {
        if (!ensure_entry_probed(next_idx)) {
            if (++skip_tries > 8) break;
            next_idx = pick_manual_next_video_in_dir(next_idx);
            continue;
        }
        skip_tries = 0;
        record_recent_video(&g_entries[next_idx]);
        *io_sel_idx = next_idx;
        if (*io_sel_idx < *io_scroll_top) *io_scroll_top = *io_sel_idx;
        if (*io_sel_idx >= *io_scroll_top + 7) *io_scroll_top = *io_sel_idx - 6;

        if (g_entries[next_idx].is_meteo) {
            draw_browser_ui(*io_sel_idx, *io_scroll_top);
            launch_meteo_rom_live_patched(next_idx, first_iter ? force_zero : 0);
            return;
        }

        uint32_t start_frame = 0;
        if (first_iter) {
            if (!force_zero) start_frame = load_sd_bookmark_for_entry(next_idx);
            if (start_frame == BOOKMARK_PLAYED) start_frame = 0;
        } else {
            start_frame = 0;
        }
        first_iter = 0;

        next_idx = play_video_entry(next_idx, start_frame, io_prev_keys);
    }
}

__attribute__((noreturn))
void player_sd_main(void) {
    REG_WAITCNT = 0x4317; /* Enable Game Pak prefetch + fast ROM/PSRAM waitstates */
    REG_DISPCNT = 0x0403; /* Mode 3 (240x160 16-bit BGR555) + BG2 enable */

    /* Explicitly initialize all runtime state in .bss so soft-resets from 0x09FF0000 start 100% clean */
    g_idx_cache_base     = 0xFFFFFFFFu;
    g_ewram_vid_start    = 0xFFFFFFFFu;
    g_ewram_vid_end      = 0;
    g_has_psram          = 1;
    g_buf_mode           = BUF_MODE_PSRAM_32M;
    g_linear_psram_mode  = 0;
    g_linear_psram_ptr   = (const uint8_t *)0x08000000u;
    g_chap_vid_psram_off = 0x00100000u;
    g_chap_aud_psram_off = 0x01A00000u;
    g_psram_aud_start    = 0xFFFFFFFFu;
    g_psram_vid_start    = 0xFFFFFFFFu;
    g_auto_chain         = CHAIN_NEXT;
    g_show_load_bar      = LOAD_BAR_FILE;
    g_clean_names        = 1;
    g_rng_state          = 0x9E3779B9u ^ ((uint32_t)REG_VCOUNT << 16) ^ REG_TM0CNT_L;
    g_bookmark_seq       = 1;
    g_sram_bmk_cached    = 0;
    g_cur_dir[0]         = '/';
    g_cur_dir[1]         = 0;
    load_sram_settings();
    refresh_sram_bookmark_cache();

    uint16_t boot_keys = ~REG_KEYINPUT & 0x03FF;
    uint16_t prev_keys = boot_keys;
    int sel_idx = 0;
    int scroll_top = 0;

    /* Check if this .GBA ROM was built as an auto-playing standalone .GBA Playable ROM ("AUTO" at 0x0800FFFC) */
    const AgvHeaderFixed *boot_rom_hdr = (const AgvHeaderFixed *)0x08010000;
    int is_standalone_rom_boot = ((*(const volatile uint32_t *)0x0800FFFC == 0x4155544Fu || *(const volatile uint32_t *)0x0800FFFC == 0x4F545541u) &&
                                  boot_rom_hdr->magic == 0x31564741u &&
                                  boot_rom_hdr->total_frames > 0);
    uint32_t boot_rom_frames = is_standalone_rom_boot ? boot_rom_hdr->total_frames : 0;
    uint32_t boot_rom_aud    = is_standalone_rom_boot ? boot_rom_hdr->audio_offset : 0;

    if (is_standalone_rom_boot && !(boot_keys & KEY_B)) {
        /* Play the embedded .GBA ROM stream immediately from 0x08010000 (zero SD access during part!) */
        g_entry_count = 1;
        SdVideoEntry *e = &g_entries[0];
        const char *custom_name = (const char *)0x0800FFD0;
        const char *dname = (custom_name[0] >= 0x21 && custom_name[0] < 0x7F) ? custom_name : "Current_ROM.gba";
        int i = 0;
        while (dname[i] && i < 35) { e->name[i] = dname[i]; e->path[i] = dname[i]; i++; }
        e->name[i] = 0; e->path[i] = 0;
        e->hdr_offset = 0x08010000;
        e->total_frames = boot_rom_frames;
        e->audio_offset = boot_rom_aud;
        uint32_t vpf = boot_rom_hdr->vblanks_per_frame ? boot_rom_hdr->vblanks_per_frame : 3;
        uint32_t fps = (boot_rom_hdr->seek_15s_frames >= 75) ? (boot_rom_hdr->seek_15s_frames / 15) : (60 / vpf);
        if (fps == 0) fps = 20;
        e->fps = (uint16_t)fps;
        e->file_size = boot_rom_aud + ((boot_rom_frames * (boot_rom_hdr->audio_rate ? boot_rom_hdr->audio_rate : 10512u)) / fps);
        e->file_hash = fnv1a_hash_ci(e->path, e->file_size, e->total_frames);
        e->is_rom_demo = 1;
        e->is_agv = 0;

        g_entry_count = 1;
        uint32_t resume_f = load_sd_bookmark_for_entry(0);
        int chain_res = play_video_entry(0, resume_f, &prev_keys);

        /* Now mount EZ-FLASH SD card and scan all .GBA and .AGV files alphabetically! */
        scan_all_videos();
        while (chain_res >= 1 && !g_sd_mounted) {
            /* In a standard GBA emulator without an SD card, loop the standalone .GBA video seamlessly unless B is pressed */
            g_entry_count = 1;
            chain_res = play_video_entry(0, 0, &prev_keys);
        }
        int matched_idx = -1;
        for (int k = 0; k < g_entry_count; k++) {
            if (!g_entries[k].is_rom_demo &&
                g_entries[k].total_frames == boot_rom_frames &&
                g_entries[k].audio_offset == boot_rom_aud) {
                matched_idx = k;
                break;
            }
        }
        if (matched_idx >= 0) {
            g_loaded_psram_hash = g_entries[matched_idx].file_hash;
        }
        if (chain_res >= 1 && matched_idx >= 0) {
            int nxt = pick_next_video_in_dir(matched_idx, 0);
            if (nxt >= 0) {
                run_playback_chain(nxt, 0, &prev_keys, &sel_idx, &scroll_top);
            }
        } else if (matched_idx >= 0) {
            sel_idx = matched_idx;
            if (sel_idx >= 7) scroll_top = sel_idx - 6;
        }
    } else {
        if (*(const volatile uint32_t *)0x0803FFF0 == 0x54414656) {
            g_use_rom_vfat = 1;
        }
        load_sram_cur_dir();
        scan_all_videos();
    }

    load_sram_settings();
    int meteo_nav_action = 0;
    uint32_t meteo_nav_hash = sync_meteo_return_bookmark(&meteo_nav_action);

    /* Highlight last-played video from SRAM if B is not held at boot */
    begin_sram_access();
    if (sram_read_u32(0) == SRAM_MAGIC_V2) {
        uint32_t last_hash = sram_read_u32(4);
        uint32_t last_frm  = sram_read_u32(8);
        uint32_t last_chk  = sram_read_u32(12);
        if ((last_hash ^ last_frm ^ 0xA5A5A5A5u) == last_chk) {
            for (int i = 0; i < g_entry_count; i++) {
                if (g_entries[i].file_hash == last_hash) {
                    sel_idx = i;
                    if (sel_idx >= 7) scroll_top = sel_idx - 6;
                    break;
                }
            }
        }
    }
    end_sram_access();

    /* If returning from an old Meteo .GBA file via EOF (action 1), DOWN=Next/Random (action 2), or UP=Prev (action 3),
     * automatically advance to and launch the target video in the current folder! */
    if (meteo_nav_hash != 0 && meteo_nav_action != 0 && !((~REG_KEYINPUT) & KEY_B)) {
        int fin_idx = -1;
        for (int i = 0; i < g_entry_count; i++) {
            if (g_entries[i].file_hash == meteo_nav_hash) {
                fin_idx = i;
                break;
            }
        }
        if (fin_idx >= 0) {
            int nxt_idx = -1;
            if (meteo_nav_action == 2) {
                nxt_idx = pick_manual_next_video_in_dir(fin_idx);
            } else if (meteo_nav_action == 3) {
                nxt_idx = pick_prev_video_in_dir(fin_idx);
            } else if (meteo_nav_action == 1 && g_auto_chain != CHAIN_OFF) {
                nxt_idx = pick_next_video_in_dir(fin_idx, 0);
            }
            if (nxt_idx >= 0 && nxt_idx < g_entry_count && !g_entries[nxt_idx].is_dir) {
                run_playback_chain(nxt_idx, 0, &prev_keys, &sel_idx, &scroll_top);
            }
        }
    }

    draw_browser_ui(sel_idx, scroll_top);
    /* If returning from Meteo or video playback with B/A/START held, wait for button release */
    while ((~REG_KEYINPUT) & (KEY_A | KEY_B | KEY_START)) {
        wait_vblank();
    }
    prev_keys = ~REG_KEYINPUT & 0x03FF;

    while (1) {
        wait_vblank();
        uint16_t keys = ~REG_KEYINPUT & 0x03FF;
        uint16_t newly = keys & ~prev_keys;
        prev_keys = keys;
        step_rng(keys);

        int redraw = 0;
        if ((newly & KEY_DOWN) && g_entry_count > 0) {
            sel_idx = (sel_idx + 1) % g_entry_count;
            if (sel_idx < scroll_top) scroll_top = sel_idx;
            if (sel_idx >= scroll_top + 7) scroll_top = sel_idx - 6;
            redraw = 1;
        }
        if ((newly & KEY_UP) && g_entry_count > 0) {
            sel_idx = (sel_idx - 1 + g_entry_count) % g_entry_count;
            if (sel_idx < scroll_top) scroll_top = sel_idx;
            if (sel_idx >= scroll_top + 7) scroll_top = sel_idx - 6;
            redraw = 1;
        }
        /* L / R in the file browser: fast Page Up / Page Down (-7 / +7 entries) */
        if ((newly & KEY_R) && g_entry_count > 0) {
            sel_idx += 7;
            if (sel_idx >= g_entry_count) sel_idx = g_entry_count - 1;
            if (sel_idx < scroll_top) scroll_top = sel_idx;
            if (sel_idx >= scroll_top + 7) scroll_top = sel_idx - 6;
            redraw = 1;
        }
        if ((newly & KEY_L) && g_entry_count > 0) {
            sel_idx -= 7;
            if (sel_idx < 0) sel_idx = 0;
            if (sel_idx < scroll_top) scroll_top = sel_idx;
            if (sel_idx >= scroll_top + 7) scroll_top = sel_idx - 6;
            redraw = 1;
        }
        /* SELECT opens the dedicated Player v3.8 Settings Modal Window! */
        if (newly & KEY_SELECT) {
            int shuffle_launch_idx = run_settings_modal(sel_idx, &prev_keys);
            if (shuffle_launch_idx >= 0 && shuffle_launch_idx < g_entry_count && !g_entries[shuffle_launch_idx].is_dir) {
                run_playback_chain(shuffle_launch_idx, 0, &prev_keys, &sel_idx, &scroll_top);
            }
            redraw = 1;
        }
        if (newly & KEY_B) {
            /* B in file browser goes up to parent directory if inside a subfolder */
            if (g_cur_dir[0] == '/' && g_cur_dir[1] != 0) {
                char prev_dir[192];
                int k = 0;
                while (g_cur_dir[k] && k < 190) { prev_dir[k] = g_cur_dir[k]; k++; }
                prev_dir[k] = 0;
                get_parent_dir(prev_dir, g_cur_dir);
                save_sram_cur_dir();
                scan_all_videos();
                sel_idx = 0;
                scroll_top = 0;
                for (int i = 0; i < g_entry_count; i++) {
                    if (g_entries[i].is_dir == 1 && str_cmp_ci(g_entries[i].path, prev_dir) == 0) {
                        sel_idx = i;
                        if (sel_idx >= 7) scroll_top = sel_idx - 6;
                        break;
                    }
                }
                redraw = 1;
            }
        }
        /* START in the file browser opens Recently Played on SD, or starts from 00:00 in Standalone ROM mode! */
        if (newly & KEY_START) {
            if (!g_sd_mounted) {
                if (sel_idx >= 0 && sel_idx < g_entry_count && !g_entries[sel_idx].is_dir) {
                    run_playback_chain(sel_idx, 1, &prev_keys, &sel_idx, &scroll_top);
                }
                redraw = 1;
            } else {
                int f_zero = 0;
                int rec_launch_idx = run_recent_modal(&sel_idx, &scroll_top, &f_zero, &prev_keys);
                if (rec_launch_idx >= 0 && rec_launch_idx < g_entry_count && !g_entries[rec_launch_idx].is_dir) {
                    run_playback_chain(rec_launch_idx, f_zero, &prev_keys, &sel_idx, &scroll_top);
                }
                redraw = 1;
            }
        }
        if ((newly & KEY_A) && g_entry_count > 0) {
            if (g_entries[sel_idx].is_dir) {
                char target_dir[192];
                int k = 0;
                while (g_entries[sel_idx].path[k] && k < 188) {
                    target_dir[k] = g_entries[sel_idx].path[k];
                    k++;
                }
                target_dir[k] = 0;
                memcpy(g_cur_dir, target_dir, 192);
                save_sram_cur_dir();
                scan_all_videos();
                sel_idx = 0;
                scroll_top = 0;
                /* Auto-select first video file in the opened folder if present */
                for (int i = 0; i < g_entry_count; i++) {
                    if (!g_entries[i].is_dir) {
                        sel_idx = i;
                        if (sel_idx >= 7) scroll_top = sel_idx - 6;
                        break;
                    }
                }
                redraw = 1;
            } else {
                int force_zero = ((keys & KEY_B) || (keys & KEY_L)) ? 1 : 0;
                run_playback_chain(sel_idx, force_zero, &prev_keys, &sel_idx, &scroll_top);
                redraw = 1;
            }
        }

        if (!redraw && sel_idx >= 0 && sel_idx < g_entry_count &&
            !g_entries[sel_idx].is_dir && g_entries[sel_idx].probed == 0 &&
            !(keys & (KEY_UP | KEY_DOWN | KEY_L | KEY_R))) {
            redraw = 1;
        }
        if (redraw) {
            draw_browser_ui(sel_idx, scroll_top);
        }
    }
}
