rsemu 0.0.4

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
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
//! Tests for the NES APU.
//!
//! These check *facts* rather than behaviour-in-general: the frame sequencer's
//! exact CPU-cycle schedule in both modes, the IRQ's timing and its two clear
//! paths, the length table, the sweep unit's mute conditions and its two
//! negation flavours, the noise LFSR's period in both modes, the DMC's rate
//! table and memory reader, and a save/load round trip. A test that only
//! asserted "something happened" would pass against a wrong table.

use alloc::string::ToString;
use alloc::vec::Vec;

use super::*;
use crate::core::space::AddressSpace;
use crate::core::state::{ChunkReader, MachineShape, Migrations, StateReader, StateWriter};
use crate::core::sync::{AtomicU32, Ordering as AtomicOrdering};
use crate::core::wire::{Wire, WireId, WireIdAllocator, WireSink};
use frame::{FrameCounter, FrameEvent};
use units::LENGTH_TABLE;

/// A machine-less APU with a given property set.
fn apu_with(props: Props) -> Apu {
    Apu::new(&props).expect("properties are valid")
}

/// A machine-less APU with default properties.
fn apu() -> Apu {
    apu_with(Props::new())
}

// ---------------------------------------------------------------------------
// Frame counter
// ---------------------------------------------------------------------------

/// What the sequencer produced over a run, as CPU cycle numbers.
#[derive(Debug, Default, PartialEq, Eq)]
struct Schedule {
    quarters: Vec<u64>,
    halves: Vec<u64>,
    irq_rises: Vec<u64>,
}

/// Whether CPU cycle `n` is a put, in the phase the frame counter's tables
/// assume: cycle 1 is a get and they alternate from there.
fn on_put(n: u64) -> bool {
    n.is_multiple_of(2)
}

/// Run `cycles` CPU cycles through `fc`, starting the cycle count at `from`.
fn record(fc: &mut FrameCounter, from: u64, cycles: u64) -> Schedule {
    let mut out = Schedule::default();
    let mut was_irq = fc.irq();
    for i in 0..cycles {
        let now = from + i;
        let event = fc.tick(now, on_put(now));
        if event.quarter {
            out.quarters.push(now - from + 1);
        }
        if event.half {
            out.halves.push(now - from + 1);
        }
        if fc.irq() && !was_irq {
            out.irq_rises.push(now - from + 1);
        }
        was_irq = fc.irq();
    }
    out
}

#[test]
fn the_four_step_sequence_clocks_on_the_documented_cpu_cycles() {
    // NESdev APU Frame Counter, mode 0, converted from APU cycles: 3728 PUT is
    // CPU 7457, 14914 GET is CPU 29828, and the wrap is CPU 29830.
    let mut fc = FrameCounter::new(Region::Ntsc);
    let s = record(&mut fc, 1, 29830);
    assert_eq!(s.quarters, [7457, 14913, 22371, 29829]);
    assert_eq!(s.halves, [14913, 29829]);
    assert_eq!(s.irq_rises, [29828]);
    assert_eq!(fc.cycle(), 0, "the sequence wraps at 29830");
}

#[test]
fn the_four_step_sequence_repeats_every_29830_cycles() {
    let mut fc = FrameCounter::new(Region::Ntsc);
    let first = record(&mut fc, 1, 29830);
    let second = record(&mut fc, 29831, 29830);
    assert_eq!(first.quarters, second.quarters);
    assert_eq!(first.halves, second.halves);
    assert_eq!(first.irq_rises, [29828]);
    // The flag is already set going into the second pass, so no rising edge.
    assert!(second.irq_rises.is_empty());
}

#[test]
fn the_pal_four_step_sequence_uses_its_own_table() {
    let mut fc = FrameCounter::new(Region::Pal);
    let s = record(&mut fc, 1, 33254);
    assert_eq!(s.quarters, [8313, 16627, 24939, 33253]);
    assert_eq!(s.halves, [16627, 33253]);
    assert_eq!(s.irq_rises, [33252]);
}

#[test]
fn the_five_step_sequence_clocks_immediately_and_never_raises_an_irq() {
    let mut fc = FrameCounter::new(Region::Ntsc);
    // Written on a get cycle, so the reset lands 4 CPU cycles later.
    fc.write(0x80, false);
    assert_eq!(fc.mode(), Mode::FiveStep);
    assert_eq!(fc.tick(1, on_put(1)), FrameEvent::NONE);
    assert_eq!(fc.tick(2, on_put(2)), FrameEvent::NONE);
    assert_eq!(fc.tick(3, on_put(3)), FrameEvent::NONE);
    assert_eq!(
        fc.tick(4, on_put(4)),
        FrameEvent::BOTH,
        "bit 7 set clocks both units when the reset takes effect"
    );
    assert_eq!(fc.cycle(), 0);

    let s = record(&mut fc, 5, 37282);
    assert_eq!(s.quarters, [7457, 14913, 22371, 37281]);
    assert_eq!(s.halves, [14913, 37281]);
    assert!(s.irq_rises.is_empty(), "mode 1 never sets the frame IRQ");
    assert!(!fc.irq());
}

#[test]
fn a_four_step_write_resets_without_clocking_anything() {
    let mut fc = FrameCounter::new(Region::Ntsc);
    // Get some distance into the sequence first.
    record(&mut fc, 1, 10_000);
    assert_ne!(fc.cycle(), 0);
    fc.write(0x00, true); // put cycle: 3 CPU cycles
    assert_eq!(fc.tick(10_001, on_put(10_001)), FrameEvent::NONE);
    assert_eq!(fc.tick(10_002, on_put(10_002)), FrameEvent::NONE);
    assert_eq!(
        fc.tick(10_003, on_put(10_003)),
        FrameEvent::NONE,
        "bit 7 clear resets the sequence without clocking"
    );
    assert_eq!(fc.cycle(), 0);
}

#[test]
fn the_4017_reset_delay_is_three_or_four_cycles_by_alignment() {
    for (write_on_put, delay) in [(true, 3u64), (false, 4u64)] {
        let mut fc = FrameCounter::new(Region::Ntsc);
        record(&mut fc, 1, 1000);
        fc.write(0x00, write_on_put);
        for i in 1..delay {
            fc.tick(1000 + i, on_put(1000 + i));
            assert!(fc.reset_pending(), "reset fired {i} cycles early");
        }
        fc.tick(1000 + delay, on_put(1000 + delay));
        assert!(!fc.reset_pending());
        assert_eq!(fc.cycle(), 0);
    }
}

