This repository was archived by the owner on Aug 28, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnvram_monitor.py
More file actions
2210 lines (1989 loc) · 85.4 KB
/
Copy pathnvram_monitor.py
File metadata and controls
2210 lines (1989 loc) · 85.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
990
991
992
993
994
995
996
997
998
999
1000
import glob
import json
import os
import re
import subprocess
import sys
import time
import zlib
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple
try:
import psutil as _psutil
_PSUTIL_OK = True
except ImportError:
_psutil = None # type: ignore
_PSUTIL_OK = False
try:
from pinmame_live import PinMameLiveSession
except Exception:
PinMameLiveSession = None # type: ignore
def _parse_int(value, default=None):
if value is None:
return default
if isinstance(value, bool):
return int(value)
if isinstance(value, int):
return value
if isinstance(value, str):
v = value.strip().lower()
if v.startswith('0x'):
try:
return int(v, 16)
except Exception:
return default
try:
return int(v)
except Exception:
return default
return default
@dataclass
class NVRAMSegment:
address: int
size: int
file_base: int
nibble: str
class MapRepository:
def __init__(self, root_dir: str):
self.root_dir = root_dir
self.index_path = os.path.join(root_dir, 'index.json')
self.maps_dir = os.path.join(root_dir, 'maps')
self.platform_dir = os.path.join(root_dir, 'platforms')
self._index = {}
self._map_cache: Dict[str, dict] = {}
self._platform_cache: Dict[str, dict] = {}
self._load_index()
def _load_index(self):
with open(self.index_path, 'r', encoding='utf-8') as f:
self._index = json.load(f)
def _resolve_map_rel(self, rom: str) -> Optional[str]:
rel = self._index.get(rom)
if isinstance(rel, str) and rel.endswith('.map.json'):
return rel
return None
def has_rom(self, rom: str) -> bool:
return self._resolve_map_rel(rom) is not None
def map_for_rom(self, rom: str) -> Optional[dict]:
rel = self._resolve_map_rel(rom)
if not rel:
return None
if rel not in self._map_cache:
p = os.path.join(self.root_dir, rel)
with open(p, 'r', encoding='utf-8') as f:
self._map_cache[rel] = json.load(f)
return self._map_cache[rel]
def platform_for_map(self, map_data: dict) -> Optional[dict]:
meta = map_data.get('_metadata', {})
platform = meta.get('platform')
if not platform:
return None
if platform not in self._platform_cache:
p = os.path.join(self.platform_dir, f'{platform}.json')
with open(p, 'r', encoding='utf-8') as f:
self._platform_cache[platform] = json.load(f)
return self._platform_cache[platform]
class DescriptorDecoder:
def __init__(self, map_data: dict, platform_data: Optional[dict], direct_mode: bool = False):
self.map_data = map_data or {}
self.platform_data = platform_data or {}
self.char_map = self.map_data.get('_metadata', {}).get('char_map')
self.shared_values = self.map_data.get('_metadata', {}).get('values', {})
self.default_endian = self.platform_data.get('endian', 'big').lower()
self.segments = self._build_segments(self.platform_data)
self.low_ram_mirror_limit = self._infer_low_ram_mirror_limit(self.platform_data)
self.default_nibble = self.segments[0].nibble if self.segments else 'both'
self.direct_mode = direct_mode
@staticmethod
def _build_segments(platform_data: dict) -> List[NVRAMSegment]:
layout = platform_data.get('memory_layout', []) if isinstance(platform_data, dict) else []
nv = []
for entry in layout:
if entry.get('type') != 'nvram':
continue
addr = _parse_int(entry.get('address'))
size = _parse_int(entry.get('size'))
if addr is None or size is None or size <= 0:
continue
nv.append((addr, size, (entry.get('nibble') or 'both').lower()))
nv.sort(key=lambda x: x[0])
out: List[NVRAMSegment] = []
file_base = 0
for addr, size, nibble in nv:
out.append(NVRAMSegment(address=addr, size=size, file_base=file_base, nibble=nibble))
file_base += size
return out
@staticmethod
def _infer_low_ram_mirror_limit(platform_data: dict) -> int:
layout = platform_data.get('memory_layout', []) if isinstance(platform_data, dict) else []
nvram_addrs: List[int] = []
ram_zero_size = 0
for entry in layout:
addr = _parse_int(entry.get('address'))
size = _parse_int(entry.get('size'))
if addr is None or size is None or size <= 0:
continue
typ = (entry.get('type') or '').lower()
if typ == 'nvram':
nvram_addrs.append(addr)
elif typ == 'ram' and addr == 0:
ram_zero_size = max(ram_zero_size, size)
if not nvram_addrs or ram_zero_size <= 0:
return 0
first_nvram = min(nvram_addrs)
# Some platforms (notably Williams System4/6/7) mirror low banked RAM
# into the beginning of the persisted NVRAM blob.
if first_nvram > 0 and ram_zero_size >= first_nvram:
return first_nvram
return 0
def _segment_for_addr(self, addr: int) -> Optional[NVRAMSegment]:
for seg in self.segments:
if seg.address <= addr < seg.address + seg.size:
return seg
return None
def _resolve_addresses(self, desc: dict) -> List[int]:
if 'offsets' in desc and isinstance(desc['offsets'], list):
return [a for a in (_parse_int(v) for v in desc['offsets']) if a is not None]
start = _parse_int(desc.get('start'))
if start is None:
return []
length = _parse_int(desc.get('length'))
if length is not None:
if length < 1:
return []
return list(range(start, start + length))
end = _parse_int(desc.get('end'))
if end is not None and end >= start:
return list(range(start, end + 1))
return [start]
def _resolve_values(self, desc: dict) -> List[Any]:
values = desc.get('values', [])
if isinstance(values, str):
shared = self.shared_values.get(values)
if isinstance(shared, list):
return shared
return []
if isinstance(values, list):
return values
return []
def _apply_mask(self, b: int, desc: dict) -> int:
mask = desc.get('mask')
if mask is None:
return b
m = _parse_int(mask)
if m is None:
return b
return b & m
def _read_units(self, data: bytes, desc: dict) -> Optional[Tuple[List[int], str]]:
addrs = self._resolve_addresses(desc)
if not addrs:
return None
units: List[int] = []
desc_nibble = (desc.get('nibble') or '').lower()
for addr in addrs:
if self.direct_mode:
file_off = addr
nibble_mode = desc_nibble or 'both'
# Preferred path: platform-aware address mapping.
elif self.segments:
seg = self._segment_for_addr(addr)
if seg is None:
if self.low_ram_mirror_limit > 0 and 0 <= addr < self.low_ram_mirror_limit:
file_off = addr
# Mirrored low RAM is stored as raw bytes at the beginning
# of the NVRAM file, independent of NVRAM nibble packing.
nibble_mode = desc_nibble or 'both'
else:
return None
else:
file_off = seg.file_base + (addr - seg.address)
nibble_mode = desc_nibble or seg.nibble
else:
# Compatibility path for maps without platform metadata.
file_off = addr
nibble_mode = desc_nibble or 'both'
if file_off < 0 or file_off >= len(data):
return None
raw_b = data[file_off]
if nibble_mode == 'low':
# For nibble-based platforms, apply mask to the selected nibble unit.
# Maps use nibble masks (0x0..0xF), not byte masks (0x00..0xFF).
unit = raw_b & 0x0F
units.append(self._apply_mask(unit, desc))
elif nibble_mode == 'high':
unit = (raw_b >> 4) & 0x0F
units.append(self._apply_mask(unit, desc))
else:
units.append(self._apply_mask(raw_b, desc))
return units, (desc_nibble or (nibble_mode if 'nibble_mode' in locals() else 'both'))
def _decode_int(self, units: List[int], endian: str) -> int:
ordered = list(reversed(units)) if endian == 'little' else units
value = 0
for b in ordered:
value = (value << 8) | (b & 0xFF)
return value
def _decode_bcd(self, units: List[int], nibble_mode: str, endian: str) -> int:
ordered = list(reversed(units)) if endian == 'little' else units
digits = []
if nibble_mode in ('low', 'high'):
for n in ordered:
digits.append(n if 0 <= n <= 9 else 0)
else:
for b in ordered:
hi = (b >> 4) & 0x0F
lo = b & 0x0F
digits.append(hi if hi <= 9 else 0)
digits.append(lo if lo <= 9 else 0)
value = 0
for d in digits:
value = (value * 10) + d
return value
def _decode_ch(self, units: List[int], nibble_mode: str, desc: dict) -> str:
if nibble_mode in ('low', 'high'):
bytes_out = []
i = 0
while i + 1 < len(units):
bytes_out.append(((units[i] & 0x0F) << 4) | (units[i + 1] & 0x0F))
i += 2
else:
bytes_out = [u & 0xFF for u in units]
chars = []
null_mode = (desc.get('null') or 'ignore').lower()
for b in bytes_out:
if self.char_map:
if b < len(self.char_map):
ch = self.char_map[b]
else:
ch = ' '
else:
if b == 0:
ch = '\x00'
elif 32 <= b <= 126:
ch = chr(b)
else:
ch = ' '
if ch == '\x00':
if null_mode in ('truncate', 'terminate'):
break
if null_mode == 'ignore':
continue
chars.append(ch)
return ''.join(chars)
def _decode_dipsw(self, data: bytes, desc: dict):
# PinMAME DIP switches are stored in the last 6 bytes of the .nv file.
# SW1 is LSB of the first of those six bytes.
offsets = desc.get('offsets')
if not isinstance(offsets, list) or not offsets:
return None
if len(data) < 6:
return None
index = 0
dip_base = len(data) - 6
for sw in offsets:
sw_num = _parse_int(sw)
if sw_num is None or sw_num < 1:
return None
pos = sw_num - 1
byte_off = dip_base + (pos // 8)
bit_off = pos % 8
if byte_off < dip_base or byte_off >= len(data):
return None
bit = 1 if (data[byte_off] & (1 << bit_off)) else 0
index = (index << 1) | bit
values = self._resolve_values(desc)
if values and 0 <= index < len(values):
return values[index]
return index
def _decode_bits(self, units: List[int], endian: str, desc: dict):
raw = self._decode_int(units, endian)
values = self._resolve_values(desc)
if not values:
return raw
# Spec expects numeric values that are summed for set bits.
if all(isinstance(v, (int, float)) for v in values):
out = 0
for i, v in enumerate(values):
if raw & (1 << i):
out += int(v)
return out
# Fallback for non-numeric maps: return selected labels.
selected = []
for i, v in enumerate(values):
if raw & (1 << i):
selected.append(v)
return selected
def _decode_enum(self, units: List[int], endian: str, desc: dict):
idx = self._decode_int(units, endian)
values = self._resolve_values(desc)
if values and 0 <= idx < len(values):
return values[idx]
return idx
def _decode_wpc_rtc(self, units: List[int], endian: str):
ordered = list(reversed(units)) if endian == 'little' else units
if len(ordered) < 7:
return None
year = ((ordered[0] & 0xFF) << 8) | (ordered[1] & 0xFF)
month = ordered[2] & 0xFF
day = ordered[3] & 0xFF
dow = ordered[4] & 0xFF
hour = ordered[5] & 0xFF
minute = ordered[6] & 0xFF
return {
'year': year,
'month': month,
'day': day,
'day_of_week': dow,
'hour': hour,
'minute': minute,
}
def decode(self, data: bytes, desc: dict):
encoding = (desc.get('encoding') or '').lower()
if not encoding:
return None
if encoding == 'dipsw':
return self._decode_dipsw(data, desc)
ru = self._read_units(data, desc)
if ru is None:
return None
units, nibble_mode = ru
endian = (desc.get('endian') or self.default_endian or 'big').lower()
if encoding == 'int':
value = self._decode_int(units, endian)
elif encoding == 'bcd':
value = self._decode_bcd(units, nibble_mode, endian)
elif encoding == 'bool':
raw = self._decode_int(units, endian)
value = raw != 0
if bool(desc.get('invert', False)):
value = not value
return value
elif encoding == 'ch':
return self._decode_ch(units, nibble_mode, desc)
elif encoding == 'raw':
return bytes(units)
elif encoding == 'enum':
return self._decode_enum(units, endian, desc)
elif encoding == 'bits':
value = self._decode_bits(units, endian, desc)
elif encoding == 'wpc_rtc':
return self._decode_wpc_rtc(units, endian)
else:
return None
if isinstance(value, int):
scale = desc.get('scale')
if scale is not None:
try:
value = int(value * float(scale))
except Exception:
pass
off = desc.get('offset')
if off is not None:
try:
value = int(value + float(off))
except Exception:
pass
return value
@dataclass
class RomState:
active: bool = False
session_best: int = 0
last_best: int = 0
last_scores: Tuple[int, ...] = tuple()
last_change_ts: float = 0.0
last_update_ts: float = 0.0
session_start_ts: float = 0.0
baseline_match_counter: Optional[int] = None
last_match_counter: Optional[int] = None
last_game_over: Optional[bool] = None
last_current_ball: Optional[int] = None
last_sent_score: int = 0
last_sent_ts: float = 0.0
has_nonstart_update: bool = False
warned_no_disk_updates: bool = False
last_short_end_warn_ts: float = 0.0
last_progress_ts: float = 0.0
attract_pattern_ts: float = 0.0
class NVRAMMonitor:
def __init__(
self,
maps_root: str,
nvram_dir: str,
nvram_scan_pattern: str,
logger: Callable[[str, str], None],
on_current_scores: Callable[[str, List[int], Optional[int]], None],
on_game_end: Callable[[str, List[int], str, Optional[int]], None],
on_game_start: Optional[Callable[[str], None]] = None,
on_status_message: Optional[Callable[[str, str], None]] = None,
use_live_pinmame: bool = True,
poll_interval_sec: float = 1.0,
game_end_stable_sec: float = 8.0,
idle_end_sec: float = 45.0,
min_game_duration_sec: float = 60.0,
):
self.repo = MapRepository(maps_root)
self.nvram_dir = nvram_dir
self.nvram_scan_pattern = (nvram_scan_pattern or '*.nv').strip() or '*.nv'
self._log = logger
self.on_current_scores = on_current_scores
self.on_game_end = on_game_end
self.on_game_start = on_game_start
self.on_status_message = on_status_message
self.use_live_pinmame = bool(use_live_pinmame)
self.poll_interval_sec = max(0.2, poll_interval_sec)
self.game_end_stable_sec = max(3.0, game_end_stable_sec)
self.idle_end_sec = max(self.game_end_stable_sec, idle_end_sec)
self.min_game_duration_sec = max(0.0, min_game_duration_sec)
self._file_mtime: Dict[str, float] = {}
self._file_crc32: Dict[str, int] = {}
self._state: Dict[str, RomState] = {}
self.active_rom: Optional[str] = None
self.active_path: Optional[str] = None
self._live_session = PinMameLiveSession() if PinMameLiveSession is not None else None
self._last_live_crc_by_rom: Dict[str, int] = {}
self._last_live_diag_ts = 0.0
self._last_live_unchanged_log_ts = 0.0
self._last_live_snapshot_err_ts = 0.0
self._last_live_warn_ts = 0.0
self._last_live_attach_attempt_log_ts = 0.0
self._last_live_snapshot_attempt_log_ts = 0.0
self._last_wait_log_ts = 0.0
self._last_vpx_probe_ts = 0.0
self._last_vpx_diag_ts = 0.0
self._last_vpx_presence_diag_ts = 0.0
self._last_any_vpx_seen_ts = 0.0
self._last_attach_filter_diag_ts = 0.0
self._vpx_proc_cache: Optional[List[Tuple[int, str, str]]] = None
self._vpx_proc_cache_ts: float = 0.0
self._last_unsupported_warn_by_rom: Dict[str, float] = {}
self._rom_live_support_cache: Dict[str, Tuple[bool, str]] = {}
self._unsupported_active_rom: Optional[str] = None
self._unsupported_active_path: Optional[str] = None
self._unsupported_active_since: float = 0.0
self._live_unsupported_by_rom: Dict[str, str] = {}
self._last_live_unsupported_log_by_rom: Dict[str, float] = {}
# Limit attach targets to known VPX renderer executables.
self._allowed_attach_exec_basenames = {
'vpinballx_bgfx',
'vpinballx_bgfx.exe',
'vpinball_bgfx',
'vpinball_bgfx.exe',
'vpinballx_bgfx64',
'vpinballx_bgfx64.exe',
'vpinball_bgfx64',
'vpinball_bgfx64.exe',
'vpinballx_gl',
'vpinballx_gl.exe',
'vpinball_gl',
'vpinball_gl.exe',
'vpinballx_gl64',
'vpinballx_gl64.exe',
'vpinball_gl64',
'vpinball_gl64.exe',
}
@staticmethod
def _looks_nonplay_score_pattern(scores: Tuple[int, ...]) -> bool:
if not scores:
return True
non_zero = [v for v in scores if isinstance(v, int) and v > 0]
if not non_zero:
return True
# Attract/high-score cycle pattern seen in several families.
if len(non_zero) >= 3 and len(set(non_zero)) == 1:
return True
# In single-player games, P1=0 while other players show values is usually
# not an in-play score state.
if scores[0] == 0 and any(v > 0 for v in scores[1:]):
return True
return False
def _canon_path(self, path: str) -> str:
p = os.path.expanduser(path or '')
p = os.path.normpath(p)
p = os.path.realpath(p)
if os.name == 'nt':
p = os.path.normcase(p)
return p
def _read_file(self, path: str) -> Optional[bytes]:
try:
with open(path, 'rb') as f:
return f.read()
except Exception:
return None
def _extract_game_state(self, rom: str, data: bytes, direct_mode: bool = False):
map_data = self.repo.map_for_rom(rom)
if not map_data:
return None
platform_data = self.repo.platform_for_map(map_data) or {}
decoder = DescriptorDecoder(map_data, platform_data, direct_mode=direct_mode)
gs = map_data.get('game_state')
if not isinstance(gs, dict):
return None
def decode_desc(d):
if not isinstance(d, dict):
return None
return decoder.decode(data, d)
scores = []
raw_scores = gs.get('scores')
if isinstance(raw_scores, list):
for s in raw_scores:
v = decode_desc(s)
try:
iv = int(v)
except Exception:
iv = 0
scores.append(max(0, iv))
game_over = decode_desc(gs.get('game_over')) if isinstance(gs.get('game_over'), dict) else None
current_ball = decode_desc(gs.get('current_ball')) if isinstance(gs.get('current_ball'), dict) else None
try:
current_ball = int(current_ball) if current_ball is not None else None
except Exception:
current_ball = None
match_counter = decode_desc(gs.get('match_counter')) if isinstance(gs.get('match_counter'), dict) else None
try:
match_counter = int(match_counter) if match_counter is not None else None
except Exception:
match_counter = None
player_count = decode_desc(gs.get('player_count')) if isinstance(gs.get('player_count'), dict) else None
try:
player_count = int(player_count) if player_count is not None else None
except Exception:
player_count = None
current_player = decode_desc(gs.get('current_player')) if isinstance(gs.get('current_player'), dict) else None
try:
current_player = int(current_player) if current_player is not None else None
except Exception:
current_player = None
ball_count = decode_desc(gs.get('ball_count')) if isinstance(gs.get('ball_count'), dict) else None
try:
ball_count = int(ball_count) if ball_count is not None else None
except Exception:
ball_count = None
final_scores: List[int] = []
if isinstance(gs.get('final_scores'), list):
for s in gs.get('final_scores', []):
v = decode_desc(s)
try:
iv = int(v)
except Exception:
iv = 0
final_scores.append(max(0, iv))
return {
'scores': scores,
'best': max(scores) if scores else 0,
'final_scores': final_scores,
'game_over': bool(game_over) if isinstance(game_over, bool) else None,
'current_ball': current_ball,
'match_counter': match_counter,
'player_count': player_count,
'current_player': current_player,
'ball_count': ball_count,
}
def _should_start(self, st: RomState, parsed: dict, prev_best: int, prev_scores: Tuple[int, ...]) -> bool:
best = parsed['best']
game_over = parsed['game_over']
current_ball = parsed['current_ball']
ball_count = parsed.get('ball_count')
player_count = parsed['player_count']
current_player = parsed.get('current_player')
prev_game_over = st.last_game_over
valid_ball = False
if current_ball is not None and current_ball > 0:
if ball_count is None or ball_count <= 0:
valid_ball = True
else:
valid_ball = current_ball <= ball_count
valid_player = False
if player_count is not None and player_count > 0:
if current_player is None:
valid_player = True
else:
valid_player = 1 <= current_player <= player_count
# Strongest start signal: known game-over flag transitions true -> false.
if prev_game_over is True and game_over is False:
return True
# A positively asserted game-over state should not arm a new session.
if game_over is True:
return False
# Active play indicators from map (ball and/or player state).
if valid_ball and (valid_player or player_count is None):
return True
# Use game_over=false only when corroborated by valid player context.
if game_over is False and valid_player and (valid_ball or best > 0):
return True
# Last-resort fallback when maps only expose scores:
# require at least one prior sample to avoid stale attract-mode starts.
if prev_scores and prev_best > 0 and best > prev_best and best > 0 and game_over is not True:
return True
return False
def _clear_active_monitoring(self, rom: Optional[str] = None, force_wait_log: bool = False):
if rom is not None and self.active_rom != rom:
return
self.active_rom = None
self.active_path = None
if self._live_session is not None:
self._live_session.detach()
self._last_live_crc_by_rom.clear()
if force_wait_log:
self._log_waiting(force=True)
def _mark_live_unsupported(self, rom: str, reason: str):
self._live_unsupported_by_rom[rom] = reason
now = time.time()
last = self._last_live_unsupported_log_by_rom.get(rom, 0.0)
if (now - last) >= 30.0:
if os.name == 'nt' and reason == 'pinmame_exports_not_found':
self._log(
'WARN',
(
f'Windows VPX build for ROM "{rom}" does not expose the live PinMAME API; '
'using NVRAM file fallback only'
),
)
else:
self._log('WARN', f'Live PinMAME disabled for ROM "{rom}": {reason}')
self._last_live_unsupported_log_by_rom[rom] = now
def _maybe_emit_game_end(self, rom: str, st: RomState, parsed: dict, reason: str):
now = time.time()
duration = now - st.session_start_ts if st.session_start_ts else 0
if duration < self.min_game_duration_sec:
if (now - st.last_short_end_warn_ts) >= 5.0:
self._log(
'WARN',
(
f'Ignoring game_end for {rom}: reason={reason}, '
f'duration too short ({duration:.1f}s < {self.min_game_duration_sec:.0f}s)'
),
)
st.last_short_end_warn_ts = now
# Keep active sessions alive for in-play false positives (for example,
# transient game_over/ball signals between balls). Only clear state when
# the table has actually exited.
if reason in ('vpx_play_exit', 'vpx_exit_unsupported_nvram'):
st.active = False
st.session_best = 0
st.session_start_ts = 0.0
st.has_nonstart_update = False
st.warned_no_disk_updates = False
st.last_progress_ts = 0.0
st.attract_pattern_ts = 0.0
else:
# Rearm stable-window checks to avoid repeated end attempts every tick.
st.last_change_ts = now
return
best = max(st.session_best, parsed.get('best', 0))
if best <= 0:
st.active = False
st.session_best = 0
st.session_start_ts = 0.0
st.has_nonstart_update = False
st.warned_no_disk_updates = False
st.last_progress_ts = 0.0
st.attract_pattern_ts = 0.0
self._clear_active_monitoring(rom, force_wait_log=True)
return
if st.last_sent_score == best and (now - st.last_sent_ts) < 15:
st.active = False
st.session_best = 0
st.session_start_ts = 0.0
st.has_nonstart_update = False
st.warned_no_disk_updates = False
st.last_progress_ts = 0.0
st.attract_pattern_ts = 0.0
self._clear_active_monitoring(rom, force_wait_log=True)
return
scores = parsed.get('scores') or [best]
final_scores = parsed.get('final_scores') or []
if isinstance(final_scores, list) and final_scores:
final_norm: List[int] = []
for v in final_scores:
try:
iv = int(v)
except Exception:
iv = 0
final_norm.append(max(0, iv))
if parsed.get('game_over') is True:
session_ref = max(st.session_best, parsed.get('best', 0))
final_best = max(final_norm, default=0)
# Use final_scores only when it is plausible for the active session.
if final_best > 0 and (session_ref <= 0 or final_best <= int(session_ref * 1.2) + 100000):
scores = final_norm
best = max(best, final_best)
self.on_game_end(rom, scores, reason, int(duration))
st.last_sent_score = best
st.last_sent_ts = now
st.active = False
st.session_best = 0
st.session_start_ts = 0.0
st.has_nonstart_update = False
st.warned_no_disk_updates = False
st.last_short_end_warn_ts = 0.0
st.last_progress_ts = 0.0
st.attract_pattern_ts = 0.0
self._clear_active_monitoring(rom, force_wait_log=True)
def _handle_update(self, rom: str, parsed: dict, force_start: bool = False):
now = time.time()
st = self._state.setdefault(rom, RomState())
started_now = False
scores = tuple(parsed.get('scores') or [])
best = parsed.get('best', 0)
prev_scores = st.last_scores
prev_game_over = st.last_game_over
prev_current_ball = st.last_current_ball
st.last_update_ts = now
if scores != st.last_scores:
st.last_scores = scores
st.last_change_ts = now
prev_best = st.last_best
if scores:
self.on_current_scores(rom, list(scores), parsed.get('current_ball'))
if not st.active and (force_start or self._should_start(st, parsed, prev_best, prev_scores)):
if force_start or not self._looks_nonplay_score_pattern(scores):
st.active = True
st.session_start_ts = now
st.session_best = best
st.last_progress_ts = now
st.last_change_ts = now
st.baseline_match_counter = parsed.get('match_counter')
# A start signal can come from stale state in builds that only flush .nv on exit.
# Require at least one subsequent update before allowing idle/game-over heuristics.
st.has_nonstart_update = False
st.warned_no_disk_updates = False
st.attract_pattern_ts = 0.0
started_now = True
self._log('INFO', f'Game started (NVRAM): {rom}')
if self.on_game_start:
self.on_game_start(rom)
if st.active:
if not started_now and not force_start:
st.has_nonstart_update = True
st.warned_no_disk_updates = False
effective_best = best
looks_nonplay = self._looks_nonplay_score_pattern(scores)
non_zero_scores = [v for v in scores if isinstance(v, int) and v > 0]
is_mirrored_attract = len(non_zero_scores) >= 3 and len(set(non_zero_scores)) == 1
if is_mirrored_attract and st.session_best > 0:
st.attract_pattern_ts = now
if looks_nonplay and st.session_best > 0:
# Do not treat attract/high-score cycles as in-play score progress.
effective_best = st.session_best
if effective_best > st.session_best:
st.last_progress_ts = now
st.session_best = max(st.session_best, effective_best)
match_counter = parsed.get('match_counter')
game_over = parsed.get('game_over')
current_ball = parsed.get('current_ball')
if st.baseline_match_counter is not None and match_counter is not None and match_counter != st.baseline_match_counter:
self._maybe_emit_game_end(rom, st, parsed, 'match_counter_changed')
st.baseline_match_counter = match_counter
st.last_match_counter = match_counter
st.last_game_over = game_over
st.last_current_ball = current_ball
return
stable = (now - st.last_change_ts) >= self.game_end_stable_sec
ball_count = parsed.get('ball_count')
final_scores = parsed.get('final_scores') or []
final_best = 0
if isinstance(final_scores, list):
for v in final_scores:
try:
iv = int(v)
except Exception:
iv = 0
if iv > final_best:
final_best = iv
def _is_in_play_ball(ball_value: Optional[int], count_value: Optional[int]) -> bool:
if ball_value is None:
return False
if ball_value <= 0:
return False
if count_value is None or count_value <= 0:
return True
return ball_value <= count_value
current_in_play_ball = _is_in_play_ball(current_ball, ball_count)
prev_in_play_ball = _is_in_play_ball(prev_current_ball, ball_count)
progress_idle = (now - st.last_progress_ts) if st.last_progress_ts else 0.0
if game_over is True and prev_game_over is not True and stable and st.has_nonstart_update:
self._maybe_emit_game_end(rom, st, parsed, 'game_over')
elif (not current_in_play_ball) and prev_in_play_ball and stable and st.has_nonstart_update:
# Generic fallback from map spec: current_ball values of 0 or
# values larger than ball_count indicate "no game in progress".
self._maybe_emit_game_end(rom, st, parsed, 'ball_out_of_play_stable')
elif (
game_over is True
and stable
and st.has_nonstart_update
and st.session_best > 0
and progress_idle >= self.game_end_stable_sec
):
# Generic fallback when edge transitions were missed but end-of-game
# state is latched and score progression has stopped.
self._maybe_emit_game_end(rom, st, parsed, 'game_over_latched')
elif (
st.has_nonstart_update
and st.session_best > 0
and progress_idle >= self.game_end_stable_sec
and final_best > 0
and final_best >= int(st.session_best * 0.80)
and best <= int(st.session_best * 0.25)
):
# Fallback for families where end-of-game DMD cycles keep changing
# "scores" rapidly (preventing score-stability checks), but final_scores
# already contain the just-finished game result.
self._maybe_emit_game_end(rom, st, parsed, 'final_scores_no_progress')
elif (
st.has_nonstart_update
and st.session_best > 0
and st.attract_pattern_ts > 0
and (now - st.attract_pattern_ts) >= 2.0
and progress_idle >= self.game_end_stable_sec
and looks_nonplay
):
# Generic fallback when maps do not expose reliable game_over/current_ball:
# if we have seen attract-style mirrored scores and no in-game score progress,
# treat it as game end without waiting for VPX process exit.
self._maybe_emit_game_end(rom, st, parsed, 'attract_pattern_no_progress')
st.last_best = best
st.last_match_counter = parsed.get('match_counter')
st.last_game_over = parsed.get('game_over')
st.last_current_ball = parsed.get('current_ball')
def _check_idle_ends(self):
now = time.time()
for rom, st in self._state.items():
if not st.active:
continue
if not st.has_nonstart_update:
# Session was force-started (e.g. file handle detected) but no
# real NVRAM content updates were observed yet.
continue
idle = now - st.last_update_ts
stable = now - st.last_change_ts
if idle >= self.idle_end_sec and stable >= self.game_end_stable_sec:
parsed = {
'scores': list(st.last_scores) if st.last_scores else [st.session_best],
'best': max(st.session_best, st.last_best),
}
self._maybe_emit_game_end(rom, st, parsed, 'idle_timeout')
if self.active_rom == rom:
self.active_rom = None
self._log_waiting(force=True)
def _check_stale_disk_updates(self):
now = time.time()
for rom, st in self._state.items():
if not st.active:
continue
if st.has_nonstart_update:
continue
if st.warned_no_disk_updates:
continue
if not st.session_start_ts:
continue
if (now - st.session_start_ts) < 20.0:
continue
st.warned_no_disk_updates = True
self._log(
'WARN',
(
f'No NVRAM disk updates observed for active ROM "{rom}" after '
f'{now - st.session_start_ts:.0f}s; this VPX build appears to flush NVRAM on exit'
),
)
def _check_vpx_play_exit(self):
if self.active_rom is None: