oxideav-dvd 0.0.3

Read-only DVD-Video disc reader — ISO 9660 + UDF 1.02 mount + VIDEO_TS directory walk — clean-room per ECMA-267/268 + OSTA UDF 1.02
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
//! DVD-Video VM **instruction decoder** — Phase 3c precursor.
//!
//! This module turns a raw 8-byte [`NavCommand`] word into a typed
//! [`NavInstruction`] tree describing the opcode family, the GPRM /
//! SPRM register operands, the inline 16-bit values, the comparison
//! and arithmetic sub-ops, and the link / jump / call target. **It
//! does not execute anything.** Execution (an interpreter that owns
//! GPRMs + SPRMs + PC + RSM stack) is the bulk of Phase 3c proper;
//! decoding the instruction stream is the prerequisite step a
//! debugger / analyser / future executor all share.
//!
//! Clean-room per:
//!
//! - `docs/container/dvd/application/mpucoder-vmi.html` — the full
//!   opcode table (Type 0..7) including the SET/CMP sub-op codes and
//!   the link-subset table.
//! - `docs/container/dvd/application/mpucoder-vmi-sum.html` — the
//!   plain-English instruction-family summary used to verify each
//!   variant's intent.
//! - `docs/container/dvd/application/mpucoder-vmi-jmp.html` — the
//!   jump-target table for `JumpSS` / `CallSS`.
//! - `docs/container/dvd/application/mpucoder-sprm.html` — the SPRM
//!   numbering for the [`Register`] enum.
//!
//! Instruction layouts derive from the `docs/container/dvd/`
//! references listed above.

use crate::ifo::NavCommand;

// =====================================================================
// Registers — GPRM / SPRM addressing.
// =====================================================================

/// Register identifier referenced by a VM operand byte.
///
/// Per the asterisk note on `mpucoder-vmi.html`:
/// `0x00..=0x0F` are general-purpose registers (GPRM 0..15);
/// `0x80..=0x97` are system-parameter registers (SPRM 0..23);
/// everything else is invalid and must be reported as
/// [`Register::Invalid`] — we preserve the raw byte so a future
/// auditor can still see what the encoder put on disc.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Register {
    /// General-purpose register (writable; persists across PGCs).
    /// Index is 0..=15.
    Gprm(u8),
    /// System-parameter register (largely read-only state, see
    /// `mpucoder-sprm.html` for the per-index meaning). Index is
    /// 0..=23 (raw byte minus `0x80`).
    Sprm(u8),
    /// The raw byte was outside the two valid ranges. We surface it
    /// verbatim rather than refusing to decode — malformed PGC
    /// command tables in the wild often carry junk here.
    Invalid(u8),
}

impl Register {
    /// Classify an 8-bit register field.
    pub fn decode(byte: u8) -> Self {
        match byte {
            0x00..=0x0F => Self::Gprm(byte),
            0x80..=0x97 => Self::Sprm(byte - 0x80),
            _ => Self::Invalid(byte),
        }
    }
}

// =====================================================================
// SET / CMP sub-op codes.
// =====================================================================

/// 4-bit SET sub-op — assignment / arithmetic / bitwise operation.
///
/// Codes 0..=0x0B per `mpucoder-vmi.html` "SET and CMP operations"
/// table; codes 0x0C..=0x0F are listed as invalid in the same row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetOp {
    /// `0` — no SET operation (the encoded command is pure compare /
    /// link).
    None,
    /// `1` — `mov` — `dst = src`.
    Mov,
    /// `2` — `swp` — `dst <-> src`.
    Swp,
    /// `3` — `add` — `dst += src`.
    Add,
    /// `4` — `sub` — `dst -= src`.
    Sub,
    /// `5` — `mul` — `dst *= src`.
    Mul,
    /// `6` — `div` — `dst /= src`.
    Div,
    /// `7` — `mod` — `dst %= src`.
    Mod,
    /// `8` — `rnd` — random in `[0, src)` per common interpretation
    /// (the spec page leaves the operand column blank; we don't act
    /// on the operand here).
    Rnd,
    /// `9` — `and` — `dst &= src`.
    And,
    /// `A` — `or`  — `dst |= src`.
    Or,
    /// `B` — `xor` — `dst ^= src`.
    Xor,
    /// `C..F` — listed as invalid.
    Invalid(u8),
}

impl SetOp {
    /// Decode a 4-bit SET sub-op.
    pub fn decode(code: u8) -> Self {
        match code & 0x0F {
            0 => Self::None,
            1 => Self::Mov,
            2 => Self::Swp,
            3 => Self::Add,
            4 => Self::Sub,
            5 => Self::Mul,
            6 => Self::Div,
            7 => Self::Mod,
            8 => Self::Rnd,
            9 => Self::And,
            0xA => Self::Or,
            0xB => Self::Xor,
            other => Self::Invalid(other),
        }
    }
}

/// 3-bit CMP sub-op — comparison predicate.
///
/// Codes 0..=7 per `mpucoder-vmi.html` "SET and CMP operations".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpOp {
    /// `0` — no compare (unconditional).
    None,
    /// `1` — `BC` — bit-clear test (`(lhs & rhs) == 0`).
    Bc,
    /// `2` — `EQ` — equal.
    Eq,
    /// `3` — `NE` — not equal.
    Ne,
    /// `4` — `GE` — greater or equal.
    Ge,
    /// `5` — `GT` — greater than.
    Gt,
    /// `6` — `LE` — less or equal.
    Le,
    /// `7` — `LT` — less than.
    Lt,
}

impl CmpOp {
    /// Decode a 3-bit CMP sub-op.
    pub fn decode(code: u8) -> Self {
        match code & 0x07 {
            0 => Self::None,
            1 => Self::Bc,
            2 => Self::Eq,
            3 => Self::Ne,
            4 => Self::Ge,
            5 => Self::Gt,
            6 => Self::Le,
            _ => Self::Lt,
        }
    }
}

// =====================================================================
// Compare operand — register or immediate.
// =====================================================================

/// Operand for a compare or a Set right-hand side.
///
/// The "direct" bit of the encoding chooses between a register
/// operand (`Register`) and a 16-bit immediate (`Immediate`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operand {
    /// Register reference (GPRM or SPRM — see [`Register`]).
    Register(Register),
    /// 16-bit big-endian immediate constant.
    Immediate(u16),
}

// =====================================================================
// Link subset — the type-1.0.1 "Link" inner table.
// =====================================================================

/// Inner code for a `0x20 0x01` "Link subset" command per the
/// `link_subset` table in `mpucoder-vmi.html`.
///
/// Codes 0x04, 0x08, 0x0E, 0x0F, and 0x11..0x1F are listed as
/// invalid; we surface the raw byte so a downstream auditor can
/// reason about non-conforming discs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkSubset {
    /// `00` — NOP (no-op within the link group).
    Nop,
    /// `01` — `LinkTopCell` — restart current cell.
    LinkTopCell,
    /// `02` — `LinkNextCell` — proceed to next cell.
    LinkNextCell,
    /// `03` — `LinkPrevCell` — return to previous cell.
    LinkPrevCell,
    /// `05` — `LinkTopPG` — restart current Program.
    LinkTopPG,
    /// `06` — `LinkNextPG` — proceed to next Program.
    LinkNextPG,
    /// `07` — `LinkPrevPG` — return to previous Program.
    LinkPrevPG,
    /// `09` — `LinkTopPGC` — restart current PGC.
    LinkTopPGC,
    /// `0A` — `LinkNextPGC` — proceed to next-PGCN.
    LinkNextPGC,
    /// `0B` — `LinkPrevPGC` — return to prev-PGCN.
    LinkPrevPGC,
    /// `0C` — `LinkGoupPGC` — go up to group-PGCN.
    LinkGoupPGC,
    /// `0D` — `LinkTailPGC` — jump to PGC's post-commands.
    LinkTailPGC,
    /// `10` — `RSM` — resume from saved CallSS state.
    Rsm,
    /// Anything in `04, 08, 0E, 0F, 11..1F` per the spec's "invalid"
    /// row.
    Invalid(u8),
}