#[test]
fn a_status_read_arms_the_clear_rather_than_performing_it() {
    // The clear happens inside the counter, on its next get cycle, and a set
    // signal on that cycle wins. So a read on the last cycle before the flag is
    // set leaves it set, and one two cycles later does not.
    let mut fc = FrameCounter::new(Region::Ntsc);
    // Cycle 29828 is where the flag is first set, and it is set again on 29829
    // and 29830.
    record(&mut fc, 1, 29828);
    assert!(fc.irq());
    assert!(fc.read_irq(false));
    assert!(fc.irq(), "the read itself clears nothing");
    // 29829 is a put, so the armed clear waits; and the sequencer sets the flag
    // again on that cycle anyway.
    fc.tick(29829, on_put(29829));
    assert!(fc.irq());
    // Past the last set, the next get applies it.
    record(&mut fc, 29830, 4);
    assert!(fc.read_irq(false));
    record(&mut fc, 29834, 2);
    assert!(!fc.irq(), "the armed clear landed on a get cycle");
}

#[test]
fn a_debug_read_never_clears_the_frame_irq() {
    let mut fc = FrameCounter::new(Region::Ntsc);
    record(&mut fc, 1, 29830);
    assert!(fc.irq());
    assert!(fc.read_irq(true));
    assert!(fc.irq(), "MemAttrs::debug must have no side effect");
}

#[test]
fn setting_the_inhibit_bit_clears_the_frame_irq_and_gates_the_line() {
    let mut fc = FrameCounter::new(Region::Ntsc);
    record(&mut fc, 1, 29830);
    assert!(fc.irq());
    fc.write(0x40, false);
    assert!(!fc.irq(), "bit 6 clears the flag immediately");
    assert!(fc.inhibited());

    // What the inhibit bit does *not* do is stop the flag being raised. It is
    // still set on the first two of the three cycles the sequencer asserts it,
    // and a program reading `$4015` there sees it; the third cycle is where the
    // inhibit finally wins, and the IRQ *line* is gated throughout.
    let s = record(&mut fc, 29831, 4 + 29830);
    assert_eq!(
        s.irq_rises.len(),
        1,
        "raised once, on the first of the three set cycles"
    );
    assert!(!fc.irq(), "and clear again by the third");
}

// ---------------------------------------------------------------------------
// Length counters
// ---------------------------------------------------------------------------

#[test]
fn the_length_table_matches_the_documented_values() {
    // NESdev APU Length Counter. Written out rather than computed so that a
    // transcription slip is visible here rather than only as a wrong note.
    assert_eq!(
        LENGTH_TABLE,
        [
            10, 254, 20, 2, 40, 4, 80, 6, 160, 8, 60, 10, 14, 12, 26, 14, 12, 16, 24, 18, 48, 20,
            96, 22, 192, 24, 72, 26, 16, 28, 32, 30
        ]
    );
}

#[test]
fn the_length_table_has_the_documented_structure() {
    // The wiki's second presentation of the same table: with index bit 0 set
    // the remaining bits select a linear length, except for index 1.
    for i in (3..32usize).step_by(2) {
        assert_eq!(
            usize::from(LENGTH_TABLE[i]),
            i - 1,
            "odd index {i} should be the linear length {}",
            i - 1
        );
    }
    assert_eq!(LENGTH_TABLE[1], 254);
    // Even indices are note lengths on a base of 10 (bit 4 clear) or 12 (set).
    assert_eq!(LENGTH_TABLE[0x00], 10);
    assert_eq!(LENGTH_TABLE[0x10], 12);
    assert_eq!(LENGTH_TABLE[0x18], 192);
    assert_eq!(LENGTH_TABLE[0x08], 160);
}

#[test]
fn a_disabled_channel_cannot_load_its_length_counter() {
    let apu = apu();
    // Pulse 1 is disabled at power-up, so the load is discarded.
    apu.write(0x03, 0x08);
    assert_eq!(
        apu.read(0x15, 0) & 0x01,
        0,
        "load while disabled is ignored"
    );
    apu.write(0x15, 0x01);
    apu.write(0x03, 0x08);
    assert_eq!(apu.read(0x15, 0) & 0x01, 0x01);
    // Clearing the enable bit forces the counter to zero and loses the value.
    apu.write(0x15, 0x00);
    assert_eq!(apu.read(0x15, 0) & 0x01, 0);
    apu.write(0x15, 0x01);
    assert_eq!(
        apu.read(0x15, 0) & 0x01,
        0,
        "enabling does not restore a length"
    );
}

#[test]
fn a_halted_length_counter_does_not_count_down() {
    let apu = apu();
    apu.write(0x15, 0x01);
    apu.write(0x00, 0x30); // halt set (bit 5), constant volume
    apu.write(0x03, 0x08); // length index 1 -> 254
    // Two full sequences is four half-frame clocks; nothing should move.
    apu.advance(2 * 29830);
    assert_eq!(apu.read(0x15, 0) & 0x01, 0x01);

    // Clearing the halt bit lets it run out.
    apu.write(0x15, 0x02);
    apu.write(0x04, 0x10); // pulse 2: halt clear
    apu.write(0x07, 0x18); // length index 3 -> 2
    apu.advance(2 * 29830);
    assert_eq!(
        apu.read(0x15, 0) & 0x02,
        0,
        "two half frames expire a length of 2"
    );
}

// ---------------------------------------------------------------------------
// Sweep
// ---------------------------------------------------------------------------

#[test]
fn a_period_below_eight_mutes_the_pulse_channel() {
    let sweep = pulse::Sweep::new(true);
    for period in 0..8u16 {
        assert!(sweep.muting(period), "period {period} must mute");
    }
    assert!(!sweep.muting(8));
}

#[test]
fn a_target_period_above_7ff_mutes_even_with_the_sweep_disabled() {
    // Negate clear, shift 0, current period >= $400: the target is twice the
    // period, which overflows and mutes. This is the case the wiki calls out as
    // the reason the bottom octave of the pulse channels is unused.
    let sweep = pulse::Sweep::new(true);
    assert!(!sweep.muting(0x3FF));
    assert!(sweep.muting(0x400));
    assert_eq!(sweep.target(0x400), 0x800);
}

#[test]
fn pulse_one_negates_with_the_ones_complement_and_pulse_two_with_the_twos() {
    // The wiki's own example: making a change amount of 20 negative gives -21
    // on pulse 1 and -20 on pulse 2.
    let mut one = pulse::Sweep::new(true);
    let mut two = pulse::Sweep::new(false);
    // Shift 0 makes the change amount equal to the period; negate set.
    one.write(0x88);
    two.write(0x88);
    assert_eq!(one.target(20), 0, "20 - 21 clamps to zero on pulse 1");
    assert_eq!(two.target(20), 0, "20 - 20 is zero on pulse 2");

    // A shift of 1 separates them: change = 10.
    one.write(0x89);
    two.write(0x89);
    assert_eq!(one.target(20), 20 - 10 - 1);
    assert_eq!(two.target(20), 20 - 10);
}

