#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Ask a running libretro core which joypad id it names as which button. A core hands the frontend its input descriptors when a game loads (RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, 11): its published interface, observed with the core run as a closed box, its source never opened. The evidence for ``libretro_frames.CORE_BUTTONS``. python scripts/libretro_buttons.py CORE.so CARTRIDGE.bin """ from __future__ import annotations import ctypes as C import sys import tempfile from pathlib import Path ENV_SET_INPUT_DESCRIPTORS = 11 ENV_GET_SYSTEM_DIRECTORY = 9 ENV_GET_SAVE_DIRECTORY = 31 ENV_SET_PIXEL_FORMAT = 10 RETRO_DEVICE_JOYPAD = 1 class Descriptor(C.Structure): _fields_ = ( ("port", C.c_uint), ("device", C.c_uint), ("index", C.c_uint), ("id", C.c_uint), ("description", C.c_char_p), ) class GameInfo(C.Structure): _fields_ = ( ("path", C.c_char_p), ("data", C.c_void_p), ("size", C.c_size_t), ("meta", C.c_char_p), ) def descriptors(core_path: Path, cartridge: Path) -> list[tuple[int, str]]: """Pad 1's (libretro id, the core's name for it), in the order the core gives them.""" core = C.CDLL(str(core_path)) work = tempfile.mkdtemp(prefix="libretro-buttons-").encode() found: list[tuple[int, str]] = [] def environment(command: int, data: int) -> bool: command &= 0xFFFF if command == ENV_SET_INPUT_DESCRIPTORS: table = C.cast(data, C.POINTER(Descriptor)) i = 0 while table[i].description: entry = table[i] if entry.port == 0 and entry.device == RETRO_DEVICE_JOYPAD: found.append((entry.id, entry.description.decode())) i += 1 return True if command in (ENV_GET_SYSTEM_DIRECTORY, ENV_GET_SAVE_DIRECTORY): C.cast(data, C.POINTER(C.c_char_p))[0] = work return True return command == ENV_SET_PIXEL_FORMAT callbacks = [ (core.retro_set_environment, C.CFUNCTYPE(C.c_bool, C.c_uint, C.c_void_p)(environment)), ( core.retro_set_video_refresh, C.CFUNCTYPE(None, C.c_void_p, C.c_uint, C.c_uint, C.c_size_t)(lambda *a: None), ), (core.retro_set_audio_sample, C.CFUNCTYPE(None, C.c_int16, C.c_int16)(lambda *a: None)), ( core.retro_set_audio_sample_batch, C.CFUNCTYPE(C.c_size_t, C.c_void_p, C.c_size_t)(lambda *a: 0), ), (core.retro_set_input_poll, C.CFUNCTYPE(None)(lambda: None)), ( core.retro_set_input_state, C.CFUNCTYPE(C.c_int16, C.c_uint, C.c_uint, C.c_uint, C.c_uint)(lambda *a: 0), ), ] for setter, callback in callbacks: setter(callback) core.retro_init() image = cartridge.read_bytes() buffer = C.create_string_buffer(image, len(image)) info = GameInfo(str(cartridge).encode(), C.cast(buffer, C.c_void_p), len(image), None) core.retro_load_game.argtypes = [C.POINTER(GameInfo)] core.retro_load_game(C.byref(info)) return found def main() -> int: for libretro_id, name in descriptors(Path(sys.argv[1]), Path(sys.argv[2])): print(f"{libretro_id:3d} {name}") return 0 if __name__ == "__main__": sys.exit(main())