impl LinkSubset {
    /// Decode the bottom 5 bits of byte 7 (the `Lnk` field).
    pub fn decode(code: u8) -> Self {
        match code & 0x1F {
            0x00 => Self::Nop,
            0x01 => Self::LinkTopCell,
            0x02 => Self::LinkNextCell,
            0x03 => Self::LinkPrevCell,
            0x05 => Self::LinkTopPG,
            0x06 => Self::LinkNextPG,
            0x07 => Self::LinkPrevPG,
            0x09 => Self::LinkTopPGC,
            0x0A => Self::LinkNextPGC,
            0x0B => Self::LinkPrevPGC,
            0x0C => Self::LinkGoupPGC,
            0x0D => Self::LinkTailPGC,
            0x10 => Self::Rsm,
            other => Self::Invalid(other),
        }
    }
}

// =====================================================================
// JumpSS / CallSS targets.
// =====================================================================

/// `JumpSS` destination per the Type-1.1, CMD=6 family in
/// `mpucoder-vmi.html`.
///
/// The two-bit selector in byte 5 bits 5..4 picks the destination
/// kind; we surface each as a typed variant rather than the raw
/// selector word.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JumpSSTarget {
    /// Selector `0` — `JumpSS FP` (jump to the First-Play PGC).
    FirstPlay,
    /// Selector `1` — `JumpSS VMGM menu, <menu_id>` (a VMG menu
    /// identified by the 4-bit menu index).
    VmgmMenu { menu: u8 },
    /// Selector `2` — `JumpSS VTSM <vts>, <ttn>, <menu>` (a VTS-menu
    /// PGC).
    VtsmMenu { vts: u8, ttn: u8, menu: u8 },
    /// Selector `3` — `JumpSS VMGM pgcn` (a specific VMG PGC by
    /// number — the 16-bit `pgcn` field from operand 1).
    VmgmPgcn { pgcn: u16 },
}

/// `CallSS` destination per the Type-1.1, CMD=8 family in
/// `mpucoder-vmi.html`. Adds a `rsm_cell` field common to all four
/// variants — the cell to resume to on a later `RSM`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallSSTarget {
    /// `CallSS FP` (with resume-cell).
    FirstPlay { rsm_cell: u8 },
    /// `CallSS VMGM menu, <menu>` (with resume-cell).
    VmgmMenu { menu: u8, rsm_cell: u8 },
    /// `CallSS VTSM menu, <menu>` (with resume-cell). Per the spec
    /// table, the VTS / TTN selectors aren't carried in CallSS the
    /// way they are in JumpSS — only the menu index.
    VtsmMenu { menu: u8, rsm_cell: u8 },
    /// `CallSS VMGM pgcn` (with resume-cell).
    VmgmPgcn { pgcn: u16, rsm_cell: u8 },
}

// =====================================================================
// NavInstruction — the typed decode tree.
// =====================================================================