#[test]
fn a_disabled_sweep_never_updates_the_period() {
    let mut sweep = pulse::Sweep::new(false);
    sweep.write(0x00); // disabled, shift 0
    let mut period = 0x100u16;
    for _ in 0..16 {
        sweep.clock(&mut period);
    }
    assert_eq!(period, 0x100);
}

#[test]
fn an_enabled_sweep_updates_the_period_on_its_divider_period() {
    let mut sweep = pulse::Sweep::new(false);
    // Enabled, P = 0 (period 1 half frame), negate clear, shift 1.
    sweep.write(0x81);
    let mut period = 0x100u16;
    sweep.clock(&mut period); // reload pass: divider was 0, so it updates
    assert_eq!(period, 0x180);
}

// ---------------------------------------------------------------------------
// Triangle
// ---------------------------------------------------------------------------

#[test]
fn the_linear_counter_reload_flag_persists_while_the_control_flag_is_set() {
    let apu = apu();
    apu.write(0x15, 0x04);
    apu.write(0x08, 0xFF); // control set, reload value 127
    apu.write(0x0B, 0x08); // sets the reload flag
    // Every quarter frame reloads the counter while control stays set.
    apu.advance(29830);
    apu.advance(29830);
    // Clearing the control flag lets the next clock consume the reload flag and
    // the counter then counts down.
    apu.write(0x08, 0x02); // control clear, reload value 2
    apu.advance(29830 * 2);
    // Four quarter frames per sequence: reload to 2, then 1, 0, 0 ... the
    // channel is silent, which is what the linear counter is for.
    assert_eq!(
        apu.read(0x15, 0) & 0x04,
        0x04,
        "the length counter is separate"
    );
}

#[test]
fn the_triangle_holds_its_output_when_ultrasonic_halt_is_enabled() {
    let props = Props::new()
        .with("halt-ultrasonic", true)
        .with("sample-buffer", 0u64);
    let apu = apu_with(props);
    apu.write(0x15, 0x04);
    apu.write(0x08, 0xFF);
    apu.write(0x0A, 0x00);
    apu.write(0x0B, 0x08); // period 0: ultrasonic
    apu.advance(1000);
    let held = apu.output();
    apu.advance(1000);
    assert_eq!(apu.output(), held, "an ultrasonic triangle is frozen");
}

// ---------------------------------------------------------------------------
// Noise
// ---------------------------------------------------------------------------

#[test]
fn the_noise_period_table_matches_the_documented_values() {
    assert_eq!(
        noise::periods(Region::Ntsc),
        [
            4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068
        ]
    );
    assert_eq!(
        noise::periods(Region::Pal),
        [
            4, 8, 14, 30, 60, 88, 118, 148, 188, 236, 354, 472, 708, 944, 1890, 3778
        ]
    );
    // Every entry is even, because the timer is clocked once per APU cycle.
    for period in noise::periods(Region::Ntsc) {
        assert_eq!(period % 2, 0);
    }
}

/// Shift the LFSR until it returns to its starting value, up to `limit` steps.
fn lfsr_period(mode: u8, limit: u32) -> u32 {
    let mut n = noise::Noise::new(Region::Ntsc);
    n.write_period(mode); // period index 0: one shift every two APU cycles
    let start = n.shift();
    for step in 1..=limit {
        n.tick_timer();
        n.tick_timer();
        if n.shift() == start {
            return step;
        }
    }
    0
}

#[test]
fn the_noise_lfsr_has_the_documented_periods_in_both_modes() {
    // 32767 steps with the mode flag clear (tap on bit 1), and 93 with it set
    // (tap on bit 6) from the power-on value of 1.
    assert_eq!(lfsr_period(0x00, 40_000), 32767);
    assert_eq!(lfsr_period(0x80, 40_000), 93);
}

#[test]
fn the_noise_lfsr_shifts_right_with_feedback_into_bit_14() {
    let mut n = noise::Noise::new(Region::Ntsc);
    assert_eq!(n.shift(), 1, "power-on value");
    n.write_period(0x00);
    n.tick_timer();
    // 1: bit 0 is 1, bit 1 is 0, feedback 1; shift right gives 0, then bit 14.
    assert_eq!(n.shift(), 0x4000);
    n.tick_timer();
    n.tick_timer();
    assert_eq!(n.shift(), 0x2000);
}

// ---------------------------------------------------------------------------
// DMC
// ---------------------------------------------------------------------------

#[test]
fn the_dmc_rate_table_matches_the_documented_values() {
    assert_eq!(
        dmc::rates(Region::Ntsc),
        [
            428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54
        ]
    );
    assert_eq!(
        dmc::rates(Region::Pal),
        [
            398, 354, 316, 298, 276, 236, 210, 198, 176, 148, 132, 118, 98, 78, 66, 50
        ]
    );
    for rate in dmc::rates(Region::Ntsc) {
        assert_eq!(rate % 2, 0, "rates are even: the timer runs at APU rate");
    }
}

#[test]
fn enabling_the_dmc_schedules_a_load_fetch_from_the_sample_address() {
    let apu = apu();
    apu.write(0x12, 0x01); // $C000 + 1 * 64
    apu.write(0x13, 0x00); // 0 * 16 + 1 = one byte
    assert!(apu.dma_request().is_none());
    apu.write(0x15, 0x10);
    let request = apu.dma_request().expect("a load fetch is scheduled");
    assert_eq!(request.kind, DmaKind::Load);
    assert_eq!(request.addr, 0xC040);
    assert_eq!(
        apu.read(0x15, 0) & 0x10,
        0x10,
        "bytes remaining is non-zero"
    );

    assert!(apu.dma_complete(request.serial, 0x55));
    assert!(apu.dma_request().is_none(), "one byte, one fetch");
    assert_eq!(apu.read(0x15, 0) & 0x10, 0, "the sample is exhausted");
}

#[test]
fn a_4015_enable_holds_the_next_fetch_off_for_three_cycles() {
    // "It just doesn't run until the DMA is enabled, 2 or 3 cycles after a
    // write to $4015" - AccuracyCoin's "Delta Modulation Channel" subtests L,
    // M and N, which write $4015 two, one and zero cycles before the timer
    // reaches zero and expect the fetch delayed by one, two and three.
    let apu = apu();
    apu.write(0x12, 0x00);
    apu.write(0x13, 0x00); // one byte
    apu.advance(100);
    apu.write(0x15, 0x10);
    let request = apu.dma_request().expect("a load fetch is scheduled");
    assert_eq!(
        request.not_before,
        request.at + 3,
        "the enable latches three cycles after the write"
    );
    // A write that does not start the channel does not move the latch: it is
    // the same value going back into the same flip-flop.
    let armed = request.not_before;
    apu.advance(4);
    apu.write(0x15, 0x10);
    assert_eq!(apu.dma_request().unwrap().not_before, armed);
}

