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
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
//! IFO body parser — Video Manager Information (VMGI), Video Title
//! Set Information (VTSI), Program Chain Information (PGCI), Title
//! Search Pointer Table (TT_SRPT), Part-of-Title Search Pointer Table
//! (VTS_PTT_SRPT), Cell Address Table (VTS_C_ADT).
//!
//! Phase 2: structural decoding of the IFO files only — title list,
//! chapter list, program-chain layout, cell sector ranges. No VOB
//! demuxing, no cell concatenation, no virtual-machine command
//! execution, no playback. Those are Phase 3.
//!
//! ## Sector / byte addressing convention
//!
//! IFO files are sequences of 2048-byte logical sectors. Field
//! offsets in `VMGI_MAT` / `VTSI_MAT` that are described as "sector
//! pointers" are sector indexes **relative to the start of the IFO
//! file**, not absolute disc-LBA values. The "start sector" fields
//! inside `TT_SRPT` entries, by contrast, are absolute disc LBAs
//! (referenced to the whole disc, where `VIDEO_TS.IFO` lives at LBA
//! 0 of that title set).
//!
//! All multi-byte integer fields are big-endian (network byte order).
//!
//! ## Clean-room references
//!
//! Material consulted while writing this module:
//!
//! - `docs/container/dvd/application/mpucoder-ifo.html`
//!   (VMGI_MAT / VTSI_MAT field layout, sector-pointer offsets,
//!   C_ADT / VOBU_ADMAP entry format).
//! - `docs/container/dvd/application/mpucoder-ifo_vmg.html`
//!   (TT_SRPT, VMGM_PGCI_UT, VMG_PTL_MAIT, VMG_VTS_ATRT).
//! - `docs/container/dvd/application/mpucoder-ifo_vts.html`
//!   (VTS_PTT_SRPT, VTS_PGCI, VTSM_PGCI_UT, VTS_TMAPTI).
//! - `docs/container/dvd/application/mpucoder-pgc.html`
//!   (PGC header at offset 0..0xEC, command table, program map,
//!   cell playback information table, cell position information).
//! - `docs/container/dvd/application/stnsoft-vmindx.html`
//!   (cross-reference for VTS_C_ADT entry layout).
//!
//! Field layouts derive from the
//! `docs/container/dvd/application/` references listed above.

use crate::error::{Error, Result};

/// Logical-sector size on a DVD-ROM (per ECMA-267 §1.7).
pub const DVD_SECTOR: usize = 2048;

/// Magic at byte 0 of `VIDEO_TS.IFO`.
pub const VMG_MAGIC: &[u8; 12] = b"DVDVIDEO-VMG";

/// Magic at byte 0 of `VTS_xx_0.IFO`.
pub const VTS_MAGIC: &[u8; 12] = b"DVDVIDEO-VTS";

// ------------------------------------------------------------------
// Common helpers
// ------------------------------------------------------------------

fn read_u16(buf: &[u8], off: usize) -> Result<u16> {
    let slice = buf
        .get(off..off + 2)
        .ok_or(Error::InvalidUdf("ifo: u16 read past end"))?;
    Ok(u16::from_be_bytes([slice[0], slice[1]]))
}

fn read_u32(buf: &[u8], off: usize) -> Result<u32> {
    let slice = buf
        .get(off..off + 4)
        .ok_or(Error::InvalidUdf("ifo: u32 read past end"))?;
    Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}

fn read_u8(buf: &[u8], off: usize) -> Result<u8> {
    buf.get(off)
        .copied()
        .ok_or(Error::InvalidUdf("ifo: u8 read past end"))
}

// ------------------------------------------------------------------
// PgcTime — BCD playback time + frame-rate bits
// ------------------------------------------------------------------

/// Playback time field used by `PGC_GI` and per-cell `C_PBI` entries.
///
/// Layout per mpucoder-pgc.html: 4 bytes — `hh:mm:ss:ff` in BCD, with
/// bits 7 & 6 of the last byte encoding the frame rate. `11b` = 30 fps
/// (NTSC drop / non-drop), `01b` = 25 fps (PAL). `10b` and `00b` are
/// declared illegal by the spec — we surface them as
/// [`FrameRate::Illegal`] rather than rejecting outright since some
/// authoring tools emit zero-time placeholder fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PgcTime {
    pub hours: u8,
    pub minutes: u8,
    pub seconds: u8,
    pub frames: u8,
    pub frame_rate: FrameRate,
}

/// Frame-rate encoding used by [`PgcTime`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameRate {
    /// `00b` — illegal per spec, but present in some authoring outputs.
    Illegal,
    /// `01b` — 25 fps (PAL).
    Pal25,
    /// `10b` — illegal per spec.
    Reserved,
    /// `11b` — 30 fps (NTSC; the spec lumps drop/non-drop together).
    Ntsc30,
}

impl PgcTime {
    /// Decode a 4-byte BCD playback time field.
    pub fn from_bytes(bytes: [u8; 4]) -> Self {
        fn bcd(b: u8) -> u8 {
            ((b >> 4) & 0x0F) * 10 + (b & 0x0F)
        }
        let hours = bcd(bytes[0]);
        let minutes = bcd(bytes[1]);
        let seconds = bcd(bytes[2]);
        // Frames byte: bits 7+6 = frame-rate; bits 5..0 = BCD frames.
        // Per mpucoder-pgc.html the frames nibble pair is itself BCD,
        // but only the low 6 bits encode frames (so the tens digit is
        // 0..3, sufficient for max 29 frames at 30 fps).
        let frame_rate = match (bytes[3] >> 6) & 0x03 {
            0b00 => FrameRate::Illegal,
            0b01 => FrameRate::Pal25,
            0b10 => FrameRate::Reserved,
            0b11 => FrameRate::Ntsc30,
            _ => unreachable!(),
        };
        let f_lo = bytes[3] & 0x0F;
        let f_hi = (bytes[3] >> 4) & 0x03;
        let frames = f_hi * 10 + f_lo;
        Self {
            hours,
            minutes,
            seconds,
            frames,
            frame_rate,
        }
    }

    /// Total integer seconds (frames truncated, frame-rate ignored).
    /// Convenient when callers just need a "ballpark length" without
    /// the per-frame rounding.
    pub fn total_seconds(self) -> u32 {
        u32::from(self.hours) * 3600 + u32::from(self.minutes) * 60 + u32::from(self.seconds)
    }

    /// Convert this BCD field to absolute nanoseconds.
    ///
    /// `hh:mm:ss` resolves to whole seconds via [`Self::total_seconds`],
    /// then the `frames` count is scaled by the per-rate frame period
    /// (33,333,333 ns at 30 fps, 40,000,000 ns at 25 fps). Rational
    /// arithmetic — `(frames * 1e9) / fps` — caps the per-call truncation
    /// at ±1 ns instead of accumulating ~5e-9 per frame.
    ///
    /// Spec-`Illegal` and reserved-`10b` frame-rate codes contribute
    /// only the whole-second portion; the fractional frames are
    /// dropped because the spec defines no rate to scale them by.
    /// This keeps a malformed BCD field from poisoning a chapter
    /// length with a wildly-wrong scaled value, while still letting a
    /// caller surface a "best-effort" duration.
    ///
    /// Layout per `mpucoder-pgc.html` (PgcTime) and
    /// `mpucoder-dsi_pkt.html` `c_eltm` (same BCD shape).
    pub fn to_nanoseconds(self) -> u64 {
        let secs = u64::from(self.total_seconds());
        let secs_ns = secs.saturating_mul(1_000_000_000);
        let frames_ns = match self.frame_rate {
            FrameRate::Ntsc30 => u64::from(self.frames).saturating_mul(1_000_000_000) / 30,
            FrameRate::Pal25 => u64::from(self.frames).saturating_mul(1_000_000_000) / 25,
            FrameRate::Illegal | FrameRate::Reserved => 0,
        };
        secs_ns.saturating_add(frames_ns)
    }
}

// ------------------------------------------------------------------
// VMGI_MAT — Video Manager Information Management Table
// ------------------------------------------------------------------

/// Parsed VMGI_MAT (the first 0x200 bytes of `VIDEO_TS.IFO`).
///
/// Fields are surfaced in the order they appear in mpucoder-ifo.html's
/// "VMG IFO Contents" column. Sector-pointer fields are kept as-is
/// (`0` denotes "table absent" per spec).
#[derive(Debug, Clone)]
pub struct VmgIfo {
    /// Last sector of the VMG set (last sector of `VIDEO_TS.BUP`).
    pub last_sector_vmg_set: u32,
    /// Last sector of `VIDEO_TS.IFO`.
    pub last_sector_ifo: u32,
    /// VMGI version number, packed as `(major << 4) | minor` in the
    /// low byte of a 16-bit BE field (mpucoder-ifo.html "Version
    /// Number"). DVD-Video is typically `0x10` (1.0) or `0x11` (1.1).
    pub version: u16,
    /// VMG category (region mask in byte 1; rest reserved).
    pub vmg_category: u32,
    /// Number of volumes in this title set (e.g. 1 for single-volume
    /// discs; >1 for jukebox-style multi-side authoring).
    pub number_of_volumes: u16,
    /// Volume number (1-based) within the set above.
    pub volume_number: u16,
    /// Side ID (0 = side A, 1 = side B for double-sided discs).
    pub side_id: u8,
    /// Number of Video Title Sets (1..=99).
    pub number_of_title_sets: u16,
    /// Provider ID (32 ASCII bytes, NUL-padded).
    pub provider_id: String,
    /// Last byte address of `VMGI_MAT` itself.
    pub vmgi_mat_end: u32,
    /// Start address (byte offset) of First-Play PGC. `0` if absent.
    pub fp_pgc_addr: u32,
    /// Sector pointer to the VMG menu VOB (`0` if no menu).
    pub menu_vob_sector: u32,
    /// Sector pointer to TT_SRPT. Mandatory; always non-zero on a
    /// well-formed disc.
    pub tt_srpt_sector: u32,
    /// Sector pointer to VMGM_PGCI_UT. `0` if no VMG menu.
    pub vmgm_pgci_ut_sector: u32,
    /// Sector pointer to VMG_PTL_MAIT. `0` if no parental management.
    pub ptl_mait_sector: u32,
    /// Sector pointer to VMG_VTS_ATRT.
    pub vts_atrt_sector: u32,
    /// Sector pointer to VMG_TXTDT_MG (disc text data). `0` if absent.
    pub txtdt_mg_sector: u32,
    /// Sector pointer to VMGM_C_ADT (menu cell address table).
    pub vmgm_c_adt_sector: u32,
    /// Sector pointer to VMGM_VOBU_ADMAP (menu VOBU address map).
    pub vmgm_vobu_admap_sector: u32,
    /// VMGM (First-Play / VMG menu) stream attributes at
    /// 0x0100..0x015C. Empty when the buffer was too short to
    /// cover that region.
    pub menu_attributes: MenuAttributes,
}

impl VmgIfo {
    /// Parse a `VIDEO_TS.IFO` byte buffer. The buffer must cover at
    /// least the VMGI_MAT region (the first 0x200 bytes).
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 0x200 {
            return Err(Error::InvalidUdf("VMGI_MAT: buffer shorter than 0x200"));
        }
        if &buf[0..12] != VMG_MAGIC {
            return Err(Error::InvalidUdf("VMGI_MAT: bad magic"));
        }
        let last_sector_vmg_set = read_u32(buf, 0x000C)?;
        let last_sector_ifo = read_u32(buf, 0x001C)?;
        let version = read_u16(buf, 0x0020)?;
        let vmg_category = read_u32(buf, 0x0022)?;
        let number_of_volumes = read_u16(buf, 0x0026)?;
        let volume_number = read_u16(buf, 0x0028)?;
        let side_id = read_u8(buf, 0x002A)?;
        let number_of_title_sets = read_u16(buf, 0x003E)?;
        let provider_id_raw = &buf[0x0040..0x0060];
        let provider_id = decode_ascii_trim(provider_id_raw);
        let vmgi_mat_end = read_u32(buf, 0x0080)?;
        let fp_pgc_addr = read_u32(buf, 0x0084)?;
        let menu_vob_sector = read_u32(buf, 0x00C0)?;
        let tt_srpt_sector = read_u32(buf, 0x00C4)?;
        let vmgm_pgci_ut_sector = read_u32(buf, 0x00C8)?;
        let ptl_mait_sector = read_u32(buf, 0x00CC)?;
        let vts_atrt_sector = read_u32(buf, 0x00D0)?;
        let txtdt_mg_sector = read_u32(buf, 0x00D4)?;
        let vmgm_c_adt_sector = read_u32(buf, 0x00D8)?;
        let vmgm_vobu_admap_sector = read_u32(buf, 0x00DC)?;
        let menu_attributes = parse_menu_attribute_block(buf, 0x0100)?;

        Ok(Self {
            last_sector_vmg_set,
            last_sector_ifo,
            version,
            vmg_category,
            number_of_volumes,
            volume_number,
            side_id,
            number_of_title_sets,
            provider_id,
            vmgi_mat_end,
            fp_pgc_addr,
            menu_vob_sector,
            tt_srpt_sector,
            vmgm_pgci_ut_sector,
            ptl_mait_sector,
            vts_atrt_sector,
            txtdt_mg_sector,
            vmgm_c_adt_sector,
            vmgm_vobu_admap_sector,
            menu_attributes,
        })
    }
}

fn decode_ascii_trim(buf: &[u8]) -> String {
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8_lossy(&buf[..end]).trim_end().to_string()
}

// ------------------------------------------------------------------
// TT_SRPT — Title Search Pointer Table (VMG-side)
// ------------------------------------------------------------------

/// One entry of the VMG-side TT_SRPT (title search pointer table).
///
/// Per mpucoder-ifo_vmg.html "TT_SRPT" each entry is 12 bytes and
/// indexes the disc-global "title number" to the (title-set, title-
/// in-title-set) pair plus the VTS's start sector on the disc.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DvdTitleEntry {
    /// Title type byte (jump/link/call permission bits — see spec).
    pub title_type: u8,
    /// Number of angles (1..=9).
    pub angle_count: u8,
    /// Number of chapters / parts-of-title (PTTs) in this title.
    pub chapter_count: u16,
    /// Parental management mask (16-bit; bit N set = blocked at level N).
    pub parental_mask: u16,
    /// VTS number (1..=99) this title lives in.
    pub vts_number: u8,
    /// Title number within that VTS.
    pub vts_title_number: u8,
    /// Start sector of the VTS (whole-disc-relative LBA).
    pub vts_start_sector: u32,
}

impl DvdTitleEntry {
    /// 2-bit UOP-prohibition subset packed into the low bits of
    /// [`Self::title_type`].
    ///
    /// Per `docs/container/dvd/application/mpucoder-uops.html`,
    /// TT_SRPT carries only UOP-0 (`TimePlayOrSearch`) and UOP-1
    /// (`PttPlayOrSearch`); they live in the two low bits of
    /// `title_type`. The remaining `title_type` bits encode the
    /// title's jump/link/call permission flags per
    /// `mpucoder-ifo_vmg.html` and stay outside the UOP surface.
    #[inline]
    pub fn uop_mask(&self) -> crate::uops::UopMask {
        crate::uops::title_type_uop_mask(self.title_type)
    }

    /// `true` when `op` is **not** prohibited at the TT_SRPT level
    /// for this title. Only the two TT_SRPT-applicable ops
    /// (`TimePlayOrSearch`, `PttPlayOrSearch`) ever yield a `false`
    /// here; every other op returns `true` because TT_SRPT has no
    /// bit to encode them. The PGC-level and PCI-VOBU-level masks
    /// still need to be consulted via
    /// [`crate::uops::UopMask::merge_or`].
    #[inline]
    pub fn is_user_op_allowed(&self, op: crate::uops::UserOp) -> bool {
        self.uop_mask().is_allowed(op)
    }
}

/// Parsed TT_SRPT body — 8-byte header plus N × 12-byte entries.
#[derive(Debug, Clone)]
pub struct TtSrpt {
    /// Number of titles (= entry count).
    pub title_count: u16,
    /// `end_address` field (last byte of last entry, relative to TT_SRPT start).
    pub end_address: u32,
    /// Parsed entries.
    pub entries: Vec<DvdTitleEntry>,
}

impl TtSrpt {
    /// Parse a TT_SRPT byte buffer. Buffer must include the 8-byte
    /// header and at least `title_count * 12` entry bytes.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("TT_SRPT: shorter than 8-byte header"));
        }
        let title_count = read_u16(buf, 0)?;
        let end_address = read_u32(buf, 4)?;
        let needed = 8usize.saturating_add(usize::from(title_count) * 12);
        if buf.len() < needed {
            return Err(Error::InvalidUdf(
                "TT_SRPT: buffer shorter than title_count*12",
            ));
        }
        let mut entries = Vec::with_capacity(usize::from(title_count));
        for i in 0..usize::from(title_count) {
            let base = 8 + i * 12;
            entries.push(DvdTitleEntry {
                title_type: read_u8(buf, base)?,
                angle_count: read_u8(buf, base + 1)?,
                chapter_count: read_u16(buf, base + 2)?,
                parental_mask: read_u16(buf, base + 4)?,
                vts_number: read_u8(buf, base + 6)?,
                vts_title_number: read_u8(buf, base + 7)?,
                vts_start_sector: read_u32(buf, base + 8)?,
            });
        }
        Ok(Self {
            title_count,
            end_address,
            entries,
        })
    }
}

// ------------------------------------------------------------------
// Stream attribute extension blocks
//
// mpucoder-ifo.html documents a shared attribute layout that lives
// at fixed offsets inside both `VMGI_MAT` (one block at 0x0100..
// 0x015C covering the VMGM menu VOBS) and `VTSI_MAT` (the menu
// block at 0x0100..0x015C plus the title-content block at 0x0200..
// 0x0318 plus the 8×24-byte multichannel-extension table at
// 0x0318..0x03D8). Each block is a self-contained `(video, audio
// list, sub-picture list)` triple; the multichannel-extension
// table is karaoke-only and only present on the VTS title side.
// ------------------------------------------------------------------

/// MPEG coding mode field of `<a name="vidatt">video attributes</a>`.
/// (mpucoder-ifo.html byte 0 bits 7..6 of the 2-byte video-attr field.)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoCodingMode {
    Mpeg1,
    Mpeg2,
}

/// Display standard — bits 5..4 of byte 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoStandard {
    Ntsc,
    Pal,
}

/// Display aspect ratio — bits 3..2 of byte 0. The "1" and "2"
/// values are reserved by the spec; we surface them as
/// [`VideoAspectRatio::Reserved`] rather than rejecting outright.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoAspectRatio {
    /// `00b` — 4:3 frame, no display-mode pulldown.
    Ratio4x3,
    /// `11b` — 16:9 frame, anamorphic or letterboxed delivery.
    Ratio16x9,
    /// `01b` / `10b` — reserved by the spec.
    Reserved(u8),
}

/// Decoded NTSC / PAL pixel resolution — byte 1 bits 5..3 of the
/// 2-byte video-attr field. The spec encodes resolution as a 3-bit
/// index whose meaning depends on the standard byte; we resolve it
/// to absolute pixel dimensions for the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoResolution {
    /// Full-D1 — `0` index. 720×480 (NTSC) / 720×576 (PAL).
    FullD1,
    /// Three-quarter D1 — `1` index. 704×480 (NTSC) / 704×576 (PAL).
    ThreeQuarterD1,
    /// Half-D1 — `2` index. 352×480 (NTSC) / 352×576 (PAL).
    HalfD1,
    /// SIF — `3` index. 352×240 (NTSC) / 352×288 (PAL).
    Sif,
    /// `4..=7` — reserved by the spec.
    Reserved(u8),
}

impl VideoResolution {
    /// Decoded `(width, height)` in pixels for this resolution code +
    /// the parent's `VideoStandard`. Returns `None` for reserved
    /// codes (caller can fall back to the raw resolution index from
    /// [`VideoAttributes::resolution_code`]).
    pub fn dimensions(self, standard: VideoStandard) -> Option<(u16, u16)> {
        let h = match standard {
            VideoStandard::Ntsc => 480,
            VideoStandard::Pal => 576,
        };
        let w = match self {
            VideoResolution::FullD1 => 720,
            VideoResolution::ThreeQuarterD1 => 704,
            VideoResolution::HalfD1 => 352,
            VideoResolution::Sif => 352,
            VideoResolution::Reserved(_) => return None,
        };
        let h = if matches!(self, VideoResolution::Sif) && matches!(standard, VideoStandard::Ntsc) {
            240
        } else if matches!(self, VideoResolution::Sif) && matches!(standard, VideoStandard::Pal) {
            288
        } else {
            h
        };
        Some((w, h))
    }
}

/// Decoded 2-byte VMGM / VTSM / VTS video-attribute field.
///
/// mpucoder-ifo.html "Video Attributes" lays the field out as:
///
/// ```text
///   byte 0:
///     bit 7..6  coding mode (00=MPEG-1, 01=MPEG-2)
///     bit 5..4  standard (00=NTSC, 01=PAL)
///     bit 3..2  aspect ratio (00=4:3, 11=16:9, 01/10 reserved)
///     bit 1     1 = automatic pan/scan disallowed
///     bit 0     1 = automatic letterbox disallowed
///   byte 1:
///     bit 7     CC for line 21 field 1 in GOP (NTSC only)
///     bit 6     CC for line 21 field 2 in GOP (NTSC only)
///     bit 5..3  resolution index (see VideoResolution)
///     bit 2     1 = letterboxed source
///     bit 1     reserved
///     bit 0     PAL only: 0 = camera, 1 = film
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VideoAttributes {
    /// Raw 2-byte field, kept for fidelity / round-trip diagnostics.
    pub raw: [u8; 2],
    pub coding_mode: VideoCodingMode,
    pub standard: VideoStandard,
    pub aspect_ratio: VideoAspectRatio,
    /// `true` when `byte0 bit 1` is set — pan/scan delivery
    /// disabled at the disc level even for 4:3 displays.
    pub pan_scan_disallowed: bool,
    /// `true` when `byte0 bit 0` is set — letterbox delivery
    /// disabled at the disc level.
    pub letterbox_disallowed: bool,
    /// `true` when `byte1 bit 7` is set — line-21 closed captioning
    /// is present on field 1 of every GOP (NTSC only; ignored on PAL).
    pub line21_field1_cc: bool,
    /// `true` when `byte1 bit 6` is set — closed captioning on field 2.
    pub line21_field2_cc: bool,
    /// Raw 3-bit resolution index — see [`VideoResolution`] for the
    /// decoded form.
    pub resolution_code: u8,
    pub resolution: VideoResolution,
    /// `true` when the source itself is letterboxed (separate from
    /// the delivery-mode "letterbox disallowed" bit).
    pub letterboxed_source: bool,
    /// PAL-only: `false` = camera-captured, `true` = film-source
    /// (progressive at 24 fps, telecined to 25 fps). Always `false`
    /// on NTSC.
    pub film_source_pal: bool,
}

impl VideoAttributes {
    /// Parse a 2-byte video-attribute field.
    pub fn parse(buf: &[u8; 2]) -> Self {
        let b0 = buf[0];
        let b1 = buf[1];
        let coding_mode = match (b0 >> 6) & 0b11 {
            0 => VideoCodingMode::Mpeg1,
            _ => VideoCodingMode::Mpeg2,
        };
        let standard = match (b0 >> 4) & 0b11 {
            0 => VideoStandard::Ntsc,
            _ => VideoStandard::Pal,
        };
        let aspect_ratio = match (b0 >> 2) & 0b11 {
            0 => VideoAspectRatio::Ratio4x3,
            3 => VideoAspectRatio::Ratio16x9,
            x => VideoAspectRatio::Reserved(x),
        };
        let resolution_code = (b1 >> 3) & 0b111;
        let resolution = match resolution_code {
            0 => VideoResolution::FullD1,
            1 => VideoResolution::ThreeQuarterD1,
            2 => VideoResolution::HalfD1,
            3 => VideoResolution::Sif,
            x => VideoResolution::Reserved(x),
        };
        Self {
            raw: *buf,
            coding_mode,
            standard,
            aspect_ratio,
            pan_scan_disallowed: (b0 & 0b0000_0010) != 0,
            letterbox_disallowed: (b0 & 0b0000_0001) != 0,
            line21_field1_cc: (b1 & 0b1000_0000) != 0,
            line21_field2_cc: (b1 & 0b0100_0000) != 0,
            resolution_code,
            resolution,
            letterboxed_source: (b1 & 0b0000_0100) != 0,
            film_source_pal: (b1 & 0b0000_0001) != 0,
        }
    }
}

/// Audio coding mode — byte 0 bits 7..5 of the 8-byte audio-attr
/// field. `0` = AC-3, `2` = MPEG-1, `3` = MPEG-2 extended, `4` = LPCM,
/// `6` = DTS. Codes `1`, `5`, `7` are reserved by the spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioCodingMode {
    Ac3,
    Mpeg1,
    Mpeg2Ext,
    Lpcm,
    Dts,
    Reserved(u8),
}

/// Application mode — byte 0 bits 1..0. `0` = unspecified,
/// `1` = karaoke (multichannel extension applies), `2` = surround
/// (Dolby-Surround-suitable bit lives in byte 7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioApplicationMode {
    Unspecified,
    Karaoke,
    Surround,
    Reserved(u8),
}

/// Audio quantization / dynamic-range-control field — byte 1 bits
/// 7..6. The interpretation switches with the coding mode:
/// LPCM uses the field as a sample-depth selector (16 / 20 / 24 bps),
/// MPEG-1/2 uses it as a DRC flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioQuantizationDrc {
    /// LPCM-only: 16 bps per sample.
    Lpcm16,
    /// LPCM-only: 20 bps per sample.
    Lpcm20,
    /// LPCM-only: 24 bps per sample.
    Lpcm24,
    /// MPEG-only: dynamic-range control absent.
    NoDrc,
    /// MPEG-only: dynamic-range control present.
    Drc,
    /// Field present but caller didn't supply the coding mode
    /// hint — surface the raw 2-bit value.
    Raw(u8),
}

/// Language type — byte 0 bits 3..2. `0` = unspecified (bytes 2..=4
/// reserved), `1` = ISO-639 language code present in bytes 2..=4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioLanguageType {
    Unspecified,
    Iso639,
    Reserved(u8),
}

