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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677 | class NodeEngine(BaseEngine):
"""
This engine manages players for each node
Communicates with the ControllerEngine via OSCQuery
Interacts with Player objects via OSC
It is responsible for:
- Starting and stopping players
- Monitoring player status
- Restarting players
- Updating player configurations
- Handling player failures
- Providing a clean interface for starting and stopping players
- Providing a clean interface for monitoring player status
"""
# Set in _setup_nng_command_callback; None until then (and in unit tests
# that build the engine without its comms).
_follow_relay = None
# D31 (d): the UI toggles this node has received (bus order), and how
# many it had when the last GO arrived (a toggle that came before a GO
# counts for everything that GO starts). Class defaults: shells built
# with object.__new__ read them too.
_ui_seq = 0
_go_root_seq = 0
_no_send_time_warned_gen = None
# stop_project (869fhjdq5): after this node reports an authored end of the
# show, how long it waits for the controller's STOP before it logs that
# the show is still running. Log only; the node never stops itself.
_STOP_PROJECT_WATCHDOG_S = 3.0
_stop_project_watchdog: threading.Timer | None = None
# GO anchor tolerance (Badajoz 2026-09-25 fix): how far the controller's
# shipped GO instant may disagree with this node's own MTC before
# _resolve_go_anchor distrusts it and falls back to a live local read.
# Positive: the controller may be slightly AHEAD of this node's own read
# (its go_script runs microseconds before this node computes the lag).
# Negative: this node may lag the controller by up to 10s before the
# value is treated as stale/misrouted rather than "node was just slow".
_GO_ANCHOR_FUTURE_TOL_MS = 200.0
_GO_ANCHOR_MAX_LAG_MS = 10_000.0
# 869feynrj §4.5d: this node's output latency + one JACK period (ms), the
# maximum seen since start (settings override, a JACK query at start,
# every player's LATENCY line), and the largest value already reported
# to the controller (armed_ready, or the out_latency STATUS).
_out_latency_ms: float | None = None
_out_latency_reported: float | None = None
_out_latency_warned_load = False
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._command_lock = threading.Lock()
self._loading_lock = threading.Lock()
self._loading = False
self._project_generation: int = 0
# Bumped on EVERY set_next_cue call, even reselecting the same cue.
# Lets a PreArm background thread's should_continue notice a later
# selection landed and stop advancing its own (now stale) walk —
# 869f79ecc.
self._selection_epoch: int = 0
# Cue ids that loop in legacy mode on this node for the loaded project
# (no loop period in time, 869ejxng3); reported in every armed_ready.
self._legacy_period: list[str] = []
# with_cm=False (test shells) skips ConfigManager — no controller_ip/cm.
if self.with_cm and hasattr(self, "cm") and hasattr(self, "controller_ip"):
self.nng_hub_address = (
f"tcp://{self.controller_ip}:{self.cm.node_conf['nng_hub_port']}"
)
# add_system_ports() / add_config_ports() moved to
# BaseEngine.__init__ so the controller engine gets them too.
self.deploy_manager = CuemsDeploy(
library_path=self.cm.library_path,
tmp_path=self.cm.tmp_path,
controller_ip=self.controller_ip, # set by set_config_manager()
)
PLAYER_HANDLER.add_media_folder(self.cm.library_path)
PLAYER_HANDLER.set_player_endpoints_generator(
self.add_player_endpoints,
# TODO: Use node host from config
prefix="/players",
)
else:
self.nng_hub_address = None
self.deploy_manager = None
def start(self):
self._log_versions()
PLAYER_HANDLER.refresh_video_caps()
START_GATE.set_node_name(socket.gethostname())
START_GATE.set_latency_listener(self._on_player_latency)
CUE_HANDLER.set_nng_comms(self.nng_hub_address, self.cm.node_uuid)
self.deploy_manager.loop = CUE_HANDLER.communications_thread.event_loop
# Creates command dictionary and OSCQuery client
self.set_oscquery_comms()
# Creates player devices - must be before NNG callback
self.set_players()
# Set up NNG command receiving (after players ready)
self._setup_nng_command_callback()
if self.mtc_listener is not None:
self.mtc_listener.start()
super().start()
@staticmethod
def _log_versions() -> None:
"""The engine's own Debian package version (every rc6-N tag says
0.1.0rc6 to importlib, I8), and whether ffprobe is there for the loop
periods (869ejxng3 §4.5): the only version visibility there is (G15)."""
version = None
try:
r = subprocess.run(
["dpkg-query", "-W", "-f=${Version}", "cuems-engine"],
capture_output=True,
text=True,
timeout=5,
)
version = r.stdout.strip() if r.returncode == 0 else None
except Exception:
pass
if not version:
try:
from importlib.metadata import version as _v
version = f"{_v('cuemsengine')} (python package)"
except Exception:
version = "unknown"
Logger.info(f"node engine: cuems-engine {version}")
test_knobs.announce()
if shutil.which("ffprobe") is None:
Logger.warning(
"ffprobe not found: looping cues without a .period sidecar run "
"in legacy mode (a gap per pass)"
)
def _setup_nng_command_callback(self):
"""
Set up the callback for receiving commands via NNG from
ControllerEngine.
This provides push-based command delivery as an alternative to HTTP
polling.
Commands are received via the NNG bus and routed to the appropriate
handlers.
"""
if (
hasattr(CUE_HANDLER, "communications_thread")
and CUE_HANDLER.communications_thread
):
CUE_HANDLER.communications_thread.set_command_callback(
self._handle_nng_command
)
Logger.info("NNG command callback registered for NodeEngine")
# Cross-node Auto follow (869fc8ytz): announce this node's
# follows, apply the ones relayed from other nodes, in bus order.
self._follow_relay = FollowRelay(
CUE_HANDLER,
node_id=self.cm.node_uuid,
send=self._send_follow,
get_script=lambda: self.script,
get_mtc=lambda: getattr(self, "mtc_listener", None),
get_project_gen=lambda: self._project_generation,
first_local=self._first_local_enabled_in_go_chain,
)
CUE_HANDLER._follow = self._follow_relay
CUE_HANDLER.communications_thread.set_receive_hook(
self._on_command_received
)
else:
Logger.warning(
"CUE_HANDLER communications thread: "
"not available for command callback"
)
from .cues.ActionHandler import ACTION_HANDLER
ACTION_HANDLER.finalize_node_layer_bindings()
ACTION_HANDLER.set_result_sink(self._action_result_sink)
def _on_command_received(self, command_name: str, value, sent_ms=None) -> bool:
"""Receive hook: runs for every command in BUS order, before its
command thread races the others for the command lock (869fc8ytz).
A UI toggle sets its cue's flag here, with the controller's send time
(1amfwm7jnqf, D31 d, Design §3): toggles are taken in the order the
controller sent them, whatever order their command threads get the
lock. A GO records how many toggles came before it. A follow message
is applied here and consumed. GO records the controller's run
counter, STOP and load clear it and every pending follow -- here, so
a follow relayed before a STOP can never be applied after it. Must
not block."""
if command_name == "cue_enabled":
self._receive_toggle(value, sent_ms)
elif command_name == "go":
self._go_root_seq = self._ui_seq
relay = self._follow_relay
if relay is None:
return False
if command_name == "follow":
try:
relay.on_message(value)
except Exception as e:
# Consumed anyway: a follow message must never reach the
# command lock.
Logger.error(f"Follow message failed: {e}")
return True
if command_name == "go":
relay.begin_run(value)
elif command_name in ("stop", "load", "unload"):
relay.end_run(command_name)
# The STOP (or load) a stop_project cue was waiting for.
self._cancel_stop_project_watchdog()
return False
def _receive_toggle(self, value, sent_ms) -> None:
"""A UI toggle, in the receive hook: the flag is set at once and a
record kept on the cue (chain_pass.ui_toggle). With no send time, or
one more than W from this node's MTC, it counts from its arrival,
with a WARNING while a pass runs. Never raises."""
cue, enabled = self._parse_cue_enabled(value, quiet=True)
if cue is None:
return
self._ui_seq = self._ui_seq + 1
seq = self._ui_seq
now = None
mtc = getattr(self, "mtc_listener", None)
if mtc is not None:
try:
now = float(mtc.main_tc.milliseconds_exact)
except Exception:
now = None
CUE_HANDLER.retire_records(now)
try:
placed = chain_pass.ui_toggle(cue, enabled, sent_ms, now, seq)
except Exception as e:
Logger.error(f"cue_enabled for {cue.id}: the toggle hook failed ({e})")
chain_pass.place_at_arrival(cue, enabled, now, seq)
placed = False
if placed:
return
running = getattr(self, "ongoing_cue", None) is not None
if not running:
return
if sent_ms is None:
gen = getattr(self, "_project_generation", None)
if self._no_send_time_warned_gen != gen:
self._no_send_time_warned_gen = gen
Logger.warning(
"cue_enabled without a send time while a pass runs: "
"applied at once"
)
return
late = (now if now is not None else 0.0) - float(sent_ms)
Logger.warning(
f"cue_enabled for {cue.id} arrived {late:.0f} ms after it was sent "
f"(limit {chain_pass.W_MS:.0f} ms): applied at once"
)
def _parse_cue_enabled(self, value, quiet=False):
"""(cue, enabled) from ``"<cue_id> <0|1>"``, or (None, None)."""
warn = Logger.debug if quiet else Logger.warning
script = getattr(self, "script", None)
if not script:
warn("No script loaded, cannot toggle cue enabled")
return None, None
if not value or not isinstance(value, str):
warn(f"Invalid cue_enabled value: {repr(value)}")
return None, None
parts = value.split(" ", 1)
if len(parts) != 2 or parts[1] not in ("0", "1"):
warn(f"Invalid cue_enabled format: {repr(value)}")
return None, None
cue = script.find(parts[0])
if not cue:
warn(f"cue_enabled: cue {parts[0]} not found in script")
return None, None
return cue, parts[1] == "1"
def _send_follow(self, data: dict) -> None:
"""Queue a follow message (announce or cancel) to the controller,
which relays it to every node. Never waits."""
from .comms.NodesHub import ActionType, NodeOperation, OperationType
CUE_HANDLER.communications_thread.send_operation_nowait(
NodeOperation(
type=OperationType.STATUS,
action=ActionType.UPDATE,
sender=self.cm.node_uuid,
target="follow",
data=data,
)
)
def _handle_nng_command(self, command_name: str, value, address: str = None):
"""Handle a command received via NNG from ControllerEngine.
Args:
command_name: The command name (e.g., 'go', 'load', 'stop',
'player_control')
value: The command value
address: The original OSC address (optional)
"""
arrived = monotonic()
Logger.info(f"NNG command received: {command_name} = {repr(value)}")
if command_name == "player_control" and address:
# Handle player control messages (mixer volumes, video controls,
# etc.)
self._handle_player_control_message(address, value)
else:
# Handle standard commands (go, load, stop)
self.run_command(command_name, value, arrived=arrived)
def _handle_player_control_message(self, address: str, value):
"""Handle player control messages received via NNG.
Routes to appropriate player handlers based on the OSC address.
Supports two formats:
1. Engine format: /engine/players/<uuid>/<type>/...
2. Direct format: /<uuid>/<type>/... (from UI)
Args:
address: The OSC address
value: The value to set
"""
parts = address.strip("/").split("/")
# Determine format and extract node_uuid, player_type, path_parts
if len(parts) >= 4 and parts[0] == "engine" and parts[1] == "players":
# Engine format: /engine/players/<node_uuid>/<type>/...
node_uuid = parts[2]
player_type = parts[3]
path_parts = parts[4:] if len(parts) > 4 else []
elif len(parts) >= 2:
# Direct format: /<node_uuid>/<type>/...
node_uuid = parts[0]
player_type = parts[1]
path_parts = parts[2:] if len(parts) > 2 else []
else:
Logger.warning(f"Invalid player control address: {address}")
return
# Only handle messages for this node
if node_uuid != self.cm.node_uuid:
Logger.debug(f"Ignoring player message for other node: {node_uuid}")
return
Logger.debug(
f"Handling player control: type={player_type}, path={path_parts},"
f"value={value}"
)
# Route to appropriate handler based on player type
if player_type == "video":
redirect_video_cmd(path_parts, value)
elif player_type == "audio":
CUE_HANDLER.route_audio_message(path_parts, value)
elif player_type == "dmx":
CUE_HANDLER.route_dmx_message(path_parts, value)
elif player_type == "audiomixer":
# Legacy: pre-2026 OSC format /{uuid}/audiomixer/{channel}.
# The current UI sends
# /{uuid}/audio/mixer/{output_index}/{channel}/volume,
# which routes via player_type == 'audio' →
# CueHandler.route_audio_message().
# Kept for backwards compatibility with any external tool still
# using
# the old format; new code should not target this path.
# Direct audiomixer command: /<uuid>/audiomixer/<channel>
# path_parts[0] is channel (e.g., '0', 'master')
self._handle_audiomixer_command(path_parts, value)
elif player_type == "jadeo":
# Direct video command: /<uuid>/jadeo/<cmd>
redirect_video_cmd(["jadeo"] + path_parts, value)
else:
Logger.debug(f"Unknown player type in control message: {player_type}")
def _handle_audiomixer_command(self, path_parts: list, value):
"""Handle direct audiomixer OSC command.
Args:
path_parts: Remaining path parts after /<uuid>/audiomixer/
e.g., ['0'] for channel 0, ['master'] for master
value: Volume value (0.0 to 1.0)
"""
if not path_parts:
Logger.warning("Empty audiomixer command path")
return
channel = path_parts[0]
# jack-volume expects /audiomixer/<client_name>/<channel>
mixer_cmd = f"/audiomixer/0_mixer/{channel}"
try:
PLAYER_HANDLER.get_audio_mixer_client().set_value(mixer_cmd, value)
Logger.debug(f"Audiomixer command: {mixer_cmd} = {value}")
except Exception as e:
Logger.error(f"Error sending audiomixer command: {e}")
@logged
def stop(self):
self.stop_requested = True
self._cancel_stop_project_watchdog()
self.stop_node_engine()
self.stop_comms()
super().stop()
@logged
def stop_comms(self):
"""Stop the NNG comms thread before the interpreter tears down.
pynng registers an atexit hook that calls nng_fini(), destroying NNG's
global state. CPython does not join daemon threads before running
atexit hooks, so a comms thread still polling the bus at that point
calls into freed NNG internals and aborts the process
("panic: pthread_mutex_lock: Invalid argument", ClickUp 869ed00ya).
ControllerEngine does the equivalent in its own stop_comms(); without
this, only the node engine core-dumped on every restart.
"""
comms = getattr(CUE_HANDLER, "communications_thread", None)
if comms is None:
return
try:
comms.stop()
except Exception as e:
Logger.error(f"Error stopping NNG comms thread: {e}")
def stop_node_engine(self):
"""Stop the NodeEngine elements"""
CUE_HANDLER.disarm_all(reason="shutdown")
self.stop_video_devs()
def stop_video_devs(self):
try:
self.unload_video_devs()
Logger.info("Video devs stopped")
except Exception as e:
Logger.warning(f"Exception raised when stopping video devs: {e}")
def quit_video_devs(self):
try:
PLAYER_HANDLER.quit_videocomposer()
Logger.info("Videocomposer quit successfully")
except Exception as e:
Logger.exception(e)
def unload_video_devs(self):
try:
PLAYER_HANDLER.reset_videocomposer()
Logger.info("Videocomposer reset successfully")
except Exception as e:
Logger.exception(e)
#########################
# OSCQuery logic
#########################
def add_player_endpoints(self, cue: Cue, prefix: str = "/players"):
"""Add player endpoints from a cue to the OSCQuery server
Args:
cue: The cue containing the player client
prefix: Prefix to add to all endpoint paths (default: '/players')
"""
if not hasattr(cue, "_osc") or cue._osc is None:
Logger.warning(f"Cue {cue.id} has no OSC client, cannot add endpoints")
return
try:
# Get endpoints from the player client
endpoints = cue._osc.get_endpoints()
if not endpoints:
Logger.warning(f"No endpoints found for cue {cue.id}")
return
# Add prefix to all endpoints
prefixed_endpoints = add_prefix_to_all(
endpoints, f"{prefix}/{self.cm.node_uuid}/{cue.id}"
)
# Add endpoints to OSCQuery server
if hasattr(self, "oscquery_server") and self.oscquery_server:
self.oscquery_server.add_endpoints(prefixed_endpoints)
Logger.debug(
f"Added {len(prefixed_endpoints)} endpoints for cue {cue.id}"
)
else:
Logger.warning("OSCQuery server not initialized, cannot add endpoints")
except Exception as e:
Logger.error(f"Error adding player endpoints for cue {cue.id}: {e}")
Logger.exception(e)
def set_oscquery_comms(self):
"""Set up the command dictionary for the NodeEngine.
Commands are received via NNG from ControllerEngine.
OSCQuery client is no longer used since pyossia server was removed.
"""
self.commands_dict = {
"deploy": self.ready_project,
"load": self.load_project,
"loadcue": None,
"go": self.go_script,
"gocue": self.go_script,
"pause": None,
"resetall": None,
"stop": self.stop_playback,
"setnextcue": self.set_next_cue,
"cue_enabled": self._handle_cue_enabled,
"test": None,
"unload": self.unload_project,
"update": None,
}
def route_message(self, parameter, value):
# Exclude 'engine' common node
path_elements = str(parameter.node).split("/")[2:]
if path_elements[0] == "command":
self.run_command(path_elements[1], value)
elif path_elements[0] == "status":
Logger.debug(f"Status update received: {path_elements[1]} = {repr(value)}")
elif path_elements[0] == "players":
# Exclude other nodes' players
if path_elements[1] != self.cm.node_uuid:
Logger.debug(
f"Ignoring player message for other node: {path_elements[1]}"
)
return
# Route the message to the appropriate player handler
if path_elements[2] == "video":
redirect_video_cmd(path_elements[3:], value)
if path_elements[2] == "audio":
CUE_HANDLER.route_audio_message(path_elements[3:], value)
if path_elements[2] == "dmx":
CUE_HANDLER.route_dmx_message(path_elements[3:], value)
else:
Logger.debug(f"Recieved unused OSCQuery path: {str(parameter.node)}")
return
# The GO commands timed by step 3 (S0-19): an operator GO, and the
# power-bridge's /gocue (setnextcue + go).
_TIMED_GO_COMMANDS = ("go", "gocue")
def run_command(self, command, value, arrived: float | None = None):
"""Run one command under _command_lock. ``arrived``: monotonic()
at the NNG handler's entry (now when not given). A GO logs how long
it waited for the lock and how long it held it (869feynrj step 3)."""
if arrived is None:
arrived = monotonic()
timed = command in self._TIMED_GO_COMMANDS
with self._command_lock:
acquired = monotonic()
if timed:
self._go_what = []
hold = test_knobs.hold_command_lock_ms()
if hold:
# R10 (test knob, inert in production): this GO's handling
# is slower than L.
Logger.warning(f"TEST KNOB: holding the command lock {hold:.1f} ms")
sleep(hold / 1000.0)
self._go_note("test hold", hold)
try:
return self._run_command_locked(command, value)
finally:
if timed:
self._log_go_timing(arrived, acquired, monotonic())
def _run_command_locked(self, command, value):
Logger.debug(f"NodeEngine executing command: {command}({repr(value)})")
if command in self.commands_dict.keys():
handler = self.commands_dict[command]
if handler is not None:
try:
handler(value)
finally:
if command in ("stop", "load", "unload") and self._follow_relay:
# The receive hook counted it received; until
# here this node's epochs still belonged to the
# run it ends (869fc8ytz).
self._follow_relay.stop_applied()
return True
else:
Logger.warning(f"Command {command} has no handler")
return False
else:
Logger.error(f"Command {command} not found")
return False
def _go_note(self, what: str, ms: float | None = None) -> None:
"""Name what a GO did under _command_lock, for its timing line."""
parts = getattr(self, "_go_what", None)
if isinstance(parts, list):
parts.append(what if ms is None else f"{what} {ms:.1f} ms")
def _log_go_timing(self, arrived: float, acquired: float, released: float):
"""869feynrj step 3 (S0-19): one line per GO handled."""
parts = getattr(self, "_go_what", None) or ["go"]
self._go_what = None
Logger.info(
f"GO timing: command lock waited {(acquired - arrived) * 1000:.1f} ms, "
f"held {(released - acquired) * 1000:.1f} ms ({', '.join(parts)})"
)
#########################
# Player logic
#########################
def set_players(self):
# A player binary the orphan cleanups do not know by name escapes them
# all; say so at start (869evtdf7).
check_orphan_binary_names(self.cm.node_conf)
self.set_video_players()
self.set_audio_players()
self.set_dmx_players()
self.set_gradient_client()
def set_gradient_client(self) -> None:
"""
Wire GradientClient into PLAYER_HANDLER using settings from node_conf.
"""
port = int(self.cm.node_conf["gradient_osc_port"])
node_name = self._resolve_gradient_node_name()
PLAYER_HANDLER.set_gradient_client(port=port, node_name=node_name)
def _resolve_gradient_node_name(self) -> str:
"""
Resolve the identifier gradient-motiond's node_name filter expects.
gradient-motiond defaults its --node-name to the OS hostname (see
node-identity-contract.md in cuems-common); cuems-nodeconf keeps the
OS hostname in sync with network_map.xml's <role_id> and only
persists <hostname> as a legacy override when the two diverge. The
node's UUID is never what the daemon filters on.
"""
node = self.cm.node_network_map or {}
node_name = node.get("hostname") or node.get("role_id")
if not node_name:
node_name = self.cm.node_uuid
Logger.warning(
"gradient_node_name: no role_id/hostname in network_map for "
f"node {self.cm.node_uuid}; falling back to node_uuid — "
"gradient-motiond's node_name filter will likely reject fades"
)
return node_name
# Audio functions
def set_audio_players(self):
"""Set the audio players and audio mixer"""
# Initialize the audio mixer for this node
if self.cm.node_hw_outputs.get("audio_outputs"):
audio_outputs = self.cm.node_hw_outputs["audio_outputs"]
Logger.info(f"Initializing audio mixer with {len(audio_outputs)} outputs")
mixer_id = "0" # TODO: make this a unique identifier for the mixer
# Start the audio mixer. The port draw is inside the try: it can
# now raise if the pool is exhausted, and losing the mixer must
# not abort the whole node start.
# (assign_ports(cue=None) registers via add_config_ports itself —
# the explicit second call that used to sit here was redundant.)
try:
mixer_ports = PORT_HANDLER.assign_ports(["audio_mixer"])
PLAYER_HANDLER.start_audio_mixer(
audio_outputs=audio_outputs,
port=mixer_ports["audio_mixer"],
mixer_id=mixer_id,
path=self.cm.node_conf["audiomixer"]["path"],
args=self.cm.node_conf["audiomixer"]["args"],
)
Logger.info(f"Audio mixer started successfully for mixer {mixer_id}")
# Register mixer with Controller via NNG
try:
CUE_HANDLER.communications_thread.add_player(
f"audiomixer_{mixer_id}", None, timeout=0.1
)
Logger.info(f"Audio mixer {mixer_id} registered with Controller")
except Exception as e:
Logger.warning(f"Could not register mixer with Controller: {e}")
# Assert a known unity state at startup so the controller shadow
# (hence the UI) reflects real gain from t=0, then snapshot it.
try:
mixer_client = PLAYER_HANDLER.get_audio_mixer_client()
if mixer_client:
mixer_client.reset_volumes()
self._report_mixer_status()
except Exception as e:
Logger.warning(f"Mixer startup state assert/report failed: {e}")
except Exception as e:
Logger.error(
f"Error starting audio mixer: {e}. "
f"Audio on this node will be SILENT."
)
Logger.exception(e)
else:
Logger.info(
"No audio outputs detected, skipping audio mixer initialization"
)
# Build audio output lookup keyed by <id> (mirrors video output
# pattern)
audio_outputs = {}
for port_type_dict in self.cm.node_mappings.get("audio", []):
for port_type_list in port_type_dict.values():
for port in port_type_list:
for _, output_data in port.items():
output_id = str(output_data.get("id", output_data["name"]))
mappings = output_data.get("mappings", [])
mapped_to = (
mappings[0]["mapped_to"]
if mappings
else output_data["name"]
)
audio_outputs[output_id] = {
"name": output_data["name"],
"mapped_to": mapped_to,
}
PLAYER_HANDLER.set_audio_outputs(audio_outputs)
# Set the audio player generator. Append --output-latency-ms
# from settings.xml when the operator supplied an integer
# override (isinstance int); "auto" or absent ⇒ audioplayer
# runs its Phase-3 JACK-latency query path.
audio_args = _append_output_latency_flag(
self.cm.node_conf["audioplayer"]["args"],
self.cm.node_conf["audioplayer"],
)
PLAYER_HANDLER.set_audio_output_generator(
self.cm.node_conf["audioplayer"]["path"],
audio_args,
)
self._init_out_latency()
# 869feynrj §4.5d: this node's output latency, known independently of
# armed players (review 3 N3), carried to the controller for L.
def _init_out_latency(self) -> None:
"""At node start: the settings override when set, else a JACK query
of the playback ports; latency + one JACK period from every source
(review 4 m1). Never raises."""
jack_lat = None
try:
mixer = PLAYER_HANDLER.get_audio_mixer()
conn_man = getattr(mixer, "conn_man", None) if mixer else None
if conn_man is not None:
answer = conn_man.playback_latency()
if (
isinstance(answer, tuple)
and len(answer) == 3
and all(isinstance(x, int) for x in answer)
and answer[1] > 0
):
jack_lat = answer
except Exception as e:
Logger.warning(f"Output latency: JACK query failed: {e}")
override = None
try:
value = self.cm.node_conf["audioplayer"].get("output_latency_ms")
if isinstance(value, int) and not isinstance(value, bool):
override = float(value)
except Exception:
override = None
if override is not None:
period_ms = (
jack_lat[2] * 1000.0 / jack_lat[1]
if jack_lat is not None
else 512 * 1000.0 / 48000
)
self._note_out_latency(override + period_ms, "settings output_latency_ms")
elif jack_lat is not None:
frames, rate, period = jack_lat
self._note_out_latency(
(frames + period) * 1000.0 / rate, "JACK playback latency"
)
else:
Logger.info(
"Output latency not known yet (no settings override, no JACK "
"answer): the first player's LATENCY line will tell"
)
def _on_player_latency(self, player, latency) -> None:
"""START_GATE's latency listener: a player's LATENCY line."""
self._note_out_latency(latency.out_latency_ms, "player LATENCY line")
def _note_out_latency(self, ms: float, source: str) -> None:
"""Keep the maximum; tell the controller when it grows (an additive
STATUS, so an audio cue armed after the load still raises L, N3).
Never blocks: it runs on a player's stdout reader too."""
if not isinstance(ms, (int, float)) or isinstance(ms, bool) or ms <= 0:
return
current = self._out_latency_ms
if current is not None and ms <= current:
return
self._out_latency_ms = float(ms)
CUE_HANDLER.out_latency_ms = float(ms)
Logger.info(
f"Output latency {ms:.1f} ms (latency + one period, from the {source});"
f" follow lead F {go_lead.follow_lead_ms(ms):.0f} ms"
)
# Reported when nothing was yet (no latency known at armed_ready: the
# first LATENCY line must still reach the controller, N3) or larger.
reported = self._out_latency_reported
if reported is None or ms > reported + 0.05:
self._send_out_latency(ms)
def _send_out_latency(self, ms: float) -> None:
from .comms.NodesHub import ActionType, NodeOperation, OperationType
try:
CUE_HANDLER.communications_thread.send_operation_nowait(
NodeOperation(
type=OperationType.STATUS,
action=ActionType.UPDATE,
sender=self.cm.node_uuid,
target="out_latency",
data={"out_latency_ms": round(float(ms), 3)},
)
)
self._out_latency_reported = float(ms)
except Exception as e:
Logger.warning(f"Could not report the output latency: {e}")
def _report_mixer_status(self, output_index: str = "0") -> None:
"""Snapshot the local mixer's authoritative gain to the controller.
Sent on SETTLE EVENTS only — mixer startup and after each
reset_volumes — never per UI write. A per-write report would race the
controller's synchronous optimistic populate (unordered NNG command
threads) and make faders jump backward on a fast drag; live UI writes
are already shadowed accurately controller-side, so the node only needs
to report the resets the controller can't observe.
"""
try:
mixer_client = PLAYER_HANDLER.get_audio_mixer_client()
if not mixer_client:
return
entries = mixer_client.snapshot()
if not entries:
return
CUE_HANDLER.communications_thread.update_mixer_status(
entries, output_index=output_index, timeout=0.1
)
Logger.debug(f"Reported mixer status to controller: {entries}")
except Exception as e:
Logger.warning(f"Could not report mixer status: {e}")
# Video functions
def set_video_players(self):
"""Set the video players"""
Logger.info(f'Setting video players with: {self.cm.node_conf["videoplayer"]}')
if not self.cm.node_hw_outputs["video_outputs"]:
Logger.info("No video outputs detected.")
return
PLAYER_HANDLER.add_node_uuid(self.cm.node_uuid)
vc_conf = self.cm.node_conf.get("videoplayer", {})
osc_video_port = int(vc_conf.get("osc_port", VIDEOCOMPOSER_OSC_PORT_DEFAULT))
# Declare BEFORE building the client: the client draws its own local
# OSC port from the pool, and must not be handed the videocomposer's.
# This is also the only registration of this port — it comes from the
# nested videoplayer/osc_port key, which get_config_ports() (top-level
# only) cannot see, so BaseEngine's hoisted call misses it.
PORT_HANDLER.add_config_ports({"videocomposer": osc_video_port})
try:
PLAYER_HANDLER.set_video_client(osc_video_port)
except Exception as e:
Logger.error(
f"Could not create the videocomposer OSC client: {e}. "
f"Video on this node will not respond."
)
Logger.exception(e)
return
# Canvas geometry comes from /run/cuems/display.conf, written by
# cuems-generate-display-conf (videocomposer's ExecStartPre). It's the
# same file the videocomposer reads, so engine + VC agree on canvas
# size and per-output regions without a handshake. The XML's optional
# <canvas_region> is a UI-template hint (normalized [0,1]) and is
# ignored here — engine never sources physical layout from XML.
display_regions, (canvas_w, canvas_h) = read_display_conf()
video_outputs = {}
for port_type_dict in self.cm.node_mappings.get("video", []):
for port_type_list in port_type_dict.values():
for port in port_type_list:
for _, output_data in port.items():
output_id = str(output_data.get("id", output_data["name"]))
name = output_data["name"]
mappings = output_data.get("mappings", [])
mapped_to = mappings[0]["mapped_to"] if mappings else name
region = display_regions.get(mapped_to)
if region is None:
Logger.warning(
f"DISPLAY_MISMATCH: XML output id={output_id} "
f"name={name!r} maps to {mapped_to!r} which"
f"is "
f"not in display.conf; skipping. Available: "
f"{sorted(display_regions.keys())}"
)
continue
video_outputs[output_id] = {
"name": name,
"mapped_to": mapped_to,
"x": region["x"],
"y": region["y"],
"width": region["width"],
"height": region["height"],
"canvas_region": dict(region),
}
PLAYER_HANDLER.start_video_outputs(
video_outputs, canvas_override=(canvas_w, canvas_h)
)
# DMX functions
def set_dmx_players(self):
"""Set the DMX player for this node and register its endpoints."""
# Get node UUID for player naming
node_uuid = self.cm.node_conf.get("uuid", "default_node")
# Start the DMX player. The port draw is inside the try: it can now
# raise if the pool is exhausted, and losing DMX must not abort the
# whole node start. (assign_ports(cue=None) registers via
# add_config_ports itself — the second call here was redundant.)
try:
dmx_ports = PORT_HANDLER.assign_ports(["dmx_player"])
# Append --output-latency-ms from settings.xml when an
# integer override is present. Dmx has no "auto" form —
# absent ⇒ dmxplayer's 35 ms Phase-5A default stands.
dmx_args = _append_output_latency_flag(
self.cm.node_conf["dmxplayer"]["args"],
self.cm.node_conf["dmxplayer"],
)
PLAYER_HANDLER.start_dmx_player(
port=dmx_ports["dmx_player"],
node_uuid=node_uuid,
path=self.cm.node_conf["dmxplayer"]["path"],
args=dmx_args,
)
try:
CUE_HANDLER.communications_thread.add_player(
f"dmxplayer_{node_uuid}", None, timeout=0.1
)
except Exception:
pass # Ignore - NNG is for distributed nodes
Logger.info(f"DMX player started successfully for node {node_uuid}")
except Exception as e:
Logger.error(f"Error starting DMX player: {e}")
Logger.exception(e)
return
def quit_dmx_devs(self):
"""Quit the DMX player if it exists"""
dmx_client = PLAYER_HANDLER.get_dmx_player_client()
if dmx_client:
try:
dmx_client.set_value("/quit", 1)
except Exception as e:
Logger.exception(e)
CUE_HANDLER.communications_thread.remove_player(
f"dmxplayer_{self.cm.node_uuid}"
)
#########################
# Project logic
#########################
def ready_project(self, project):
"""Prepare the project to be played.
deploy_project() runs in _load_project_inner BEFORE this point,
before the teardown of the previous project — so that a deploy
failure aborts the load without destroying running state.
Media deploy runs here because it is best-effort: a failure
logs but does not abort (cached media may already be on disk).
"""
self.cm.load_project_config(project)
self.read_script(project)
media_synced = self.deploy_media(project)
self.check_own_media_sizes(media_synced)
self.ensure_video_indexes()
self.outputs_map = self.map_cue_outputs()
PLAYER_HANDLER.set_outputs_map(self.outputs_map)
PORT_HANDLER.clean_random_ports()
def map_cue_outputs(self, cuelist: CueList = None):
"""Load the output mappings for the project"""
outputs_map = {}
if cuelist is None:
cuelist = self.script.cuelist
if cuelist.contents is None:
Logger.warning("Cuelist contents is None, skipping map_cue_outputs")
return outputs_map
for cue in cuelist.contents:
if isinstance(cue, CueList):
outputs_map.update(self.map_cue_outputs(cue))
continue
elif not isinstance(cue, MediaCue):
continue
outputs = [
x[1] for x in cue.get_all_output_names() if x[0] == self.cm.node_uuid
]
if outputs:
outputs_map[cue.id] = outputs
Logger.debug(f"Outputs map: {outputs_map}")
return outputs_map
def load_project(self, project):
"""Load the project files to the node"""
with self._loading_lock:
if self._loading:
Logger.warning(
f"Load already in progress, ignoring duplicate load of {project}"
)
return
self._loading = True
try:
return self._load_project_inner(project)
finally:
with self._loading_lock:
self._loading = False
def _load_project_inner(self, project):
# Don't allow loading while script is running
if self.get_status("running") == "yes":
Logger.warning(
f"Cannot load project {project} while script is running. "
f"Stop the script first."
)
return False
# Deploy the critical project files (script.xml, mappings.xml,
# settings.xml) BEFORE tearing down the previous project. If the
# controller is unreachable we abort here with the previous
# project still armed and usable — better than ending up with
# everything stopped and no new project loaded.
if not self.deploy_project(project):
Logger.error(
f"Project deploy FAILED for {project} — aborting load; "
f"previous project remains unchanged"
)
return False
self._teardown_project("load")
# 869feynrj: the once-per-load lines may be said again.
START_GATE.reset_for_load()
self._out_latency_warned_load = False
# Clear the engine's 24h MTC wrap accumulator on this project transition,
# co-orchestrated with the DMX blackout + videocomposer reset above (which
# clear the C++ receivers' offsets via resetWrapOffset). A graceful
# reload's small backward wire delta can't trip the wire-driven reset, so
# do it explicitly here — else a project loaded after a >24h run starts
# at hour 24+ and the reset_callback cascade stays silenced. (Plan 4)
if self.mtc_listener is not None:
self.mtc_listener.reset_24h_state()
# Obtain the project files (this replaces self.script with new project)
self.ready_project(project)
# Name the video cues aimed at outputs this node doesn't drive, before
# anything arms. Here and not in ready_project: that one is also the
# `deploy` bus command, which can arrive mid-show.
self.check_unrouted_video_outputs()
# Loop periods (869ejxng3 §4.1, D12): read or probed beside the arm,
# waited for before armed_ready, so GO is enabled only when every node
# knows each looping cue's mode.
period_probe = self._start_loop_period_probe()
# Prepare the script to be played (arms new cues)
self.ready_script(reason="load")
self._finish_loop_period_probe(period_probe)
# Start cue dependencies
# self.set_players()
# Confirm the project is loaded
self.set_show_lock_file()
self.script.unix_name = project
self.set_status("load", project)
Logger.info(f"Project {project} loaded")
# Notify Controller that arming is complete (GO button can go green)
self._notify_armed_ready("arming after load")
# Broadcast initial nextcue to UI
self._broadcast_nextcue()
return True
def unload_project(self, value=None):
"""Unload the project: the teardown of a load, and nothing armed after.
The controller sends this on project_unload. It used to send a STOP,
and stop_playback re-arms the script this node still holds, so every
node spawned new players for a project that was no longer loaded
(869fh8kef).
"""
if self.get_status("running") == "yes":
# The controller refuses an unload while running; a node that
# still thinks it is running does not tear down under the show.
Logger.warning("Cannot unload while the script is running. Stop first.")
return False
name = getattr(self.script, "name", None)
Logger.info(f"UNLOAD command received. Unloading project {name}.")
# Abort in-flight ReArm/PreArm threads: on a STOP or a load,
# ready_script bumps this, and nothing here calls ready_script.
self._project_generation += 1
self._teardown_project("unload")
self.reset_script()
self._legacy_period = []
self.set_status("load", "")
self.remove_show_lock_file()
self._broadcast_nextcue()
Logger.info(f"Project {name} unloaded")
return True
def _teardown_project(self, reason: str):
"""Release everything the current project holds on this node:
cue threads, DMX, video layers, mixer gains, audio players, armed cues.
Shared by a load (before the new project arms) and an unload.
"""
self._gradient_cancel_all(f"project {reason}")
# Stop any running cue threads from the previous project first,
# so they can't interfere with cleanup (same logic as stop_playback).
CUE_HANDLER.stop_all_cues()
# DMX: stop following MTC, blackout all universes.
self._dmx_reset()
# Video: reset videocomposer (remove all layers, cancel loads, reset
# master).
self.unload_video_devs()
# Audio: reset mixer volumes, kill all players, clean up JACK.
mixer_client = PLAYER_HANDLER.get_audio_mixer_client()
if mixer_client:
try:
mixer_client.reset_volumes()
except Exception as e:
Logger.warning(f"JACK volume reset failed: {e}")
# Report the reset so the UI reflects real (unity) gain, not the
# stale value it may have shown from a previous UI write.
self._report_mixer_status()
PLAYER_HANDLER.kill_all_audio_players()
PLAYER_HANDLER.kill_orphaned_audio_processes()
PLAYER_HANDLER.cleanup_zombie_jack_clients()
# Disarm all cues from the previous project.
CUE_HANDLER.disarm_all(reason=reason)
def deploy_project(self, project):
"""Deploy the project files (script.xml, mappings.xml, settings.xml).
Critical path: if these fail to sync, the local copy may be stale
and arming cues against it is unsafe. Caller is expected to abort
the load on False.
"""
return self.deploy_manager.sync_files(project, "project")
def deploy_media(self, project):
"""Deploy the media files (and their .idx sidecar indexes).
Best-effort: a failure here is recoverable if media is already
cached on disk. Returns False to surface the failure to logs,
but the caller continues the load.
"""
if not self.script:
Logger.error("No script loaded")
return False
bare_names = self.script.get_own_media_filenames(config=self.cm)
if len(bare_names) == 0:
Logger.info("No media files to deploy")
return True
if not self.deploy_manager.sync_files(project, "media", bare_names):
Logger.error(
f"Media deploy failed for {project} — continuing with cached "
f"files; cues whose media is missing locally will fail on GO"
)
return False
return True
def check_own_media_sizes(self, media_synced: bool = True) -> list:
"""Report this node's media files that differ from the project, or
are missing (869fat84r D20, L2).
The editor corrects the project before a load when a file on the
controller changed; this is the last defence, for a copy that differs
only here (a failed media sync, a file placed on this node only, an
OSC load that bypassed the editor). Report only: the cue keeps the
stored duration, so this node stays in step with the others. Never
raises: the previous project is already torn down at this point.
"""
try:
found = own_media_size_mismatches(
self.script.get_own_media(config=self.cm),
self.script.find,
PLAYER_HANDLER.media_path,
)
except Exception as e:
Logger.error(
f"Media size check skipped ({type(e).__name__}: {e}); the load goes on"
)
return []
sync = "" if media_synced else " This load's media sync failed."
for file_name, stored, actual in found:
if actual is None:
Logger.error(
f"Media file {file_name} is missing on this node: its cues will "
f"fail.{sync}"
)
else:
Logger.error(
f"Media file {file_name} on this node is {actual} bytes; the "
f"project stores {stored}: it was replaced or not synced. The "
"stored duration is kept so the nodes stay in step; re-sync it, "
f"or re-upload it in the editor.{sync}"
)
return found
def check_unrouted_video_outputs(self) -> list:
"""Name every enabled video cue of this node that points at an output
this node doesn't drive (869fgq3xv). Log only.
Such an output is never loaded (arm_videoCue), so the cue stays dark
there; this says so at load, before the show, instead of on the
screens. Also starts the load's once-only arm errors afresh. Uses the
same PlayerHandler.partition_cue_outputs as the arm, so the two cannot
disagree. Never raises: the previous project is already torn down.
"""
PLAYER_HANDLER.reset_unrouted_warnings()
found = []
try:
video_cues = []
for cue_id, output_names in (self.outputs_map or {}).items():
cue = self.script.find(cue_id)
# outputs_map holds every MediaCue of this node, audio and
# disabled cues included.
if isinstance(cue, VideoCue) and getattr(cue, "enabled", True):
video_cues.append((cue, output_names))
if not video_cues:
return found
if PLAYER_HANDLER.get_video_client() is None:
# set_video_players returned early: every video cue fails at
# arm ("No video client"), for a reason that is not the cue's.
Logger.warning(
f"no video stack on this node: {len(video_cues)} video cue(s)"
" will not play here"
)
return found
driven = PLAYER_HANDLER.driven_video_outputs()
for cue, output_names in video_cues:
_, unrouted = PLAYER_HANDLER.partition_cue_outputs(cue, output_names)
if not unrouted:
continue
found.append(
{
"cue_id": cue.id,
"cue_name": getattr(cue, "name", ""),
"outputs": [
{"output": name, "reason": reason}
for name, reason in unrouted
],
}
)
cue_name = getattr(cue, "name", "")
for output_name, reason in unrouted:
Logger.warning(
f'UNROUTED_VIDEO_OUTPUT: cue {cue.id} "{cue_name}"'
f' → output "{output_name}" not driven by this node ({reason});'
f" it will stay dark. Driven outputs: {driven}"
)
if found:
Logger.warning(
f"{len(found)} video cue(s) point at outputs this node doesn't"
" drive; see UNROUTED_VIDEO_OUTPUT (and DISPLAY_MISMATCH at"
" node start)"
)
except Exception as e:
Logger.exception(
f"Unrouted video output check skipped ({type(e).__name__}: {e});"
" the load goes on"
)
return []
return found
def ensure_video_indexes(self):
"""
Run cuems-videoindexer on any video files whose .idx sidecar is missing
or stale.
This is a safety net for files that were copied manually or deployed to
a node that never ran the editor upload hook. For normally-uploaded
files the index was already created by the editor and this is a no-op.
The caller is shared with the editor
(``cuemsutils.tools.media_sidecars.ensure_video_index``, 869ejxng3).
"""
if not self.script:
return
file_names = self.script.get_own_media_filenames(config=self.cm)
video_exts = {".mp4", ".mov", ".avi", ".mkv", ".mpg"}
videos = [
PLAYER_HANDLER.media_path(name)
for name in file_names
if os.path.splitext(name)[1].lower() in video_exts
]
if videos:
media_sidecars.ensure_video_index(videos, timeout_s=600)
def _loop_period_cues(self) -> list:
"""Mark every CueList child ``_in_cuelist`` (they play once, Q2, I11) and
return the local looping AudioCues and VideoCues whose period the load
needs: loop != 1, enabled or not (a cue enabled at runtime then has its
period, I16i), not inside a CueList. A VideoCue needs it for its
realFrames and its D15 length too (X2, §4.1a)."""
found = []
def walk(cuelist, inside):
for cue in cuelist.contents or []:
cue._in_cuelist = inside
if isinstance(cue, CueList):
walk(cue, True)
elif (
isinstance(cue, (AudioCue, VideoCue))
and not inside
and getattr(cue, "_local", False) is True
and cue.loop != 1
):
found.append(cue)
if self.script and self.script.cuelist:
walk(self.script.cuelist, False)
return found
def _start_loop_period_probe(self):
"""Give the looping cues their period beside the arm (§4.1): from the
editor's sidecar, this node's cache, or a probe within the budget.
The videocomposer's caps file is read here too, at every load (§4.2)."""
self._legacy_period = []
cues = self._loop_period_cues()
self._check_video_caps(cues)
self._check_visible_at(self.script.cuelist if self.script else None)
if not cues:
return None
cancel = Event()
lock = Lock()
result = {}
def run():
result["legacy"] = probe_loop_periods(
cues,
PLAYER_HANDLER.media_path,
PLAYER_HANDLER.loop_period_cache,
cancel=cancel,
lock=lock,
)
t = Thread(target=run, name="loop-period-probe", daemon=True)
t.start()
return (t, cancel, result, cues, monotonic(), lock)
def _finish_loop_period_probe(self, probe) -> None:
if probe is None:
return
t, cancel, result, cues, started, lock = probe
budget = test_knobs.probe_budget_s(LOOP_PERIOD_LOAD_BUDGET_S)
t.join(max(0.0, budget + 2.0 - (monotonic() - started)))
with lock: # the modes are fixed from here on (reported in armed_ready)
cancel.set()
if t.is_alive():
Logger.warning("loop period probe still running after the load budget")
self._choose_loop_lengths(cues)
self._legacy_period = [
str(c.id) for c in cues if getattr(c, "_loop_period", None) is None
]
Logger.info(
f"loop periods: {len(cues) - len(self._legacy_period)} of {len(cues)} "
f"looping cue(s) have one; legacy: {self._legacy_period or 'none'}"
)
for cue in cues:
if isinstance(cue, VideoCue):
self._check_video_period(cue)
self._warn_loop_drift()
def _looping_media_cues(self) -> list:
"""Every looping AudioCue and VideoCue at the project's top level (not a
CueList child), on any node, enabled or not: the members a D15 pair is
looked up among (§4.1a; a pair may be split across nodes, and every
node must choose the same length without an exchange)."""
if not (self.script and self.script.cuelist):
return []
return [
c
for c in self.script.cuelist.contents or []
if isinstance(c, (AudioCue, VideoCue)) and c.loop != 1
]
def _choose_loop_lengths(self, cues) -> None:
"""D15 (§4.1a, rev 3.17): give every local looping cue with a period the
length it loops on — its own track, A within the slack threshold, or a
same-file pair's choice — then apply the force-period test knob to that
choice (R3) and re-check the int32 bound on the chosen num (R12). The
file's period as probed is kept as ``_loop_period_raw``; the origin
(audio / video / longest) as ``_loop_origin``."""
contents = (
self.script.cuelist.contents or []
if self.script and self.script.cuelist
else []
)
key = start_together_key(contents)
groups = {}
for c in self._looping_media_cues():
groups.setdefault((media_file(c), key(c)), []).append(c)
raw_of_file = {}
for cue in cues:
raw = loop_mode.period_of(cue)
cue._loop_period_raw = raw
cue._loop_origin = None
cue._loop_partners = []
if raw is not None:
raw_of_file.setdefault(media_file(cue), raw)
logged_groups = set()
for cue in cues:
raw = cue._loop_period_raw
if raw is None:
continue
gkey = (media_file(cue), key(cue))
group = groups.get(gkey, [cue])
paired = any(isinstance(c, AudioCue) for c in group) and any(
isinstance(c, VideoCue) for c in group
)
choice = loop_mode.choose_period(raw, isinstance(cue, VideoCue), paired)
chosen = choice.period
if choice.paired:
cue._loop_partners = [str(c.id) for c in group if c is not cue]
if gkey not in logged_groups:
logged_groups.add(gkey)
self._log_pair(cue, group, raw, choice)
forced = test_knobs.forced_period(cue.id)
if forced is not None:
chosen = dataclasses.replace(chosen, num=forced[0], den=forced[1])
Logger.warning(
f"TEST KNOB: loop period of {cue.id} forced to "
f"{forced[0]}/{forced[1]} (after the {choice.origin} choice)"
)
if chosen.num > LOOP_PERIOD_INT32_MAX:
Logger.error(
f"loop period of {cue.id} ({chosen.num}/{chosen.den}, the "
f"{choice.origin} length) exceeds the int32 wire range: legacy loop"
)
cue._loop_period = None
continue
cue._loop_period = chosen
cue._loop_origin = choice.origin
pair = (
f", pair with {', '.join(cue._loop_partners)}"
if cue._loop_partners
else ""
)
tail = (
f", tail {choice.tail_ms:.3f} ms on the "
f"{'video' if isinstance(cue, VideoCue) else 'audio'}, "
f"{choice.treatment}"
if choice.treatment
else ""
)
Logger.info(
f"loop length for {cue.id}: {chosen.num}/{chosen.den} = "
f"{chosen.ms:.3f} ms ({choice.origin}{pair}; audio "
f"{self._fmt_ms(choice.audio_ms)}, video "
f"{self._fmt_ms(choice.video_ms)}){tail}"
)
self._warn_same_file_different_starts(groups, raw_of_file)
@staticmethod
def _fmt_ms(ms) -> str:
return "-" if ms is None else f"{ms:.3f} ms"
def _log_pair(self, cue, group, raw, choice) -> None:
"""One INFO line per same-file pair beyond the slack threshold (§4.5)."""
video_tail = loop_mode.choose_period(raw, True, True)
audio_tail = loop_mode.choose_period(raw, False, True)
tails = "; ".join(
f"tail {c.tail_ms:.3f} ms on the {kind}, {c.treatment}"
for kind, c in (("video", video_tail), ("audio", audio_tail))
if c.treatment
)
Logger.info(
f"A/V pair on {media_file(cue)}: "
f"{', '.join(str(c.id) for c in group)}; audio "
f"{self._fmt_ms(choice.audio_ms)}, video {self._fmt_ms(choice.video_ms)}; "
f"loops on the {choice.origin} length" + (f"; {tails}" if tails else "")
)
def _warn_same_file_different_starts(self, groups, raw_of_file) -> None:
"""R10: looping cues on one file that do not start together are not a
pair: each loops on its own track, and when those lengths differ they
drift apart by the difference every pass — one WARNING per file (a file
no local cue loops is left to the nodes that loop it), DEBUG when the
lengths agree."""
by_file = {}
for (file, _), group in groups.items():
by_file.setdefault(file, []).append(group)
for file, file_groups in by_file.items():
raw = raw_of_file.get(file)
if raw is None or len(file_groups) < 2:
continue
lengths = {}
for group in file_groups:
paired = any(isinstance(c, AudioCue) for c in group) and any(
isinstance(c, VideoCue) for c in group
)
for c in group:
p = loop_mode.choose_period(
raw, isinstance(c, VideoCue), paired
).period
lengths[str(c.id)] = p.ms
if len(set(lengths.values())) > 1:
diff = max(lengths.values()) - min(lengths.values())
Logger.warning(
f"same file, different starts: {', '.join(lengths)} on {file} "
f"loop on different tracks and drift apart by {diff:.3f} ms per "
"pass (start them together to make them a pair)"
)
else:
Logger.debug(
f"same file, different starts: {', '.join(lengths)} on {file} "
"loop on the same length"
)
@staticmethod
def _check_video_caps(cues) -> None:
"""Re-read the videocomposer's caps file; WARNING when this load loops
video and the videocomposer cannot wrap on a period (§4.2)."""
caps = PLAYER_HANDLER.refresh_video_caps()
if loop_mode.VC_LOOP_PERIOD in caps:
return
videos = [str(c.id) for c in cues if isinstance(c, VideoCue)]
if videos:
Logger.warning(
"videocomposer without the loop_period capability (no valid "
f"{caps_path()}): looping video cue(s) {videos} run in legacy mode "
"(re-anchored every pass on P; an A/V pair stays within one pass)"
)
@staticmethod
def _check_visible_at(cuelist) -> None:
"""One INFO per load when this node plays video and its videocomposer
does not take ``visible_at`` (869feynrj §4.6 "Skew"): its VideoCues
then reveal as today, ``/visible 1`` at the polled reveal. Reads the
caps _check_video_caps has just refreshed."""
if loop_mode.vc_visible_at(PLAYER_HANDLER.video_caps):
return
def has_local_video(node) -> bool:
for cue in getattr(node, "contents", None) or []:
if isinstance(cue, CueList):
if has_local_video(cue):
return True
elif isinstance(cue, VideoCue) and getattr(cue, "_local", False):
return True
return False
if cuelist is not None and has_local_video(cuelist):
Logger.info(
"videocomposer without the visible_at capability (no token in "
f"{caps_path()}): video cues reveal at the polled reveal "
"(/visible 1), not on their first frame"
)
@staticmethod
def _check_video_period(cue) -> None:
"""A looping VideoCue's period at load (§4.4): without a video frame
count or rate it runs legacy (WARNING, R21); a variable frame rate is
outside the guarantee (WARNING). No mismatch ever sends a cue to legacy
(D15: D8's bands 2–3 are gone)."""
period = loop_mode.period_of(cue)
if period is None:
return
if loop_mode.video_length(period) is None:
Logger.warning(
f"video {cue.id}: loop period without a video frame count or rate "
f"(fps {period.fps}, frames {period.real_frames}): legacy mode"
)
return
Logger.info(
f"video {cue.id}: {period.real_frames} frames at {period.fps} fps "
f"({period.frames_rule}), period {period.num}/{period.den} = "
f"{period.ms:.3f} ms ({getattr(cue, '_loop_origin', None)})"
)
if getattr(period, "vfr", False):
Logger.warning(
f"video {cue.id}: variable frame rate (avg != r_frame_rate), outside "
"the A/V loop guarantee"
)
def _warn_loop_drift(self) -> None:
"""D7 (warning only): two looping media cues on this node, on different
files, that start together (the same Auto-continue chain and the same
prewait) with periods less than 5 % apart but not equal drift apart by
the difference on every pass: one WARNING per pair. Pairs split across
nodes are not compared (the D15 grouping, which decides behaviour, is
whole-project)."""
if not (self.script and self.script.cuelist):
return
for a, b, diff_ms in loop_drift_pairs(self.script.cuelist.contents or []):
Logger.warning(
f"loop drift: {a.id} (P = {loop_mode.period_of(a).ms:.3f} ms) and "
f"{b.id} (P = {loop_mode.period_of(b).ms:.3f} ms) start together but "
f"their periods differ by {diff_ms:.3f} ms: they drift apart by that "
"much on every pass (make the files the same length, or one file)"
)
#########################
# Nextcue
#########################
def _broadcast_nextcue(self):
"""Send the current next_cue_pointer UUID to the Controller via NNG."""
cue_id = self.next_cue_pointer.id if self.next_cue_pointer else ""
try:
CUE_HANDLER.communications_thread.update_nextcue(cue_id, timeout=0.1)
Logger.debug(f'Broadcast nextcue: {cue_id or "(none)"}')
except Exception as e:
Logger.warning(f"Could not broadcast nextcue: {e}")
def _arm_with_enabled_guard(self, cue, project_gen: int, arm_epoch: int = None):
"""
Arm a cue, and disarm it if it was disabled while arming.
Runs in a daemon thread (ReArm:<id>). `arm_epoch` is the STOP/load
epoch captured by whoever spawned it (_apply_cue_enabled_side_effects):
the arm belongs to it, so CUE_HANDLER.arm() refuses it if a STOP or a
load happened before this thread got to run, and abandons it -- never
publishing the cue, releasing the player it spawned -- if one happens
while it is arming.
This method therefore does NOT disarm on a project change any more
(869f9wqpn). It used to, after arm() had already published the cue:
by then the restarted run could be playing it, and after a reload of
the same project the disarm hit the NEW object's player, because Cue
equality is by id.
"""
if self._project_generation != project_gen:
Logger.info(f"Aborting arm of {cue.id} — project generation changed")
return
try:
CUE_HANDLER.arm(cue, init=True, epoch=arm_epoch)
except Exception as exc:
Logger.error(f"Async re-arm of enabled cue {cue.id} failed: {exc}")
return
if self._project_generation != project_gen:
# A STOP/load landed during the arm. arm() either abandoned it or
# published it before the STOP began, in which case the STOP's
# own disarm_all took it. Nothing to undo, nothing to rejoin.
Logger.info(
f"Project changed during the async arm of {cue.id} — left to "
"the STOP/load that caused it"
)
return
# If cue was disabled while we were arming, disarm now -- unless it
# is playing (a disable never stops a playing cue, 869feynrj S0-21).
if (
not cue.enabled
and CUE_HANDLER.find_armed_cue(cue)
and not getattr(cue, "_playing", False)
):
CUE_HANDLER.disarm(cue, reason="disabled")
Logger.info(f"Disarmed cue {cue.id} — disabled during async arm")
return
def _action_result_sink(self, outcome: dict):
"""
Custom result sink for ActionHandler — extends default with cue_enabled
sync.
"""
from .cues.ActionHandler import ACTION_HANDLER
# Always run default behavior (sends action_cue_outcome via NNG)
ACTION_HANDLER._default_result_sink(outcome)
# If an enable/disable action was applied, notify Controller and apply
# the local arm/disarm side effects (pre-arm the enabled cue so its GO
# doesn't hit the not-loaded fallback re-arm; disarm a disabled idle
# cue). 'applied_no_change' outcomes are deliberately excluded →
# idempotent under rapid toggles.
action_type = outcome.get("action_type")
status = outcome.get("status")
if action_type == "stop_project" and status == "applied":
# The authored end of the show (869fhjdq5): tell the controller,
# which runs its own STOP path. Nothing is stopped locally.
self._notify_stop_project(outcome.get("origin_cue_id"))
return
if action_type in ("enable", "disable") and status == "applied":
target_id = outcome.get("target_id")
if target_id:
enabled = action_type == "enable"
# Notify FIRST: the Controller cache/UI update must never be
# starved by a side-effect failure (an exception here would be
# swallowed by _emit_outcome's blanket try/except).
self._notify_cue_enabled(target_id, enabled)
script = self.script
if script is None:
# Project unloading concurrently — nothing to arm/disarm;
# in-flight ReArm threads self-cancel on generation change.
return
cue = script.find(target_id)
if cue is None:
Logger.warning(
f"cue_enabled side effects: cue {target_id} not found in script"
)
return
try:
self._apply_cue_enabled_side_effects(cue, enabled)
except Exception as exc:
Logger.error(
f"cue_enabled side effects failed for {target_id}: {exc}"
)
def _gradient_cancel_all(self, context: str):
"""Cancel all in-flight gradient fades.
Shared by _load_project_inner (project load) and stop_playback
(STOP) — both must flush queued fades before stopping cue threads,
so gradient OSC traffic never outlives the cues that started it.
"""
gradient_client = PLAYER_HANDLER.get_gradient_client()
if gradient_client:
try:
gradient_client.send_cancel_all()
except Exception as exc:
Logger.error(f"gradient send_cancel_all failed on {context}: {exc}")
else:
Logger.debug(
f"gradient_client not initialised, skipping cancel_all on {context}"
)
def _dmx_reset(self):
"""Stop DMX MTC following and blackout all universes.
Shared by _load_project_inner and stop_playback: both need the DMX
playhead frozen and outputs zeroed before video/audio teardown.
"""
dmx_client = PLAYER_HANDLER.get_dmx_player_client()
if dmx_client:
try:
dmx_client.disable_mtcfollow()
except Exception as e:
Logger.warning(f"DMX disable mtcfollow failed: {e}")
try:
dmx_client.send_blackout()
except Exception as e:
Logger.warning(f"DMX blackout failed: {e}")
def _notify_armed_ready(self, context: str):
"""Notify Controller that this node finished (re)arming, so the GO
button can go green.
Shared by _load_project_inner (arming after load) and stop_playback
(re-arm after STOP).
"""
from .comms.NodesHub import ActionType, NodeOperation, OperationType
try:
data = {"armed": "yes"}
# D16 (1amfwm7jnqf): additive; an older controller reads only
# "armed".
data["engine_version"] = engine_version()
# The cues that loop in legacy mode on this node for this load
# (869ejxng3 §4.2): repeated as is by the re-arm after STOP. An old
# controller reads only "armed".
legacy = list(getattr(self, "_legacy_period", None) or [])
if legacy:
data["legacy_period"] = legacy
# 869feynrj §4.5d: additive; an old controller reads only "armed".
out_latency = getattr(self, "_out_latency_ms", None)
if out_latency is not None:
data["out_latency_ms"] = round(float(out_latency), 3)
self._out_latency_reported = float(out_latency)
elif not getattr(self, "_out_latency_warned_load", False):
self._out_latency_warned_load = True
Logger.warning(
"No output latency known on this node (settings, JACK, a "
"player's LATENCY line): the controller's GO lead uses its "
"floor for this node"
)
operation = NodeOperation(
type=OperationType.STATUS,
action=ActionType.UPDATE,
sender=self.cm.node_uuid,
target="armed_ready",
data=data,
)
CUE_HANDLER.communications_thread.send_operation(operation, timeout=0.1)
Logger.debug(f"Notified Controller that {context} is complete")
except Exception as e:
Logger.warning(f"Could not notify Controller of armed_ready: {e}")
def _notify_cue_enabled(self, cue_id: str, enabled: bool):
"""Send cue enabled status to Controller via NNG."""
from .comms.NodesHub import ActionType, NodeOperation, OperationType
try:
operation = NodeOperation(
type=OperationType.STATUS,
action=ActionType.UPDATE,
sender=(
self.cm.node_uuid if hasattr(self, "cm") and self.cm else "node"
),
target="cue_enabled",
data={"cue_id": cue_id, "enabled": enabled},
)
CUE_HANDLER.communications_thread.send_operation(operation, timeout=0.1)
except Exception as e:
Logger.warning(f"Could not notify cue_enabled: {e}")
def _notify_stop_project(self, cue_id):
"""A stop_project ActionCue was revealed on this node (869fhjdq5).
Send the controller a STATUS op carrying the cue and the current run;
the controller validates it like a follow message (adopted sender,
cue in project, running, current run_seq) and runs stop_script, which
is the operator STOP. Every node reveals every ActionCue, so the
controller gets one message per node and acts on the first; the rest
are dropped there at INFO.
Nothing is stopped here: one stop path, the controller's. If no STOP
or load is received within _STOP_PROJECT_WATCHDOG_S the watchdog
logs a WARNING and the show keeps running, which is the safe side.
Skipped (INFO) when a STOP or load is already pending on this node, or
when no run is in progress (run_seq is None between a STOP/load and
the next GO): both mean the show is ending or ended anyway.
"""
from .comms.NodesHub import ActionType, NodeOperation, OperationType
relay = self._follow_relay
if relay is None:
Logger.warning(
f"stop_project cue {cue_id}: no comms relay on this node, cannot "
"notify the controller; the show keeps running"
)
return
if relay.stop_pending:
Logger.info(
f"stop_project cue {cue_id}: a STOP or load is already pending on "
"this node, not sending"
)
return
run_seq = relay.run_seq
if run_seq is None:
Logger.info(
f"stop_project cue {cue_id}: no run in progress (no GO since the "
"last STOP or load), not sending"
)
return
stops_at_send = relay.stops_received
try:
CUE_HANDLER.communications_thread.send_operation_nowait(
NodeOperation(
type=OperationType.STATUS,
action=ActionType.UPDATE,
sender=self.cm.node_uuid,
target="stop_project",
data={"cue": str(cue_id), "run_seq": run_seq},
)
)
except Exception as e:
Logger.error(
f"stop_project cue {cue_id}: could not notify the controller "
f"({e}); the show keeps running"
)
return
Logger.info(
f"stop_project cue {cue_id}: notified the controller (run {run_seq})"
)
self._arm_stop_project_watchdog(cue_id, stops_at_send)
def _arm_stop_project_watchdog(self, cue_id, stops_at_send: int) -> None:
self._cancel_stop_project_watchdog()
timer = threading.Timer(
self._STOP_PROJECT_WATCHDOG_S,
self._on_stop_project_watchdog_fire,
args=(cue_id, stops_at_send),
)
timer.daemon = True
self._stop_project_watchdog = timer
timer.start()
def _cancel_stop_project_watchdog(self) -> None:
timer = self._stop_project_watchdog
if timer is not None:
timer.cancel()
self._stop_project_watchdog = None
def _on_stop_project_watchdog_fire(self, cue_id, stops_at_send: int) -> None:
"""Compares STOP/load RECEIPTS, not executions: a STOP queued behind a
long command has still been received, and an operator STOP that got in
first counts too. Log only."""
relay = self._follow_relay
if relay is not None and relay.stops_received > stops_at_send:
return
Logger.warning(
f"stop_project cue {cue_id} sent, no STOP received from the "
f"controller in {self._STOP_PROJECT_WATCHDOG_S:.0f} s; the show "
"keeps running"
)
def set_next_cue(self, value):
"""
Handle setnextcue command from the UI — override next_cue_pointer.
Arms the SELECTED cue synchronously (a GO right after this needs it
immediately), but extends the arm-ahead window in a background
PreArm:<id> thread. Badajoz, 2026-09-25 (869f79ecc): that extension
used to run here, synchronously, inside run_command's
_command_lock. A cold-boot pre-arm took ~500ms; a GO sent right
after (UI, power-bridge /gocue) waited for the lock, executed
late, and read its own MTC ~520ms later than the other nodes —
anchoring its whole Auto-continue chain late. See go_script /
_resolve_go_anchor for the anchor half of that fix; this is the
half that stops the delay from happening in the first place.
"""
if not self.script:
Logger.warning("No script loaded, cannot set next cue.")
return
cue = self.script.find(value)
if cue:
self.next_cue_pointer = cue
self._selection_epoch += 1
selection_epoch = self._selection_epoch
project_gen = self._project_generation
# Captured HERE, on the command thread: the lookahead belongs to
# the STOP/load epoch in which it was asked for.
arm_epoch = CUE_HANDLER.arm_epoch()
if not CUE_HANDLER.find_armed_cue(cue):
Logger.info(f"Re-arming cue {cue.id} selected as next cue")
CUE_HANDLER.arm(cue, init=True)
threading.Thread(
target=self._prearm_thread,
args=(
self._prearm_lookahead,
cue,
project_gen,
selection_epoch,
arm_epoch,
),
daemon=True,
name=f"PreArm:{cue.id}",
).start()
self._broadcast_nextcue()
Logger.info(f"Next cue overridden by UI: {value}")
else:
Logger.warning(f"setnextcue: cue {value} not found in script")
def _prearm_thread(self, body, cue, *args):
"""Body of every PreArm:<id> thread: run `body(cue, *args)`, then log
what the node holds armed -- also when the walk was abandoned or
failed. Measurement only."""
try:
body(cue, *args)
finally:
CUE_HANDLER.log_armed_inventory(f"PreArm:{cue.id}")
def _prearm_lookahead(self, cue, project_gen, selection_epoch, arm_epoch):
"""Background half of set_next_cue — see its docstring.
should_continue re-checks BOTH the project generation (a STOP/load
bumps it, same guard as _arm_with_enabled_guard) and this
selection's own epoch (a later set_next_cue call bumps it even if
it reselects the same cue), so a stale walk stops advancing as
soon as either happens, without waiting for it to finish.
arm_epoch is the STOP/load epoch captured by the command that spawned
this thread. Every arm the walk makes belongs to it: CUE_HANDLER
refuses or abandons an arm whose epoch has moved, so a cue this walk
was arming across a STOP or a load is never published. That is why
this thread disarms NOTHING afterwards (869f9wqpn) -- it used to, and
by then the restarted run could already be playing the cue.
Audio is pre-armed here like any other local cue. It was excluded
at first (skip_arming_types=(AudioCue,)) for fear of a slow JACK
port wait racing a GO for the same cue; measured instead
(2026-09-25): the port appears 0-0.6 s after the engine starts
waiting (Badajoz, taller, test2 node01), and a fully concurrent
spawn of 16 audioplayers takes ~4.2 s -- while this walk adds at
most one extra concurrent arm. Excluding audio cost ~320 ms of late
audio on every run where audio follows local cues. If that ever has
to be revisited, skip_arming_types is still the lever.
"""
def should_continue():
return (
self._project_generation == project_gen
and self._selection_epoch == selection_epoch
)
CUE_HANDLER._arm_ahead(
cue, should_continue=should_continue, arm_epoch=arm_epoch
)
def _prearm_after_advance(self):
"""Pre-arm this node's next segment after a GO advanced the pointer
with nothing local to play.
Target = what the NEXT GO will dispatch on this node:
`_first_local_enabled_in_go_chain(next_cue_pointer)` -- None when
that GO is another node's too, in which case nothing is armed yet
(the next advance re-checks), so this never preloads a cue that is
many GOs away. The target AND its lookahead are armed on the same
PreArm:<id> background thread set_next_cue uses, with the same
project-generation / selection-epoch abort guards (a STOP, a load or
a later selection abandons it).
Nothing is armed here, synchronously: this runs inside run_command's
_command_lock, and an audio target spawns a player and waits for its
JACK ports -- a STOP or the next GO sent meanwhile would wait for the
whole arm (869f79ecc removed exactly that from set_next_cue). A GO
that lands mid-arm is safe: arm() makes it wait on the in-progress
arm instead of arming the cue twice.
What IS done here, on the command thread, is capturing the STOP/load
epoch the arm belongs to. A STOP between this GO and the thread's
first step must find the arm stale, not current.
"""
target = self._first_local_enabled_in_go_chain(self.next_cue_pointer)
if target is None:
return
self._selection_epoch += 1
Logger.info(
"Pointer advanced with no local cue; pre-arming next local cue "
f"{target.id} ({type(target).__name__}) + lookahead"
)
threading.Thread(
target=self._prearm_thread,
args=(
self._prearm_segment,
target,
self._project_generation,
self._selection_epoch,
CUE_HANDLER.arm_epoch(),
),
daemon=True,
name=f"PreArm:{target.id}",
).start()
def _prearm_segment(self, target, project_gen, selection_epoch, arm_epoch):
"""PreArm:<id> body for _prearm_after_advance: arm the segment's
first cue, then the lookahead from it.
It never disarms. If a STOP or a load lands while the target is
arming, CUE_HANDLER.arm() abandons that arm itself: the cue is never
published, so the restarted run's GO arms it fresh and nothing can
cut it afterwards (869f9wqpn; see _prearm_lookahead).
"""
def should_continue():
return (
self._project_generation == project_gen
and self._selection_epoch == selection_epoch
)
if not should_continue():
return
if not CUE_HANDLER.find_armed_cue(target):
# A walk, so arm()'s own post_go / action-target recursion obeys
# the same guards and the same epoch (869f79ecc).
walk = _ArmWalk(should_continue=should_continue, epoch=arm_epoch)
CUE_HANDLER.arm(target, init=True, walk=walk)
# The epoch moves when a STOP BEGINS (stop_all_cues), before the
# generation does (ready_script): check it too, or the walk would
# start inside the teardown.
if not should_continue() or CUE_HANDLER.arm_epoch() != arm_epoch:
return
self._prearm_lookahead(target, project_gen, selection_epoch, arm_epoch)
def _handle_cue_enabled(self, value):
"""The command thread of a UI toggle (``"<cue_id> <0|1>"``). The flag
was set by the receive hook, in bus order (D31 d): this thread does
not write it. It runs the side effects and the STATUS for the flag as
it is by then; running them twice changes nothing."""
cue, _ = self._parse_cue_enabled(value)
if cue is None:
return
cue_id = value.split(" ", 1)[0]
enabled = chain_pass.cue_enabled(cue)
self._apply_cue_enabled_side_effects(cue, enabled)
self._notify_cue_enabled(cue_id, enabled)
Logger.info(f'Cue {cue_id} set to {"enabled" if enabled else "disabled"}')
def _apply_cue_enabled_side_effects(self, cue, enabled: bool):
"""React to a cue's flag (Design §3): enabled, the async arm and the
retake at the enable (D33); disabled, the retake, else disarm if
idle. A toggle moves no other cue, no time and not the pointer
(D26, D30). A cue more than one node runs is neither retaken nor
disarmed while a pass holds it: its thread decides at its own
instants. A CueList's child disabled before its commit is cancelled
(cancel_child).
Shared by _handle_cue_enabled (Controller-driven toggle) and
_action_result_sink (enable/disable ActionCue executed on this node).
Callers notify the Controller themselves — this method never does.
"""
mtc = getattr(self, "mtc_listener", None)
held = getattr(cue, "_pass", None) is not None and getattr(
cue, "_playing", False
)
if isinstance(cue, CueList):
if held:
return
# A CueList has no player of its own: react on its first enabled
# child, mirroring run_cueList's first-enabled-child walk.
child = next(
(c for c in getattr(cue, "contents", None) or [] if c.enabled), None
)
if child is not None:
self._apply_cue_enabled_side_effects(child, enabled)
return
if held and CueHandler._runs_everywhere(cue):
CUE_HANDLER.log_toggle(cue, enabled, None)
if mtc is not None and getattr(cue, "action_type", None) == "stop_project":
CUE_HANDLER.stop_project_toggled(cue, mtc)
return
if not enabled:
if (
getattr(cue, "_pass", None) is None
and CUE_HANDLER.cancel_child(cue) is True
):
# A CueList's child, set up and not committed: silent in its
# parent's pass (S89).
return
taken = CUE_HANDLER.retake(cue, mtc) if mtc is not None else None
if held:
CUE_HANDLER.log_toggle(cue, False, taken)
# Disarm only if armed, not held by a pass (a retaken cue must be
# found armed by an enable before its commit) and NOT playing
# (never cut live playback).
if (
not taken
and CUE_HANDLER.find_armed_cue(cue)
and not getattr(cue, "_playing", False)
):
CUE_HANDLER.disarm(cue, reason="disabled")
Logger.info(f"Disarmed disabled cue {cue.id}")
else:
# Re-arm in a daemon thread to avoid blocking the caller
# (arm() is slow — media loading, process spawning).
if cue._local and not CUE_HANDLER.find_armed_cue(cue):
gen = self._project_generation
# Captured by the spawner -- the command thread, or an
# ActionCue's own thread (_action_result_sink) -- not by the
# ReArm thread when it gets to run.
threading.Thread(
target=self._arm_with_enabled_guard,
args=(cue, gen, CUE_HANDLER.arm_epoch()),
daemon=True,
name=f"ReArm:{cue.id}",
).start()
Logger.info(f"Re-arming enabled cue {cue.id} (async)")
# D33: the retake at the enable, not at the end of the arm: the
# thread it starts waits for the arm in flight and plays late if
# the arm ends after its start.
if mtc is not None:
taken = CUE_HANDLER.retake(cue, mtc)
if held:
CUE_HANDLER.log_toggle(cue, True, taken)
#########################
# Script logic
#########################
def ready_script(self, reason: str = "ready_script"):
"""Check if the script is ready to be played.
``reason`` is passed to disarm_all so its log names the caller
(``load``, ``stop``).
"""
if not self.script:
Logger.warning("No script loaded, cannot process GO command.")
return
self.ongoing_cue = None
self.next_cue_pointer = None
self.go_offset = 0
self._project_generation += 1 # Abort in-flight daemon arm threads
self.unload_video_devs()
CUE_HANDLER.disarm_all(reason=reason)
# Reset mixer volumes to default when preparing script
mixer_client = PLAYER_HANDLER.get_audio_mixer_client()
if mixer_client:
mixer_client.reset_volumes()
# Report the reset so the UI reflects real (unity) gain.
self._report_mixer_status()
self.initial_cuelist_process()
# Set initial nextcue to the first enabled cue in the script
if self.script.cuelist.contents:
first_enabled = None
for c in self.script.cuelist.contents:
if c.enabled:
first_enabled = c
break
self.next_cue_pointer = first_enabled
Logger.info(f"Script {self.script.name} loaded and ready to be played")
# Measurement only: what the load / STOP re-arm left armed.
CUE_HANDLER.log_armed_inventory(reason)
def _resolve_go_anchor(self, value):
"""Resolve the GO_mtc anchor for this GO.
Prefers the controller's own GO instant, shipped as
value == {"go_mtc_ms": <float>, "lead_ms": <float>, ...} by
ControllerEngine.go_script. Falls back to this node's own MTC
whenever `value` doesn't carry a usable one, or the controller's
instant looks implausible against this node's own MTC.
Badajoz, 2026-09-25: a node whose setnextcue pre-arm held
_command_lock for ~500ms read its own MTC ~520ms later than the
other two boxes at GO time and anchored its whole Auto-continue
chain late. MTC-following cannot correct a wrong anchor -- only
agreeing on one does.
869feynrj §4.5c-d, D11: the controller's anchor is LED, interpolated
MTC + L ceiled to the next frame, so the plausibility check runs
against anchor - lead_ms (the instant of the press); a controller
that sends no lead_ms (older) is checked against anchor - the floor.
The fallback is this node's interpolated MTC + the same lead, ceiled
to the next frame: the only other place L is applied (S0-13).
"""
local = self.mtc_listener.main_tc.milliseconds_exact
lead = go_lead.GO_LEAD_FLOOR_MS
if isinstance(value, dict):
shipped = value.get("lead_ms")
if (
isinstance(shipped, (int, float))
and not isinstance(shipped, bool)
and shipped >= 0
):
lead = float(shipped)
ctrl = value.get("go_mtc_ms")
if isinstance(ctrl, (int, float)) and not isinstance(ctrl, bool):
lag = local - (ctrl - lead)
if -self._GO_ANCHOR_FUTURE_TOL_MS <= lag <= self._GO_ANCHOR_MAX_LAG_MS:
Logger.info(
f"GO anchored at controller instant {ctrl:.1f}ms "
f"(lead {lead:.0f}ms, node lag {lag:.1f}ms)"
)
return ctrl
Logger.warning(
f"GO anchor from controller ({ctrl:.1f}ms, lead {lead:.0f}ms) "
f"implausible against local MTC ({local:.1f}ms, lag "
f"{lag:.1f}ms) -- using local MTC instead"
)
now = CUE_HANDLER._interpolated_clock(self.mtc_listener)()
anchor = go_lead.ceil_frame(now + lead)
Logger.info(
f"GO anchored at local MTC {now:.1f}ms + lead {lead:.0f}ms -> "
f"{anchor:.0f}ms"
)
return anchor
def go_script(self, value):
try:
self._go_script(value)
finally:
# Measurement only: what this node holds armed once the GO is
# done (dispatched, nothing local, or skipped). go()'s own
# lookahead is synchronous, so it is included.
if self.script:
CUE_HANDLER.log_armed_inventory("GO")
def _go_script(self, value):
if not self.script:
Logger.warning("No script loaded, cannot process GO command.")
return
if not self.with_mtc:
Logger.warning("No MTC listener, cannot process GO command.")
return
# The last GO value seen (the R4 test knob's supersede re-sends its
# run_seq and lead_ms).
self._last_go_value = value if isinstance(value, dict) else None
# Determine the cue to go
if not self.ongoing_cue:
# First GO - use next_cue_pointer (may have been overridden by
# setnextcue)
cue_to_go = self.next_cue_pointer or self.script.cuelist.contents[0]
Logger.info(f"GO command received. Starting script {self.script.name}")
else:
# Successive GO - advance to next cue
if self.next_cue_pointer:
cue_to_go = self.next_cue_pointer
Logger.info(
f"GO command received. Advancing to next cue: {cue_to_go.id}"
)
else:
# No next cue - script has finished. Do not stop timecode or
# reset state.
Logger.info("No more cues. Press STOP to restart.")
self._go_note("no more cues")
return
# Capture the GO instant ONCE: the pass's anchor AND the drift
# baseline (go_offset). Resolved from the controller's own instant
# when it shipped one (see _resolve_go_anchor): every node then lays
# out the SAME pass from the SAME value.
GO_mtc = self._resolve_go_anchor(value)
# The pass, laid out from the script alone (1amfwm7jnqf, Design §1):
# every cue linked by post_go='go' from the GO's cue, each at its
# arrival, enabled or not, local or not -- the same on every node.
entry = cue_to_go
layout = chain_pass.layout(entry, GO_mtc, CueHandler._advance_mode(entry))
first, arrival = CueHandler._first_local_in(layout)
root = int(getattr(self, "_go_root_seq", 0) or 0)
if first is None:
# Nothing of this pass is this node's. The pass still has its
# place and its line, and the pointer moves in lockstep with the
# node that did play (a global sequence property).
CUE_HANDLER.mint_pass(layout, GO_mtc, root)
self.next_cue_pointer = self._pointer_after(entry)
self._broadcast_nextcue()
Logger.info(
f'No local cue in post_go="go" chain from {entry.id}; '
f"nothing to play on this node. Advanced next cue to "
f'{self.next_cue_pointer.id if self.next_cue_pointer else "none"}'
)
# ...and arm what the NEXT GO will dispatch here, now (Medina
# sala1, 2026-09-30: the node's first cue fired 240 ms late).
self._prearm_after_advance()
self._go_note("no local cue")
return
# Update state
self.set_status("running", "yes")
self.ongoing_cue = first
# D32 (Design §4): no arm here. A cue still arming is dispatched at
# once; its own thread waits for the arm and it plays late, a failed
# arm silences that cue on this node only, and the command lock is
# not held for an arm.
t_go = monotonic()
with chain_pass_root(root):
main_thread = CUE_HANDLER.go(
first, self.mtc_listener, arrival, layout=layout
)
self._go_note("go+lookahead", (monotonic() - t_go) * 1000)
if main_thread is not None:
# R4 (test knob, inert in production).
self._test_cancel_at(entry, GO_mtc)
if main_thread is None:
# A STOP landed meanwhile (the chain-epoch barrier refuses the
# dispatch), or the cue became non-local.
Logger.error(f"Cue {first.id} was not started; aborting GO")
self.set_status("running", "no")
self.ongoing_cue = None
return
Logger.info(f"Cue {first.id} started on main thread: {main_thread.name}")
# Update next cue pointer (N2, D30)
self.next_cue_pointer = self._pointer_after(entry)
# Drift baseline; consumed by BaseEngine.timecode = mtc - go_offset.
# GO_mtc is the LED anchor (869feynrj §4.5).
self.go_offset = GO_mtc
# Broadcast nextcue to UI
self._broadcast_nextcue()
Logger.info(
f"Cue {first.id} started. Next cue:"
f'{self.next_cue_pointer.id if self.next_cue_pointer else "none"}'
)
@staticmethod
def _pointer_after(cue):
"""The next-cue pointer after a GO on ``cue`` (N2, D30): the first
enabled cue behind Z, the first ``pause`` cue reached from ``cue``
along the links, through ``go`` and Auto-follow cues, enabled or
not. With Z enabled that is what Cue.get_next_cue() returns (a
nested CueList keeps its stepping); with Z disabled get_next_cue()
would walk on through it, so the walk is done here."""
z, walked = cue, 0
while (
z is not None
and getattr(z, "post_go", None) != "pause"
and getattr(z, "_target_object", None) is not None
and walked < 1024
):
z = z._target_object
walked += 1
if z is None or chain_pass.cue_enabled(z):
return cue.get_next_cue()
nxt, walked = getattr(z, "_target_object", None), 0
while nxt is not None and not chain_pass.cue_enabled(nxt) and walked < 1024:
nxt = getattr(nxt, "_target_object", None)
walked += 1
return nxt
# ---- R4 test knob: a cancel at start + offset, by the real path --------
_test_injecting = False
def _test_cancel_at(self, cue_to_go, arrival_ms: float) -> None:
"""CUEMS_TEST_CANCEL_AT (869feynrj step 5, R4): schedule one cancel of
this operator GO's pass. Never for a GO the knob injected itself."""
if self._test_injecting:
return
plan = self._test_cancel_plan(cue_to_go, arrival_ms)
if plan is None:
return
threading.Thread(
target=self._test_cancel_fire,
args=plan,
daemon=True,
name=f"TestCancelAt:{plan[2].id}",
).start()
def _test_cancel_plan(self, cue_to_go, arrival_ms: float):
"""(action, offset, target, mtc to fire at, k, len): the first local,
enabled AudioCue of the pass (the GO's cue and its Auto-continue
chain), at its start label (arrival + prewait, rounded to the 40 ms
grid as the player gets it) + this GO's offset (the k-th of len, taken
in turn). None when the knob is off or there is no such cue."""
spec = test_knobs.cancel_at()
if spec is None:
return None
action, offset, k, count = spec
# 1amfwm7jnqf (§6): the AudioCue's start is its arrival in the pass's
# layout + its prewait; every cue before it advances the chain.
for node, arrival in chain_pass.layout(
cue_to_go, arrival_ms, CueHandler._advance_mode(cue_to_go)
):
if (
isinstance(node, AudioCue)
and getattr(node, "_local", False)
and getattr(node, "enabled", False)
):
start = arrival + node.prewait.milliseconds_exact
label = round(start / go_lead.FRAME_MS) * go_lead.FRAME_MS
return action, offset, node, label + offset, k, count
Logger.warning(
f"TEST KNOB: cancel {action}: no local AudioCue in this GO's pass"
)
return None
def _test_cancel_fire(
self,
action: str,
offset: float,
target,
at_ms: float,
k: int = 1,
count: int = 1,
):
"""Wait for the node's interpolated MTC to reach ``at_ms`` (1 ms
resolution), then inject the cancel through the path the real command
takes: STOP / cue_enabled / setnextcue + go through the bus receive
hook and the NNG handler, the actions through the ActionHandler."""
clock = CUE_HANDLER._interpolated_clock(self.mtc_listener)
late = clock() - at_ms
if late > 1.0:
# e.g. an offset below -L on a prewait-0 cue: before the GO itself
Logger.warning(
f"TEST KNOB: cancel {action} at start{offset:+.1f} ms was already "
f"{late:.1f} ms past when the GO was handled; firing now (use a "
"cue with a prewait for this offset)"
)
while clock() < at_ms:
sleep(0.0005)
Logger.warning(
f"TEST KNOB: cancel {action} at start{offset:+.1f} ms (mtc {clock():.1f}) "
f"(offset {k}/{count})"
)
self._test_injecting = True
try:
if action == "stop":
self._test_inject("stop", None)
elif action == "disable":
self._test_inject("cue_enabled", f"{target.id} 0")
elif action == "supersede":
last = getattr(self, "_last_go_value", None) or {}
relay = self._follow_relay
value = {
"run_seq": relay.run_seq if relay else last.get("run_seq"),
"lead_ms": last.get("lead_ms", go_lead.GO_LEAD_FLOOR_MS),
}
self._test_inject("setnextcue", str(target.id))
self._test_inject("go", value)
else:
from cuemsutils.cues import ActionCue
from .cues.ActionHandler import ACTION_HANDLER
kind = {
"actionstop": "stop",
"actionpause": "pause",
"actionfadeout": "fade_out",
}[action]
action_cue = ActionCue()
action_cue.action_type = kind
action_cue.action_target = target.id
action_cue._action_target_object = target
ACTION_HANDLER.execute_action(action_cue, self.mtc_listener, None)
except Exception as e:
Logger.error(f"TEST KNOB: cancel {action} failed: {e}")
finally:
self._test_injecting = False
def _test_inject(self, command: str, value) -> None:
"""A bus command as it arrives: the receive hook, then the handler."""
if not self._on_command_received(command, value):
self._handle_nng_command(command, value)
def stop_playback(self, value=None):
"""Stop playback, full cleanup, then re-arm so GO is available again.
Does the cleanup that ready_script() doesn't handle (DMX blackout,
disconnect video, kill audio), then delegates reset + re-arm to
ready_script(). Notifies Controller when armed (GO button green).
"""
Logger.info("STOP command received. Stopping playback.")
self.set_status("running", "no")
self._gradient_cancel_all("stop")
# Signal all running cue threads to stop immediately.
# Must happen BEFORE blackout/reset so loop_cue threads don't
# re-push DMX frames or send /visible after cleanup.
CUE_HANDLER.stop_all_cues()
# 50 ms: loop_cue polls every 20 ms. 869feynrj D10: stop_all_cues sent
# /cancelstart to every selfgate player that may follow, and the first
# disconnect below must not cut its fade: wait max(50 ms, transit +
# one period + fade_ms + margin) (review 4 m3).
sleep(max(0.05, START_GATE.pending_fade_wait_s()))
# DMX: disable MTC following first (freezes the playhead so queued
# scenes can't fire), then blackout via OLA for instant visual reset.
self._dmx_reset()
# Unload all video layers (instant visual blackout)
self.unload_video_devs()
# Kill all audio players (ready_script does not do this)
PLAYER_HANDLER.kill_all_audio_players()
PLAYER_HANDLER.cleanup_zombie_jack_clients()
# Reset state + disarm + volume reset + re-arm cues
if self.script:
self.ready_script(reason="stop")
Logger.info(f"Project {self.script.name} reset and ready for GO.")
# Notify Controller that re-arm is complete (GO button can go
# green)
self._notify_armed_ready("re-arm")
# Broadcast nextcue (reset to first cue after stop)
self._broadcast_nextcue()
else:
Logger.info("Playback stopped (no script loaded).")
Logger.info("Playback stopped.")
|