#[test]
fn two_fetches_cannot_be_back_to_back() {
    // "The DMA cannot occur within 2 cycles of a previous DMC DMA"
    // (AccuracyCoin, "Implicit DMA Abort" subtest 4).
    let apu = apu();
    apu.write(0x12, 0x00);
    apu.write(0x13, 0x0f); // long enough to keep asking
    apu.advance(100);
    apu.write(0x15, 0x10);
    let first = apu.dma_request().expect("a load fetch is scheduled");
    assert!(apu.dma_complete(first.serial, 0x55));
    // Run the output unit until the buffer empties and the reload is asked for.
    apu.advance(8 * 428);
    let next = apu.dma_request().expect("the reader wants the next byte");
    assert!(
        next.not_before > first.at,
        "the fetch that follows one cannot halt on top of it"
    );
}

#[test]
fn the_memory_reader_wraps_from_ffff_to_8000() {
    let apu = apu();
    apu.write(0x12, 0xFF); // $C000 + 255 * 64 = $FFC0
    apu.write(0x13, 0x0F); // 15 * 16 + 1 = 241 bytes
    apu.write(0x15, 0x10);
    let mut addrs = Vec::new();
    for byte in 0..80u8 {
        let request = apu.dma_request().expect("the reader keeps asking");
        addrs.push(request.addr);
        assert!(apu.dma_complete(request.serial, byte));
        // Emptying the buffer is what schedules the next fetch, so run the
        // output unit until it does.
        apu.advance(8 * 428);
    }
    assert_eq!(addrs[0], 0xFFC0);
    assert_eq!(addrs[63], 0xFFFF);
    assert_eq!(addrs[64], 0x8000, "the address counter wraps to $8000");
}

#[test]
fn a_non_looping_sample_raises_the_dmc_irq_when_its_last_byte_is_read() {
    let apu = apu();
    apu.write(0x10, 0x80); // IRQ enabled, no loop, rate 0
    apu.write(0x12, 0x00);
    apu.write(0x13, 0x00); // one byte
    apu.write(0x15, 0x10);
    let request = apu.dma_request().unwrap();
    assert!(apu.dma_complete(request.serial, 0x00));
    assert_eq!(apu.read(0x15, 0) & 0x80, 0x80, "the DMC IRQ flag is set");
    // The line the core samples follows the flag by one CPU cycle.
    apu.advance(1);
    assert_eq!(apu.irq_level(), Level::High);
    // A $4015 read does not clear it; only a $4015 write or $4010 bit 7 does.
    assert_eq!(apu.read(0x15, 0) & 0x80, 0x80);
    apu.write(0x15, 0x00);
    assert_eq!(apu.read(0x15, 0) & 0x80, 0);
    apu.advance(1);
    assert_eq!(apu.irq_level(), Level::Low);
}

#[test]
fn clearing_the_dmc_irq_enable_bit_clears_the_flag() {
    let apu = apu();
    apu.write(0x10, 0x80);
    apu.write(0x13, 0x00);
    apu.write(0x15, 0x10);
    let request = apu.dma_request().unwrap();
    apu.dma_complete(request.serial, 0x00);
    assert_eq!(apu.read(0x15, 0) & 0x80, 0x80);
    apu.write(0x10, 0x00);
    assert_eq!(apu.read(0x15, 0) & 0x80, 0);
}

#[test]
fn a_looping_sample_restarts_instead_of_raising_an_irq() {
    let apu = apu();
    apu.write(0x10, 0xC0); // IRQ enabled and loop set: loop wins
    apu.write(0x12, 0x00);
    apu.write(0x13, 0x00);
    apu.write(0x15, 0x10);
    let request = apu.dma_request().unwrap();
    assert!(apu.dma_complete(request.serial, 0xFF));
    assert_eq!(apu.read(0x15, 0) & 0x80, 0, "no IRQ on a looping sample");
    assert_eq!(apu.read(0x15, 0) & 0x10, 0x10, "the reader restarted");
}

#[test]
fn stopping_playback_leaves_a_scheduled_fetch_alone() {
    // A `$4015` write that stops playback does **not** cancel a fetch that is
    // already scheduled: the CPU has been told to halt and the DMA runs its
    // full length. AccuracyCoin's "Explicit DMA Abort" measures exactly that —
    // a stop landing while the fetch is in flight still costs the core three or
    // four cycles, and only a stop landing in the APU cycle *before* the fetch
    // would have been scheduled produces the one-cycle aborted DMA.
    let apu = apu();
    apu.write(0x13, 0x00);
    apu.write(0x15, 0x10);
    let request = apu.dma_request().unwrap();
    assert!(apu.dma_is_pending(request.serial));
    apu.write(0x15, 0x00);
    assert!(
        apu.dma_is_pending(request.serial),
        "the fetch still happens"
    );
    assert!(apu.dma_complete(request.serial, 0x42));
    assert!(apu.dma_request().is_none(), "and nothing follows it");
}

#[test]
fn the_output_unit_moves_the_level_by_two_per_bit() {
    let apu = apu();
    apu.write(0x11, 0x40); // direct load: level 64
    apu.write(0x10, 0x0F); // fastest rate, no IRQ, no loop
    apu.write(0x13, 0x00);
    apu.write(0x15, 0x10);
    let request = apu.dma_request().unwrap();
    // 0xFF is eight 1 bits: +2 each, so 64 -> 80.
    assert!(apu.dma_complete(request.serial, 0xFF));
    // Rate $F is 54 CPU cycles per bit; the first clock loads the shifter.
    apu.advance(54 * 9);
    assert_eq!(apu.read(0x11, 0x5a), 0x5a, "$4011 is write-only");
    assert!(apu.output() > 0);
}

#[test]
fn the_dmc_level_saturates_rather_than_wrapping() {
    let apu = apu();
    apu.write(0x11, 0x7F);
    assert_eq!(apu.dmc_output(), 0x7F);
    apu.write(0x11, 0xFF);
    assert_eq!(apu.dmc_output(), 0x7F, "only seven bits are loadable");
}

// ---------------------------------------------------------------------------
// $4015 and open bus
// ---------------------------------------------------------------------------