/// Top-level VM instruction decoded from an 8-byte [`NavCommand`].
///
/// This is the "first pass" disassembly. The well-defined opcodes in
/// Types 0..3 (NOP, Goto, Break, SetTmpPML, the link / jump / call
/// family, SetSystem, plain Set) are returned as named variants; the
/// compound-operation families Type 4..6 (SetCLnk, CSetCLnk,
/// CmpSetLnk) and the rare conditional forms are surfaced as
/// [`NavInstruction::Compound`] with their classifier sub-fields
/// pre-decoded but the inner sub-operations left to a Phase-3c
/// executor.
///
/// All variants preserve the originating 8-byte word so a downstream
/// debugger can render the raw hex alongside the decoded form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavInstruction {
    // ---- Type 0 — special / compare-only ---------------------------
    /// `00 00` — `NOP`.
    Nop,
    /// `00 01 .. line` — `Goto line` (intra-PGC pre/post jump).
    Goto { line: u8 },
    /// `00 02` — `Break` (exits the current pre / post / cell list).
    Break,
    /// `00 03 .. lvl line` — `SetTmpPML lvl, line`.
    SetTmpPml { level: u8, line: u8 },

    // ---- Type 1 — link family (byte0[4] == 0, "Link") --------------
    /// `20 01` plus link-subset code in byte 7 — `Link<subset>
    /// [button=<hl_bn>]` (the 13 `Link*` / `RSM` inner forms).
    LinkSub { subset: LinkSubset, hl_bn: u8 },
    /// `20 04 .. pgcn` — `LinkPGCN pgcn`.
    LinkPgcn { pgcn: u16 },
    /// `20 05 .. (hl_bn|pttn)` — `LinkPTTN pttn [, button=hl_bn]`.
    LinkPttn { pttn: u16, hl_bn: u8 },
    /// `20 06 .. (hl_bn|pgn)` — `LinkPGN pgn [, button=hl_bn]`.
    LinkPgn { pgn: u8, hl_bn: u8 },
    /// `20 07 .. (hl_bn|cn)` — `LinkCN cn [, button=hl_bn]`.
    LinkCn { cn: u8, hl_bn: u8 },

    // ---- Type 1 — jump / call family (byte0[4] == 1) ---------------
    /// `30 01` — `Exit`.
    Exit,
    /// `30 02 .. ttn` — `JumpTT ttn`.
    JumpTT { ttn: u8 },
    /// `30 03 .. ttn` — `JumpVTS_TT ttn`.
    JumpVtsTt { ttn: u8 },
    /// `30 05 .. pttn .. ttn` — `JumpVTS_PTT ttn, pttn`.
    JumpVtsPtt { ttn: u8, pttn: u16 },
    /// `30 06 .. <target>` — `JumpSS <target>`.
    JumpSs(JumpSSTarget),
    /// `30 08 .. <target>` — `CallSS <target>`.
    CallSs(CallSSTarget),

    // ---- Type 2 — SetSystem family ---------------------------------
    /// `41 .. / 51 ..` — `SetSTN` (audio / sub-picture / angle).
    /// Raw fields preserved; consumers map `af`/`sf`/`nf` flag bits
    /// to act on the corresponding `src*` slot.
    SetStn {
        /// `0` = source is a register (`Operand::Register`); `1` =
        /// inline 16-bit immediate spread across the three 7-bit
        /// `aval`/`sval`/`nval` slots, per `mpucoder-vmi.html`
        /// row Type-2 SET=1 CMD=0.
        direct: bool,
        /// Audio-flag (`af` bit, byte 3 bit 7) — apply `audio_src`.
        af: bool,
        /// Audio source (register form: 4-bit `sr1`; immediate form:
        /// 7-bit `aval`).
        audio_src: u8,
        /// Sub-picture flag (`sf` bit).
        sf: bool,
        /// Sub-picture source.
        subpic_src: u8,
        /// Angle flag (`nf` bit).
        nf: bool,
        /// Angle source.
        angle_src: u8,
    },
    /// `42 .. / 52 ..` — `SetNVTMR srs, pgcn` (load nav timer +
    /// associated PGC number).
    SetNvtmr { src: Operand, pgcn: u16 },
    /// `43 .. / 53 ..` — `SetGPRMMD G<srd> = <src> [,COUNTER]`.
    SetGprmMd {
        src: Operand,
        dst: Register,
        /// `mf` bit — when set, the destination GPRM becomes a
        /// 1-Hz counter rather than a plain register.
        counter: bool,
    },
    /// `44 .. / 54 ..` — `SetAMXMD G<srs>` (karaoke mixing mode).
    SetAmxMd { src: Operand },
    /// `46 .. / 56 ..` — `SetHL_BTNN G<srs>` (force highlight to a
    /// specific button).
    SetHlBtnn { src: Operand },

    // ---- Type 3 — Set arithmetic -----------------------------------
    /// `6x .. / 7x ..` with sub-op `1..=B` — `Set G<srd> <set-op>
    /// <src>` (the plain Set / arithmetic / bitwise family).
    Set {
        op: SetOp,
        dst: Register,
        src: Operand,
    },

    // ---- Type 4..6 — compound CMP/SET/LNK families -----------------
    /// Type 4 — `SetCLnk` (Set then Compare & Link).
    ///
    /// Semantics per `mpucoder-vmi-sum.html`: (1) `G<scr> set-op
    /// src`; (2) `cmp-op(G<scr>, cr2)`; (3) on `true`, `Link(subset,
    /// hl_bn)`. The destination register is implicit — the same
    /// 4-bit `scr` selector serves as both the SET destination /
    /// CMP left-hand operand.
    SetCLnk {
        set_op: SetOp,
        cmp_op: CmpOp,
        /// Selector register (G<scr>) used as both SET destination
        /// and CMP left-hand side. Always a GPRM (4-bit field).
        scr: Register,
        /// SET right-hand operand. Either `Register(srs)` (SET-dir
        /// flag clear) or `Immediate(sval)` (SET-dir flag set).
        set_src: Operand,
        /// CMP right-hand operand. Either `Register(cr2)` or
        /// `Immediate(cval)` per the CMP-dir flag.
        cmp_rhs: Operand,
        /// Optional highlight-button override carried into the
        /// linked target (byte 6 bits 7..2 = 6-bit `hl_bn`).
        hl_bn: u8,
        /// Link subset selecting the inner Link destination on
        /// `cmp-op == true`.
        link: LinkSubset,
    },
    /// Type 5 — `CSetCLnk` (Compare then Set & Link).
    ///
    /// Semantics per `mpucoder-vmi-sum.html`: (1) `cmp-op(cr1, cr2)`;
    /// (2) on `true`, `G<sr1> set-op sr2`; (3) on `true`,
    /// `Link(subset, hl_bn)`. Unlike Type 4 the SET destination
    /// (`sr1`) and CMP left-hand (`cr1`) are independent selectors.
    CSetCLnk {
        set_op: SetOp,
        cmp_op: CmpOp,
        /// SET destination register (`sr1`, 4-bit GPRM selector).
        sr1: Register,
        /// SET right-hand operand: register form `Register(sr2)`
        /// (SET-dir clear) or immediate `sval2` (SET-dir set).
        set_src: Operand,
        /// CMP left-hand register (`cr1`, 8-bit GPRM/SPRM selector).
        cmp_lhs: Register,
        /// CMP right-hand operand: register form `Register(cr2)` or
        /// immediate `cval` per the CMP-dir flag.
        cmp_rhs: Operand,
        /// Highlight-button override.
        hl_bn: u8,
        /// Link subset selecting the inner Link destination on
        /// `cmp-op == true`.
        link: LinkSubset,
    },
    /// Type 6 — `CmpSetLnk` (Compare then Set, then unconditional Link).
    ///
    /// Semantics per `mpucoder-vmi-sum.html`: (1) `cmp-op(G<sr1>,
    /// cr2)`; (2) on `true`, `G<sr1> set-op src`; (3)
    /// `Link(subset, hl_bn)` ALWAYS — distinguishing Type 6 from
    /// Type 5 is that Type 6's Link fires regardless of the CMP
    /// outcome.
    CmpSetLnk {
        set_op: SetOp,
        cmp_op: CmpOp,
        /// Shared selector register (`sr1`) used as both SET
        /// destination and CMP left-hand side.
        sr1: Register,
        /// SET right-hand operand: register form `Register(srs)` or
        /// immediate `sval`.
        set_src: Operand,
        /// CMP right-hand operand: register form `Register(cr2)` or
        /// immediate `cval`.
        cmp_rhs: Operand,
        /// Highlight-button override.
        hl_bn: u8,
        /// Link subset — fires unconditionally per Type 6's "Link
        /// runs even on `cmp-op == false`" rule.
        link: LinkSubset,
    },

    // ---- Type 7 — undefined ----------------------------------------
    /// Type 7 — never observed in the wild per `mpucoder-vmi.html`;
    /// we surface it as `Unknown` rather than refusing to decode so
    /// disc-debug tooling keeps working.
    Unknown,

    // ---- Catch-all for malformed encodings -------------------------
    /// The byte 0 type field selected a known family but the
    /// inner CMD / SET / direct fields formed an "invalid" encoding
    /// per the spec's red rows. The 8 raw bytes are preserved.
    Invalid,
}

// =====================================================================
// Decoder.
// =====================================================================

impl NavCommand {
    /// Decode the 8-byte command word into a typed [`NavInstruction`].
    ///
    /// This is a single-pass classifier: it inspects byte 0's top
    /// three bits to pick the family, then dispatches to a per-type
    /// helper that pulls out the operand bytes. The well-defined
    /// instructions in Types 0..3 are returned in full; the compound
    /// families Type 4..6 surface their CMP/SET classifier sub-ops
    /// but leave the full operand decoding to a Phase-3c executor.
    ///
    /// **Pure function** — no side effects; the call is `O(1)`.
    pub fn decode(&self) -> NavInstruction {
        let b = &self.bytes;
        // byte 0: TTT D SSSS where TTT = type (bits 7..5), D = SET-direct flag,
        // SSSS = set-op or auxiliary nibble depending on family.
        let cmd_type = b[0] >> 5;
        let set_direct = (b[0] & 0x10) != 0;
        let set_nibble = b[0] & 0x0F;
        // byte 1: C HHH CCCC where C = CMP-direct flag (bit 7), HHH = cmp-op
        // (bits 6..4), CCCC = link/command nibble (bits 3..0).
        let cmd_nibble = b[1] & 0x0F;
        let cmp_op = CmpOp::decode((b[1] >> 4) & 0x07);
        let cmp_direct = (b[1] & 0x80) != 0;

        match cmd_type {
            0 => decode_type0(b, cmd_nibble),
            1 => {
                if (b[0] & 0x10) == 0 {
                    decode_type1_link(b, cmd_nibble)
                } else {
                    decode_type1_jumpcall(b, cmd_nibble)
                }
            }
            2 => decode_type2_setsystem(b, set_direct, set_nibble),
            3 => decode_type3_set(b, set_direct, set_nibble),
            4 => decode_type4(b, set_direct, cmp_direct, set_nibble, cmp_op),
            5 => decode_type5(b, set_direct, cmp_direct, set_nibble, cmp_op),
            6 => decode_type6(b, set_direct, cmp_direct, set_nibble, cmp_op),
            _ => NavInstruction::Unknown,
        }
    }
}

