// PlayAgain's shim for PPSSPP: a libretro frontend inside the module, and the
// flat C ABI the adapter drives (see ../README.md).
//
// PPSSPP's own libretro front-end (libretro/libretro.cpp) is the core; this
// file plays RetroArch's part: it answers the environment, takes the frames
// and the sound, and hands over the pad. One PSP, one thread (the build has no
// pthreads, see ppsspp-*.patch): retro_run is one vblank, on the caller's
// thread, drawn by the software renderer into an RGBA buffer, or (pa_set_renderer(1)) by
// PPSSPP's GL renderer on a WebGL2 context on Module.canvas, an OffscreenCanvas in the worker,
// with its render queue run inline on this same thread (ppsspp-*-webgl.patch).
//
// The guest sees no wall clock: the RTC is set from the session clock after
// boot, the MAC address is fixed, and PPSSPP's sleeps do nothing (the host
// paces frames).

#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>
#include <vector>
#include <algorithm>

#include <dirent.h>
#include <pthread.h>
#include <sys/stat.h>
#include <unistd.h>

#include <emscripten.h>
#include <emscripten/html5.h>

#include <libretro.h>

#include "Common/Serialize/Serializer.h"
#include "Core/Config.h"
#include "Core/ConfigValues.h"
#include "Core/Core.h"
#include "Core/CoreTiming.h"
#include "Core/HLE/sceRtc.h"
#include "Core/MIPS/MIPS.h"
#include "Core/MemMap.h"
#include "Core/SaveState.h"
#include "Core/System.h"
#include "GPU/GPUCommon.h"
#include "ext/xxhash.h"
#include "pa_wasmjit.h"

namespace Libretro {
extern bool g_pendingBoot;
extern std::string g_bootErrorString;
}

#define PA_EXPORT extern "C" __attribute__((used, visibility("default")))