#[test]
fn bit_five_of_the_status_register_is_open_bus() {
    let apu = apu();
    assert_eq!(apu.read(0x15, 0xFF) & 0x20, 0x20);
    assert_eq!(apu.read(0x15, 0x00) & 0x20, 0x00);
    // And bit 5 is the *only* bit the open bus contributes.
    assert_eq!(apu.read(0x15, 0xFF), 0x20);
}

#[test]
fn the_write_only_registers_read_back_as_open_bus() {
    let apu = apu();
    for index in [0x00u8, 0x03, 0x08, 0x0F, 0x10, 0x13, 0x17] {
        assert_eq!(apu.read(index, 0xA5), 0xA5, "register {index:#04x}");
    }
}

#[test]
fn a_debug_status_read_reports_the_frame_irq_without_clearing_it() {
    let apu = apu();
    // 29831 rather than 29830: the flag is (re)set on cycles 29828, 29829 and
    // 29830, and a read on any of those returns 1 *without* clearing.
    apu.advance(29831);
    assert_eq!(apu.peek(0x15, 0) & 0x40, 0x40);
    assert_eq!(
        apu.peek(0x15, 0) & 0x40,
        0x40,
        "peeking twice still shows it"
    );
    assert_eq!(apu.read(0x15, 0) & 0x40, 0x40);
    // The read arms the clear; the frame counter applies it on its next get
    // cycle, so an immediate second read still sees the flag.
    assert_eq!(
        apu.read(0x15, 0) & 0x40,
        0x40,
        "the read itself clears nothing"
    );
    apu.advance(2);
    assert_eq!(apu.read(0x15, 0) & 0x40, 0x00, "and then it is gone");
}

#[test]
fn the_frame_irq_drives_the_irq_line_and_a_status_read_drops_it() {
    let apu = apu();
    assert_eq!(apu.irq_level(), Level::Low);
    // 29832 rather than 29831: the line the core samples is the level the
    // previous cycle left, so it follows the flag by one CPU cycle.
    apu.advance(29832);
    assert_eq!(apu.irq_level(), Level::High);
    apu.read(0x15, 0);
    apu.advance(3);
    assert_eq!(apu.irq_level(), Level::Low);
}

// ---------------------------------------------------------------------------
// Wiring
// ---------------------------------------------------------------------------

/// A wire sink that counts the levels it is told about.
#[derive(Debug, Default)]
struct Counter {
    highs: AtomicU32,
    lows: AtomicU32,
}

impl WireSink for Counter {
    fn set_level(&self, _src: WireId, _line: u32, level: Level) {
        match level {
            Level::High => self.highs.fetch_add(1, AtomicOrdering::SeqCst),
            Level::Low => self.lows.fetch_add(1, AtomicOrdering::SeqCst),
        };
    }
}

#[test]
fn the_apu_drives_its_irq_wire_on_both_edges() {
    let ids = WireIdAllocator::new();
    let id = ids.alloc();
    let sink = Arc::new(Counter::default());
    let wire = Arc::new(Wire::builder().source(id).sink(sink.clone(), 0).build());
    let apu = apu();
    apu.connect_irq(WireSource::new(Arc::clone(&wire), id));

    assert_eq!(sink.highs.load(AtomicOrdering::SeqCst), 0);
    apu.advance(29832);
    assert_eq!(sink.highs.load(AtomicOrdering::SeqCst), 1);
    apu.read(0x15, 0);
    apu.advance(3);
    assert_eq!(sink.lows.load(AtomicOrdering::SeqCst), 1);
}

// ---------------------------------------------------------------------------
// Clock domain
// ---------------------------------------------------------------------------

#[test]
fn the_apu_follows_the_clock_domain_it_is_attached_to() {
    use crate::core::clock::{ClockForest, Rational};

    // The NES topology: one crystal, CPU = master / 12 (`ROADMAP.md` §4.2).
    let mut forest = ClockForest::new();
    let master = forest
        .add_oscillator("master", Rational::new(236_250_000, 11).unwrap())
        .unwrap();
    let cpu = forest.add_domain("cpu", master, 1, 12).unwrap();

    let apu = apu();
    apu.attach_clock(cpu);
    assert_eq!(apu.clock_domain(), Some(cpu));

    forest.advance_domain(cpu, 29_831).unwrap();
    apu.advance_to(forest.ticks(cpu).unwrap());
    assert_eq!(apu.ticks(), 29_831);
    assert_eq!(apu.irq_level(), Level::High);

    // advance_to is idempotent, which is what makes it safe to call before
    // every access.
    apu.advance_to(forest.ticks(cpu).unwrap());
    assert_eq!(apu.ticks(), 29_831);
}

// ---------------------------------------------------------------------------
// Memory-mapped access
// ---------------------------------------------------------------------------

#[test]
fn the_regions_cover_exactly_the_registers_the_apu_decodes() {
    let apu = apu();
    let regions = apu.regions();
    let shapes: Vec<(u64, u64)> = regions.iter().map(|(at, r)| (*at, r.len())).collect();
    assert_eq!(
        shapes,
        [(0x00, 0x14), (0x15, 1), (0x17, 1)],
        "$4014 and $4016 belong to other devices and must not be covered"
    );
}

#[test]
fn an_mmio_write_reaches_the_register_and_a_debug_write_does_not() {
    let apu = apu();
    let regions = apu.regions();
    let status = regions
        .iter()
        .find(|(at, _)| *at == 0x15)
        .map(|(_, r)| r)
        .expect("the status region exists");
    let ops = match status.kind() {
        crate::core::space::RegionKind::Io(ops) => Arc::clone(ops),
        _ => panic!("the status region is an I/O region"),
    };

    ops.write(0, &[0x0F], MemAttrs::DEFAULT).unwrap();
    apu.write(0x03, 0x08);
    let mut byte = [0u8];
    ops.read(0, &mut byte, MemAttrs::DEFAULT).unwrap();
    assert_eq!(byte[0] & 0x01, 0x01, "the enable write went through");

    ops.write(0, &[0x00], MemAttrs::DEBUG).unwrap();
    ops.read(0, &mut byte, MemAttrs::DEFAULT).unwrap();
    assert_eq!(byte[0] & 0x01, 0x01, "a debug write changes nothing");
}

#[test]
fn a_multi_byte_access_is_rejected() {
    let apu = apu();
    let regions = apu.regions();
    let (_, region) = &regions[0];
    let ops = match region.kind() {
        crate::core::space::RegionKind::Io(ops) => Arc::clone(ops),
        _ => panic!("channels is an I/O region"),
    };
    let mut buf = [0u8; 2];
    assert!(ops.read(0, &mut buf, MemAttrs::DEFAULT).is_err());
    assert!(ops.write(0, &[0, 0], MemAttrs::DEFAULT).is_err());
}