/// Decoded 8-byte audio-attribute field.
///
/// Layout per mpucoder-ifo.html "Audio Attributes":
///
/// ```text
///   byte 0:
///     bit 7..5  coding mode (0=AC3, 2=MPEG-1, 3=MPEG-2ext, 4=LPCM, 6=DTS)
///     bit 4     multichannel-extension present (karaoke)
///     bit 3..2  language type (0=unspecified, 1=ISO-639 in bytes 2..=4)
///     bit 1..0  application mode (0=unspec, 1=karaoke, 2=surround)
///   byte 1:
///     bit 7..6  quantization / DRC (interpretation switches on coding mode)
///     bit 5..4  sample-rate selector (only `0` = 48 kHz defined)
///     bit 3     reserved
///     bit 2..0  channels - 1   (so `1` = stereo, `5` = 5.1)
///   bytes 2..=3:  ISO-639 two-letter language code (if `language_type == Iso639`)
///   byte 4:       reserved for language-code extension
///   byte 5:       code-extension byte — `0..=4` per `SPRM #17`
///   byte 6:       reserved
///   byte 7:       Application-information byte (karaoke channel
///                 assignment or surround Dolby-suitable bit, per
///                 the application mode)
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AudioAttributes {
    pub raw: [u8; 8],
    pub coding_mode: AudioCodingMode,
    /// `true` when the karaoke multichannel-extension entry for this
    /// stream is populated. Always `false` outside karaoke titles.
    pub multichannel_extension_present: bool,
    pub language_type: AudioLanguageType,
    pub application_mode: AudioApplicationMode,
    pub quantization: AudioQuantizationDrc,
    /// Sample-rate index (only `0` = 48 kHz is defined; any other
    /// value is reserved).
    pub sample_rate_code: u8,
    /// Channel count, post-decoding the `channels - 1` field.
    pub channel_count: u8,
    /// Two-character ISO-639 language code, or empty when
    /// `language_type` is `Unspecified`.
    pub language_code: [u8; 2],
    pub code_extension: u8,
    /// Raw application-information byte at offset 7. Karaoke and
    /// surround application modes both pack secondary flags in here;
    /// callers can decode them with the helpers below.
    pub application_info: u8,
}

impl AudioAttributes {
    /// Parse an 8-byte audio-attribute field.
    pub fn parse(buf: &[u8; 8]) -> Self {
        let b0 = buf[0];
        let b1 = buf[1];
        let coding_mode_raw = (b0 >> 5) & 0b111;
        let coding_mode = match coding_mode_raw {
            0 => AudioCodingMode::Ac3,
            2 => AudioCodingMode::Mpeg1,
            3 => AudioCodingMode::Mpeg2Ext,
            4 => AudioCodingMode::Lpcm,
            6 => AudioCodingMode::Dts,
            x => AudioCodingMode::Reserved(x),
        };
        let language_type = match (b0 >> 2) & 0b11 {
            0 => AudioLanguageType::Unspecified,
            1 => AudioLanguageType::Iso639,
            x => AudioLanguageType::Reserved(x),
        };
        let application_mode = match b0 & 0b11 {
            0 => AudioApplicationMode::Unspecified,
            1 => AudioApplicationMode::Karaoke,
            2 => AudioApplicationMode::Surround,
            x => AudioApplicationMode::Reserved(x),
        };
        let quant_raw = (b1 >> 6) & 0b11;
        let quantization = match coding_mode {
            AudioCodingMode::Lpcm => match quant_raw {
                0 => AudioQuantizationDrc::Lpcm16,
                1 => AudioQuantizationDrc::Lpcm20,
                2 => AudioQuantizationDrc::Lpcm24,
                _ => AudioQuantizationDrc::Raw(quant_raw),
            },
            AudioCodingMode::Mpeg1 | AudioCodingMode::Mpeg2Ext => match quant_raw {
                0 => AudioQuantizationDrc::NoDrc,
                1 => AudioQuantizationDrc::Drc,
                _ => AudioQuantizationDrc::Raw(quant_raw),
            },
            _ => AudioQuantizationDrc::Raw(quant_raw),
        };
        Self {
            raw: *buf,
            coding_mode,
            multichannel_extension_present: (b0 & 0b0001_0000) != 0,
            language_type,
            application_mode,
            quantization,
            sample_rate_code: (b1 >> 4) & 0b11,
            channel_count: (b1 & 0b0000_0111).saturating_add(1),
            language_code: [buf[2], buf[3]],
            code_extension: buf[5],
            application_info: buf[7],
        }
    }

    /// Decoded sample rate in hertz. Returns `Some(48_000)` for
    /// `sample_rate_code == 0` (the only defined value) and `None`
    /// for the reserved codes.
    pub fn sample_rate_hz(self) -> Option<u32> {
        match self.sample_rate_code {
            0 => Some(48_000),
            _ => None,
        }
    }

    /// Surround application mode only: `true` when byte 7 bit 3 is
    /// set (Dolby-Surround-decodable downmix). Always `false`
    /// outside `AudioApplicationMode::Surround`.
    pub fn dolby_surround_suitable(self) -> bool {
        matches!(self.application_mode, AudioApplicationMode::Surround)
            && (self.application_info & 0b0000_1000) != 0
    }

    /// Karaoke application mode only — channel-assignment index
    /// from byte 7 bits 6..4. The spec maps:
    /// `2` = 2/0 L,R / `3` = 3/0 L,M,R / `4` = 2/1 L,R,V1 /
    /// `5` = 3/1 L,M,R,V1 / `6` = 2/2 L,R,V1,V2 / `7` = 3/2 L,M,R,V1,V2.
    /// `0` and `1` are flagged "not valid" by the spec.
    pub fn karaoke_channel_assignment(self) -> Option<u8> {
        if matches!(self.application_mode, AudioApplicationMode::Karaoke) {
            Some((self.application_info >> 4) & 0b0000_0111)
        } else {
            None
        }
    }

    /// Karaoke version index — byte 7 bits 3..2.
    pub fn karaoke_version(self) -> Option<u8> {
        if matches!(self.application_mode, AudioApplicationMode::Karaoke) {
            Some((self.application_info >> 2) & 0b11)
        } else {
            None
        }
    }

    /// Karaoke MC-intro flag — byte 7 bit 1.
    pub fn karaoke_mc_intro_present(self) -> Option<bool> {
        if matches!(self.application_mode, AudioApplicationMode::Karaoke) {
            Some((self.application_info & 0b10) != 0)
        } else {
            None
        }
    }

    /// Karaoke solo / duet flag — byte 7 bit 0 (`0` = solo, `1` = duet).
    pub fn karaoke_duet(self) -> Option<bool> {
        if matches!(self.application_mode, AudioApplicationMode::Karaoke) {
            Some((self.application_info & 0b01) != 0)
        } else {
            None
        }
    }
}

/// Sub-picture coding mode — byte 0 bits 7..5 of the 6-byte sub-
/// picture-attribute field. Only `0` (2-bit RLE) is defined.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubpictureCodingMode {
    Rle2Bit,
    Reserved(u8),
}

/// Language type — same as the audio variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubpictureLanguageType {
    Unspecified,
    Iso639,
    Reserved(u8),
}

/// Decoded 6-byte sub-picture attribute field.
///
/// Layout per mpucoder-ifo.html "Subpicture Attributes":
///
/// ```text
///   byte 0:
///     bit 7..5  coding mode (0 = 2-bit RLE)
///     bit 4..2  reserved
///     bit 1..0  language type
///   byte 1:     reserved
///   bytes 2..=3: ISO-639 two-letter language code
///   byte 4:     reserved for language-code extension
///   byte 5:     code extension — see SPRM #19
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubpictureAttributes {
    pub raw: [u8; 6],
    pub coding_mode: SubpictureCodingMode,
    pub language_type: SubpictureLanguageType,
    pub language_code: [u8; 2],
    pub code_extension: u8,
}

impl SubpictureAttributes {
    /// Parse a 6-byte sub-picture-attribute field.
    pub fn parse(buf: &[u8; 6]) -> Self {
        let b0 = buf[0];
        let coding_mode = match (b0 >> 5) & 0b111 {
            0 => SubpictureCodingMode::Rle2Bit,
            x => SubpictureCodingMode::Reserved(x),
        };
        let language_type = match b0 & 0b11 {
            0 => SubpictureLanguageType::Unspecified,
            1 => SubpictureLanguageType::Iso639,
            x => SubpictureLanguageType::Reserved(x),
        };
        Self {
            raw: *buf,
            coding_mode,
            language_type,
            language_code: [buf[2], buf[3]],
            code_extension: buf[5],
        }
    }
}

/// One 8-byte karaoke multichannel-extension entry, decoded per
/// mpucoder-ifo.html "MultiChannel Extension - Karaoke mode".
///
/// Bytes 0x05..=0x17 are reserved-zero and absorbed silently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct McExtensionEntry {
    pub raw: [u8; 8],
    /// Byte 0 bit 0 — guide melody on audio channel 0 of the
    /// downmix is present.
    pub ach0_guide_melody: bool,
    /// Byte 1 bit 0 — guide melody on audio channel 1.
    pub ach1_guide_melody: bool,
    /// Byte 2 bit 3 — guide vocal 1 on audio channel 2.
    pub ach2_guide_vocal_1: bool,
    /// Byte 2 bit 2 — guide vocal 2 on audio channel 2.
    pub ach2_guide_vocal_2: bool,
    /// Byte 2 bit 1 — guide melody 1 on audio channel 2.
    pub ach2_guide_melody_1: bool,
    /// Byte 2 bit 0 — guide melody 2 on audio channel 2.
    pub ach2_guide_melody_2: bool,
    /// Byte 3 bit 3 — guide vocal 1 on audio channel 3.
    pub ach3_guide_vocal_1: bool,
    /// Byte 3 bit 2 — guide vocal 2 on audio channel 3.
    pub ach3_guide_vocal_2: bool,
    /// Byte 3 bit 1 — guide melody A on audio channel 3.
    pub ach3_guide_melody_a: bool,
    /// Byte 3 bit 0 — sound effect A on audio channel 3.
    pub ach3_sound_effect_a: bool,
    /// Byte 4 bit 3 — guide vocal 1 on audio channel 4.
    pub ach4_guide_vocal_1: bool,
    /// Byte 4 bit 2 — guide vocal 2 on audio channel 4.
    pub ach4_guide_vocal_2: bool,
    /// Byte 4 bit 1 — guide melody B on audio channel 4.
    pub ach4_guide_melody_b: bool,
    /// Byte 4 bit 0 — sound effect B on audio channel 4.
    pub ach4_sound_effect_b: bool,
}

impl McExtensionEntry {
    /// Parse one 8-byte multichannel-extension entry. (The spec
    /// labels the entry's footprint as `8*24` bytes — actually 24
    /// entries × 8 bytes each — but each individual entry is 8
    /// bytes wide.)
    pub fn parse(buf: &[u8; 8]) -> Self {
        let b0 = buf[0];
        let b1 = buf[1];
        let b2 = buf[2];
        let b3 = buf[3];
        let b4 = buf[4];
        Self {
            raw: *buf,
            ach0_guide_melody: (b0 & 0b0000_0001) != 0,
            ach1_guide_melody: (b1 & 0b0000_0001) != 0,
            ach2_guide_vocal_1: (b2 & 0b0000_1000) != 0,
            ach2_guide_vocal_2: (b2 & 0b0000_0100) != 0,
            ach2_guide_melody_1: (b2 & 0b0000_0010) != 0,
            ach2_guide_melody_2: (b2 & 0b0000_0001) != 0,
            ach3_guide_vocal_1: (b3 & 0b0000_1000) != 0,
            ach3_guide_vocal_2: (b3 & 0b0000_0100) != 0,
            ach3_guide_melody_a: (b3 & 0b0000_0010) != 0,
            ach3_sound_effect_a: (b3 & 0b0000_0001) != 0,
            ach4_guide_vocal_1: (b4 & 0b0000_1000) != 0,
            ach4_guide_vocal_2: (b4 & 0b0000_0100) != 0,
            ach4_guide_melody_b: (b4 & 0b0000_0010) != 0,
            ach4_sound_effect_b: (b4 & 0b0000_0001) != 0,
        }
    }
}

// ------------------------------------------------------------------
// VTSI_MAT — Video Title Set Information Management Table
// ------------------------------------------------------------------

/// VMGM / VTSM-side menu-attribute block — video format plus the
/// audio + sub-picture stream lists for the menu VOBS.
///
/// `audio_streams` and `subpicture_streams` are populated to the
/// declared `number_of_*_streams` count (≤ 8 for audio per the
/// 8×8-byte attribute slot, ≤ 1 for sub-picture per the single
/// 6-byte slot). Any tail attribute slots beyond the declared
/// counts are ignored.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MenuAttributes {
    pub video: Option<VideoAttributes>,
    pub audio_streams: Vec<AudioAttributes>,
    pub subpicture_streams: Vec<SubpictureAttributes>,
}

/// VTS_VOBS-side title-attribute block — video format plus the
/// title audio (≤ 8) and sub-picture (≤ 32) stream lists, plus the
/// karaoke multichannel-extension table (24 × 8-byte entries; one
/// per audio stream slot, even for slots not populated).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TitleAttributes {
    pub video: Option<VideoAttributes>,
    pub audio_streams: Vec<AudioAttributes>,
    pub subpicture_streams: Vec<SubpictureAttributes>,
    /// Karaoke multichannel extension entries — populated when the
    /// buffer is long enough to cover offset 0x0318..0x03D8 of
    /// VTSI_MAT. Empty for non-karaoke titles and for buffers
    /// shorter than 0x03D8.
    pub multichannel_extension: Vec<McExtensionEntry>,
}

/// Parsed VTSI_MAT (the first 0x300 + audio/sub-picture extension
/// bytes of a `VTS_xx_0.IFO` file).
///
/// Like [`VmgIfo`], sector-pointer fields stay raw — `0` denotes
/// "absent".
#[derive(Debug, Clone)]
pub struct VtsiMat {
    /// Last sector of this title set (last sector of `VTS_xx_0.BUP`).
    pub last_sector_title_set: u32,
    /// Last sector of this IFO file (`VTS_xx_0.IFO`).
    pub last_sector_ifo: u32,
    /// Version number — see [`VmgIfo::version`].
    pub version: u16,
    /// VTS category (0 = unspecified, 1 = Karaoke).
    pub vts_category: u32,
    /// Last byte of the VTSI_MAT region.
    pub vtsi_mat_end: u32,
    /// Start sector of the menu VOB (`0` if no menu).
    pub menu_vob_sector: u32,
    /// Start sector of the title VOBs.
    pub title_vob_sector: u32,
    /// Sector pointer to VTS_PTT_SRPT.
    pub vts_ptt_srpt_sector: u32,
    /// Sector pointer to VTS_PGCI.
    pub vts_pgci_sector: u32,
    /// Sector pointer to VTSM_PGCI_UT (menu PGCI).
    pub vtsm_pgci_ut_sector: u32,
    /// Sector pointer to VTS_TMAPTI (time map table).
    pub vts_tmapti_sector: u32,
    /// Sector pointer to VTSM_C_ADT (menu cell address table).
    pub vtsm_c_adt_sector: u32,
    /// Sector pointer to VTSM_VOBU_ADMAP (menu VOBU address map).
    pub vtsm_vobu_admap_sector: u32,
    /// Sector pointer to VTS_C_ADT (title-set cell address table).
    pub vts_c_adt_sector: u32,
    /// Sector pointer to VTS_VOBU_ADMAP (title-set VOBU address map).
    pub vts_vobu_admap_sector: u32,
    /// VTSM (menu) stream attributes at 0x0100..0x015C. Empty
    /// when the buffer was too short to cover that region — the
    /// minimal buffer-length check is still `0x200` for backwards
    /// compatibility with the original sector-only parse.
    pub menu_attributes: MenuAttributes,
    /// VTS_VOBS (title-content) stream attributes at 0x0200..
    /// 0x03D8. Empty when the buffer was too short to cover that
    /// region.
    pub title_attributes: TitleAttributes,
}

impl VtsiMat {
    /// Parse a `VTS_xx_0.IFO` byte buffer. Buffer must cover at least
    /// the VTSI_MAT region (the first 0x200 bytes).
    ///
    /// Audio / sub-picture / multichannel attribute extension blocks
    /// are decoded opportunistically — fields populated up to the
    /// last full block the buffer covers, the rest stays empty.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 0x200 {
            return Err(Error::InvalidUdf("VTSI_MAT: buffer shorter than 0x200"));
        }
        if &buf[0..12] != VTS_MAGIC {
            return Err(Error::InvalidUdf("VTSI_MAT: bad magic"));
        }
        let menu_attributes = parse_menu_attribute_block(buf, 0x0100)?;
        let title_attributes = parse_title_attribute_block(buf)?;
        Ok(Self {
            last_sector_title_set: read_u32(buf, 0x000C)?,
            last_sector_ifo: read_u32(buf, 0x001C)?,
            version: read_u16(buf, 0x0020)?,
            vts_category: read_u32(buf, 0x0022)?,
            vtsi_mat_end: read_u32(buf, 0x0080)?,
            menu_vob_sector: read_u32(buf, 0x00C0)?,
            title_vob_sector: read_u32(buf, 0x00C4)?,
            vts_ptt_srpt_sector: read_u32(buf, 0x00C8)?,
            vts_pgci_sector: read_u32(buf, 0x00CC)?,
            vtsm_pgci_ut_sector: read_u32(buf, 0x00D0)?,
            vts_tmapti_sector: read_u32(buf, 0x00D4)?,
            vtsm_c_adt_sector: read_u32(buf, 0x00D8)?,
            vtsm_vobu_admap_sector: read_u32(buf, 0x00DC)?,
            vts_c_adt_sector: read_u32(buf, 0x00E0)?,
            vts_vobu_admap_sector: read_u32(buf, 0x00E4)?,
            menu_attributes,
            title_attributes,
        })
    }
}

/// Decode a menu-attribute block (VMGM- or VTSM-side) that starts at
/// `block_off`. The block's footprint per mpucoder-ifo.html
/// 0x0100..0x015C is:
///
/// ```text
///   +0x00  u16  video attributes (2 bytes)
///   +0x02  u16  number of audio streams (≤ 8)
///   +0x04  8 × 8 bytes  audio attributes
///   +0x44  16 bytes     reserved
///   +0x54  u16  number of subpicture streams (0 or 1)
///   +0x56  6 bytes      subpicture attribute slot (slot 0)
///   +0x5C  ...           reserved tail
/// ```
fn parse_menu_attribute_block(buf: &[u8], block_off: usize) -> Result<MenuAttributes> {
    // Need at least the 2-byte video field + 2-byte audio count.
    if buf.len() < block_off + 0x04 {
        return Ok(MenuAttributes::default());
    }
    let video = read_video_attr(buf, block_off)?;
    let audio_count = read_u16(buf, block_off + 0x02)? as usize;
    let mut audio_streams = Vec::new();
    if buf.len() >= block_off + 0x04 + 8 * 8 {
        for i in 0..audio_count.min(8) {
            audio_streams.push(read_audio_attr(buf, block_off + 0x04 + i * 8)?);
        }
    }
    let subp_count_off = block_off + 0x54;
    let mut subpicture_streams = Vec::new();
    if buf.len() >= subp_count_off + 2 + 6 {
        let subp_count = read_u16(buf, subp_count_off)? as usize;
        if subp_count >= 1 {
            subpicture_streams.push(read_subp_attr(buf, subp_count_off + 2)?);
        }
    }
    Ok(MenuAttributes {
        video: Some(video),
        audio_streams,
        subpicture_streams,
    })
}

/// Decode the VTS-VOBS title attribute block at fixed offset 0x0200.
/// The block's footprint is:
///
/// ```text
///   0x0200  u16  video attributes
///   0x0202  u16  number of audio streams (≤ 8)
///   0x0204  8 × 8 bytes  audio attributes
///   0x0244  16 bytes     reserved
///   0x0254  u16  number of subpicture streams (≤ 32)
///   0x0256  32 × 6 bytes  subpicture attributes
///   0x0316  2 bytes      reserved
///   0x0318  24 × 8 bytes  multichannel-extension entries (karaoke only)
///   0x03D8  end
/// ```
fn parse_title_attribute_block(buf: &[u8]) -> Result<TitleAttributes> {
    if buf.len() < 0x0204 {
        return Ok(TitleAttributes::default());
    }
    let video = read_video_attr(buf, 0x0200)?;
    let audio_count = read_u16(buf, 0x0202)? as usize;
    let mut audio_streams = Vec::new();
    if buf.len() >= 0x0204 + 8 * 8 {
        for i in 0..audio_count.min(8) {
            audio_streams.push(read_audio_attr(buf, 0x0204 + i * 8)?);
        }
    }
    let mut subpicture_streams = Vec::new();
    if buf.len() >= 0x0256 + 32 * 6 {
        let subp_count = read_u16(buf, 0x0254)? as usize;
        for i in 0..subp_count.min(32) {
            subpicture_streams.push(read_subp_attr(buf, 0x0256 + i * 6)?);
        }
    }
    // Multichannel extension — the spec slot is 24 × 8 = 192 bytes
    // starting at 0x0318 and ending at 0x03D8. Only decode the
    // entries that fit; non-karaoke titles leave the slot all-zero
    // (which Default-decodes cleanly, hence we still populate the
    // table — callers can inspect `vts_category` or the audio
    // `multichannel_extension_present` flag to know whether to
    // consume them).
    let mut multichannel_extension = Vec::new();
    if buf.len() >= 0x03D8 {
        for i in 0..24 {
            let off = 0x0318 + i * 8;
            let slice: [u8; 8] = buf[off..off + 8]
                .try_into()
                .map_err(|_| Error::InvalidUdf("VTSI_MAT: MC ext slice"))?;
            multichannel_extension.push(McExtensionEntry::parse(&slice));
        }
    }
    Ok(TitleAttributes {
        video: Some(video),
        audio_streams,
        subpicture_streams,
        multichannel_extension,
    })
}

fn read_video_attr(buf: &[u8], off: usize) -> Result<VideoAttributes> {
    let slice = buf
        .get(off..off + 2)
        .ok_or(Error::InvalidUdf("ifo: video attr read past end"))?;
    Ok(VideoAttributes::parse(&[slice[0], slice[1]]))
}

fn read_audio_attr(buf: &[u8], off: usize) -> Result<AudioAttributes> {
    let slice = buf
        .get(off..off + 8)
        .ok_or(Error::InvalidUdf("ifo: audio attr read past end"))?;
    let arr: [u8; 8] = slice
        .try_into()
        .map_err(|_| Error::InvalidUdf("ifo: audio attr slice"))?;
    Ok(AudioAttributes::parse(&arr))
}

fn read_subp_attr(buf: &[u8], off: usize) -> Result<SubpictureAttributes> {
    let slice = buf
        .get(off..off + 6)
        .ok_or(Error::InvalidUdf("ifo: subp attr read past end"))?;
    let arr: [u8; 6] = slice
        .try_into()
        .map_err(|_| Error::InvalidUdf("ifo: subp attr slice"))?;
    Ok(SubpictureAttributes::parse(&arr))
}

// ------------------------------------------------------------------
// VTS_PTT_SRPT — Part-of-Title Search Pointer Table (chapters)
// ------------------------------------------------------------------

/// One PTT (chapter) — points to a `(PGCN, PGN)` pair within the VTS.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ptt {
    /// Program Chain number (1-based).
    pub pgcn: u16,
    /// Program number within the PGC (1-based).
    pub pgn: u16,
}

/// One title in the PTT search pointer table — the list of chapters
/// for that title.
#[derive(Debug, Clone)]
pub struct PttTitle {
    pub chapters: Vec<Ptt>,
}

/// Parsed VTS_PTT_SRPT — 8-byte header + per-title offset list +
/// per-title PTT entries.
#[derive(Debug, Clone)]
pub struct VtsPttSrpt {
    pub title_count: u16,
    pub end_address: u32,
    pub titles: Vec<PttTitle>,
}

impl VtsPttSrpt {
    /// Parse a VTS_PTT_SRPT body.
    ///
    /// Layout per mpucoder-ifo_vts.html:
    ///
    /// ```text
    ///   0000: u16 number_of_titles (Nt)
    ///   0002: u16 reserved
    ///   0004: u32 end_address (last byte of last VTS_PTT)
    ///   0008: u32 offset_to_PTT[1]     ← VTS_PTTI[1]
    ///   000C: u32 offset_to_PTT[2]     ← VTS_PTTI[2]
    ///   ...
    ///   ...
    /// ```
    ///
    /// Each title's PTT region is a list of 4-byte `(PGCN, PGN)` pairs.
    /// The end of title i's region is bounded by either title i+1's
    /// offset (for i < Nt) or by `end_address + 1` (for i == Nt). We
    /// divide that span by 4 to recover the chapter count.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf(
                "VTS_PTT_SRPT: shorter than 8-byte header",
            ));
        }
        let title_count = read_u16(buf, 0)?;
        let end_address = read_u32(buf, 4)?;
        let nt = usize::from(title_count);
        let offsets_end = 8usize.saturating_add(nt * 4);
        if buf.len() < offsets_end {
            return Err(Error::InvalidUdf(
                "VTS_PTT_SRPT: offset list past end of buffer",
            ));
        }
        let mut offsets = Vec::with_capacity(nt);
        for i in 0..nt {
            offsets.push(read_u32(buf, 8 + i * 4)? as usize);
        }
        let mut titles = Vec::with_capacity(nt);
        for i in 0..nt {
            let start = offsets[i];
            // End of this title's PTT region: next title's offset, or
            // (end_address + 1) for the last title.
            let end_excl = if i + 1 < nt {
                offsets[i + 1]
            } else {
                (end_address as usize).saturating_add(1)
            };
            if end_excl < start {
                return Err(Error::InvalidUdf(
                    "VTS_PTT_SRPT: title offsets not monotonic",
                ));
            }
            let span = end_excl - start;
            if span % 4 != 0 {
                return Err(Error::InvalidUdf(
                    "VTS_PTT_SRPT: title span not a multiple of 4",
                ));
            }
            let n_ptt = span / 4;
            if buf.len() < start + n_ptt * 4 {
                return Err(Error::InvalidUdf(
                    "VTS_PTT_SRPT: title body past end of buffer",
                ));
            }
            let mut chapters = Vec::with_capacity(n_ptt);
            for j in 0..n_ptt {
                let off = start + j * 4;
                chapters.push(Ptt {
                    pgcn: read_u16(buf, off)?,
                    pgn: read_u16(buf, off + 2)?,
                });
            }
            titles.push(PttTitle { chapters });
        }
        Ok(Self {
            title_count,
            end_address,
            titles,
        })
    }
}

// ------------------------------------------------------------------
// PGC — Program Chain (header + cells)
// ------------------------------------------------------------------