fn decode_type0(b: &[u8; 8], cmd_nibble: u8) -> NavInstruction {
    // Compare-only sub-table (CMP-op != 0): per spec row "0 1-7 0-3"
    // these are conditional NOP / Goto / Break / SetTmpPML wrappers —
    // we decode the underlying instruction and ignore the compare
    // (a Phase-3c executor would honour it).
    match cmd_nibble {
        0 => NavInstruction::Nop,
        1 => NavInstruction::Goto { line: b[7] },
        2 => NavInstruction::Break,
        3 => NavInstruction::SetTmpPml {
            level: b[6] & 0x0F,
            line: b[7],
        },
        // 4..F per spec's red row: "invalid".
        _ => NavInstruction::Invalid,
    }
}

fn decode_type1_link(b: &[u8; 8], cmd_nibble: u8) -> NavInstruction {
    // hl_bn (highlight-button) is byte 6 bits 5..0 across the link
    // family per the operand-3 column.
    let hl_bn = b[6] & 0x3F;
    match cmd_nibble {
        0 => NavInstruction::Nop,
        1 => NavInstruction::LinkSub {
            subset: LinkSubset::decode(b[7]),
            hl_bn,
        },
        4 => NavInstruction::LinkPgcn {
            pgcn: u16::from_be_bytes([b[6], b[7]]),
        },
        5 => NavInstruction::LinkPttn {
            // 10-bit pttn occupies byte 6 bits 1..0 + byte 7.
            pttn: u16::from_be_bytes([b[6] & 0x03, b[7]]),
            hl_bn,
        },
        6 => NavInstruction::LinkPgn { pgn: b[7], hl_bn },
        7 => NavInstruction::LinkCn { cn: b[7], hl_bn },
        // 2, 3, 8..F: invalid Link nibbles per spec.
        _ => NavInstruction::Invalid,
    }
}

fn decode_type1_jumpcall(b: &[u8; 8], cmd_nibble: u8) -> NavInstruction {
    match cmd_nibble {
        0 => NavInstruction::Nop,
        1 => NavInstruction::Exit,
        2 => NavInstruction::JumpTT { ttn: b[5] },
        3 => NavInstruction::JumpVtsTt { ttn: b[5] },
        5 => NavInstruction::JumpVtsPtt {
            ttn: b[5],
            // 10-bit pttn — byte 2 bits 1..0 + byte 3.
            pttn: u16::from_be_bytes([b[2] & 0x03, b[3]]),
        },
        6 => NavInstruction::JumpSs(decode_jumpss_target(b)),
        8 => NavInstruction::CallSs(decode_callss_target(b)),
        // 4, 7, 9..F per spec: invalid.
        _ => NavInstruction::Invalid,
    }
}

fn decode_jumpss_target(b: &[u8; 8]) -> JumpSSTarget {
    // Selector at byte 5 bits 5..4. Operand layout per the four
    // `JumpSS` rows on the spec page.
    let selector = (b[5] >> 4) & 0x03;
    match selector {
        0 => JumpSSTarget::FirstPlay,
        1 => JumpSSTarget::VmgmMenu { menu: b[5] & 0x0F },
        2 => JumpSSTarget::VtsmMenu {
            ttn: b[3],
            vts: b[4],
            menu: b[5] & 0x0F,
        },
        _ => JumpSSTarget::VmgmPgcn {
            pgcn: u16::from_be_bytes([b[2], b[3]]),
        },
    }
}

fn decode_callss_target(b: &[u8; 8]) -> CallSSTarget {
    let selector = (b[5] >> 4) & 0x03;
    let rsm_cell = b[4];
    match selector {
        0 => CallSSTarget::FirstPlay { rsm_cell },
        1 => CallSSTarget::VmgmMenu {
            menu: b[5] & 0x0F,
            rsm_cell,
        },
        2 => CallSSTarget::VtsmMenu {
            menu: b[5] & 0x0F,
            rsm_cell,
        },
        _ => CallSSTarget::VmgmPgcn {
            pgcn: u16::from_be_bytes([b[2], b[3]]),
            rsm_cell,
        },
    }
}

fn decode_type2_setsystem(b: &[u8; 8], direct: bool, sub: u8) -> NavInstruction {
    // sub: byte 0 bits 3..0 picks the SetSystem opcode (1..6 valid
    // per `mpucoder-vmi.html`'s Type-2 SET=1 column).
    match sub {
        // SetSTN — sub-code 1.
        1 => {
            // Flag bits live at byte 3 bit 7 (af), byte 4 bit 7
            // (sf), byte 5 bit 7 (nf) in both register and immediate
            // forms; the source values live in bytes 3/4/5 either as
            // 4-bit register selectors (register form, low nibble)
            // or 7-bit immediates (immediate form, bits 6..0).
            let af = (b[3] & 0x80) != 0;
            let sf = (b[4] & 0x80) != 0;
            let nf = (b[5] & 0x80) != 0;
            let mask = if direct { 0x7F } else { 0x0F };
            NavInstruction::SetStn {
                direct,
                af,
                audio_src: b[3] & mask,
                sf,
                subpic_src: b[4] & mask,
                nf,
                angle_src: b[5] & mask,
            }
        }
        // SetNVTMR — sub-code 2.
        2 => NavInstruction::SetNvtmr {
            src: if direct {
                Operand::Immediate(u16::from_be_bytes([b[2], b[3]]))
            } else {
                Operand::Register(Register::decode(b[3]))
            },
            pgcn: u16::from_be_bytes([b[4], b[5]]),
        },
        // SetGPRMMD — sub-code 3. The 'mf' counter flag is byte 4
        // bit 7 in both forms.
        3 => NavInstruction::SetGprmMd {
            src: if direct {
                Operand::Immediate(u16::from_be_bytes([b[2], b[3]]))
            } else {
                Operand::Register(Register::decode(b[3]))
            },
            dst: Register::Gprm(b[5] & 0x0F),
            counter: (b[4] & 0x80) != 0,
        },
        // SetAMXMD — sub-code 4.
        4 => NavInstruction::SetAmxMd {
            src: if direct {
                Operand::Immediate(u16::from_be_bytes([b[4], b[5]]))
            } else {
                Operand::Register(Register::Gprm(b[5] & 0x0F))
            },
        },
        // SetHL_BTNN — sub-code 6.
        6 => NavInstruction::SetHlBtnn {
            src: if direct {
                Operand::Immediate(u16::from_be_bytes([b[4], b[5]]))
            } else {
                Operand::Register(Register::Gprm(b[5] & 0x0F))
            },
        },
        // 5 + 7..F per spec: invalid SetSystem.
        _ => NavInstruction::Invalid,
    }
}

fn decode_type3_set(b: &[u8; 8], direct: bool, sub: u8) -> NavInstruction {
    // sub: byte 0 bits 3..0 selects the SET sub-op; 1..=B valid.
    if !(1..=0x0B).contains(&sub) {
        return NavInstruction::Invalid;
    }
    let dst = Register::Gprm(b[3] & 0x0F);
    let src = if direct {
        Operand::Immediate(u16::from_be_bytes([b[4], b[5]]))
    } else {
        Operand::Register(Register::decode(b[5]))
    };
    NavInstruction::Set {
        op: SetOp::decode(sub),
        dst,
        src,
    }
}

