-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
989 lines (864 loc) · 40.4 KB
/
Copy pathserver.py
File metadata and controls
989 lines (864 loc) · 40.4 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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
#!/usr/bin/env python3
"""RomM Streaming Server.
Two play paths, one backend:
- Roku (legacy): Chromium+EmulatorJS or RetroArch on Xvfb → FFmpeg → HLS,
input relayed via CDP (Chromium) or xdotool (RetroArch).
- Xbox (WebRTC): RetroArch on Xvfb → aiortc H.264/Opus, input over the
WebRTC data channel. ~100 ms instead of HLS's 2-4 s.
Plus: tier routing (/api/play/route), ROM proxy for EmulatorJS-in-browser,
and save-state persistence shared across tiers.
"""
import asyncio
import json
import logging
import os
import urllib.parse
import uuid
from pathlib import Path
from aiohttp import web
import archives
import runner_retroarch
import saves
import tiers
import vpad
from sessions import Allocator
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('romm-stream')
HLS_DIR = '/opt/romm-stream/hls'
ROM_BASE = '/mnt/usb1/roms'
PUBLIC_BASE = os.environ.get('ROMM_STREAM_PUBLIC', 'http://192.168.0.94:8091')
# Origins a web session (POST /api/stream/start {"url": ...}) may open.
WEB_SESSION_PREFIXES = (
'https://crypticrealm.com',
'https://www.crypticrealm.com',
'https://worldofclaudecraft.com',
'https://xbox.moveweight.com',
'https://romm.moveweight.com',
'http://localhost:8080', # RomM served locally on the same host
'http://127.0.0.1:8080',
)
# RomM instance this server drives for autoplay (login + EJS launcher). Any
# RomM base can be passed per-request as romm_base for "anyone's RomM server".
ROMM_LOCAL_BASE = os.environ.get('ROMM_BASE', 'http://localhost:8080')
# The GPU stream runner (mw-laptop VM 9000, RTX 3050) renders the heavy 3D
# platforms this GPU-less host cannot. CT104 proxies those platforms there.
GPU_HOST = os.environ.get('GPU_HOST', 'http://192.168.0.201:8090')
GPU_PLATFORMS = {'n64', 'psx', 'ps', 'ps2', 'ngc', 'wii', 'dc', 'dreamcast',
'naomi', 'atomiswave', 'saturn', 'psp'}
# Sessions we handed to the GPU host, sid -> True, so input/stop proxy there too.
GPU_STREAMS = {}
STREAMS = {}
ALLOC = Allocator()
PLAYER_HTML = '''<!DOCTYPE html><html><head><meta charset="utf-8">
<title>__NAME__</title>
<style>*{margin:0;padding:0}body{background:#000;overflow:hidden}</style>
</head><body>
<div id="game" style="width:1280px;height:720px"></div>
<script>
window.EJS_player = "#game";
window.EJS_core = "__CORE__";
window.EJS_gameUrl = "__ROM_URL__";
window.EJS_pathtodata = "/emu/data/";
window.EJS_startOnLoaded = true;
window.EJS_volume = 0.5;
window.EJS_defaultOptions = { fullscreen: false };
</script>
<script src="/emu/data/loader.js"></script>
</body></html>'''
# CDP key map for web (Cryptic Realm) sessions: WASD movement + the game's
# default binds (E interact, Space jump, digits = ability slots, Tab target).
# Cryptic Realm (web game) key map: WASD movement + game binds.
WEB_KEY_MAP = {
'up': ('KeyW', 'w'), 'down': ('KeyS', 's'),
'left': ('KeyA', 'a'), 'right': ('KeyD', 'd'),
'a': ('KeyE', 'e'), 'b': ('Escape', 'Escape'),
'x': ('Digit1', '1'), 'y': ('Digit2', '2'),
'l1': ('Tab', 'Tab'), 'r1': ('Space', ' '),
'start': ('KeyB', 'b'), 'select': ('Digit3', '3'),
'enter': ('Enter', 'Enter'),
}
# EmulatorJS default keyboard binds (RomM games): arrows + z/x/a/s/enter/shift.
EJS_KEY_MAP = {
'up': ('ArrowUp', 'ArrowUp'), 'down': ('ArrowDown', 'ArrowDown'),
'left': ('ArrowLeft', 'ArrowLeft'), 'right': ('ArrowRight', 'ArrowRight'),
'a': ('KeyX', 'x'), 'b': ('KeyZ', 'z'),
'x': ('KeyS', 's'), 'y': ('KeyA', 'a'),
'l1': ('KeyQ', 'q'), 'r1': ('KeyW', 'w'),
'start': ('Enter', 'Enter'), 'select': ('ShiftRight', 'Shift'),
'enter': ('Enter', 'Enter'),
}
# CDP key map for the legacy Chromium/EmulatorJS sessions.
KEY_MAP = {
'up': 'ArrowUp', 'down': 'ArrowDown', 'left': 'ArrowLeft', 'right': 'ArrowRight',
'a': 'KeyX', 'b': 'KeyZ', 'x': 'KeyS', 'y': 'KeyA',
'l1': 'KeyQ', 'r1': 'KeyW', 'start': 'Enter', 'select': 'ShiftRight',
}
def resolve_rom(platform: str, rom_name: str) -> Path | None:
"""Path of a ROM under ROM_BASE; None if missing or traversal attempt.
Most of this library is archived (100% of wii and arcade, 99% of ps2 and
snes). For platforms whose emulator cannot read an archive, this returns the
extracted disc image instead of the `.7z` — see archives.playable_path,
which caches so the cost is paid once per title, and which deliberately
leaves arcade zips alone because there the zip *is* the romset.
"""
if not platform or not rom_name:
return None
base = Path(ROM_BASE).resolve()
try:
p = (base / platform / rom_name).resolve()
except (OSError, ValueError):
return None
if not str(p).startswith(str(base)) or not p.is_file():
return None
try:
return archives.playable_path(platform, p)
except Exception:
log.exception('archive extraction failed for %s/%s', platform, rom_name)
return None
# ---------------------------------------------------------------- tier route
async def handle_streamable(req):
"""What this server can actually stream, and why not for the rest.
The client mirrors this instead of hardcoding a core list, so a platform is
never offered on a server that has no core or no firmware for it.
"""
slugs = tiers.streamable_slugs()
unavailable = {}
for slug in sorted(tiers.RETROARCH_CORES):
if slug not in slugs:
why = tiers.why_not(slug)
if why:
unavailable[slug] = why
# Slugs the *local* tier claims but cannot actually serve, because the
# EmulatorJS core was never downloaded. Without this the client happily
# returns 'local' for them from its own EJS_CORES table and the game dies at
# launch — the local-tier twin of the missing-RetroArch-core dead end.
ejs_unavailable = sorted(
slug for slug, system in tiers.EJS_CORES.items()
if not tiers.ejs_core_installed(system))
# Fold in the heavy 3D platforms the GPU host renders, so the client offers
# N64/PS1/PS2/GC/DC/Saturn/PSP too. Best-effort: if the GPU host is down we
# just omit them rather than fail the whole listing.
gpu_slugs = await _gpu_streamable()
merged = sorted(set(slugs) | set(gpu_slugs))
for g in gpu_slugs:
unavailable.pop(g, None) # no longer "unavailable" — GPU has it
return _cors(web.json_response({'streamable': merged,
'unavailable': unavailable,
'ejs_unavailable': ejs_unavailable}))
async def _gpu_streamable():
"""Ask the GPU host what it can render; empty list if it's unreachable."""
import aiohttp
try:
async with aiohttp.ClientSession() as s:
async with s.get(f'{GPU_HOST}/api/play/streamable',
timeout=aiohttp.ClientTimeout(total=4)) as r:
return (await r.json()).get('streamable', [])
except Exception:
return []
async def handle_route(req):
slug = req.query.get('platform', '')
tier = tiers.route(slug)
if tier is None:
# Before refusing, ask the GPU host — the same fold-in
# handle_streamable does.
#
# tiers.route() reads THIS host's cores and system directory, and the
# heavy 3D platforms are deliberately not rendered here: they are
# proxied. So the local answer for dc, ps2, wii and ngc is "no core"
# or "needs firmware" while the GPU host has both and streams them
# perfectly well. Two endpoints on one server were giving opposite
# answers about the same platform, and this is the one clients ask
# about a single title — so a Dreamcast game the stack can play was
# reported unplayable at exactly the moment somebody asked for it.
if slug and slug.lower() in set(await _gpu_streamable()):
return _cors(web.json_response({'tier': 'stream', 'via': 'gpu'}))
# Say which of the several reasons it is: "no core exists" and "you need
# to supply firmware" are very different problems for the operator.
return _cors(web.json_response(
{'error': 'unplayable',
'why': tiers.why_not(slug) or 'no emulator exists for this platform'},
status=404))
return _cors(web.json_response({'tier': tier}))
# ---------------------------------------------------------------- ROM proxy
async def handle_romfile(req):
p = resolve_rom(req.match_info['platform'],
urllib.parse.unquote(req.match_info['name']))
if p is None:
return web.json_response({'error': 'not found'}, status=404)
return web.FileResponse(p, headers={
'Access-Control-Allow-Origin': '*'})
# ---------------------------------------------------------------- saves
async def handle_save_put(req):
try:
p = saves.save_path(req.match_info['platform'],
urllib.parse.unquote(req.match_info['name']))
except ValueError:
return web.json_response({'error': 'bad path'}, status=400)
body = await req.read()
if len(body) > saves.MAX_SAVE_BYTES:
return web.json_response({'error': 'too large'}, status=413)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(body)
return web.json_response({'ok': True, 'bytes': len(body)})
async def handle_save_get(req):
try:
p = saves.save_path(req.match_info['platform'],
urllib.parse.unquote(req.match_info['name']))
except ValueError:
return web.json_response({'error': 'bad path'}, status=400)
if not p.is_file():
return web.json_response({'error': 'no save'}, status=404)
return web.FileResponse(p, headers={'Access-Control-Allow-Origin': '*'})
# ------------------------------------------------- legacy HLS (Roku) session
async def start_ffmpeg_hls(display: str, stream_dir: Path):
hls_path = str(stream_dir / 'stream.m3u8')
seg = str(stream_dir / 'seg_%03d.ts')
# Roku's H.264 decoder only handles up to High profile @ 4:2:0 (yuv420p).
# x11grab captures RGB and libx264 would otherwise emit High 4:4:4 (yuv444p),
# which Roku cannot decode -> the Video node buffers forever. Force yuv420p +
# baseline-friendly profile/level, and add a silent AAC track (Roku HLS
# dislikes video-only streams). 2s GOP with segment-aligned keyframes.
return await asyncio.create_subprocess_exec(
'ffmpeg',
'-f', 'x11grab', '-video_size', '1280x720',
'-framerate', '30', '-i', display + '.0+0,0',
'-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100',
'-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
'-profile:v', 'high', '-level', '4.0', '-pix_fmt', 'yuv420p',
'-b:v', '3M', '-maxrate', '3M', '-bufsize', '2M',
# 1-second GOP so every segment starts on a keyframe and the player can
# begin almost immediately. Was a 2s GOP + 6-segment window = up to ~12 s
# of buffered latency (the "large delay"); 1s segments with a 3-deep
# window cut worst-case latency to ~3-4 s, about as low as HLS goes.
'-g', '30', '-keyint_min', '30', '-sc_threshold', '0',
'-c:a', 'aac', '-b:a', '128k', '-ac', '2',
'-hls_time', '1', '-hls_list_size', '3',
'-hls_flags', 'delete_segments+independent_segments',
# Roku's HLS player expects a MASTER playlist with #EXT-X-STREAM-INF,
# not a bare media playlist; without it playback fails with a vague
# "error in the HTTP response". Emit master.m3u8 alongside the media list.
'-master_pl_name', 'master.m3u8',
'-hls_segment_filename', seg, '-f', 'hls', hls_path,
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL)
async def _cdp_eval(ws, expr, await_promise=False):
"""Evaluate JS in the page over an open CDP websocket; return the value."""
import websocket as _ws
_id = 1
ws.send(json.dumps({'id': _id, 'method': 'Runtime.evaluate', 'params': {
'expression': expr, 'returnByValue': True,
'awaitPromise': await_promise}}))
while True:
m = json.loads(ws.recv())
if m.get('id') == _id:
return m.get('result', {}).get('result', {}).get('value')
def _romm_api_login(base, user, password):
"""Log into RomM via its API and return session cookies as CDP setCookie
params. RomM 4.9 login = POST /api/login with HTTP Basic auth + the
x-csrftoken header (value from the romm_csrftoken cookie)."""
import base64 as _b64
import http.cookiejar
from urllib.request import build_opener, HTTPCookieProcessor, Request
from urllib.parse import urlparse
host = urlparse(base).hostname or 'localhost'
jar = http.cookiejar.CookieJar()
opener = build_opener(HTTPCookieProcessor(jar))
opener.open(base + '/api/heartbeat', timeout=6).read() # prime CSRF cookie
csrf = next((c.value for c in jar if c.name == 'romm_csrftoken'), '')
creds = _b64.b64encode(f'{user}:{password}'.encode()).decode()
req = Request(base + '/api/login', data=b'', method='POST')
req.add_header('Authorization', 'Basic ' + creds)
if csrf:
req.add_header('x-csrftoken', csrf)
opener.open(req, timeout=6).read() # sets romm_session
out = []
for c in jar:
out.append({'name': c.name, 'value': c.value, 'domain': host,
'path': c.path or '/', 'httpOnly': False, 'secure': False})
return out
async def romm_autoplay(cdp_ws, base, rom_id, user, password):
"""Drive RomM's web UI: login if on the login page, then click EJS Play."""
import websocket
try:
ws = websocket.create_connection(
cdp_ws.replace('localhost', '127.0.0.1'), timeout=8)
except Exception:
return
# Turn off Chrome's password-save UI at the DevTools level so no bubble
# appears after the login form submits.
try:
for m in ('Autofill.disable', 'Page.enable'):
ws.send(json.dumps({'id': 50, 'method': m, 'params': {}}))
while True:
r = json.loads(ws.recv())
if r.get('id') == 50:
break
except Exception:
pass
def ev(expr):
ws.send(json.dumps({'id': 1, 'method': 'Runtime.evaluate', 'params': {
'expression': expr, 'returnByValue': True}}))
while True:
m = json.loads(ws.recv())
if m.get('id') == 1:
return m.get('result', {}).get('result', {}).get('value')
def cmd(method, params, mid=7):
ws.send(json.dumps({'id': mid, 'method': method, 'params': params}))
while True:
m = json.loads(ws.recv())
if m.get('id') == mid:
return m
try:
# Log in via RomM's API and inject the session cookie with CDP, so no
# login FORM is ever submitted -> Chrome never shows a save-password
# bubble (which otherwise covers half the game).
if user:
try:
cmd('Network.enable', {})
sess = _romm_api_login(base, user, password)
for c in sess:
cmd('Network.setCookie', c, mid=8)
except Exception:
pass
# Go straight to the EJS launcher (now authenticated by the cookie).
ev('window.location.assign(%r)' % f'{base}/rom/{rom_id}/ejs')
await asyncio.sleep(3)
cur = ev('location.href') or ''
# Fallback: if the cookie login didn't take and we're on /login, do the
# form login once.
if '/login' in cur and user:
fill = ('(function(){function s(el,v){var d=Object.'
'getOwnPropertyDescriptor(HTMLInputElement.prototype,'
'"value").set;d.call(el,v);el.dispatchEvent(new Event('
'"input",{bubbles:true}));el.dispatchEvent(new Event('
'"change",{bubbles:true}));}var u=document.querySelector('
'"input[name=username],input[type=text]");var p='
'document.querySelector("input[type=password]");'
'if(u&&p){s(u,%r);s(p,%r);var b=[...document.'
'querySelectorAll("button")].find(b=>/login/i.test('
'b.innerText)&&!/authentik/i.test(b.innerText));'
'if(b){b.click();}}return "x";})()') % (user, password)
ev(fill)
await asyncio.sleep(4)
ev('window.location.assign(%r)' % f'{base}/rom/{rom_id}/ejs')
await asyncio.sleep(2)
for _ in range(30):
r = ev('(function(){var b=[...document.querySelectorAll("button")]'
'.find(b=>b.innerText.trim()==="Play");if(b){b.click();'
'return "play";}return "wait";})()')
if r == 'play':
break
await asyncio.sleep(0.5)
except Exception:
pass
finally:
try:
ws.close()
except Exception:
pass
async def _proxy_to_gpu(data):
"""Forward a start request to the GPU host and return its JSON response.
The GPU host serves HLS from its own address, so its hls_url already points
at the right place; we just remember the sid so input/stop go there too.
"""
import aiohttp
try:
async with aiohttp.ClientSession() as s:
async with s.post(f'{GPU_HOST}/api/stream/start', json=data,
timeout=aiohttp.ClientTimeout(total=90)) as r:
body = await r.json()
if r.status == 200 and body.get('stream_id'):
GPU_STREAMS[body['stream_id']] = True
return web.json_response(body, status=r.status)
except Exception as e:
return web.json_response(
{'error': f'gpu host unreachable: {e}'}, status=502)
async def _proxy_to_gpu_path(sid, path, method='POST', data=None):
"""Proxy an input/stop call for a GPU session to the GPU host."""
import aiohttp
try:
async with aiohttp.ClientSession() as s:
m = s.post if method == 'POST' else s.get
async with m(f'{GPU_HOST}/api/stream/{sid}{path}', json=data,
timeout=aiohttp.ClientTimeout(total=10)) as r:
return web.json_response(await r.json(), status=r.status)
except Exception:
return web.json_response({'ok': False}, status=502)
async def handle_start(req):
"""Roku-compatible HLS session. Uses RetroArch when the platform has a
server core (better compat), else the legacy Chromium+EmulatorJS page."""
try:
data = await req.json()
except Exception:
data = {}
platform = data.get('platform', 'n64')
rom_name = data.get('rom_name', '')
web_url = data.get('url', '')
client = data.get('client', '')
display_name = data.get('name', rom_name or 'game')
# RomM autoplay: drive RomM's own web UI (login -> EJS launcher -> Play) in
# Chromium, exactly like a real user, so RomM configures the emulator. Far
# more reliable than launching a bare EJS core headless.
romm_rom_id = data.get('romm_rom_id')
romm_base = data.get('romm_base', ROMM_LOCAL_BASE)
romm_user = data.get('romm_user', '')
romm_pass = data.get('romm_pass', '')
if romm_rom_id:
web_url = f'{romm_base}/rom/{romm_rom_id}/ejs'
# Heavy 3D platforms (N64/PS1/PS2/GC/Wii/DC/Saturn/PSP) can't render on this
# GPU-less host — they go to the GPU runner on the mw-laptop VM (RTX 3050,
# shared with ArcForge but not disrupting it). CT104 stays the single front
# door: clients always POST here, and we transparently proxy heavy platforms
# to the GPU host and hand back its HLS url. 2D software cores stay local.
if not web_url and (platform or '').lower() in GPU_PLATFORMS:
return await _proxy_to_gpu(data)
# Reap prior sessions from the same client (e.g. a Roku relaunch) so they
# don't pile up as orphan Chromium/FFmpeg processes and confuse which
# session is live. A client only ever needs one active stream.
if client:
for old_sid in [k for k, v in STREAMS.items() if v.get('client') == client]:
old = STREAMS.pop(old_sid, None)
if old:
await runner_retroarch.terminate(
old.get('ffmpeg'), old.get('chrome'),
old.get('retroarch'), old.get('xvfb'))
ALLOC.release(old['display_num'])
rom = None
if web_url:
# Web session (e.g. Cryptic Realm on Roku): headless Chromium runs the
# page itself. Allowlisted origins only — this must not be an open proxy.
# RomM autoplay (romm_rom_id set) may target any RomM base the caller
# provides, since it requires valid RomM credentials to do anything.
if not romm_rom_id and not any(
web_url.startswith(p) for p in WEB_SESSION_PREFIXES):
return web.json_response({'error': 'url not allowed'}, status=403)
else:
rom = resolve_rom(platform, rom_name)
if rom is None:
return web.json_response({'error': 'rom not found'}, status=404)
try:
display_num, debug_port = ALLOC.acquire()
except RuntimeError:
return web.json_response({'error': 'server busy'}, status=503)
sid = uuid.uuid4().hex[:8]
stream_dir = Path(HLS_DIR) / sid
stream_dir.mkdir(parents=True, exist_ok=True)
display = f':{display_num}'
xvfb = await runner_retroarch.start_xvfb(display_num)
engine, chrome, ra, cdp_ws = 'retroarch', None, None, ''
# This host has no GPU, so the ONLY thing that renders a real frame is a
# native RetroArch software core (video_driver=sdl2). EmulatorJS-in-Chromium
# was preferred here historically, but its WebGL canvas paints black under
# SwiftShader on this box — EJS_emulator.started is true yet every pixel is
# zero. So for a local ROM we prefer a native SOFTWARE core whenever one
# exists; heavy HW-GL cores (Dolphin/PCSX2/Flycast/Mupen64Plus/Citra/PPSSPP)
# are deliberately NOT launched here — they need a real GL context and would
# exit with "Cannot open video driver", streaming a black frame. Those heavy
# systems fall through to Chromium only as a last resort (still likely black,
# but never a hard crash); route()/streamable_slugs already hide them from
# clients so users are not offered a platform this host cannot render.
core_file = tiers.stream_core(platform) or ''
if rom is not None and tiers.is_software_core(core_file):
try:
ra = await runner_retroarch.start_retroarch(
platform, str(rom), display_num, rom_name)
except FileNotFoundError:
ra = None
if ra is None:
engine = 'chromium'
if web_url:
page_url = web_url
else:
core = tiers.EJS_CORES.get(platform, platform)
rom_url = f'{PUBLIC_BASE}/roms/' + urllib.parse.quote(
platform + '/' + rom_name)
html = (PLAYER_HTML.replace('__NAME__', display_name)
.replace('__CORE__', core).replace('__ROM_URL__', rom_url))
(stream_dir / 'player.html').write_text(html)
page_url = f'{PUBLIC_BASE}/player/{sid}/player.html'
# Fresh throwaway profile per session + crash flags kill the
# "Chromium didn't shut down correctly / Restore pages?" infobar that
# appears when a prior session's profile was left dirty.
profile_dir = str(stream_dir / 'chrome-profile')
chrome = await asyncio.create_subprocess_exec(
'chromium', '--display=' + display, '--no-sandbox',
'--disable-gpu-sandbox', '--use-gl=angle',
'--use-angle=swiftshader', '--enable-webgl',
'--ignore-gpu-blocklist', '--window-size=1280,720',
'--start-fullscreen', '--kiosk',
'--user-data-dir=' + profile_dir,
'--no-first-run', '--no-default-browser-check',
'--disable-session-crashed-bubble',
'--disable-infobars', '--hide-crash-restore-bubble',
'--disable-features=InfiniteSessionRestore,Translate,'
'PasswordManagerOnboarding,AutofillEnableAccountWalletStorage,'
'PasswordManager,PasswordGeneration,AutofillServerCommunication,'
'PasswordLeakDetection,AutofillEnablePasswordManager',
'--password-store=basic',
'--remote-debugging-port=' + str(debug_port),
# Chromium >=111 rejects CDP WebSocket connections (403) unless the
# origin is allowlisted; without this every controller keypress
# fails silently at handle_input's websocket.create_connection.
'--remote-allow-origins=*',
page_url,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
env=dict(os.environ, DISPLAY=display))
await asyncio.sleep(4)
try:
from urllib.request import urlopen
pages = json.loads(urlopen(
f'http://localhost:{debug_port}/json', timeout=5).read())
if pages:
cdp_ws = pages[0].get('webSocketDebuggerUrl', '')
except Exception:
pass
# RomM autoplay: log in (if creds given) then click the EJS "Play"
# button, so the game boots without any user gesture.
if romm_rom_id and cdp_ws:
await romm_autoplay(cdp_ws, romm_base, romm_rom_id,
romm_user, romm_pass)
ffmpeg = await start_ffmpeg_hls(display, stream_dir)
# Wait until the master playlist AND at least one segment exist before
# returning, otherwise the client (Roku) requests master.m3u8 during the
# FFmpeg startup window, gets 404, and aborts playback. Up to ~12s.
master_pl = stream_dir / 'master.m3u8'
for _ in range(60):
segs = list(stream_dir.glob('seg_*.ts'))
if master_pl.exists() and len(segs) >= 2:
break
await asyncio.sleep(0.2)
STREAMS[sid] = {'xvfb': xvfb, 'chrome': chrome, 'retroarch': ra,
'ffmpeg': ffmpeg, 'display_num': display_num,
'engine': engine, 'rom_name': display_name,
'cdp_ws': cdp_ws, 'web': bool(web_url), 'client': client,
'ejs': bool(romm_rom_id), 'platform': platform}
# Point clients at the master playlist (Roku requires #EXT-X-STREAM-INF).
# RetroArch/HLS-only sessions without a master fall back to the media list.
return web.json_response({
'stream_id': sid, 'engine': engine,
'hls_url': f'{PUBLIC_BASE}/hls/{sid}/master.m3u8',
'debug_port': debug_port})
async def handle_stop(req):
sid = req.match_info['sid']
if GPU_STREAMS.pop(sid, None):
return await _proxy_to_gpu_path(sid, '/stop')
s = STREAMS.pop(sid, None)
if s:
await runner_retroarch.terminate(
s.get('ffmpeg'), s.get('chrome'), s.get('retroarch'), s.get('xvfb'))
ALLOC.release(s['display_num'])
return web.json_response({'ok': True})
async def handle_input(req):
sid = req.match_info['sid']
try:
data = await req.json()
except Exception:
data = {}
key, pressed = data.get('key', ''), data.get('pressed', True)
if sid in GPU_STREAMS:
return await _proxy_to_gpu_path(sid, '/input', data=data)
s = STREAMS.get(sid)
if not s:
return web.json_response({'error': 'stream not found'}, status=404)
if s['engine'] == 'retroarch':
ok = await runner_retroarch.send_key(s['display_num'], key, pressed)
return web.json_response({'ok': ok, 'key': key})
if s.get('ejs'):
code, char = EJS_KEY_MAP.get(key, (key, key))
elif s.get('web'):
code, char = WEB_KEY_MAP.get(key, (key, key))
else:
code = char = KEY_MAP.get(key, key)
_cdp_key(s, char, code, pressed)
return web.json_response({'ok': True, 'key': key, 'mapped': code})
def _cdp_key(s, char, code, pressed):
"""Dispatch a key over the session's PERSISTENT CDP websocket.
Opening a fresh CDP websocket per keypress (the old behaviour) added a TCP
connect + WS handshake — 50-200 ms — to every button, which is what made the
controls feel laggy. We keep one connection per session in s['cdp_conn'] and
only reconnect if a send fails.
"""
import websocket
ws_url = s.get('cdp_ws', '').replace('localhost', '127.0.0.1')
if not ws_url:
return
msg = json.dumps({'id': 1, 'method': 'Input.dispatchKeyEvent', 'params': {
'type': 'keyDown' if pressed else 'keyUp',
'key': char, 'code': code, 'windowsVirtualKeyCode': 0}})
conn = s.get('cdp_conn')
for attempt in (0, 1):
try:
if conn is None:
conn = websocket.create_connection(ws_url, timeout=2)
conn.settimeout(0.4) # never block the request on a slow send
s['cdp_conn'] = conn
conn.send(msg)
return
except Exception:
try:
if conn:
conn.close()
except Exception:
pass
conn = s['cdp_conn'] = None # force a reconnect on the next attempt
async def handle_analog(req):
"""Analog-stick input from the phone remote / a physical controller.
Body: {stick: 'left'|'right', x: -1..1, y: -1..1}. For a RetroArch session
we translate the left stick past a deadzone into d-pad key presses (via the
same xdotool path as digital input), which is what the software 2D cores this
host runs actually need — none of them read true analog. True analog would
require the uinput vpad (see vpad.py) wired into the HLS session; the cores
offered here don't use it, so this keeps the contract without pretending.
"""
sid = req.match_info['sid']
s = STREAMS.get(sid)
if not s:
return web.json_response({'error': 'stream not found'}, status=404)
try:
d = await req.json()
except Exception:
d = {}
stick = d.get('stick', 'left')
x, y = float(d.get('x', 0) or 0), float(d.get('y', 0) or 0)
# Only the left stick drives movement here; right stick is a no-op for these
# 2D cores. Track per-session which dpad keys the stick is currently holding
# so we release them cleanly when it recenters.
if stick != 'left' or s['engine'] != 'retroarch':
return web.json_response({'ok': True, 'noop': True})
DZ = 0.5
want = {'left': x < -DZ, 'right': x > DZ, 'up': y < -DZ, 'down': y > DZ}
holds = s.setdefault('_axis_holds', {})
for k, on in want.items():
if bool(holds.get(k)) != on:
holds[k] = on
await runner_retroarch.send_key(s['display_num'], k, on)
return web.json_response({'ok': True})
async def handle_status(req):
return web.json_response({'streams': [
{'id': k, 'name': v['rom_name'], 'engine': v['engine'],
'client': v.get('client', ''), 'platform': v.get('platform', '')}
for k, v in STREAMS.items()]})
def _cdp_send(cdp_ws, method, params):
"""Fire a single CDP command over a short-lived websocket."""
import websocket
try:
ws = websocket.create_connection(
cdp_ws.replace('localhost', '127.0.0.1'), timeout=2)
ws.send(json.dumps({'id': 1, 'method': method, 'params': params}))
ws.close()
return True
except Exception:
return False
async def handle_text(req):
"""Type a whole string into the focused field of a web session (keyboard
from the phone remote) via CDP Input.insertText."""
s = STREAMS.get(req.match_info['sid'])
if not s or not s.get('cdp_ws'):
return web.json_response({'error': 'no session'}, status=404)
try:
text = (await req.json()).get('text', '')
except Exception:
text = ''
_cdp_send(s['cdp_ws'], 'Input.insertText', {'text': text})
return web.json_response({'ok': True, 'len': len(text)})
# Virtual cursor position per session for the phone trackpad.
MOUSE_POS = {}
async def handle_mouse(req):
"""Move/click a virtual mouse in a web session via CDP Input.dispatchMouseEvent."""
sid = req.match_info['sid']
s = STREAMS.get(sid)
if not s or not s.get('cdp_ws'):
return web.json_response({'error': 'no session'}, status=404)
try:
d = await req.json()
except Exception:
d = {}
action = d.get('action', 'move')
x, y = MOUSE_POS.get(sid, (640, 360))
if action == 'move':
x = max(0, min(1280, x + float(d.get('dx', 0)) * 1.5))
y = max(0, min(720, y + float(d.get('dy', 0)) * 1.5))
MOUSE_POS[sid] = (x, y)
_cdp_send(s['cdp_ws'], 'Input.dispatchMouseEvent',
{'type': 'mouseMoved', 'x': x, 'y': y})
else:
btn = 'right' if action == 'right' else 'left'
for t in ('mousePressed', 'mouseReleased'):
_cdp_send(s['cdp_ws'], 'Input.dispatchMouseEvent',
{'type': t, 'x': x, 'y': y, 'button': btn,
'clickCount': 1})
return web.json_response({'ok': True, 'x': x, 'y': y})
REMOTE_HTML = None
async def handle_remote(req):
"""Serve the phone/gamepad remote UI, branded per app via ?app=."""
global REMOTE_HTML
if REMOTE_HTML is None:
try:
html_src = (Path(__file__).parent / 'remote.html').read_text()
# Inline layouts.js so the remote is a single self-contained document
# (no second request, and it works even if a static route isn't set).
layouts = (Path(__file__).parent / 'layouts.js').read_text()
REMOTE_HTML = html_src.replace(
'<script src="layouts.js"></script>',
'<script>\n' + layouts + '\n</script>')
except Exception:
return web.json_response({'error': 'remote unavailable'}, status=500)
app_id = req.query.get('app', 'game')
title = {'crypticrealm': 'Cryptic Realm', 'romm': 'RomM'}.get(
app_id, app_id.title())
client = {'crypticrealm': 'roku-crypticrealm', 'romm': 'roku-romm'}.get(
app_id, req.query.get('client', ''))
html = (REMOTE_HTML.replace('__TITLE__', title)
.replace('__CLIENT__', client))
return web.Response(text=html, content_type='text/html')
# ------------------------------------------------------ WebRTC (Xbox) session
# Sessions started over HTTP, keyed by session id. The WebSocket path keeps its
# session on the connection; this one has to outlive a request.
RTC_SESSIONS: dict = {}
async def handle_rtc_offer(req):
"""Start a session and answer an SDP offer in one request.
CORS is answered permissively because the caller is a packaged app on another
origin (app.local) and this server is LAN-only by design.
"""
try:
body = await req.json()
except Exception:
return _cors(web.json_response({'error': 'bad json'}, status=400))
platform = (body.get('platform') or '').strip()
rom_name = (body.get('rom_name') or '').strip()
sdp = body.get('sdp') or ''
if not sdp:
return _cors(web.json_response({'error': 'no sdp'}, status=400))
rom = resolve_rom(platform, rom_name)
if rom is None or not tiers.stream_core(platform):
return _cors(web.json_response(
{'error': 'not streamable'}, status=404))
try:
display_num, _ = ALLOC.acquire()
except RuntimeError:
return _cors(web.json_response({'error': 'server busy'}, status=503))
sid = uuid.uuid4().hex
xvfb = ra = None
pad = None
try:
# Created before RetroArch starts so its input driver enumerates the pad
# at launch; a pad appearing later is not always picked up.
pad = vpad.create()
xvfb = await runner_retroarch.start_xvfb(display_num)
await (await asyncio.create_subprocess_exec(
'pactl', 'load-module', 'module-null-sink',
f'sink_name=romm{display_num}',
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL)).wait()
ra = await runner_retroarch.start_retroarch(
platform, str(rom), display_num, rom_name,
pad_event=pad.event_node if pad is not None else None)
import webrtc
async def cleanup():
RTC_SESSIONS.pop(sid, None)
await runner_retroarch.terminate(ra, xvfb)
if pad is not None:
pad.close()
ALLOC.release(display_num)
pc, answer_sdp, close = await webrtc.answer_offer(
display_num, sdp, cleanup, pad)
RTC_SESSIONS[sid] = {'pc': pc, 'close': close,
'display': display_num}
return _cors(web.json_response({'session_id': sid,
'sdp': answer_sdp}))
except Exception as e:
log.exception('rtc offer failed')
await runner_retroarch.terminate(ra, xvfb)
if pad is not None:
pad.close()
ALLOC.release(display_num)
return _cors(web.json_response({'error': str(e)}, status=500))
async def handle_rtc_stop(req):
s = RTC_SESSIONS.get(req.match_info.get('sid', ''))
if s is None:
return _cors(web.json_response({'ok': True, 'note': 'already gone'}))
await s['close']()
return _cors(web.json_response({'ok': True}))
async def handle_rtc_options(req):
return _cors(web.Response(status=204))
def _cors(resp):
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
return resp
async def handle_rtc_signal(req):
"""WS signaling + full session lifecycle for one WebRTC play session."""
platform = req.query.get('platform', '')
rom_name = urllib.parse.unquote(req.query.get('rom_name', ''))
rom = resolve_rom(platform, rom_name)
if rom is None or not tiers.stream_core(platform):
return web.json_response({'error': 'not streamable'}, status=404)
ws = web.WebSocketResponse(heartbeat=20)
await ws.prepare(req)
try:
display_num, _ = ALLOC.acquire()
except RuntimeError:
await ws.send_json({'type': 'error', 'error': 'server busy'})
await ws.close()
return ws
xvfb = ra = None
try:
xvfb = await runner_retroarch.start_xvfb(display_num)
# per-session pulse null sink for audio capture
await (await asyncio.create_subprocess_exec(
'pactl', 'load-module', 'module-null-sink',
f'sink_name=romm{display_num}',
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL)).wait()
ra = await runner_retroarch.start_retroarch(
platform, str(rom), display_num, rom_name)
await ws.send_json({'type': 'ready'})
import webrtc
async def cleanup():
await runner_retroarch.terminate(ra, xvfb)
ALLOC.release(display_num)
await webrtc.run_peer(ws, display_num, cleanup)
except Exception as e:
log.exception('rtc session failed')
try:
await ws.send_json({'type': 'error', 'error': str(e)})
except Exception:
pass
await runner_retroarch.terminate(ra, xvfb)
ALLOC.release(display_num)
finally:
if not ws.closed:
await ws.close()
return ws
# --------------------------------------------------------------------- app
def build_app() -> web.Application:
app = web.Application(client_max_size=saves.MAX_SAVE_BYTES + 1024)
r = app.router
r.add_post('/api/stream/start', handle_start)
r.add_post('/api/stream/{sid}/stop', handle_stop)
r.add_post('/api/stream/{sid}/input', handle_input)
r.add_post('/api/stream/{sid}/analog', handle_analog)
r.add_post('/api/stream/{sid}/text', handle_text)
r.add_post('/api/stream/{sid}/mouse', handle_mouse)
r.add_get('/api/stream/status', handle_status)
r.add_get('/remote', handle_remote)
r.add_get('/api/play/route', handle_route)
r.add_get('/api/play/streamable', handle_streamable)
r.add_get('/api/romfile/{platform}/{name}', handle_romfile)
r.add_put('/api/saves/{platform}/{name}', handle_save_put)
r.add_get('/api/saves/{platform}/{name}', handle_save_get)
r.add_get('/api/rtc/signal', handle_rtc_signal)
# HTTP signaling, for clients that cannot use the WebSocket one — see
# webrtc.answer_offer for why the Xbox shell is one of them.
r.add_post('/api/rtc/offer', handle_rtc_offer)
r.add_options('/api/rtc/offer', handle_rtc_options)
r.add_post('/api/rtc/{sid}/stop', handle_rtc_stop)
return app
async def main():
runner = web.AppRunner(build_app())
await runner.setup()
await web.TCPSite(runner, '0.0.0.0', 8090).start()
log.info('RomM stream server on :8090')
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(main())