/// Per-cell playback information (16 bytes per entry in C_PBI).
///
/// Field layout per mpucoder-pgc.html "cell playback information
/// table entry":
///
/// - byte 0: cell category bits (cell type, block type, seamless,
///   interleaved, STC discontinuity, seamless-angle).
/// - byte 1: restricted flag (`0x80` = trick-play disallowed).
/// - byte 2: cell still time.
/// - byte 3: cell command # (1..=128, 0 = no command).
/// - bytes 4..8: cell playback time (BCD).
/// - bytes 8..12: first VOBU start sector.
/// - bytes 12..16: first ILVU end sector.
/// - bytes 16..20: last VOBU start sector.
/// - bytes 20..24: last VOBU end sector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CellPlaybackInfo {
    pub category_byte0: u8,
    pub restricted: bool,
    pub still_time: u8,
    pub cell_command: u8,
    pub playback_time: PgcTime,
    pub first_vobu_start_sector: u32,
    pub first_ilvu_end_sector: u32,
    pub last_vobu_start_sector: u32,
    pub last_vobu_end_sector: u32,
}

impl CellPlaybackInfo {
    fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 24 {
            return Err(Error::InvalidUdf("C_PBI entry shorter than 24 bytes"));
        }
        let category_byte0 = read_u8(buf, 0)?;
        let restricted = (read_u8(buf, 1)? & 0x80) != 0;
        let still_time = read_u8(buf, 2)?;
        let cell_command = read_u8(buf, 3)?;
        let mut t = [0u8; 4];
        t.copy_from_slice(&buf[4..8]);
        let playback_time = PgcTime::from_bytes(t);
        let first_vobu_start_sector = read_u32(buf, 8)?;
        let first_ilvu_end_sector = read_u32(buf, 12)?;
        let last_vobu_start_sector = read_u32(buf, 16)?;
        let last_vobu_end_sector = read_u32(buf, 20)?;
        Ok(Self {
            category_byte0,
            restricted,
            still_time,
            cell_command,
            playback_time,
            first_vobu_start_sector,
            first_ilvu_end_sector,
            last_vobu_start_sector,
            last_vobu_end_sector,
        })
    }
}

/// Per-cell position information (4 bytes per entry in C_POS).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CellPositionInfo {
    pub vob_id: u16,
    pub cell_id: u8,
}

impl CellPositionInfo {
    fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 4 {
            return Err(Error::InvalidUdf("C_POS entry shorter than 4 bytes"));
        }
        let vob_id = read_u16(buf, 0)?;
        // byte 2 reserved
        let cell_id = read_u8(buf, 3)?;
        Ok(Self { vob_id, cell_id })
    }
}

/// One entry of the PGC subpicture/highlight colour-LUT.
///
/// Per mpucoder-pgc.html the PGC header at offset `0x00A4` carries a
/// `16 × 4`-byte palette laid out as `(0, Y, Cr, Cb)`: byte 0 is a
/// reserved/zero pad, then the luma + the two chroma-difference
/// samples in 8-bit BT.601-range form. These sixteen entries are the
/// colour source a subpicture (SPU) display-control sequence indexes
/// into via its 4-bit colour codes (the SPU itself only stores the
/// 0..=15 palette index + a contrast/alpha nibble — see
/// mpucoder-spu.html), so a renderer needs this table to resolve a
/// subtitle/menu pixel to an actual YCrCb value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PaletteEntry {
    /// Luma (Y) sample, 8-bit.
    pub y: u8,
    /// Cr (red chroma-difference) sample, 8-bit.
    pub cr: u8,
    /// Cb (blue chroma-difference) sample, 8-bit.
    pub cb: u8,
}

impl PaletteEntry {
    /// Parse one 4-byte `(0, Y, Cr, Cb)` palette cell. The leading
    /// byte is reserved and ignored.
    fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 4 {
            return Err(Error::InvalidUdf("PGC palette entry shorter than 4 bytes"));
        }
        Ok(Self {
            y: buf[1],
            cr: buf[2],
            cb: buf[3],
        })
    }
}

/// One 8-byte DVD-Video navigation command (VM instruction word).
///
/// Per mpucoder-pgc.html every command in a PGC command table is a
/// fixed 8-byte word. Decoding the opcode/operand semantics is
/// Phase 3c VM work (mpucoder-vmi.html); at the container layer we
/// surface the raw word so a downstream interpreter can execute it.
/// We expose the leading byte's top three bits as `command_type`
/// (the VMI command-group selector) for convenience without
/// committing to a full opcode model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct NavCommand {
    /// The eight raw command bytes, big-endian on the wire.
    pub bytes: [u8; 8],
}

impl NavCommand {
    /// Wrap an 8-byte command word.
    fn parse(buf: &[u8]) -> Result<Self> {
        let slice = buf
            .get(0..8)
            .ok_or(Error::InvalidUdf("PGC command shorter than 8 bytes"))?;
        let mut bytes = [0u8; 8];
        bytes.copy_from_slice(slice);
        Ok(Self { bytes })
    }

    /// VMI command-type selector — the top three bits of byte 0.
    ///
    /// This is the coarse command-group field per mpucoder-vmi.html;
    /// full opcode decode is delegated to the Phase 3c VM via
    /// [`Self::decode_instruction`]. Provided so callers can classify
    /// a word (e.g. distinguish a link/jump from a SetSystem/Compare)
    /// without a full interpreter.
    pub fn command_type(&self) -> u8 {
        self.bytes[0] >> 5
    }

    /// Decode this raw command word into a typed
    /// [`crate::nav::NavInstruction`].
    ///
    /// Convenience wrapper around the Phase 3c-precursor disassembler
    /// in the `nav` module, which adds a `decode()` method to this
    /// same `NavCommand` type. Callers iterating a
    /// [`PgcCommandTable`] can stay inside the `ifo` namespace and
    /// reach the typed instruction tree via a single method call
    /// rather than importing the `nav` module's surface explicitly.
    #[inline]
    pub fn decode_instruction(&self) -> crate::nav::NavInstruction {
        self.decode()
    }
}

/// PGC command table — pre, post, and cell command lists.
///
/// Per mpucoder-pgc.html "command table" the table opens with an
/// 8-byte header (`pre count`, `post count`, `cell count`, and an
/// `end address` relative to the table start), followed by the three
/// command lists back to back, each entry a fixed 8-byte
/// [`NavCommand`]. The total `pre + post + cell` count is `<= 128`.
///
/// *Pre* commands run before the PGC's first cell; *post* commands
/// run after the last cell finishes; *cell* commands are referenced
/// by the per-cell `cell_command` index in [`CellPlaybackInfo`]
/// (1-based; `0` = none). Executing the words is Phase 3c VM work —
/// here we only carve the raw 8-byte words out of the table.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PgcCommandTable {
    /// Commands executed when the PGC starts.
    pub pre: Vec<NavCommand>,
    /// Commands executed when the PGC ends.
    pub post: Vec<NavCommand>,
    /// Commands indexed by a cell's `cell_command` field (1-based).
    pub cell: Vec<NavCommand>,
    /// `end address` field — last byte offset of the table relative
    /// to its own start.
    pub end_address: u16,
}

impl PgcCommandTable {
    /// Parse a command table. `buf` must start at the table's first
    /// byte (the `pre count` u16) and span at least through the last
    /// command word.
    fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("PGC command table shorter than header"));
        }
        let pre_count = read_u16(buf, 0)?;
        let post_count = read_u16(buf, 2)?;
        let cell_count = read_u16(buf, 4)?;
        let end_address = read_u16(buf, 6)?;

        let total = usize::from(pre_count) + usize::from(post_count) + usize::from(cell_count);
        // Spec invariant: the three lists together hold <= 128 words.
        if total > 128 {
            return Err(Error::InvalidUdf("PGC command table claims > 128 commands"));
        }

        let read_list = |start: usize, count: u16| -> Result<Vec<NavCommand>> {
            let mut out = Vec::with_capacity(usize::from(count));
            for i in 0..usize::from(count) {
                let off = start + i * 8;
                let word = buf
                    .get(off..off + 8)
                    .ok_or(Error::InvalidUdf("PGC command table list past end"))?;
                out.push(NavCommand::parse(word)?);
            }
            Ok(out)
        };

        let pre_start = 8usize;
        let post_start = pre_start + usize::from(pre_count) * 8;
        let cell_start = post_start + usize::from(post_count) * 8;

        let pre = read_list(pre_start, pre_count)?;
        let post = read_list(post_start, post_count)?;
        let cell = read_list(cell_start, cell_count)?;

        Ok(Self {
            pre,
            post,
            cell,
            end_address,
        })
    }

    /// Iterate the **pre** command list as typed
    /// [`crate::nav::NavInstruction`]s.
    ///
    /// Per `docs/container/dvd/application/mpucoder-pgc.html` the
    /// pre-command list runs once at PGC entry, before the first
    /// cell. Each 8-byte [`NavCommand`] word is fed through the
    /// `nav` disassembler so iterator consumers receive the typed
    /// instruction tree directly without a manual decode step.
    pub fn pre_instructions(&self) -> impl Iterator<Item = crate::nav::NavInstruction> + '_ {
        self.pre.iter().map(NavCommand::decode_instruction)
    }

    /// Iterate the **post** command list as typed
    /// [`crate::nav::NavInstruction`]s.
    ///
    /// The post-command list runs once when the last cell of the
    /// PGC finishes, per `mpucoder-pgc.html`. Same shape as
    /// [`Self::pre_instructions`].
    pub fn post_instructions(&self) -> impl Iterator<Item = crate::nav::NavInstruction> + '_ {
        self.post.iter().map(NavCommand::decode_instruction)
    }

    /// Iterate the **cell** command list as typed
    /// [`crate::nav::NavInstruction`]s.
    ///
    /// The cell command list is indexed by each
    /// [`CellPlaybackInfo`]'s 1-based `cell_command` field per
    /// `mpucoder-pgc.html`; this iterator walks it in storage order.
    /// Use [`Self::cell_instruction`] for the indexed lookup a
    /// cell actually performs.
    pub fn cell_instructions(&self) -> impl Iterator<Item = crate::nav::NavInstruction> + '_ {
        self.cell.iter().map(NavCommand::decode_instruction)
    }

    /// Look up a cell command by its 1-based index — the encoding
    /// `CellPlaybackInfo::cell_command` carries on the wire — and
    /// return the typed [`crate::nav::NavInstruction`].
    ///
    /// Per `mpucoder-pgc.html` `cell_command = 0` means "no command
    /// associated with this cell"; the spec stores cell commands in
    /// a 1-based table. Passing `0` returns `None`; passing any
    /// out-of-range index also returns `None` rather than panicking,
    /// matching the malformed-disc-tolerance pattern used elsewhere
    /// in this crate's typed decoders.
    pub fn cell_instruction(&self, index_1based: u16) -> Option<crate::nav::NavInstruction> {
        if index_1based == 0 {
            return None;
        }
        let idx = usize::from(index_1based - 1);
        self.cell.get(idx).map(NavCommand::decode_instruction)
    }
}

/// Parsed PGC header + cell tables.
///
/// Layout per mpucoder-pgc.html:
///
/// - 0x0000..0x00E4: PGC general information (PGC_GI) +
///   PGC_AST_CTL + PGC_SPST_CTL + PGC_PB_TIME + still time +
///   playback mode + palette (16 × 4-byte `(0, Y, Cr, Cb)` at
///   0x00A4).
/// - 0x00E4: u16 offset_to_commands (relative to PGC start). The
///   command table at that offset holds the pre/post/cell
///   navigation command lists ([`PgcCommandTable`]).
/// - 0x00E6: u16 offset_to_program_map.
/// - 0x00E8: u16 offset_to_cell_playback_information.
/// - 0x00EA: u16 offset_to_cell_position_information.
#[derive(Debug, Clone)]
pub struct Pgc {
    /// Number of programs in this PGC.
    pub number_of_programs: u8,
    /// Number of cells.
    pub number_of_cells: u8,
    /// PGC playback time (BCD).
    pub playback_time: PgcTime,
    /// Prohibited user-operation mask.
    pub prohibited_user_ops: u32,
    /// Next PGCN (`0` = none).
    pub next_pgcn: u16,
    /// Previous PGCN (`0` = none).
    pub prev_pgcn: u16,
    /// "Goup" (group-up) PGCN (`0` = none).
    pub goup_pgcn: u16,
    /// PGC still time (`255` = infinite).
    pub still_time: u8,
    /// Playback mode (0 = sequential; non-zero encodes
    /// random/shuffle + program count, see spec).
    pub playback_mode: u8,
    /// Subpicture/highlight colour-LUT — 16 `(Y, Cr, Cb)` entries
    /// from PGC offset `0x00A4` per mpucoder-pgc.html.
    pub palette: [PaletteEntry; 16],
    /// Offset within PGC to commands table (`0` = absent).
    pub offset_commands: u16,
    /// Offset within PGC to program map (`0` = absent).
    pub offset_program_map: u16,
    /// Offset within PGC to cell-playback-information table.
    pub offset_cell_playback: u16,
    /// Offset within PGC to cell-position-information table.
    pub offset_cell_position: u16,
    /// Per-program entry-cell numbers, length = `number_of_programs`.
    pub program_map: Vec<u8>,
    /// Per-cell playback info.
    pub cells: Vec<CellPlaybackInfo>,
    /// Per-cell position info (VOB id + Cell id pairs).
    pub cell_positions: Vec<CellPositionInfo>,
    /// Parsed pre/post/cell navigation command table. `None` when
    /// `offset_commands == 0` (no command table present).
    pub commands: Option<PgcCommandTable>,
}

impl Pgc {
    /// Parse one PGC blob. `buf` must start at the PGC's first byte
    /// and span at least through the last table referenced by the
    /// offset fields.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 0xEC {
            return Err(Error::InvalidUdf("PGC: buffer shorter than header"));
        }
        let number_of_programs = read_u8(buf, 0x0002)?;
        let number_of_cells = read_u8(buf, 0x0003)?;
        let mut t = [0u8; 4];
        t.copy_from_slice(&buf[0x0004..0x0008]);
        let playback_time = PgcTime::from_bytes(t);
        let prohibited_user_ops = read_u32(buf, 0x0008)?;
        let next_pgcn = read_u16(buf, 0x009C)?;
        let prev_pgcn = read_u16(buf, 0x009E)?;
        let goup_pgcn = read_u16(buf, 0x00A0)?;
        let still_time = read_u8(buf, 0x00A2)?;
        let playback_mode = read_u8(buf, 0x00A3)?;

        // Palette (subpicture colour-LUT): 16 × 4-byte (0, Y, Cr, Cb)
        // entries at PGC offset 0x00A4. This is part of the fixed
        // header (which the 0xEC length check above already covers).
        let mut palette = [PaletteEntry::default(); 16];
        for (i, slot) in palette.iter_mut().enumerate() {
            let base = 0x00A4 + i * 4;
            *slot = PaletteEntry::parse(&buf[base..base + 4])?;
        }

        let offset_commands = read_u16(buf, 0x00E4)?;
        let offset_program_map = read_u16(buf, 0x00E6)?;
        let offset_cell_playback = read_u16(buf, 0x00E8)?;
        let offset_cell_position = read_u16(buf, 0x00EA)?;

        // Program map: number_of_programs × 1 byte. Padded to word
        // boundary with zero per spec, but we only need the first N.
        let mut program_map = Vec::with_capacity(usize::from(number_of_programs));
        if offset_program_map != 0 {
            let base = usize::from(offset_program_map);
            for i in 0..usize::from(number_of_programs) {
                program_map.push(read_u8(buf, base + i)?);
            }
        }

        // Cell playback information table: number_of_cells × 24 bytes.
        let mut cells = Vec::with_capacity(usize::from(number_of_cells));
        if offset_cell_playback != 0 {
            let base = usize::from(offset_cell_playback);
            for i in 0..usize::from(number_of_cells) {
                let entry = &buf
                    .get(base + i * 24..base + (i + 1) * 24)
                    .ok_or(Error::InvalidUdf("PGC: C_PBI past end of buffer"))?;
                cells.push(CellPlaybackInfo::parse(entry)?);
            }
        }

        // Cell position information table: number_of_cells × 4 bytes.
        let mut cell_positions = Vec::with_capacity(usize::from(number_of_cells));
        if offset_cell_position != 0 {
            let base = usize::from(offset_cell_position);
            for i in 0..usize::from(number_of_cells) {
                let entry = &buf
                    .get(base + i * 4..base + (i + 1) * 4)
                    .ok_or(Error::InvalidUdf("PGC: C_POS past end of buffer"))?;
                cell_positions.push(CellPositionInfo::parse(entry)?);
            }
        }

        // Command table (pre/post/cell command lists). Absent when
        // offset_commands == 0 per mpucoder-pgc.html.
        let commands = if offset_commands != 0 {
            let base = usize::from(offset_commands);
            let tbl = buf
                .get(base..)
                .ok_or(Error::InvalidUdf("PGC: command table past end of buffer"))?;
            Some(PgcCommandTable::parse(tbl)?)
        } else {
            None
        };

        Ok(Self {
            number_of_programs,
            number_of_cells,
            playback_time,
            prohibited_user_ops,
            next_pgcn,
            prev_pgcn,
            goup_pgcn,
            still_time,
            playback_mode,
            palette,
            offset_commands,
            offset_program_map,
            offset_cell_playback,
            offset_cell_position,
            program_map,
            cells,
            cell_positions,
            commands,
        })
    }

    /// Typed view over [`Self::prohibited_user_ops`].
    ///
    /// The PGC-level UOP-prohibition mask follows the same 25-bit
    /// layout as the PCI / TT_SRPT levels; this accessor wraps the
    /// raw word so callers can use named [`UserOp`] variants
    /// instead of magic bit numbers. Per
    /// `docs/container/dvd/application/mpucoder-uops.html`, a set
    /// bit inhibits the associated control.
    #[inline]
    pub fn uop_mask(&self) -> crate::uops::UopMask {
        crate::uops::UopMask::from_bits(self.prohibited_user_ops)
    }

    /// `true` when `op` is **not** prohibited at the PGC level.
    /// The full player-visible answer is still subject to the
    /// TT_SRPT and PCI-VOBU masks per the spec's three-level OR
    /// rule; use [`crate::uops::UopMask::merge_or`] to combine.
    #[inline]
    pub fn is_user_op_allowed(&self, op: crate::uops::UserOp) -> bool {
        self.uop_mask().is_allowed(op)
    }
}

// ------------------------------------------------------------------
// PGCI — Program Chain Information (table of PGCs)
// ------------------------------------------------------------------

/// One entry in the PGCI SRP — category byte + offset to the PGC body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PgciSrp {
    pub category: u32,
    /// Offset to the PGC body, relative to the PGCI start.
    pub offset: u32,
}

/// Parsed PGCI (VTS_PGCI or VMGM_PGCI body).
#[derive(Debug, Clone)]
pub struct Pgci {
    pub number_of_pgcs: u16,
    pub end_address: u32,
    pub srp: Vec<PgciSrp>,
    pub pgcs: Vec<Pgc>,
}

impl Pgci {
    /// Parse a PGCI body. `buf` must start at the first byte of the
    /// PGCI table and span at least through the last PGC.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("PGCI: shorter than 8-byte header"));
        }
        let number_of_pgcs = read_u16(buf, 0)?;
        let end_address = read_u32(buf, 4)?;
        let n = usize::from(number_of_pgcs);
        let srp_end = 8usize.saturating_add(n * 8);
        if buf.len() < srp_end {
            return Err(Error::InvalidUdf("PGCI: SRP list past end of buffer"));
        }
        let mut srp = Vec::with_capacity(n);
        for i in 0..n {
            let base = 8 + i * 8;
            srp.push(PgciSrp {
                category: read_u32(buf, base)?,
                offset: read_u32(buf, base + 4)?,
            });
        }
        let mut pgcs = Vec::with_capacity(n);
        for entry in &srp {
            let off = entry.offset as usize;
            if off == 0 || off >= buf.len() {
                return Err(Error::InvalidUdf("PGCI: PGC offset out of range"));
            }
            let pgc_buf = &buf[off..];
            pgcs.push(Pgc::parse(pgc_buf)?);
        }
        Ok(Self {
            number_of_pgcs,
            end_address,
            srp,
            pgcs,
        })
    }
}

// ------------------------------------------------------------------
// VMGM_PGCI_UT / VTSM_PGCI_UT — Menu PGCI Unit Table
// ------------------------------------------------------------------
//
// Per `docs/container/dvd/application/mpucoder-ifo_vmg.html` §VMGM_PGCI_UT
// and `mpucoder-ifo_vts.html` §VTSM_PGCI_UT. Two-level hierarchy:
//
//   VMGM_PGCI_UT / VTSM_PGCI_UT
//     ├── language-unit search-pointer list (one per ISO 639 language)
//     │     each entry: ISO639 code (2 B) + language-code ext (1 B)
//     │     + menu-existence-flag byte (1 B) + offset to LU (4 B)
//     └── Language Unit (PGCI_LU)
//           ├── PGC search-pointer list (one per menu PGC in this LU)
//           │     each entry: PGC category (4 B) + offset to PGC (4 B)
//           └── PGC bodies (parsed via `Pgc::parse`)
//
// The 8-byte unit-header at the LU and the unit-table top use the same
// `{ u16 count, u16 reserved, u32 end_address }` shape, then each list
// entry is 8 bytes.

/// Menu existence-flag bits used in a VTSM language-unit entry's byte 3.
///
/// Per `mpucoder-ifo_vts.html` §VTSM_PGCI_UT — bit set ⇒ the
/// corresponding menu exists in that language unit. Bit `0x80` ("root")
/// is the only flag VMGM_PGCI_UT uses (treated as "title" on the VMG
/// side per `mpucoder-ifo_vmg.html`).
pub mod menu_existence {
    /// `0x80` — root menu exists (VTSM) / title menu exists (VMGM).
    pub const ROOT: u8 = 0x80;
    /// `0x40` — sub-picture menu exists (VTSM only).
    pub const SUBPICTURE: u8 = 0x40;
    /// `0x20` — audio menu exists (VTSM only).
    pub const AUDIO: u8 = 0x20;
    /// `0x10` — angle menu exists (VTSM only).
    pub const ANGLE: u8 = 0x10;
    /// `0x08` — PTT (chapter) menu exists (VTSM only).
    pub const PTT: u8 = 0x08;
}

/// Menu-type enum decoded from a PGC category byte 0 (low nibble) per
/// `mpucoder-ifo_vts.html` §VTSM_PGCI_UT (PGC category breakdown).
///
/// Only meaningful when the entry-PGC flag (`category[0] >> 7`) is set;
/// for non-entry PGCs the menu-type field is unused per the spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MenuType {
    /// VMGM-side: title menu (`2`).
    Title,
    /// VTSM-side: root menu (`3`).
    Root,
    /// VTSM-side: sub-picture menu (`4`).
    Subpicture,
    /// VTSM-side: audio menu (`5`).
    Audio,
    /// VTSM-side: angle menu (`6`).
    Angle,
    /// VTSM-side: PTT (chapter) menu (`7`).
    Ptt,
    /// Any other value the spec doesn't define (reserved).
    Unknown(u8),
}

impl MenuType {
    /// Decode the low nibble of PGC category byte 0.
    pub fn from_nibble(n: u8) -> Self {
        match n & 0x0F {
            2 => MenuType::Title,
            3 => MenuType::Root,
            4 => MenuType::Subpicture,
            5 => MenuType::Audio,
            6 => MenuType::Angle,
            7 => MenuType::Ptt,
            other => MenuType::Unknown(other),
        }
    }
}

/// One PGC search-pointer inside a Language Unit (`PGCI_LU`).
///
/// `category` is the 32-bit PGC category dword; the high bit of byte 0
/// is the entry-PGC flag and the low nibble of byte 0 is the menu type
/// (only valid when the entry-PGC flag is set). Bytes 2..4 carry the
/// parental management mask. `offset` is the byte distance from the
/// start of the enclosing Language Unit to the PGC body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PgciLuSrp {
    /// Raw 32-bit PGC category dword.
    pub category: u32,
    /// Byte offset to the PGC body, relative to this Language Unit's
    /// start.
    pub offset: u32,
}

impl PgciLuSrp {
    /// `true` when the entry-PGC flag (byte 0 bit 7) is set.
    pub fn is_entry_pgc(&self) -> bool {
        (self.category >> 24) & 0x80 != 0
    }

    /// Decode the menu-type nibble (only meaningful when
    /// [`Self::is_entry_pgc`] is `true`).
    pub fn menu_type(&self) -> MenuType {
        MenuType::from_nibble((self.category >> 24) as u8)
    }

    /// Parental management mask (low 16 bits of the category dword).
    pub fn parental_mask(&self) -> u16 {
        (self.category & 0xFFFF) as u16
    }
}

/// One Language Unit (`PGCI_LU`) — a PGC search-pointer list plus the
/// parsed PGC bodies it points at.
#[derive(Debug, Clone)]
pub struct PgciLu {
    /// Number of PGCs in this language unit.
    pub number_of_pgcs: u16,
    /// Last byte address of the last PGC body in this LU, relative to
    /// the LU's start.
    pub end_address: u32,
    /// PGC search pointers in declaration order.
    pub srp: Vec<PgciLuSrp>,
    /// Parsed PGC bodies in the same order as `srp`.
    pub pgcs: Vec<Pgc>,
}

impl PgciLu {
    /// Parse a Language Unit body. `buf` must start at the LU's first
    /// byte and span at least through the last PGC body.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("PGCI_LU: shorter than 8-byte header"));
        }
        let number_of_pgcs = read_u16(buf, 0)?;
        // bytes 2..4 reserved
        let end_address = read_u32(buf, 4)?;
        let n = usize::from(number_of_pgcs);
        let srp_end = 8usize
            .checked_add(
                n.checked_mul(8)
                    .ok_or(Error::InvalidUdf("PGCI_LU: SRP list × 8 overflow"))?,
            )
            .ok_or(Error::InvalidUdf("PGCI_LU: SRP list size overflow"))?;
        if buf.len() < srp_end {
            return Err(Error::InvalidUdf("PGCI_LU: SRP list past end of buffer"));
        }
        let mut srp = Vec::with_capacity(n);
        for i in 0..n {
            let base = 8 + i * 8;
            srp.push(PgciLuSrp {
                category: read_u32(buf, base)?,
                offset: read_u32(buf, base + 4)?,
            });
        }
        let mut pgcs = Vec::with_capacity(n);
        for entry in &srp {
            let off = entry.offset as usize;
            if off == 0 || off >= buf.len() {
                return Err(Error::InvalidUdf("PGCI_LU: PGC offset out of range"));
            }
            pgcs.push(Pgc::parse(&buf[off..])?);
        }
        Ok(Self {
            number_of_pgcs,
            end_address,
            srp,
            pgcs,
        })
    }
}