// ---------- Type 4..6 compound CMP/SET/LNK helpers --------------------
//
// All three families share the same trailing-byte layout:
//
//   byte 1 bits 3..0 = scr / sr1  (4-bit GPRM selector)
//   byte 6 bits 7..2 = hl_bn      (highlight-button override)
//   byte 7 bits 4..0 = Lnk subset (Link-family inner code)
//
// The SET-direct and CMP-direct flag bits choose how operand bytes
// 2..5 are interpreted, but they always cover the same byte ranges:
//
//   Type 4 SET-source  : byte 3 (register `srs`) or bytes 2-3 (16-bit `sval`)
//          CMP-RHS     : byte 5 (register `cr2`) or bytes 4-5 (16-bit `cval`)
//   Type 5 SET-dst-reg : byte 2 high nibble unused, byte 1 low nibble = `sr1`
//          SET-source  : byte 3 (register `sr2`) or bytes 2-3 (16-bit `sval2`)
//          CMP-LHS     : byte 4 (register `cr1`)
//          CMP-RHS     : byte 5 (register `cr2`) or bytes 4-5 (16-bit `cval`)
//                        — note: when CMP-dir=1 the `cval` immediate overlays
//                          byte 4's `cr1`, leaving `cr1` undefined in row 94
//                          ("cval" colspan=16). Per the spec page we treat
//                          `cr1` as 0 in that arrangement (the immediate
//                          form makes the CMP-LHS irrelevant — `cval` is
//                          compared against the SET destination instead).
//   Type 6 SET-dst-reg : `sr1` shared between SET destination and CMP-LHS
//          SET-source  : byte 3 (register `srs`) or bytes 2-3 (16-bit `sval`)
//          CMP-RHS     : byte 5 (register `cr2`) or bytes 4-5 (16-bit `cval`)
//
// Per the spec's red rows: SET-dir == 1 AND CMP-dir == 1 is "Illegal"
// for Types 5 and 6 (the operand bytes overlap in those rows) — the
// decoder surfaces `NavInstruction::Invalid` for those words.

fn decode_type4(
    b: &[u8; 8],
    set_direct: bool,
    cmp_direct: bool,
    set_nibble: u8,
    cmp_op: CmpOp,
) -> NavInstruction {
    let scr = Register::Gprm(b[1] & 0x0F);
    let set_src = if set_direct {
        Operand::Immediate(u16::from_be_bytes([b[2], b[3]]))
    } else {
        Operand::Register(Register::decode(b[3]))
    };
    let cmp_rhs = if cmp_direct {
        Operand::Immediate(u16::from_be_bytes([b[4], b[5]]))
    } else {
        Operand::Register(Register::decode(b[5]))
    };
    NavInstruction::SetCLnk {
        set_op: SetOp::decode(set_nibble),
        cmp_op,
        scr,
        set_src,
        cmp_rhs,
        hl_bn: (b[6] >> 2) & 0x3F,
        link: LinkSubset::decode(b[7]),
    }
}

fn decode_type5(
    b: &[u8; 8],
    set_direct: bool,
    cmp_direct: bool,
    set_nibble: u8,
    cmp_op: CmpOp,
) -> NavInstruction {
    // Row 96 (red): SET-dir=1, CMP-dir=1 is Illegal CSetCLnk.
    if set_direct && cmp_direct {
        return NavInstruction::Invalid;
    }
    let sr1 = Register::Gprm(b[1] & 0x0F);
    // Per the spec rows, the SET source is bytes 2-3 in the immediate
    // form (`sval2`) and byte 3 in the register form (`sr2`).
    let set_src = if set_direct {
        Operand::Immediate(u16::from_be_bytes([b[2], b[3]]))
    } else {
        Operand::Register(Register::decode(b[3]))
    };
    // CMP-LHS register `cr1` lives in byte 4 in the register form. In
    // the SET-dir=1 / CMP-dir=0 row (row 95) `cr1` is also at byte 4.
    let cmp_lhs = Register::decode(b[4]);
    let cmp_rhs = if cmp_direct {
        Operand::Immediate(u16::from_be_bytes([b[4], b[5]]))
    } else {
        Operand::Register(Register::decode(b[5]))
    };
    NavInstruction::CSetCLnk {
        set_op: SetOp::decode(set_nibble),
        cmp_op,
        sr1,
        set_src,
        cmp_lhs,
        cmp_rhs,
        hl_bn: (b[6] >> 2) & 0x3F,
        link: LinkSubset::decode(b[7]),
    }
}

fn decode_type6(
    b: &[u8; 8],
    set_direct: bool,
    cmp_direct: bool,
    set_nibble: u8,
    cmp_op: CmpOp,
) -> NavInstruction {
    // Row 101 (red): SET-dir=1, CMP-dir=1 is Illegal CmpSetLnk.
    if set_direct && cmp_direct {
        return NavInstruction::Invalid;
    }
    let sr1 = Register::Gprm(b[1] & 0x0F);
    let set_src = if set_direct {
        Operand::Immediate(u16::from_be_bytes([b[2], b[3]]))
    } else {
        Operand::Register(Register::decode(b[3]))
    };
    let cmp_rhs = if cmp_direct {
        Operand::Immediate(u16::from_be_bytes([b[4], b[5]]))
    } else {
        Operand::Register(Register::decode(b[5]))
    };
    NavInstruction::CmpSetLnk {
        set_op: SetOp::decode(set_nibble),
        cmp_op,
        sr1,
        set_src,
        cmp_rhs,
        hl_bn: (b[6] >> 2) & 0x3F,
        link: LinkSubset::decode(b[7]),
    }
}