// ---------------------------------------------------------------------------
// Mixer
// ---------------------------------------------------------------------------

#[test]
fn silence_mixes_to_zero_and_the_loudest_combination_fits_a_u16() {
    assert_eq!(mixer::mix(0, 0, 0, 0, 0), 0);
    let loudest = mixer::mix(15, 15, 15, 15, 127);
    assert_eq!(
        loudest, 65534,
        "the tables are scaled so a sample cannot clip"
    );
    assert!(loudest < u16::MAX);
}

#[test]
fn the_mixer_tables_are_monotonic() {
    for i in 1..mixer::PULSE_TABLE.len() {
        assert!(mixer::PULSE_TABLE[i] > mixer::PULSE_TABLE[i - 1]);
    }
    for i in 1..mixer::TND_TABLE.len() {
        assert!(mixer::TND_TABLE[i] > mixer::TND_TABLE[i - 1]);
    }
}

#[test]
fn samples_are_produced_once_per_apu_cycle() {
    let apu = apu_with(Props::new().with("sample-buffer", 4096u64));
    apu.advance(1000);
    let mut out = Vec::new();
    apu.take_samples(&mut out);
    assert_eq!(out.len(), 500, "one sample per two CPU cycles");
    let mut again = Vec::new();
    apu.take_samples(&mut again);
    assert!(again.is_empty(), "draining consumes the ring");
}

#[test]
fn a_zero_capacity_ring_produces_nothing() {
    let apu = apu_with(Props::new().with("sample-buffer", 0u64));
    apu.advance(1000);
    let mut out = Vec::new();
    apu.take_samples(&mut out);
    assert!(out.is_empty());
    assert_eq!(apu.samples_dropped(), 0);
}

#[test]
fn an_undrained_ring_drops_the_oldest_samples_and_says_so() {
    let apu = apu_with(Props::new().with("sample-buffer", 16u64));
    apu.advance(100);
    assert_eq!(apu.samples_dropped(), 50 - 16);
    let mut out = Vec::new();
    apu.take_samples(&mut out);
    assert_eq!(out.len(), 16);
}

// ---------------------------------------------------------------------------
// Properties, class, reset
// ---------------------------------------------------------------------------

#[test]
fn an_unknown_property_is_rejected_and_a_bad_region_names_the_options() {
    let bad = Apu::new(&Props::new().with("reigon", "ntsc"));
    assert!(
        bad.is_err(),
        "a typo'd property must not be silently ignored"
    );

    let err = Apu::new(&Props::new().with("region", "secam")).unwrap_err();
    let text = alloc::format!("{err}");
    assert!(text.contains("ntsc"), "{text}");
    assert!(text.contains("pal"), "{text}");
    assert!(text.contains("dendy"), "{text}");
}

#[test]
fn the_class_registers_and_constructs() {
    let mut registry = Registry::new();
    register(&mut registry).unwrap();
    assert!(registry.get("nes.apu").is_some());
    let device = registry.create("nes.apu", &Props::new()).unwrap();
    assert_eq!(device.class().name, "nes.apu");
    assert!(
        register(&mut registry).is_err(),
        "no duplicate registration"
    );
}

#[test]
fn a_cold_reset_returns_every_register_to_its_power_on_value() {
    let apu = apu();
    apu.write(0x15, 0x1F);
    apu.write(0x03, 0x08);
    apu.advance(29830);
    assert_ne!(apu.read(0x15, 0) & 0x0F, 0);
    apu.reset(ResetKind::Cold);
    assert_eq!(apu.read(0x15, 0), 0x00);
    assert_eq!(apu.ticks(), 0);
    assert_eq!(apu.irq_level(), Level::Low);
}

#[test]
fn a_warm_reset_silences_the_channels_but_keeps_4017() {
    let apu = apu();
    apu.write(0x17, 0x80); // five-step mode
    apu.advance(10);
    apu.write(0x15, 0x0F);
    apu.write(0x03, 0x08);
    apu.write(0x11, 0x7F);
    apu.reset(ResetKind::Warm);
    assert_eq!(apu.read(0x15, 0) & 0x1F, 0, "a reset writes $00 to $4015");
    assert_eq!(apu.frame_mode(), Mode::FiveStep, "$4017 is unchanged");
    assert_eq!(apu.dmc_output(), 1, "the DMC level is ANDed with 1");
}

// ---------------------------------------------------------------------------
// Snapshot
// ---------------------------------------------------------------------------

/// Write one device's chunk and return the whole snapshot.
fn snapshot(apu: &Apu) -> Vec<u8> {
    let mut shape = MachineShape::new();
    shape.add_device("apu", "nes.apu").unwrap();
    let mut writer = StateWriter::new(shape);
    {
        let mut chunk = writer.chunk("apu", "nes.apu", APU_CLASS.version).unwrap();
        apu.save(&mut chunk).unwrap();
    }
    writer.to_vec().unwrap()
}