/// One language-unit search-pointer in the menu PGCI Unit Table.
///
/// `language_code` is the raw 16-bit ISO 639 alpha-2 code (two ASCII
/// letters packed big-endian — e.g. `b"en"` = `0x656E`).
/// `language_code_ext` is the 1-byte language-code extension slot (the
/// spec keeps it reserved-zero; mirrors the SPRM-17 / SPRM-19 layout).
/// `menu_existence` is the byte 3 flag byte — see the
/// [`menu_existence`] constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PgciUtSrp {
    /// Big-endian-packed ISO 639 language code.
    pub language_code: u16,
    /// Language-code extension byte (reserved-zero by the spec).
    pub language_code_ext: u8,
    /// Menu existence flag byte — bitset of [`menu_existence`] bits.
    pub menu_existence: u8,
    /// Byte offset to the Language Unit body, relative to the start
    /// of `PGCI_UT`.
    pub offset: u32,
}

impl PgciUtSrp {
    /// `true` when bit `0x80` (root / title menu) is set.
    pub fn has_root_menu(&self) -> bool {
        self.menu_existence & menu_existence::ROOT != 0
    }

    /// `true` when bit `0x40` (sub-picture menu) is set. Only
    /// meaningful for VTSM_PGCI_UT.
    pub fn has_subpicture_menu(&self) -> bool {
        self.menu_existence & menu_existence::SUBPICTURE != 0
    }

    /// `true` when bit `0x20` (audio menu) is set. Only meaningful for
    /// VTSM_PGCI_UT.
    pub fn has_audio_menu(&self) -> bool {
        self.menu_existence & menu_existence::AUDIO != 0
    }

    /// `true` when bit `0x10` (angle menu) is set. Only meaningful for
    /// VTSM_PGCI_UT.
    pub fn has_angle_menu(&self) -> bool {
        self.menu_existence & menu_existence::ANGLE != 0
    }

    /// `true` when bit `0x08` (PTT menu) is set. Only meaningful for
    /// VTSM_PGCI_UT.
    pub fn has_ptt_menu(&self) -> bool {
        self.menu_existence & menu_existence::PTT != 0
    }
}

/// Parsed VMGM_PGCI_UT or VTSM_PGCI_UT body.
///
/// Two-level table: an outer search-pointer list keyed by ISO 639
/// language code, with each entry pointing at a Language Unit that
/// itself holds the menu PGCs for that language. The wire format is
/// identical between the VMG and VTS sides; the only difference is
/// the documented set of `menu_existence` / `MenuType` values
/// (the VMG side only authors a "title" menu type, while the VTS
/// side authors root / subpicture / audio / angle / PTT menus).
#[derive(Debug, Clone)]
pub struct PgciUt {
    /// Number of Language Units in this table.
    pub number_of_language_units: u16,
    /// Last byte address of the last PGC body in the last LU,
    /// relative to the start of `PGCI_UT`.
    pub end_address: u32,
    /// Outer search-pointer list — one entry per language unit.
    pub srp: Vec<PgciUtSrp>,
    /// Parsed Language Units in the same order as `srp`.
    pub language_units: Vec<PgciLu>,
}

impl PgciUt {
    /// Parse a `VMGM_PGCI_UT` or `VTSM_PGCI_UT` body. `buf` must start
    /// at the first byte of the table and span at least through the
    /// last PGC body in the last LU.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("PGCI_UT: shorter than 8-byte header"));
        }
        let number_of_language_units = read_u16(buf, 0)?;
        // bytes 2..4 reserved
        let end_address = read_u32(buf, 4)?;
        let n = usize::from(number_of_language_units);
        let srp_end = 8usize
            .checked_add(
                n.checked_mul(8)
                    .ok_or(Error::InvalidUdf("PGCI_UT: SRP list × 8 overflow"))?,
            )
            .ok_or(Error::InvalidUdf("PGCI_UT: SRP list size overflow"))?;
        if buf.len() < srp_end {
            return Err(Error::InvalidUdf("PGCI_UT: SRP list past end of buffer"));
        }
        let mut srp = Vec::with_capacity(n);
        for i in 0..n {
            let base = 8 + i * 8;
            srp.push(PgciUtSrp {
                language_code: read_u16(buf, base)?,
                language_code_ext: buf[base + 2],
                menu_existence: buf[base + 3],
                offset: read_u32(buf, base + 4)?,
            });
        }
        let mut language_units = Vec::with_capacity(n);
        for entry in &srp {
            let off = entry.offset as usize;
            if off == 0 || off >= buf.len() {
                return Err(Error::InvalidUdf("PGCI_UT: LU offset out of range"));
            }
            language_units.push(PgciLu::parse(&buf[off..])?);
        }
        Ok(Self {
            number_of_language_units,
            end_address,
            srp,
            language_units,
        })
    }

    /// Look up the Language Unit for the given 16-bit ISO 639 language
    /// code (e.g. `b"en"` packed big-endian = `0x656E`).
    pub fn language_unit(&self, language_code: u16) -> Option<&PgciLu> {
        self.srp
            .iter()
            .position(|s| s.language_code == language_code)
            .and_then(|i| self.language_units.get(i))
    }
}

// ------------------------------------------------------------------
// VTS_C_ADT — Cell Address Table
// ------------------------------------------------------------------

/// One row of the cell address table.
///
/// Per stnsoft-vmindx.html / mpucoder-ifo.html `c_adt`: each entry is
/// 12 bytes — `(vob_id u16, cell_id u8, reserved u8, start_sector
/// u32, end_sector u32)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CellAddrEntry {
    pub vob_id: u16,
    pub cell_id: u8,
    pub start_sector: u32,
    pub end_sector: u32,
}

/// Parsed VTS_C_ADT body — also covers VMGM_C_ADT and VTSM_C_ADT
/// since they share the wire format.
#[derive(Debug, Clone)]
pub struct VtsCAdt {
    /// Number of distinct VOB IDs covered (NOT the entry count —
    /// per spec, multiple entries can share a VOB ID for the cells
    /// inside that VOB).
    pub number_of_vob_ids: u16,
    /// `end_address` field.
    pub end_address: u32,
    /// Parsed cell-address entries.
    pub entries: Vec<CellAddrEntry>,
}

impl VtsCAdt {
    /// Parse a C_ADT body. Entry count is recovered from
    /// `(end_address - 7) / 12` — the spec stores it implicitly.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("C_ADT: shorter than 8-byte header"));
        }
        let number_of_vob_ids = read_u16(buf, 0)?;
        let end_address = read_u32(buf, 4)?;
        // end_address = byte index of the last entry's last byte
        // relative to start of C_ADT. The entries start at byte 8.
        // Entry count = (end_address + 1 - 8) / 12.
        let body_bytes = (end_address as usize).saturating_add(1).saturating_sub(8);
        if body_bytes % 12 != 0 {
            return Err(Error::InvalidUdf(
                "C_ADT: end_address implies non-12-byte entry size",
            ));
        }
        let n = body_bytes / 12;
        let needed = 8 + n * 12;
        if buf.len() < needed {
            return Err(Error::InvalidUdf("C_ADT: buffer shorter than entry table"));
        }
        let mut entries = Vec::with_capacity(n);
        for i in 0..n {
            let base = 8 + i * 12;
            entries.push(CellAddrEntry {
                vob_id: read_u16(buf, base)?,
                cell_id: read_u8(buf, base + 2)?,
                // byte 3 reserved
                start_sector: read_u32(buf, base + 4)?,
                end_sector: read_u32(buf, base + 8)?,
            });
        }
        Ok(Self {
            number_of_vob_ids,
            end_address,
            entries,
        })
    }

    /// Look up the disc-LBA range for a `(vob_id, cell_id)` pair.
    /// Sectors are relative to the start of the title's VOB chunks.
    pub fn lookup(&self, vob_id: u16, cell_id: u8) -> Option<(u32, u32)> {
        self.entries
            .iter()
            .find(|e| e.vob_id == vob_id && e.cell_id == cell_id)
            .map(|e| (e.start_sector, e.end_sector))
    }
}

// ------------------------------------------------------------------
// VOBU_ADMAP — VOBU Address Map (absolute sector list)
// ------------------------------------------------------------------

/// Parsed VOBU address map — covers `VMGM_VOBU_ADMAP`,
/// `VTSM_VOBU_ADMAP`, and `VTS_VOBU_ADMAP` (the three tables share
/// the same wire layout per `mpucoder-ifo.html`).
///
/// Layout (per the same source):
///
/// ```text
///   0x00: u32 end_address (last byte of last entry, relative to map start)
///   0x04: u32 starting sector within VOB of VOBU 1
///   0x08: u32 starting sector within VOB of VOBU 2
///   ...
/// ```
///
/// Entry count is implicit in `end_address`: each entry is exactly
/// four bytes, so `(end_address + 1 - 4) / 4` rounds down to the
/// number of VOBUs.
///
/// The 4-byte sector values are VOB-relative (i.e. relative to the
/// start of the first VOB the map covers — `VTS_xx_1.VOB` for
/// `VTS_VOBU_ADMAP`, the menu VOB for the menu variants); a player
/// adds the title-set VOB base LBA recorded in the corresponding
/// `VTSI_MAT::title_vob_sector` to recover the absolute disc LBA.
#[derive(Debug, Clone)]
pub struct VobuAdmap {
    /// `end_address` field — last byte of the last entry, relative
    /// to the start of the address map.
    pub end_address: u32,
    /// VOB-relative starting sectors, one per VOBU, in playback
    /// order. Index 0 = VOBU 1; index `entries.len() - 1` = the last
    /// VOBU declared by the map.
    pub entries: Vec<u32>,
}

impl VobuAdmap {
    /// Parse a VOBU_ADMAP body. `buf` must start at the 4-byte
    /// `end_address` field and span at least through the last entry.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 4 {
            return Err(Error::InvalidUdf("VOBU_ADMAP: shorter than 4-byte header"));
        }
        let end_address = read_u32(buf, 0)?;
        // end_address points at the last byte of the last entry,
        // relative to the table start. Entries begin at byte 4; each
        // entry is 4 bytes wide.
        let body_bytes = (end_address as usize).saturating_add(1).saturating_sub(4);
        if body_bytes % 4 != 0 {
            return Err(Error::InvalidUdf(
                "VOBU_ADMAP: end_address implies non-4-byte entry size",
            ));
        }
        let n = body_bytes / 4;
        let needed = 4 + n * 4;
        if buf.len() < needed {
            return Err(Error::InvalidUdf(
                "VOBU_ADMAP: buffer shorter than entry table",
            ));
        }
        let mut entries = Vec::with_capacity(n);
        for i in 0..n {
            entries.push(read_u32(buf, 4 + i * 4)?);
        }
        Ok(Self {
            end_address,
            entries,
        })
    }

    /// Number of VOBUs covered by this map.
    #[inline]
    pub fn vobu_count(&self) -> usize {
        self.entries.len()
    }

    /// VOB-relative starting sector of the 1-based VOBU number.
    /// Returns `None` for `vobu_number == 0` or any number past the
    /// last entry.
    pub fn vobu_start_sector(&self, vobu_number: u32) -> Option<u32> {
        if vobu_number == 0 {
            return None;
        }
        self.entries.get((vobu_number - 1) as usize).copied()
    }

    /// Translate a VOB-relative sector into the 1-based VOBU number
    /// whose range covers it. Returns `None` when the sector falls
    /// before the map's first VOBU or the map is empty.
    ///
    /// Because consecutive entries delimit each VOBU's range
    /// (entry `i` starts VOBU `i + 1`; entry `i + 1` starts the next
    /// one), the lookup is a partition search: the matching VOBU is
    /// the highest-indexed entry whose value `<= sector`.
    pub fn vobu_containing(&self, sector: u32) -> Option<u32> {
        if self.entries.is_empty() {
            return None;
        }
        // Binary partition.
        let idx = self.entries.partition_point(|&v| v <= sector);
        if idx == 0 {
            None
        } else {
            Some(idx as u32)
        }
    }
}

// ------------------------------------------------------------------
// VTS_TMAPTI — Time Map Table (one map per PGC)
// ------------------------------------------------------------------

/// One time-map entry: VOB-relative sector of the VOBU at the
/// associated time stamp.
///
/// Bit 31 of the on-disc value is a discontinuity flag; the remaining
/// 31 bits carry the VOB-relative sector. Per `mpucoder-ifo_vts.html`
/// "VTS_TMAP" the discontinuity bit signals that the previous entry's
/// time stamp is **not** continuous with this one — typically because
/// the underlying VOBU sits across a cell boundary or an `STC`
/// reset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TmapEntry {
    /// VOB-relative sector of the VOBU at this time index.
    pub sector: u32,
    /// `true` when the source flagged a time discontinuity with the
    /// previous entry (bit 31 of the raw word).
    pub discontinuous: bool,
}

impl TmapEntry {
    /// Bit 31 of the raw entry word: discontinuity-with-previous
    /// flag per `mpucoder-ifo_vts.html`.
    pub const DISCONTINUITY_BIT: u32 = 1 << 31;

    /// Low-31-bit sector mask.
    pub const SECTOR_MASK: u32 = 0x7FFF_FFFF;

    /// Decode one 4-byte entry word.
    fn from_raw(raw: u32) -> Self {
        Self {
            sector: raw & Self::SECTOR_MASK,
            discontinuous: (raw & Self::DISCONTINUITY_BIT) != 0,
        }
    }
}

/// One per-PGC time map: time-unit length plus the per-step sector
/// list.
///
/// Layout (per `mpucoder-ifo_vts.html` "VTS_TMAP"):
///
/// ```text
///   0x00: u8  time_unit (seconds per step)
///   0x01: u8  reserved
///   0x02: u16 number_of_entries (`0` for empty map)
///   0x04: u32 entry[0]   ← VOB-relative VOBU sector
///   0x08: u32 entry[1]
///   ...
/// ```
///
/// An empty time map (number_of_entries = 0) is legal and is the
/// authoring convention for a PGC the disc decided not to time-index
/// (typically very short menus or warning still-frames).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VtsTmap {
    /// Seconds covered by one entry step.
    pub time_unit: u8,
    /// Decoded entry list, one per step.
    pub entries: Vec<TmapEntry>,
}

impl VtsTmap {
    /// Parse one VTS_TMAP. `buf` must start at the `time_unit` byte
    /// and span at least through the last entry.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 4 {
            return Err(Error::InvalidUdf("VTS_TMAP: shorter than 4-byte header"));
        }
        let time_unit = read_u8(buf, 0)?;
        // byte 1 reserved
        let number_of_entries = read_u16(buf, 2)?;
        let n = usize::from(number_of_entries);
        let needed = 4usize.saturating_add(n * 4);
        if buf.len() < needed {
            return Err(Error::InvalidUdf(
                "VTS_TMAP: buffer shorter than entry table",
            ));
        }
        let mut entries = Vec::with_capacity(n);
        for i in 0..n {
            let raw = read_u32(buf, 4 + i * 4)?;
            entries.push(TmapEntry::from_raw(raw));
        }
        Ok(Self { time_unit, entries })
    }

    /// Translate a playback time `seconds` (PGC-relative) into the
    /// VOB-relative starting sector of the VOBU whose time bracket
    /// contains it. Returns `None` for an empty map or when the
    /// requested time falls before the first step.
    ///
    /// Bracket assignment per the spec: entry `i` (1-based) covers
    /// `[(i - 1) * time_unit, i * time_unit)` seconds.
    pub fn sector_at(&self, seconds: u32) -> Option<u32> {
        if self.entries.is_empty() || self.time_unit == 0 {
            return None;
        }
        let step = u32::from(self.time_unit);
        let idx_zero_based = (seconds / step) as usize;
        let idx = idx_zero_based.min(self.entries.len() - 1);
        Some(self.entries[idx].sector)
    }

    /// Total time covered by the map, in seconds. `time_unit *
    /// number_of_entries` — the upper edge of the last step's
    /// bracket.
    pub fn total_seconds(&self) -> u32 {
        u32::from(self.time_unit) * self.entries.len() as u32
    }
}

/// Parsed VTS_TMAPTI — one [`VtsTmap`] per program chain.
///
/// Layout (per `mpucoder-ifo_vts.html`):
///
/// ```text
///   0x00: u16 number_of_program_chains (Npgc)
///   0x02: u16 reserved
///   0x04: u32 end_address (last byte of last VTS_TMAP)
///   0x08: u32 offset_to_VTS_TMAP[1]
///   0x0C: u32 offset_to_VTS_TMAP[2]
///   ...
/// ```
///
/// "Each PGC MUST have a time map, even if it is empty" — the spec
/// guarantees `maps.len() == number_of_program_chains`.
#[derive(Debug, Clone)]
pub struct VtsTmapti {
    /// Number of program chains covered (= maps.len()).
    pub number_of_pgcs: u16,
    /// `end_address` field.
    pub end_address: u32,
    /// Decoded time maps, one per program chain. Index `i` (0-based)
    /// is the map for `PGCN = i + 1`.
    pub maps: Vec<VtsTmap>,
}

impl VtsTmapti {
    /// Parse a VTS_TMAPTI body. `buf` must start at byte 0 of the
    /// time-map table and span at least through the last `VTS_TMAP`.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("VTS_TMAPTI: shorter than 8-byte header"));
        }
        let number_of_pgcs = read_u16(buf, 0)?;
        let end_address = read_u32(buf, 4)?;
        let n = usize::from(number_of_pgcs);
        let offsets_end = 8usize.saturating_add(n * 4);
        if buf.len() < offsets_end {
            return Err(Error::InvalidUdf(
                "VTS_TMAPTI: offset list past end of buffer",
            ));
        }
        let mut offsets = Vec::with_capacity(n);
        for i in 0..n {
            offsets.push(read_u32(buf, 8 + i * 4)? as usize);
        }
        let mut maps = Vec::with_capacity(n);
        for off in &offsets {
            let tmap_buf = buf.get(*off..).ok_or(Error::InvalidUdf(
                "VTS_TMAPTI: VTS_TMAP offset past end of buffer",
            ))?;
            maps.push(VtsTmap::parse(tmap_buf)?);
        }
        Ok(Self {
            number_of_pgcs,
            end_address,
            maps,
        })
    }

    /// Look up the time map for the 1-based program-chain number.
    pub fn get(&self, pgcn: u16) -> Option<&VtsTmap> {
        if pgcn == 0 {
            return None;
        }
        self.maps.get((pgcn - 1) as usize)
    }
}

// ------------------------------------------------------------------
// High-level chapter / title materialisation
// ------------------------------------------------------------------

/// A chapter (Part-of-Title) at the API surface — pulls fields from
/// the PTT entry, the referenced PGC's cell list, and the C_ADT.
#[derive(Debug, Clone)]
pub struct DvdChapter {
    /// 1-based chapter number within the title.
    pub number: u16,
    /// Program-chain number this chapter lives in.
    pub pgcn: u16,
    /// Program number within that PGC.
    pub pgn: u16,
    /// First cell of this chapter (inclusive, 1-based).
    pub start_cell: u8,
    /// Last cell of this chapter (inclusive, 1-based). For all
    /// chapters but the last in a PGC this is the cell immediately
    /// before the next chapter's `start_cell`; for the last chapter
    /// it is the PGC's final cell.
    pub end_cell: u8,
    /// PGC-relative playback time for this chapter — the BCD field
    /// from the PGC header itself (chapters within a PGC don't carry
    /// their own playback time field, so we surface the PGC total).
    pub playback_time: PgcTime,
}

/// A title at the API surface — pulls fields from TT_SRPT (for the
/// title-level header) and VTS_PTT_SRPT (for the chapter list).
#[derive(Debug, Clone)]
pub struct DvdTitle {
    /// 1-based VTS_TTN — title number within its VTS.
    pub number: u8,
    /// Number of camera angles (1..=9).
    pub angle_count: u8,
    /// Number of chapters (= `chapters.len()`).
    pub chapter_count: u16,
    /// Per-chapter detail.
    pub chapters: Vec<DvdChapter>,
}

/// Parsed VTS — pulls VTSI_MAT, VTS_PTT_SRPT, VTS_PGCI, VTS_C_ADT,
/// VTS_VOBU_ADMAP, and VTS_TMAPTI into a single materialised view
/// that's convenient for chapter enumeration and time-based seek
/// without re-walking the byte buffer.
#[derive(Debug, Clone)]
pub struct VtsIfo {
    /// VTS number (1..=99).
    pub vts_number: u8,
    /// Number of titles in this VTS.
    pub title_count: u8,
    /// Per-title chapter list.
    pub titles: Vec<DvdTitle>,
    /// All program chains in the VTS.
    pub pgcs: Vec<Pgc>,
    /// Cell address table.
    pub cell_adt: VtsCAdt,
    /// Per-VOBU sector list for the title-set VOBs
    /// (`VTS_xx_1.VOB` … `VTS_xx_9.VOB`). `None` when the IFO's
    /// `vts_vobu_admap_sector` field is zero (rare; the spec lists
    /// `VTS_VOBU_ADMAP` as mandatory but some authoring tools
    /// elide it on title sets that hold only menu VOBs).
    pub vobu_admap: Option<VobuAdmap>,
    /// Per-PGC time map. `None` when the IFO's `vts_tmapti_sector`
    /// field is zero (the spec lists `VTS_TMAPTI` as optional —
    /// without it the title set is not time-seekable).
    pub time_map: Option<VtsTmapti>,
    /// Raw VTSI_MAT (kept around so callers can reach sector
    /// pointers for the bits we don't materialise — the
    /// VMGM/VTSM menu tables, the VOBU address maps on the menu
    /// side, etc.).
    pub mat: VtsiMat,
}

impl VtsIfo {
    /// Build a `VtsIfo` from the full IFO byte buffer (the entire
    /// `VTS_xx_0.IFO`, which is `last_sector_ifo` + 1 sectors long).
    ///
    /// Sector pointers in `VTSI_MAT` are interpreted as offsets into
    /// `buf` after multiplication by [`DVD_SECTOR`].
    pub fn parse(buf: &[u8], vts_number: u8) -> Result<Self> {
        let mat = VtsiMat::parse(buf)?;

        // VTS_PTT_SRPT
        let ptt_off = (mat.vts_ptt_srpt_sector as usize)
            .checked_mul(DVD_SECTOR)
            .ok_or(Error::InvalidUdf("VTSI: PTT sector overflow"))?;
        let ptt_buf = buf
            .get(ptt_off..)
            .ok_or(Error::InvalidUdf("VTSI: PTT sector past end"))?;
        let ptt_srpt = VtsPttSrpt::parse(ptt_buf)?;

        // VTS_PGCI
        let pgci_off = (mat.vts_pgci_sector as usize)
            .checked_mul(DVD_SECTOR)
            .ok_or(Error::InvalidUdf("VTSI: PGCI sector overflow"))?;
        let pgci_buf = buf
            .get(pgci_off..)
            .ok_or(Error::InvalidUdf("VTSI: PGCI sector past end"))?;
        let pgci = Pgci::parse(pgci_buf)?;

        // VTS_C_ADT
        let cadt_off = (mat.vts_c_adt_sector as usize)
            .checked_mul(DVD_SECTOR)
            .ok_or(Error::InvalidUdf("VTSI: C_ADT sector overflow"))?;
        let cadt_buf = buf
            .get(cadt_off..)
            .ok_or(Error::InvalidUdf("VTSI: C_ADT sector past end"))?;
        let cell_adt = VtsCAdt::parse(cadt_buf)?;

        // VTS_VOBU_ADMAP (optional — sector 0 means absent).
        let vobu_admap = if mat.vts_vobu_admap_sector != 0 {
            let off = (mat.vts_vobu_admap_sector as usize)
                .checked_mul(DVD_SECTOR)
                .ok_or(Error::InvalidUdf("VTSI: VOBU_ADMAP sector overflow"))?;
            let body = buf
                .get(off..)
                .ok_or(Error::InvalidUdf("VTSI: VOBU_ADMAP sector past end"))?;
            Some(VobuAdmap::parse(body)?)
        } else {
            None
        };

        // VTS_TMAPTI (optional — sector 0 means absent).
        let time_map = if mat.vts_tmapti_sector != 0 {
            let off = (mat.vts_tmapti_sector as usize)
                .checked_mul(DVD_SECTOR)
                .ok_or(Error::InvalidUdf("VTSI: TMAPTI sector overflow"))?;
            let body = buf
                .get(off..)
                .ok_or(Error::InvalidUdf("VTSI: TMAPTI sector past end"))?;
            Some(VtsTmapti::parse(body)?)
        } else {
            None
        };

        // Materialise the chapter list. The PTT entry gives us
        // (PGCN, PGN). To recover (start_cell, end_cell) we look at
        // the referenced PGC's program_map — entry `pgn-1` is the
        // start cell, entry `pgn` (if it exists) is the next chapter's
        // start cell minus one. The last chapter runs through the
        // PGC's last cell.
        let title_count_u8 = u8::try_from(ptt_srpt.title_count.min(255))
            .map_err(|_| Error::InvalidUdf("VTSI: title count > 255"))?;
        let mut titles = Vec::with_capacity(usize::from(title_count_u8));
        for (i, ptt_title) in ptt_srpt.titles.iter().enumerate() {
            let title_number = (i as u8).saturating_add(1);
            let mut chapters = Vec::with_capacity(ptt_title.chapters.len());
            for (ch_i, ptt) in ptt_title.chapters.iter().enumerate() {
                let pgc = pgci
                    .pgcs
                    .get(usize::from(ptt.pgcn.saturating_sub(1)))
                    .ok_or(Error::InvalidUdf(
                        "VTSI: PTT references PGCN past end of PGCI",
                    ))?;
                let pgn_idx = usize::from(ptt.pgn.saturating_sub(1));
                let start_cell = *pgc
                    .program_map
                    .get(pgn_idx)
                    .ok_or(Error::InvalidUdf("VTSI: PTT PGN past program_map"))?;
                // Determine end_cell: next chapter in the same PGC
                // gives us its start_cell - 1; otherwise the PGC's
                // last cell.
                let next_in_same_pgc = ptt_title.chapters.get(ch_i + 1).and_then(|next_ptt| {
                    if next_ptt.pgcn == ptt.pgcn {
                        pgc.program_map
                            .get(usize::from(next_ptt.pgn.saturating_sub(1)))
                            .copied()
                            .map(|next_start| next_start.saturating_sub(1))
                    } else {
                        None
                    }
                });
                let end_cell = next_in_same_pgc.unwrap_or(pgc.number_of_cells);
                chapters.push(DvdChapter {
                    number: (ch_i as u16).saturating_add(1),
                    pgcn: ptt.pgcn,
                    pgn: ptt.pgn,
                    start_cell,
                    end_cell,
                    playback_time: pgc.playback_time,
                });
            }
            let chapter_count = chapters.len() as u16;
            titles.push(DvdTitle {
                number: title_number,
                angle_count: 1,
                chapter_count,
                chapters,
            });
        }

        Ok(Self {
            vts_number,
            title_count: title_count_u8,
            titles,
            pgcs: pgci.pgcs,
            cell_adt,
            vobu_admap,
            time_map,
            mat,
        })
    }