// =====================================================================
// Tests.
// =====================================================================

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

    /// Helper — wrap 8 bytes as a [`NavCommand`] for decoding.
    fn cmd(bytes: [u8; 8]) -> NavCommand {
        NavCommand { bytes }
    }

    // -----------------------------------------------------------------
    // Register classifier.
    // -----------------------------------------------------------------

    #[test]
    fn register_decode_gprm_range() {
        for i in 0u8..=15 {
            assert_eq!(Register::decode(i), Register::Gprm(i));
        }
    }

    #[test]
    fn register_decode_sprm_range() {
        for i in 0u8..=23 {
            assert_eq!(Register::decode(0x80 + i), Register::Sprm(i));
        }
    }

    #[test]
    fn register_decode_invalid_holes() {
        // The mid-range hole (0x10..=0x7F) per the * note.
        assert_eq!(Register::decode(0x10), Register::Invalid(0x10));
        assert_eq!(Register::decode(0x7F), Register::Invalid(0x7F));
        // The upper hole (0x98..=0xFF).
        assert_eq!(Register::decode(0x98), Register::Invalid(0x98));
        assert_eq!(Register::decode(0xFF), Register::Invalid(0xFF));
    }

    // -----------------------------------------------------------------
    // SET / CMP op tables.
    // -----------------------------------------------------------------

    #[test]
    fn set_op_decodes_all_named_codes() {
        let table: &[(u8, SetOp)] = &[
            (0, SetOp::None),
            (1, SetOp::Mov),
            (2, SetOp::Swp),
            (3, SetOp::Add),
            (4, SetOp::Sub),
            (5, SetOp::Mul),
            (6, SetOp::Div),
            (7, SetOp::Mod),
            (8, SetOp::Rnd),
            (9, SetOp::And),
            (0xA, SetOp::Or),
            (0xB, SetOp::Xor),
        ];
        for (code, expect) in table {
            assert_eq!(SetOp::decode(*code), *expect);
        }
        assert_eq!(SetOp::decode(0xC), SetOp::Invalid(0xC));
        assert_eq!(SetOp::decode(0xF), SetOp::Invalid(0xF));
    }

    #[test]
    fn cmp_op_decodes_all_codes() {
        let table: &[(u8, CmpOp)] = &[
            (0, CmpOp::None),
            (1, CmpOp::Bc),
            (2, CmpOp::Eq),
            (3, CmpOp::Ne),
            (4, CmpOp::Ge),
            (5, CmpOp::Gt),
            (6, CmpOp::Le),
            (7, CmpOp::Lt),
        ];
        for (code, expect) in table {
            assert_eq!(CmpOp::decode(*code), *expect);
        }
    }

    // -----------------------------------------------------------------
    // Link-subset table.
    // -----------------------------------------------------------------

    #[test]
    fn link_subset_decodes_named_codes() {
        let table: &[(u8, LinkSubset)] = &[
            (0x00, LinkSubset::Nop),
            (0x01, LinkSubset::LinkTopCell),
            (0x02, LinkSubset::LinkNextCell),
            (0x03, LinkSubset::LinkPrevCell),
            (0x05, LinkSubset::LinkTopPG),
            (0x06, LinkSubset::LinkNextPG),
            (0x07, LinkSubset::LinkPrevPG),
            (0x09, LinkSubset::LinkTopPGC),
            (0x0A, LinkSubset::LinkNextPGC),
            (0x0B, LinkSubset::LinkPrevPGC),
            (0x0C, LinkSubset::LinkGoupPGC),
            (0x0D, LinkSubset::LinkTailPGC),
            (0x10, LinkSubset::Rsm),
        ];
        for (code, expect) in table {
            assert_eq!(LinkSubset::decode(*code), *expect);
        }
        // Spec's invalid bag.
        assert_eq!(LinkSubset::decode(0x04), LinkSubset::Invalid(0x04));
        assert_eq!(LinkSubset::decode(0x08), LinkSubset::Invalid(0x08));
        assert_eq!(LinkSubset::decode(0x0E), LinkSubset::Invalid(0x0E));
        assert_eq!(LinkSubset::decode(0x1F), LinkSubset::Invalid(0x1F));
    }

    // -----------------------------------------------------------------
    // Type 0 — NOP / Goto / Break / SetTmpPML.
    // -----------------------------------------------------------------

    #[test]
    fn decode_type0_nop() {
        assert_eq!(
            cmd([0x00, 0x00, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Nop
        );
    }

    #[test]
    fn decode_type0_goto() {
        // byte0 type=0, byte1 cmd-nibble=1 → Goto, line in byte 7.
        let i = cmd([0x00, 0x01, 0, 0, 0, 0, 0, 0x2A]).decode();
        assert_eq!(i, NavInstruction::Goto { line: 0x2A });
    }

    #[test]
    fn decode_type0_break() {
        assert_eq!(
            cmd([0x00, 0x02, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Break
        );
    }

    #[test]
    fn decode_type0_settmppml() {
        // Type 0, cmd-nibble=3 → SetTmpPML, lvl = byte6 low nibble,
        // line = byte 7.
        let i = cmd([0x00, 0x03, 0, 0, 0, 0, 0x05, 0x99]).decode();
        assert_eq!(
            i,
            NavInstruction::SetTmpPml {
                level: 5,
                line: 0x99
            }
        );
    }

    #[test]
    fn decode_type0_invalid_cmd_nibble() {
        // cmd-nibble = 4 → invalid per spec.
        assert_eq!(
            cmd([0x00, 0x04, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Invalid
        );
    }

    // -----------------------------------------------------------------
    // Type 1 link family.
    // -----------------------------------------------------------------

    #[test]
    fn decode_link_subset_with_button() {
        // 20 01 .. .. .. .. (hl_bn<<0=0x05) (subset=0x10 RSM)
        let i = cmd([0x20, 0x01, 0, 0, 0, 0, 0x05, 0x10]).decode();
        assert_eq!(
            i,
            NavInstruction::LinkSub {
                subset: LinkSubset::Rsm,
                hl_bn: 5,
            }
        );
    }

    #[test]
    fn decode_link_pgcn() {
        // 20 04 .. .. .. .. .. (pgcn = 0x1234 across bytes 6..7)
        let i = cmd([0x20, 0x04, 0, 0, 0, 0, 0x12, 0x34]).decode();
        assert_eq!(i, NavInstruction::LinkPgcn { pgcn: 0x1234 });
    }

    #[test]
    fn decode_link_pttn() {
        // 20 05 — pttn is 10-bit: byte6 bits 1..0 + byte7. hl_bn lives
        // in byte 6 bits 5..0 (and the top 2 bits of the pttn share
        // byte 6 with hl_bn — we treat the low 2 bits as pttn high
        // bits per the spec column).
        // pttn = 0x103 → byte6 low = 0b01, byte7 = 0x03.
        // hl_bn = 0x09.
        let i = cmd([0x20, 0x05, 0, 0, 0, 0, (0x09 & 0x3F) | 0x40 | 0x01, 0x03]).decode();
        match i {
            NavInstruction::LinkPttn { pttn, hl_bn } => {
                assert_eq!(pttn, 0x103);
                assert_eq!(hl_bn, 0x09);
            }
            _ => panic!("expected LinkPttn"),
        }
    }

    #[test]
    fn decode_link_pgn_and_cn() {
        let i = cmd([0x20, 0x06, 0, 0, 0, 0, 0x05, 0x11]).decode();
        assert_eq!(
            i,
            NavInstruction::LinkPgn {
                pgn: 0x11,
                hl_bn: 5
            }
        );
        let i = cmd([0x20, 0x07, 0, 0, 0, 0, 0x06, 0x42]).decode();
        assert_eq!(i, NavInstruction::LinkCn { cn: 0x42, hl_bn: 6 });
    }

    #[test]
    fn decode_link_invalid_nibble() {
        // cmd-nibble = 2 is invalid per Link spec.
        assert_eq!(
            cmd([0x20, 0x02, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Invalid
        );
    }

    // -----------------------------------------------------------------
    // Type 1 jump / call family.
    // -----------------------------------------------------------------

    #[test]
    fn decode_exit() {
        // byte0 = 0x30 (type=1, byte0[4]=1), byte1=0x01 → Exit.
        assert_eq!(
            cmd([0x30, 0x01, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Exit
        );
    }

    #[test]
    fn decode_jump_tt_and_vts_tt() {
        let i = cmd([0x30, 0x02, 0, 0, 0, 0x07, 0, 0]).decode();
        assert_eq!(i, NavInstruction::JumpTT { ttn: 7 });
        let i = cmd([0x30, 0x03, 0, 0, 0, 0x09, 0, 0]).decode();
        assert_eq!(i, NavInstruction::JumpVtsTt { ttn: 9 });
    }

    #[test]
    fn decode_jump_vts_ptt() {
        // ttn in byte 5; pttn 10-bit in byte 2 low 2 bits + byte 3.
        // pttn = 0x205 → byte2 low = 2, byte3 = 5.
        let i = cmd([0x30, 0x05, 0x02, 0x05, 0, 0x04, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::JumpVtsPtt {
                ttn: 4,
                pttn: 0x205
            }
        );
    }

    #[test]
    fn decode_jump_ss_first_play() {
        // selector byte5 bits 5..4 = 0 → FirstPlay.
        let i = cmd([0x30, 0x06, 0, 0, 0, 0x00, 0, 0]).decode();
        assert_eq!(i, NavInstruction::JumpSs(JumpSSTarget::FirstPlay));
    }

    #[test]
    fn decode_jump_ss_vmgm_menu() {
        // selector 1, menu = 0x0A in byte5 low nibble.
        let i = cmd([0x30, 0x06, 0, 0, 0, 0x1A, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::JumpSs(JumpSSTarget::VmgmMenu { menu: 0x0A })
        );
    }

    #[test]
    fn decode_jump_ss_vtsm() {
        // selector 2, vts in byte4, ttn in byte3, menu in byte5 low.
        let i = cmd([0x30, 0x06, 0, 0x07, 0x02, 0x23, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::JumpSs(JumpSSTarget::VtsmMenu {
                vts: 2,
                ttn: 7,
                menu: 3,
            })
        );
    }

    #[test]
    fn decode_jump_ss_vmgm_pgcn() {
        // selector 3 → VmgmPgcn; pgcn = u16 from bytes 2..3.
        let i = cmd([0x30, 0x06, 0xAB, 0xCD, 0, 0x30, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::JumpSs(JumpSSTarget::VmgmPgcn { pgcn: 0xABCD })
        );
    }

    #[test]
    fn decode_call_ss_first_play() {
        // CallSS: cmd-nibble=8, selector 0, rsm_cell in byte 4.
        let i = cmd([0x30, 0x08, 0, 0, 0x42, 0x00, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::CallSs(CallSSTarget::FirstPlay { rsm_cell: 0x42 })
        );
    }

    #[test]
    fn decode_call_ss_vmgm_pgcn() {
        // selector 3, pgcn in bytes 2..3, rsm_cell in byte 4.
        let i = cmd([0x30, 0x08, 0x11, 0x22, 0x07, 0x30, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::CallSs(CallSSTarget::VmgmPgcn {
                pgcn: 0x1122,
                rsm_cell: 0x07,
            })
        );
    }

    // -----------------------------------------------------------------
    // Type 2 SetSystem family.
    // -----------------------------------------------------------------

    #[test]
    fn decode_set_stn_register_form() {
        // byte0=0x41 (type=2, direct=0, sub=1) — SetSTN register form.
        // af set (byte3 bit 7), audio_src=4 (byte3 low nibble).
        // sf set, subpic_src=5. nf cleared, angle_src=0.
        let i = cmd([0x41, 0x00, 0, 0x84, 0x85, 0x00, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetStn {
                direct: false,
                af: true,
                audio_src: 4,
                sf: true,
                subpic_src: 5,
                nf: false,
                angle_src: 0,
            }
        );
    }

    #[test]
    fn decode_set_stn_immediate_form() {
        // byte0=0x51 (type=2, direct=1, sub=1) — SetSTN immediate.
        // 7-bit aval/sval/nval span byte 3/4/5 low 7 bits; flags in
        // bit 7 of each.
        let i = cmd([0x51, 0x00, 0, 0x80 | 0x12, 0x80 | 0x34, 0x80 | 0x56, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetStn {
                direct: true,
                af: true,
                audio_src: 0x12,
                sf: true,
                subpic_src: 0x34,
                nf: true,
                angle_src: 0x56,
            }
        );
    }

    #[test]
    fn decode_set_nvtmr_register_form() {
        // byte0=0x42 (type=2, direct=0, sub=2) — SetNVTMR register.
        // src = GPRM 3 (byte3); pgcn = 0x1234 (bytes 4..5).
        let i = cmd([0x42, 0, 0, 0x03, 0x12, 0x34, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetNvtmr {
                src: Operand::Register(Register::Gprm(3)),
                pgcn: 0x1234,
            }
        );
    }

    #[test]
    fn decode_set_nvtmr_immediate_form() {
        // byte0=0x52 (direct, sub=2); immediate from bytes 2..3.
        let i = cmd([0x52, 0, 0xAA, 0xBB, 0x12, 0x34, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetNvtmr {
                src: Operand::Immediate(0xAABB),
                pgcn: 0x1234,
            }
        );
    }

    #[test]
    fn decode_set_gprmmd_with_counter() {
        // byte0=0x43 (register form, sub=3); src=GPRM 6 (byte3);
        // dst=GPRM 9 (byte5 low nibble); mf set (byte4 bit 7).
        let i = cmd([0x43, 0, 0, 0x06, 0x80, 0x09, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetGprmMd {
                src: Operand::Register(Register::Gprm(6)),
                dst: Register::Gprm(9),
                counter: true,
            }
        );
    }

    #[test]
    fn decode_set_amxmd_immediate() {
        // byte0=0x54 (direct, sub=4); imm = bytes 4..5.
        let i = cmd([0x54, 0, 0, 0, 0x01, 0x23, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetAmxMd {
                src: Operand::Immediate(0x0123),
            }
        );
    }

    #[test]
    fn decode_set_hlbtnn_register() {
        // byte0=0x46 (register, sub=6); src=GPRM 7 (byte5 low nibble).
        let i = cmd([0x46, 0, 0, 0, 0, 0x07, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::SetHlBtnn {
                src: Operand::Register(Register::Gprm(7)),
            }
        );
    }

    #[test]
    fn decode_setsystem_invalid_subcode() {
        // sub=5 is reserved per the SetSystem column.
        assert_eq!(
            cmd([0x45, 0, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Invalid
        );
    }

    // -----------------------------------------------------------------
    // Type 3 Set family.
    // -----------------------------------------------------------------

    #[test]
    fn decode_set_add_register_form() {
        // byte0=0x63 (type=3, direct=0, sub=3=add); dst=GPRM 4 (byte3
        // low nibble); src=GPRM 9 (byte5).
        let i = cmd([0x63, 0, 0, 0x04, 0, 0x09, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::Set {
                op: SetOp::Add,
                dst: Register::Gprm(4),
                src: Operand::Register(Register::Gprm(9)),
            }
        );
    }

    #[test]
    fn decode_set_mov_immediate_form() {
        // byte0=0x71 (type=3, direct=1, sub=1=mov); dst=GPRM 0; imm
        // from bytes 4..5.
        let i = cmd([0x71, 0, 0, 0x00, 0xFF, 0xEE, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::Set {
                op: SetOp::Mov,
                dst: Register::Gprm(0),
                src: Operand::Immediate(0xFFEE),
            }
        );
    }

    #[test]
    fn decode_set_invalid_subcode() {
        // sub = 0 (None) and sub = C..F → invalid.
        assert_eq!(
            cmd([0x60, 0, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Invalid
        );
        assert_eq!(
            cmd([0x6C, 0, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Invalid
        );
        assert_eq!(
            cmd([0x6F, 0, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Invalid
        );
    }

    #[test]
    fn decode_set_src_routes_to_sprm() {
        // Register-form, src byte = 0x82 → SPRM 2 (SPSTN).
        let i = cmd([0x61, 0, 0, 0x05, 0, 0x82, 0, 0]).decode();
        assert_eq!(
            i,
            NavInstruction::Set {
                op: SetOp::Mov,
                dst: Register::Gprm(5),
                src: Operand::Register(Register::Sprm(2)),
            }
        );
    }

    // -----------------------------------------------------------------
    // Types 4..6 compound classifiers + Type 7.
    // -----------------------------------------------------------------

    #[test]
    fn decode_type4_setclnk_full_operand_register_form() {
        // byte 0 = 0x83 → type=4, SET-dir=0, set-op=3 (Add).
        // byte 1 = 0x17 → CMP-dir=0, cmp-op=1 (BC), scr=GPRM 7.
        // byte 3 = 0x09 → SET-source register GPRM 9.
        // byte 5 = 0x84 → CMP-RHS register SPRM 4 (0x84 - 0x80).
        // byte 6 = 0x3C → hl_bn = 0x3C >> 2 = 0x0F.
        // byte 7 = 0x06 → Link subset LinkNextPG.
        let i = cmd([0x83, 0x17, 0x00, 0x09, 0x00, 0x84, 0x3C, 0x06]).decode();
        assert_eq!(
            i,
            NavInstruction::SetCLnk {
                set_op: SetOp::Add,
                cmp_op: CmpOp::Bc,
                scr: Register::Gprm(7),
                set_src: Operand::Register(Register::Gprm(9)),
                cmp_rhs: Operand::Register(Register::Sprm(4)),
                hl_bn: 0x0F,
                link: LinkSubset::LinkNextPG,
            }
        );
    }

    #[test]
    fn decode_type4_setclnk_immediate_forms() {
        // SET-dir=1, CMP-dir=1 → both operands immediate.
        // byte 0 = 0x93 → type=4, SET-dir=1, set-op=3 (Add).
        // byte 1 = 0x95 → CMP-dir=1, cmp-op=1 (BC), scr=GPRM 5.
        // bytes 2-3 = 0x1234 = sval. bytes 4-5 = 0x5678 = cval.
        // byte 6 = 0x04 → hl_bn = 1. byte 7 = 0x10 → Rsm.
        let i = cmd([0x93, 0x95, 0x12, 0x34, 0x56, 0x78, 0x04, 0x10]).decode();
        assert_eq!(
            i,
            NavInstruction::SetCLnk {
                set_op: SetOp::Add,
                cmp_op: CmpOp::Bc,
                scr: Register::Gprm(5),
                set_src: Operand::Immediate(0x1234),
                cmp_rhs: Operand::Immediate(0x5678),
                hl_bn: 1,
                link: LinkSubset::Rsm,
            }
        );
    }

    #[test]
    fn decode_type5_csetclnk_register_form() {
        // byte 0 = 0xA2 → type=5, SET-dir=0, set-op=2 (Swp).
        // byte 1 = 0x23 → CMP-dir=0, cmp-op=2 (Eq), sr1=GPRM 3.
        // byte 3 = 0x05 → SET-src register GPRM 5 (sr2).
        // byte 4 = 0x07 → CMP-LHS register GPRM 7 (cr1).
        // byte 5 = 0x08 → CMP-RHS register GPRM 8 (cr2).
        // byte 6 = 0x10 → hl_bn = 4. byte 7 = 0x09 → LinkTopPGC.
        let i = cmd([0xA2, 0x23, 0x00, 0x05, 0x07, 0x08, 0x10, 0x09]).decode();
        assert_eq!(
            i,
            NavInstruction::CSetCLnk {
                set_op: SetOp::Swp,
                cmp_op: CmpOp::Eq,
                sr1: Register::Gprm(3),
                set_src: Operand::Register(Register::Gprm(5)),
                cmp_lhs: Register::Gprm(7),
                cmp_rhs: Operand::Register(Register::Gprm(8)),
                hl_bn: 4,
                link: LinkSubset::LinkTopPGC,
            }
        );
    }

    #[test]
    fn decode_type5_csetclnk_set_immediate_form() {
        // SET-dir=1, CMP-dir=0 — row 95 — `sval2` at bytes 2..3.
        // byte 0 = 0xB1 → type=5, SET-dir=1, set-op=1 (Mov).
        // byte 1 = 0x22 → CMP-dir=0, cmp-op=2 (Eq), sr1=GPRM 2.
        let i = cmd([0xB1, 0x22, 0xAB, 0xCD, 0x06, 0x07, 0x00, 0x05]).decode();
        assert_eq!(
            i,
            NavInstruction::CSetCLnk {
                set_op: SetOp::Mov,
                cmp_op: CmpOp::Eq,
                sr1: Register::Gprm(2),
                set_src: Operand::Immediate(0xABCD),
                cmp_lhs: Register::Gprm(6),
                cmp_rhs: Operand::Register(Register::Gprm(7)),
                hl_bn: 0,
                link: LinkSubset::LinkTopPG,
            }
        );
    }

    #[test]
    fn decode_type5_set_dir_and_cmp_dir_both_set_is_invalid() {
        // Row 96: SET-dir=1 + CMP-dir=1 = "Illegal CSetCLnk" (red row).
        let i = cmd([0xB1, 0xA2, 0, 0, 0, 0, 0, 0]).decode();
        assert_eq!(i, NavInstruction::Invalid);
    }

    #[test]
    fn decode_type6_cmpsetlnk_register_form() {
        // byte 0 = 0xC4 → type=6, SET-dir=0, set-op=4 (Sub).
        // byte 1 = 0x71 → CMP-dir=0, cmp-op=7 (Lt), sr1=GPRM 1.
        // byte 3 = 0x06 → SET-src register GPRM 6 (srs).
        // byte 5 = 0x82 → CMP-RHS register SPRM 2 (cr2).
        // byte 6 = 0x08 → hl_bn = 2. byte 7 = 0x0A → LinkNextPGC.
        let i = cmd([0xC4, 0x71, 0x00, 0x06, 0x00, 0x82, 0x08, 0x0A]).decode();
        assert_eq!(
            i,
            NavInstruction::CmpSetLnk {
                set_op: SetOp::Sub,
                cmp_op: CmpOp::Lt,
                sr1: Register::Gprm(1),
                set_src: Operand::Register(Register::Gprm(6)),
                cmp_rhs: Operand::Register(Register::Sprm(2)),
                hl_bn: 2,
                link: LinkSubset::LinkNextPGC,
            }
        );
    }

    #[test]
    fn decode_type6_set_dir_and_cmp_dir_both_set_is_invalid() {
        // Row 101: SET-dir=1 + CMP-dir=1 = "Illegal CmpSetLnk".
        let i = cmd([0xD1, 0xA2, 0, 0, 0, 0, 0, 0]).decode();
        assert_eq!(i, NavInstruction::Invalid);
    }

    #[test]
    fn decode_type7_unknown() {
        // Any byte0 with top three bits = 7 → Unknown.
        assert_eq!(
            cmd([0xE0, 0, 0, 0, 0, 0, 0, 0]).decode(),
            NavInstruction::Unknown
        );
        assert_eq!(
            cmd([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).decode(),
            NavInstruction::Unknown
        );
    }

    // -----------------------------------------------------------------
    // Round-trip integration — a NavCommand sourced from PgcCommandTable.
    // -----------------------------------------------------------------

    #[test]
    fn decoded_from_navcommand_default() {
        // Default NavCommand (all zeros) decodes to NOP — the
        // canonical no-op encoding per the spec's first row.
        let nc = NavCommand::default();
        assert_eq!(nc.decode(), NavInstruction::Nop);
    }
}