oxurack-rt 0.1.0

Real-time MIDI clock and I/O thread for oxurack.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
//! The real-time MIDI thread main loop.
//!
//! This module contains the entry point for the dedicated RT thread.
//! The loop handles clock tick generation/tracking, MIDI I/O, and
//! command processing from the ECS world via lock-free queues.
//!
//! # Event-push discipline
//!
//! Every push into `queues.events` in this file goes through
//! [`push_event`]. The one exception is the raw push inside
//! `push_event` itself, which emits the overflow warning as a
//! last resort and must not recurse. Anything else is a bug.

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::queues::RtSideQueues;

/// Number of consecutive queue push failures before a
/// [`crate::RtErrorCode::QueueOverflow`] event is emitted.
const OVERFLOW_REPORT_THRESHOLD: u32 = 10;

/// Runs the RT thread main loop.
///
/// This function is the entry point for the spawned real-time thread.
/// It elevates thread priority, opens MIDI ports (both output and
/// input), and enters a tight loop that:
///
/// 1. Drains incoming [`crate::EcsCommand`]s and processes them.
/// 2. Sleeps until the next clock tick.
/// 3. Emits MIDI Clock (0xF8) on all output ports.
/// 4. Pushes a [`crate::RtEvent::ClockTick`] event to the ECS world.
/// 5. Advances the master clock to the next tick position.
/// 6. Drains MIDI input events, classifies them, and pushes the
///    appropriate [`crate::RtEvent`]s to the ECS world.
///
/// The loop exits when a [`crate::EcsCommand::Shutdown`] command is
/// received, the shutdown flag is set, or an unrecoverable error occurs.
///
/// # Arguments
///
/// * `queues` - The RT-side queue handles for sending events and
///   receiving commands.
/// * `config` - The runtime configuration (clock mode, ports, etc.).
/// * `ready_signal` - A channel to signal readiness (or error) back to
///   the spawning thread.
/// * `shutdown` - An atomic flag checked each iteration to allow
///   external shutdown.
pub(crate) fn rt_thread_main(
    mut queues: RtSideQueues,
    config: crate::RuntimeConfig,
    ready_signal: std::sync::mpsc::SyncSender<Result<(), crate::Error>>,
    shutdown: Arc<AtomicBool>,
) {
    // Track consecutive queue overflow failures across all modes.
    let mut consecutive_overflows: u32 = 0;

    // 1. Elevate RT priority. If `allow_normal_priority` is false,
    //    failure is fatal and the thread reports the error to the
    //    spawning thread via the ready signal. When allowed, a failure
    //    is reported as a non-fatal event on the queue.
    let _rt_priority_handle = match crate::priority::elevate_rt_priority() {
        Ok(handle) => Some(handle),
        Err(e) => {
            if !config.allow_normal_priority {
                let _ = ready_signal.send(Err(e));
                return;
            }
            push_event(
                &mut queues,
                crate::RtEvent::NonFatalError(crate::RtErrorCode::PriorityElevationFailed),
                &mut consecutive_overflows,
            );
            None
        }
    };

    // 2. Open MIDI output ports.
    let mut midi_ports = match crate::midi_io::MidiPorts::open_outputs(&config.outputs) {
        Ok(ports) => ports,
        Err(e) => {
            let _ = ready_signal.send(Err(e));
            return;
        }
    };

    // 3. Open MIDI input ports.
    let mut midi_input_ports = match crate::midi_io::MidiInputPorts::open(&config.inputs) {
        Ok(ports) => ports,
        Err(e) => {
            let _ = ready_signal.send(Err(e));
            return;
        }
    };

    // 4. Signal readiness to the spawning thread.
    let _ = ready_signal.send(Ok(()));

    // 5. Create clock and timing infrastructure.
    let clock = crate::timing::MonotonicClock::new();

    match &config.clock_mode {
        crate::ClockMode::Master {
            tempo_bpm,
            send_transport,
        } => {
            let send_transport = *send_transport;
            let mut master = crate::clock::master::MasterClock::new(*tempo_bpm, clock.now());
            let mut is_running = true;

            // Master mode loop.
            loop {
                if shutdown.load(Ordering::Relaxed) {
                    break;
                }

                // Drain commands from ECS.
                while let Ok(cmd) = queues.commands.pop() {
                    match cmd {
                        crate::EcsCommand::Shutdown => {
                            shutdown.store(true, Ordering::Relaxed);
                            break;
                        }
                        crate::EcsCommand::SetTempo { bpm } => {
                            master.set_tempo(bpm);
                        }
                        crate::EcsCommand::SendMidi {
                            output_port_index,
                            message,
                        } => {
                            let bytes = message.to_bytes();
                            let len = message.length as usize;
                            let _ = midi_ports.send(output_port_index, &bytes[..len]);
                        }
                        crate::EcsCommand::SendTransport(transport) => {
                            match transport {
                                crate::TransportEvent::Start => {
                                    if send_transport {
                                        for i in 0..config.outputs.len() {
                                            let _ = midi_ports.send(i as u8, &[0xFA]);
                                        }
                                    }
                                    master.reset();
                                    is_running = true;
                                }
                                crate::TransportEvent::Stop => {
                                    if send_transport {
                                        for i in 0..config.outputs.len() {
                                            let _ = midi_ports.send(i as u8, &[0xFC]);
                                        }
                                    }
                                    is_running = false;
                                }
                                crate::TransportEvent::Continue => {
                                    if send_transport {
                                        for i in 0..config.outputs.len() {
                                            let _ = midi_ports.send(i as u8, &[0xFB]);
                                        }
                                    }
                                    is_running = true;
                                }
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(transport),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::EcsCommand::SendSongPosition { position } => {
                            if send_transport {
                                let lsb = (position & 0x7F) as u8;
                                let msb = ((position >> 7) & 0x7F) as u8;
                                for i in 0..config.outputs.len() {
                                    let _ = midi_ports.send(i as u8, &[0xF2, lsb, msb]);
                                }
                            }
                            master.set_position_from_spp(position);
                            push_event(
                                &mut queues,
                                crate::RtEvent::SongPosition { position },
                                &mut consecutive_overflows,
                            );
                        }
                    }
                }

                if shutdown.load(Ordering::Relaxed) {
                    break;
                }

                if is_running {
                    // Sleep until the next tick.
                    let schedule = master.next_tick();
                    crate::timing::precision_sleep(schedule.next_tick_ns, &clock);

                    // Emit MIDI Clock (0xF8) on all output ports.
                    for i in 0..config.outputs.len() {
                        let _ = midi_ports.send(i as u8, &[0xF8]);
                    }

                    // Push ClockTick event to ECS.
                    let tick_event = crate::RtEvent::ClockTick {
                        subdivision: schedule.subdivision,
                        beat: schedule.beat,
                        tempo_bpm: master.tempo(),
                        timestamp_ns: clock.now(),
                    };
                    push_event(&mut queues, tick_event, &mut consecutive_overflows);

                    // Advance to the next tick position.
                    master.advance();
                } else {
                    // When stopped, sleep briefly to avoid busy-waiting.
                    // We use a plain sleep rather than a condvar because
                    // the RT thread avoids blocking synchronisation
                    // primitives that could cause priority inversion or
                    // unbounded latency when transport resumes.
                    std::thread::sleep(std::time::Duration::from_millis(1));
                }

                // Drain MIDI input events and classify them.
                drain_midi_input(
                    &mut midi_input_ports,
                    &mut queues,
                    &mut consecutive_overflows,
                );
            }
        }
        crate::ClockMode::Passthrough {
            timeout_ns,
            multiply,
            divide,
            ..
        } => {
            let mut pt_clock =
                crate::clock::passthrough::PassthroughClock::new(*multiply, *divide, *timeout_ns);

            // Passthrough mode loop.
            loop {
                if shutdown.load(Ordering::Relaxed) {
                    break;
                }

                // Drain commands from ECS.
                while let Ok(cmd) = queues.commands.pop() {
                    match cmd {
                        crate::EcsCommand::Shutdown => {
                            shutdown.store(true, Ordering::Relaxed);
                            break;
                        }
                        crate::EcsCommand::SendMidi {
                            output_port_index,
                            message,
                        } => {
                            let bytes = message.to_bytes();
                            let len = message.length as usize;
                            let _ = midi_ports.send(output_port_index, &bytes[..len]);
                        }
                        crate::EcsCommand::SetTempo { .. } => {
                            // In passthrough mode, tempo is determined by the
                            // external clock source. Ignore SetTempo.
                        }
                        crate::EcsCommand::SendTransport(transport) => {
                            // Forward transport to output ports.
                            let byte = match transport {
                                crate::TransportEvent::Start => {
                                    pt_clock.reset();
                                    pt_clock.set_running(true);
                                    0xFA
                                }
                                crate::TransportEvent::Stop => {
                                    pt_clock.set_running(false);
                                    0xFC
                                }
                                crate::TransportEvent::Continue => {
                                    pt_clock.set_running(true);
                                    0xFB
                                }
                            };
                            for i in 0..config.outputs.len() {
                                let _ = midi_ports.send(i as u8, &[byte]);
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(transport),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::EcsCommand::SendSongPosition { position } => {
                            pt_clock.set_position_from_spp(position);
                            let lsb = (position & 0x7F) as u8;
                            let msb = ((position >> 7) & 0x7F) as u8;
                            for i in 0..config.outputs.len() {
                                let _ = midi_ports.send(i as u8, &[0xF2, lsb, msb]);
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::SongPosition { position },
                                &mut consecutive_overflows,
                            );
                        }
                    }
                }

                if shutdown.load(Ordering::Relaxed) {
                    break;
                }

                // Drain MIDI input events, routing clock/transport to
                // the PassthroughClock and forwarding to outputs.
                let now = clock.now();
                let mut any_tick = false;

                for raw_event in midi_input_ports.drain_all() {
                    let Some(classification) = crate::messages::classify_midi(
                        &raw_event.bytes[..raw_event.length as usize],
                    ) else {
                        continue;
                    };

                    match classification {
                        crate::messages::MidiClassification::Clock => {
                            if !pt_clock.is_running() {
                                continue;
                            }
                            let output_ticks = pt_clock.feed_clock(raw_event.timestamp_ns);
                            for _ in 0..output_ticks {
                                // Emit 0xF8 on all output ports.
                                for i in 0..config.outputs.len() {
                                    let _ = midi_ports.send(i as u8, &[0xF8]);
                                }
                                // Push ClockTick event to ECS.
                                let tick_event = crate::RtEvent::ClockTick {
                                    subdivision: pt_clock.output_subdivision(),
                                    beat: pt_clock.output_beat(),
                                    tempo_bpm: 0.0, // Passthrough does not estimate tempo.
                                    timestamp_ns: clock.now(),
                                };
                                push_event(&mut queues, tick_event, &mut consecutive_overflows);
                                pt_clock.advance_output();
                                any_tick = true;
                            }
                        }
                        crate::messages::MidiClassification::Start => {
                            pt_clock.reset();
                            pt_clock.set_running(true);
                            // Forward to outputs.
                            for i in 0..config.outputs.len() {
                                let _ = midi_ports.send(i as u8, &[0xFA]);
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(crate::TransportEvent::Start),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::Stop => {
                            pt_clock.set_running(false);
                            // Forward to outputs.
                            for i in 0..config.outputs.len() {
                                let _ = midi_ports.send(i as u8, &[0xFC]);
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(crate::TransportEvent::Stop),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::Continue => {
                            pt_clock.set_running(true);
                            // Forward to outputs.
                            for i in 0..config.outputs.len() {
                                let _ = midi_ports.send(i as u8, &[0xFB]);
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(crate::TransportEvent::Continue),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::SongPosition { position } => {
                            pt_clock.set_position_from_spp(position);
                            // Forward to outputs.
                            let lsb = (position & 0x7F) as u8;
                            let msb = ((position >> 7) & 0x7F) as u8;
                            for i in 0..config.outputs.len() {
                                let _ = midi_ports.send(i as u8, &[0xF2, lsb, msb]);
                            }
                            push_event(
                                &mut queues,
                                crate::RtEvent::SongPosition { position },
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::Channel(msg) => {
                            let event = crate::RtEvent::MidiInput {
                                input_port_index: raw_event.port_index,
                                timestamp_ns: raw_event.timestamp_ns,
                                message: msg,
                            };
                            push_event(&mut queues, event, &mut consecutive_overflows);
                        }
                        crate::messages::MidiClassification::ActiveSensing
                        | crate::messages::MidiClassification::SystemReset => {
                            // Ignored system messages.
                        }
                    }
                }

                // Check for clock dropout.
                if pt_clock.check_dropout(now) {
                    push_event(
                        &mut queues,
                        crate::RtEvent::NonFatalError(crate::RtErrorCode::ClockDropout),
                        &mut consecutive_overflows,
                    );
                }

                // If no tick was produced this iteration, sleep briefly
                // to avoid busy-waiting.
                if !any_tick {
                    std::thread::sleep(std::time::Duration::from_millis(1));
                }
            }
        }
        crate::ClockMode::Slave { timeout_ns, .. } => {
            let mut slave_clock = crate::clock::slave::SlaveClock::new(*timeout_ns);

            // Track when we last emitted a "not locked" warning to
            // avoid flooding the ECS queue (limit to ~1 per second).
            let mut last_not_locked_ns: u64 = 0;
            const NOT_LOCKED_INTERVAL_NS: u64 = 1_000_000_000; // 1 second

            // Slave mode loop.
            loop {
                if shutdown.load(Ordering::Relaxed) {
                    break;
                }

                // Drain commands from ECS.
                while let Ok(cmd) = queues.commands.pop() {
                    match cmd {
                        crate::EcsCommand::Shutdown => {
                            shutdown.store(true, Ordering::Relaxed);
                            break;
                        }
                        crate::EcsCommand::SendMidi {
                            output_port_index,
                            message,
                        } => {
                            let bytes = message.to_bytes();
                            let len = message.length as usize;
                            let _ = midi_ports.send(output_port_index, &bytes[..len]);
                        }
                        crate::EcsCommand::SetTempo { .. } => {
                            // In slave mode, tempo is determined by the
                            // external clock source. Ignore SetTempo.
                        }
                        crate::EcsCommand::SendTransport(transport) => {
                            slave_clock.feed_transport(transport, clock.now());
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(transport),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::EcsCommand::SendSongPosition { position } => {
                            slave_clock.feed_spp(position);
                            push_event(
                                &mut queues,
                                crate::RtEvent::SongPosition { position },
                                &mut consecutive_overflows,
                            );
                        }
                    }
                }

                if shutdown.load(Ordering::Relaxed) {
                    break;
                }

                // Drain MIDI input events, routing clock/transport to
                // the SlaveClock and forwarding everything else to ECS.
                let now = clock.now();
                for raw_event in midi_input_ports.drain_all() {
                    let Some(classification) = crate::messages::classify_midi(
                        &raw_event.bytes[..raw_event.length as usize],
                    ) else {
                        continue;
                    };

                    match classification {
                        crate::messages::MidiClassification::Clock => {
                            slave_clock.feed_clock_byte(raw_event.timestamp_ns);
                        }
                        crate::messages::MidiClassification::Start => {
                            slave_clock.feed_transport(
                                crate::TransportEvent::Start,
                                raw_event.timestamp_ns,
                            );
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(crate::TransportEvent::Start),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::Stop => {
                            slave_clock.feed_transport(
                                crate::TransportEvent::Stop,
                                raw_event.timestamp_ns,
                            );
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(crate::TransportEvent::Stop),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::Continue => {
                            slave_clock.feed_transport(
                                crate::TransportEvent::Continue,
                                raw_event.timestamp_ns,
                            );
                            push_event(
                                &mut queues,
                                crate::RtEvent::Transport(crate::TransportEvent::Continue),
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::SongPosition { position } => {
                            slave_clock.feed_spp(position);
                            push_event(
                                &mut queues,
                                crate::RtEvent::SongPosition { position },
                                &mut consecutive_overflows,
                            );
                        }
                        crate::messages::MidiClassification::Channel(msg) => {
                            let event = crate::RtEvent::MidiInput {
                                input_port_index: raw_event.port_index,
                                timestamp_ns: raw_event.timestamp_ns,
                                message: msg,
                            };
                            push_event(&mut queues, event, &mut consecutive_overflows);
                        }
                        crate::messages::MidiClassification::ActiveSensing
                        | crate::messages::MidiClassification::SystemReset => {
                            // Ignored system messages.
                        }
                    }
                }

                // Check for clock dropout.
                if slave_clock.check_dropout(now) {
                    push_event(
                        &mut queues,
                        crate::RtEvent::NonFatalError(crate::RtErrorCode::ClockDropout),
                        &mut consecutive_overflows,
                    );
                }

                // If the slave clock has a tick ready, sleep until it
                // and emit a ClockTick event.
                if let Some(schedule) = slave_clock.next_tick() {
                    crate::timing::precision_sleep(schedule.next_tick_ns, &clock);

                    let tempo_bpm = slave_clock.estimated_bpm().unwrap_or(0.0);
                    let tick_event = crate::RtEvent::ClockTick {
                        subdivision: schedule.subdivision,
                        beat: schedule.beat,
                        tempo_bpm,
                        timestamp_ns: clock.now(),
                    };
                    push_event(&mut queues, tick_event, &mut consecutive_overflows);

                    slave_clock.advance();
                } else {
                    // Not locked: emit a periodic warning.
                    if now.saturating_sub(last_not_locked_ns) >= NOT_LOCKED_INTERVAL_NS {
                        push_event(
                            &mut queues,
                            crate::RtEvent::NonFatalError(crate::RtErrorCode::ClockNotLocked),
                            &mut consecutive_overflows,
                        );
                        last_not_locked_ns = now;
                    }

                    // Sleep briefly to avoid busy-waiting when unlocked.
                    std::thread::sleep(std::time::Duration::from_millis(1));
                }
            }
        }
    }
}

/// Pushes an event to the ECS event queue with overflow tracking.
///
/// If the push fails, increments `consecutive_overflows`. When the
/// counter reaches the reporting threshold (10), attempts to push a
/// [`crate::RtEvent::NonFatalError`] with [`crate::RtErrorCode::QueueOverflow`].
/// On a successful push, the counter is reset to zero.
fn push_event(queues: &mut RtSideQueues, event: crate::RtEvent, consecutive_overflows: &mut u32) {
    if queues.events.push(event).is_ok() {
        *consecutive_overflows = 0;
    } else {
        *consecutive_overflows = consecutive_overflows.saturating_add(1);
        if *consecutive_overflows >= OVERFLOW_REPORT_THRESHOLD {
            // Intentional raw push: the overflow warning itself must not recurse into
            // push_event. Last-resort; if this also fails, the bookkeeping resets and
            // the next threshold hit will try again.
            let _ = queues.events.push(crate::RtEvent::NonFatalError(
                crate::RtErrorCode::QueueOverflow,
            ));
            *consecutive_overflows = 0;
        }
    }
}

/// Drains all pending raw MIDI events from the input ports, classifies
/// them, and pushes the appropriate [`crate::RtEvent`]s to the ECS
/// event queue.
///
/// Called once per RT loop iteration. This function is allocation-free
/// on the hot path.
fn drain_midi_input(
    midi_input_ports: &mut crate::midi_io::MidiInputPorts,
    queues: &mut RtSideQueues,
    consecutive_overflows: &mut u32,
) {
    for raw_event in midi_input_ports.drain_all() {
        let Some(classification) =
            crate::messages::classify_midi(&raw_event.bytes[..raw_event.length as usize])
        else {
            continue;
        };

        match classification {
            crate::messages::MidiClassification::Channel(msg) => {
                let event = crate::RtEvent::MidiInput {
                    input_port_index: raw_event.port_index,
                    timestamp_ns: raw_event.timestamp_ns,
                    message: msg,
                };
                push_event(queues, event, consecutive_overflows);
            }
            crate::messages::MidiClassification::Start => {
                push_event(
                    queues,
                    crate::RtEvent::Transport(crate::TransportEvent::Start),
                    consecutive_overflows,
                );
            }
            crate::messages::MidiClassification::Stop => {
                push_event(
                    queues,
                    crate::RtEvent::Transport(crate::TransportEvent::Stop),
                    consecutive_overflows,
                );
            }
            crate::messages::MidiClassification::Continue => {
                push_event(
                    queues,
                    crate::RtEvent::Transport(crate::TransportEvent::Continue),
                    consecutive_overflows,
                );
            }
            crate::messages::MidiClassification::SongPosition { position } => {
                push_event(
                    queues,
                    crate::RtEvent::SongPosition { position },
                    consecutive_overflows,
                );
            }
            crate::messages::MidiClassification::Clock => {
                // In master mode, external clock bytes are ignored.
                // Slave mode handles clock bytes in its own loop.
            }
            crate::messages::MidiClassification::ActiveSensing
            | crate::messages::MidiClassification::SystemReset => {
                // Ignored system messages.
            }
        }
    }
}

/// Runs a timing precision test loop at elevated priority.
///
/// Elevates the calling thread to real-time priority (best-effort),
/// then executes `iterations` sleep cycles of `interval_ns` nanoseconds
/// each, recording the actual wall-clock interval between consecutive
/// wake-ups.
///
/// Scheduling uses a **drift-preventing** strategy: each target wake-up
/// is computed from the *scheduled* (ideal) time, not the actual wake-up
/// time. This mirrors the master-clock design and prevents jitter from
/// accumulating into long-term drift.
///
/// # Arguments
///
/// * `iterations` - Number of sleep/wake cycles to execute.
/// * `interval_ns` - Desired interval between wake-ups, in nanoseconds.
///
/// # Returns
///
/// A vector of `iterations` measured intervals (in nanoseconds) between
/// consecutive actual wake-up timestamps.
#[cfg(test)]
pub(crate) fn run_timing_test(iterations: u32, interval_ns: u64) -> Vec<u64> {
    use crate::timing::{MonotonicClock, precision_sleep};

    let clock = MonotonicClock::new();

    // Best-effort RT priority elevation; ignore failures (e.g. in CI
    // sandboxes where the calling thread may lack permissions).
    let _rt_priority_handle = crate::priority::elevate_rt_priority().ok();

    let mut intervals: Vec<u64> = Vec::with_capacity(iterations as usize);

    let initial_now = clock.now();
    let mut scheduled = initial_now;
    let mut prev_actual = initial_now;

    for _ in 0..iterations {
        // Compute the next ideal wake-up from the scheduled timeline,
        // not from the actual wake time (drift prevention).
        scheduled += interval_ns;
        precision_sleep(scheduled, &clock);

        let actual_now = clock.now();
        let actual_interval = actual_now.saturating_sub(prev_actual);
        intervals.push(actual_interval);
        prev_actual = actual_now;
    }

    intervals
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Validates that the RT timing loop achieves sub-millisecond jitter.
    ///
    /// Runs 1 000 iterations at a 1 ms interval on a dedicated thread
    /// with RT priority, then checks that the median jitter is under
    /// 200 us and the P99 jitter is under 1 ms.
    ///
    /// Marked `#[ignore]` because results are timing-sensitive and may
    /// vary across machines and CI environments.
    #[test]
    #[ignore]
    fn test_timing_loop_jitter() {
        let handle = std::thread::spawn(|| run_timing_test(1_000, 1_000_000));
        let intervals = handle.join().expect("timing test thread panicked");

        let expected_ns: u64 = 1_000_000;

        let mut jitters: Vec<u64> = intervals
            .iter()
            .map(|&iv| iv.abs_diff(expected_ns))
            .collect();

        jitters.sort_unstable();

        let median = jitters[500];
        let p99 = jitters[990];
        let max = *jitters.last().expect("jitters should not be empty");

        eprintln!(
            "Timing test: median jitter = {}us, P99 = {}us, max = {}us",
            median / 1_000,
            p99 / 1_000,
            max / 1_000,
        );

        assert!(
            median < 200_000,
            "median jitter {median} ns ({} us) exceeds 200 us threshold",
            median / 1_000,
        );
        assert!(
            p99 < 2_000_000,
            "P99 jitter {p99} ns ({} us) exceeds 2 ms threshold",
            p99 / 1_000,
        );
    }

    /// Validates that the scheduled-to-scheduled timing strategy prevents
    /// cumulative drift.
    ///
    /// Runs 1 000 iterations at a 1 ms interval and checks that the
    /// total elapsed time is within 1 % of the expected 1 000 ms
    /// (i.e. drift < 10 ms over one second).
    ///
    /// Marked `#[ignore]` because results are timing-sensitive.
    #[test]
    #[ignore]
    fn test_timing_loop_no_drift() {
        let handle = std::thread::spawn(|| run_timing_test(1_000, 1_000_000));
        let intervals = handle.join().expect("timing test thread panicked");

        let total_ns: u64 = intervals.iter().sum();
        let expected_total_ns: u64 = 1_000 * 1_000_000;

        let drift_ns = total_ns.abs_diff(expected_total_ns);

        let drift_pct = (drift_ns as f64 / expected_total_ns as f64) * 100.0;

        eprintln!(
            "Drift test: total = {} ms, expected = {} ms, drift = {} ms ({:.3}%)",
            total_ns / 1_000_000,
            expected_total_ns / 1_000_000,
            drift_ns / 1_000_000,
            drift_pct,
        );

        assert!(
            drift_ns < expected_total_ns / 100,
            "total drift {drift_ns} ns ({drift_pct:.3}%) exceeds 1% of expected {expected_total_ns} ns",
        );
    }

    // ── Runtime integration tests (M2.4) ────────────────────────────

    /// Helper to build a minimal `RuntimeConfig` for testing (no MIDI
    /// ports, master clock mode). Sets `allow_normal_priority: true` so
    /// tests do not fail in CI sandboxes that lack RT scheduling
    /// permissions.
    fn test_config(tempo_bpm: f64) -> crate::RuntimeConfig {
        crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Master {
                tempo_bpm,
                send_transport: false,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        }
    }

    #[test]
    fn test_runtime_starts_and_stops() {
        let config = test_config(120.0);
        let result = crate::Runtime::start(config);
        assert!(result.is_ok(), "Runtime::start failed: {result:?}");

        let (mut runtime, _handles) = result.unwrap();

        // Let the thread run briefly.
        std::thread::sleep(std::time::Duration::from_millis(100));

        let stop_result = runtime.stop();
        assert!(stop_result.is_ok(), "Runtime::stop failed: {stop_result:?}");
    }

    #[test]
    fn test_runtime_produces_clock_ticks() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Drain events while running. Use a generous window because
        // coverage instrumentation can slow the RT thread significantly.
        let mut tick_count = 0u64;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if matches!(event, crate::RtEvent::ClockTick { .. }) {
                    tick_count += 1;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        runtime.stop().unwrap();

        eprintln!("Received {tick_count} clock ticks in ~500 ms");
        assert!(
            tick_count >= 2,
            "expected at least 2 ticks, got {tick_count}"
        );
    }

    #[test]
    fn test_set_tempo_command() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Change tempo to 60 BPM.
        let cmd = crate::EcsCommand::SetTempo { bpm: 60.0 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // Let ticks accumulate for 500 ms at the new tempo.
        std::thread::sleep(std::time::Duration::from_millis(500));

        runtime.stop().unwrap();

        // Drain all tick events.
        let mut tick_count = 0u64;
        while let Ok(event) = handles.events.pop() {
            if matches!(event, crate::RtEvent::ClockTick { .. }) {
                tick_count += 1;
            }
        }

        // At 60 BPM: 24 ticks/beat * 1 beat/sec = 24 ticks/sec.
        // In 500 ms we expect ~12 ticks. Just verify we got some.
        eprintln!("Received {tick_count} clock ticks after tempo change");
        assert!(
            tick_count >= 3,
            "expected at least 3 ticks, got {tick_count}"
        );
    }

    #[test]
    fn test_shutdown_command() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Send Shutdown command.
        let cmd = crate::EcsCommand::Shutdown;
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // The thread should exit cleanly within the stop() timeout.
        // We use stop() which internally joins the thread.
        let stop_result = runtime.stop();
        assert!(
            stop_result.is_ok(),
            "thread should exit cleanly after Shutdown command: {stop_result:?}"
        );
    }

    #[test]
    fn test_drop_stops_thread() {
        let config = test_config(120.0);
        let (runtime, _handles) = crate::Runtime::start(config).unwrap();

        // Drop the runtime -- should not hang or panic.
        drop(runtime);
    }

    // ── Transport tests (M5.1) ───────────────────────────────────────

    #[test]
    fn test_master_transport_start_resets_position() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Let ticks accumulate for 100ms.
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Send Transport Start to reset position.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Start);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // Let a few more ticks happen.
        std::thread::sleep(std::time::Duration::from_millis(100));

        runtime.stop().unwrap();

        // Drain events and check for Transport(Start) and that beat
        // reset to 0 in subsequent ticks.
        let mut saw_start = false;
        let mut beat_after_start = None;
        while let Ok(event) = handles.events.pop() {
            match event {
                crate::RtEvent::Transport(crate::TransportEvent::Start) => {
                    saw_start = true;
                }
                crate::RtEvent::ClockTick { beat, .. }
                    if saw_start && beat_after_start.is_none() =>
                {
                    beat_after_start = Some(beat);
                }
                crate::RtEvent::ClockTick { .. } => {}
                crate::RtEvent::Transport(crate::TransportEvent::Stop) => {}
                crate::RtEvent::Transport(crate::TransportEvent::Continue) => {}
                crate::RtEvent::MidiInput { .. } => {}
                crate::RtEvent::SongPosition { .. } => {}
                crate::RtEvent::NonFatalError(_) => {}
            }
        }

        assert!(saw_start, "expected Transport(Start) event");
        // After a Start, the beat counter resets. The first tick
        // after Start should be at beat 0 (or very close to 0 due
        // to timing of when the command is processed).
        if let Some(beat) = beat_after_start {
            assert!(beat <= 1, "expected beat near 0 after Start, got {beat}");
        }
    }

    #[test]
    fn test_master_transport_stop_halts_ticks() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Let ticks accumulate. Generous window for coverage builds.
        let mut ticks_before_stop = 0u64;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(300);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if matches!(event, crate::RtEvent::ClockTick { .. }) {
                    ticks_before_stop += 1;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        // Send Transport Stop.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Stop);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // Wait for the Stop to be processed, draining while we wait.
        let mut saw_stop = false;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(200);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if matches!(
                    event,
                    crate::RtEvent::Transport(crate::TransportEvent::Stop)
                ) {
                    saw_stop = true;
                }
            }
            if saw_stop {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        // Now wait 200ms and count any new ticks (should be zero).
        let mut ticks_after_stop = 0u64;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(200);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if matches!(event, crate::RtEvent::ClockTick { .. }) {
                    ticks_after_stop += 1;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }

        assert!(saw_stop, "expected Transport(Stop) event");
        assert_eq!(
            ticks_after_stop, 0,
            "expected no ticks after Stop, got {ticks_after_stop}"
        );

        // Send Transport Continue and verify ticks resume.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Continue);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        let mut ticks_after_continue = 0u64;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if matches!(event, crate::RtEvent::ClockTick { .. }) {
                    ticks_after_continue += 1;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        runtime.stop().unwrap();

        eprintln!(
            "ticks before={ticks_before_stop}, after_stop={ticks_after_stop}, after_continue={ticks_after_continue}"
        );
        assert!(
            ticks_after_continue >= 1,
            "expected ticks after Continue, got {ticks_after_continue}"
        );
    }

    #[test]
    fn test_master_transport_continue_preserves_position() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Let ticks accumulate for 200ms to advance the beat counter.
        let mut last_beat = 0u64;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(200);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if let crate::RtEvent::ClockTick { beat, .. } = event {
                    last_beat = beat;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        // Stop.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Stop);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
        // Drain stop event.
        while handles.events.pop().is_ok() {}

        // Continue (should NOT reset beat).
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Continue);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // Collect a few ticks and check beat wasn't reset.
        let mut beat_after_continue = None;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(150);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if let crate::RtEvent::ClockTick { beat, .. } = event
                    && beat_after_continue.is_none()
                {
                    beat_after_continue = Some(beat);
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        runtime.stop().unwrap();

        let beat = beat_after_continue.expect("expected ticks after Continue");
        eprintln!("last_beat before stop = {last_beat}, beat after continue = {beat}");
        // Continue preserves position, so beat should be >= where we left off.
        // (It may have advanced a few ticks between stop command and processing.)
        assert!(
            beat >= last_beat,
            "expected beat ({beat}) >= last_beat ({last_beat}) after Continue (not Start)"
        );
    }

    // ── SPP test (M5.2) ────────────────────────────────────────────────

    #[test]
    fn test_master_spp_sets_position() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Send SPP command.
        let cmd = crate::EcsCommand::SendSongPosition { position: 96 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // Drain while running to catch the SongPosition event.
        let mut saw_spp = false;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                if let crate::RtEvent::SongPosition { position } = event {
                    assert_eq!(position, 96);
                    saw_spp = true;
                }
            }
            if saw_spp {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        runtime.stop().unwrap();

        assert!(saw_spp, "expected SongPosition event with position=96");
    }

    // ── Passthrough mode test (Task 10) ────────────────────────────────

    #[test]
    fn test_passthrough_mode_starts_and_stops() {
        let config = crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Passthrough {
                clock_input_port: String::new(),
                timeout_ns: 1_000_000_000,
                multiply: 1,
                divide: 1,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        };
        let (mut runtime, _handles) = crate::Runtime::start(config).unwrap();

        // Let the thread run briefly.
        std::thread::sleep(std::time::Duration::from_millis(100));

        let stop_result = runtime.stop();
        assert!(
            stop_result.is_ok(),
            "Runtime::stop failed in passthrough mode: {stop_result:?}"
        );
    }

    #[test]
    fn test_passthrough_mode_shutdown_command() {
        let config = crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Passthrough {
                clock_input_port: String::new(),
                timeout_ns: 1_000_000_000,
                multiply: 2,
                divide: 1,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        };
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Send Shutdown command.
        let cmd = crate::EcsCommand::Shutdown;
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        let stop_result = runtime.stop();
        assert!(
            stop_result.is_ok(),
            "thread should exit cleanly after Shutdown command in passthrough mode: {stop_result:?}"
        );
    }

    #[test]
    fn test_passthrough_mode_exercises_command_paths() {
        let config = crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Passthrough {
                clock_input_port: String::new(),
                timeout_ns: 1_000_000_000,
                multiply: 1,
                divide: 1,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        };
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // SetTempo should be silently ignored in passthrough mode.
        let cmd = crate::EcsCommand::SetTempo { bpm: 200.0 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // SendMidi should exercise the passthrough-mode SendMidi path.
        let msg = crate::MidiMessage::note_on(0, 60, 100);
        let cmd = crate::EcsCommand::SendMidi {
            output_port_index: 0,
            message: msg,
        };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // SendTransport Start.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Start);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        // SendTransport Stop.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Stop);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        // SendTransport Continue.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Continue);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        // SendSongPosition.
        let cmd = crate::EcsCommand::SendSongPosition { position: 32 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(100));

        runtime.stop().unwrap();

        // Drain all events and verify transport + SPP events appeared.
        let mut saw_start = false;
        let mut saw_stop = false;
        let mut saw_continue = false;
        let mut saw_spp = false;

        while let Ok(event) = handles.events.pop() {
            match event {
                crate::RtEvent::Transport(crate::TransportEvent::Start) => saw_start = true,
                crate::RtEvent::Transport(crate::TransportEvent::Stop) => saw_stop = true,
                crate::RtEvent::Transport(crate::TransportEvent::Continue) => {
                    saw_continue = true;
                }
                crate::RtEvent::SongPosition { position } => {
                    assert_eq!(position, 32);
                    saw_spp = true;
                }
                crate::RtEvent::ClockTick { .. } => {}
                crate::RtEvent::MidiInput { .. } => {}
                crate::RtEvent::NonFatalError(_) => {}
            }
        }

        assert!(
            saw_start,
            "expected Transport(Start) event in passthrough mode"
        );
        assert!(
            saw_stop,
            "expected Transport(Stop) event in passthrough mode"
        );
        assert!(
            saw_continue,
            "expected Transport(Continue) event in passthrough mode"
        );
        assert!(saw_spp, "expected SongPosition event in passthrough mode");
    }

    // ── Slave transport test (M5.3) ────────────────────────────────────

    #[test]
    fn test_slave_transport_via_command() {
        let config = crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Slave {
                clock_input_port: String::new(),
                timeout_ns: 1_000_000_000,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        };
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Send Transport Start.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Start);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // Wait for it to be processed.
        std::thread::sleep(std::time::Duration::from_millis(100));

        runtime.stop().unwrap();

        // Drain events.
        let mut saw_start = false;
        while let Ok(event) = handles.events.pop() {
            if matches!(
                event,
                crate::RtEvent::Transport(crate::TransportEvent::Start)
            ) {
                saw_start = true;
            }
        }

        assert!(saw_start, "expected Transport(Start) event in slave mode");
    }

    // ── Error handling tests (M5.4) ───────────────────────────────────

    #[test]
    fn test_push_event_overflow_tracking() {
        // Create a tiny queue that fills up quickly.
        let (mut rt_side, _ecs_side) = crate::queues::create_queues(4, 4);
        let mut overflows: u32 = 0;

        let tick = crate::RtEvent::ClockTick {
            subdivision: 0,
            beat: 0,
            tempo_bpm: 120.0,
            timestamp_ns: 0,
        };

        // Fill the queue.
        for _ in 0..4 {
            push_event(&mut rt_side, tick, &mut overflows);
        }
        assert_eq!(overflows, 0, "no overflows while queue has space");

        // Now pushes should fail and increment the counter.
        push_event(&mut rt_side, tick, &mut overflows);
        assert_eq!(overflows, 1);

        // Push enough to reach the threshold (already at 1, need 9 more).
        for _ in 0..9 {
            push_event(&mut rt_side, tick, &mut overflows);
        }
        // After reaching 10, the counter should reset (push_event tries
        // to push a QueueOverflow error, which may also fail, but the
        // counter resets either way).
        assert_eq!(overflows, 0, "counter should reset after threshold");
    }

    #[test]
    fn test_port_lost_send_returns_error() {
        let mut ports = crate::midi_io::MidiPorts::open_outputs(&[]).unwrap();
        // Sending to a nonexistent port should return PortNotFound.
        let result = ports.send(0, &[0xF8]);
        assert!(result.is_err());
    }

    // ── Input integration tests (M3.3) ──────────────────────────────

    #[test]
    fn test_runtime_with_no_inputs_still_works() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Drain events while running. Generous window for coverage builds.
        let mut tick_count = 0u64;
        let mut midi_input_count = 0u64;
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
        while std::time::Instant::now() < deadline {
            while let Ok(event) = handles.events.pop() {
                match event {
                    crate::RtEvent::ClockTick { .. } => tick_count += 1,
                    crate::RtEvent::MidiInput { .. } => midi_input_count += 1,
                    crate::RtEvent::Transport(crate::TransportEvent::Start) => {}
                    crate::RtEvent::Transport(crate::TransportEvent::Stop) => {}
                    crate::RtEvent::Transport(crate::TransportEvent::Continue) => {}
                    crate::RtEvent::SongPosition { .. } => {}
                    crate::RtEvent::NonFatalError(_) => {}
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }

        runtime.stop().unwrap();

        eprintln!("Ticks: {tick_count}, MidiInputs: {midi_input_count}");
        assert!(tick_count > 0, "expected clock ticks to be produced");
        assert_eq!(
            midi_input_count, 0,
            "expected no MidiInput events with no input ports"
        );
    }

    // ── Transport with send_transport enabled (coverage) ────────────

    /// Helper to build a config with `send_transport: true`.
    fn test_config_with_transport(bpm: f64) -> crate::RuntimeConfig {
        crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Master {
                tempo_bpm: bpm,
                send_transport: true,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        }
    }

    #[test]
    fn test_master_transport_with_send_enabled() {
        let config = test_config_with_transport(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Let ticks accumulate briefly.
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Send Transport Start.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Start);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        // Send Transport Stop.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Stop);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        // Send Transport Continue.
        let cmd = crate::EcsCommand::SendTransport(crate::TransportEvent::Continue);
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        // Send SPP with send_transport enabled.
        let cmd = crate::EcsCommand::SendSongPosition { position: 48 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }
        std::thread::sleep(std::time::Duration::from_millis(50));

        runtime.stop().unwrap();

        // Drain all events and verify transport events appeared.
        let mut saw_start = false;
        let mut saw_stop = false;
        let mut saw_continue = false;
        let mut saw_spp = false;

        while let Ok(event) = handles.events.pop() {
            match event {
                crate::RtEvent::Transport(crate::TransportEvent::Start) => saw_start = true,
                crate::RtEvent::Transport(crate::TransportEvent::Stop) => saw_stop = true,
                crate::RtEvent::Transport(crate::TransportEvent::Continue) => {
                    saw_continue = true;
                }
                crate::RtEvent::SongPosition { position } => {
                    assert_eq!(position, 48);
                    saw_spp = true;
                }
                crate::RtEvent::ClockTick { .. } => {}
                crate::RtEvent::MidiInput { .. } => {}
                crate::RtEvent::NonFatalError(_) => {}
            }
        }

        assert!(saw_start, "expected Transport(Start) event");
        assert!(saw_stop, "expected Transport(Stop) event");
        assert!(saw_continue, "expected Transport(Continue) event");
        assert!(saw_spp, "expected SongPosition event");
    }

    // ── Double-stop returns AlreadyStopped ──────────────────────────

    #[test]
    fn test_double_stop_returns_already_stopped() {
        let config = test_config(120.0);
        let (mut runtime, _handles) = crate::Runtime::start(config).unwrap();

        std::thread::sleep(std::time::Duration::from_millis(50));

        let first_stop = runtime.stop();
        assert!(first_stop.is_ok(), "first stop should succeed");

        let second_stop = runtime.stop();
        assert!(second_stop.is_err(), "second stop should return an error");
        match second_stop.unwrap_err() {
            crate::Error::AlreadyStopped => {} // expected
            other => panic!("expected AlreadyStopped, got: {other}"),
        }
    }

    // ── Push-event overflow emits NonFatalError (expanded) ──────────

    #[test]
    fn test_push_event_overflow_emits_error() {
        // Create a queue with capacity 2 so it fills up quickly.
        let (mut rt_side, _ecs_side) = crate::queues::create_queues(2, 4);
        let mut overflows: u32 = 0;

        let tick = crate::RtEvent::ClockTick {
            subdivision: 0,
            beat: 0,
            tempo_bpm: 120.0,
            timestamp_ns: 0,
        };

        // Fill the queue.
        for _ in 0..2 {
            push_event(&mut rt_side, tick, &mut overflows);
        }
        assert_eq!(overflows, 0, "no overflows while queue has space");

        // Push 11 more times to exceed the threshold.
        // The 10th failure should trigger the overflow reporting path.
        for _ in 0..11 {
            push_event(&mut rt_side, tick, &mut overflows);
        }

        // After the 10th overflow, the counter should reset to 0.
        // Then the 11th push fails and sets overflows to 1.
        assert_eq!(
            overflows, 1,
            "counter should have reset after threshold and then incremented once"
        );
    }

    // ── SendMidi command in master mode ─────────────────────────────

    #[test]
    fn test_send_midi_command_exercises_path() {
        let config = test_config(120.0);
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // Send a MIDI note-on via the command queue. Since there are
        // no output ports, the send will fail silently, but the code
        // path is exercised.
        let msg = crate::MidiMessage::note_on(0, 60, 100);
        let cmd = crate::EcsCommand::SendMidi {
            output_port_index: 0,
            message: msg,
        };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        std::thread::sleep(std::time::Duration::from_millis(100));
        runtime.stop().unwrap();
    }

    // ── Slave mode: SetTempo ignored, SPP, SendMidi ────────────────

    #[test]
    fn test_slave_mode_ignores_set_tempo() {
        let config = crate::RuntimeConfig {
            clock_mode: crate::ClockMode::Slave {
                clock_input_port: String::new(),
                timeout_ns: 1_000_000_000,
            },
            outputs: Vec::new(),
            inputs: Vec::new(),
            event_queue_capacity: 1024,
            command_queue_capacity: 1024,
            allow_normal_priority: true,
        };
        let (mut runtime, mut handles) = crate::Runtime::start(config).unwrap();

        // SetTempo should be silently ignored in slave mode.
        let cmd = crate::EcsCommand::SetTempo { bpm: 200.0 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // SendMidi should exercise the slave-mode SendMidi path.
        let msg = crate::MidiMessage::note_on(0, 60, 100);
        let cmd = crate::EcsCommand::SendMidi {
            output_port_index: 0,
            message: msg,
        };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        // SendSongPosition in slave mode.
        let cmd = crate::EcsCommand::SendSongPosition { position: 64 };
        while handles.commands.push(cmd).is_err() {
            std::thread::yield_now();
        }

        std::thread::sleep(std::time::Duration::from_millis(200));

        runtime.stop().unwrap();

        // Drain and verify SPP event appeared.
        let mut saw_spp = false;
        while let Ok(event) = handles.events.pop() {
            if let crate::RtEvent::SongPosition { position } = event {
                assert_eq!(position, 64);
                saw_spp = true;
            }
        }
        assert!(saw_spp, "expected SongPosition event in slave mode");
    }

    // ── Task C: push_event coverage for newly-routed paths ─────────

    #[test]
    fn test_midi_input_event_uses_push_event() {
        let (mut rt_side, _ecs_side) = crate::queues::create_queues(4, 4);
        let mut overflows: u32 = 0;

        // Fill the queue.
        let filler = crate::RtEvent::ClockTick {
            subdivision: 0,
            beat: 0,
            tempo_bpm: 120.0,
            timestamp_ns: 0,
        };
        for _ in 0..4 {
            push_event(&mut rt_side, filler, &mut overflows);
        }
        assert_eq!(overflows, 0);

        // Push a MidiInput event when the queue is full.
        let midi_event = crate::RtEvent::MidiInput {
            input_port_index: 0,
            timestamp_ns: 1000,
            message: crate::MidiMessage::note_on(0, 60, 100),
        };
        push_event(&mut rt_side, midi_event, &mut overflows);
        assert_eq!(
            overflows, 1,
            "MidiInput push to full queue should increment consecutive_overflows"
        );
    }

    #[test]
    fn test_non_fatal_error_uses_push_event() {
        let (mut rt_side, _ecs_side) = crate::queues::create_queues(4, 4);
        let mut overflows: u32 = 0;

        // Fill the queue.
        let filler = crate::RtEvent::ClockTick {
            subdivision: 0,
            beat: 0,
            tempo_bpm: 120.0,
            timestamp_ns: 0,
        };
        for _ in 0..4 {
            push_event(&mut rt_side, filler, &mut overflows);
        }
        assert_eq!(overflows, 0);

        // Push a NonFatalError event when the queue is full.
        let error_event =
            crate::RtEvent::NonFatalError(crate::RtErrorCode::PriorityElevationFailed);
        push_event(&mut rt_side, error_event, &mut overflows);
        assert_eq!(
            overflows, 1,
            "NonFatalError push to full queue should increment consecutive_overflows"
        );
    }

    #[test]
    fn test_slave_mode_clock_tick_uses_push_event() {
        let (mut rt_side, _ecs_side) = crate::queues::create_queues(4, 4);
        let mut overflows: u32 = 0;

        // Fill the queue.
        let filler = crate::RtEvent::ClockTick {
            subdivision: 0,
            beat: 0,
            tempo_bpm: 120.0,
            timestamp_ns: 0,
        };
        for _ in 0..4 {
            push_event(&mut rt_side, filler, &mut overflows);
        }
        assert_eq!(overflows, 0);

        // Push a ClockTick (the type emitted in slave mode) when full.
        let tick = crate::RtEvent::ClockTick {
            subdivision: 12,
            beat: 42,
            tempo_bpm: 118.5,
            timestamp_ns: 999_999,
        };
        push_event(&mut rt_side, tick, &mut overflows);
        assert_eq!(
            overflows, 1,
            "slave-mode ClockTick push to full queue should increment consecutive_overflows"
        );
    }
}