    /// VOB-relative starting sector of the VOBU that covers playback
    /// time `seconds` (PGC-relative) for the 1-based program-chain
    /// number `pgcn`.
    ///
    /// Convenience wrapper around [`VtsTmapti::get`] + [`VtsTmap::sector_at`].
    /// Returns `None` when this title set carries no time map, when
    /// the requested PGCN is past the table, when the map for that
    /// PGC is empty, or when its `time_unit` field is zero.
    ///
    /// To recover the disc-absolute LBA, add
    /// [`VtsiMat::title_vob_sector`] to the returned VOB-relative
    /// sector.
    pub fn vobu_sector_at_pgc_time(&self, pgcn: u16, seconds: u32) -> Option<u32> {
        self.time_map
            .as_ref()
            .and_then(|t| t.get(pgcn))
            .and_then(|m| m.sector_at(seconds))
    }
}

// ------------------------------------------------------------------
// VMG_VTS_ATRT — per-VTS attribute table on the VMG side
// ------------------------------------------------------------------

/// One entry of the `VMG_VTS_ATRT` table.
///
/// Per `mpucoder-ifo_vmg.html` each `VTS_ATRT` body is:
///   - offset `0..4`: end address (EA) of this entry, relative to the
///     entry's own start.
///   - offset `4..8`: `VTS_CAT` — a 32-bit category copy of `0x022..0x025`
///     of the corresponding VTS IFO (`0` = unspecified, `1` = Karaoke).
///   - offset `8..EA-7`: raw copy of the VTS attribute block starting
///     at offset `0x0100` of the VTS IFO (usually `0x300` bytes long;
///     equivalent to the buffer fed to [`parse_menu_attribute_block`] +
///     the title-side block that [`VtsiMat::parse`] already handles).
///
/// We keep the attribute blob as raw bytes so callers that want the
/// typed shape can feed it back through [`MenuAttributes`] /
/// [`TitleAttributes`] reuse without us re-decoding the same fields
/// twice (once here, once in the VTSI proper). The 1-based VTS index
/// is the entry's position in the table.
#[derive(Debug, Clone)]
pub struct VmgVtsAtrtEntry {
    /// 1-based VTS number this entry mirrors.
    pub vts_number: u8,
    /// `VTS_CAT` copy of the VTS IFO's `0x022..0x025` field.
    pub vts_category: u32,
    /// Raw VTS attribute block — a verbatim copy of bytes `0x0100..`
    /// of the corresponding `VTS_xx_0.IFO` file (length = entry-EA - 7).
    pub attributes_blob: Vec<u8>,
}

/// Parsed `VMG_VTS_ATRT` — the per-VTS attribute copies stored on the
/// VMG side.
///
/// `VIDEO_TS.IFO` carries `VMG_VTS_ATRT` so a player can answer
/// per-VTS attribute queries (audio/subpicture stream counts, codec
/// IDs, language codes, …) without having to open every `VTS_xx_0.IFO`
/// individually. Each entry mirrors the attribute block found at the
/// start of the corresponding VTSI body.
#[derive(Debug, Clone)]
pub struct VmgVtsAtrt {
    /// Number of title sets referenced by this table.
    pub number_of_title_sets: u16,
    /// Last byte address of the last `VTS_ATRT` entry — relative to
    /// the start of `VMG_VTS_ATRT` itself.
    pub end_address: u32,
    /// One entry per title set, in `vts_number` order (1-based).
    pub entries: Vec<VmgVtsAtrtEntry>,
}

impl VmgVtsAtrt {
    /// Parse the `VMG_VTS_ATRT` table from a buffer that starts at
    /// the table's first byte.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("VMG_VTS_ATRT: header < 8 bytes"));
        }
        let number_of_title_sets = read_u16(buf, 0)?;
        // bytes 2..4 reserved
        let end_address = read_u32(buf, 4)?;

        let count = usize::from(number_of_title_sets);
        let offset_table_len = count.checked_mul(4).ok_or(Error::InvalidUdf(
            "VMG_VTS_ATRT: title-set count × 4 overflow",
        ))?;
        let header_len = 8usize
            .checked_add(offset_table_len)
            .ok_or(Error::InvalidUdf("VMG_VTS_ATRT: header length overflow"))?;
        if buf.len() < header_len {
            return Err(Error::InvalidUdf("VMG_VTS_ATRT: offset table past end"));
        }

        // Read the offset list first so we can derive the EA of each
        // entry (next-entry-offset minus one, or table EA for the last).
        let mut offsets = Vec::with_capacity(count);
        for i in 0..count {
            offsets.push(read_u32(buf, 8 + i * 4)?);
        }

        let mut entries = Vec::with_capacity(count);
        for (i, &off) in offsets.iter().enumerate() {
            // Per-entry "end address" lives in the entry header at
            // offset 0 (relative to the entry start). Trust the header
            // EA, but bound-check against the next entry's offset
            // (or the table EA) so a malformed entry can't read past
            // the buffer / past the next entry.
            let entry_start = off as usize;
            let entry_hdr = buf
                .get(entry_start..entry_start + 8)
                .ok_or(Error::InvalidUdf("VMG_VTS_ATRT: entry header past buffer"))?;
            let entry_ea_rel =
                u32::from_be_bytes([entry_hdr[0], entry_hdr[1], entry_hdr[2], entry_hdr[3]])
                    as usize;
            let vts_category =
                u32::from_be_bytes([entry_hdr[4], entry_hdr[5], entry_hdr[6], entry_hdr[7]]);
            // The entry's "end_address" is inclusive of the last byte
            // of the entry (zero-based, relative to the entry start);
            // total entry length is therefore `entry_ea_rel + 1`. The
            // attribute blob runs from offset 8 through end-of-entry.
            let entry_total = entry_ea_rel
                .checked_add(1)
                .ok_or(Error::InvalidUdf("VMG_VTS_ATRT: entry EA overflow"))?;
            if entry_total < 8 {
                return Err(Error::InvalidUdf(
                    "VMG_VTS_ATRT: entry length shorter than 8-byte header",
                ));
            }
            // Bound against the next entry's offset (if any) so an
            // overlong EA can't pull bytes out of the following entry.
            let next_start = offsets
                .get(i + 1)
                .map(|&n| n as usize)
                .unwrap_or((end_address as usize).saturating_add(1));
            if entry_start.saturating_add(entry_total) > next_start {
                return Err(Error::InvalidUdf(
                    "VMG_VTS_ATRT: entry EA overlaps next entry",
                ));
            }
            let blob_end = entry_start
                .checked_add(entry_total)
                .ok_or(Error::InvalidUdf("VMG_VTS_ATRT: entry end overflow"))?;
            let blob = buf
                .get(entry_start + 8..blob_end)
                .ok_or(Error::InvalidUdf("VMG_VTS_ATRT: blob past buffer"))?
                .to_vec();
            entries.push(VmgVtsAtrtEntry {
                vts_number: (i as u8).saturating_add(1),
                vts_category,
                attributes_blob: blob,
            });
        }

        Ok(Self {
            number_of_title_sets,
            end_address,
            entries,
        })
    }

    /// Return the entry for the 1-based `vts_number`, or `None` when
    /// the index is past the table.
    pub fn entry(&self, vts_number: u8) -> Option<&VmgVtsAtrtEntry> {
        if vts_number == 0 {
            return None;
        }
        self.entries.get(usize::from(vts_number - 1))
    }
}

// ------------------------------------------------------------------
// VMG_PTL_MAIT — parental management table
// ------------------------------------------------------------------

/// One country-keyed sub-table of `VMG_PTL_MAIT`.
///
/// Each country gets one `PTL_MAIT` body — a flat array of
/// `Nts + 1` 16-bit masks per parental level. The spec describes
/// the body as 8 stacked level-blocks (level 8 first at body offset
/// 0, then level 7, …, level 1 at body offset `14 × (Nts + 1)`).
///
/// `masks[level_minus_one][title_set_index]` is the 16-bit mask for
/// the title set (where `title_set_index = 0` is the VMG itself and
/// `1..=nts` are the title sets in `1..=nts` order).
#[derive(Debug, Clone)]
pub struct PtlMait {
    /// 16-bit country code (BCD-packed ISO 3166 per `mpucoder-sprm.html`).
    pub country_code: u16,
    /// Eight per-level mask arrays. `masks[0]` = level 1, …,
    /// `masks[7]` = level 8 (level order surfaced ascending — easier
    /// to index by `parental_level - 1` than to invert the spec's
    /// descending storage order at every call site).
    ///
    /// Each inner `Vec` has `nts + 1` entries: index `0` = VMG mask,
    /// `1..=nts` = title-set 1..=nts mask. A set bit at position `i`
    /// in `masks[L-1][T]` means title-set `T` is blocked from level `L`
    /// in this country.
    pub masks: [Vec<u16>; 8],
}

impl PtlMait {
    /// Look up the mask for `parental_level` (1..=8) and
    /// `title_set` (0 = VMG, 1..=nts = title set).
    pub fn mask(&self, parental_level: u8, title_set: u8) -> Option<u16> {
        if !(1..=8).contains(&parental_level) {
            return None;
        }
        let level_idx = usize::from(parental_level - 1);
        self.masks[level_idx].get(usize::from(title_set)).copied()
    }
}

/// Parsed `VMG_PTL_MAIT` (parental management country/level table).
///
/// `mpucoder-ifo_vmg.html` documents one country-keyed entry per
/// supported region — each entry pointing at a sub-table of 8
/// parental-level mask arrays of length `nts + 1`. Strict literal
/// reading of the entry layout (8 cells of 16 bits each):
/// `country_code (u16) | reserved (u16) | ptl_mait_offset (u16) |
/// reserved (u16)`. The 16-bit offset bounds the per-country
/// sub-table to within the first 64 KB of `VMG_PTL_MAIT`, which is
/// the natural ceiling on DVD-Video discs (99 title sets × 16 bytes
/// per level × 8 levels = 12.7 KB per country, with up to ~100
/// countries fitting under the bound).
#[derive(Debug, Clone)]
pub struct VmgPtlMait {
    /// Number of countries (each gets one sub-table).
    pub number_of_countries: u16,
    /// Number of title sets (the body sub-tables carry `Nts + 1`
    /// masks per level — index 0 is the VMG-side mask).
    pub number_of_title_sets: u16,
    /// Last byte address of the last `PTL_MAIT` body, relative to
    /// the start of `VMG_PTL_MAIT`.
    pub end_address: u32,
    /// One sub-table per country.
    pub entries: Vec<PtlMait>,
}

impl VmgPtlMait {
    /// Parse `VMG_PTL_MAIT` from a buffer that starts at the
    /// table's first byte.
    pub fn parse(buf: &[u8]) -> Result<Self> {
        if buf.len() < 8 {
            return Err(Error::InvalidUdf("VMG_PTL_MAIT: header < 8 bytes"));
        }
        let number_of_countries = read_u16(buf, 0)?;
        let number_of_title_sets = read_u16(buf, 2)?;
        let end_address = read_u32(buf, 4)?;

        let nts = usize::from(number_of_title_sets);
        let masks_per_level = nts
            .checked_add(1)
            .ok_or(Error::InvalidUdf("VMG_PTL_MAIT: nts + 1 overflow"))?;
        let level_block_bytes = masks_per_level
            .checked_mul(2)
            .ok_or(Error::InvalidUdf("VMG_PTL_MAIT: level block size overflow"))?;
        let body_bytes = level_block_bytes
            .checked_mul(8)
            .ok_or(Error::InvalidUdf("VMG_PTL_MAIT: body size overflow"))?;

        let count = usize::from(number_of_countries);
        // Country entries are 8 bytes each starting at offset 8.
        let header_len = 8usize
            .checked_add(
                count
                    .checked_mul(8)
                    .ok_or(Error::InvalidUdf("VMG_PTL_MAIT: country list × 8 overflow"))?,
            )
            .ok_or(Error::InvalidUdf("VMG_PTL_MAIT: header length overflow"))?;
        if buf.len() < header_len {
            return Err(Error::InvalidUdf("VMG_PTL_MAIT: country list past end"));
        }

        let mut entries = Vec::with_capacity(count);
        for i in 0..count {
            let entry_base = 8 + i * 8;
            let country_code = read_u16(buf, entry_base)?;
            // bytes 2..4 reserved
            let body_offset = usize::from(read_u16(buf, entry_base + 4)?);
            // bytes 6..8 reserved
            let body_end = body_offset
                .checked_add(body_bytes)
                .ok_or(Error::InvalidUdf("VMG_PTL_MAIT: country body end overflow"))?;
            if body_end > buf.len() {
                return Err(Error::InvalidUdf(
                    "VMG_PTL_MAIT: country body past buffer end",
                ));
            }

            // The body stores level 8 first at body_offset, then level 7
            // at body_offset + level_block_bytes, … level 1 at
            // body_offset + 7 × level_block_bytes. Surface them in
            // ascending order so `masks[0]` = level 1.
            let mut masks: [Vec<u16>; 8] = Default::default();
            for level_storage_idx in 0..8 {
                // Storage idx 0 = level 8; storage idx 7 = level 1.
                let level_value = 8 - level_storage_idx; // 8..=1
                let block_start = body_offset + level_storage_idx * level_block_bytes;
                let mut row = Vec::with_capacity(masks_per_level);
                for slot in 0..masks_per_level {
                    row.push(read_u16(buf, block_start + slot * 2)?);
                }
                masks[level_value - 1] = row;
            }

            entries.push(PtlMait {
                country_code,
                masks,
            });
        }

        Ok(Self {
            number_of_countries,
            number_of_title_sets,
            end_address,
            entries,
        })
    }

    /// Look up the country-keyed sub-table for the given 16-bit
    /// country code.
    pub fn country(&self, country_code: u16) -> Option<&PtlMait> {
        self.entries.iter().find(|e| e.country_code == country_code)
    }
}