namespace {

constexpr int kWidth = 480;
constexpr int kHeight = 272;
constexpr int kAudioRate = 44100;
constexpr int kRingFrames = 1 << 16; // about 1.5 s of stereo sound
constexpr const char *kSystemDir = "/pa/system";
constexpr const char *kSaveDir = "/pa/save";
constexpr const char *kSavedata = "/pa/save/PSP/SAVEDATA";

// --- the PlayAgain button mask (src/realtime/protocol/protocol.ts BUTTONS) ---
enum : uint32_t {
	PA_UP = 1u << 0, PA_DOWN = 1u << 1, PA_LEFT = 1u << 2, PA_RIGHT = 1u << 3,
	PA_A = 1u << 4, PA_B = 1u << 5, PA_X = 1u << 6, PA_Y = 1u << 7,
	PA_START = 1u << 8, PA_SELECT = 1u << 9, PA_L1 = 1u << 10, PA_R1 = 1u << 11,
};

struct State {
	bool inited = false;
	bool loaded = false;
	bool failed = false;
	int verbose = 0;
	int64_t clock = 1700000000; // the session clock, unix seconds
	uint32_t keys = 0;           // PlayAgain mask
	int16_t axisX = 0, axisY = 0;
	uint8_t fb[kWidth * kHeight * 4] = {};
	int fbWidth = kWidth, fbHeight = kHeight;
	uint32_t frames = 0;
	int16_t ring[kRingFrames * 2] = {};
	uint32_t ringRead = 0, ringWrite = 0; // in frames, free-running
	uint64_t savesHash = 0;
	bool savesHashed = false;
	std::string gamePath;
	bool gl = false;                       // PPSSPP's GL renderer on WebGL2 (pa_set_renderer)
	bool presented = false;                // a GL frame reached the canvas since pa_presented last asked
	retro_hw_render_callback hw = {};      // what PPSSPP asked for (its context_reset)
	EMSCRIPTEN_WEBGL_CONTEXT_HANDLE glCtx = 0;
};

State g;

// --- libretro callbacks --------------------------------------------------------------------------

void LogCb(enum retro_log_level level, const char *fmt, ...) {
	if (level < RETRO_LOG_WARN && !g.verbose)
		return;
	if (level < RETRO_LOG_ERROR && g.verbose < 0)
		return;
	va_list args;
	va_start(args, fmt);
	vfprintf(stderr, fmt, args);
	va_end(args);
}

// The core options PlayAgain answers; every other one keeps PPSSPP's default.
const char *Variable(const char *key) {
	// GL: PPSSPP's own renderer, one frame in flight (the queue runs inline, a frame at a time).
	if (g.gl) {
		if (!strcmp(key, "ppsspp_backend"))
			return "opengl";
		if (!strcmp(key, "ppsspp_software_rendering"))
			return "disabled";
		if (!strcmp(key, "ppsspp_inflight_frames"))
			return "No buffer";
	}
	static const struct { const char *key, *value; } table[] = {
		{"ppsspp_backend", "none"},                    // no GL context: the software renderer
		{"ppsspp_software_rendering", "enabled"},
		{"ppsspp_internal_resolution", "480x272"},
		{"ppsspp_cropto16x9", "disabled"},
		{"ppsspp_frameskip", "0"},
		{"ppsspp_auto_frameskip", "disabled"},
		{"ppsspp_frame_duplication", "disabled"},
		{"ppsspp_detect_vsync_swap_interval", "disabled"},
		{"ppsspp_language", "English"},
		{"ppsspp_fast_memory", "enabled"},
		{"ppsspp_ignore_bad_memory_access", "enabled"},
		{"ppsspp_io_timing_method", "Fast"},           // not "Host": no host time in the guest
		{"ppsspp_force_lag_sync", "disabled"},
		{"ppsspp_locked_cpu_speed", "0"},
		{"ppsspp_cache_iso", "disabled"},
		{"ppsspp_cheats", "disabled"},
		{"ppsspp_psp_model", "psp_2000_3000"},
		{"ppsspp_button_preference", "Cross"},
		{"ppsspp_analog_is_circular", "disabled"},
		{"ppsspp_analog_deadzone", "0.0"},
		{"ppsspp_analog_sensitivity", "1.0"},
		{"ppsspp_memstick_inserted", "enabled"},
		{"ppsspp_depth_raster", "off"},           // its worker is a thread
		{"ppsspp_enable_wlan", "disabled"},
		{"ppsspp_enable_upnp", "disabled"},
		{"ppsspp_texture_replacement", "disabled"},
	};
	for (const auto &e : table)
		if (!strcmp(e.key, key))
			return e.value;
	// The MAC address, one hex digit a key (ppsspp_change_mac_address01..12): fixed, since
	// PPSSPP would otherwise make one up from the wall clock.
	static const char kMac[] = "020000000001";
	static char digit[2];
	const char *prefix = "ppsspp_change_mac_address";
	if (!strncmp(key, prefix, strlen(prefix))) {
		int i = atoi(key + strlen(prefix)) - 1;
		if (i >= 0 && i < 12) {
			digit[0] = kMac[i];
			return digit;
		}
	}
	return nullptr;
}

uintptr_t CurrentFramebuffer() { return 0; } // the canvas

retro_proc_address_t ProcAddress(const char *sym) {
	return (retro_proc_address_t)emscripten_webgl_get_proc_address(sym);
}

// The canvas is Module.canvas (an OffscreenCanvas in the worker): Emscripten resolves "#canvas"
// through specialHTMLTargets, and a worker has no document (as the N64 core's pa_bind_canvas).
EM_JS(int, pa_bind_canvas, (void), {
	if (!Module['canvas']) return 0;
	specialHTMLTargets['#canvas'] = Module['canvas'];
	return 1;
});

// A WebGL2 context on the canvas, current from here on. 0, or -3 without Module.canvas, -1 no WebGL2, -2 not current.
int MakeGlContext() {
	if (!pa_bind_canvas())
		return -3;
	EmscriptenWebGLContextAttributes attrs;
	emscripten_webgl_init_context_attributes(&attrs);
	attrs.majorVersion = 2;
	attrs.minorVersion = 0;
	attrs.alpha = EM_FALSE;
	attrs.depth = EM_TRUE;
	attrs.stencil = EM_TRUE;
	attrs.antialias = EM_FALSE;
	attrs.premultipliedAlpha = EM_FALSE;
	attrs.preserveDrawingBuffer = EM_FALSE; // the worker takes each frame as an ImageBitmap
	attrs.powerPreference = EM_WEBGL_POWER_PREFERENCE_HIGH_PERFORMANCE;
	attrs.enableExtensionsByDefault = EM_TRUE;
	emscripten_set_canvas_element_size("#canvas", kWidth, kHeight);
	g.glCtx = emscripten_webgl_create_context("#canvas", &attrs);
	if (g.glCtx <= 0) {
		g.glCtx = 0;
		return -1;
	}
	if (emscripten_webgl_make_context_current(g.glCtx) != EMSCRIPTEN_RESULT_SUCCESS)
		return -2;
	return 0;
}

bool Environment(unsigned cmd, void *data) {
	switch (cmd) {
	case RETRO_ENVIRONMENT_GET_LOG_INTERFACE:
		static_cast<retro_log_callback *>(data)->log = LogCb;
		return true;
	case RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY:
		*static_cast<const char **>(data) = kSystemDir;
		return true;
	case RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY:
		*static_cast<const char **>(data) = kSaveDir;
		return true;
	case RETRO_ENVIRONMENT_GET_VARIABLE: {
		auto *var = static_cast<retro_variable *>(data);
		var->value = var->key ? Variable(var->key) : nullptr;
		return var->value != nullptr;
	}
	case RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE:
		*static_cast<bool *>(data) = false;
		return true;
	case RETRO_ENVIRONMENT_SET_PIXEL_FORMAT:
		return *static_cast<retro_pixel_format *>(data) == RETRO_PIXEL_FORMAT_XRGB8888;
	case RETRO_ENVIRONMENT_GET_INPUT_BITMASKS:
		return true;
	case RETRO_ENVIRONMENT_GET_LANGUAGE:
		*static_cast<unsigned *>(data) = RETRO_LANGUAGE_ENGLISH;
		return true;
	case RETRO_ENVIRONMENT_GET_FASTFORWARDING:
		*static_cast<bool *>(data) = false;
		return true;
	case RETRO_ENVIRONMENT_GET_USERNAME:
		*static_cast<const char **>(data) = "PlayAgain";
		return true;
	case RETRO_ENVIRONMENT_SET_HW_RENDER: {
		// GL only: the WebGL2 context pa_init made is current; its default framebuffer is the canvas.
		if (!g.gl)
			return false;
		auto *cb = static_cast<retro_hw_render_callback *>(data);
		if (cb->context_type != RETRO_HW_CONTEXT_OPENGLES2 && cb->context_type != RETRO_HW_CONTEXT_OPENGLES3 &&
		    cb->context_type != RETRO_HW_CONTEXT_OPENGL)
			return false;
		cb->get_current_framebuffer = CurrentFramebuffer;
		cb->get_proc_address = ProcAddress;
		g.hw = *cb;
		return true;
	}
	case RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER:
		if (!g.gl)
			return false;
		*static_cast<retro_hw_context_type *>(data) = RETRO_HW_CONTEXT_OPENGLES3;
		return true;
	case RETRO_ENVIRONMENT_GET_VFS_INTERFACE:       // libretro-common's own stdio VFS
	case RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION:  // the legacy SET_VARIABLES path, ignored
	case RETRO_ENVIRONMENT_GET_MESSAGE_INTERFACE_VERSION:
		return false;
	case RETRO_ENVIRONMENT_SHUTDOWN:
		g.failed = true;
		return true;
	default:
		// SET_MESSAGE, SET_GEOMETRY, SET_INPUT_DESCRIPTORS, SET_VARIABLES and the like: noted, nothing to do.
		return true;
	}
}

void VideoRefresh(const void *data, unsigned width, unsigned height, size_t pitch) {
	if (!data || width == 0 || height == 0)
		return;
	if (data == RETRO_HW_FRAME_BUFFER_VALID) {
		// GL: the frame is on the canvas already.
		g.fbWidth = (int)width;
		g.fbHeight = (int)height;
		g.presented = true;
		return;
	}
	width = std::min<unsigned>(width, kWidth);
	height = std::min<unsigned>(height, kHeight);
	g.fbWidth = (int)width;
	g.fbHeight = (int)height;
	// XRGB8888 (B, G, R, X in memory) to R, G, B, 0xFF, ready for an ImageData.
	for (unsigned y = 0; y < height; ++y) {
		const uint8_t *src = static_cast<const uint8_t *>(data) + y * pitch;
		uint8_t *dst = g.fb + y * width * 4;
		for (unsigned x = 0; x < width; ++x) {
			dst[x * 4 + 0] = src[x * 4 + 2];
			dst[x * 4 + 1] = src[x * 4 + 1];
			dst[x * 4 + 2] = src[x * 4 + 0];
			dst[x * 4 + 3] = 0xFF;
		}
	}
}

size_t AudioBatch(const int16_t *data, size_t frames) {
	for (size_t i = 0; i < frames; ++i) {
		if (g.ringWrite - g.ringRead >= (uint32_t)kRingFrames)
			g.ringRead++; // full: the oldest frame goes
		uint32_t at = (g.ringWrite % kRingFrames) * 2;
		g.ring[at] = data[i * 2];
		g.ring[at + 1] = data[i * 2 + 1];
		g.ringWrite++;
	}
	return frames;
}

void AudioSample(int16_t left, int16_t right) {
	int16_t frame[2] = {left, right};
	AudioBatch(frame, 1);
}

void InputPoll() {}

// PlayAgain's mask as libretro's joypad: X is △, A is ○, B is ✕, Y is □ (libretro.cpp's retro_input).
int16_t InputState(unsigned port, unsigned device, unsigned index, unsigned id) {
	if (port != 0)
		return 0;
	if (device == RETRO_DEVICE_JOYPAD) {
		static const struct { uint32_t pa; unsigned retro; } map[] = {
			{PA_UP, RETRO_DEVICE_ID_JOYPAD_UP}, {PA_DOWN, RETRO_DEVICE_ID_JOYPAD_DOWN},
			{PA_LEFT, RETRO_DEVICE_ID_JOYPAD_LEFT}, {PA_RIGHT, RETRO_DEVICE_ID_JOYPAD_RIGHT},
			{PA_X, RETRO_DEVICE_ID_JOYPAD_X}, {PA_A, RETRO_DEVICE_ID_JOYPAD_A},
			{PA_B, RETRO_DEVICE_ID_JOYPAD_B}, {PA_Y, RETRO_DEVICE_ID_JOYPAD_Y},
			{PA_L1, RETRO_DEVICE_ID_JOYPAD_L}, {PA_R1, RETRO_DEVICE_ID_JOYPAD_R},
			{PA_START, RETRO_DEVICE_ID_JOYPAD_START}, {PA_SELECT, RETRO_DEVICE_ID_JOYPAD_SELECT},
		};
		int16_t bits = 0;
		for (const auto &m : map)
			if (g.keys & m.pa)
				bits |= (int16_t)(1 << m.retro);
		if (id == RETRO_DEVICE_ID_JOYPAD_MASK)
			return bits;
		return (bits >> id) & 1;
	}
	if (device == RETRO_DEVICE_ANALOG && index == RETRO_DEVICE_INDEX_ANALOG_LEFT) {
		if (id == RETRO_DEVICE_ID_ANALOG_X)
			return g.axisX;
		if (id == RETRO_DEVICE_ID_ANALOG_Y)
			return g.axisY;
	}
	return 0;
}

// --- files ---------------------------------------------------------------------------------------

void MakeDirs(const std::string &path) {
	std::string at;
	size_t pos = 0;
	while (pos != std::string::npos) {
		pos = path.find('/', pos + 1);
		at = path.substr(0, pos);
		if (!at.empty())
			mkdir(at.c_str(), 0777);
	}
}

// Every file under `dir`, as paths relative to `base`, sorted so an export is the same bytes each time.
void ListFiles(const std::string &base, const std::string &rel, std::vector<std::string> *out) {
	std::string dir = rel.empty() ? base : base + "/" + rel;
	DIR *d = opendir(dir.c_str());
	if (!d)
		return;
	std::vector<std::string> names;
	while (dirent *e = readdir(d)) {
		if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
			continue;
		names.push_back(e->d_name);
	}
	closedir(d);
	std::sort(names.begin(), names.end());
	for (const std::string &name : names) {
		std::string child = rel.empty() ? name : rel + "/" + name;
		struct stat st;
		if (stat((base + "/" + child).c_str(), &st) != 0)
			continue;
		if (S_ISDIR(st.st_mode))
			ListFiles(base, child, out);
		else if (S_ISREG(st.st_mode))
			out->push_back(child);
	}
}

bool ReadFile(const std::string &path, std::vector<uint8_t> *out) {
	FILE *f = fopen(path.c_str(), "rb");
	if (!f)
		return false;
	fseek(f, 0, SEEK_END);
	long n = ftell(f);
	fseek(f, 0, SEEK_SET);
	out->resize(n > 0 ? (size_t)n : 0);
	bool ok = n <= 0 || fread(out->data(), 1, (size_t)n, f) == (size_t)n;
	fclose(f);
	return ok;
}

void RemoveTree(const std::string &path) {
	DIR *d = opendir(path.c_str());
	if (!d)
		return;
	std::vector<std::string> names;
	while (dirent *e = readdir(d))
		if (strcmp(e->d_name, ".") && strcmp(e->d_name, ".."))
			names.push_back(e->d_name);
	closedir(d);
	for (const std::string &name : names) {
		std::string child = path + "/" + name;
		struct stat st;
		if (stat(child.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) {
			RemoveTree(child);
			rmdir(child.c_str());
		} else {
			unlink(child.c_str());
		}
	}
}

// The save archive (README "Game saves"): "PPSV", u32 version 1, u32 count, then per file
// u16 path length, the path (UTF-8, relative to PSP/SAVEDATA, '/' between parts), u32 size, the bytes.
std::vector<uint8_t> PackSaves() {
	std::vector<std::string> files;
	ListFiles(kSavedata, "", &files);
	std::vector<uint8_t> out = {'P', 'P', 'S', 'V', 1, 0, 0, 0};
	auto u32 = [&](uint32_t v) { for (int i = 0; i < 4; ++i) out.push_back((uint8_t)(v >> (8 * i))); };
	u32((uint32_t)files.size());
	std::vector<uint8_t> bytes;
	for (const std::string &rel : files) {
		bytes.clear();
		ReadFile(std::string(kSavedata) + "/" + rel, &bytes);
		out.push_back((uint8_t)(rel.size() & 0xFF));
		out.push_back((uint8_t)(rel.size() >> 8));
		out.insert(out.end(), rel.begin(), rel.end());
		u32((uint32_t)bytes.size());
		out.insert(out.end(), bytes.begin(), bytes.end());
	}
	return out;
}

uint64_t HashSaves() {
	std::vector<uint8_t> packed = PackSaves();
	return XXH3_64bits(packed.data(), packed.size());
}

bool SafeRelative(const std::string &rel) {
	// A NUL would cut the path short where the file system sees it ("a/..\0x" is "a/..").
	if (rel.empty() || rel[0] == '/' || rel.find('\\') != std::string::npos || rel.find('\0') != std::string::npos)
		return false;
	size_t start = 0;
	while (start <= rel.size()) {
		size_t end = rel.find('/', start);
		std::string part = rel.substr(start, end == std::string::npos ? std::string::npos : end - start);
		if (part.empty() || part == "." || part == "..")
			return false;
		if (end == std::string::npos)
			break;
		start = end + 1;
	}
	return true;
}

void ApplyHostDefaults() {
	// One thread, no host time, no network: what the software proof and lockstep need.
	g_Config.bSeparateSASThread = false;
	g_Config.iDepthRasterMode = (int)DepthRasterMode::OFF; // its worker is a thread
	g_Config.bCacheFullIsoInRam = false;
	g_Config.iRewindSnapshotInterval = 0;
	g_Config.bForceLagSync = false;
	g_Config.bEnableWlan = false;
	g_Config.bEnableCheats = false;
	g_Config.iIOTimingMethod = IOTIMING_FAST;
	g_Config.sMACAddress = "02:00:00:00:00:01"; // CreateRandMAC seeds from time()
	g_Config.sNickName = "PlayAgain";
}

} // namespace

// Emscripten without pthreads has no thread names; PPSSPP names the one thread it has.
extern "C" int pthread_setname_np(pthread_t, const char *) { return 0; }

// The host's clock and time zone stay out of the guest (the link wraps these, see build.sh):
// time() is the session clock plus the emulated time since boot (libkirk's PRNG and the
// MAC address generator read it), and local time is UTC, whatever zone the browser is in
// (sceRtc's local-time calls and its timegm fallback, which goes through mktime).
extern "C" time_t __wrap_time(time_t *out) {
	time_t t = (time_t)g.clock;
	if (g.loaded && currentMIPS)
		t += (time_t)(CoreTiming::GetGlobalTimeUs() / 1000000);
	if (out)
		*out = t;
	return t;
}
extern "C" struct tm *__wrap_localtime(const time_t *t) { return gmtime(t); }
extern "C" struct tm *__wrap_localtime_r(const time_t *t, struct tm *out) { return gmtime_r(t, out); }
extern "C" time_t __wrap_mktime(struct tm *tm) { return timegm(tm); }

// --- the C ABI -------------------------------------------------------------------------------------

/**
 * 1: PPSSPP's GL renderer on a WebGL2 context on Module.canvas (an OffscreenCanvas); 0: the software
 * renderer (the default). Before pa_init only; 0, or -1 once inited.
 */
PA_EXPORT int pa_set_renderer(int gl) {
	if (g.inited)
		return -1;
	g.gl = gl != 0;
	return 0;
}

/** 1 when this module draws with GL. */
PA_EXPORT int pa_renderer() { return g.gl ? 1 : 0; }

/** 1 if a GL frame reached the canvas since the last call (the worker takes it then); always 0 in software. */
PA_EXPORT int pa_presented() {
	bool was = g.presented;
	g.presented = false;
	return was ? 1 : 0;
}

/**
 * A fresh PPSSPP; sound comes out at 44100 Hz whatever `sampleRate` says (pa_audio_rate). 0 on success.
 * With the GL renderer: -3 without Module.canvas, -1 no WebGL2, -2 the context would not be current;
 * nothing is inited then, so pa_set_renderer(0) and pa_init again give the software renderer.
 */
PA_EXPORT int pa_init(int sampleRate) {
	(void)sampleRate;
	if (g.inited)
		return 0;
	if (g.gl) {
		int made = MakeGlContext();
		if (made != 0)
			return made;
	}
	MakeDirs(std::string(kSystemDir) + "/PPSSPP");
	MakeDirs(kSavedata);
	// pa_saves_dirty's baseline: the memory stick as it is now (empty, or what an import puts there),
	// so a game that saves before the first pa_saves_dirty call is still reported.
	g.savesHash = HashSaves();
	g.savesHashed = true;
	retro_set_environment(Environment);
	retro_set_video_refresh(VideoRefresh);
	retro_set_audio_sample(AudioSample);
	retro_set_audio_sample_batch(AudioBatch);
	retro_set_input_poll(InputPoll);
	retro_set_input_state(InputState);
	retro_init();
	ApplyHostDefaults();
	g.inited = true;
	return 0;
}

/** Log level: -1 errors only, 0 warnings and errors (the default), 1 everything. */
PA_EXPORT void pa_set_verbose(int level) { g.verbose = level; }

/** The session clock (unix seconds) the PSP's RTC starts from at boot; nothing else of the host's time reaches the guest. */
PA_EXPORT void pa_set_clock(double unixSeconds) {
	g.clock = (int64_t)unixSeconds;
	if (g.loaded)
		RtcSetBaseTime((int32_t)g.clock, 0);
}

/**
 * Boots the game at `path` in the module's file system (an ISO, CSO, PBP, ELF or CHD that PPSSPP reads
 * through its own loaders). 0 on success; -1 not inited or already loaded, -2 PPSSPP refused it
 * (pa_error says why).
 */
PA_EXPORT int pa_load(const char *path) {
	if (!g.inited || g.loaded || !path)
		return -1;
	g.gamePath = path;
	retro_game_info info = {};
	info.path = g.gamePath.c_str();
	// Without threads the loader has already run: a file PPSSPP can't boot fails here, not a frame later.
	if (!retro_load_game(&info) || !PSP_CoreParameter().errorString.empty()) {
		g.failed = true;
		return -2;
	}
	retro_system_av_info av;
	retro_get_system_av_info(&av); // sets the render size, as RetroArch's call after a load does
	// GL: the context exists and is current; RetroArch hands it over right after the load.
	if (g.gl && g.hw.context_reset)
		g.hw.context_reset();
	// The loader ran in place (no threads), so the kernel and its RTC exist now.
	RtcSetBaseTime((int32_t)g.clock, 0);
	g.loaded = true;
	return 0;
}

/** Writes `len` bytes at `ptr` to /pa/game/<name> and boots it (pa_load). */
PA_EXPORT int pa_load_bytes(const uint8_t *ptr, int len, const char *name) {
	if (!ptr || len <= 0 || !name || !*name || strchr(name, '/'))
		return -1;
	MakeDirs("/pa/game");
	std::string path = std::string("/pa/game/") + name;
	FILE *f = fopen(path.c_str(), "wb");
	if (!f)
		return -1;
	bool ok = fwrite(ptr, 1, (size_t)len, f) == (size_t)len;
	fclose(f);
	return ok ? pa_load(path.c_str()) : -1;
}

/** Why the boot failed, or "". */
PA_EXPORT const char *pa_error() {
	if (!Libretro::g_bootErrorString.empty())
		return Libretro::g_bootErrorString.c_str();
	return PSP_CoreParameter().errorString.c_str();
}

/** PlayAgain's 16-bit button mask (protocol.ts BUTTONS): △ = x, ○ = a, ✕ = b, □ = y, L = l1, R = r1. */
PA_EXPORT void pa_set_keys(int mask) { g.keys = (uint32_t)mask & 0xFFFF; }

/** The analog nub, -32768..32767; y grows downwards. */
PA_EXPORT void pa_set_axes(int x, int y) {
	g.axisX = (int16_t)std::max(-32768, std::min(32767, x));
	g.axisY = (int16_t)std::max(-32768, std::min(32767, y));
}

/**
 * One retro_run: the game runs up to its next flip. That is one vblank for a 60 fps game, two for a
 * 30 fps one, up to ten while it shows a still picture (sceDisplay flips at least every ten), so
 * the call returns the emulated microseconds it covered and the caller's clock runs on those, not
 * on a fixed 60 a second (paced as one vblank a call, a 30 fps game ran at double speed and its
 * sound overflowed). -1 if no game runs (not loaded, or the boot or the game failed).
 */
PA_EXPORT int pa_run_frame() {
	if (!g.loaded || g.failed)
		return -1;
	const uint64_t before = currentMIPS ? CoreTiming::GetGlobalTimeUs() : 0;
	const double started = emscripten_get_now();
	retro_run();
	if (g.failed)
		return -1;
	g.frames++;
	// The JIT compiles what got hot, between frames (host time only: the guest's clocks don't see it).
	if (PaWasmJit::Active())
		PaWasmJit::Frame(emscripten_get_now() - started);
	const uint64_t after = currentMIPS ? CoreTiming::GetGlobalTimeUs() : before;
	return after > before ? (int)std::min<uint64_t>(after - before, 1000000) : 0;
}

/** The last frame, RGBA, pa_fb_width() × pa_fb_height() (480 × 272), stride width × 4. */
PA_EXPORT const uint8_t *pa_fb() { return g.fb; }
PA_EXPORT int pa_fb_width() { return g.fbWidth; }
PA_EXPORT int pa_fb_height() { return g.fbHeight; }

/** Stereo s16 frames waiting; pa_read_audio copies up to `maxFrames` of them and returns how many. */
PA_EXPORT int pa_audio_available() { return (int)(g.ringWrite - g.ringRead); }
PA_EXPORT int pa_read_audio(int16_t *out, int maxFrames) {
	int n = 0;
	while (n < maxFrames && g.ringRead != g.ringWrite) {
		uint32_t at = (g.ringRead % kRingFrames) * 2;
		out[n * 2] = g.ring[at];
		out[n * 2 + 1] = g.ring[at + 1];
		g.ringRead++;
		n++;
	}
	return n;
}
PA_EXPORT int pa_audio_rate() { return kAudioRate; }
/** 60000/1001 Hz, in µHz. */
PA_EXPORT int pa_frame_rate() { return 59940060; }

/** A state's size now (it can grow a little as the game runs; allow some room). 0 before the first frame. */
PA_EXPORT int pa_state_size() {
	if (!gpu)
		return 0;
	SaveState::SaveStart state;
	return (int)CChunkFileReader::MeasurePtr(state);
}

/** Writes a state (retro_serialize's blob); returns its length, -1 if `max` is short or nothing runs. */
PA_EXPORT int pa_save_state(uint8_t *ptr, int max) {
	if (!gpu || !ptr || max <= 0)
		return -1;
	SaveState::SaveStart state;
	uint8_t *buffer = ptr;
	size_t size = (size_t)max;
	if (CChunkFileReader::MeasureAndSavePtr(state, &buffer, &size) != CChunkFileReader::ERROR_NONE)
		return -1;
	return (int)size;
}

/** Loads a state of `len` bytes; 0 on success. */
PA_EXPORT int pa_load_state(uint8_t *ptr, int len) {
	if (!gpu || !ptr || len <= 0)
		return -1;
	SaveState::SaveStart state;
	std::string error;
	if (CChunkFileReader::LoadPtr(ptr, (size_t)len, state, &error) != CChunkFileReader::ERROR_NONE) {
		LogCb(RETRO_LOG_ERROR, "pa_load_state: %s\n", error.c_str());
		return -2;
	}
	return 0;
}

/** PSP RAM in place: pa_ram_size() bytes from 0x08000000. */
PA_EXPORT uint8_t *pa_ram_ptr() {
	return Memory::IsActive() ? Memory::GetPointerWriteUnchecked(PSP_GetKernelMemoryBase()) : nullptr;
}
PA_EXPORT int pa_ram_size() { return Memory::IsActive() ? (int)Memory::g_MemorySize : 0; }

/** XXH3 of PSP RAM and the CPU's registers (GPRs, FPU, VFPU, pc, hi, lo, fcr31), folded to 32 bits. */
PA_EXPORT uint32_t pa_digest() {
	XXH3_state_t *s = XXH3_createState();
	XXH3_64bits_reset(s);
	if (uint8_t *ram = pa_ram_ptr())
		XXH3_64bits_update(s, ram, (size_t)pa_ram_size());
	if (currentMIPS) {
		const MIPSState *m = currentMIPS;
		XXH3_64bits_update(s, m->r, sizeof(m->r));
		XXH3_64bits_update(s, m->fi, sizeof(m->fi));
		XXH3_64bits_update(s, m->v, sizeof(m->v));
		XXH3_64bits_update(s, m->vfpuCtrl, sizeof(m->vfpuCtrl));
		const uint32_t rest[4] = {m->pc, m->hi, m->lo, m->fcr31};
		XXH3_64bits_update(s, rest, sizeof(rest));
	}
	uint64_t h = XXH3_64bits_digest(s);
	XXH3_freeState(s);
	return (uint32_t)(h ^ (h >> 32));
}

/** The game's saves as one archive (README "Game saves"): its size, and a copy (returns the length, -1 if `max` is short). */
PA_EXPORT int pa_saves_size() { return (int)PackSaves().size(); }
PA_EXPORT int pa_saves_export(uint8_t *ptr, int max) {
	std::vector<uint8_t> packed = PackSaves();
	if (!ptr || max < 0 || (size_t)max < packed.size())
		return -1;
	memcpy(ptr, packed.data(), packed.size());
	return (int)packed.size();
}

/** Replaces PSP/SAVEDATA with an archive from pa_saves_export. 0 on success, -1 malformed (nothing changed). */
PA_EXPORT int pa_saves_import(const uint8_t *ptr, int len) {
	if (!ptr || len < 12 || memcmp(ptr, "PPSV", 4) != 0)
		return -1;
	auto u32 = [&](size_t at) { return (uint32_t)ptr[at] | (uint32_t)ptr[at + 1] << 8 | (uint32_t)ptr[at + 2] << 16 | (uint32_t)ptr[at + 3] << 24; };
	if (u32(4) != 1)
		return -1;
	struct Entry { std::string rel; size_t at, size; };
	std::vector<Entry> entries;
	size_t at = 12;
	for (uint32_t i = 0, n = u32(8); i < n; ++i) {
		if (at + 2 > (size_t)len)
			return -1;
		size_t plen = ptr[at] | ptr[at + 1] << 8;
		at += 2;
		if (at + plen + 4 > (size_t)len)
			return -1;
		std::string rel((const char *)ptr + at, plen);
		at += plen;
		size_t size = u32(at);
		at += 4;
		// size_t is 32 bits in wasm: `at + size` would wrap for a size near 4 GB, so compare against what is left.
		if (size > (size_t)len - at || !SafeRelative(rel))
			return -1;
		entries.push_back({rel, at, size});
		at += size;
	}
	// Each path once, and none both a file and a directory ("A" and "A/B"): an archive that could
	// only be written in part is refused before anything is removed.
	std::vector<std::string> paths;
	for (const Entry &e : entries)
		paths.push_back(e.rel);
	std::sort(paths.begin(), paths.end());
	for (size_t i = 0; i < paths.size(); ++i) {
		if (i + 1 < paths.size() && paths[i] == paths[i + 1])
			return -1;
		const std::string dir = paths[i] + "/";
		auto next = std::lower_bound(paths.begin(), paths.end(), dir);
		if (next != paths.end() && next->compare(0, dir.size(), dir) == 0)
			return -1;
	}
	RemoveTree(kSavedata);
	for (const Entry &e : entries) {
		std::string path = std::string(kSavedata) + "/" + e.rel;
		MakeDirs(path.substr(0, path.rfind('/')));
		FILE *f = fopen(path.c_str(), "wb");
		if (!f)
			continue;
		fwrite(ptr + e.at, 1, e.size, f);
		fclose(f);
	}
	g.savesHash = HashSaves();
	g.savesHashed = true;
	return 0;
}

/** 1 if the game's saves changed since the last call (or since an import); 0 if not. Reads the tree: call it now and then, not every frame. */
PA_EXPORT int pa_saves_dirty() {
	uint64_t h = HashSaves();
	bool changed = g.savesHashed ? h != g.savesHash : false;
	g.savesHash = h;
	g.savesHashed = true;
	return changed ? 1 : 0;
}

/** Frames run since the load. */
PA_EXPORT uint32_t pa_frame_count() { return g.frames; }

// --- the WebAssembly JIT (pa_wasmjit.cpp; README "The JIT") ------------------------------------------

/** 1: the CPU compiles hot IR blocks to WebAssembly; 0: the IR interpreter alone (the default). Before pa_load; 0, or -1 once loaded. */
PA_EXPORT int pa_set_jit(int on) {
	if (g.loaded)
		return -1;
	PaWasmJit::SetWanted(on != 0);
	return 0;
}

/** 1 when the running CPU is the JIT. */
PA_EXPORT int pa_jit_active() { return PaWasmJit::Active() ? 1 : 0; }

/** Compiles what got hot now (pa_run_frame does this itself after each frame). */
PA_EXPORT void pa_jit_service() { PaWasmJit::Frame(0); }

/** Tuning for tests and measurements: 1 threshold, 2 batch, 3 island factor, 4 block cap, 5 budget (µs), 6 modules a frame, 7 canary, 8 canary window (frames), 9 (tests) stop as the canary does. 0, or -1 unknown. */
PA_EXPORT int pa_jit_config(int key, int value) { return PaWasmJit::Configure(key, value); }

/** The JIT's counters as a JSON C string; pa_jit_stats_reset starts a new window for the per-window ones. */
PA_EXPORT const char *pa_jit_stats() { return PaWasmJit::StatsJson(); }
PA_EXPORT void pa_jit_stats_reset() { PaWasmJit::ResetWindow(); }

/** The JIT's fuzz: n random blocks, each run by the interpreter and as compiled code; how many differed (-1: could not run). */
PA_EXPORT int pa_jit_selftest(int seed, int n) { return PaWasmJit::SelfTest((uint32_t)seed, n); }
PA_EXPORT const char *pa_jit_selftest_report() { return PaWasmJit::SelfTestReport(); }