/// FNV-1a over a byte slice: a state hash for the round-trip assertion.
fn hash(bytes: &[u8]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in bytes {
        h ^= u64::from(*b);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// Put an APU into a state that touches every unit.
fn exercised() -> Apu {
    let apu = apu();
    apu.write(0x00, 0xBF); // pulse 1: duty 2, halt, constant volume 15
    apu.write(0x01, 0x8A); // sweep enabled
    apu.write(0x02, 0x34);
    apu.write(0x04, 0x76); // pulse 2
    apu.write(0x05, 0x99);
    apu.write(0x06, 0x21);
    apu.write(0x08, 0xC3); // triangle linear counter
    apu.write(0x0A, 0x55);
    apu.write(0x0C, 0x1A); // noise envelope
    apu.write(0x0E, 0x87); // short mode, period 7
    apu.write(0x10, 0x4B); // DMC: loop, rate $B
    apu.write(0x11, 0x39);
    apu.write(0x12, 0x20);
    apu.write(0x13, 0x03);
    apu.write(0x15, 0x1F);
    apu.write(0x03, 0x28);
    apu.write(0x07, 0x51);
    apu.write(0x0B, 0x93);
    apu.write(0x0F, 0xC8);
    apu.write(0x17, 0x00);
    apu.advance(20_000);
    apu
}

#[test]
fn save_and_load_round_trip_to_an_identical_state_hash() {
    let original = exercised();
    let bytes = snapshot(&original);

    let restored = apu();
    let reader = StateReader::new(&bytes).unwrap();
    let (class, version, data) = reader.load_raw("apu").unwrap();
    assert_eq!(class, "nes.apu");
    assert_eq!(version, APU_CLASS.version);
    let mut chunk = ChunkReader::new(data);
    restored.load(&mut chunk).unwrap();
    chunk
        .end()
        .expect("load must consume every byte save wrote");

    assert_eq!(
        hash(&snapshot(&restored)),
        hash(&bytes),
        "a restored APU must serialize identically"
    );
}

#[test]
fn a_restored_apu_continues_identically() {
    let original = exercised();
    let bytes = snapshot(&original);
    let restored = apu();
    let reader = StateReader::new(&bytes).unwrap();
    let (_, _, data) = reader.load_raw("apu").unwrap();
    restored.load(&mut ChunkReader::new(data)).unwrap();

    original.advance(50_000);
    restored.advance(50_000);
    assert_eq!(
        hash(&snapshot(&original)),
        hash(&snapshot(&restored)),
        "the two must stay in lockstep after the restore"
    );
    assert_eq!(original.read(0x15, 0), restored.read(0x15, 0));
    assert_eq!(original.output(), restored.output());
}

#[test]
fn a_pending_dmc_fetch_survives_a_round_trip() {
    let apu = apu();
    apu.write(0x13, 0x02);
    apu.write(0x15, 0x10);
    let request = apu.dma_request().unwrap();

    let bytes = snapshot(&apu);
    let restored = self::apu();
    let reader = StateReader::new(&bytes).unwrap();
    let (_, _, data) = reader.load_raw("apu").unwrap();
    restored.load(&mut ChunkReader::new(data)).unwrap();

    assert_eq!(restored.dma_request(), Some(request));
    assert!(restored.dma_complete(request.serial, 0x11));
}

// ---------------------------------------------------------------------------
// Regions
//
// Sources: NESdev APU Frame Counter (the NTSC and PAL step tables), APU Noise
// and APU DMC (the two period tables each lists), and the cycle reference
// chart (https://www.nesdev.org/wiki/Cycle_reference_chart) for the CPU
// dividers and the three frame-counter rates.
// ---------------------------------------------------------------------------

/// The three regions, for tests that must cover all of them.
const REGIONS: [Region; 3] = [Region::Ntsc, Region::Pal, Region::Dendy];

#[test]
fn each_region_runs_its_own_four_step_schedule() {
    let expected = [
        (
            Region::Ntsc,
            29830u64,
            [7457u32, 14913, 22371, 29829],
            [14913u32, 29829],
            29828u32,
        ),
        (
            Region::Pal,
            33254,
            [8313, 16627, 24939, 33253],
            [16627, 33253],
            33252,
        ),
        // Dendy runs the NTSC sequence; only the rate it is clocked at differs.
        (
            Region::Dendy,
            29830,
            [7457, 14913, 22371, 29829],
            [14913, 29829],
            29828,
        ),
    ];
    for (region, wrap, quarters, halves, irq) in expected {
        let mut fc = FrameCounter::new(region);
        assert_eq!(fc.tv_region(), region);
        let s = record(&mut fc, 1, wrap);
        assert_eq!(s.quarters, quarters.map(u64::from), "{region}");
        assert_eq!(s.halves, halves.map(u64::from), "{region}");
        assert_eq!(s.irq_rises, [u64::from(irq)], "{region}");
        assert_eq!(fc.cycle(), 0, "{region} wraps at {wrap}");
    }
}

#[test]
fn each_region_runs_its_own_five_step_schedule() {
    for region in REGIONS {
        let t = region.five_step();
        let mut fc = FrameCounter::new(region);
        fc.write(0x80, true);
        // The write's 3-cycle delay, whose last cycle clocks both units.
        record(&mut fc, 1, 3);
        let s = record(&mut fc, 4, u64::from(t[5]));
        assert_eq!(
            s.quarters,
            [
                u64::from(t[0]),
                u64::from(t[1]),
                u64::from(t[2]),
                u64::from(t[4])
            ],
            "{region}"
        );
        assert_eq!(s.halves, [u64::from(t[1]), u64::from(t[4])], "{region}");
        assert!(s.irq_rises.is_empty(), "{region}: mode 1 never raises IRQ");
    }
    assert_eq!(
        Region::Pal.five_step(),
        [8313, 16627, 24939, 33253, 41565, 41566]
    );
    assert_eq!(Region::Dendy.five_step(), Region::Ntsc.five_step());
}

#[test]
fn dendy_uses_the_ntsc_sequence_because_that_is_what_59_hz_means() {
    // The cycle reference chart gives the frame counter rate as 60 Hz (NTSC),
    // 50 Hz (PAL) and 59 Hz (Dendy), and gives no Dendy step table. Only one
    // of the two existing tables produces 59 Hz at Dendy's CPU rate, and the
    // check below is that arithmetic, in integers.
    //
    // rate = cpu_hz / wrap, with cpu_hz = master_num / (master_den * divider).
    for (region, hz) in [
        (Region::Ntsc, 60u64),
        (Region::Pal, 50),
        (Region::Dendy, 59),
    ] {
        let (num, den) = region.master_clock();
        let wrap = u64::from(region.four_step()[5]);
        // Round-to-nearest, done as integers: 2*num / (2*den*divider*wrap).
        let denom = den * region.cpu_divider() * wrap;
        let rounded = (2 * num + denom) / (2 * denom);
        assert_eq!(rounded, hz, "{region}");
    }
    // And the alternative really is wrong for Dendy: the PAL sequence at a
    // Dendy CPU rate would be 53 Hz, not 59.
    let (num, den) = Region::Dendy.master_clock();
    let denom = den * Region::Dendy.cpu_divider() * u64::from(Region::Pal.four_step()[5]);
    assert_eq!((2 * num + denom) / (2 * denom), 53);
}

#[test]
fn the_noise_and_dmc_tables_are_pal_only_where_the_wiki_says_so() {
    // Both tables are genuinely different on the RP2A07 — they are listed
    // separately by NESdev APU Noise and APU DMC, not derived — while the
    // UA6527P is a 2A03 clone and keeps NTSC's.
    assert_eq!(
        noise::periods(Region::Pal),
        [
            4, 8, 14, 30, 60, 88, 118, 148, 188, 236, 354, 472, 708, 944, 1890, 3778
        ]
    );
    assert_eq!(
        dmc::rates(Region::Pal),
        [
            398, 354, 316, 298, 276, 236, 210, 198, 176, 148, 132, 118, 98, 78, 66, 50
        ]
    );
    assert_ne!(noise::periods(Region::Pal), noise::periods(Region::Ntsc));
    assert_ne!(dmc::rates(Region::Pal), dmc::rates(Region::Ntsc));
    assert_eq!(noise::periods(Region::Dendy), noise::periods(Region::Ntsc));
    assert_eq!(dmc::rates(Region::Dendy), dmc::rates(Region::Ntsc));

    // Every noise period stays even, because the timer is clocked once per APU
    // cycle and the table is in CPU cycles.
    for region in REGIONS {
        for period in noise::periods(region) {
            assert_eq!(period % 2, 0, "{region}");
        }
    }
}

#[test]
fn the_frame_irq_lands_on_each_regions_own_cycle() {
    // The device-level version of the table test: run the whole APU and watch
    // $4015 bit 6.
    for region in REGIONS {
        let irq_at = u64::from(region.four_step()[3]);
        let apu = apu_with(Props::new().with("region", region.name()));
        assert_eq!(apu.tv_region(), region);
        apu.advance(irq_at - 1);
        assert_eq!(apu.read(0x15, 0) & 0x40, 0, "{region}: one cycle too early");
        apu.advance(1);
        assert_ne!(apu.read(0x15, 0) & 0x40, 0, "{region}: the frame IRQ fires");
    }
}

#[test]
fn the_dividers_are_12_16_and_15() {
    // The chart, with the reason for PAL's 16: Nintendo kept the Johnson
    // counter, which always has an even period.
    assert_eq!(Region::Ntsc.cpu_divider(), 12);
    assert_eq!(Region::Pal.cpu_divider(), 16);
    assert_eq!(Region::Dendy.cpu_divider(), 15);
    assert_eq!(Region::Ntsc.master_clock(), (236_250_000, 11));
    assert_eq!(Region::Pal.master_clock(), (53_203_425, 2));
    assert_eq!(Region::Dendy.master_clock(), Region::Pal.master_clock());
    for region in REGIONS {
        let (num, den) = region.master_clock();
        assert_ne!(num % den, 0, "{region} is not a whole number of hertz");
        assert!(!region.part_number().is_empty());
        assert_eq!(Region::from_name(region.name()), Some(region));
        assert!(Region::NAMES.contains(&region.name()));
    }
    assert_eq!(Region::from_name("secam"), None);
}

#[test]
fn the_region_is_configuration_and_a_snapshot_cannot_change_it() {
    let pal = apu_with(Props::new().with("region", "pal"));
    pal.advance(5_000);
    let mut w = StateWriter::new(MachineShape::new());
    {
        let mut chunk = w.chunk("/apu", APU_CLASS.name, APU_CLASS.version).unwrap();
        pal.save(&mut chunk).unwrap();
    }
    let bytes = w.to_vec().unwrap();

    let ntsc = apu_with(Props::new().with("region", "ntsc"));
    let reader = StateReader::new(&bytes).unwrap();
    let chunk = reader
        .load(
            "/apu",
            APU_CLASS.name,
            APU_CLASS.version,
            &Migrations::new(),
        )
        .unwrap();
    ntsc.load(&mut chunk.reader()).unwrap();
    assert_eq!(
        ntsc.tv_region(),
        Region::Ntsc,
        "the machine decides, not the file"
    );
    assert_eq!(ntsc.ticks(), 5_000);
}

// ---------------------------------------------------------------------------
// The connection surface (`ROADMAP.md` §4.4)
// ---------------------------------------------------------------------------

#[test]
fn the_three_windows_are_the_regions_a_map_statement_names() {
    let apu = apu();
    for window in WINDOWS {
        let region = Device::region(&apu, window.name)
            .unwrap_or_else(|| panic!("no region `{}`", window.name));
        assert_eq!(region.len(), window.len, "{}", window.name);
        // One window, one region: two `map` statements naming it must not get
        // two identities for one piece of hardware.
        let again = Device::region(&apu, window.name).unwrap();
        assert!(Arc::ptr_eq(&region, &again), "{}", window.name);
    }
    // $4014 and $4016 are holes, and there is no "whole aperture" to hand out.
    assert!(Device::region(&apu, "").is_none());
    assert!(Device::region(&apu, "regs").is_none());

    // `regions` and `Device::region` agree, offsets included.
    let listed = apu.regions();
    assert_eq!(listed.len(), WINDOWS.len());
    for ((offset, region), window) in listed.iter().zip(WINDOWS) {
        assert_eq!(*offset, window.offset);
        assert!(Arc::ptr_eq(
            region,
            &Device::region(&apu, window.name).unwrap()
        ));
    }

    // And the status window really is $4015: read it through an address space.
    let space = AddressSpace::new("cpu", 16);
    for (offset, region) in apu.regions() {
        space.topology().map(region, 0x4000 + offset).unwrap();
    }
    apu.advance(29_831);
    let status = space.read(0x4015, Width::U8, MemAttrs::DEFAULT).unwrap();
    assert_ne!(status as u8 & 0x40, 0, "the frame IRQ flag");
}

#[test]
fn the_irq_pin_connects_announces_and_refuses_anything_else() {
    let apu = apu();
    // Raise the frame interrupt before anything is connected, so the net is
    // undriven and inconsistent — which is what the realize sweep is for.
    apu.advance(29_831);

    let ids = WireIdAllocator::new();
    let id = ids.alloc();
    let sink = Arc::new(Counter::default());
    let wire = Arc::new(Wire::builder().source(id).sink(sink.clone(), 0).build());
    apu.connect(IRQ_PIN, WireSource::new(Arc::clone(&wire), id))
        .unwrap();
    // `connect_irq` refreshes on connection, so the level is already right;
    // announcing again is idempotent and is what the sweep calls.
    apu.announce(IRQ_PIN);
    assert!(sink.highs.load(AtomicOrdering::SeqCst) >= 1);

    let other = Arc::new(Wire::builder().source(id).build());
    let err = apu
        .connect("nmi", WireSource::new(other, id))
        .unwrap_err()
        .to_string();
    assert!(err.contains("nmi"), "{err}");
    // An unknown pin announce is silently nothing: the sweep asks everyone.
    apu.announce("nmi");
}

#[test]
fn the_class_constructs_through_the_registry_with_a_region() {
    let mut registry = Registry::new();
    register(&mut registry).unwrap();
    let device = registry
        .create("nes.apu", &Props::new().with("region", "dendy"))
        .unwrap();
    assert_eq!(device.class().name, "nes.apu");
    assert!(
        APU_CLASS.properties.iter().any(|p| p.name == "region"),
        "`rsemu describe nes.apu` must list it"
    );
    assert!(Device::region(device.as_ref(), "status").is_some());
    assert!(
        registry
            .create("nes.apu", &Props::new().with("region", "secam"))
            .is_err()
    );
}