// ------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------

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

    // -------------------------------------------------------------
    // PgcTime decode
    // -------------------------------------------------------------

    #[test]
    fn pgc_time_decode_ntsc_30() {
        // 01:23:45.20 @ 30 fps → bytes 0x01 0x23 0x45 (0b11_10_0000 = 0xE0).
        // Frame field: bits 7+6 = 11 (30 fps), bits 5+4 = 0b10 = 2 in BCD
        // hi-nibble (frame tens), bits 3+0 = 0b0000 = 0 in BCD lo-nibble.
        // So frames = 2 * 10 + 0 = 20.
        let t = PgcTime::from_bytes([0x01, 0x23, 0x45, 0xE0]);
        assert_eq!(t.hours, 1);
        assert_eq!(t.minutes, 23);
        assert_eq!(t.seconds, 45);
        assert_eq!(t.frames, 20);
        assert_eq!(t.frame_rate, FrameRate::Ntsc30);
        assert_eq!(t.total_seconds(), 3600 + 23 * 60 + 45);
    }

    #[test]
    fn pgc_time_decode_pal_25() {
        // 00:00:01.00 @ 25 fps → bytes 0x00 0x00 0x01 (0b01_00_0000 = 0x40).
        let t = PgcTime::from_bytes([0x00, 0x00, 0x01, 0x40]);
        assert_eq!(t.frame_rate, FrameRate::Pal25);
        assert_eq!(t.frames, 0);
        assert_eq!(t.total_seconds(), 1);
    }

    // -------------------------------------------------------------
    // PgcTime::to_nanoseconds — exposes the per-rate fractional-frame
    // conversion that mkv_writer previously held privately.
    // -------------------------------------------------------------

    #[test]
    fn pgc_time_to_ns_ntsc_30_integer_seconds() {
        // 00:00:01.00 @ 30 fps → exactly 1 second, no frame fraction.
        let t = PgcTime::from_bytes([0x00, 0x00, 0x01, 0xC0]);
        assert_eq!(t.frame_rate, FrameRate::Ntsc30);
        assert_eq!(t.to_nanoseconds(), 1_000_000_000);
    }

    #[test]
    fn pgc_time_to_ns_ntsc_30_half_second() {
        // 00:00:01.15 @ 30 fps → 1 s + 15/30 s = 1.5 s exact.
        // Frame byte: rate=11, frames-tens=01 (bits 5+4), frames-units=0101
        //   = 0b11_01_0101 = 0xD5. BCD frames hi-nibble = 1, lo-nibble = 5
        //   → 15 frames.
        let t = PgcTime::from_bytes([0x00, 0x00, 0x01, 0xD5]);
        assert_eq!(t.frame_rate, FrameRate::Ntsc30);
        assert_eq!(t.frames, 15);
        assert_eq!(t.to_nanoseconds(), 1_500_000_000);
    }

    #[test]
    fn pgc_time_to_ns_pal_25_frame_period() {
        // 00:00:00.01 @ 25 fps → 1 frame × 40_000_000 ns/frame = 40 ms.
        // Frame byte: rate=01, frames=01 → 0b01_00_0001 = 0x41.
        let t = PgcTime::from_bytes([0x00, 0x00, 0x00, 0x41]);
        assert_eq!(t.frame_rate, FrameRate::Pal25);
        assert_eq!(t.frames, 1);
        assert_eq!(t.to_nanoseconds(), 40_000_000);
    }

    #[test]
    fn pgc_time_to_ns_illegal_rate_drops_frames() {
        // 00:00:02.07 with rate bits = 00 (illegal). Whole-seconds
        // portion survives; the 7-frame fraction is dropped because the
        // spec defines no rate to scale it by.
        let t = PgcTime::from_bytes([0x00, 0x00, 0x02, 0x07]);
        assert_eq!(t.frame_rate, FrameRate::Illegal);
        assert_eq!(t.frames, 7);
        assert_eq!(t.to_nanoseconds(), 2_000_000_000);
    }

    // -------------------------------------------------------------
    // VMGI MAT parse
    // -------------------------------------------------------------

    fn build_vmg_mat() -> Vec<u8> {
        let mut b = vec![0u8; 0x200];
        b[0..12].copy_from_slice(VMG_MAGIC);
        // 0x000C: last sector of VMG set = 1000
        b[0x000C..0x0010].copy_from_slice(&1000u32.to_be_bytes());
        // 0x001C: last sector of IFO = 4
        b[0x001C..0x0020].copy_from_slice(&4u32.to_be_bytes());
        // 0x0020: version 0x0011 (major 1, minor 1)
        b[0x0020..0x0022].copy_from_slice(&0x0011u16.to_be_bytes());
        // 0x0022: VMG category (region mask byte 1 = 0xFF "no region")
        b[0x0022..0x0026].copy_from_slice(&0x00FF_0000u32.to_be_bytes());
        // 0x0026: number of volumes = 1
        b[0x0026..0x0028].copy_from_slice(&1u16.to_be_bytes());
        // 0x0028: volume number = 1
        b[0x0028..0x002A].copy_from_slice(&1u16.to_be_bytes());
        // 0x002A: side ID = 0
        b[0x002A] = 0;
        // 0x003E: number of title sets = 2
        b[0x003E..0x0040].copy_from_slice(&2u16.to_be_bytes());
        // 0x0040: provider ID "OXIDEAV-TEST"
        let pid = b"OXIDEAV-TEST";
        b[0x0040..0x0040 + pid.len()].copy_from_slice(pid);
        // 0x0080: VMGI_MAT end
        b[0x0080..0x0084].copy_from_slice(&0x01FFu32.to_be_bytes());
        // 0x0084: FP_PGC start address = 0
        b[0x0084..0x0088].copy_from_slice(&0u32.to_be_bytes());
        // 0x00C0: menu VOB sector = 0 (no menu)
        // 0x00C4: TT_SRPT sector = 1
        b[0x00C4..0x00C8].copy_from_slice(&1u32.to_be_bytes());
        // 0x00C8: VMGM_PGCI_UT sector = 0
        // 0x00CC: VMG_PTL_MAIT sector = 0
        // 0x00D0: VMG_VTS_ATRT sector = 2
        b[0x00D0..0x00D4].copy_from_slice(&2u32.to_be_bytes());
        // 0x00D4: TXTDT_MG sector = 0
        // 0x00D8: VMGM_C_ADT sector = 0
        // 0x00DC: VMGM_VOBU_ADMAP sector = 0
        b
    }

    #[test]
    fn vmgi_mat_parse_roundtrip() {
        let buf = build_vmg_mat();
        let vmg = VmgIfo::parse(&buf).unwrap();
        assert_eq!(vmg.last_sector_vmg_set, 1000);
        assert_eq!(vmg.last_sector_ifo, 4);
        assert_eq!(vmg.version, 0x0011);
        assert_eq!(vmg.number_of_volumes, 1);
        assert_eq!(vmg.volume_number, 1);
        assert_eq!(vmg.side_id, 0);
        assert_eq!(vmg.number_of_title_sets, 2);
        assert_eq!(vmg.provider_id, "OXIDEAV-TEST");
        assert_eq!(vmg.tt_srpt_sector, 1);
        assert_eq!(vmg.vts_atrt_sector, 2);
        assert_eq!(vmg.menu_vob_sector, 0);
    }

    #[test]
    fn vmgi_mat_rejects_bad_magic() {
        let mut buf = build_vmg_mat();
        buf[0..12].copy_from_slice(b"DVDVIDEO-BAD");
        let err = VmgIfo::parse(&buf).unwrap_err();
        match err {
            Error::InvalidUdf(_) => {}
            other => panic!("expected InvalidUdf, got {other:?}"),
        }
    }

    // -------------------------------------------------------------
    // VTSI MAT parse
    // -------------------------------------------------------------

    fn build_vtsi_mat(
        ptt_srpt_sector: u32,
        pgci_sector: u32,
        c_adt_sector: u32,
        title_vob_sector: u32,
    ) -> Vec<u8> {
        let mut b = vec![0u8; 0x200];
        b[0..12].copy_from_slice(VTS_MAGIC);
        // last_sector_title_set
        b[0x000C..0x0010].copy_from_slice(&100_000u32.to_be_bytes());
        // last_sector_ifo
        b[0x001C..0x0020].copy_from_slice(&15u32.to_be_bytes());
        // version 0x0011
        b[0x0020..0x0022].copy_from_slice(&0x0011u16.to_be_bytes());
        // VTS category = 0
        // VTSI_MAT end
        b[0x0080..0x0084].copy_from_slice(&0x01FFu32.to_be_bytes());
        // menu VOB sector = 0
        // title VOB sector
        b[0x00C4..0x00C8].copy_from_slice(&title_vob_sector.to_be_bytes());
        // PTT_SRPT
        b[0x00C8..0x00CC].copy_from_slice(&ptt_srpt_sector.to_be_bytes());
        // PGCI
        b[0x00CC..0x00D0].copy_from_slice(&pgci_sector.to_be_bytes());
        // VTSM_PGCI_UT = 0
        // VTS_TMAPTI = 0
        // VTSM_C_ADT = 0
        // VTSM_VOBU_ADMAP = 0
        // VTS_C_ADT
        b[0x00E0..0x00E4].copy_from_slice(&c_adt_sector.to_be_bytes());
        // VTS_VOBU_ADMAP = 0
        b
    }

    #[test]
    fn vtsi_mat_parse_roundtrip() {
        let buf = build_vtsi_mat(1, 2, 3, 42);
        let mat = VtsiMat::parse(&buf).unwrap();
        assert_eq!(mat.last_sector_title_set, 100_000);
        assert_eq!(mat.last_sector_ifo, 15);
        assert_eq!(mat.version, 0x0011);
        assert_eq!(mat.title_vob_sector, 42);
        assert_eq!(mat.vts_ptt_srpt_sector, 1);
        assert_eq!(mat.vts_pgci_sector, 2);
        assert_eq!(mat.vts_c_adt_sector, 3);
    }

    // -------------------------------------------------------------
    // TT_SRPT
    // -------------------------------------------------------------

    fn build_tt_srpt(entries: &[(u8, u8, u16, u8, u8, u32)]) -> Vec<u8> {
        // 8-byte header + N * 12 entries.
        let n = entries.len();
        let len = 8 + n * 12;
        let mut b = vec![0u8; len];
        b[0..2].copy_from_slice(&(n as u16).to_be_bytes());
        // reserved at 2..4 = 0
        // end_address = last byte of last entry, relative to start
        let end_addr = (len - 1) as u32;
        b[4..8].copy_from_slice(&end_addr.to_be_bytes());
        for (i, e) in entries.iter().enumerate() {
            let base = 8 + i * 12;
            b[base] = e.0; // title_type
            b[base + 1] = e.1; // angle_count
            b[base + 2..base + 4].copy_from_slice(&e.2.to_be_bytes()); // chapter_count
            b[base + 4..base + 6].copy_from_slice(&0u16.to_be_bytes()); // parental_mask
            b[base + 6] = e.3; // vts_number
            b[base + 7] = e.4; // vts_title_number
            b[base + 8..base + 12].copy_from_slice(&e.5.to_be_bytes()); // vts_start_sector
            let _ = e; // suppress unused
        }
        b
    }

    #[test]
    fn tt_srpt_parses_titles() {
        // 3 titles: VTS1-title1 (15 chapters), VTS1-title2 (4 chapters),
        // VTS2-title1 (1 chapter).
        let entries = [
            (0x3F, 1u8, 15u16, 1u8, 1u8, 0x0000_0500u32),
            (0x3F, 1u8, 4u16, 1u8, 2u8, 0x0000_0500u32),
            (0x3F, 2u8, 1u16, 2u8, 1u8, 0x0000_8000u32),
        ];
        let buf = build_tt_srpt(&entries);
        let srpt = TtSrpt::parse(&buf).unwrap();
        assert_eq!(srpt.title_count, 3);
        assert_eq!(srpt.end_address, (8 + 3 * 12 - 1) as u32);
        assert_eq!(srpt.entries[0].chapter_count, 15);
        assert_eq!(srpt.entries[1].vts_title_number, 2);
        assert_eq!(srpt.entries[2].vts_number, 2);
        assert_eq!(srpt.entries[2].angle_count, 2);
        assert_eq!(srpt.entries[2].vts_start_sector, 0x0000_8000);
    }

    // -------------------------------------------------------------
    // VTS_C_ADT
    // -------------------------------------------------------------

    fn build_c_adt(rows: &[(u16, u8, u32, u32)]) -> Vec<u8> {
        let n = rows.len();
        let len = 8 + n * 12;
        let mut b = vec![0u8; len];
        // number_of_vob_ids — let's pick the distinct vob count
        let distinct = {
            let mut v: Vec<u16> = rows.iter().map(|r| r.0).collect();
            v.sort();
            v.dedup();
            v.len() as u16
        };
        b[0..2].copy_from_slice(&distinct.to_be_bytes());
        // end_address = last byte of last entry, relative to start
        let end_addr = (len - 1) as u32;
        b[4..8].copy_from_slice(&end_addr.to_be_bytes());
        for (i, r) in rows.iter().enumerate() {
            let base = 8 + i * 12;
            b[base..base + 2].copy_from_slice(&r.0.to_be_bytes());
            b[base + 2] = r.1;
            // reserved at +3 = 0
            b[base + 4..base + 8].copy_from_slice(&r.2.to_be_bytes());
            b[base + 8..base + 12].copy_from_slice(&r.3.to_be_bytes());
        }
        b
    }

    #[test]
    fn c_adt_parses_four_rows() {
        // 4 cells: VOB 1 → cells 1 + 2 + 3; VOB 2 → cell 1.
        let rows = [
            (1u16, 1u8, 100u32, 199u32),
            (1u16, 2u8, 200u32, 299u32),
            (1u16, 3u8, 300u32, 399u32),
            (2u16, 1u8, 1000u32, 1999u32),
        ];
        let buf = build_c_adt(&rows);
        let adt = VtsCAdt::parse(&buf).unwrap();
        assert_eq!(adt.number_of_vob_ids, 2);
        assert_eq!(adt.entries.len(), 4);
        assert_eq!(adt.lookup(1, 2), Some((200, 299)));
        assert_eq!(adt.lookup(2, 1), Some((1000, 1999)));
        assert_eq!(adt.lookup(3, 1), None);
    }

    // -------------------------------------------------------------
    // PGCI with 1 PGC + 3 cells
    // -------------------------------------------------------------

    fn build_pgc_with_cells(cells: &[CellPlaybackInfo], positions: &[CellPositionInfo]) -> Vec<u8> {
        assert_eq!(cells.len(), positions.len());
        let n = cells.len();
        // PGC header is 0xEC bytes. Then program map (1 program, 1
        // byte each, padded to word boundary). Then C_PBI (24*n). Then
        // C_POS (4*n).
        let header_size = 0xEC;
        let prog_count = 1u8;
        let prog_map_size = (usize::from(prog_count) + 1) & !1; // pad to word
        let pre_n = 1usize; // command table: 1 pre + 1 post + 2 cell = 4 words
        let post_n = 1usize;
        let cmd_cell_n = 2usize;
        let cmd_table_size = 8 + (pre_n + post_n + cmd_cell_n) * 8;
        let cpbi_size = n * 24;
        let cpos_size = n * 4;
        let mut b = vec![0u8; header_size + cmd_table_size + prog_map_size + cpbi_size + cpos_size];

        // number_of_programs at 0x0002
        b[0x0002] = prog_count;
        // number_of_cells at 0x0003
        b[0x0003] = n as u8;
        // playback time
        b[0x0004..0x0008].copy_from_slice(&[0x00, 0x05, 0x00, 0xE0]); // 00:05:00.00 @ 30fps
                                                                      // 0x0008..: prohibited UOPs = 0
                                                                      // next/prev/goup at 0x009C / 0x009E / 0x00A0 = 0
                                                                      // still time, playback mode = 0

        // Palette at 0x00A4: 16 × (0, Y, Cr, Cb). Fill entry i with a
        // deterministic (Y=0x10+i, Cr=0x80, Cb=0x80) so the round-trip
        // can assert the layout decode.
        for i in 0..16usize {
            let base = 0x00A4 + i * 4;
            b[base] = 0x00; // reserved
            b[base + 1] = 0x10 + i as u8; // Y
            b[base + 2] = 0x80; // Cr
            b[base + 3] = 0x80; // Cb
        }

        let off_cmd = header_size as u16; // command table right after header
        let off_pmap = (header_size + cmd_table_size) as u16;
        let off_cpbi = (header_size + cmd_table_size + prog_map_size) as u16;
        let off_cpos = (header_size + cmd_table_size + prog_map_size + cpbi_size) as u16;
        b[0x00E4..0x00E6].copy_from_slice(&off_cmd.to_be_bytes());
        b[0x00E6..0x00E8].copy_from_slice(&off_pmap.to_be_bytes());
        b[0x00E8..0x00EA].copy_from_slice(&off_cpbi.to_be_bytes());
        b[0x00EA..0x00EC].copy_from_slice(&off_cpos.to_be_bytes());

        // Command table header + words. Each word is tagged in byte 0
        // so the round-trip can tell pre/post/cell apart.
        let ct = header_size;
        b[ct..ct + 2].copy_from_slice(&(pre_n as u16).to_be_bytes());
        b[ct + 2..ct + 4].copy_from_slice(&(post_n as u16).to_be_bytes());
        b[ct + 4..ct + 6].copy_from_slice(&(cmd_cell_n as u16).to_be_bytes());
        b[ct + 6..ct + 8].copy_from_slice(&((cmd_table_size - 1) as u16).to_be_bytes());
        let mut w = ct + 8;
        b[w] = 0xA0; // pre[0]: command_type = 0b101
        b[w + 7] = 0x01;
        w += 8;
        b[w] = 0xB0; // post[0]
        b[w + 7] = 0x02;
        w += 8;
        b[w] = 0xC0; // cell[0]
        b[w + 7] = 0x03;
        w += 8;
        b[w] = 0xC1; // cell[1]
        b[w + 7] = 0x04;

        // program map: 1 program starting at cell 1
        b[off_pmap as usize] = 1;
        // (no padding needed since prog_map_size already includes pad)

        // C_PBI
        for (i, c) in cells.iter().enumerate() {
            let base = off_cpbi as usize + i * 24;
            b[base] = c.category_byte0;
            b[base + 1] = if c.restricted { 0x80 } else { 0 };
            b[base + 2] = c.still_time;
            b[base + 3] = c.cell_command;
            // playback time — synthesise a deterministic field
            b[base + 4] = 0x00;
            b[base + 5] = 0x01;
            b[base + 6] = 0x00;
            b[base + 7] = 0xE0;
            b[base + 8..base + 12].copy_from_slice(&c.first_vobu_start_sector.to_be_bytes());
            b[base + 12..base + 16].copy_from_slice(&c.first_ilvu_end_sector.to_be_bytes());
            b[base + 16..base + 20].copy_from_slice(&c.last_vobu_start_sector.to_be_bytes());
            b[base + 20..base + 24].copy_from_slice(&c.last_vobu_end_sector.to_be_bytes());
        }

        // C_POS
        for (i, p) in positions.iter().enumerate() {
            let base = off_cpos as usize + i * 4;
            b[base..base + 2].copy_from_slice(&p.vob_id.to_be_bytes());
            b[base + 3] = p.cell_id;
        }
        b
    }

    fn make_cell(start: u32, end: u32) -> CellPlaybackInfo {
        CellPlaybackInfo {
            category_byte0: 0,
            restricted: false,
            still_time: 0,
            cell_command: 0,
            playback_time: PgcTime::from_bytes([0, 1, 0, 0xE0]),
            first_vobu_start_sector: start,
            first_ilvu_end_sector: start + 5,
            last_vobu_start_sector: end - 5,
            last_vobu_end_sector: end,
        }
    }

    #[test]
    fn pgci_parses_one_pgc_with_three_cells() {
        let cells = [
            make_cell(1000, 1999),
            make_cell(2000, 2999),
            make_cell(3000, 3999),
        ];
        let positions = [
            CellPositionInfo {
                vob_id: 1,
                cell_id: 1,
            },
            CellPositionInfo {
                vob_id: 1,
                cell_id: 2,
            },
            CellPositionInfo {
                vob_id: 1,
                cell_id: 3,
            },
        ];
        let pgc_blob = build_pgc_with_cells(&cells, &positions);

        // Wrap that single PGC into a PGCI: 8-byte header + 1 SRP
        // entry (8 bytes) + the PGC body.
        let srp_size = 8usize;
        let body_off = 8 + srp_size; // PGC starts here
        let total = body_off + pgc_blob.len();
        let mut b = vec![0u8; total];
        // number_of_pgcs = 1
        b[0..2].copy_from_slice(&1u16.to_be_bytes());
        // reserved at 2..4 = 0
        // end_address = total - 1
        b[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());
        // SRP[0]: category 0, offset = body_off
        b[8..12].copy_from_slice(&0u32.to_be_bytes());
        b[12..16].copy_from_slice(&(body_off as u32).to_be_bytes());
        // Copy PGC body
        b[body_off..body_off + pgc_blob.len()].copy_from_slice(&pgc_blob);

        let pgci = Pgci::parse(&b).unwrap();
        assert_eq!(pgci.number_of_pgcs, 1);
        assert_eq!(pgci.pgcs.len(), 1);
        let pgc = &pgci.pgcs[0];
        assert_eq!(pgc.number_of_programs, 1);
        assert_eq!(pgc.number_of_cells, 3);
        assert_eq!(pgc.cells.len(), 3);
        assert_eq!(pgc.cell_positions.len(), 3);
        assert_eq!(pgc.cells[0].first_vobu_start_sector, 1000);
        assert_eq!(pgc.cells[2].last_vobu_end_sector, 3999);
        assert_eq!(pgc.cell_positions[1].cell_id, 2);
        assert_eq!(pgc.playback_time.frame_rate, FrameRate::Ntsc30);

        // Palette decode: entry i carries (Y=0x10+i, Cr=0x80, Cb=0x80).
        assert_eq!(
            pgc.palette[0],
            PaletteEntry {
                y: 0x10,
                cr: 0x80,
                cb: 0x80
            }
        );
        assert_eq!(
            pgc.palette[15],
            PaletteEntry {
                y: 0x1F,
                cr: 0x80,
                cb: 0x80
            }
        );

        // Command table: 1 pre + 1 post + 2 cell, tagged in byte 0.
        let cmds = pgc.commands.as_ref().expect("command table present");
        assert_eq!(cmds.pre.len(), 1);
        assert_eq!(cmds.post.len(), 1);
        assert_eq!(cmds.cell.len(), 2);
        assert_eq!(cmds.pre[0].bytes[0], 0xA0);
        assert_eq!(cmds.pre[0].bytes[7], 0x01);
        assert_eq!(cmds.pre[0].command_type(), 0b101);
        assert_eq!(cmds.post[0].bytes[0], 0xB0);
        assert_eq!(cmds.post[0].bytes[7], 0x02);
        assert_eq!(cmds.cell[0].bytes[7], 0x03);
        assert_eq!(cmds.cell[1].bytes[7], 0x04);
    }

    // -------------------------------------------------------------
    // PGC palette + command table — focused unit tests
    // -------------------------------------------------------------

    #[test]
    fn palette_entry_skips_reserved_byte() {
        // (reserved, Y, Cr, Cb)
        let e = PaletteEntry::parse(&[0xFF, 0x42, 0x10, 0xC0]).unwrap();
        assert_eq!(
            e,
            PaletteEntry {
                y: 0x42,
                cr: 0x10,
                cb: 0xC0
            }
        );
        // Too short → error.
        assert!(PaletteEntry::parse(&[0x00, 0x01, 0x02]).is_err());
    }

    #[test]
    fn command_table_carves_three_lists() {
        // 2 pre + 1 post + 1 cell = 4 words.
        let pre = 2u16;
        let post = 1u16;
        let cell = 1u16;
        let total = (pre + post + cell) as usize;
        let size = 8 + total * 8;
        let mut b = vec![0u8; size];
        b[0..2].copy_from_slice(&pre.to_be_bytes());
        b[2..4].copy_from_slice(&post.to_be_bytes());
        b[4..6].copy_from_slice(&cell.to_be_bytes());
        b[6..8].copy_from_slice(&((size - 1) as u16).to_be_bytes());
        // Tag each word's last byte with its 1-based index.
        for i in 0..total {
            b[8 + i * 8 + 7] = (i + 1) as u8;
        }
        let t = PgcCommandTable::parse(&b).unwrap();
        assert_eq!(t.pre.len(), 2);
        assert_eq!(t.post.len(), 1);
        assert_eq!(t.cell.len(), 1);
        assert_eq!(t.end_address, (size - 1) as u16);
        // pre = words 1,2; post = word 3; cell = word 4.
        assert_eq!(t.pre[0].bytes[7], 1);
        assert_eq!(t.pre[1].bytes[7], 2);
        assert_eq!(t.post[0].bytes[7], 3);
        assert_eq!(t.cell[0].bytes[7], 4);
    }

    #[test]
    fn command_table_rejects_overlong_count() {
        // pre alone claims 129 words → > 128 invariant violated.
        let mut b = vec![0u8; 8];
        b[0..2].copy_from_slice(&129u16.to_be_bytes());
        assert!(PgcCommandTable::parse(&b).is_err());
    }

    #[test]
    fn command_table_rejects_truncated_list() {
        // Header claims 2 words but the buffer only holds one.
        let mut b = vec![0u8; 8 + 8];
        b[0..2].copy_from_slice(&2u16.to_be_bytes());
        assert!(PgcCommandTable::parse(&b).is_err());
    }

    // -------------------------------------------------------------
    // PgcCommandTable — typed-instruction iterator surface
    // -------------------------------------------------------------

    /// Build a synthetic `PgcCommandTable` with 1 pre + 1 post +
    /// 3 cell words covering distinct instruction types so the
    /// iterators below have something to discriminate on.
    fn synth_command_table() -> PgcCommandTable {
        let pre = 1u16;
        let post = 1u16;
        let cell = 3u16;
        let total = (pre + post + cell) as usize;
        let size = 8 + total * 8;
        let mut b = vec![0u8; size];
        b[0..2].copy_from_slice(&pre.to_be_bytes());
        b[2..4].copy_from_slice(&post.to_be_bytes());
        b[4..6].copy_from_slice(&cell.to_be_bytes());
        b[6..8].copy_from_slice(&((size - 1) as u16).to_be_bytes());
        // Word layout (per mpucoder-vmi.html "command word layout"):
        //   byte 0 = TTT D SSSS where TTT = type (bits 7..5),
        //     D = SET-direct flag (bit 4), SSSS = SET-op nibble.
        //   byte 1 = C HHH CCCC where C = CMP-direct (bit 7),
        //     HHH = CMP-op (bits 6..4), CCCC = cmd_nibble (bits 3..0).
        // pre[0] stays all-zero at offset 8 → Type 0 + cmd_nibble 0
        //   = NOP per `decode_type0`.
        // post[0]: Type 1 jumpcall + cmd_nibble 1 = Exit. Byte 0
        //   needs the SET-direct bit (D=1) so the dispatcher routes
        //   to `decode_type1_jumpcall`.
        let post_off = 8 + 8;
        b[post_off] = 0b0011_0000;
        b[post_off + 1] = 0x01;
        // cell[0]: same Type 1 Exit encoding as post[0].
        let cell0 = post_off + 8;
        b[cell0] = 0b0011_0000;
        b[cell0 + 1] = 0x01;
        // cell[1]: Type 0 Break — byte 0 = 0, cmd_nibble = 2.
        let cell1 = cell0 + 8;
        b[cell1] = 0x00;
        b[cell1 + 1] = 0x02;
        // cell[2]: Type 0 NOP — all zeros (already).
        PgcCommandTable::parse(&b).unwrap()
    }

    #[test]
    fn pgc_cmd_table_typed_iterators_walk_all_three_lists() {
        let t = synth_command_table();
        let pre: Vec<_> = t.pre_instructions().collect();
        let post: Vec<_> = t.post_instructions().collect();
        let cell: Vec<_> = t.cell_instructions().collect();
        assert_eq!(pre.len(), 1);
        assert_eq!(post.len(), 1);
        assert_eq!(cell.len(), 3);
        // pre[0] = NOP per the synth payload.
        assert!(matches!(pre[0], crate::nav::NavInstruction::Nop));
        // post[0] = Exit per the Type 1 / link-family `0x01` encoding.
        assert!(matches!(post[0], crate::nav::NavInstruction::Exit));
        // cell[0] = Exit; cell[1] = Break; cell[2] = NOP.
        assert!(matches!(cell[0], crate::nav::NavInstruction::Exit));
        assert!(matches!(cell[1], crate::nav::NavInstruction::Break));
        assert!(matches!(cell[2], crate::nav::NavInstruction::Nop));
    }

    #[test]
    fn pgc_cmd_table_cell_instruction_uses_one_based_index() {
        let t = synth_command_table();
        // Spec: cell_command = 0 means "no command associated"; the
        // accessor returns None.
        assert!(t.cell_instruction(0).is_none());
        // 1-based indexing — index 1 picks cell[0] = Exit.
        assert!(matches!(
            t.cell_instruction(1),
            Some(crate::nav::NavInstruction::Exit)
        ));
        // index 2 picks cell[1] = Break.
        assert!(matches!(
            t.cell_instruction(2),
            Some(crate::nav::NavInstruction::Break)
        ));
        // index 3 picks cell[2] = NOP.
        assert!(matches!(
            t.cell_instruction(3),
            Some(crate::nav::NavInstruction::Nop)
        ));
        // Out-of-range index returns None rather than panicking.
        assert!(t.cell_instruction(4).is_none());
        assert!(t.cell_instruction(u16::MAX).is_none());
    }

    #[test]
    fn nav_command_decode_instruction_matches_nav_decode() {
        // Same NavCommand word reached through the IFO-side
        // convenience and the explicit `nav` disassembler should
        // yield the same typed instruction.
        let mut bytes = [0u8; 8];
        bytes[0] = 0b0011_0000; // Type 1 + SET-direct → jumpcall family.
        bytes[1] = 0x01; // cmd_nibble = 1 → Exit.
        let raw = NavCommand { bytes };
        assert_eq!(raw.decode_instruction(), raw.decode());
        assert!(matches!(
            raw.decode_instruction(),
            crate::nav::NavInstruction::Exit
        ));
    }

    #[test]
    fn pgc_without_command_table_yields_none() {
        // build_pgc_with_cells always emits a command table; build a
        // minimal header-only PGC with offset_commands == 0.
        let mut b = vec![0u8; 0xEC];
        b[0x0002] = 0; // 0 programs
        b[0x0003] = 0; // 0 cells
        b[0x0004..0x0008].copy_from_slice(&[0x00, 0x00, 0x00, 0xC0]); // PAL 25 fps
                                                                      // all four table offsets stay 0
        let pgc = Pgc::parse(&b).unwrap();
        assert!(pgc.commands.is_none());
        // Palette defaults to all-zero when bytes are zero.
        assert_eq!(pgc.palette[7], PaletteEntry::default());
    }

    // -------------------------------------------------------------
    // VTS_PTT_SRPT walking 2 titles × 5 chapters
    // -------------------------------------------------------------

    #[test]
    fn ptt_srpt_walks_two_titles_five_chapters() {
        // 2 titles × 5 chapters each = 10 PTT entries × 4 bytes = 40 bytes
        // of chapter data. Plus 8-byte header + 2 × 4-byte offsets = 16
        // bytes of header. Total = 56 bytes.
        let n_titles = 2usize;
        let n_chaps = 5usize;
        let offsets_size = n_titles * 4;
        let header_size = 8 + offsets_size;
        let title_body_size = n_chaps * 4;
        let total = header_size + n_titles * title_body_size;
        let mut b = vec![0u8; total];
        // number_of_titles
        b[0..2].copy_from_slice(&(n_titles as u16).to_be_bytes());
        // end_address = total - 1
        b[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());
        // offset_to_PTT[1] = header_size
        // offset_to_PTT[2] = header_size + title_body_size
        for ti in 0..n_titles {
            let off = (header_size + ti * title_body_size) as u32;
            b[8 + ti * 4..8 + ti * 4 + 4].copy_from_slice(&off.to_be_bytes());
        }
        // Fill chapter entries: PGCN = title_number, PGN = chapter_number
        for ti in 0..n_titles {
            for ci in 0..n_chaps {
                let base = header_size + ti * title_body_size + ci * 4;
                let pgcn = (ti + 1) as u16;
                let pgn = (ci + 1) as u16;
                b[base..base + 2].copy_from_slice(&pgcn.to_be_bytes());
                b[base + 2..base + 4].copy_from_slice(&pgn.to_be_bytes());
            }
        }

        let srpt = VtsPttSrpt::parse(&b).unwrap();
        assert_eq!(srpt.title_count, 2);
        assert_eq!(srpt.titles.len(), 2);
        for ti in 0..n_titles {
            assert_eq!(srpt.titles[ti].chapters.len(), 5);
            assert_eq!(srpt.titles[ti].chapters[0].pgcn, (ti + 1) as u16);
            assert_eq!(srpt.titles[ti].chapters[0].pgn, 1);
            assert_eq!(srpt.titles[ti].chapters[4].pgn, 5);
        }
    }

    // -------------------------------------------------------------
    // Round-trip composite: VTSI_MAT + PTT_SRPT + PGCI + C_ADT
    // -------------------------------------------------------------

    fn make_composite_vts() -> Vec<u8> {
        // We lay out a minimal IFO image:
        //   sector 0: VTSI_MAT
        //   sector 1: VTS_PTT_SRPT (1 title × 3 chapters)
        //   sector 2: VTS_PGCI (1 PGC with 5 cells; 3 programs)
        //   sector 3: VTS_C_ADT (5 cell entries)
        let mut img = vec![0u8; DVD_SECTOR * 4];

        // ---------- Sector 0: VTSI_MAT ----------
        let mat = build_vtsi_mat(1, 2, 3, 100);
        img[0..mat.len()].copy_from_slice(&mat);

        // ---------- Sector 2: VTS_PGCI ----------
        // 1 PGC with 5 cells (and 3 programs: cells 1, 3, 5 are
        // program entry points). Cells: 1, 2, 3, 4, 5 with disjoint
        // sector ranges.
        let cells: Vec<CellPlaybackInfo> = (0..5)
            .map(|i| make_cell(1000 + i * 1000, 1999 + i * 1000))
            .collect();
        let positions: Vec<CellPositionInfo> = (0..5)
            .map(|i| CellPositionInfo {
                vob_id: 1,
                cell_id: (i + 1) as u8,
            })
            .collect();
        // build_pgc_with_cells assumes 1 program; we extend manually
        // to 3 programs whose program_map = [1, 3, 5].
        let header_size = 0xEC;
        let prog_count = 3u8;
        let prog_map_size = (usize::from(prog_count) + 1) & !1; // 4
        let cpbi_size = 5 * 24;
        let cpos_size = 5 * 4;
        let pgc_blob_len = header_size + prog_map_size + cpbi_size + cpos_size;
        let mut pgc_blob = vec![0u8; pgc_blob_len];
        pgc_blob[0x0002] = prog_count;
        pgc_blob[0x0003] = 5; // number_of_cells
        pgc_blob[0x0004..0x0008].copy_from_slice(&[0x00, 0x15, 0x00, 0xE0]);
        let off_pmap = header_size as u16;
        let off_cpbi = (header_size + prog_map_size) as u16;
        let off_cpos = (header_size + prog_map_size + cpbi_size) as u16;
        pgc_blob[0x00E6..0x00E8].copy_from_slice(&off_pmap.to_be_bytes());
        pgc_blob[0x00E8..0x00EA].copy_from_slice(&off_cpbi.to_be_bytes());
        pgc_blob[0x00EA..0x00EC].copy_from_slice(&off_cpos.to_be_bytes());
        pgc_blob[header_size] = 1; // program 1 starts at cell 1
        pgc_blob[header_size + 1] = 3; // program 2 starts at cell 3
        pgc_blob[header_size + 2] = 5; // program 3 starts at cell 5
        for (i, c) in cells.iter().enumerate() {
            let base = header_size + prog_map_size + i * 24;
            pgc_blob[base + 4..base + 8].copy_from_slice(&[0, 1, 0, 0xE0]);
            pgc_blob[base + 8..base + 12].copy_from_slice(&c.first_vobu_start_sector.to_be_bytes());
            pgc_blob[base + 12..base + 16].copy_from_slice(&c.first_ilvu_end_sector.to_be_bytes());
            pgc_blob[base + 16..base + 20].copy_from_slice(&c.last_vobu_start_sector.to_be_bytes());
            pgc_blob[base + 20..base + 24].copy_from_slice(&c.last_vobu_end_sector.to_be_bytes());
        }
        for (i, p) in positions.iter().enumerate() {
            let base = header_size + prog_map_size + cpbi_size + i * 4;
            pgc_blob[base..base + 2].copy_from_slice(&p.vob_id.to_be_bytes());
            pgc_blob[base + 3] = p.cell_id;
        }
        // Wrap into PGCI
        let srp_size = 8usize;
        let body_off = 8 + srp_size;
        let pgci_total = body_off + pgc_blob.len();
        let mut pgci = vec![0u8; pgci_total];
        pgci[0..2].copy_from_slice(&1u16.to_be_bytes());
        pgci[4..8].copy_from_slice(&((pgci_total - 1) as u32).to_be_bytes());
        pgci[12..16].copy_from_slice(&(body_off as u32).to_be_bytes());
        pgci[body_off..body_off + pgc_blob.len()].copy_from_slice(&pgc_blob);
        img[2 * DVD_SECTOR..2 * DVD_SECTOR + pgci.len()].copy_from_slice(&pgci);

        // ---------- Sector 1: VTS_PTT_SRPT ----------
        // 1 title with 3 chapters at programs 1, 2, 3.
        let n_titles = 1usize;
        let n_chaps = 3usize;
        let header_sz = 8 + n_titles * 4;
        let title_body = n_chaps * 4;
        let total = header_sz + title_body;
        let mut ptt = vec![0u8; total];
        ptt[0..2].copy_from_slice(&(n_titles as u16).to_be_bytes());
        ptt[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());
        ptt[8..12].copy_from_slice(&(header_sz as u32).to_be_bytes());
        for ci in 0..n_chaps {
            let base = header_sz + ci * 4;
            ptt[base..base + 2].copy_from_slice(&1u16.to_be_bytes()); // PGCN
            ptt[base + 2..base + 4].copy_from_slice(&((ci + 1) as u16).to_be_bytes());
            // PGN
        }
        img[DVD_SECTOR..DVD_SECTOR + ptt.len()].copy_from_slice(&ptt);

        // ---------- Sector 3: VTS_C_ADT ----------
        let cadt_rows: Vec<(u16, u8, u32, u32)> = (0..5)
            .map(|i| {
                (
                    1u16,
                    (i + 1) as u8,
                    1000 + i as u32 * 1000,
                    1999 + i as u32 * 1000,
                )
            })
            .collect();
        let cadt = build_c_adt(&cadt_rows);
        img[3 * DVD_SECTOR..3 * DVD_SECTOR + cadt.len()].copy_from_slice(&cadt);

        img
    }

    #[test]
    fn composite_vts_roundtrip() {
        let img = make_composite_vts();
        let vts = VtsIfo::parse(&img, 1).unwrap();
        assert_eq!(vts.vts_number, 1);
        assert_eq!(vts.title_count, 1);
        assert_eq!(vts.pgcs.len(), 1);
        // The PGC has 5 cells and 3 programs.
        assert_eq!(vts.pgcs[0].number_of_cells, 5);
        assert_eq!(vts.pgcs[0].number_of_programs, 3);
        // Chapter materialisation:
        let t = &vts.titles[0];
        assert_eq!(t.chapter_count, 3);
        // program_map = [1, 3, 5]; PTT[1] = (PGCN=1, PGN=1) →
        // start_cell=1, end_cell=2 (next program's start_cell - 1 = 3-1).
        assert_eq!(t.chapters[0].start_cell, 1);
        assert_eq!(t.chapters[0].end_cell, 2);
        // PTT[2] = (PGCN=1, PGN=2) → start_cell=3, end_cell=4.
        assert_eq!(t.chapters[1].start_cell, 3);
        assert_eq!(t.chapters[1].end_cell, 4);
        // PTT[3] = (PGCN=1, PGN=3) → start_cell=5, end_cell=5 (last PGC cell).
        assert_eq!(t.chapters[2].start_cell, 5);
        assert_eq!(t.chapters[2].end_cell, 5);
        // C_ADT must give us first cell's sector range.
        assert_eq!(vts.cell_adt.lookup(1, 1), Some((1000, 1999)));
        assert_eq!(vts.cell_adt.lookup(1, 5), Some((5000, 5999)));
        // The composite IFO was built without VOBU_ADMAP / TMAPTI
        // sector pointers — both materialised tables must be `None`.
        assert!(vts.vobu_admap.is_none());
        assert!(vts.time_map.is_none());
    }

    // -------------------------------------------------------------
    // VOBU_ADMAP
    // -------------------------------------------------------------

    fn build_vobu_admap(entries: &[u32]) -> Vec<u8> {
        // 4-byte end_address + N × 4-byte sector words.
        let n = entries.len();
        let len = 4 + n * 4;
        let mut b = vec![0u8; len];
        let end_addr = (len - 1) as u32;
        b[0..4].copy_from_slice(&end_addr.to_be_bytes());
        for (i, s) in entries.iter().enumerate() {
            b[4 + i * 4..4 + (i + 1) * 4].copy_from_slice(&s.to_be_bytes());
        }
        b
    }

    #[test]
    fn vobu_admap_parses_three_vobus() {
        let entries = [0u32, 200u32, 450u32];
        let buf = build_vobu_admap(&entries);
        let map = VobuAdmap::parse(&buf).unwrap();
        assert_eq!(map.vobu_count(), 3);
        assert_eq!(map.entries, entries);
        assert_eq!(map.end_address, (buf.len() - 1) as u32);
        // 1-based VOBU lookup.
        assert_eq!(map.vobu_start_sector(1), Some(0));
        assert_eq!(map.vobu_start_sector(2), Some(200));
        assert_eq!(map.vobu_start_sector(3), Some(450));
        assert_eq!(map.vobu_start_sector(4), None);
        assert_eq!(map.vobu_start_sector(0), None);
    }

    #[test]
    fn vobu_admap_partition_locates_containing_vobu() {
        // VOBUs start at sectors 0, 100, 300, 600.
        let buf = build_vobu_admap(&[0, 100, 300, 600]);
        let map = VobuAdmap::parse(&buf).unwrap();
        // Boundary-inclusive: a sector that matches an entry exactly
        // belongs to that VOBU.
        assert_eq!(map.vobu_containing(0), Some(1));
        assert_eq!(map.vobu_containing(99), Some(1));
        assert_eq!(map.vobu_containing(100), Some(2));
        assert_eq!(map.vobu_containing(299), Some(2));
        assert_eq!(map.vobu_containing(300), Some(3));
        assert_eq!(map.vobu_containing(599), Some(3));
        assert_eq!(map.vobu_containing(600), Some(4));
        // Far past — still maps to the last VOBU (its end is unknown
        // until the next entry, so the partition returns the last one).
        assert_eq!(map.vobu_containing(1_000_000), Some(4));
    }

    #[test]
    fn vobu_admap_first_entry_above_zero_returns_none_for_pre_sector() {
        // Map's first VOBU starts at sector 100; sector 50 falls
        // before it, so the lookup must return `None`.
        let buf = build_vobu_admap(&[100, 200, 300]);
        let map = VobuAdmap::parse(&buf).unwrap();
        assert_eq!(map.vobu_containing(0), None);
        assert_eq!(map.vobu_containing(99), None);
        assert_eq!(map.vobu_containing(100), Some(1));
    }

    #[test]
    fn vobu_admap_empty_map_lookups_return_none() {
        // end_address = 3 → body span = 0 bytes → zero entries.
        let mut b = vec![0u8; 4];
        b[0..4].copy_from_slice(&3u32.to_be_bytes());
        let map = VobuAdmap::parse(&b).unwrap();
        assert_eq!(map.vobu_count(), 0);
        assert_eq!(map.vobu_start_sector(1), None);
        assert_eq!(map.vobu_containing(0), None);
    }

    #[test]
    fn vobu_admap_rejects_non_multiple_end_address() {
        // end_address = 5 implies a 2-byte body span — not a
        // multiple of the 4-byte entry size.
        let mut b = vec![0u8; 8];
        b[0..4].copy_from_slice(&5u32.to_be_bytes());
        assert!(VobuAdmap::parse(&b).is_err());
    }

    #[test]
    fn vobu_admap_rejects_truncated_buffer() {
        // end_address = 11 implies 2 entries (8 body bytes), but
        // the buffer is only 4 + 4 = 8 bytes long, missing the
        // second entry.
        let mut b = vec![0u8; 4 + 4];
        b[0..4].copy_from_slice(&11u32.to_be_bytes());
        assert!(VobuAdmap::parse(&b).is_err());
    }

    // -------------------------------------------------------------
    // VTS_TMAP / VTS_TMAPTI
    // -------------------------------------------------------------

    fn build_tmap(time_unit: u8, entries: &[(u32, bool)]) -> Vec<u8> {
        let n = entries.len();
        let len = 4 + n * 4;
        let mut b = vec![0u8; len];
        b[0] = time_unit;
        // byte 1 reserved
        b[2..4].copy_from_slice(&(n as u16).to_be_bytes());
        for (i, (sector, disc)) in entries.iter().enumerate() {
            let mut raw = *sector & TmapEntry::SECTOR_MASK;
            if *disc {
                raw |= TmapEntry::DISCONTINUITY_BIT;
            }
            b[4 + i * 4..4 + (i + 1) * 4].copy_from_slice(&raw.to_be_bytes());
        }
        b
    }

    #[test]
    fn tmap_decodes_entries_and_discontinuity() {
        // Three 4-second steps, second entry flagged discontinuous.
        let buf = build_tmap(4, &[(100, false), (250, true), (400, false)]);
        let map = VtsTmap::parse(&buf).unwrap();
        assert_eq!(map.time_unit, 4);
        assert_eq!(map.entries.len(), 3);
        assert_eq!(
            map.entries[0],
            TmapEntry {
                sector: 100,
                discontinuous: false
            }
        );
        assert_eq!(
            map.entries[1],
            TmapEntry {
                sector: 250,
                discontinuous: true
            }
        );
        assert_eq!(map.total_seconds(), 12);
    }

    #[test]
    fn tmap_sector_at_brackets_seconds_per_time_unit() {
        // 5-second steps; first entry covers [0,5), second [5,10),
        // third [10,15).
        let buf = build_tmap(5, &[(10, false), (20, false), (30, false)]);
        let map = VtsTmap::parse(&buf).unwrap();
        assert_eq!(map.sector_at(0), Some(10));
        assert_eq!(map.sector_at(4), Some(10));
        assert_eq!(map.sector_at(5), Some(20));
        assert_eq!(map.sector_at(9), Some(20));
        assert_eq!(map.sector_at(10), Some(30));
        assert_eq!(map.sector_at(14), Some(30));
        // Past the last bracket: clamp to the last entry rather than
        // return `None` so playback engines that pass an inaccurate
        // wall-clock get a reasonable "seek to end" answer.
        assert_eq!(map.sector_at(15), Some(30));
        assert_eq!(map.sector_at(1_000_000), Some(30));
    }

    #[test]
    fn tmap_empty_map_yields_no_sector() {
        // number_of_entries = 0 → empty entry table → all lookups
        // return `None`.
        let buf = build_tmap(2, &[]);
        let map = VtsTmap::parse(&buf).unwrap();
        assert_eq!(map.time_unit, 2);
        assert!(map.entries.is_empty());
        assert_eq!(map.sector_at(0), None);
        assert_eq!(map.sector_at(60), None);
        assert_eq!(map.total_seconds(), 0);
    }

    #[test]
    fn tmap_zero_time_unit_yields_no_sector() {
        // time_unit = 0 with a populated entry table is a malformed
        // map — sector_at would divide by zero, so we explicitly
        // surface `None` instead.
        let buf = build_tmap(0, &[(1, false), (2, false)]);
        let map = VtsTmap::parse(&buf).unwrap();
        assert_eq!(map.sector_at(0), None);
    }

    #[test]
    fn tmap_rejects_truncated_buffer() {
        // number_of_entries = 2 (8 body bytes needed) but buffer
        // only carries 4 + 4 = 8 bytes — one entry missing.
        let mut b = vec![0u8; 4 + 4];
        b[0] = 1;
        b[2..4].copy_from_slice(&2u16.to_be_bytes());
        assert!(VtsTmap::parse(&b).is_err());
    }

    fn build_tmapti(maps: &[Vec<u8>]) -> Vec<u8> {
        // 8-byte header + N × 4-byte offsets + concatenated map bodies.
        let n = maps.len();
        let offsets_size = n * 4;
        let header_size = 8 + offsets_size;
        let body_size: usize = maps.iter().map(|m| m.len()).sum();
        let total = header_size + body_size;
        let mut b = vec![0u8; total];
        b[0..2].copy_from_slice(&(n as u16).to_be_bytes());
        // reserved at 2..4 = 0
        b[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());
        let mut cursor = header_size;
        for (i, m) in maps.iter().enumerate() {
            let off = cursor as u32;
            b[8 + i * 4..8 + (i + 1) * 4].copy_from_slice(&off.to_be_bytes());
            b[cursor..cursor + m.len()].copy_from_slice(m);
            cursor += m.len();
        }
        b
    }

    #[test]
    fn tmapti_walks_two_pgc_maps() {
        let map_a = build_tmap(2, &[(0, false), (50, false), (100, false)]);
        let map_b = build_tmap(3, &[(200, false), (400, true)]);
        let buf = build_tmapti(&[map_a, map_b]);
        let table = VtsTmapti::parse(&buf).unwrap();
        assert_eq!(table.number_of_pgcs, 2);
        assert_eq!(table.maps.len(), 2);
        // PGCN lookups are 1-based.
        let m1 = table.get(1).unwrap();
        assert_eq!(m1.time_unit, 2);
        assert_eq!(m1.entries.len(), 3);
        let m2 = table.get(2).unwrap();
        assert_eq!(m2.time_unit, 3);
        assert!(m2.entries[1].discontinuous);
        assert_eq!(table.get(0), None);
        assert_eq!(table.get(3), None);
    }

    #[test]
    fn tmapti_carries_empty_map_per_spec_invariant() {
        // The spec mandates "each PGC MUST have a time map, even if
        // it is empty" — make sure an empty map decodes cleanly when
        // the offset list points at it.
        let empty = build_tmap(0, &[]);
        let buf = build_tmapti(&[empty]);
        let table = VtsTmapti::parse(&buf).unwrap();
        assert_eq!(table.number_of_pgcs, 1);
        let m = table.get(1).unwrap();
        assert!(m.entries.is_empty());
        assert_eq!(m.sector_at(0), None);
    }

    #[test]
    fn tmapti_rejects_short_offset_list() {
        // number_of_pgcs = 3 but only 8 bytes available — the offset
        // list runs past the buffer end.
        let mut b = vec![0u8; 8];
        b[0..2].copy_from_slice(&3u16.to_be_bytes());
        assert!(VtsTmapti::parse(&b).is_err());
    }

    // -------------------------------------------------------------
    // Composite VTS round-trip with VOBU_ADMAP + TMAPTI populated
    // -------------------------------------------------------------

    fn make_composite_vts_with_admap_and_tmap() -> Vec<u8> {
        // Sector layout:
        //   sector 0: VTSI_MAT
        //   sector 1: VTS_PTT_SRPT (1 title × 3 chapters)
        //   sector 2: VTS_PGCI (1 PGC, 5 cells, 3 programs)
        //   sector 3: VTS_C_ADT (5 cell entries)
        //   sector 4: VTS_VOBU_ADMAP (4 VOBUs)
        //   sector 5: VTS_TMAPTI (1 PGC × 3 steps)
        let mut img = vec![0u8; DVD_SECTOR * 6];

        // VTSI_MAT — populate the four sector pointers we exercise.
        // build_vtsi_mat zeroes the TMAPTI + VOBU_ADMAP pointers,
        // so patch them in manually after the base copy.
        let mat = build_vtsi_mat(1, 2, 3, 100);
        img[0..mat.len()].copy_from_slice(&mat);
        img[0x00D4..0x00D8].copy_from_slice(&5u32.to_be_bytes()); // TMAPTI sector
        img[0x00E4..0x00E8].copy_from_slice(&4u32.to_be_bytes()); // VOBU_ADMAP sector

        // PGCI — re-use the helper that already builds 1 PGC with 5
        // cells + 3 programs.
        let cells: Vec<CellPlaybackInfo> = (0..5)
            .map(|i| make_cell(1000 + i * 1000, 1999 + i * 1000))
            .collect();
        let positions: Vec<CellPositionInfo> = (0..5)
            .map(|i| CellPositionInfo {
                vob_id: 1,
                cell_id: (i + 1) as u8,
            })
            .collect();
        let header_size = 0xEC;
        let prog_count = 3u8;
        let prog_map_size = (usize::from(prog_count) + 1) & !1;
        let cpbi_size = 5 * 24;
        let cpos_size = 5 * 4;
        let pgc_blob_len = header_size + prog_map_size + cpbi_size + cpos_size;
        let mut pgc_blob = vec![0u8; pgc_blob_len];
        pgc_blob[0x0002] = prog_count;
        pgc_blob[0x0003] = 5;
        pgc_blob[0x0004..0x0008].copy_from_slice(&[0x00, 0x15, 0x00, 0xE0]);
        let off_pmap = header_size as u16;
        let off_cpbi = (header_size + prog_map_size) as u16;
        let off_cpos = (header_size + prog_map_size + cpbi_size) as u16;
        pgc_blob[0x00E6..0x00E8].copy_from_slice(&off_pmap.to_be_bytes());
        pgc_blob[0x00E8..0x00EA].copy_from_slice(&off_cpbi.to_be_bytes());
        pgc_blob[0x00EA..0x00EC].copy_from_slice(&off_cpos.to_be_bytes());
        pgc_blob[header_size] = 1;
        pgc_blob[header_size + 1] = 3;
        pgc_blob[header_size + 2] = 5;
        for (i, c) in cells.iter().enumerate() {
            let base = header_size + prog_map_size + i * 24;
            pgc_blob[base + 4..base + 8].copy_from_slice(&[0, 1, 0, 0xE0]);
            pgc_blob[base + 8..base + 12].copy_from_slice(&c.first_vobu_start_sector.to_be_bytes());
            pgc_blob[base + 12..base + 16].copy_from_slice(&c.first_ilvu_end_sector.to_be_bytes());
            pgc_blob[base + 16..base + 20].copy_from_slice(&c.last_vobu_start_sector.to_be_bytes());
            pgc_blob[base + 20..base + 24].copy_from_slice(&c.last_vobu_end_sector.to_be_bytes());
        }
        for (i, p) in positions.iter().enumerate() {
            let base = header_size + prog_map_size + cpbi_size + i * 4;
            pgc_blob[base..base + 2].copy_from_slice(&p.vob_id.to_be_bytes());
            pgc_blob[base + 3] = p.cell_id;
        }
        let srp_size = 8usize;
        let body_off = 8 + srp_size;
        let pgci_total = body_off + pgc_blob.len();
        let mut pgci = vec![0u8; pgci_total];
        pgci[0..2].copy_from_slice(&1u16.to_be_bytes());
        pgci[4..8].copy_from_slice(&((pgci_total - 1) as u32).to_be_bytes());
        pgci[12..16].copy_from_slice(&(body_off as u32).to_be_bytes());
        pgci[body_off..body_off + pgc_blob.len()].copy_from_slice(&pgc_blob);
        img[2 * DVD_SECTOR..2 * DVD_SECTOR + pgci.len()].copy_from_slice(&pgci);

        // PTT_SRPT
        let n_titles = 1usize;
        let n_chaps = 3usize;
        let header_sz = 8 + n_titles * 4;
        let title_body = n_chaps * 4;
        let total = header_sz + title_body;
        let mut ptt = vec![0u8; total];
        ptt[0..2].copy_from_slice(&(n_titles as u16).to_be_bytes());
        ptt[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());
        ptt[8..12].copy_from_slice(&(header_sz as u32).to_be_bytes());
        for ci in 0..n_chaps {
            let base = header_sz + ci * 4;
            ptt[base..base + 2].copy_from_slice(&1u16.to_be_bytes());
            ptt[base + 2..base + 4].copy_from_slice(&((ci + 1) as u16).to_be_bytes());
        }
        img[DVD_SECTOR..DVD_SECTOR + ptt.len()].copy_from_slice(&ptt);

        // C_ADT
        let cadt_rows: Vec<(u16, u8, u32, u32)> = (0..5)
            .map(|i| {
                (
                    1u16,
                    (i + 1) as u8,
                    1000 + i as u32 * 1000,
                    1999 + i as u32 * 1000,
                )
            })
            .collect();
        let cadt = build_c_adt(&cadt_rows);
        img[3 * DVD_SECTOR..3 * DVD_SECTOR + cadt.len()].copy_from_slice(&cadt);

        // VTS_VOBU_ADMAP at sector 4 — 4 VOBUs at VOB-relative
        // sectors 0, 250, 600, 1100.
        let admap = build_vobu_admap(&[0, 250, 600, 1100]);
        img[4 * DVD_SECTOR..4 * DVD_SECTOR + admap.len()].copy_from_slice(&admap);

        // VTS_TMAPTI at sector 5 — one PGC, 4-second steps, three
        // entries pointing into the VOBU sector list.
        let tmap = build_tmap(4, &[(0, false), (250, false), (600, false)]);
        let tmapti = build_tmapti(&[tmap]);
        img[5 * DVD_SECTOR..5 * DVD_SECTOR + tmapti.len()].copy_from_slice(&tmapti);

        img
    }

    #[test]
    fn composite_vts_materialises_admap_and_tmap() {
        let img = make_composite_vts_with_admap_and_tmap();
        let vts = VtsIfo::parse(&img, 1).unwrap();
        let admap = vts.vobu_admap.as_ref().expect("VOBU_ADMAP materialised");
        assert_eq!(admap.vobu_count(), 4);
        assert_eq!(admap.vobu_start_sector(1), Some(0));
        assert_eq!(admap.vobu_start_sector(4), Some(1100));
        // Sector 700 falls inside VOBU 3's range [600, 1100).
        assert_eq!(admap.vobu_containing(700), Some(3));

        let tmapti = vts.time_map.as_ref().expect("VTS_TMAPTI materialised");
        assert_eq!(tmapti.number_of_pgcs, 1);
        let pgc_map = tmapti.get(1).unwrap();
        assert_eq!(pgc_map.time_unit, 4);
        assert_eq!(pgc_map.entries.len(), 3);

        // Time-based seek: 5 seconds in → step 2 (covers [4, 8)) →
        // VOBU at VOB-relative sector 250.
        assert_eq!(vts.vobu_sector_at_pgc_time(1, 5), Some(250));
        // 0 seconds → step 1 → sector 0.
        assert_eq!(vts.vobu_sector_at_pgc_time(1, 0), Some(0));
        // 9 seconds → step 3 → sector 600.
        assert_eq!(vts.vobu_sector_at_pgc_time(1, 9), Some(600));
        // Out-of-range PGCN → `None`.
        assert_eq!(vts.vobu_sector_at_pgc_time(2, 0), None);
    }

    // -------------------------------------------------------------
    // VTSI_MAT stream-attribute extension
    // -------------------------------------------------------------

    /// Build a single 8-byte audio-attribute slot covering the
    /// fields we exercise in the typed parse.
    #[allow(clippy::too_many_arguments)]
    fn pack_audio_attr(
        coding: u8,
        mc_ext: bool,
        lang_type: u8,
        app_mode: u8,
        quant: u8,
        sample_rate: u8,
        chans_minus_one: u8,
        lang: [u8; 2],
        code_ext: u8,
        app_info: u8,
    ) -> [u8; 8] {
        let mut b = [0u8; 8];
        b[0] = ((coding & 0b111) << 5)
            | (if mc_ext { 0b1_0000 } else { 0 })
            | ((lang_type & 0b11) << 2)
            | (app_mode & 0b11);
        b[1] = ((quant & 0b11) << 6) | ((sample_rate & 0b11) << 4) | (chans_minus_one & 0b111);
        b[2] = lang[0];
        b[3] = lang[1];
        b[5] = code_ext;
        b[7] = app_info;
        b
    }

    #[allow(clippy::too_many_arguments)]
    fn pack_video_attr(
        coding: u8,
        standard: u8,
        aspect: u8,
        pan_scan_disallowed: bool,
        letterbox_disallowed: bool,
        cc1: bool,
        cc2: bool,
        resolution: u8,
        letterbox_src: bool,
        film_pal: bool,
    ) -> [u8; 2] {
        let mut b = [0u8; 2];
        b[0] = ((coding & 0b11) << 6)
            | ((standard & 0b11) << 4)
            | ((aspect & 0b11) << 2)
            | (if pan_scan_disallowed { 0b10 } else { 0 })
            | (if letterbox_disallowed { 0b01 } else { 0 });
        b[1] = (if cc1 { 0b1000_0000 } else { 0 })
            | (if cc2 { 0b0100_0000 } else { 0 })
            | ((resolution & 0b111) << 3)
            | (if letterbox_src { 0b0000_0100 } else { 0 })
            | (if film_pal { 0b0000_0001 } else { 0 });
        b
    }

    fn pack_subp_attr(coding: u8, lang_type: u8, lang: [u8; 2], code_ext: u8) -> [u8; 6] {
        let mut b = [0u8; 6];
        b[0] = ((coding & 0b111) << 5) | (lang_type & 0b11);
        b[2] = lang[0];
        b[3] = lang[1];
        b[5] = code_ext;
        b
    }

    #[test]
    fn video_attributes_mpeg2_pal_16x9_full_d1() {
        let raw = pack_video_attr(1, 1, 3, false, false, false, false, 0, false, true);
        let v = VideoAttributes::parse(&raw);
        assert_eq!(v.coding_mode, VideoCodingMode::Mpeg2);
        assert_eq!(v.standard, VideoStandard::Pal);
        assert_eq!(v.aspect_ratio, VideoAspectRatio::Ratio16x9);
        assert_eq!(v.resolution, VideoResolution::FullD1);
        assert_eq!(
            v.resolution.dimensions(VideoStandard::Pal),
            Some((720, 576))
        );
        assert!(v.film_source_pal);
        assert!(!v.line21_field1_cc);
    }

    #[test]
    fn video_attributes_mpeg2_ntsc_4x3_sif_with_cc() {
        let raw = pack_video_attr(1, 0, 0, true, false, true, true, 3, true, false);
        let v = VideoAttributes::parse(&raw);
        assert_eq!(v.coding_mode, VideoCodingMode::Mpeg2);
        assert_eq!(v.standard, VideoStandard::Ntsc);
        assert_eq!(v.aspect_ratio, VideoAspectRatio::Ratio4x3);
        assert_eq!(v.resolution, VideoResolution::Sif);
        assert_eq!(
            v.resolution.dimensions(VideoStandard::Ntsc),
            Some((352, 240))
        );
        assert!(v.pan_scan_disallowed);
        assert!(v.line21_field1_cc);
        assert!(v.line21_field2_cc);
        assert!(v.letterboxed_source);
    }

    #[test]
    fn video_attributes_reserved_aspect_and_resolution() {
        let raw = pack_video_attr(1, 0, 1, false, false, false, false, 5, false, false);
        let v = VideoAttributes::parse(&raw);
        assert_eq!(v.aspect_ratio, VideoAspectRatio::Reserved(1));
        assert_eq!(v.resolution, VideoResolution::Reserved(5));
        assert_eq!(v.resolution.dimensions(VideoStandard::Ntsc), None);
    }

    #[test]
    fn audio_attributes_ac3_stereo_english() {
        // coding=0 (AC3), mc_ext=false, lang_type=1 (ISO), app=0 (unspec),
        // quant=0, sample=0 (48 kHz), chans-1=1 (stereo).
        let raw = pack_audio_attr(0, false, 1, 0, 0, 0, 1, *b"en", 0, 0);
        let a = AudioAttributes::parse(&raw);
        assert_eq!(a.coding_mode, AudioCodingMode::Ac3);
        assert!(!a.multichannel_extension_present);
        assert_eq!(a.language_type, AudioLanguageType::Iso639);
        assert_eq!(a.application_mode, AudioApplicationMode::Unspecified);
        assert_eq!(a.channel_count, 2);
        assert_eq!(a.sample_rate_hz(), Some(48_000));
        assert_eq!(&a.language_code, b"en");
        assert!(!a.dolby_surround_suitable());
    }

    #[test]
    fn audio_attributes_lpcm_24bit_six_channel() {
        // coding=4 (LPCM), quant=2 (24bps), chans-1=5 (6 channels).
        let raw = pack_audio_attr(4, false, 0, 0, 2, 0, 5, [0, 0], 0, 0);
        let a = AudioAttributes::parse(&raw);
        assert_eq!(a.coding_mode, AudioCodingMode::Lpcm);
        assert_eq!(a.quantization, AudioQuantizationDrc::Lpcm24);
        assert_eq!(a.channel_count, 6);
    }

    #[test]
    fn audio_attributes_mpeg2_drc_flag() {
        let raw = pack_audio_attr(3, false, 0, 0, 1, 0, 1, [0, 0], 0, 0);
        let a = AudioAttributes::parse(&raw);
        assert_eq!(a.coding_mode, AudioCodingMode::Mpeg2Ext);
        assert_eq!(a.quantization, AudioQuantizationDrc::Drc);
    }

    #[test]
    fn audio_attributes_surround_dolby_suitable_bit() {
        // surround app_mode + byte 7 bit 3 = Dolby-Surround-suitable.
        let raw = pack_audio_attr(0, false, 0, 2, 0, 0, 1, [0, 0], 0, 0b0000_1000);
        let a = AudioAttributes::parse(&raw);
        assert_eq!(a.application_mode, AudioApplicationMode::Surround);
        assert!(a.dolby_surround_suitable());
    }

    #[test]
    fn audio_attributes_karaoke_channel_assignment_3_0() {
        // karaoke app_mode + byte 7 bits 6..4 = 3 (= 3/0 L,M,R) + bit 1 set (MC intro).
        let raw = pack_audio_attr(0, true, 0, 1, 0, 0, 2, [0, 0], 0, 0b0011_0010);
        let a = AudioAttributes::parse(&raw);
        assert_eq!(a.application_mode, AudioApplicationMode::Karaoke);
        assert!(a.multichannel_extension_present);
        assert_eq!(a.karaoke_channel_assignment(), Some(3));
        assert_eq!(a.karaoke_mc_intro_present(), Some(true));
        assert_eq!(a.karaoke_duet(), Some(false));
    }

    #[test]
    fn subpicture_attributes_2bit_rle_japanese() {
        let raw = pack_subp_attr(0, 1, *b"ja", 0);
        let s = SubpictureAttributes::parse(&raw);
        assert_eq!(s.coding_mode, SubpictureCodingMode::Rle2Bit);
        assert_eq!(s.language_type, SubpictureLanguageType::Iso639);
        assert_eq!(&s.language_code, b"ja");
    }

    #[test]
    fn mc_extension_entry_decodes_per_channel_flags() {
        let raw = [
            0b0000_0001, // ACH0 guide melody
            0b0000_0000,
            0b0000_1010, // ACH2 GV1 + GM1
            0b0000_0101, // ACH3 GV2 + SE_A
            0b0000_1001, // ACH4 GV1 + SE_B
            0,
            0,
            0,
        ];
        let m = McExtensionEntry::parse(&raw);
        assert!(m.ach0_guide_melody);
        assert!(!m.ach1_guide_melody);
        assert!(m.ach2_guide_vocal_1);
        assert!(m.ach2_guide_melody_1);
        assert!(m.ach3_guide_vocal_2);
        assert!(m.ach3_sound_effect_a);
        assert!(m.ach4_guide_vocal_1);
        assert!(m.ach4_sound_effect_b);
        assert!(!m.ach4_guide_melody_b);
    }

    /// Build a full 0x03D8-byte VTSI_MAT carrying the menu + title
    /// attribute extension blocks. We populate enough fields to
    /// exercise the typed decoders end-to-end.
    fn build_vtsi_mat_with_attrs() -> Vec<u8> {
        let mut b = vec![0u8; 0x03D8];
        b[0..12].copy_from_slice(VTS_MAGIC);
        b[0x0080..0x0084].copy_from_slice(&(0x03D7u32).to_be_bytes());
        // Sector pointers we don't exercise stay zero.

        // Menu block at 0x0100..0x015C — MPEG-2 PAL 4:3 full-D1,
        // one MPEG-1 stereo audio stream, one Japanese sub-picture.
        let v_menu = pack_video_attr(1, 1, 0, false, false, false, false, 0, false, false);
        b[0x0100..0x0102].copy_from_slice(&v_menu);
        b[0x0102..0x0104].copy_from_slice(&1u16.to_be_bytes());
        let a_menu = pack_audio_attr(2, false, 1, 0, 0, 0, 1, *b"en", 1, 0);
        b[0x0104..0x010C].copy_from_slice(&a_menu);
        b[0x0154..0x0156].copy_from_slice(&1u16.to_be_bytes());
        let s_menu = pack_subp_attr(0, 1, *b"ja", 0);
        b[0x0156..0x015C].copy_from_slice(&s_menu);

        // Title block at 0x0200..0x03D8 — MPEG-2 NTSC 16:9 full-D1,
        // two AC-3 streams (en 5.1, fr stereo) + two sub-picture
        // streams (en + de).
        let v_title = pack_video_attr(1, 0, 3, false, false, false, false, 0, false, false);
        b[0x0200..0x0202].copy_from_slice(&v_title);
        b[0x0202..0x0204].copy_from_slice(&2u16.to_be_bytes());
        let a0 = pack_audio_attr(0, false, 1, 0, 0, 0, 5, *b"en", 1, 0);
        let a1 = pack_audio_attr(0, false, 1, 0, 0, 0, 1, *b"fr", 1, 0);
        b[0x0204..0x020C].copy_from_slice(&a0);
        b[0x020C..0x0214].copy_from_slice(&a1);
        b[0x0254..0x0256].copy_from_slice(&2u16.to_be_bytes());
        let s0 = pack_subp_attr(0, 1, *b"en", 0);
        let s1 = pack_subp_attr(0, 1, *b"de", 0);
        b[0x0256..0x025C].copy_from_slice(&s0);
        b[0x025C..0x0262].copy_from_slice(&s1);

        // MC extension slot at 0x0318 — leave 24 zeroed entries.
        b
    }

    #[test]
    fn vtsi_mat_decodes_menu_and_title_attribute_blocks() {
        let buf = build_vtsi_mat_with_attrs();
        let mat = VtsiMat::parse(&buf).unwrap();

        let menu_v = mat.menu_attributes.video.unwrap();
        assert_eq!(menu_v.standard, VideoStandard::Pal);
        assert_eq!(menu_v.aspect_ratio, VideoAspectRatio::Ratio4x3);
        assert_eq!(mat.menu_attributes.audio_streams.len(), 1);
        assert_eq!(
            mat.menu_attributes.audio_streams[0].coding_mode,
            AudioCodingMode::Mpeg1
        );
        assert_eq!(mat.menu_attributes.subpicture_streams.len(), 1);
        assert_eq!(
            &mat.menu_attributes.subpicture_streams[0].language_code,
            b"ja"
        );

        let title_v = mat.title_attributes.video.unwrap();
        assert_eq!(title_v.standard, VideoStandard::Ntsc);
        assert_eq!(title_v.aspect_ratio, VideoAspectRatio::Ratio16x9);
        assert_eq!(mat.title_attributes.audio_streams.len(), 2);
        assert_eq!(mat.title_attributes.audio_streams[0].channel_count, 6);
        assert_eq!(&mat.title_attributes.audio_streams[1].language_code, b"fr");
        assert_eq!(mat.title_attributes.subpicture_streams.len(), 2);
        assert_eq!(
            &mat.title_attributes.subpicture_streams[1].language_code,
            b"de"
        );
        assert_eq!(mat.title_attributes.multichannel_extension.len(), 24);
        assert!(!mat.title_attributes.multichannel_extension[0].ach0_guide_melody);
    }

    #[test]
    fn vtsi_mat_short_buffer_leaves_attributes_partial() {
        // The 0x200-byte buffer used by the legacy roundtrip test
        // covers the menu block but not the title block.
        let buf = build_vtsi_mat(1, 2, 3, 42);
        let mat = VtsiMat::parse(&buf).unwrap();
        // Menu block fits entirely within 0x200, so its video field
        // is parsed (all-zero → MPEG-1 NTSC 4:3).
        let menu_v = mat.menu_attributes.video.unwrap();
        assert_eq!(menu_v.coding_mode, VideoCodingMode::Mpeg1);
        // Title block starts at 0x0200 — buffer ends before that.
        assert!(mat.title_attributes.video.is_none());
        assert!(mat.title_attributes.audio_streams.is_empty());
        assert!(mat.title_attributes.multichannel_extension.is_empty());
    }

    // -------------------------------------------------------------
    // VMG_VTS_ATRT
    // -------------------------------------------------------------

    /// Build a synthetic `VMG_VTS_ATRT` with `entries.len()` entries,
    /// each carrying the supplied `(vts_category, blob)` pair.
    fn build_vts_atrt(entries: &[(u32, Vec<u8>)]) -> Vec<u8> {
        // Header is 8 bytes + 4 bytes per offset entry.
        let header = 8 + 4 * entries.len();
        // Each entry body = 8-byte header + blob.
        let mut offsets = Vec::with_capacity(entries.len());
        let mut bodies = Vec::with_capacity(entries.len());
        let mut cursor = header;
        for (cat, blob) in entries {
            offsets.push(cursor as u32);
            let entry_total = 8 + blob.len();
            let entry_ea = (entry_total - 1) as u32;
            let mut e = Vec::with_capacity(entry_total);
            e.extend_from_slice(&entry_ea.to_be_bytes());
            e.extend_from_slice(&cat.to_be_bytes());
            e.extend_from_slice(blob);
            bodies.push(e);
            cursor += entry_total;
        }
        let total = cursor;
        let mut out = vec![0u8; total];
        out[0..2].copy_from_slice(&(entries.len() as u16).to_be_bytes());
        // bytes 2..4 reserved
        out[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());
        for (i, off) in offsets.iter().enumerate() {
            out[8 + i * 4..8 + (i + 1) * 4].copy_from_slice(&off.to_be_bytes());
        }
        for (i, body) in bodies.iter().enumerate() {
            let start = offsets[i] as usize;
            out[start..start + body.len()].copy_from_slice(body);
        }
        out
    }

    #[test]
    fn vts_atrt_walks_two_entries() {
        let blob_a = (0..0x300u32).map(|i| (i & 0xFF) as u8).collect::<Vec<_>>();
        let blob_b = vec![0x55u8; 0x300];
        let buf = build_vts_atrt(&[(0, blob_a.clone()), (1, blob_b.clone())]);
        let atrt = VmgVtsAtrt::parse(&buf).unwrap();
        assert_eq!(atrt.number_of_title_sets, 2);
        assert_eq!(atrt.entries.len(), 2);

        let e1 = atrt.entry(1).unwrap();
        assert_eq!(e1.vts_number, 1);
        assert_eq!(e1.vts_category, 0);
        assert_eq!(e1.attributes_blob, blob_a);

        let e2 = atrt.entry(2).unwrap();
        assert_eq!(e2.vts_number, 2);
        assert_eq!(e2.vts_category, 1); // Karaoke flag
        assert_eq!(e2.attributes_blob, blob_b);

        assert!(atrt.entry(0).is_none());
        assert!(atrt.entry(3).is_none());
    }

    #[test]
    fn vts_atrt_rejects_short_header() {
        let buf = vec![0u8; 4];
        assert!(VmgVtsAtrt::parse(&buf).is_err());
    }

    #[test]
    fn vts_atrt_rejects_offset_list_past_end() {
        let mut buf = vec![0u8; 8];
        buf[0..2].copy_from_slice(&5u16.to_be_bytes()); // claims 5 entries
                                                        // but the offset list (20 bytes) doesn't fit in the 8-byte buffer
        assert!(VmgVtsAtrt::parse(&buf).is_err());
    }

    #[test]
    fn vts_atrt_rejects_entry_ea_overlapping_next_entry() {
        // Build a valid 2-entry table, then corrupt entry 1's EA so it
        // claims more bytes than entry 2's offset allows.
        let blob = vec![0xAAu8; 0x100];
        let mut buf = build_vts_atrt(&[(0, blob.clone()), (0, blob.clone())]);
        // Entry 1 is at offset = read_u32(buf, 8). Bloat its EA field
        // (entry-local offset 0..4) so the entry would extend past
        // entry 2's start.
        let e1_off = u32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]) as usize;
        buf[e1_off..e1_off + 4].copy_from_slice(&0xFFFFu32.to_be_bytes());
        assert!(VmgVtsAtrt::parse(&buf).is_err());
    }

    // -------------------------------------------------------------
    // VMG_PTL_MAIT
    // -------------------------------------------------------------

    /// Build a synthetic `VMG_PTL_MAIT` with `entries.len()` countries
    /// and `nts` title sets. Each entry's `masks` are passed as
    /// `[level1..level8]` arrays of `nts + 1` u16s — they're stored on
    /// disc in descending level order (level 8 first).
    fn build_ptl_mait(
        country_codes: &[u16],
        nts: u16,
        masks_per_country: &[[Vec<u16>; 8]],
    ) -> Vec<u8> {
        assert_eq!(country_codes.len(), masks_per_country.len());
        let header_len = 8 + 8 * country_codes.len();
        let level_block_bytes = (usize::from(nts) + 1) * 2;
        let body_bytes = level_block_bytes * 8;
        let total = header_len + body_bytes * country_codes.len();

        let mut buf = vec![0u8; total];
        buf[0..2].copy_from_slice(&(country_codes.len() as u16).to_be_bytes());
        buf[2..4].copy_from_slice(&nts.to_be_bytes());
        buf[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());

        for (i, (&cc, masks)) in country_codes
            .iter()
            .zip(masks_per_country.iter())
            .enumerate()
        {
            let body_offset = header_len + i * body_bytes;
            // Entry: cc(u16) | reserved(u16) | offset(u16) | reserved(u16)
            let entry_base = 8 + i * 8;
            buf[entry_base..entry_base + 2].copy_from_slice(&cc.to_be_bytes());
            // bytes 2..4 reserved
            buf[entry_base + 4..entry_base + 6]
                .copy_from_slice(&(body_offset as u16).to_be_bytes());
            // bytes 6..8 reserved
            // Body: 8 stacked blocks, level 8 first.
            for storage_idx in 0..8usize {
                let level_value = 8 - storage_idx; // 8..=1
                let row = &masks[level_value - 1]; // user passed ascending
                assert_eq!(row.len(), usize::from(nts) + 1);
                let block_start = body_offset + storage_idx * level_block_bytes;
                for (slot, &m) in row.iter().enumerate() {
                    buf[block_start + slot * 2..block_start + slot * 2 + 2]
                        .copy_from_slice(&m.to_be_bytes());
                }
            }
        }
        buf
    }

    #[test]
    fn ptl_mait_walks_two_countries() {
        // 2 countries × nts=2 (so masks_per_level = 3: VMG + 2 VTSs).
        let mut country_a_masks: [Vec<u16>; 8] = Default::default();
        let mut country_b_masks: [Vec<u16>; 8] = Default::default();
        for lvl_idx in 0..8 {
            // level 1..=8 stored ascending in the user-facing layout.
            let lvl = (lvl_idx + 1) as u16;
            country_a_masks[lvl_idx] = vec![lvl, lvl + 0x10, lvl + 0x20];
            country_b_masks[lvl_idx] =
                vec![0xF000 | lvl, 0xF000 | (lvl + 0x10), 0xF000 | (lvl + 0x20)];
        }
        // Country code 'us' = 0x7553; 'jp' = 0x6A70.
        let buf = build_ptl_mait(
            &[0x7553, 0x6A70],
            2,
            &[country_a_masks.clone(), country_b_masks.clone()],
        );

        let pm = VmgPtlMait::parse(&buf).unwrap();
        assert_eq!(pm.number_of_countries, 2);
        assert_eq!(pm.number_of_title_sets, 2);
        assert_eq!(pm.entries.len(), 2);

        let us = pm.country(0x7553).expect("US country present");
        // Level 1 mask for VMG (title_set=0) was 1.
        assert_eq!(us.mask(1, 0), Some(1));
        // Level 1 mask for VTS 1 was 0x11.
        assert_eq!(us.mask(1, 1), Some(0x11));
        // Level 1 mask for VTS 2 was 0x21.
        assert_eq!(us.mask(1, 2), Some(0x21));
        // Level 8 mask for VTS 2 was 8 + 0x20 = 0x28.
        assert_eq!(us.mask(8, 2), Some(0x28));

        let jp = pm.country(0x6A70).unwrap();
        assert_eq!(jp.mask(1, 0), Some(0xF001));
        assert_eq!(jp.mask(8, 2), Some(0xF028));

        assert!(pm.country(0x4242).is_none());
        // Out-of-range parental level.
        assert_eq!(us.mask(0, 0), None);
        assert_eq!(us.mask(9, 0), None);
        // Out-of-range title-set index.
        assert_eq!(us.mask(1, 3), None);
    }

    #[test]
    fn ptl_mait_zero_countries_decodes_empty() {
        let buf = build_ptl_mait(&[], 2, &[]);
        let pm = VmgPtlMait::parse(&buf).unwrap();
        assert_eq!(pm.number_of_countries, 0);
        assert!(pm.entries.is_empty());
    }

    #[test]
    fn ptl_mait_rejects_short_header() {
        let buf = vec![0u8; 4];
        assert!(VmgPtlMait::parse(&buf).is_err());
    }

    #[test]
    fn ptl_mait_rejects_country_list_past_end() {
        let mut buf = vec![0u8; 8];
        buf[0..2].copy_from_slice(&5u16.to_be_bytes()); // 5 countries
        buf[2..4].copy_from_slice(&2u16.to_be_bytes());
        // Truncated — no room for 5 × 8-byte entries after the header.
        assert!(VmgPtlMait::parse(&buf).is_err());
    }

    #[test]
    fn ptl_mait_rejects_body_offset_past_buffer() {
        // 1 country, nts=2 → body needs 8 × 6 = 48 bytes. Header
        // (8) + entry (8) = 16. Total valid buffer would be 16 + 48 = 64
        // bytes; truncate to 16 to trip the bound check.
        let mut buf = vec![0u8; 16];
        buf[0..2].copy_from_slice(&1u16.to_be_bytes());
        buf[2..4].copy_from_slice(&2u16.to_be_bytes());
        buf[4..8].copy_from_slice(&63u32.to_be_bytes());
        buf[8..10].copy_from_slice(&0x7553u16.to_be_bytes());
        buf[12..14].copy_from_slice(&16u16.to_be_bytes()); // body starts past buf end
        assert!(VmgPtlMait::parse(&buf).is_err());
    }

    // ----------------------------------------------------------------
    // VMGM_PGCI_UT / VTSM_PGCI_UT — Menu PGCI Unit Table
    // ----------------------------------------------------------------

    /// Minimal PGC body (236 bytes) — all sub-table offsets zero so
    /// `Pgc::parse` walks the header alone.
    fn empty_pgc_body() -> Vec<u8> {
        vec![0u8; 0xEC]
    }

    /// Build a synthetic PGCI_UT buffer from `(language_code,
    /// language_code_ext, menu_existence, pgc_categories)` tuples.
    /// Each language unit gets one PGC per `pgc_categories` entry,
    /// each PGC carries an empty 236-byte body.
    fn build_pgci_ut(units: &[(u16, u8, u8, Vec<u32>)]) -> Vec<u8> {
        let header_len = 8 + 8 * units.len();
        // Layout: outer header, outer SRP list, then back-to-back LUs.
        // Each LU has its own (8 + n_pgcs × 8) header + (n_pgcs × 236)
        // PGC bodies.
        let lu_lens: Vec<usize> = units
            .iter()
            .map(|(_, _, _, pgcs)| 8 + pgcs.len() * 8 + pgcs.len() * 0xEC)
            .collect();
        let total: usize = header_len + lu_lens.iter().sum::<usize>();
        let mut buf = vec![0u8; total];
        // Outer header: num LUs + end_address.
        buf[0..2].copy_from_slice(&(units.len() as u16).to_be_bytes());
        buf[4..8].copy_from_slice(&((total - 1) as u32).to_be_bytes());

        let mut lu_offset = header_len;
        for (i, ((lang, ext, exist, pgcs), &lu_len)) in units.iter().zip(lu_lens.iter()).enumerate()
        {
            // Outer SRP entry: lang(u16) | ext(u8) | exist(u8) | offset(u32)
            let srp_base = 8 + i * 8;
            buf[srp_base..srp_base + 2].copy_from_slice(&lang.to_be_bytes());
            buf[srp_base + 2] = *ext;
            buf[srp_base + 3] = *exist;
            buf[srp_base + 4..srp_base + 8].copy_from_slice(&(lu_offset as u32).to_be_bytes());

            // LU header at lu_offset: n_pgcs + end_address relative to LU.
            buf[lu_offset..lu_offset + 2].copy_from_slice(&(pgcs.len() as u16).to_be_bytes());
            buf[lu_offset + 4..lu_offset + 8].copy_from_slice(&((lu_len - 1) as u32).to_be_bytes());

            // Inner SRP entries + back-to-back PGC bodies.
            let inner_srp_end = 8 + pgcs.len() * 8;
            for (j, &cat) in pgcs.iter().enumerate() {
                let inner_base = lu_offset + 8 + j * 8;
                buf[inner_base..inner_base + 4].copy_from_slice(&cat.to_be_bytes());
                let pgc_offset_in_lu = (inner_srp_end + j * 0xEC) as u32;
                buf[inner_base + 4..inner_base + 8]
                    .copy_from_slice(&pgc_offset_in_lu.to_be_bytes());

                // Body is all zero from the vec init — that matches
                // empty_pgc_body() and parses fine.
                let pgc_global = lu_offset + pgc_offset_in_lu as usize;
                let empty = empty_pgc_body();
                buf[pgc_global..pgc_global + 0xEC].copy_from_slice(&empty);
            }

            lu_offset += lu_len;
        }
        buf
    }

    #[test]
    fn pgci_ut_walks_two_language_units() {
        // EN + JP, each with 2 PGCs. Categories encode entry-PGC flag
        // (bit 31) + menu-type nibble (low 4 bits of byte 0).
        // EN: PGC1 = entry-Root (0x83_00_00_00), PGC2 = non-entry (0x00_…).
        // JP: PGC1 = entry-Title (0x82_00_00_00), PGC2 = non-entry.
        let units = vec![
            (
                0x656E, // "en"
                0,
                menu_existence::ROOT | menu_existence::AUDIO,
                vec![0x83_00_00_00, 0x00_00_00_00],
            ),
            (
                0x6A70, // "jp"
                0,
                menu_existence::ROOT,
                vec![0x82_00_00_00, 0x00_00_00_00],
            ),
        ];
        let buf = build_pgci_ut(&units);
        let table = PgciUt::parse(&buf).unwrap();

        assert_eq!(table.number_of_language_units, 2);
        assert_eq!(table.srp.len(), 2);
        assert_eq!(table.language_units.len(), 2);

        // First LU: English, root + audio menus.
        let en_srp = &table.srp[0];
        assert_eq!(en_srp.language_code, 0x656E);
        assert!(en_srp.has_root_menu());
        assert!(en_srp.has_audio_menu());
        assert!(!en_srp.has_subpicture_menu());
        assert!(!en_srp.has_angle_menu());
        assert!(!en_srp.has_ptt_menu());

        let en_lu = &table.language_units[0];
        assert_eq!(en_lu.number_of_pgcs, 2);
        assert_eq!(en_lu.srp.len(), 2);
        assert_eq!(en_lu.pgcs.len(), 2);
        assert!(en_lu.srp[0].is_entry_pgc());
        assert_eq!(en_lu.srp[0].menu_type(), MenuType::Root);
        assert!(!en_lu.srp[1].is_entry_pgc());

        // Second LU: Japanese, title-menu entry.
        let jp_srp = &table.srp[1];
        assert_eq!(jp_srp.language_code, 0x6A70);
        let jp_lu = &table.language_units[1];
        assert_eq!(jp_lu.srp[0].menu_type(), MenuType::Title);

        // language_unit() lookup round-trips.
        assert_eq!(
            table.language_unit(0x656E).map(|lu| lu.number_of_pgcs),
            Some(2)
        );
        assert!(table.language_unit(0x4242).is_none());
    }

    #[test]
    fn pgci_ut_zero_language_units_decodes_empty() {
        let buf = build_pgci_ut(&[]);
        let table = PgciUt::parse(&buf).unwrap();
        assert_eq!(table.number_of_language_units, 0);
        assert!(table.srp.is_empty());
        assert!(table.language_units.is_empty());
    }

    #[test]
    fn pgci_ut_rejects_short_header() {
        let buf = vec![0u8; 4];
        assert!(PgciUt::parse(&buf).is_err());
    }

    #[test]
    fn pgci_ut_rejects_srp_list_past_buffer() {
        // Claim 5 LUs but truncate after the header.
        let mut buf = vec![0u8; 8];
        buf[0..2].copy_from_slice(&5u16.to_be_bytes());
        assert!(PgciUt::parse(&buf).is_err());
    }

    #[test]
    fn pgci_ut_rejects_lu_offset_zero() {
        // One LU with offset=0 — should be rejected per the in-range
        // check in `PgciUt::parse`.
        let mut buf = vec![0u8; 16];
        buf[0..2].copy_from_slice(&1u16.to_be_bytes());
        // outer SRP entry at offset 8: lang=0x656E, exist=0x80, off=0.
        buf[8..10].copy_from_slice(&0x656Eu16.to_be_bytes());
        buf[11] = menu_existence::ROOT;
        // offset bytes already zero.
        assert!(PgciUt::parse(&buf).is_err());
    }

    #[test]
    fn pgci_ut_rejects_lu_offset_past_buffer() {
        // One LU whose offset points beyond the buffer end.
        let mut buf = vec![0u8; 16];
        buf[0..2].copy_from_slice(&1u16.to_be_bytes());
        buf[8..10].copy_from_slice(&0x656Eu16.to_be_bytes());
        buf[11] = menu_existence::ROOT;
        buf[12..16].copy_from_slice(&64u32.to_be_bytes()); // beyond 16-byte buf
        assert!(PgciUt::parse(&buf).is_err());
    }

    #[test]
    fn pgci_lu_rejects_pgc_offset_past_buffer() {
        // A 16-byte LU body claiming 1 PGC whose offset points outside
        // the LU buffer.
        let mut buf = vec![0u8; 16];
        buf[0..2].copy_from_slice(&1u16.to_be_bytes());
        // Inner SRP at offset 8: category=0, offset=512 (way past 16).
        buf[12..16].copy_from_slice(&512u32.to_be_bytes());
        assert!(PgciLu::parse(&buf).is_err());
    }

    #[test]
    fn pgci_lu_srp_decodes_parental_mask() {
        // Build a single-LU table with one PGC whose category dword
        // is 0x83_00_00_FF — entry-Root menu, parental mask 0x00FF.
        let units = vec![(0x656E, 0, menu_existence::ROOT, vec![0x83_00_00_FF_u32])];
        let buf = build_pgci_ut(&units);
        let table = PgciUt::parse(&buf).unwrap();
        let lu = &table.language_units[0];
        assert!(lu.srp[0].is_entry_pgc());
        assert_eq!(lu.srp[0].menu_type(), MenuType::Root);
        assert_eq!(lu.srp[0].parental_mask(), 0x00FF);
    }

    #[test]
    fn menu_type_unknown_for_undefined_nibble() {
        // The spec defines 2..=7; 1 / 8..=15 fall through to Unknown.
        assert_eq!(MenuType::from_nibble(1), MenuType::Unknown(1));
        assert_eq!(MenuType::from_nibble(0), MenuType::Unknown(0));
        // High nibble is masked off — only low 4 bits matter.
        assert_eq!(MenuType::from_nibble(0xF3), MenuType::Root);
    }
}