-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative.ts
More file actions
682 lines (594 loc) · 24.6 KB
/
native.ts
File metadata and controls
682 lines (594 loc) · 24.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/**
* native.ts — Native RetroArch orchestration for Retrobox
*
* Manages the lifecycle of native RetroArch running under Cage (Wayland compositor).
* Browser Retrobox UI handles game selection → this module launches native RetroArch
* for rendering → on quit, kiosk service restarts automatically.
*
* Dynamically imported by server.ts — if import fails, web-only mode.
*/
import { execSync, spawn, type ChildProcess } from "child_process";
import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync } from "fs";
import { join, extname } from "path";
// ── Paths ───────────────────────────────────────────────────────────────────
const RETROARCH_BIN = "/nix/store/fi2vcpb1xv0b4592nhly5vcbv622xckn-retroarch-bare-1.21.0/bin/retroarch";
const CORES_DIR = "/nix/store/68hizy252msdd7br3jig3j3310ldmy13-retroarch-with-cores-1.21.0/lib/retroarch/cores";
const GLES3_CORE = "/nix/store/qgaqgc3zz7ivfjvbnzwa8scyg7vk83lf-libretro-mupen64plus-next-gles3-0-unstable-2025-11-14/lib/retroarch/cores/mupen64plus_next_gles3_libretro.so";
const AUTOCONFIG_DIR = "/nix/store/zrk72vsvnwi3sdxhlh48629q9s7gk36c-retroarch-joypad-autoconfig-1.22.0/share/libretro/autoconfig";
const CAGE_BIN = "/run/current-system/sw/bin/cage";
const SYSTEMCTL = "/run/current-system/sw/bin/systemctl";
const KIOSK_HOME = "/var/cache/kiosk-home";
const RETROARCH_CFG = join(KIOSK_HOME, ".config/retroarch/retroarch.cfg");
const CORE_OPTIONS_DIR = join(KIOSK_HOME, ".config/retroarch/config");
const SAVES_DIR = join(KIOSK_HOME, ".config/retroarch/saves");
const STATES_DIR = join(KIOSK_HOME, ".config/retroarch/states");
const NATIVE_FLAG = "/tmp/retroarch-native";
const KIOSK_OVERRIDE_DIR = "/run/systemd/system/kiosk.service.d";
const EXTRACT_DIR = join(KIOSK_HOME, ".cache/retroarch-extract");
const HDMI_AUDIO_CANDIDATES = [
{ status: "/sys/class/drm/card1-HDMI-A-1/status", device: "hdmi:CARD=vc4hdmi0,DEV=0" },
{ status: "/sys/class/drm/card1-HDMI-A-2/status", device: "hdmi:CARD=vc4hdmi1,DEV=0" },
];
// ── Systems that need uncompressed content ──────────────────────────────────
/** These cores can't load from zip — need extraction first */
const NEEDS_EXTRACTION = new Set(["psx", "n64"]);
/** Preferred content file extensions per system (in priority order) */
const CONTENT_EXTENSIONS: Record<string, string[]> = {
psx: [".cue", ".bin", ".img", ".iso", ".pbp", ".chd"],
n64: [".z64", ".n64", ".v64"],
};
function preferredAlsaDevice(): string {
for (const candidate of HDMI_AUDIO_CANDIDATES) {
try {
if (readFileSync(candidate.status, "utf-8").trim() === "connected") {
return candidate.device;
}
} catch {}
}
return HDMI_AUDIO_CANDIDATES[0].device;
}
// ── Core map ────────────────────────────────────────────────────────────────
/** Maps system ID → core .so filename (without path) */
export const NATIVE_CORE_MAP: Record<string, string> = {
n64: "mupen64plus_next_gles3_libretro.so",
snes: "snes9x_libretro.so",
gba: "mgba_libretro.so",
segaMD: "genesis_plus_gx_libretro.so",
arcade: "fbneo_libretro.so",
psx: "pcsx_rearmed_libretro.so",
};
/** Per-core option file names (RetroArch uses the core's "display name") */
const CORE_OPTION_DIRS: Record<string, string> = {
n64: "Mupen64Plus-Next",
snes: "Snes9x",
gba: "mGBA",
segaMD: "Genesis Plus GX",
arcade: "FinalBurn Neo",
psx: "PCSX-ReARMed",
};
// ── State ───────────────────────────────────────────────────────────────────
type NativeState = "idle" | "launching" | "running" | "stopping";
let state: NativeState = "idle";
let cageProcess: ChildProcess | null = null;
let currentCore: string | null = null;
let currentRom: string | null = null;
let exitCallback: ((code: number | null, signal: string | null) => void) | null = null;
// ── Platform probe ──────────────────────────────────────────────────────────
export interface NativeProbe {
supported: boolean;
retroarch: boolean;
cage: boolean;
seatd: boolean;
cores: Record<string, boolean>;
}
/** Check if native RetroArch mode is available on this platform */
export function probeNativeSupport(): NativeProbe {
const retroarch = existsSync(RETROARCH_BIN);
const cage = existsSync(CAGE_BIN);
let seatd = false;
try {
const out = execSync(`${SYSTEMCTL} is-active seatd 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }).trim();
seatd = out === "active";
} catch {}
const cores: Record<string, boolean> = {};
for (const [system, coreName] of Object.entries(NATIVE_CORE_MAP)) {
// N64 GLES3 core lives in a separate store path
if (system === "n64") {
cores[system] = existsSync(GLES3_CORE);
} else {
cores[system] = existsSync(join(CORES_DIR, coreName));
}
}
const supported = retroarch && cage && seatd && Object.values(cores).some(Boolean);
return { supported, retroarch, cage, seatd, cores };
}
// ── Core option writing ─────────────────────────────────────────────────────
/** Default core options per system (merged with any user overrides) */
const DEFAULT_CORE_OPTIONS: Record<string, Record<string, string>> = {
psx: {
"pcsx_rearmed_neon_interlace_enable": "disabled",
"pcsx_rearmed_neon_enhancement_enable": "enabled",
"pcsx_rearmed_neon_enhancement_no_main": "enabled",
"pcsx_rearmed_frameskip_type": "disabled",
"pcsx_rearmed_gpu_thread_rendering": "async",
"pcsx_rearmed_drc": "enabled",
"pcsx_rearmed_psxclock": "57",
"pcsx_rearmed_input_sensitivity": "1.00",
},
n64: {
"mupen64plus-cpucore": "cached_interpreter",
"mupen64plus-rdp-plugin": "gliden64",
"mupen64plus-rsp-plugin": "hle",
"mupen64plus-EnableNativeResFactor": "2",
"mupen64plus-FXAA": "1",
"mupen64plus-EnableHWLighting": "True",
"mupen64plus-EnableLODEmulation": "True",
"mupen64plus-EnableShadersStorage": "True",
"mupen64plus-ThreadedRenderer": "True",
"mupen64plus-EnableCopyColorToRDRAM": "Off",
"mupen64plus-EnableCopyDepthToRDRAM": "Off",
"mupen64plus-EnableCopyAuxToRDRAM": "False",
"mupen64plus-EnableCopyColorFromRDRAM": "False",
"mupen64plus-EnableFBEmulation": "True",
"mupen64plus-BilinearMode": "3point",
"mupen64plus-EnableTextureCache": "True",
"mupen64plus-MaxTxCacheSize": "8000",
},
};
/**
* Write core options file for a given system.
* Merges defaults with provided overrides.
* Uses sudo because kiosk-home is owned by kiosk user.
*/
export function writeCoreOptions(system: string, overrides?: Record<string, string>): void {
const dirName = CORE_OPTION_DIRS[system];
if (!dirName) return;
try {
const optDir = join(CORE_OPTIONS_DIR, dirName);
const optFile = join(optDir, `${dirName}.opt`);
// Ensure directory exists (needs sudo — owned by kiosk)
execSync(`/run/wrappers/bin/sudo mkdir -p "${optDir}"`, { timeout: 10000 });
// Read existing options if file exists
const existing: Record<string, string> = {};
if (existsSync(optFile)) {
try {
const content = execSync(`/run/wrappers/bin/sudo cat "${optFile}"`, { encoding: "utf-8", timeout: 10000 });
for (const line of content.split("\n")) {
const match = line.match(/^(.+?)\s*=\s*"(.+)"$/);
if (match) existing[match[1]] = match[2];
}
} catch {}
}
// Merge: existing ← defaults ← overrides
const defaults = DEFAULT_CORE_OPTIONS[system] || {};
const merged = { ...existing, ...defaults, ...overrides };
const lines = Object.entries(merged)
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, v]) => `${k} = "${v}"`);
const content = lines.join("\n") + "\n";
execSync(`/run/wrappers/bin/sudo tee "${optFile}" > /dev/null`, { input: content, timeout: 10000 });
console.log(`[native] Wrote core options: ${optFile}`);
} catch (e: any) {
console.warn(`[native] Failed to write core options for ${system}:`, e.message);
}
}
/**
* Ensure retroarch.cfg has optimal input latency + controller settings.
* Reads → patches → writes back. Uses sudo (kiosk-owned file).
*/
function ensureRetroarchCfg(): void {
// RetroAchievements from env vars
const raUser = process.env.RA_USERNAME || "";
const raToken = process.env.RA_TOKEN || "";
const OPTIMAL: Record<string, string> = {
// RetroAchievements
...(raUser && raToken ? {
"cheevos_enable": "true",
"cheevos_username": raUser,
"cheevos_token": raToken,
"cheevos_hardcore_mode_enable": "false",
"cheevos_badges_enable": "true",
"cheevos_unlock_sound_enable": "true",
} : {}),
// Input: late polling = reads joypad as late as possible before frame render
"input_poll_type_behavior": "2",
// GPU hard sync: CPU waits for GPU — reduces internal pipeline lag
"video_hard_sync": "true",
"video_hard_sync_frames": "1",
// Audio: lower buffer = less perceived lag (32ms safe, below may crackle)
"audio_latency": "32",
"audio_driver": "alsa",
"audio_device": preferredAlsaDevice(),
// Frame delay: hold CPU before rendering to absorb input at last moment
"video_frame_delay": "4",
"video_frame_delay_auto": "true",
// Controller quit combo: 4 = Start+Select (DS4-friendly)
"input_quit_gamepad_combo": "4",
// Menu toggle: 6 = Hold Start 2s
"input_menu_toggle_gamepad_combo": "6",
// Never save config on exit (preserves our settings)
"config_save_on_exit": "false",
// Absolute save paths (~ resolves wrong for kiosk user)
"savefile_directory": "/var/cache/kiosk-home/.config/retroarch/saves",
"savestate_directory": "/var/cache/kiosk-home/.config/retroarch/states",
// Sort saves into core subdirs (matches EmulatorJS save structure)
"sort_savefiles_enable": "true",
"sort_savestates_enable": "true",
// Always show FPS counter in native mode
"fps_show": "true",
};
try {
let content = "";
try {
content = execSync(`/run/wrappers/bin/sudo cat "${RETROARCH_CFG}"`, { encoding: "utf-8", timeout: 10000 });
} catch { return; }
const lines = content.split("\n");
const found = new Set<string>();
const patched = lines.map((line) => {
const match = line.match(/^(\S+)\s*=\s*/);
if (match && match[1] in OPTIMAL) {
found.add(match[1]);
return `${match[1]} = "${OPTIMAL[match[1]]}"`;
}
return line;
});
// Append any missing keys
for (const [k, v] of Object.entries(OPTIMAL)) {
if (!found.has(k)) patched.push(`${k} = "${v}"`);
}
execSync(`/run/wrappers/bin/sudo tee "${RETROARCH_CFG}" > /dev/null`, {
input: patched.join("\n"),
timeout: 10000,
});
console.log("[native] RetroArch cfg patched for low-latency input");
} catch (e: any) {
console.warn("[native] Failed to patch retroarch.cfg:", e.message);
}
}
// ── Kiosk lifecycle ─────────────────────────────────────────────────────────
/**
* Stop the kiosk service by creating a runtime override that replaces ExecStart.
* NixOS manages the service symlink, so `systemctl mask` doesn't work —
* we use a drop-in override instead.
*/
function stopKiosk(): boolean {
try {
// Create native flag
writeFileSync(NATIVE_FLAG, String(Date.now()));
// Create runtime override to prevent kiosk restart
execSync(`/run/wrappers/bin/sudo mkdir -p ${KIOSK_OVERRIDE_DIR}`, { timeout: 10000 });
execSync(
`sudo bash -c 'cat > ${KIOSK_OVERRIDE_DIR}/override.conf << EOF
[Service]
ExecStart=
ExecStart=/bin/true
EOF'`,
{ timeout: 10000 }
);
execSync(`/run/wrappers/bin/sudo ${SYSTEMCTL} daemon-reload`, { timeout: 15000 });
execSync(`/run/wrappers/bin/sudo ${SYSTEMCTL} stop kiosk.service`, { timeout: 30000 });
console.log("[native] Kiosk stopped");
return true;
} catch (e: any) {
try {
execSync(`/run/wrappers/bin/sudo rm -rf ${KIOSK_OVERRIDE_DIR}`, { timeout: 10000 });
execSync(`/run/wrappers/bin/sudo ${SYSTEMCTL} daemon-reload`, { timeout: 15000 });
} catch {}
console.error("[native] Failed to stop kiosk:", e.message);
return false;
}
}
/**
* Restart the kiosk service by removing the runtime override.
*/
function restartKiosk(): void {
try {
// Remove native flag
try { execSync(`rm -f ${NATIVE_FLAG}`, { timeout: 2000 }); } catch {}
// Remove runtime override
try { execSync(`/run/wrappers/bin/sudo rm -rf ${KIOSK_OVERRIDE_DIR}`, { timeout: 10000 }); } catch {}
// Use systemctl restart — let systemd handle stop+start atomically.
// TimeoutStopSec=5s ensures Cage gets SIGKILL quickly.
// Don't pkill manually — that races with hdmi-hotplug udev watcher.
execSync(`/run/wrappers/bin/sudo ${SYSTEMCTL} daemon-reload`, { timeout: 15000 });
try { execSync(`/run/wrappers/bin/sudo ${SYSTEMCTL} reset-failed kiosk.service`, { timeout: 10000 }); } catch {}
execSync(`/run/wrappers/bin/sudo ${SYSTEMCTL} restart kiosk.service`, { timeout: 45000 });
console.log("[native] Kiosk restarted");
} catch (e: any) {
console.error("[native] Failed to restart kiosk:", e.message);
}
}
// ── ROM permissions ─────────────────────────────────────────────────────────
/** Ensure the kiosk user can read ROM files (Pi home dir needs o+x) */
function ensureRomPermissions(): void {
try {
execSync("chmod o+x /home/pi /home/pi/retrobox", { timeout: 10000 });
execSync("chmod -R o+r /home/pi/retrobox/presets/", { timeout: 15000 });
} catch (e: any) {
console.warn("[native] Permission fix failed:", e.message);
}
}
// ── ZIP extraction for cores that need uncompressed content ─────────────────
let extractedDir: string | null = null;
/**
* Extract a zip ROM to a temp directory and return the content file path.
* For PSX, finds the .cue file (or .bin/.iso fallback).
* Cleans up any previous extraction first.
*/
function extractRom(system: string, zipPath: string): string | null {
cleanupExtraction();
const dir = join(EXTRACT_DIR, `${system}-${Date.now()}`);
try {
execSync(`/run/wrappers/bin/sudo mkdir -p "${dir}"`, { timeout: 10000 });
execSync(`/run/wrappers/bin/sudo unzip -o -q "${zipPath}" -d "${dir}"`, { timeout: 100000 });
execSync(`/run/wrappers/bin/sudo chmod -R a+rX "${dir}"`, { timeout: 10000 });
// Ensure parent dirs are traversable by pi user
execSync(`/run/wrappers/bin/sudo chmod a+x "${EXTRACT_DIR}" "${KIOSK_HOME}/.cache"`, { timeout: 10000 });
extractedDir = dir;
// Find the best content file
const files = readdirSync(dir);
const exts = CONTENT_EXTENSIONS[system] || [];
for (const ext of exts) {
const match = files.find(f => f.toLowerCase().endsWith(ext));
if (match) {
console.log(`[native] Extracted: ${match}`);
return join(dir, match);
}
}
// Fallback: first file that isn't a directory
const fallback = files.find(f => {
try { return !require("fs").statSync(join(dir, f)).isDirectory(); } catch { return false; }
});
if (fallback) {
console.log(`[native] Extracted (fallback): ${fallback}`);
return join(dir, fallback);
}
console.error(`[native] No content file found in extracted archive`);
return null;
} catch (e: any) {
console.error(`[native] Extraction failed:`, e.message);
cleanupExtraction();
return null;
}
}
/** Clean up extracted files */
function cleanupExtraction(): void {
if (extractedDir) {
try { execSync(`/run/wrappers/bin/sudo rm -rf "${extractedDir}"`, { timeout: 15000 }); } catch {}
extractedDir = null;
}
// Also clean stale dirs
try {
if (existsSync(EXTRACT_DIR)) {
for (const d of readdirSync(EXTRACT_DIR)) {
try { execSync(`/run/wrappers/bin/sudo rm -rf "${join(EXTRACT_DIR, d)}"`, { timeout: 15000 }); } catch {}
}
}
} catch {}
}
// ── Launch / Quit ───────────────────────────────────────────────────────────
export interface LaunchOptions {
/** Core option overrides for this launch */
coreOptions?: Record<string, string>;
/** Called when native process exits */
onExit?: (code: number | null, signal: string | null) => void;
}
/**
* Resolve the core .so path for a system.
* N64 GLES3 variant lives in a separate Nix store path.
*/
function resolveCorePath(system: string): string | null {
const coreName = NATIVE_CORE_MAP[system];
if (!coreName) return null;
if (system === "n64") return GLES3_CORE;
return join(CORES_DIR, coreName);
}
/**
* Launch a game natively via Cage + RetroArch.
*
* 1. Write core options
* 2. Stop kiosk service
* 3. Spawn `cage -s -d -- retroarch -L core rom`
* 4. On exit → restart kiosk
*/
export async function launchNative(
system: string,
romPath: string,
options?: LaunchOptions
): Promise<{ ok: boolean; error?: string }> {
if (state !== "idle") {
return { ok: false, error: `Cannot launch: state is ${state}` };
}
// Resolve core
const corePath = resolveCorePath(system);
if (!corePath || !existsSync(corePath)) {
return { ok: false, error: `Core not found for system: ${system}` };
}
// Verify ROM exists
if (!existsSync(romPath)) {
return { ok: false, error: `ROM not found: ${romPath}` };
}
state = "launching";
currentCore = system;
currentRom = romPath;
exitCallback = options?.onExit || null;
console.log(`[native] Launching: ${system} → ${romPath}`);
// Extract zip for cores that need uncompressed content
let actualRomPath = romPath;
if (NEEDS_EXTRACTION.has(system) && romPath.toLowerCase().endsWith(".zip")) {
console.log(`[native] ${system} requires extraction — unzipping...`);
const extracted = extractRom(system, romPath);
if (!extracted) {
state = "idle";
currentCore = null;
currentRom = null;
return { ok: false, error: "Failed to extract ROM archive" };
}
actualRomPath = extracted;
}
// Write core options + patch retroarch.cfg for optimal latency
writeCoreOptions(system, options?.coreOptions);
ensureRetroarchCfg();
// Ensure ROM readability
ensureRomPermissions();
// Ensure saves/states dirs exist
// Symlink native saves to web saves dir so both share the same .srm files
const SUDO = "/run/wrappers/bin/sudo";
const webSavesDir = join(import.meta.dir, "saves");
try {
execSync(`${SUDO} mkdir -p "${webSavesDir}" "${STATES_DIR}"`, { timeout: 10000 });
execSync(`chmod a+rwX "${webSavesDir}"`, { timeout: 1000 });
// If saves dir is a real directory, merge contents then replace with symlink
const isSymlink = execSync(`test -L "${SAVES_DIR}" && echo 1 || echo 0`, { timeout: 1000 }).toString().trim() === "1";
if (!isSymlink) {
// Copy existing native saves to web dir (don't overwrite)
try { execSync(`${SUDO} cp -rn "${SAVES_DIR}/"* "${webSavesDir}/" 2>/dev/null; ${SUDO} chown -R pi:users "${webSavesDir}"`, { timeout: 15000 }); } catch {}
execSync(`${SUDO} rm -rf "${SAVES_DIR}"`, { timeout: 10000 });
}
const target = execSync(`readlink -f "${SAVES_DIR}" 2>/dev/null || echo ""`, { timeout: 1000 }).toString().trim();
if (target !== webSavesDir) {
execSync(`${SUDO} ln -sfn "${webSavesDir}" "${SAVES_DIR}"`, { timeout: 10000 });
}
} catch {}
// Stop kiosk
if (!stopKiosk()) {
state = "idle";
currentCore = null;
currentRom = null;
return { ok: false, error: "Failed to stop kiosk service" };
}
// Small delay for seatd to release the seat
await new Promise((r) => setTimeout(r, 1500));
// Spawn Cage → RetroArch
try {
const env: Record<string, string> = {
XDG_RUNTIME_DIR: "/run/user/1000",
LIBSEAT_BACKEND: "seatd",
WLR_RENDERER: "gles2",
WLR_NO_HARDWARE_CURSORS: "1",
HOME: KIOSK_HOME,
};
const retroarchArgs = [
"-s", "-d", "--",
RETROARCH_BIN,
"--config", RETROARCH_CFG,
"--appendconfig", "/dev/null", // prevent NixOS wrapper injection
"-L", corePath,
actualRomPath,
];
console.log(`[native] exec: ${CAGE_BIN} ${retroarchArgs.join(" ")}`);
cageProcess = spawn(CAGE_BIN, retroarchArgs, {
env: {
...process.env,
...env,
PATH: `/run/wrappers/bin:/run/current-system/sw/bin:${process.env.PATH || ""}`,
},
stdio: ["ignore", "pipe", "pipe"],
detached: false,
});
state = "running";
// Log stdout/stderr
cageProcess.stdout?.on("data", (d: Buffer) => {
const line = d.toString().trim();
if (line) console.log(`[retroarch] ${line}`);
});
cageProcess.stderr?.on("data", (d: Buffer) => {
const line = d.toString().trim();
if (line) console.error(`[retroarch] ${line}`);
});
// Handle exit
cageProcess.on("exit", (code, signal) => {
console.log(`[native] Cage exited: code=${code}, signal=${signal}`);
const wasRunning = state === "running" || state === "stopping";
state = "idle";
cageProcess = null;
const exitCore = currentCore;
const exitRom = currentRom;
currentCore = null;
currentRom = null;
// Clean up extracted ROM files
cleanupExtraction();
// Restart kiosk
restartKiosk();
// Notify callback
if (exitCallback) {
try { exitCallback(code, signal); } catch {}
exitCallback = null;
}
});
cageProcess.on("error", (err) => {
console.error(`[native] Spawn error:`, err);
state = "idle";
cageProcess = null;
currentCore = null;
currentRom = null;
cleanupExtraction();
restartKiosk();
});
return { ok: true };
} catch (e: any) {
console.error(`[native] Launch failed:`, e);
state = "idle";
currentCore = null;
currentRom = null;
cleanupExtraction();
restartKiosk();
return { ok: false, error: e.message };
}
}
// ── Quit ────────────────────────────────────────────────────────────────────
/**
* Quit native RetroArch. Sends SIGINT to RetroArch (flushes saves) then SIGTERM to Cage.
* The exit handler then restarts the kiosk.
*/
export function quitNative(): { ok: boolean; error?: string } {
if (state !== "running" || !cageProcess) {
return { ok: false, error: `Cannot quit: state is ${state}` };
}
state = "stopping";
console.log("[native] Sending SIGINT to RetroArch, then SIGTERM to Cage");
try {
// Send SIGINT to RetroArch first — it flushes SRAM saves on SIGINT
try {
execSync(`/run/wrappers/bin/sudo pkill -INT -f 'retroarch.*--config'`, { timeout: 10000 });
} catch {}
// Brief wait for save flush
execSync("sleep 1", { timeout: 10000 });
// Then kill Cage
if (cageProcess.pid) {
execSync(`/run/wrappers/bin/sudo kill ${cageProcess.pid}`, { timeout: 15000 });
}
return { ok: true };
} catch (e: any) {
// Try harder — find cage process
try {
execSync("/run/wrappers/bin/sudo pkill -f 'cage.*retroarch'", { timeout: 10000 });
return { ok: true };
} catch {
return { ok: false, error: e.message };
}
}
}
// ── Status ──────────────────────────────────────────────────────────────────
export interface NativeStatus {
state: NativeState;
core: string | null;
rom: string | null;
pid: number | null;
supported: boolean;
cores: Record<string, boolean>;
}
/** Get current native mode status */
export function getNativeStatus(): NativeStatus {
const probe = probeNativeSupport();
return {
state,
core: currentCore,
rom: currentRom,
pid: cageProcess?.pid ?? null,
supported: probe.supported,
cores: probe.cores,
};
}
// ── Exported constants for server.ts integration ────────────────────────────
export { RETROARCH_BIN, CORES_DIR, CAGE_BIN };