oxideav-mp4 0.0.10

Pure-Rust MP4 / ISO base media file container for oxideav
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
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
//! MP4 / ISOBMFF demuxer.
//!
//! Strategy on open():
//! 1. Validate ftyp.
//! 2. Walk `moov/trak/*` to collect per-track metadata and sample tables.
//! 3. Expand the sample tables into a flat, file-offset-sorted list of
//!    samples `(track_idx, offset, size, pts, duration)`.
//!
//! `next_packet` then serves them in order by seeking into the mdat.

use std::collections::HashSet;
use std::io::SeekFrom;

use oxideav_core::{
    CodecId, CodecParameters, CodecResolver, CodecTag, Error, MediaType, Packet, ProbeContext,
    Result, SampleFormat, StreamInfo, TimeBase,
};
use oxideav_core::{Demuxer, ReadSeek};

use crate::boxes::*;
use crate::cenc::{
    parse_piff_pssh, parse_piff_senc, parse_piff_tenc, parse_pssh, parse_senc, parse_tenc,
    PiffSencBox, PiffTencBox, PsshBox, SencBox, TencBox, PIFF_PSSH_USERTYPE, PIFF_SENC_USERTYPE,
    PIFF_TENC_USERTYPE,
};
use crate::codec_id::{from_sample_entry, from_sample_entry_with_oti};
use crate::emsg::{parse_emsg_box, EmsgBox};

pub fn open(input: Box<dyn ReadSeek>, codecs: &dyn CodecResolver) -> Result<Box<dyn Demuxer>> {
    Ok(Box::new(open_typed(input, codecs)?))
}

/// Open an MP4 / ISOBMFF input and return the concrete [`Mp4Demuxer`] โ€”
/// same parse as [`open`], but the typed form reaches the inherent
/// accessors that aren't part of the [`Demuxer`] trait (the structured
/// `sidx` / `ssix` / `tfra` / `pssh` / CENC `senc` / `saiz`+`saio` /
/// fragment-local sample-group records a decrypting or indexing layer
/// consumes). The `Box<dyn Demuxer>` form returned by [`open`] is what
/// the registry uses.
pub fn open_typed(mut input: Box<dyn ReadSeek>, codecs: &dyn CodecResolver) -> Result<Mp4Demuxer> {
    // Walk top-level boxes looking for ftyp + moov. Continue past moov
    // to pick up any movie fragments (`moof`+`mdat` pairs) that a
    // fragmented / DASH / HLS / Smooth Streaming MP4 emits after the
    // initial movie header. ISO/IEC 14496-12 ยง8.8.
    let mut saw_ftyp = false;
    let mut moov: Option<Vec<u8>> = None;
    let mut moofs: Vec<MoofRecord> = Vec::new();
    let mut sidxes: Vec<SidxRecord> = Vec::new();
    // ยง8.16.4 โ€” optional `ssix` SubsegmentIndexBoxes (zero or one per
    // leaf-only sidx, each immediately following its associated sidx).
    // Collected in file order; informational for this demuxer (we seek
    // via sidx / tfra), surfaced for partial-subsegment fetch tooling.
    let mut ssixes: Vec<SsixRecord> = Vec::new();
    let mut tfras: Vec<TfraRecord> = Vec::new();
    // ยง8.8.12 โ€” the `mfro` trailer's declared size of the enclosing
    // `mfra`, plus that mfra's actual on-disk size, captured so the
    // pair can be surfaced for validators (a player locates the mfra
    // by reading the last 16 bytes of the file; a wrong `mfro.size`
    // silently breaks that shortcut).
    let mut mfro_size: Option<u32> = None;
    let mut mfra_actual_size: Option<u64> = None;
    let mut prfts: Vec<PrftRecord> = Vec::new();
    // ยง8.1.3 โ€” optional `pdin` ProgressiveDownloadInfoBox. Quantity is
    // zero or one per file (ยง8.1.3.1); we keep the first instance seen
    // during the top-level walk and silently ignore any subsequent
    // copies (a malformed file with two pdin boxes is no reason to
    // abort the open โ€” the first is the one the spec endorses).
    let mut pdin: Option<PdinRecord> = None;
    // QuickTime Preview Atom (`pnot`) โ€” a top-level atom locating the
    // movie's preview (poster) image. Quantity zero or one; the first
    // instance seen wins.
    let mut pnot: Option<PnotRecord> = None;
    // ยง8.11 โ€” file-level `meta` box item infrastructure (HEIF / MIAF).
    // Quantity zero or one at the top level; the first instance wins. A
    // `meta` may also appear inside `moov` / `trak` (handled in
    // `parse_moov` / `parse_trak`); the file-level one is the HEIF home.
    let mut meta_items = MetaItems::default();
    // ยง8.11.7 โ€” file-level `meco` AdditionalMetadataContainerBox. Quantity
    // zero or one at each level (ยง8.11.7.1); the first instance wins. Holds
    // additional `meta` boxes (distinct handler types) plus `mere`
    // relations. Default-empty when no `meco` is present.
    let mut meco: MecoBox = MecoBox::default();
    // ISO/IEC 23009-1 ยง5.10.3.3 โ€” `emsg` DASH Event Message Boxes.
    // Zero or more per media segment, each placed before the first
    // `moof` of the segment it applies to. Collected in file order,
    // keyed by the index of the following `moof` (== the number of
    // moofs seen so far when the emsg is encountered) so a consumer
    // can anchor a v0 `presentation_time_delta` to the right
    // fragment's earliest presentation time.
    let mut emsgs: Vec<EmsgRecord> = Vec::new();
    while let Some(hdr) = read_box_header(&mut *input)? {
        match hdr.fourcc {
            FTYP => {
                saw_ftyp = true;
                skip_box_body(&mut *input, &hdr)?;
            }
            // ยง8.1.3 โ€” `pdin` ProgressiveDownloadInfoBox. Top-level
            // FullBox carrying (rate, initial_delay) u32 pairs that hint
            // the suggested initial playback delay for a given effective
            // download rate. Captured for the structured `pdin_entries`
            // accessor and surfaced as flat `pdin` / `pdin_<n>`
            // metadata keys below.
            PDIN => {
                let body = read_box_body(&mut *input, &hdr)?;
                if pdin.is_none() {
                    pdin = Some(parse_pdin(&body)?);
                }
            }
            // QuickTime Preview Atom (`pnot`) โ€” a top-level plain `Box`
            // locating the movie's preview (poster) image. The first
            // parseable instance wins; a malformed one is dropped
            // (informational) rather than aborting the open.
            PNOT => {
                let body = read_box_body(&mut *input, &hdr)?;
                if pnot.is_none() {
                    pnot = parse_pnot(&body);
                }
            }
            MOOV => {
                moov = Some(read_box_body(&mut *input, &hdr)?);
            }
            // ยง8.16 โ€” `styp` SegmentTypeBox (CMAF / DASH segment marker).
            // Same shape as ftyp; we just skip its payload.
            STYP => skip_box_body(&mut *input, &hdr)?,
            // ยง8.16.3 โ€” `sidx` SegmentIndexBox. Sample-precision seek
            // index for adaptive-bitrate streams. Capture the absolute
            // file offset of the sidx itself โ€” sidx-internal references
            // are relative to "the first byte after this box" (per
            // spec), so we need that anchor to resolve them.
            SIDX => {
                let body_start = input.stream_position()?;
                let sidx_end_offset = body_start
                    + hdr
                        .payload_size()
                        .ok_or_else(|| Error::invalid("MP4: open-ended sidx"))?;
                let body = read_box_body(&mut *input, &hdr)?;
                if let Some(r) = parse_sidx(&body, sidx_end_offset)? {
                    sidxes.push(r);
                }
            }
            // ยง8.16.4 โ€” `ssix` SubsegmentIndexBox. Maps levels (per the
            // `leva` LevelAssignmentBox, ยง8.8.13) to byte ranges of the
            // subsegments indexed by the immediately preceding `sidx`,
            // enabling partial-subsegment byte-range access. The box is
            // informational for this demuxer (seeking uses sidx / tfra),
            // so โ€” like `leva` โ€” a malformed instance is dropped rather
            // than aborting the open.
            SSIX => {
                let body = read_box_body(&mut *input, &hdr)?;
                if let Ok(r) = parse_ssix(&body) {
                    ssixes.push(r);
                }
            }
            // ยง8.8.4 โ€” `moof` MovieFragmentBox. Capture the body and
            // remember where the box itself started โ€” the
            // `default-base-is-moof` flag in `tfhd` makes per-sample
            // offsets relative to this position.
            MOOF => {
                let payload_size = hdr
                    .payload_size()
                    .ok_or_else(|| Error::invalid("MP4: open-ended moof"))?;
                // Position after read_box_header is the body start; the
                // moof box itself starts header_len bytes earlier.
                let body_start = input.stream_position()?;
                let moof_start = body_start - hdr.header_len;
                let body = read_bytes_vec(&mut *input, payload_size as usize)?;
                moofs.push(MoofRecord { moof_start, body });
            }
            // ยง8.8.10 โ€” `mfra` MovieFragmentRandomAccessBox. Container
            // for one `tfra` per track-with-random-access plus the
            // size-of-mfra `mfro` trailer. Parsed for the byte-range
            // seek-table consumed by `seek_to`.
            MFRA => {
                let body = read_box_body(&mut *input, &hdr)?;
                mfra_actual_size = Some(hdr.header_len + body.len() as u64);
                parse_mfra(&body, &mut tfras, &mut mfro_size)?;
            }
            // ISO/IEC 23009-1 ยง5.10.3.3 โ€” `emsg` DASH Event Message
            // Box. Top-level, zero or more before the first `moof` of
            // the segment each applies to. Purely informational for
            // this demuxer (the events belong to an application
            // layer), so โ€” mirroring `ssix` / `leva` โ€” a malformed
            // instance is dropped rather than aborting the open.
            EMSG => {
                let body = read_box_body(&mut *input, &hdr)?;
                if let Ok(e) = parse_emsg_box(&body) {
                    emsgs.push(EmsgRecord {
                        next_moof_index: moofs.len(),
                        emsg: e,
                    });
                }
            }
            // ยง8.16.5 โ€” `prft` ProducerReferenceTimeBox. Top-level
            // FullBox correlating wall-clock NTP time with a media
            // time on one reference track. Multiple instances are
            // allowed; each is associated with the following moof in
            // file order. We collect them all; callers walk the
            // returned list / metadata channel.
            PRFT => {
                let body = read_box_body(&mut *input, &hdr)?;
                if let Some(r) = parse_prft(&body)? {
                    prfts.push(r);
                }
            }
            // ยง8.11 โ€” file-level `meta` box (HEIF / MIAF item catalogue).
            // Parse the ยง8.11 item infrastructure (pitm / iloc / iinf /
            // iref) the first time one is seen; subsequent copies (a
            // malformed file with two file-level meta boxes) are skipped.
            META => {
                let body = read_box_body(&mut *input, &hdr)?;
                if meta_items.is_empty() && meta_items.handler_type == [0; 4] {
                    meta_items = parse_meta_items(&body);
                }
            }
            // ยง8.11.7 โ€” file-level `meco` AdditionalMetadataContainerBox.
            // Parse the first instance's additional `meta` boxes + `mere`
            // relations; subsequent copies are skipped.
            MECO => {
                let body = read_box_body(&mut *input, &hdr)?;
                if meco.is_empty() {
                    meco = parse_meco_box(&body);
                }
            }
            _ => skip_box_body(&mut *input, &hdr)?,
        }
    }
    if !saw_ftyp {
        return Err(Error::invalid("MP4: missing ftyp box"));
    }
    let moov = moov.ok_or_else(|| Error::invalid("MP4: missing moov box"))?;

    // Established before the moov walk: several sample-table entry
    // counts (most notably the constant-size `stsz` shape, whose
    // sample_count is backed by no table bytes at all) are validated
    // against the input size so a forged 32-bit count cannot drive a
    // multi-GiB allocation from a small file.
    let file_size = input.seek(std::io::SeekFrom::End(0))?;
    let mut parsed = parse_moov(&moov, file_size)?;
    if parsed.tracks.is_empty() {
        return Err(Error::invalid("MP4: no tracks"));
    }

    // Resolve each track's ยง8.6.6 edit list onto the presentation
    // timeline. Deferred to here (not parse_trak) because the
    // `segment_duration` rescale needs the movie timescale from
    // `mvhd`, which may legitimately follow the `trak` boxes.
    let movie_timescale = parsed.movie_timescale;
    for t in &mut parsed.tracks {
        t.elst_timeline = build_elst_timeline(&t.elst, movie_timescale, t.timescale);
    }
    let parsed = parsed;

    let mut streams: Vec<StreamInfo> = Vec::with_capacity(parsed.tracks.len());
    let mut samples: Vec<SampleRef> = Vec::new();
    for (i, t) in parsed.tracks.iter().enumerate() {
        streams.push(build_stream_info(i as u32, t, codecs));
        expand_samples(t, i as u32, &mut samples)?;
    }

    // Per-track running base_media_decode_time, used when a fragment's
    // `tfdt` box is absent. Initialised from the last DTS+duration of
    // the moov-derived samples for that track (zero if none).
    let mut next_dts: Vec<i64> = vec![0; parsed.tracks.len()];
    for s in &samples {
        let idx = s.track_idx as usize;
        let end = s.dts.saturating_add(s.duration);
        if end > next_dts[idx] {
            next_dts[idx] = end;
        }
    }

    let mut senc_records: Vec<SencRecord> = Vec::new();
    let mut sai_records: Vec<SaiRecord> = Vec::new();
    let mut moof_psshes: Vec<MoofPsshRecord> = Vec::new();
    let mut traf_sample_groups: Vec<TrafSampleGroupRecord> = Vec::new();
    let mut piff_senc_records: Vec<PiffSencRecord> = Vec::new();
    let mut piff_moof_psshes: Vec<MoofPsshRecord> = Vec::new();
    let mut empty_durations: Vec<EmptyDurationRecord> = Vec::new();
    // Per-moof earliest presentation time, captured while the samples
    // each fragment contributes are still contiguous (before the
    // global offset sort below). ISO/IEC 23009-1 ยง5.10.3.3 anchors a
    // v0 emsg's `presentation_time_delta` to "the earliest
    // presentation time of the segment" โ€” this table lets
    // `Mp4Demuxer::emsg_absolute_time` resolve that anchor without
    // re-walking the file. Each entry is `(pts, track_timescale)` of
    // the earliest-presented sample the moof added (compared across
    // tracks by cross-multiplication so differing timescales order
    // correctly); `None` for a moof that added no timed samples.
    let mut moof_earliest: Vec<Option<(i64, u32)>> = Vec::with_capacity(moofs.len());
    // Whole-file sample budget: no fragmented file can materialize
    // more samples than it has bytes (every legitimate sample costs at
    // least one input byte somewhere โ€” a per-sample trun field, mdat
    // payload, or box structure). `parse_trun` charges each declared
    // `sample_count` against this budget, so a forged 32-bit count in
    // a defaults-only trun (zero wire bytes per sample) cannot drive
    // a multi-GiB `SampleRef`/`TrunSample` allocation from a small
    // input. The floor keeps degenerate-but-legal tiny files working.
    let mut sample_budget: u64 = {
        let end = input.seek(std::io::SeekFrom::End(0))?;
        end.max(4096)
    };
    for moof in &moofs {
        let before = samples.len();
        parse_moof(
            moof,
            &parsed.tracks,
            &mut samples,
            &mut next_dts,
            &mut senc_records,
            &mut sai_records,
            &mut moof_psshes,
            &mut traf_sample_groups,
            &mut piff_senc_records,
            &mut piff_moof_psshes,
            &mut empty_durations,
            &mut sample_budget,
        )?;
        let mut best: Option<(i64, u32)> = None;
        for s in &samples[before..] {
            let ts = parsed.tracks[s.track_idx as usize].timescale;
            if ts == 0 {
                continue;
            }
            best = match best {
                None => Some((s.pts, ts)),
                // `a/at < b/bt` โ‡” `aยทbt < bยทat` (timescales positive).
                Some((b_pts, b_ts)) => {
                    if (s.pts as i128) * (b_ts as i128) < (b_pts as i128) * (ts as i128) {
                        Some((s.pts, ts))
                    } else {
                        Some((b_pts, b_ts))
                    }
                }
            };
        }
        moof_earliest.push(best);
    }

    samples.sort_by_key(|s| s.offset);

    // Movie duration from mvhd (ยง8.2.2), with ยง8.8.2 `mehd`
    // (MovieExtendsHeaderBox) as fall-back for fragmented files. When
    // a fragmented file is sealed with a known overall duration, the
    // authoring step writes `mehd.fragment_duration` while
    // `mvhd.duration` may legitimately stay zero (the moov has no
    // resident samples that contribute to the duration). In that case
    // we report the mehd value; when mvhd already supplies a non-zero
    // duration and mehd is also present, the spec wording
    // ("provides the overall duration, including fragments") makes
    // mehd the authoritative total, so we still prefer it.
    let effective_duration: u64 = parsed
        .mehd_fragment_duration
        .filter(|&d| d > 0)
        .unwrap_or(parsed.movie_duration);
    let duration_micros: i64 = if parsed.movie_timescale > 0 && effective_duration > 0 {
        (effective_duration as i128 * 1_000_000 / parsed.movie_timescale as i128) as i64
    } else {
        0
    };

    // Surface ยง8.8.2 mehd fragment_duration as a top-level metadata
    // key when present. Mirrors the rest of this crate's flat metadata
    // surface: the structured value is also reflected in
    // `Demuxer::duration_micros` (see the duration calc above); this
    // key exposes the raw value in the movie timescale for tooling
    // that wants the untranslated number (e.g. CMAF live-edge probes
    // wanting to confirm a producer's sealed total against their own
    // running tally). Absent `mehd`, no key is emitted.
    let mut metadata = parsed.metadata;
    if let Some(d) = parsed.mehd_fragment_duration {
        metadata.push(("mehd_fragment_duration".to_string(), d.to_string()));
    }

    // Surface a parsed `pdin` (ProgressiveDownloadInfoBox, ยง8.1.3) on
    // the flat metadata channel. Quantity is zero or one per file
    // (ยง8.1.3.1); we emit:
    //   - `pdin_count` = number of (rate, initial_delay) pairs
    //   - `pdin_<n>` = "rate initial_delay" (decimal, space-separated)
    //     for n in 0..count, mirroring the per-pair surface used for
    //     `prft_<n>`. A consumer that wants the structured record
    //     reaches for `Mp4Demuxer::pdin_entries()` (or the public
    //     `parse_pdin_box`) โ€” the flat surface is for tooling that
    //     prefers a string-keyed metadata bag.
    // Absent `pdin`, no keys are emitted.
    if let Some(p) = pdin.as_ref() {
        metadata.push(("pdin_count".to_string(), p.entries.len().to_string()));
        for (n, e) in p.entries.iter().enumerate() {
            metadata.push((
                format!("pdin_{n}"),
                format!("{} {}", e.rate, e.initial_delay),
            ));
        }
    }

    // Surface a QuickTime Preview Atom (`pnot`) on the flat metadata
    // channel as `pnot` with value "<atom_type> <atom_index>
    // mod=<modification_date>" โ€” the FourCC of the atom that holds the
    // preview data (e.g. `PICT`), which instance of that type to use, and
    // the Macintosh-format modification date. The structured record is
    // reachable via `Mp4Demuxer::pnot()` (or the public `parse_pnot_box`).
    // Absent `pnot`, no key is emitted.
    if let Some(p) = pnot.as_ref() {
        metadata.push((
            "pnot".to_string(),
            format!(
                "{} {} mod={}",
                String::from_utf8_lossy(&p.atom_type),
                p.atom_index,
                p.modification_date
            ),
        ));
    }

    // Surface the file-level `meta` box item infrastructure (ยง8.11) on
    // the flat metadata channel. The structured records are reachable
    // via `Mp4Demuxer::meta_items()`; the flat surface mirrors the rest
    // of this crate's string-keyed bag for tooling that prefers it.
    // Emitted (only when the corresponding box was present):
    //   - `meta_handler` = the `meta`'s hdlr handler_type FourCC
    //   - `meta_primary_item` = the `pitm` primary item_ID
    //   - `meta_item_count` = number of `iinf` `infe` entries
    //   - `meta_item_<n>` = "id=<id> type=<fourcc|v0/1> name=<name>"
    //   - `meta_iloc_count` = number of `iloc` item-location records
    //   - `meta_iref_count` = number of `iref` reference groups
    surface_meta_items(&meta_items, &mut metadata);

    // Surface a file-level `meco` (AdditionalMetadataContainerBox,
    // ยง8.11.7) on the flat metadata channel. Emitted only when a `meco`
    // was present and non-empty:
    //   - `meco_meta_count` = number of additional `meta` boxes
    //   - `meco_meta_<n>` = the additional `meta`'s handler_type FourCC
    //   - `meco_relation_count` = number of `mere` relation boxes
    //   - `meco_relation_<n>` = "<first>-<second>=<relation>" (the two
    //     handler-type FourCCs and the ยง8.11.8.3 relation value)
    // Structured records via `Mp4Demuxer::meco()`.
    if !meco.is_empty() {
        if !meco.metas.is_empty() {
            metadata.push(("meco_meta_count".to_string(), meco.metas.len().to_string()));
            for (n, m) in meco.metas.iter().enumerate() {
                metadata.push((
                    format!("meco_meta_{n}"),
                    String::from_utf8_lossy(&m.handler_type).to_string(),
                ));
            }
        }
        if !meco.relations.is_empty() {
            metadata.push((
                "meco_relation_count".to_string(),
                meco.relations.len().to_string(),
            ));
            for (n, r) in meco.relations.iter().enumerate() {
                metadata.push((
                    format!("meco_relation_{n}"),
                    format!(
                        "{}-{}={}",
                        String::from_utf8_lossy(&r.first_metabox_handler_type),
                        String::from_utf8_lossy(&r.second_metabox_handler_type),
                        r.metabox_relation
                    ),
                ));
            }
        }
    }

    // Surface a parsed `leva` (LevelAssignmentBox, ยง8.8.13) on the flat
    // metadata channel. Quantity is zero or one per file (ยง8.8.13.1);
    // we emit:
    //   - `leva_count` = number of per-level entries
    //   - `leva_<n>` = "<track_id> pad=<0|1> at=<assignment_type>
    //     [grouping_type=<u32>] [grouping_type_parameter=<u32>]
    //     [sub_track_id=<u32>]" โ€” the trailing tokens are emitted only
    //     when their assignment_type variant uses them, mirroring the
    //     variant-specific tails in ยง8.8.13.2.
    // A consumer that wants the structured record reaches for
    // `Mp4Demuxer::leva_entries()` (or the public `parse_leva_box`).
    // Absent `leva`, no keys are emitted.
    if let Some(l) = parsed.leva.as_ref() {
        metadata.push(("leva_count".to_string(), l.entries.len().to_string()));
        for (n, e) in l.entries.iter().enumerate() {
            let mut s = format!(
                "{} pad={} at={}",
                e.track_id, e.padding_flag as u8, e.assignment_type
            );
            match e.assignment_type {
                0 => {
                    use std::fmt::Write;
                    let _ = write!(s, " grouping_type={}", e.grouping_type);
                }
                1 => {
                    use std::fmt::Write;
                    let _ = write!(
                        s,
                        " grouping_type={} grouping_type_parameter={}",
                        e.grouping_type, e.grouping_type_parameter,
                    );
                }
                4 => {
                    use std::fmt::Write;
                    let _ = write!(s, " sub_track_id={}", e.sub_track_id);
                }
                _ => {}
            }
            metadata.push((format!("leva_{n}"), s));
        }
    }

    // Surface any parsed `trep` TrackExtensionPropertiesBoxes (ยง8.8.15)
    // on the flat metadata channel. Quantity is zero or more (zero or
    // one per track, ยง8.8.15.1); we emit one `trep_<n>` key per box, in
    // file order, with value "<track_id> children=<k>[ <fourcc>...]" โ€”
    // the track the box describes, the number of nested child boxes,
    // and each child's four-character type (so a consumer can spot an
    // `assp` without consuming the structured record). Callers wanting
    // the structured form reach for `Mp4Demuxer::treps()` (or the
    // public `parse_trep_box`). Absent `trep`, no keys are emitted.
    for (n, t) in parsed.treps.iter().enumerate() {
        let mut s = format!("{} children={}", t.track_id, t.children.len());
        for c in &t.children {
            use std::fmt::Write;
            let _ = write!(s, " {}", String::from_utf8_lossy(&c.fourcc));
            // The one base-spec-defined child is `assp` (ยง8.8.16); when
            // it decoded cleanly, append its min_initial_alt_startup
            // offset(s) so a consumer reading the flat channel sees the
            // alternative-startup bound without reaching for the typed
            // record. v0 โ†’ "assp(off=<i>)"; v1 โ†’ one
            // "<grouping_type_parameter>:<offset>" token per entry,
            // e.g. "assp(0:-5 1:0)".
            if let Some(a) = &c.assp {
                if a.version == 0 {
                    if let Some(e) = a.entries.first() {
                        let _ = write!(s, "(off={})", e.min_initial_alt_startup_offset);
                    }
                } else {
                    let _ = write!(s, "(");
                    for (i, e) in a.entries.iter().enumerate() {
                        if i > 0 {
                            let _ = write!(s, " ");
                        }
                        let _ = write!(
                            s,
                            "{}:{}",
                            e.grouping_type_parameter.unwrap_or(0),
                            e.min_initial_alt_startup_offset
                        );
                    }
                    let _ = write!(s, ")");
                }
            }
        }
        metadata.push((format!("trep_{n}"), s));
    }

    // Surface any parsed `prft` ProducerReferenceTimeBoxes through the
    // container metadata channel as `prft_<n>` (0-based file order)
    // with value "reference_track_ID ntp_timestamp media_time" โ€” three
    // decimal integers, space-separated, mirroring the
    // `tref_<type>` / `sgpd_<n>` conventions used elsewhere in this
    // crate. When the 2022-edition `flags` annotation bits are set, a
    // trailing space-separated token list of the set names
    // (`encoder_input_output`, `finalization_time`, `file_write_time`,
    // `arbitrary_association`, `realtime_offset`) is appended; the
    // three-integer prefix stays backward-compatible. Callers wanting the
    // structured record can use the public `parse_prft_box` entry point.
    // Absent prft, no keys are emitted.
    for (n, p) in prfts.iter().enumerate() {
        let mut value = format!(
            "{} {} {}",
            p.reference_track_id, p.ntp_timestamp, p.media_time
        );
        // `realtime_offset` is the combined 0x18 mask; surface it instead
        // of its two component bits when both are set.
        if p.is_realtime_offset() {
            value.push_str(" realtime_offset");
        } else {
            if p.is_finalization_time() {
                value.push_str(" finalization_time");
            }
            if p.is_arbitrary_association() {
                value.push_str(" arbitrary_association");
            }
        }
        if p.is_encoder_input_output() {
            value.push_str(" encoder_input_output");
        }
        if p.is_file_write_time() {
            value.push_str(" file_write_time");
        }
        metadata.push((format!("prft_{n}"), value));
    }

    // Surface any parsed `ssix` SubsegmentIndexBoxes (ยง8.16.4) through
    // the container metadata channel as `ssix_<n>` (0-based file order)
    // with summary value "<subsegment_count> <total_range_count>" โ€”
    // two decimal integers, space-separated. The full per-subsegment
    // (level, range_size) table can be large (one 4-byte record per
    // partial-subsegment range), so the flat channel carries only the
    // shape; callers wanting the structured record reach for the
    // public `parse_ssix_box` entry point (or `Mp4Demuxer::ssixes`).
    // Absent ssix, no keys are emitted.
    for (n, s) in ssixes.iter().enumerate() {
        let total_ranges: usize = s.subsegments.iter().map(|ss| ss.ranges.len()).sum();
        metadata.push((
            format!("ssix_{n}"),
            format!("{} {}", s.subsegments.len(), total_ranges),
        ));
    }

    // ยง8.8.12 โ€” surface the mfro-declared mfra size (and, when it
    // disagrees with the mfra box actually measured on disk, the
    // mismatch) so a validator or last-16-bytes locator can trust or
    // flag the trailer without re-walking the file. Absent mfro, no
    // keys are emitted.
    if let Some(declared) = mfro_size {
        metadata.push(("mfro_size".to_string(), declared.to_string()));
        if let Some(actual) = mfra_actual_size {
            if declared as u64 != actual {
                metadata.push((
                    "mfro_size_mismatch".to_string(),
                    format!("declared={declared} actual={actual}"),
                ));
            }
        }
    }

    // Surface ISO/IEC 23001-7 ยง8.1 pssh boxes as `pssh_<n>` keys with
    // value `"<system_id_hex> <kid_count> <data_len>"`. Callers wanting
    // the structured record use the public `Mp4Demuxer::psshes` accessor.
    for (n, p) in parsed.psshes.iter().enumerate() {
        let sysid_hex: String = p.system_id.iter().map(|b| format!("{b:02x}")).collect();
        metadata.push((
            format!("pssh_{n}"),
            format!("{} {} {}", sysid_hex, p.kids.len(), p.data.len()),
        ));
    }

    // Aggregate counter for ยง7.2 senc โ€” one key per (track_idx,
    // moof_sequence) record with summary "<sample_count> <flags_hex>".
    for (n, r) in senc_records.iter().enumerate() {
        metadata.push((
            format!("senc_{n}"),
            format!(
                "track={} seq={} samples={} flags=0x{:08x}",
                r.track_idx,
                r.moof_sequence,
                r.senc.samples.len(),
                r.senc.flags,
            ),
        ));
    }

    // ยง8.7.8โ€“9 โ€” per-fragment `(saiz, saio)` summary, one key per
    // SaiRecord (one per `traf` that carried at least one box).
    // Format: "track=<t> seq=<s> saiz=<n> saio=<m>" so a caller knows
    // the box counts on this fragment without consuming the public
    // SaiRecord vector. Structured records remain accessible via
    // `Mp4Demuxer::sai_records()`.
    for (n, r) in sai_records.iter().enumerate() {
        metadata.push((
            format!("frag_sai_{n}"),
            format!(
                "track={} seq={} saiz={} saio={}",
                r.track_idx,
                r.moof_sequence,
                r.saiz.len(),
                r.saio.len(),
            ),
        ));
    }

    // ยง8.8.7 duration-is-empty โ€” one `frag_empty_duration_<n>` key per
    // empty-time traf, in moof-walk order. Format: "track=<t> seq=<s>
    // duration=<d>" (duration in the track's media timescale). The
    // typed records remain accessible via
    // `Mp4Demuxer::empty_duration_records()`.
    for (n, r) in empty_durations.iter().enumerate() {
        metadata.push((
            format!("frag_empty_duration_{n}"),
            format!(
                "track={} seq={} duration={}",
                r.track_idx, r.moof_sequence, r.duration,
            ),
        ));
    }

    // ISO/IEC 23001-7 ยง8.1 โ€” pssh boxes that live inside individual
    // `moof` boxes (ยง8.1.1 permits pssh in either `moov` or `moof`).
    // One `moof_pssh_<n>` key per MoofPsshRecord, in moof-walk order,
    // summarising SystemID + fragment scope. The structured records
    // are accessible via `Mp4Demuxer::moof_psshes()`. Hex encoding
    // mirrors the moov-level `pssh_<n>` SystemID surface.
    for (n, r) in moof_psshes.iter().enumerate() {
        let sysid_hex: String = r
            .pssh
            .system_id
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        metadata.push((
            format!("moof_pssh_{n}"),
            format!(
                "systemid={} seq={} kids={} data={}",
                sysid_hex,
                r.moof_sequence,
                r.pssh.kids.len(),
                r.pssh.data.len(),
            ),
        ));
    }

    // PIFF legacy `uuid` boxes โ€” flat-metadata summaries mirroring
    // their CENC 4CC counterparts, with a `piff_` prefix so a consumer
    // can tell the legacy carriage from the modern one:
    //   - `piff_pssh_<n>`      moov-level uuid pssh (SystemID + sizes)
    //   - `piff_moof_pssh_<n>` moof-level uuid pssh keyed by sequence
    //   - `piff_senc_<n>`      per-traf uuid SampleEncryptionBox
    //     summary; `override=1` marks a box whose `flags & 1` triple
    //     replaces the track defaults for this fragment.
    // Structured records via `Mp4Demuxer::piff_psshes` /
    // `piff_moof_psshes` / `piff_senc_records`.
    for (n, p) in parsed.piff_psshes.iter().enumerate() {
        let sysid_hex: String = p.system_id.iter().map(|b| format!("{b:02x}")).collect();
        metadata.push((
            format!("piff_pssh_{n}"),
            format!("{} {} {}", sysid_hex, p.kids.len(), p.data.len()),
        ));
    }
    for (n, r) in piff_moof_psshes.iter().enumerate() {
        let sysid_hex: String = r
            .pssh
            .system_id
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        metadata.push((
            format!("piff_moof_pssh_{n}"),
            format!(
                "systemid={} seq={} kids={} data={}",
                sysid_hex,
                r.moof_sequence,
                r.pssh.kids.len(),
                r.pssh.data.len(),
            ),
        ));
    }
    for (n, r) in piff_senc_records.iter().enumerate() {
        metadata.push((
            format!("piff_senc_{n}"),
            format!(
                "track={} seq={} samples={} flags=0x{:08x} override={}",
                r.track_idx,
                r.moof_sequence,
                r.senc.samples.len(),
                r.senc.flags,
                u8::from(r.senc.has_override()),
            ),
        ));
    }

    // ISO/IEC 23009-1 ยง5.10.3.3 โ€” `emsg` DASH Event Message summaries,
    // one `emsg_<n>` key per box in file order. Value:
    // "scheme=<uri> value=<v> timescale=<ts> {delta|time}=<t>
    // duration=<d> id=<i> bytes=<len> before_moof=<k>" โ€” `delta` for a
    // v0 (segment-relative) event, `time` for a v1 (absolute) one, and
    // `before_moof` the index of the moof the box preceded. Structured
    // records via `Mp4Demuxer::emsgs`.
    for (n, r) in emsgs.iter().enumerate() {
        let time_token = match r.emsg.presentation {
            crate::emsg::EmsgTime::Delta(d) => format!("delta={d}"),
            crate::emsg::EmsgTime::Absolute(t) => format!("time={t}"),
        };
        metadata.push((
            format!("emsg_{n}"),
            format!(
                "scheme={} value={} timescale={} {} duration={} id={} bytes={} before_moof={}",
                r.emsg.scheme_id_uri,
                r.emsg.value,
                r.emsg.timescale,
                time_token,
                r.emsg.event_duration,
                r.emsg.id,
                r.emsg.message_data.len(),
                r.next_moof_index,
            ),
        ));
    }

    // ยง8.9 โ€” per-fragment sample-group summary, one `frag_sample_group_<n>`
    // key per `traf` that carried at least one `sgpd` / `sbgp` / `csgp`.
    // Format: "track=<t> seq=<s> sgpd=<n> sbgp=<m> csgp=<k>" so a caller
    // knows the box counts on this fragment without consuming the public
    // record vector. Structured records are reachable via
    // `Mp4Demuxer::traf_sample_groups()`.
    for (n, r) in traf_sample_groups.iter().enumerate() {
        metadata.push((
            format!("frag_sample_group_{n}"),
            format!(
                "track={} seq={} sgpd={} sbgp={} csgp={}",
                r.track_idx,
                r.moof_sequence,
                r.sgpd.len(),
                r.sbgp.len(),
                r.csgp.len(),
            ),
        ));
    }

    Ok(Mp4Demuxer {
        input,
        input_len: file_size,
        streams,
        samples,
        cursor: 0,
        metadata,
        duration_micros,
        sidxes,
        ssixes,
        tfras,
        prfts,
        pdin,
        pnot,
        leva: parsed.leva,
        treps: parsed.treps,
        psshes: parsed.psshes,
        moof_psshes,
        senc_records,
        sai_records,
        empty_durations,
        track_tenc_iv_sizes: parsed
            .tracks
            .iter()
            .map(|t| t.tenc.as_ref().map(|x| x.default_per_sample_iv_size))
            .collect(),
        traf_sample_groups,
        piff_psshes: parsed.piff_psshes,
        piff_moof_psshes,
        piff_senc_records,
        piff_tencs: parsed.tracks.iter().map(|t| t.piff_tenc.clone()).collect(),
        emsgs,
        moof_earliest,
        meta_items,
        meco,
        movie_timescale: parsed.movie_timescale,
        track_timescales: parsed.tracks.iter().map(|t| t.timescale).collect(),
        track_ids: parsed.tracks.iter().map(|t| t.track_id).collect(),
        edit_lists: parsed
            .tracks
            .iter()
            .map(|t| t.elst.iter().map(elst_entry_to_public).collect())
            .collect(),
        last_sdi: None,
    })
}

/// One ISO/IEC 23009-1 ยง5.10.3.3 `emsg` DASH Event Message Box
/// captured during the top-level walk, in file order. The box carries
/// one timed in-band event (SCTE-35 splice, ad marker, application
/// event); it is placed before the first `moof` of the media segment
/// it applies to, so the record keys it by the index of the moof that
/// followed it.
#[derive(Clone, Debug)]
pub struct EmsgRecord {
    /// Index (into the file's moof sequence, 0-based file order) of
    /// the `moof` this box preceded โ€” the segment the event applies
    /// to. A v0 event's `presentation_time_delta` is relative to that
    /// fragment's earliest presentation time. Equal to the total moof
    /// count when a (non-conforming) producer placed the box after the
    /// last `moof`; the record is still surfaced so a validator can
    /// flag it.
    pub next_moof_index: usize,
    /// The parsed event message.
    pub emsg: EmsgBox,
}

/// One `moof` box captured from the top-level walk. We hold onto the
/// payload bytes plus the absolute file offset of the `moof` box's
/// header โ€” needed for the `default-base-is-moof` data-offset fall-back
/// (ISO/IEC 14496-12 ยง8.8.7.1, flag 0x020000) and for `tfhd`
/// `base_data_offset` arithmetic.
struct MoofRecord {
    moof_start: u64,
    body: Vec<u8>,
}

/// Decoded `sidx` (SegmentIndexBox, ยง8.16.3) for one track. Each
/// reference describes one subsegment (typically one `moof+mdat` pair):
/// its byte size, its decode-time duration in this track's timescale,
/// and a SAP-type flag (we keep the sync-bit surface but only use the
/// "starts-with-SAP" marker).
#[derive(Clone, Debug)]
pub struct SidxRecord {
    /// `reference_ID` โ€” usually a `tkhd.track_ID` for a single-track
    /// segment, or a hierarchical index ID for nested sidx.
    pub reference_id: u32,
    /// Timescale for `earliest_presentation_time` and per-reference
    /// `subsegment_duration` (per spec, NOT the track's media timescale
    /// โ€” DASH-IF Interop ยง6.2.3 uses the track timescale here, but the
    /// sidx is allowed to pick its own).
    pub timescale: u32,
    /// Composition timestamp of the first sample referenced.
    pub earliest_presentation_time: u64,
    /// File offset of the first byte of the FIRST referenced
    /// subsegment, computed from `first_offset` + `sidx_end_offset`
    /// (ยง8.16.3.1: "an unsigned integer that gives the offset relative
    /// to the first byte after this box").
    pub first_byte_offset: u64,
    pub references: Vec<SidxReference>,
}

#[derive(Clone, Copy, Debug)]
pub struct SidxReference {
    /// True when this reference points to another `sidx` (hierarchical
    /// index), false when it points to the actual media subsegment.
    pub is_sidx: bool,
    /// Total byte size of the referenced subsegment / sidx.
    pub referenced_size: u32,
    /// Decode-time duration of the subsegment in `timescale` units.
    pub subsegment_duration: u32,
    /// True when the subsegment starts with a Stream Access Point.
    pub starts_with_sap: bool,
    /// SAP type (0..=7); 1 = Closed-GOP (IDR), 2 = open-GOP IDR-like,
    /// 3 = open-GOP, etc. Per ยงI.2 of ISO/IEC 14496-12.
    pub sap_type: u8,
}

/// Decoded `ssix` (SubsegmentIndexBox, ISO/IEC 14496-12 ยง8.16.4).
///
/// Maps levels (as assigned by the `leva` LevelAssignmentBox, ยง8.8.13)
/// to byte ranges of the indexed subsegments, so a client can fetch a
/// partial subsegment (e.g. only the lower temporal levels) by byte
/// range instead of downloading the whole subsegment. Placement rules
/// (ยง8.16.4.1): zero or one per `sidx` that indexes only leaf
/// subsegments, immediately following the associated `sidx`;
/// `subsegment_count` shall equal that sidx's `reference_count`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SsixRecord {
    /// One entry per subsegment indexed by the associated `sidx`, in
    /// the same order as the sidx references.
    pub subsegments: Vec<SsixSubsegment>,
}

/// Per-subsegment range list inside an `ssix` (ยง8.16.4.2).
///
/// Every byte of the subsegment is explicitly assigned to a level, so
/// the ranges partition the subsegment: range j starts at the byte
/// immediately after range jโˆ’1 ends (the first at the subsegment's
/// first byte) and spans `range_size` bytes. ยง8.16.4.1 requires at
/// least two ranges per subsegment in a conforming file; we parse a
/// smaller count without error (the constraint binds writers โ€” a
/// reader gains nothing by rejecting a one-range partition).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SsixSubsegment {
    pub ranges: Vec<SsixRange>,
}

/// One (level, range_size) record of an `ssix` subsegment (ยง8.16.4.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SsixRange {
    /// Level this partial subsegment is assigned to (ยง8.16.4.3). For
    /// leaf subsegments, levels appear in increasing order within a
    /// subsegment โ€” samples of a partial subsegment may depend on
    /// preceding partial subsegments of the same subsegment, never on
    /// later ones.
    pub level: u8,
    /// Byte size of the partial subsegment (24-bit field, so at most
    /// 0xFF_FFFF per range; larger spans repeat the level across
    /// consecutive ranges).
    pub range_size: u32,
}

/// Decoded `tfra` (TrackFragmentRandomAccessBox, ยง8.8.11) โ€” per-track
/// table of moof byte offsets keyed by presentation time. One entry per
/// random-access point in the track.
#[derive(Clone, Debug)]
pub struct TfraRecord {
    pub track_id: u32,
    pub entries: Vec<TfraEntry>,
}

#[derive(Clone, Copy, Debug)]
pub struct TfraEntry {
    /// Decoding time of the random-access sample in the track's media
    /// timescale (NOT the movie timescale).
    pub time: u64,
    /// File offset of the `moof` box containing the sample.
    pub moof_offset: u64,
    /// 1-based traf number within that moof.
    pub traf_number: u32,
    /// 1-based trun number within that traf.
    pub trun_number: u32,
    /// 1-based sample index within that trun.
    pub sample_number: u32,
}

/// Decoded `prft` (ProducerReferenceTimeBox, ISO/IEC 14496-12 ยง8.16.5).
///
/// A producer reference time correlates a UTC wall-clock instant (in
/// NTP 64-bit format, RFC 5905 โ€” high 32 bits = seconds since 1900-01-01,
/// low 32 bits = fractional seconds) with a media time on one reference
/// track. The box appears at file scope and relates to the NEXT `moof`
/// box that follows it in bitstream order (ยง8.16.5.1 placement rule),
/// so a low-latency DASH/CMAF live consumer can match production
/// wall-clock to media presentation time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PrftRecord {
    /// `track_ID` of the reference track whose `media_time` this box
    /// annotates (ยง8.16.5.3 reference_track_ID).
    pub reference_track_id: u32,
    /// UTC time in NTP 64-bit format. Caller decomposes into seconds
    /// (`(ntp_timestamp >> 32) - 2_208_988_800` for Unix epoch) and
    /// fractional seconds (`(ntp_timestamp & 0xFFFF_FFFF) / 2^32`).
    pub ntp_timestamp: u64,
    /// Same instant expressed in the reference track's media timescale
    /// (decoding time). Promoted from u32 โ†’ u64 for the v0 layout so
    /// callers see one type regardless of box version.
    pub media_time: u64,
    /// Box version (0 โ†’ 32-bit `media_time`, 1 โ†’ 64-bit `media_time`).
    /// Surfaced so callers can validate against `media_time`'s
    /// representable range when round-tripping.
    pub version: u8,
    /// 24-bit FullBox `flags`. In the 2015 edition this is always `0`; the
    /// 2022 edition defines named bits that annotate what the NTP time
    /// represents (the body layout is unchanged either way). Preserved
    /// verbatim so a 2022-aware consumer can interpret it via
    /// [`PrftRecord::is_encoder_input_output`] / [`PrftRecord::is_finalization_time`]
    /// / [`PrftRecord::is_file_write_time`] / [`PrftRecord::is_arbitrary_association`]
    /// / [`PrftRecord::is_realtime_offset`]; a 2015-era consumer ignores it.
    pub flags: u32,
}

impl PrftRecord {
    /// `encoder_input_output` (`flags & 0x000001`, 2022 edition): the NTP
    /// time is the frame's encoder input/output time.
    pub fn is_encoder_input_output(&self) -> bool {
        self.flags & 0x00_0001 != 0
    }

    /// `finalization_time` (`flags & 0x000002`, 2022 edition): the NTP
    /// time is the finalization (segment-complete) time.
    pub fn is_finalization_time(&self) -> bool {
        self.flags & 0x00_0002 != 0
    }

    /// `file_write_time` (`flags & 0x000004`, 2022 edition): the NTP time
    /// is the file/segment write time.
    pub fn is_file_write_time(&self) -> bool {
        self.flags & 0x00_0004 != 0
    }

    /// `arbitrary_association` (`flags & 0x000008`, 2022 edition): an
    /// arbitrary association rather than the default "next moof".
    pub fn is_arbitrary_association(&self) -> bool {
        self.flags & 0x00_0008 != 0
    }

    /// `realtime_offset` (`flags & 0x000018`, 2022 edition): the combined
    /// value used for real-time-offset signalling. This is a combined
    /// mask, so all of its set bits must be present.
    pub fn is_realtime_offset(&self) -> bool {
        self.flags & 0x00_0018 == 0x00_0018
    }
}

/// Decoded `amve` (AmbientViewingEnvironmentBox, ISO/IEC 14496-12
/// post-2015 addition).
///
/// A plain `Box` (NOT a `FullBox` โ€” there is no `version` / `flags`
/// byte) carried inside a `VisualSampleEntry` (e.g. `avc1` / `hvc1` /
/// `av01`). It signals the nominal ambient viewing environment for the
/// display of the track's video โ€” the same three syntax elements, with
/// the same units and ranges, as the `ambient_viewing_environment` SEI
/// message and the ISO/IEC 23091-3 (CICP) ambient-viewing-environment
/// parameters. The body is a fixed 8 bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AmveRecord {
    /// Environmental illuminance of the ambient viewing environment, in
    /// units of 0.0001 lux (i.e. `lux = ambient_illuminance / 10000`).
    /// `0` is permitted by the syntax but generally treated as
    /// "unknown" / unspecified by consumers.
    pub ambient_illuminance: u32,
    /// Normalized CIE 1931 *x* chromaticity of the environmental ambient
    /// light, in increments of 0.00002 (`x = ambient_light_x ร— 0.00002`).
    /// The spec range is 0..=50000 (0.0 .. 1.0); the raw u16 is preserved
    /// verbatim so a producer slip out of range round-trips unchanged.
    pub ambient_light_x: u16,
    /// Normalized CIE 1931 *y* chromaticity of the environmental ambient
    /// light, in increments of 0.00002 (`y = ambient_light_y ร— 0.00002`).
    /// Range as for `ambient_light_x`.
    pub ambient_light_y: u16,
}

/// Decoded `btrt` (BitRateBox, ISO/IEC 14496-12 ยง8.5.2).
///
/// A plain `Box` (NOT a `FullBox` โ€” there is no `version` / `flags`
/// byte) that may appear, optionally, at the end of any `SampleEntry`
/// (video / audio / metadata / text). The body is a fixed 12 bytes of
/// three big-endian `u32`s: the decoding buffer size and the elementary
/// stream's maximum / average bit rate. It carries the same three
/// bandwidth quantities that the MPEG-4 `esds`
/// `DecoderConfigDescriptor` carries (`bufferSizeDB` / `maxBitrate` /
/// `avgBitrate`), but in a codec-agnostic box usable by sample entries
/// that do not carry an `esds` (e.g. `avc1` / `hvc1` / `av01` video,
/// `Opus` / `fLaC` audio).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BtrtRecord {
    /// Size of the decoding buffer for the elementary stream, in bytes
    /// (ยง8.5.2.3 `bufferSizeDB`).
    pub buffer_size_db: u32,
    /// Maximum rate, in bits/second, over any window of one second
    /// (ยง8.5.2.3 `maxBitrate`).
    pub max_bitrate: u32,
    /// Average rate, in bits/second, over the entire presentation
    /// (ยง8.5.2.3 `avgBitrate`).
    pub avg_bitrate: u32,
}

/// Decoded `pasp` (PixelAspectRatioBox, ISO/IEC 14496-12 ยง12.1.4). A
/// plain `Box` (no FullBox preamble) inside a `VisualSampleEntry`
/// declaring the relative width / height of a pixel โ€” the ratio a
/// renderer applies to obtain the display aspect.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaspRecord {
    /// `hSpacing` โ€” relative width of a pixel (ยง12.1.4.3).
    pub h_spacing: u32,
    /// `vSpacing` โ€” relative height of a pixel (ยง12.1.4.3). Same units
    /// as `h_spacing`.
    pub v_spacing: u32,
}

/// Decoded `clap` (CleanApertureBox, ISO/IEC 14496-12 ยง12.1.4). A plain
/// `Box` inside a `VisualSampleEntry` giving the clean-aperture
/// rectangle as four (numerator, denominator) fractions: the active
/// picture region after overscan / edge artefacts are cropped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClapRecord {
    /// `cleanApertureWidthN` / `cleanApertureWidthD` โ€” clean aperture
    /// width as a fraction in counted pixels (ยง12.1.4.3). `D` is positive.
    pub width_n: u32,
    pub width_d: u32,
    /// `cleanApertureHeightN` / `cleanApertureHeightD` โ€” clean aperture
    /// height fraction (ยง12.1.4.3). `D` is positive.
    pub height_n: u32,
    pub height_d: u32,
    /// `horizOffN` / `horizOffD` โ€” horizontal offset of the clean
    /// aperture centre minus `(width-1)/2`, as a fraction (typically 0).
    pub horiz_off_n: u32,
    pub horiz_off_d: u32,
    /// `vertOffN` / `vertOffD` โ€” vertical offset of the clean aperture
    /// centre minus `(height-1)/2`, as a fraction (typically 0).
    pub vert_off_n: u32,
    pub vert_off_d: u32,
}

/// Decoded `colr` (ColourInformationBox, ISO/IEC 14496-12 ยง12.1.5). A
/// plain `Box` inside a `VisualSampleEntry`. The first 32 bits are a
/// `colour_type`; the payload that follows depends on it. The three
/// base-spec types are modelled; an unknown type keeps the raw payload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ColrRecord {
    /// `nclx` (ยง12.1.5.2) โ€” on-screen colours: `colour_primaries`,
    /// `transfer_characteristics`, `matrix_coefficients` (each a
    /// 16-bit code from ISO/IEC 23091-2), plus a `full_range_flag`.
    Nclx {
        colour_primaries: u16,
        transfer_characteristics: u16,
        matrix_coefficients: u16,
        full_range: bool,
    },
    /// `rICC` (ยง12.1.5.2) โ€” a restricted ICC profile (Monochrome or
    /// Three-Component Matrix-Based input profile); raw profile bytes.
    RestrictedIcc(Vec<u8>),
    /// `prof` (ยง12.1.5.2) โ€” an unrestricted ICC profile; raw bytes.
    UnrestrictedIcc(Vec<u8>),
    /// Any other `colour_type`; the FourCC + the bytes that followed it.
    Other { colour_type: [u8; 4], data: Vec<u8> },
}

/// Decoded `stvi` (StereoVideoBox, ISO/IEC 14496-12 ยง8.15.4.2).
///
/// A `FullBox(version = 0, flags = 0)` that sits inside the
/// `schi` (SchemeInformationBox) of a sample entry's `sinf` when the
/// restricted-scheme SchemeType is `stvi` (stereoscopic video,
/// ยง8.15.4.1). It indicates that decoded frames carry either two
/// spatially packed constituent frames forming a stereo pair (frame
/// packing) or one of two views of a stereo pair (left / right in
/// different tracks).
///
/// The body is a packed `template int(30) reserved` plus `int(2)
/// single_view_allowed`, then `int(32) stereo_scheme`, `int(32) length`,
/// the `int(8)[length] stereo_indication_type` array, and optional
/// trailing boxes. The container preserves `single_view_allowed`,
/// `stereo_scheme`, and the raw `stereo_indication_type` bytes verbatim;
/// their detailed interpretation is `stereo_scheme`-specific (ยง8.15.4.2.3
/// routes to a table in ISO/IEC 14496-10 / 13818-2 / 23000-11) and is
/// left to a downstream consumer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StviRecord {
    /// `single_view_allowed` (ยง8.15.4.2.3), the low 2 bits after the
    /// 30-bit reserved field. `0` โ†’ content may only be displayed on a
    /// stereoscopic display; bit 0 (`& 1`) set โ†’ the right view may be
    /// shown on a monoscopic single-view display; bit 1 (`& 2`) set โ†’
    /// the left view may be shown on a monoscopic single-view display.
    pub single_view_allowed: u8,
    /// `stereo_scheme` (ยง8.15.4.2.3) โ€” the stereo arrangement scheme.
    /// `1` = the frame-packing-arrangement SEI scheme of ISO/IEC
    /// 14496-10; `2` = the Annex L arrangement-type scheme of ISO/IEC
    /// 13818-2; `3` = the ISO/IEC 23000-11 scheme. Other values are
    /// reserved; the raw integer is preserved verbatim.
    pub stereo_scheme: u32,
    /// The `stereo_indication_type` byte string (`length` bytes), whose
    /// syntax depends on `stereo_scheme` (ยง8.15.4.2.3). Preserved
    /// verbatim โ€” for scheme 1/2 it is a big-endian `u32`
    /// arrangement-type code, for scheme 3 it is two `u8`s
    /// (composition-type + `is_left_first` in the LSB of the second).
    pub stereo_indication_type: Vec<u8>,
}

impl StviRecord {
    /// `true` when the right view of the stereo pair may be displayed on
    /// a monoscopic single-view display (`single_view_allowed & 1`,
    /// ยง8.15.4.2.3).
    pub fn right_view_monoscopic_allowed(&self) -> bool {
        self.single_view_allowed & 1 != 0
    }

    /// `true` when the left view of the stereo pair may be displayed on
    /// a monoscopic single-view display (`single_view_allowed & 2`,
    /// ยง8.15.4.2.3).
    pub fn left_view_monoscopic_allowed(&self) -> bool {
        self.single_view_allowed & 2 != 0
    }
}

/// One `(rate, initial_delay)` pair from a `pdin`
/// ProgressiveDownloadInfoBox (ISO/IEC 14496-12 ยง8.1.3).
///
/// `rate` is an effective download rate in bytes per second; for that
/// rate, `initial_delay` (milliseconds) is the suggested initial
/// playback delay that lets the rest of the file arrive ahead of its
/// playback deadline (ยง8.1.3.3). A receiver picks two adjacent
/// entries whose rates bracket its observed throughput and linearly
/// interpolates the delay, or extrapolates from the first / last entry
/// when its observed rate sits outside the recorded range.
///
/// Both fields are `u32` on the wire (big-endian) and surfaced
/// verbatim โ€” neither is bounded by the spec other than its 32-bit
/// width, so the structure preserves whatever the producer wrote.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PdinEntry {
    /// Effective download rate in bytes / second.
    pub rate: u32,
    /// Suggested initial playback delay in milliseconds at `rate`.
    pub initial_delay: u32,
}

/// Decoded `pdin` (ProgressiveDownloadInfoBox, ISO/IEC 14496-12 ยง8.1.3).
///
/// `FullBox(version = 0, flags = 0)` whose body is `N` consecutive
/// `(rate, initial_delay)` u32 pairs โ€” `N = body_payload_size / 8`.
/// The spec fixes no minimum or maximum count; an empty body (zero
/// pairs) is permitted and yields an empty `entries` vec. The version
/// is pinned to 0 (ยง8.1.3.2); a non-zero version is tolerated rather
/// than rejected because the on-wire layout is unambiguous.
///
/// Quantity is zero or one per file (ยง8.1.3.1); the demuxer collects
/// the first instance and ignores any subsequent ones.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdinRecord {
    /// Pairs in file order, mirroring ยง8.1.3.2's loop ordering.
    /// A consumer searching by rate should sort if a non-monotonic
    /// producer is suspected โ€” the spec wording recommends interpolation
    /// but doesn't *mandate* monotonic ordering.
    pub entries: Vec<PdinEntry>,
}

/// Decoded QuickTime Preview Atom (`pnot`).
///
/// A top-level atom locating the movie's preview (poster) image โ€” a
/// representative frame suitable for display in an Open dialog. Body
/// layout (a plain `Box`, no FullBox preamble): `unsigned int(32)
/// modification_date` (a Macintosh-format date), `unsigned int(16)
/// version` (0), `unsigned int(32) atom_type` (the FourCC of the atom
/// holding the preview data, typically `PICT`), and `unsigned int(16)
/// atom_index` (which atom of that type to use, typically 1) โ€” twelve
/// bytes. All integers big-endian.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PnotRecord {
    /// The date the preview was last updated, in Macintosh format
    /// (seconds since 1904-01-01).
    pub modification_date: u32,
    /// The version number (must be 0).
    pub version: u16,
    /// The FourCC of the atom type that holds the preview data (typically
    /// `PICT` for a QuickDraw picture).
    pub atom_type: [u8; 4],
    /// Which atom of the specified type to use as the preview (typically
    /// 1 = the first).
    pub atom_index: u16,
}

/// Per-level descriptor carried by `leva` (LevelAssignmentBox, ISO/IEC
/// 14496-12 ยง8.8.13). One entry per `level_count` loop iteration in
/// ยง8.8.13.2 syntax.
///
/// On the wire each entry is:
/// `unsigned int(32) track_id; unsigned int(1) padding_flag;
/// unsigned int(7) assignment_type; <type-specific tail>`.
///
/// The trailing tail varies with `assignment_type`:
/// * 0 โ†’ `unsigned int(32) grouping_type`
/// * 1 โ†’ `unsigned int(32) grouping_type` + `unsigned int(32) grouping_type_parameter`
/// * 2 or 3 โ†’ empty (track / track-subsegment level assignment)
/// * 4 โ†’ `unsigned int(32) sub_track_id`
/// * other values are reserved (ยง8.8.13.3)
///
/// The ยง8.8.13.3 sequence rule constrains `assignment_type` ordering
/// across an entire `leva`: "zero or more of type 2 or 3, followed by
/// zero or more of exactly one type." The demuxer preserves the
/// producer's order verbatim and does not enforce the rule โ€” a downstream
/// consumer that cares about it can validate against
/// [`LevaEntry::assignment_type`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LevaEntry {
    /// `track_id` field per ยง8.8.13.3 โ€” identifies the track assigned
    /// to this level. Track 0 is not a legal value (the spec defines
    /// track IDs as โ‰ฅ 1 in ยง8.3.2.3); the demuxer carries whatever the
    /// producer wrote so a validator can flag it.
    pub track_id: u32,
    /// `padding_flag` (1-bit, ยง8.8.13.3): when `true`, a conforming
    /// fraction may be formed by concatenating any positive integer
    /// number of levels and padding the last `mdat` to its full header
    /// size with zero bytes. When `false`, this padding option is not
    /// assured by the producer.
    pub padding_flag: bool,
    /// `assignment_type` (7-bit) โ€” discriminator for the variant-specific
    /// tail; surfaced verbatim. Values 0..=4 are defined by the spec;
    /// any value > 4 falls in the ยง8.8.13.3 "reserved" range and the
    /// demuxer carries it without further parsing the tail.
    pub assignment_type: u8,
    /// `grouping_type` (set when `assignment_type` โˆˆ {0, 1}), otherwise 0.
    pub grouping_type: u32,
    /// `grouping_type_parameter` (set when `assignment_type == 1`),
    /// otherwise 0. ยง8.9.3 / ยง10.5 pin its semantics for the matching
    /// sample grouping.
    pub grouping_type_parameter: u32,
    /// `sub_track_id` (set when `assignment_type == 4`), otherwise 0.
    /// ยง8.14.4 identifies the sub-track that holds this level's samples.
    pub sub_track_id: u32,
}

/// Decoded `leva` (LevelAssignmentBox, ISO/IEC 14496-12 ยง8.8.13).
///
/// `FullBox(version = 0, flags = 0)` whose body opens with
/// `unsigned int(8) level_count` and is followed by `level_count`
/// per-level entries laid out per [`LevaEntry`]. The spec requires
/// `level_count โ‰ฅ 2` (ยง8.8.13.3 "level_count shall be greater than or
/// equal to 2"); the demuxer carries whatever the producer wrote and
/// surfaces the count via `entries.len()` so a validator can spot a
/// short table.
///
/// Quantity is zero or one per file (ยง8.8.13.1); the demuxer collects
/// the first instance seen inside `mvex` and ignores any subsequent
/// copies (a malformed file with two leva boxes is no reason to abort
/// the parse โ€” the first is the one the spec endorses).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LevaRecord {
    /// Entries in file order, mirroring ยง8.8.13.2's loop ordering.
    /// The ยง8.8.13.3 sequence rule on `assignment_type` ordering is
    /// not enforced here; a consumer can validate by walking the slice.
    pub entries: Vec<LevaEntry>,
}

/// One `(grouping_type_parameter, min_initial_alt_startup_offset)` entry
/// of a version-1 `assp` (Alternative Startup Sequence Properties Box,
/// ISO/IEC 14496-12 ยง8.8.16). A version-0 `assp` carries a single
/// implied entry with no `grouping_type_parameter`; see [`AsspRecord`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AsspEntry {
    /// ยง8.8.16.3 `grouping_type_parameter` โ€” selects which one of the
    /// alternative startup-sequence sample groupings this entry applies
    /// to (v1 only; `None` for the single implied v0 entry).
    pub grouping_type_parameter: Option<u32>,
    /// ยง8.8.16.3 `min_initial_alt_startup_offset` โ€” a signed lower bound
    /// on `sample_offset[1]` of the referred `alst` (ยง10.3.2) sample
    /// group description entries: no value shall be smaller than this.
    pub min_initial_alt_startup_offset: i32,
}

/// Decoded `assp` (Alternative Startup Sequence Properties Box, ISO/IEC
/// 14496-12 ยง8.8.16).
///
/// A `FullBox('assp', version, 0)` nested inside a `trep`
/// (TrackExtensionPropertiesBox, ยง8.8.15) that indicates the properties
/// of the alternative startup sequence (`alst`, ยง10.3.2) sample groups
/// in the subsequent track fragments of the `trep`'s track. ยง8.8.16.1
/// pins the version to track the `sbgp` version used for the `alst`
/// grouping: version 0 when the `alst` `sbgp` is v0 (one implied entry,
/// no `grouping_type_parameter`); version 1 when the `alst` `sbgp` is v1
/// (a `num_entries`-long list keyed by `grouping_type_parameter`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AsspRecord {
    /// FullBox `version` โ€” 0 (single implied entry) or 1 (keyed list).
    pub version: u8,
    /// The per-grouping entries. Version 0 yields exactly one entry with
    /// `grouping_type_parameter == None`; version 1 yields `num_entries`
    /// entries, each carrying its own `grouping_type_parameter`.
    pub entries: Vec<AsspEntry>,
}

/// One child box recorded inside a `trep` (TrackExtensionPropertiesBox,
/// ISO/IEC 14496-12 ยง8.8.15). The box body is "any number of boxes"
/// (ยง8.8.15.2) โ€” the demuxer records each child's type and payload
/// length, and additionally decodes the one child the base spec defines
/// here, `assp` (Alternative Startup Sequence Properties Box, ยง8.8.16),
/// into a typed [`AsspRecord`] (in [`TrepChild::assp`]). Any other child
/// stays opaque (type + length only) so a downstream consumer can still
/// spot it without this crate modelling every box that might be nested.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrepChild {
    /// The child box's four-character type code, verbatim on the wire.
    pub fourcc: [u8; 4],
    /// Length of the child's payload in bytes (the box size minus its
    /// header). A child whose declared size ran past the end of the
    /// `trep` body is clamped to the bytes actually available, so this
    /// reflects what was readable, not necessarily the producer's
    /// declared length.
    pub payload_len: usize,
    /// The typed `assp` record when this child is an `assp`
    /// (Alternative Startup Sequence Properties Box, ยง8.8.16) whose body
    /// parsed cleanly; `None` for any other child type or a malformed
    /// `assp` (a malformed `assp` still contributes its type + length so
    /// the child list stays faithful to the wire).
    pub assp: Option<AsspRecord>,
}

/// Decoded `trep` (TrackExtensionPropertiesBox, ISO/IEC 14496-12
/// ยง8.8.15).
///
/// `FullBox(version = 0, flags = 0)` whose body opens with
/// `unsigned int(32) track_id` (the track these extension properties
/// describe, ยง8.8.15.3) and is followed by "any number of boxes"
/// (ยง8.8.15.2). The trailing children are recorded by type + length
/// only โ€” see [`TrepChild`].
///
/// Quantity is "zero or more, zero or one per track" (ยง8.8.15.1); the
/// demuxer collects every `trep` it finds inside `mvex` in file order.
/// A `trep` with a malformed FullBox preamble or a truncated `track_id`
/// is dropped rather than aborting the parse, matching the treatment of
/// the sibling optional `mvex` boxes (`mehd`, `leva`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrepRecord {
    /// `track_id` (ยง8.8.15.3) โ€” the track for which these extension
    /// properties are provided. Carried verbatim; track 0 is not a
    /// legal value (ยง8.3.2.3 pins track IDs โ‰ฅ 1) but the demuxer does
    /// not reject it so a validator can flag it.
    pub track_id: u32,
    /// Child boxes nested in this `trep`, in file order. Each is
    /// recorded by type + payload length only ([`TrepChild`]); the
    /// list is empty for a `trep` that carries just its `track_id`.
    pub children: Vec<TrepChild>,
}

#[derive(Default)]
struct ParsedMoov {
    tracks: Vec<Track>,
    movie_timescale: u32,
    movie_duration: u64,
    /// ยง8.8.2 (`mehd` MovieExtendsHeaderBox) โ€” overall presentation
    /// duration of a fragmented movie, including fragments, in the
    /// movie timescale. `None` when the box is absent (per the spec
    /// it is optional). v0 widens to u64 on intake so the rest of the
    /// pipeline sees one type. When present and non-zero, takes
    /// precedence over `mvhd.duration` for the surfaced
    /// `Demuxer::duration_micros` value โ€” a sealed fragmented file
    /// typically has `mvhd.duration = 0` and the only authoritative
    /// total is the `mehd`.
    mehd_fragment_duration: Option<u64>,
    metadata: Vec<(String, String)>,
    /// ยง8.1 (ISO/IEC 23001-7) โ€” `pssh`
    /// ProtectionSystemSpecificHeaderBox entries collected at moov
    /// level. Each entry corresponds to one DRM system signalled in
    /// the file by SystemID UUID. moof-level `pssh` instances are
    /// also permitted by the spec but the surface here is moov-only;
    /// fragment-level pssh can be added without changing the demuxer
    /// API.
    psshes: Vec<PsshBox>,
    /// PIFF legacy `uuid` ProtectionSystemSpecificHeaderBox entries
    /// collected at moov level โ€” the pre-CENC predecessor of `pssh`,
    /// carried as a `uuid` box with
    /// [`crate::cenc::PIFF_PSSH_USERTYPE`]. Kept separate from
    /// `psshes` so a dual-branded file (one that carries both the
    /// `uuid` and the 4CC form for the same SystemID) doesn't
    /// double-report; the record shape is the shared [`PsshBox`]
    /// (the PIFF body is byte-identical to a v0 `pssh` payload).
    piff_psshes: Vec<PsshBox>,
    /// ยง8.8.13 โ€” `leva` LevelAssignmentBox. Optional FullBox inside
    /// `mvex` (quantity zero or one); maps tracks / sample groups /
    /// sub-tracks to "levels" inside subsequent movie fragments. `None`
    /// when the box is absent. Informational only โ€” the demuxer does
    /// not consume the levels itself, but downstream tooling (DASH
    /// subsegment selection, scalable-bitstream layer selection) can
    /// reach them through `Mp4Demuxer::leva_entries()` or the flat
    /// `leva_count` / `leva_<n>` metadata keys.
    leva: Option<LevaRecord>,
    /// ยง8.8.15 โ€” `trep` TrackExtensionPropertiesBox entries. Optional
    /// FullBoxes inside `mvex` (quantity zero or more, zero or one per
    /// track); each documents characteristics of one track in the
    /// subsequent movie fragments. Empty when the file carries none.
    /// Informational only โ€” the demuxer does not consume them, but
    /// downstream tooling can reach them through
    /// `Mp4Demuxer::treps()` or the flat `trep_<n>` metadata keys.
    treps: Vec<TrepRecord>,
}

/// Per-track info collected from moov.
#[derive(Clone, Debug)]
struct Track {
    /// `tkhd.track_ID` โ€” 1-based track identifier, used to match
    /// fragmented `tfhd.track_ID` to a parsed track.
    track_id: u32,
    /// Matroska-like id ("audio" / "video"); derived from handler.
    media_type: MediaType,
    codec_id_fourcc: [u8; 4],
    /// Per-track timescale (ticks per second).
    timescale: u32,
    duration: Option<u64>,
    // Audio
    channels: Option<u16>,
    sample_rate: Option<u32>,
    sample_size_bits: Option<u16>,
    // Video
    width: Option<u32>,
    height: Option<u32>,
    // Codec-specific setup payload, if any.
    extradata: Vec<u8>,
    /// MPEG-4 `objectTypeIndication` (OTI) from the esds box, if present.
    /// Used to refine `mp4a` / `mp4v` FourCCs into concrete codec ids.
    esds_oti: Option<u8>,
    // Sample tables.
    stts: Vec<(u32, u32)>, // (sample_count, sample_delta) โ€” in media timescale
    stsc: Vec<(u32, u32, u32)>, // (first_chunk, samples_per_chunk, sample_description_index)
    stsz: Vec<u32>,        // per-sample sizes (or `uniform`-derived vec of same size)
    chunk_offsets: Vec<u64>, // absolute file offsets (stco or co64)
    /// 1-based sample indices that are sync (key) frames. Empty means
    /// "all samples are sync frames" per ISO/IEC 14496-12.
    stss: Vec<u32>,
    /// ยง8.6.1.3 ctts (CompositionOffsetBox). Run-length pairs of
    /// `(sample_count, sample_offset)` mapping decoding-order index
    /// to a composition-time offset (CTS = DTS + offset). Version 0
    /// uses unsigned offsets, version 1 signed; we always store i32
    /// so callers can apply it uniformly. Empty when the box is
    /// absent (every sample's CTS equals its DTS โ€” no B-frames or
    /// the encoder didn't reorder).
    ctts: Vec<(u32, i32)>,
    /// ยง8.6.6 edts/elst โ€” full edit list. Each entry is
    /// `(segment_duration_movie_ts, media_time_track_ts, media_rate_q16)`.
    /// `media_time = -1` marks an empty edit (a "dwell" segment that
    /// pads the presentation timeline before any media is shown).
    /// `media_rate` is fixed-point 16.16 โ€” `0x0001_0000` is normal speed.
    ///
    /// `segment_duration` is in the *movie* timescale (per spec); we
    /// store it as recorded and convert at apply time.
    ///
    /// An empty vector means "no edit list" (no shift, identity
    /// presentation timeline).
    elst: Vec<ElstEntry>,
    /// The ยง8.6.6 presentation timeline precomputed from `elst` once
    /// the movie timescale is known (after the whole moov is parsed โ€”
    /// `mvhd` may follow the `trak` boxes). Identity when `elst` is
    /// empty.
    elst_timeline: ElstTimeline,
    /// `mvex/trex` per-track defaults populated from the moov; supply
    /// the fall-back per-sample size / duration / flags / sample
    /// description index when a fragment's `tfhd` / `trun` doesn't
    /// override them. Zero-initialised when the file has no `mvex`
    /// (i.e. is not fragmented).
    trex: TrexDefaults,
    /// Set when the track's sample entry was wrapped as `encv`/`enca`/
    /// `enct`/`encs` (ISO/IEC 14496-12 ยง8.12). The carried value is the
    /// `scheme_type` four-character code recovered from the inner
    /// `sinf/schm` box โ€” e.g. `cenc` / `cbc1` / `cens` / `cbcs` per
    /// ISO/IEC 23001-7. Callers should treat the per-sample payloads as
    /// encrypted (this crate does not decrypt). The original codec
    /// FourCC is recovered transparently via `sinf/frma` so
    /// `codec_id_fourcc` reflects the un-transformed sample entry and
    /// downstream decoders can be set up as if the track were plain โ€”
    /// they just won't get plaintext bytes until something else
    /// decrypts them.
    protection_scheme: Option<[u8; 4]>,
    /// ISO/IEC 23001-7 ยง8.2 โ€” `tenc` TrackEncryptionBox payload, when
    /// present. Lives inside `schi` inside `sinf` of an `enc*` sample
    /// entry. Carries the track-level defaults (KID, per-sample IV
    /// size, isProtected flag, plus v1 pattern-encryption block
    /// counts + constant IV) consumed by a downstream CENC decryptor.
    /// `None` when the track is unprotected or when the protected
    /// sample entry omits `tenc` (the spec marks it "Mandatory: No
    /// (Yes, for protected tracks)", so a missing tenc on an `enc*`
    /// entry is still parseable but the file is non-conforming).
    tenc: Option<TencBox>,
    /// PIFF legacy `uuid` TrackEncryptionBox payload, when present โ€”
    /// the pre-CENC predecessor of `tenc`, carried inside `sinf/schi`
    /// as a `uuid` box with [`crate::cenc::PIFF_TENC_USERTYPE`].
    /// Kept alongside (not merged into) `tenc` so a dual-branded file
    /// keeps both surfaces distinct; when only the PIFF form is
    /// present, the fragment walker recovers the per-sample IV width
    /// from `piff_tenc.iv_size` and [`PiffTencBox::to_tenc`] /
    /// [`PiffTencBox::scheme_decision`] bridge into the CENC
    /// decryption router.
    piff_tenc: Option<PiffTencBox>,
    /// ยง8.3.3 โ€” `tref` (TrackReferenceBox) entries. Each pair is
    /// `(reference_type, track_IDs)` where `reference_type` is the FourCC
    /// of an inner `TrackReferenceTypeBox` (e.g. `chap`, `subt`, `cdsc`,
    /// `hint`, `font`, `hind`, `vdep`, `vplx`) and `track_IDs` is the
    /// raw `unsigned int(32)` array packed in that inner box's body.
    /// Empty when the file has no `tref`. A given `reference_type` may
    /// appear at most once (per spec โ€” track-reference type boxes are
    /// keyed by their FourCC).
    tref: Vec<([u8; 4], Vec<u32>)>,
    /// ยง8.3.4 โ€” `trgr` (TrackGroupBox) child entries. Each pair is
    /// `(track_group_type, track_group_id)`: the `TrackGroupTypeBox`
    /// FourCC names the grouping (`msrc` is the spec-named example for
    /// multi-source presentations) and the 32-bit `track_group_id` is
    /// the in-file identifier โ€” two tracks sharing the same
    /// `(track_group_type, track_group_id)` pair belong to the same
    /// group. The outer `TrackGroupBox` itself is "Zero or one" per
    /// track but can hold an arbitrary list of typed child boxes; the
    /// spec does not forbid two children with the same
    /// `track_group_type` on the same track, so we preserve encounter
    /// order and surface each entry separately rather than
    /// de-duplicating by type. Track groups are **not** dependency
    /// relationships โ€” that role belongs to `tref` (ยง8.3.3).
    trgr: Vec<([u8; 4], u32)>,
    /// ยง8.4.6 โ€” `elng` (ExtendedLanguageBox). The NULL-terminated BCP 47
    /// (RFC 4646) language tag string (e.g. `en-US`, `fr-FR`, `zh-CN`).
    /// `None` when the track has no `elng` box, in which case callers
    /// should fall back to the packed 3-char language code in `mdhd`.
    /// The extended tag overrides the `mdhd` language when present
    /// (ยง8.4.6.1).
    elng: Option<String>,
    /// ยง8.10.4 โ€” `kind` (KindBox) entries from the track-level `udta`.
    /// Each pair is `(schemeURI, value)`: a NULL-terminated URI followed
    /// by a NULL-terminated value string. When `value` is empty, the URI
    /// itself defines the kind (e.g. `urn:apple:hap:closed-captions`);
    /// when a value is present, the URI identifies a naming scheme and
    /// `value` is the kind name from that scheme (e.g.
    /// `urn:mpeg:dash:role:2011`, `main`). Zero or more per track โ€”
    /// multiple `kind` boxes from different schemes can co-label the
    /// same track (spec example: two schemes both declaring "subtitles").
    kinds: Vec<(String, String)>,
    /// ยง8.10.2 โ€” `cprt` (CopyrightBox) entries from the track-level
    /// `udta`. Each record pairs a packed-3-letter ISO 639-2/T language
    /// code with the decoded notice string. Quantity "zero or more":
    /// a producer can attach one box per language for a multi-lingual
    /// per-track copyright. Distinct from the lumped 3GPP-style
    /// metadata in `Mp4Demuxer::metadata` because the typed shape
    /// preserves the language tag. Empty when the track has no `cprt`
    /// (the common case).
    copyrights: Vec<CopyrightRecord>,
    /// ยง8.10.3 โ€” `tsel` (TrackSelectionBox) from the track-level `udta`.
    /// The `switch_group` (signed; default 0) names a switching set
    /// within the alternate group declared on `tkhd` (ยง8.3.2): two
    /// tracks carrying the same non-zero `switch_group` are interchangeable
    /// at any point during playback (the consumer may switch between
    /// them on the fly, e.g. for bitrate adaptation). `attribute_list`
    /// is the list of FourCC tags drawn from ยง8.10.3.5's descriptive
    /// (`tesc`/`fgsc`/`cgsc`/`spsc`/`resc`/`vwsc`) and differentiating
    /// (`bitr` / `cdec` / `lang` / โ€ฆ) sets that characterise what the
    /// track offers. `None` when the track has no `tsel`.
    tsel: Option<TselBox>,
    /// ยง8.14.3 โ€” `strk` (Sub Track Box) entries from the track-level
    /// `udta`. Each defines a sub track (part of this track assigned to
    /// alternate / switch groups for layered-codec media selection): the
    /// `stri` (ยง8.14.4) selection metadata plus zero or more `strd/stsg`
    /// (ยง8.14.6) sample-group definitions. Quantity "zero or more"
    /// (ยง8.14.3.1); order matches the on-disk order. Empty when the
    /// track defines no sub tracks (the common case).
    sub_tracks: Vec<SubTrack>,
    /// ยง8.6.1.4 โ€” `cslg` (CompositionToDecodeBox). Present when signed
    /// composition offsets (a v1 `ctts`) are in use and the producer
    /// chose to document the compositionโ†”decode timeline relationship.
    /// `None` when the track has no `cslg` (the common case for files
    /// without B-frame reordering, or files that simply omit the box).
    cslg: Option<CslgBox>,
    /// ยง12.1.2 / ยง8.4.5 โ€” `vmhd` (VideoMediaHeaderBox). Present for
    /// video tracks (the spec marks it mandatory inside `minf` for
    /// video media). Carries the `graphicsmode` composition mode and
    /// `opcolor`. `None` for non-video tracks (which use `smhd` /
    /// `nmhd` / `sthd` instead) or when the box is absent.
    vmhd: Option<VmhdBox>,
    /// `amve` (AmbientViewingEnvironmentBox, ISO/IEC 14496-12 post-2015
    /// addition) found inside the track's `VisualSampleEntry`. Carries the
    /// nominal ambient viewing environment (illuminance + CIE 1931
    /// chromaticity) for the display of the video โ€” the file-format
    /// carriage of the `ambient_viewing_environment` SEI / ISO/IEC
    /// 23091-3 parameters. `None` for non-video tracks or when the box is
    /// absent (the common case). When two sample entries each carry an
    /// `amve`, the first encountered wins (a single nominal environment
    /// per track).
    amve: Option<AmveRecord>,
    /// ยง8.15.4.2 โ€” `stvi` (StereoVideoBox) found inside the track's
    /// sample-entry `sinf/schi` when the restricted-scheme SchemeType is
    /// `stvi` (stereoscopic video, ยง8.15.4.1). Carries
    /// `single_view_allowed`, `stereo_scheme`, and the raw
    /// `stereo_indication_type` bytes describing the stereo arrangement.
    /// `None` for non-stereo tracks (the common case) or when the box is
    /// absent / malformed. The first `stvi` encountered across the
    /// track's sample entries wins.
    stvi: Option<StviRecord>,
    /// ยง8.5.2 โ€” `btrt` (BitRateBox) found inside the track's active
    /// `SampleEntry` (`[0]`). Carries `bufferSizeDB` / `maxBitrate` /
    /// `avgBitrate`, the codec-agnostic bandwidth descriptor a player or
    /// ABR packager reads without an `esds`. `None` when the sample
    /// entry omits it (common). When several sample entries each carry a
    /// `btrt`, the first encountered (on the active entry) wins.
    btrt: Option<BtrtRecord>,
    /// ยง12.1.4 โ€” `pasp` (PixelAspectRatioBox) in the track's active
    /// `VisualSampleEntry`. `None` for non-video tracks or when absent
    /// (square pixels). First one encountered wins.
    pasp: Option<PaspRecord>,
    /// ยง12.1.4 โ€” `clap` (CleanApertureBox) in the active
    /// `VisualSampleEntry`. `None` when absent. First one wins.
    clap: Option<ClapRecord>,
    /// ยง12.1.5 โ€” `colr` (ColourInformationBox) in the active
    /// `VisualSampleEntry`. `None` when absent. The spec permits several
    /// `colr` boxes (most-accurate first); the first encountered wins.
    colr: Option<ColrRecord>,
    /// ยง12.4.2 / ยง8.4.5 โ€” `hmhd` (HintMediaHeaderBox). Present for hint
    /// tracks (a `hdlr` of type `hint`); the spec marks exactly one
    /// media header mandatory inside `minf`, and a hint track uses this
    /// one. Carries protocol-independent PDU-size + bitrate statistics.
    /// `None` for non-hint tracks (which use `vmhd` / `smhd` / `nmhd` /
    /// `sthd` instead) or when the box is absent.
    hmhd: Option<HmhdBox>,
    /// QuickTime Base Media Info Atom (`gmin`) found inside the track's
    /// `minf/gmhd` (base media information header) atom. QuickTime uses
    /// `gmhd` in place of `vmhd` / `smhd` for media types derived from the
    /// base media handler (text, timecode, music, generic/`gnrc`); its
    /// `gmin` child carries a `graphicsmode` composition mode, a
    /// three-component `opcolor`, and a `balance` (the stereo sound mix).
    /// `None` for tracks whose `minf` uses a typed media header instead, or
    /// when the atom is absent. The first parseable `gmin` seen wins.
    gmin: Option<GminBox>,
    /// QuickTime Timecode Media Information Atom (`tcmi`) found inside the
    /// track's `minf/gmhd` for a timecode track (media type `tmcd`). Carries
    /// the text-rendering parameters (font / face / size / text +
    /// background colour / font name) for the on-screen timecode. `None`
    /// for non-timecode tracks or when the atom is absent. The first
    /// parseable `tcmi` seen wins.
    tcmi: Option<TcmiBox>,
    /// QuickTime Timecode sample description (`tmcd` `stsd` entry) for a
    /// timecode track. Carries the `flags` (drop-frame / 24-hour / โ€ฆ),
    /// `timescale`, `frame_duration`, and `number_of_frames` that define
    /// how the track's timecode samples are interpreted. `None` for
    /// non-timecode tracks or when the entry cannot be parsed.
    tmcd: Option<TmcdSampleEntry>,
    /// QuickTime Text sample description (`text` `stsd` entry) for a
    /// QuickTime text track. Carries the display flags, justification,
    /// colours, default text box, font, and font name that define how the
    /// track's text samples are drawn. `None` for non-`text` entries or
    /// when the entry cannot be parsed (the raw post-preamble bytes remain
    /// available as `extradata`).
    text_entry: Option<TextSampleEntry>,
    /// QuickTime Track Load Settings Atom (`load`) found inside the track's
    /// `trak`. Carries the preload segment (start/duration), preload flags,
    /// and default playback hints. `None` when the atom is absent (the
    /// common case). The first parseable `load` seen wins.
    load_settings: Option<LoadSettingsBox>,
    /// ยง9.1.2 / ยง9.4.1.2 โ€” the RTP / SRTP / reception hint sample entry
    /// (`rtp ` / `srtp` / `rrtp`) from the track's active `stsd` entry,
    /// when present. Carries `maxpacketsize` plus the `tims` timescale and
    /// optional `tsro`/`snro` offsets (and an `srpp` SRTPProcessBox for
    /// `srtp`). `None` for non-hint tracks or a hint track whose entry
    /// format is some other protocol (e.g. an MPEG-2 TS hint).
    rtp_hint: Option<crate::hint::RtpHintSampleEntry>,
    /// ยง9.3.3.2 โ€” the MPEG-2 TS server / reception hint sample entry
    /// (`sm2t` / `rm2t`) from the track's active `stsd` entry, when
    /// present. Carries the per-TS-packet preceding/trailing byte counts
    /// and the precomputed-only flag. `None` for non-MPEG-2-TS-hint
    /// tracks.
    mpeg2ts_hint: Option<crate::hint::Mpeg2TsHintSampleEntry>,
    /// ยง9.1.5 โ€” the `hinf` Hint Statistics Box from the track's `udta`,
    /// when present. Summarises the packetised stream a server would
    /// generate (total bytes/packets sent, max-rate windows, payload
    /// rtpmap entries, โ€ฆ). Empty ([`crate::hint::HintStatistics::is_empty`])
    /// for non-hint tracks or a hint track that carried no statistics.
    hint_stats: crate::hint::HintStatistics,
    /// ยง8.7.2 โ€” `dref` (DataReferenceBox) from the track's
    /// `minf/dinf/dref`. The table of media-data locations that every
    /// sample entry's 1-based `data_reference_index` (ยง8.5.2.2) selects
    /// from: a self-contained entry (`flags & 1`) means the samples live
    /// in this same file, an external `url `/`urn ` entry names another
    /// resource. `None` when the track has no parseable `dref` (the box
    /// is mandatory inside `minf`, but a malformed one is tolerated). The
    /// common single-source case is exactly one self-contained `url `
    /// entry.
    dref: Option<DrefBox>,
    /// ยง8.6.3 โ€” `stsh` (ShadowSyncSampleBox) entries. Each pair is
    /// `(shadowed_sample_number, sync_sample_number)`, both 1-based
    /// sample indices: when seeking to (or before) the non-sync
    /// `shadowed_sample_number`, the named `sync_sample_number` may be
    /// decoded in its place to recover a usable starting point. The
    /// table is sorted by `shadowed_sample_number` per spec and is
    /// purely an optional seek optimisation โ€” it is ignored in normal
    /// forward play and a track decodes correctly without it. Empty
    /// when the box is absent (the common case).
    stsh: Vec<(u32, u32)>,
    /// ยง8.9.2 โ€” `sbgp` (SampleToGroupBox) instances. A track may carry
    /// several, one per `grouping_type`. Each entry records the grouping
    /// type, the optional v1 `grouping_type_parameter`, and the
    /// run-length `(sample_count, group_description_index)` table that
    /// maps decode-order sample runs to a sample-group description index.
    /// Empty when the track has no `sbgp` (the common case).
    sbgp: Vec<SbgpBox>,
    /// ยง8.9.3 โ€” `sgpd` (SampleGroupDescriptionBox) instances. One per
    /// `grouping_type`, each holding the per-group descriptive entries
    /// that an `sbgp` of the same type indexes. The entry payloads are
    /// grouping-type-specific blobs that the container surfaces verbatim
    /// (as hex) without interpreting them. Empty when the track has no
    /// `sgpd` (the common case).
    sgpd: Vec<SgpdBox>,
    /// ยง8.9.5 โ€” `csgp` (CompactSampleToGroupBox) instances. The compact
    /// alternative to `sbgp`: each records the grouping type, the
    /// optional `grouping_type_parameter`, and a small set of repeating
    /// index patterns replicated across the track. Empty when the track
    /// has no `csgp` (the common case โ€” `csgp` is a 2020+ addition).
    csgp: Vec<CsgpBox>,
    /// ยง8.6.4 โ€” `sdtp` (SampleDependencyTypeBox). Per-sample dependency
    /// hints in decode order: one entry per sample, four 2-bit fields
    /// `(is_leading, sample_depends_on, sample_is_depended_on,
    /// sample_has_redundancy)` packed into a single byte each on disk.
    /// Empty when the track has no `sdtp` (the common case); a present
    /// table whose length is shorter than the track's sample_count
    /// is preserved verbatim (truncation is the producer's bug, not
    /// ours to invent zeros for).
    sdtp: Vec<SdtpEntry>,
    /// ยง8.5.3 โ€” `stdp` (DegradationPriorityBox). Per-sample 16-bit
    /// `priority` values in decode order โ€” the `sample_count` is
    /// implicit from `stsz` / `stz2` (mirroring `sdtp`). The exact
    /// meaning and acceptable range of `priority` are defined by
    /// specifications derived from BMFF (ยง8.5.3.1), so the container
    /// preserves the raw u16s without interpreting them. Empty when
    /// the track has no `stdp` (the common case).
    stdp: Vec<u16>,
    /// ยง8.7.6 โ€” `padb` (PaddingBitsBox). Per-sample 3-bit
    /// `pad` counts in decode order, decoded from the packed
    /// `(reserved:1 + pad:3) ร— 2` per-byte nibble layout. The on-wire
    /// `sample_count` (declared inside the box, unlike `sdtp` / `stdp`)
    /// fixes the number of valid entries; the unused trailing nibble
    /// when `sample_count` is odd is dropped during parse. Empty when
    /// the track has no `padb` (the common case โ€” only bitstream codecs
    /// whose samples do not end on a byte boundary need this).
    padb: Vec<u8>,
    /// ยง8.7.7 โ€” `subs` (SubSampleInformationBox) instances. The spec
    /// allows more than one per container provided they differ in `flags`
    /// (the carried codec's semantics for `flags` distinguish them); we
    /// collect them in order of encounter. Empty when the track has no
    /// `subs` (the common case).
    subs: Vec<SubsBox>,
    /// ยง8.7.8 โ€” `saiz` (SampleAuxiliaryInformationSizesBox) instances
    /// found inside `stbl`. The spec allows multiple, keyed by
    /// `(aux_info_type, aux_info_type_parameter)`. Each `saiz` pairs
    /// with a `saio` of the matching key in `saio`. Empty when the
    /// track has no `saiz` in `stbl` (the common case for
    /// non-protected, non-fragmented content).
    saiz: Vec<SaizBox>,
    /// ยง8.7.9 โ€” `saio` (SampleAuxiliaryInformationOffsetsBox) instances
    /// found inside `stbl`. One per matching `saiz`; offsets are
    /// absolute file positions when read from `stbl`. Empty in the
    /// common case.
    saio: Vec<SaioBox>,
    /// ยง8.5.2 โ€” every `stsd` (SampleDescriptionBox) entry, in on-disk
    /// order. Entry `[0]` is the one used for active decode dispatch
    /// (its FourCC is mirrored to `codec_id_fourcc`); entries `[1..]`
    /// are additional sample descriptions the track may switch to via a
    /// per-chunk `stsc.sample_description_index` (โ‰ฅ 2) or, in fragments,
    /// a `tfhd` / `trex` `sample_description_index`. A track has more
    /// than one entry when the same media changes parameters mid-stream
    /// (e.g. a resolution / codec-config switch) without starting a new
    /// track. Each `StsdEntry` records the entry's FourCC plus the
    /// ยง8.5.2.2 `data_reference_index`. Never empty for a media track
    /// (a track always has at least one sample description); the vector
    /// is left empty only when the `stsd` was absent or `entry_count`
    /// was zero (both non-conforming).
    stsd_entries: Vec<StsdEntry>,
}

/// One `stsd` (SampleDescriptionBox, ยง8.5.2) entry header. Every
/// SampleEntry (ยง8.5.2.2) begins with the same 8-byte preamble โ€” 6
/// `reserved` bytes then the 16-bit `data_reference_index` โ€” regardless
/// of the concrete sample-entry class that follows. We capture that
/// common prefix plus the entry's FourCC; the codec-specific tail
/// (audio / video preamble + child config boxes) is parsed separately
/// for entry `[0]` via `parse_sample_entry`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct StsdEntry {
    /// The sample-entry FourCC (`box` type of the SampleEntry). For a
    /// protected entry this is the outer `enc*` placeholder, not the
    /// un-transformed format (ยง8.12); the active-entry unwrap only
    /// rewrites `codec_id_fourcc`, not this raw record.
    format: [u8; 4],
    /// ยง8.5.2.2 `data_reference_index` โ€” 1-based index into the track's
    /// `dref` table naming where the samples using this description are
    /// stored. Almost always `1` (samples in this same file).
    data_reference_index: u16,
}

/// One entry of an `sdtp` (SampleDependencyTypeBox, ยง8.6.4) โ€” decoded
/// from the on-wire `unsigned int(2) is_leading; unsigned int(2)
/// sample_depends_on; unsigned int(2) sample_is_depended_on;
/// unsigned int(2) sample_has_redundancy;` 8-bit packing.
///
/// Each field uses the spec's four-valued enum (0 = "unknown", a
/// reserved value 3 in some fields). We surface the raw small ints
/// rather than a typed enum to stay format-agnostic โ€” callers that
/// care about the named values consult ยง8.6.4.3 themselves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct SdtpEntry {
    /// 2 bits โ€” see ยง8.6.4.3. Values:
    /// `0` = leading nature unknown,
    /// `1` = leading with dependency before referenced I-picture (not
    /// decodable),
    /// `2` = not a leading sample,
    /// `3` = leading without dependency before referenced I-picture
    /// (decodable).
    is_leading: u8,
    /// 2 bits โ€” see ยง8.6.4.3. Values:
    /// `0` = dependency unknown,
    /// `1` = depends on others (not an I-picture),
    /// `2` = does not depend on others (I-picture),
    /// `3` = reserved.
    sample_depends_on: u8,
    /// 2 bits โ€” see ยง8.6.4.3. Values:
    /// `0` = whether others depend on this sample is unknown,
    /// `1` = other samples may depend on this one (not disposable),
    /// `2` = no other sample depends on this one (disposable),
    /// `3` = reserved.
    sample_is_depended_on: u8,
    /// 2 bits โ€” see ยง8.6.4.3. Values:
    /// `0` = unknown whether there is redundant coding,
    /// `1` = there is redundant coding,
    /// `2` = there is no redundant coding,
    /// `3` = reserved.
    sample_has_redundancy: u8,
}

/// Parsed `sbgp` (SampleToGroupBox, ISO/IEC 14496-12 ยง8.9.2).
#[derive(Clone, Debug, Default)]
pub struct SbgpBox {
    /// Four-byte grouping type identifying which `sgpd` (same type) this
    /// box indexes โ€” e.g. `rap `, `roll`, `sync`, `tele`, `alst`.
    pub grouping_type: [u8; 4],
    /// `grouping_type_parameter` โ€” present only in version 1, selecting
    /// one of several alternative groupings of the same type. `None` for
    /// version 0.
    pub grouping_type_parameter: Option<u32>,
    /// Run-length `(sample_count, group_description_index)` pairs. A
    /// `group_description_index` of 0 means "member of no group of this
    /// type"; an index โ‰ฅ 0x10001 (movie-fragment-local) is preserved
    /// verbatim โ€” the demuxer does not resolve fragment-local groups.
    pub entries: Vec<(u32, u32)>,
}

/// Parsed `sgpd` (SampleGroupDescriptionBox, ISO/IEC 14496-12 ยง8.9.3).
#[derive(Clone, Debug, Default)]
pub struct SgpdBox {
    /// Four-byte grouping type linking this description table to the
    /// `sbgp` of the same type.
    pub grouping_type: [u8; 4],
    /// `default_sample_description_index` (version โ‰ฅ 2): the group entry
    /// applied to samples not mapped by any `sbgp`. 0 (the default)
    /// means "no group of this type"; absent in versions 0/1.
    pub default_sample_description_index: Option<u32>,
    /// Per-group descriptive entries, each a grouping-type-specific
    /// opaque payload preserved verbatim. The container does not
    /// interpret them โ€” interpretation belongs to the layer that knows
    /// the `grouping_type` semantics.
    pub entries: Vec<Vec<u8>>,
}

/// One pattern of a `csgp` (CompactSampleToGroupBox, ยง8.9.5): a run of
/// `pattern_length` per-sample `sample_group_description_index` values,
/// replicated across `sample_count` consecutive groups of that length.
#[derive(Clone, Debug, Default)]
pub struct CsgpPattern {
    /// `sample_count[i]` โ€” number of consecutive groups (each
    /// `pattern_length` samples long) that replay this pattern. The
    /// pattern covers `sample_count * pattern_length` samples in total.
    pub sample_count: u32,
    /// `sample_group_description_index[i][1..=pattern_length]` โ€” one
    /// index per sample of the pattern. Index 0 means "member of no
    /// group of this type"; when the box lives in a `traf`, the index's
    /// most-significant bit (for the field's width) distinguishes a
    /// fragment-local description (set) from a global one (clear). The
    /// raw value is preserved verbatim; the demuxer does not resolve it.
    pub indices: Vec<u32>,
}

/// Parsed `csgp` (CompactSampleToGroupBox, ISO/IEC 14496-12:2020 ยง8.9.5).
#[derive(Clone, Debug, Default)]
pub struct CsgpBox {
    /// Four-byte grouping type linking this box to the `sgpd` of the
    /// same type โ€” identical role to `sbgp.grouping_type`.
    pub grouping_type: [u8; 4],
    /// `grouping_type_parameter` โ€” present only when the flag layout's
    /// presence bit is set, selecting one of several alternative
    /// groupings of the same type. `None` when the bit is clear.
    pub grouping_type_parameter: Option<u32>,
    /// `index_msb_indicates_fragment_local_description` โ€” flag layout
    /// **bit 7** (`flags & 0x80`). When set (legal only inside a `traf`),
    /// the most-significant bit of each `sample_group_description_index`,
    /// at the field's [`index_field_bits`] width, is a *source selector*
    /// rather than part of the index value: MSB = 0 โ†’ the index refers to
    /// the `trak`/`moov`-level `sgpd` (global); MSB = 1 โ†’ it refers to the
    /// fragment-local `sgpd` inside the enclosing `traf`. When clear, the
    /// index is a plain `sgpd` index with no MSB special-casing. The
    /// indices in [`CsgpPattern::indices`] are always preserved verbatim;
    /// use [`CsgpPattern::resolve_index`] to split a stored index into its
    /// (fragment-local, value) parts according to this flag and width.
    pub index_msb_indicates_fragment_local_description: bool,
    /// Bit width (`4`, `8`, `16`, or `32`) of each
    /// `sample_group_description_index` field on disk โ€” `4 << index_size_code`
    /// where `index_size_code = flags & 0x3`. The MSB convention of
    /// [`index_msb_indicates_fragment_local_description`] locates the
    /// source-selector bit at position `index_field_bits - 1`, so a
    /// resolver needs this to mask it correctly.
    pub index_field_bits: u8,
    /// The repeating index patterns, in disk order.
    pub patterns: Vec<CsgpPattern>,
}

/// One resolved `sample_group_description_index` from a `csgp` whose
/// [`CsgpBox::index_msb_indicates_fragment_local_description`] flag is
/// set: the source-selector MSB has been split off from the index value.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CsgpResolvedIndex {
    /// `true` when the field's MSB was set: the index refers to a
    /// description in the **fragment-local** `sgpd` (inside the enclosing
    /// `traf`). `false` โ†’ the **global** (`trak`/`moov`-level) `sgpd`.
    /// Always `false` when the box's flag is clear.
    pub fragment_local: bool,
    /// The group-description index with the source-selector MSB stripped
    /// (1-based into the chosen `sgpd`; `0` means "member of no group").
    /// When the box's flag is clear this is the verbatim stored value.
    pub value: u32,
}

impl CsgpPattern {
    /// Resolve the `n`-th stored index of this pattern against the box's
    /// MSB convention.
    ///
    /// When `index_msb_indicates_fragment_local_description` is set (only
    /// legal inside a `traf`), the most-significant bit of the field โ€” at
    /// `index_field_bits` width โ€” selects the `sgpd` source and is
    /// stripped from the value (ISO/IEC 14496-12:2020 ยง8.9.5). When it is
    /// clear, the index is returned verbatim with `fragment_local =
    /// false`. Returns `None` if `n` is out of range.
    pub fn resolve_index(
        &self,
        n: usize,
        index_msb_indicates_fragment_local_description: bool,
        index_field_bits: u8,
    ) -> Option<CsgpResolvedIndex> {
        let raw = *self.indices.get(n)?;
        Some(resolve_csgp_index(
            raw,
            index_msb_indicates_fragment_local_description,
            index_field_bits,
        ))
    }
}

/// Split a raw `csgp` index into its (fragment-local, value) parts.
///
/// Shared by [`CsgpPattern::resolve_index`]. With the MSB convention
/// active, the selector bit sits at `index_field_bits - 1`; it is read
/// and masked off. A `index_field_bits` of 0 (degenerate) is treated as
/// "no MSB", returning the value verbatim.
fn resolve_csgp_index(
    raw: u32,
    msb_is_fragment_local: bool,
    index_field_bits: u8,
) -> CsgpResolvedIndex {
    if !msb_is_fragment_local || index_field_bits == 0 || index_field_bits > 32 {
        return CsgpResolvedIndex {
            fragment_local: false,
            value: raw,
        };
    }
    let msb_pos = index_field_bits - 1;
    let msb_mask = 1u32 << msb_pos;
    CsgpResolvedIndex {
        fragment_local: raw & msb_mask != 0,
        value: raw & (msb_mask - 1),
    }
}

impl CsgpBox {
    /// Expand the compact patterns into one resolved
    /// `sample_group_description_index` per sample, in decoding order
    /// (ISO/IEC 14496-12:2020 ยง8.9.5, "Pattern โ†’ sample mapping").
    ///
    /// `csgp` stores a small set of index *patterns* that are each cycled
    /// across a run of samples; this method materialises the per-sample
    /// mapping the same way `sbgp` already gives it, so a caller need not
    /// re-derive the cycling rules:
    ///
    /// * Pattern `i` (with `pattern_length = indices.len()`) applies to its
    ///   `sample_count[i]` samples. When `sample_count[i] > pattern_length`
    ///   the index entries are **cycled** to cover all the samples; the
    ///   cycle may end part-way through a pattern (no requirement that it
    ///   divides evenly). When `sample_count[i] == pattern_length` the
    ///   pattern is used once, un-repeated.
    /// * A pattern with an empty index run (`pattern_length == 0`) cannot
    ///   be cycled, so it contributes nothing and its `sample_count` is
    ///   skipped (a malformed-but-bounded input rather than a hard error).
    /// * If the sum of `sample_count[i]` is **less than** `total_samples`,
    ///   the trailing unmapped samples take the `sgpd` default group, which
    ///   this method surfaces as a resolved index with `value == 0`
    ///   (`fragment_local == false`) โ€” "member of no group of this type",
    ///   exactly the same sentinel an explicit `0` index carries. The
    ///   caller substitutes the `sgpd` `default_group_description_index`
    ///   (if any) for those zeros, identically to the `sbgp` default rule.
    /// * If the sum **exceeds** `total_samples` the reader behaviour is
    ///   undefined per the spec; we clamp to `total_samples` so the output
    ///   never exceeds the track's real sample count.
    ///
    /// Each emitted index is run through the box's MSB convention via
    /// [`resolve_csgp_index`], so fragment-local vs global selection is
    /// already split out (see
    /// [`CsgpBox::index_msb_indicates_fragment_local_description`]).
    pub fn resolve_samples(&self, total_samples: usize) -> Vec<CsgpResolvedIndex> {
        let mut out: Vec<CsgpResolvedIndex> = Vec::with_capacity(total_samples);
        'patterns: for pat in &self.patterns {
            let plen = pat.indices.len();
            if plen == 0 {
                // No index entries to cycle โ€” this pattern maps nothing.
                continue;
            }
            for s in 0..pat.sample_count as usize {
                if out.len() >= total_samples {
                    break 'patterns;
                }
                let raw = pat.indices[s % plen];
                out.push(resolve_csgp_index(
                    raw,
                    self.index_msb_indicates_fragment_local_description,
                    self.index_field_bits,
                ));
            }
        }
        // Trailing samples not covered by any pattern take the sgpd default
        // (surfaced as value 0 = "no group"); pad up to total_samples.
        while out.len() < total_samples {
            out.push(CsgpResolvedIndex {
                fragment_local: false,
                value: 0,
            });
        }
        out
    }
}

/// One sub-sample of a `subs` (SubSampleInformationBox, ยง8.7.7) entry.
///
/// Fields decoded from the on-wire `unsigned int(16 or 32) subsample_size;
/// unsigned int(8) subsample_priority; unsigned int(8) discardable;
/// unsigned int(32) codec_specific_parameters;` layout. The
/// `subsample_size` field is 16-bit at version 0 and widens to 32-bit at
/// version 1; we always store as `u32` so callers handle one shape.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SubSampleEntry {
    /// ยง8.7.7.3 โ€” size in bytes of the sub-sample.
    pub subsample_size: u32,
    /// ยง8.7.7.3 โ€” degradation priority. Higher = more important to
    /// decoded quality. Codec-specific scale; the container does not
    /// interpret it.
    pub subsample_priority: u8,
    /// ยง8.7.7.3 โ€” `0` = required to decode the current sample; non-zero
    /// = optional (e.g. an SEI message that only enhances output).
    pub discardable: u8,
    /// ยง8.7.7.3 โ€” opaque codec-specific blob (4 bytes). For AVC
    /// (ISO/IEC 14496-15) this encodes NAL-unit role / dependency
    /// information; absent a codec-specific binding the field is `0`.
    pub codec_specific_parameters: u32,
}

/// One entry of a `subs` (SubSampleInformationBox, ยง8.7.7) โ€” a single
/// sample's sub-sample table together with the sparse delta that
/// addresses it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SubsEntry {
    /// ยง8.7.7.3 โ€” sample-number delta from the previous entry's sample
    /// (or from sample 0 for the first entry). The decoded absolute
    /// sample numbers are *not* materialised โ€” callers walking the table
    /// can accumulate them themselves.
    pub sample_delta: u32,
    /// The sub-samples of this entry's sample, in disk order. May be
    /// empty (`subsample_count == 0`) per ยง8.7.7.1 โ€” in that case the
    /// addressed sample has no sub-sample structure but is still
    /// enumerated by the table (the spec permits this shape so a
    /// producer can document "this sample is monolithic" alongside
    /// genuinely sub-divided neighbours).
    pub subsamples: Vec<SubSampleEntry>,
}

/// Parsed `subs` (SubSampleInformationBox, ISO/IEC 14496-12 ยง8.7.7).
///
/// The box has been a `FullBox(version, flags)` since the original 2003
/// edition. `version` selects the on-wire width of `subsample_size`
/// (16-bit at v0, 32-bit at v1); `flags` is owned by the carried codec
/// โ€” when more than one `subs` is present in the same container, the
/// spec mandates that each carry a distinct `flags` value (ยง8.7.7.1).
/// We preserve both as-recorded so codec-specific consumers can pick
/// the table whose semantics they understand.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SubsBox {
    /// FullBox version (0 or 1) โ€” determines `subsample_size` width on
    /// disk. We normalise to `u32` in `SubSampleEntry::subsample_size`.
    pub version: u8,
    /// FullBox flags โ€” codec-specific. Distinguishes co-resident `subs`
    /// boxes per ยง8.7.7.1.
    pub flags: u32,
    /// One entry per *addressed* sample (the table is sparse โ€” samples
    /// with no `subs` row contribute nothing here).
    pub entries: Vec<SubsEntry>,
}

/// Parsed `saiz` (SampleAuxiliaryInformationSizesBox, ISO/IEC 14496-12
/// ยง8.7.8).
///
/// The `aux_info_type` / `aux_info_type_parameter` pair is the lookup
/// key that pairs a `saiz` with its matching `saio` of the same key
/// (ยง8.7.8.1: "there must be a matching SampleAuxiliaryInformationOffsetsBox
/// with the same values of aux_info_type and aux_info_type_parameter").
/// Both fields are present on disk only when `flags & 1` is set; when
/// absent the implied value of `aux_info_type` is (a) the protection
/// scheme type for protected content (transformed sample entries) or
/// (b) the sample entry FourCC otherwise (ยง8.7.8.3 โ€” that fallback is
/// not materialised here; we surface `None`/`None` so callers can
/// apply the rule themselves with the surrounding sinf/sample-entry
/// context).
///
/// `default_sample_info_size` is the constant-size shortcut: when
/// non-zero, every sample in the table has that size and `per_sample`
/// is empty. When zero, `per_sample[i]` holds the size for the i-th
/// sample. `sample_count` is stored so an over-long table (the spec
/// permits `sample_count` < total stsz/stz2 count โ€” auxiliary info
/// supplied for the initial samples only) is preserved verbatim.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SaizBox {
    /// ยง8.7.8.3 `aux_info_type` โ€” present only when `flags & 1` is set.
    pub aux_info_type: Option<[u8; 4]>,
    /// ยง8.7.8.3 `aux_info_type_parameter` โ€” present only when
    /// `flags & 1` is set; defaults to 0 when omitted.
    pub aux_info_type_parameter: Option<u32>,
    /// ยง8.7.8.3 `default_sample_info_size`; non-zero means a
    /// constant-size table and `per_sample` is empty.
    pub default_sample_info_size: u8,
    /// ยง8.7.8.3 `sample_count` โ€” the declared number of samples this
    /// `saiz` covers (may be smaller than the track's full sample count
    /// per ยง8.7.8.3).
    pub sample_count: u32,
    /// ยง8.7.8.2 `sample_info_size[]` โ€” populated only when
    /// `default_sample_info_size == 0`; otherwise empty.
    pub per_sample: Vec<u8>,
}

/// Parsed `saio` (SampleAuxiliaryInformationOffsetsBox, ISO/IEC 14496-12
/// ยง8.7.9).
///
/// Same key shape as `SaizBox`: `(aux_info_type,
/// aux_info_type_parameter)` selects which auxiliary-information stream
/// these offsets belong to. The table itself is `entry_count` chunk
/// (or fragment-run) offsets; per ยง8.7.9.3 the count must be 1 (a
/// single contiguous chunk) or equal to the count of chunks (in `stbl`)
/// / `trun`s (in `traf`). When the box appears inside `stbl` the
/// offsets are absolute file positions; in `traf` they are relative to
/// the base_data_offset established by the surrounding `tfhd` (or to
/// the `moof` start when `default-base-is-moof` is set, per ยง8.8.14).
///
/// Both v0 (32-bit offsets) and v1 (64-bit offsets) are read and
/// widened to `u64` so callers handle one shape. `version` is preserved
/// so a producer round-tripping back to disk can re-emit the same
/// width.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SaioBox {
    /// FullBox version (0 or 1) โ€” selects 32-bit / 64-bit on-disk
    /// offset width. Preserved so a round-trip can match the original
    /// layout.
    pub version: u8,
    /// ยง8.7.9.3 `aux_info_type` โ€” present only when `flags & 1` is set.
    pub aux_info_type: Option<[u8; 4]>,
    /// ยง8.7.9.3 `aux_info_type_parameter` โ€” present only when
    /// `flags & 1` is set; defaults to 0 when omitted.
    pub aux_info_type_parameter: Option<u32>,
    /// ยง8.7.9.2 `offset[entry_count]` โ€” widened to u64 regardless of
    /// box version. Semantics depend on container: absolute file
    /// position inside `stbl`, base_data_offset-relative inside `traf`.
    pub offsets: Vec<u64>,
}

/// Parsed `cslg` (CompositionToDecodeBox, ISO/IEC 14496-12 ยง8.6.1.4).
///
/// All five fields are signed; version 0 stores them as 32-bit, version
/// 1 as 64-bit. We widen v0 to `i64` on read so callers handle one
/// shape. The values are in the track media timescale.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct CslgBox {
    /// Add this to every computed CTS to guarantee CTS โ‰ฅ DTS for all
    /// samples (honouring the profile/level buffer model). When
    /// `leastDecodeToDisplayDelta` is โ‰ฅ 0 this may be 0; otherwise it
    /// should be at least `-leastDecodeToDisplayDelta`.
    composition_to_dts_shift: i64,
    /// The smallest composition offset in the track's `ctts`.
    least_decode_to_display_delta: i64,
    /// The largest composition offset in the track's `ctts`.
    greatest_decode_to_display_delta: i64,
    /// The smallest computed CTS for any sample in this track's media.
    composition_start_time: i64,
    /// The CTS-plus-duration of the sample with the largest computed
    /// CTS; `0` means "composition end time unknown" (ยง8.6.1.4.3).
    composition_end_time: i64,
}

/// Parsed `vmhd` (VideoMediaHeaderBox, ISO/IEC 14496-12 ยง12.1.2,
/// defined per ยง8.4.5).
///
/// The media-type-specific header carried inside `minf` for a video
/// track. Its body, after the 4-byte `FullBox(version=0, flags=1)`
/// preamble, is a 16-bit `graphicsmode` and a `[u16; 3]` `opcolor`.
/// `graphicsmode == 0` is `copy` (copy over the existing image);
/// derived specifications may extend the set. `opcolor` is the
/// (red, green, blue) colour available to graphics modes that use one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct VmhdBox {
    /// The composition mode for the video track. `0` is `copy`
    /// (ยง12.1.2.3); other values are defined by derived specifications.
    graphicsmode: u16,
    /// The three (red, green, blue) colour components available for use
    /// by graphics modes that consume an operation colour.
    opcolor: [u16; 3],
}

/// Parsed `hmhd` (HintMediaHeaderBox, ISO/IEC 14496-12 ยง12.4.2,
/// defined per ยง8.4.5).
///
/// The media-type-specific header carried inside `minf` for a hint
/// track (a `hdlr` of type `hint`). Its body, after the 4-byte
/// `FullBox(version=0, 0)` preamble, is two 16-bit Protocol Data Unit
/// (PDU) byte sizes and two 32-bit bitrates, followed by a reserved
/// 32-bit zero (ยง12.4.2.2). The statistics are protocol-independent
/// (ยง12.4.2.1) โ€” they summarise the packetised stream a hint track
/// describes so a streaming server can size buffers / pace delivery
/// without parsing every hint sample.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct HmhdBox {
    /// Size in bytes of the largest PDU in this hint stream (ยง12.4.2.3).
    max_pdu_size: u16,
    /// Average size of a PDU over the entire presentation (ยง12.4.2.3).
    avg_pdu_size: u16,
    /// Maximum rate in bits/second over any window of one second
    /// (ยง12.4.2.3).
    max_bitrate: u32,
    /// Average rate in bits/second over the entire presentation
    /// (ยง12.4.2.3).
    avg_bitrate: u32,
}

/// Decoded QuickTime Base Media Info Atom (`gmin`).
///
/// QuickTime carries a **Base Media Information Header Atom** (`gmhd`)
/// inside `minf` for media types derived from the base media handler
/// (text, timecode, music, and generic tracks) โ€” the role that `vmhd`
/// fills for video and `smhd` for sound. The `gmhd`'s required child is
/// the **Base Media Info Atom** (`gmin`), whose fixed-size body defines
/// the media's control information: graphics mode, operation colour, and
/// stereo sound balance.
///
/// Body layout after the 4-byte `FullBox(version, flags)` preamble:
/// `unsigned int(16) graphicsmode`, `unsigned int(16)[3] opcolor`,
/// `int(16) balance`, and a reserved `unsigned int(16)` โ€” twelve payload
/// bytes after the preamble, sixteen total. All integers big-endian.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct GminBox {
    /// The transfer (composition) mode for the base media, selecting the
    /// operation performed when drawing or transferring an image from one
    /// location to another. `0` is `copy`.
    pub graphicsmode: u16,
    /// The three (red, green, blue) 16-bit colour components for the
    /// transfer-mode operation indicated by `graphicsmode`.
    pub opcolor: [u16; 3],
    /// The sound balance: the mix of this media's sound between the two
    /// speakers. Normally `0` (centered); negative favours the left
    /// speaker, positive the right (an 8.8 fixed-point value).
    pub balance: i16,
}

/// Decoded QuickTime Timecode Media Information Atom (`tcmi`).
///
/// A timecode track (media type `tmcd`) carries a `tcmi` atom inside its
/// `gmhd` (base media information header). It governs how the timecode
/// text is rendered on screen: the font, style, size, and the text and
/// background colours.
///
/// Body layout after the 4-byte `FullBox(version, flags)` preamble:
/// `unsigned int(16) text_font`, `unsigned int(16) text_face`,
/// `unsigned int(16) text_size`, a 48-bit (`[u16; 3]`) `text_color`, a
/// 48-bit `background_color`, and a Pascal-string `font_name` (a leading
/// length byte followed by that many characters). All integers
/// big-endian.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TcmiBox {
    /// The font id to use for the timecode text. `0` selects the system
    /// font; when `font_name` is a valid name this field is ignored.
    pub text_font: u16,
    /// The font style (face). `0` is normal; the low bits enable Bold
    /// (`0x01`), Italic (`0x02`), Underline (`0x04`), Outline (`0x08`),
    /// Shadow (`0x10`), Condense (`0x20`), and Extend (`0x40`).
    pub text_face: u16,
    /// The point size of the timecode text.
    pub text_size: u16,
    /// The 48-bit RGB colour of the timecode text (red, green, blue).
    pub text_color: [u16; 3],
    /// The 48-bit RGB background colour behind the timecode text.
    pub background_color: [u16; 3],
    /// The name of the timecode text's font (the Pascal string, without
    /// its leading length byte). Empty when the atom carries no name.
    pub font_name: String,
}

/// Decoded QuickTime Timecode sample description (`tmcd` `stsd` entry).
///
/// A timecode track (media type `tmcd`) carries a single `tmcd` sample
/// entry that defines how the track's timecode sample data is
/// interpreted. Body layout after the shared 8-byte sample-entry preamble
/// (`reserved[6]` + `data_reference_index`): `unsigned int(32) reserved`,
/// `unsigned int(32) flags`, `unsigned int(32) timescale`,
/// `unsigned int(32) frame_duration`, `unsigned int(8) number_of_frames`,
/// and a reserved `unsigned int(8)` (the qtff shows the trailing reserved
/// as 24 bits alongside an optional source-reference `udta`; this record
/// captures the fixed numeric fields). All integers big-endian.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TmcdSampleEntry {
    /// Timecode characteristics: Drop-frame (`0x0001`), 24-hour-max
    /// (`0x0002`), Negative-times-OK (`0x0004`), and Counter (`0x0008`).
    pub flags: u32,
    /// The time scale for interpreting `frame_duration` (units per
    /// second).
    pub timescale: u32,
    /// How long each timecode frame lasts, in `timescale` units.
    pub frame_duration: u32,
    /// The number of frames per second for the timecode format. When the
    /// Counter flag is set, the number of frames per counter tick.
    pub number_of_frames: u8,
}

impl TmcdSampleEntry {
    /// Whether the timecode is drop-frame (`flags & 0x0001`).
    pub fn drop_frame(&self) -> bool {
        self.flags & 0x0001 != 0
    }
    /// Whether the timecode wraps after 24 hours (`flags & 0x0002`).
    pub fn twenty_four_hour_max(&self) -> bool {
        self.flags & 0x0002 != 0
    }
    /// Whether negative time values are allowed (`flags & 0x0004`).
    pub fn negative_times_ok(&self) -> bool {
        self.flags & 0x0004 != 0
    }
    /// Whether the time value is a tape counter value (`flags & 0x0008`).
    pub fn counter(&self) -> bool {
        self.flags & 0x0008 != 0
    }
}

/// Decoded QuickTime Text sample description (`text` `stsd` entry).
///
/// A QuickTime text track (media type `text`) carries a `text` sample
/// entry that defines how the track's text samples are drawn. Body layout
/// after the shared 8-byte sample-entry preamble: `unsigned int(32)
/// display_flags`, `int(32) text_justification`, a 48-bit (`[u16; 3]`)
/// `background_color`, a 64-bit `default_text_box` (`[i16; 4]` = top,
/// left, bottom, right), a reserved `int(64)`, `unsigned int(16)
/// font_number`, `unsigned int(16) font_face`, a reserved `int(8)`, a
/// reserved `int(16)`, a 48-bit `foreground_color`, and a Pascal-string
/// `text_name` (the font name). All integers big-endian.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TextSampleEntry {
    /// Flags describing how the text is drawn (Don't-auto-scale `0x0002`,
    /// Use-movie-background-color `0x0008`, Scroll-in `0x0020`,
    /// Scroll-out `0x0040`, Horizontal-scroll `0x0080`, Reverse-scroll
    /// `0x0100`, Continuous-scroll `0x0200`, Drop-shadow `0x1000`,
    /// Anti-alias `0x2000`, Key-text `0x4000`).
    pub display_flags: u32,
    /// Text alignment: `0` left-justified, `1` centered, `-1`
    /// right-justified.
    pub text_justification: i32,
    /// The 48-bit RGB background colour of the text (red, green, blue).
    pub background_color: [u16; 3],
    /// The default text box rectangle (top, left, bottom, right).
    pub default_text_box: [i16; 4],
    /// The font number to use (must be 0 per the spec).
    pub font_number: u16,
    /// The font style (face). `0` is normal; the low bits enable Bold
    /// (`0x01`), Italic (`0x02`), Underline (`0x04`), Outline (`0x08`),
    /// Shadow (`0x10`), Condense (`0x20`), and Extend (`0x40`).
    pub font_face: u16,
    /// The 48-bit RGB foreground colour of the text (red, green, blue).
    pub foreground_color: [u16; 3],
    /// The name of the font to display the text with (the Pascal string,
    /// without its leading length byte). Empty when none is carried.
    pub text_name: String,
}

/// Decoded QuickTime Track Load Settings Atom (`load`).
///
/// A `trak`-level atom indicating how a reader should preload and play the
/// track. Body layout (a plain `Box`, no FullBox preamble): `int(32)
/// preload_start_time`, `int(32) preload_duration`, `int(32)
/// preload_flags`, `int(32) default_hints` โ€” sixteen bytes. Times are in
/// the movie's time coordinate system. All integers big-endian.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LoadSettingsBox {
    /// Start time, in the movie timescale, of a track segment to preload.
    pub preload_start_time: i32,
    /// Duration, in the movie timescale, of the preload segment. `-1`
    /// means the segment extends to the end of the track.
    pub preload_duration: i32,
    /// Flags governing preload (mutually exclusive): `1` preload the track
    /// regardless of enablement; `2` preload only when the track is
    /// enabled.
    pub preload_flags: i32,
    /// Playback hints (may combine): Double-buffer (`0x0020`),
    /// High-quality (`0x0100`).
    pub default_hints: i32,
}

impl LoadSettingsBox {
    /// Whether the track is preloaded regardless of enablement
    /// (`preload_flags == 1`).
    pub fn preload_always(&self) -> bool {
        self.preload_flags == 1
    }
    /// Whether the track is preloaded only when enabled
    /// (`preload_flags == 2`).
    pub fn preload_if_enabled(&self) -> bool {
        self.preload_flags == 2
    }
    /// Whether the Double-buffer hint is set (`default_hints & 0x0020`).
    pub fn double_buffer(&self) -> bool {
        self.default_hints & 0x0020 != 0
    }
    /// Whether the High-quality hint is set (`default_hints & 0x0100`).
    pub fn high_quality(&self) -> bool {
        self.default_hints & 0x0100 != 0
    }
}

/// One entry of a `dref` (DataReferenceBox, ISO/IEC 14496-12 ยง8.7.2).
///
/// Each entry is either a `url ` DataEntryUrlBox or a `urn `
/// DataEntryUrnBox. The 24-bit FullBox `flags` field carries the only
/// defined flag: bit 0 (`0x000001`) means the media data is in the same
/// file as the Movie Box that contains this data reference โ€” the
/// *self-contained* case. When self-contained, the URL form is used and
/// no string follows the flags (ยง8.7.2.3); otherwise `location` names the
/// external resource (a `urn ` entry additionally carries a `name`, the
/// URN proper).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct DataEntry {
    /// The entry box type โ€” `url ` or `urn `. Preserved verbatim so a
    /// surfacing layer can distinguish the two forms; any other FourCC is
    /// non-conforming (ยง8.7.2.1) and dropped during parse.
    kind: [u8; 4],
    /// The full 24-bit FullBox `flags`. Bit 0 set โ‡’ self-contained.
    flags: u32,
    /// For a `urn ` entry, the URN `name` (the resource's name); `None`
    /// for a `url ` entry, which has no name field.
    name: Option<String>,
    /// The `location` URL. Absent (`None`) for a self-contained entry
    /// (`flags & 1` set, no string present per ยง8.7.2.3); present for an
    /// external `url `, and optional for a `urn ` (ยง8.7.2.3 โ€” "optional
    /// in a URN entry").
    location: Option<String>,
}

impl DataEntry {
    /// ยง8.7.2.3 โ€” the data is in the same file as the Movie Box when the
    /// low flag bit is set.
    fn is_self_contained(&self) -> bool {
        self.flags & 1 != 0
    }
}

/// Parsed `dref` (DataReferenceBox, ISO/IEC 14496-12 ยง8.7.2), the table
/// of media-data locations that the per-sample-entry
/// `data_reference_index` (ยง8.5.2.2) indexes into. A track may be split
/// over several sources, so the box holds `entry_count` entries; index
/// `k` (1-based) names where the samples of a sample description carrying
/// `data_reference_index == k` are stored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct DrefBox {
    /// The data-reference table, in on-disk order. Entry `[i]` is the
    /// 1-based `data_reference_index` `i + 1`.
    entries: Vec<DataEntry>,
}

/// Parsed `tsel` (TrackSelectionBox, ISO/IEC 14496-12 ยง8.10.3).
///
/// The box carries two pieces of media-selection metadata for the
/// containing track:
///
/// * `switch_group` โ€” a signed 32-bit identifier (ยง8.10.3.4) used by
///   the consumer to group tracks that are interchangeable *during*
///   playback (e.g. multi-bitrate renditions of the same stream where
///   a player may flip between them on a frame boundary). Zero means
///   "no information"; a non-zero value must match across the entire
///   switch set. Tracks in the same `switch_group` are required by
///   the spec to be in the same alternate group (ยง8.3.2) too.
/// * `attribute_list` โ€” a list of FourCCs (ยง8.10.3.5), each one
///   *either* a descriptive tag (`tesc` = temporal scalability,
///   `fgsc` = fine-grain SNR, `cgsc` = coarse-grain SNR, `spsc` =
///   spatial, `resc` = region-of-interest, `vwsc` = view) *or* a
///   differentiating tag (`bitr` = bitrate, `cdec` = codec, `lang` =
///   language, โ€ฆ). The container preserves the on-disk byte order
///   verbatim โ€” interpretation is delegated to the consumer that
///   knows the alternate-group semantics.
///
/// `template int(32)` in the spec syntax means the field has a
/// recommended default of 0; we still parse the value as a signed
/// 32-bit integer per the type.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct TselBox {
    /// `switch_group` (ยง8.10.3.4). Signed. 0 means "no information"
    /// (also the spec-recommended default when the box is absent).
    switch_group: i32,
    /// `attribute_list` (ยง8.10.3.5). Each entry is a 4-byte FourCC.
    /// Order matches the on-disk order. Empty when the box body
    /// carried only the `switch_group`.
    attribute_list: Vec<[u8; 4]>,
}

/// One Sub Track Sample Group (ISO/IEC 14496-12 ยง8.14.6, `stsg`).
///
/// Defines one slice of a sub track as the union of the sample groups โ€”
/// of a single `grouping_type` โ€” named by the listed `sgpd` (ยง8.9.3)
/// description indices. The container does not resolve the indices
/// against the matching `sgpd` table; it preserves the `(grouping_type,
/// indices)` pairing verbatim for a consumer that knows the grouping
/// semantics.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct SubTrackSampleGroup {
    /// `grouping_type` (ยง8.14.6.3). The same FourCC used by the matching
    /// `sbgp` (ยง8.9.2) and `sgpd` (ยง8.9.3) boxes on the parent track.
    grouping_type: [u8; 4],
    /// `group_description_index[]` (ยง8.14.6.3). Each entry indexes a
    /// `sgpd` entry of `grouping_type` that describes samples belonging
    /// to this sub track. Order matches the on-disk order.
    group_description_indices: Vec<u32>,
}

/// One parsed Sub Track (ISO/IEC 14496-12 ยง8.14.3, `strk`).
///
/// A sub track assigns *part* of the containing track to alternate /
/// switch groups (ยง8.14.1), letting a media-selection layer choose among
/// layered-codec alternatives (SVC / MVC temporal, spatial, SNR, or view
/// layers) that don't map onto whole-track boundaries. The mandatory
/// `stri` (ยง8.14.4) carries the selection metadata; the mandatory `strd`
/// (ยง8.14.5) holds zero or more `stsg` (ยง8.14.6) that define which sample
/// groups make up the sub track.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct SubTrack {
    /// `stri.switch_group` (ยง8.14.4.3). Signed; 0 (default) means "no
    /// switching information". Shares the global numbering with
    /// `tsel.switch_group` (ยง8.10.3) so a switch group can span track
    /// and sub-track boundaries. `None` when the `strk` carried no
    /// well-formed `stri` (the box is mandatory per ยง8.14.4.1, but a
    /// malformed entry is tolerated rather than aborting the demux).
    switch_group: i16,
    /// `stri.alternate_group` (ยง8.14.4.3). Signed; 0 (default) means "no
    /// information on relations to other tracks/sub-tracks". Shares the
    /// numbering with `tkhd.alternate_group` (ยง8.3.2).
    alternate_group: i16,
    /// `stri.sub_track_ID` (ยง8.14.4.3). A non-zero value uniquely
    /// identifies the sub track locally within the parent track; 0
    /// (default) means "not assigned".
    sub_track_id: u32,
    /// `stri.attribute_list[]` (ยง8.14.4.3). Each entry is a 4-byte
    /// FourCC drawn from the descriptive set (`tesc`, `fgsc`, `cgsc`,
    /// `spsc`, `resc`, `vwsc`) or the differentiating set (`bitr`,
    /// `frar`, `nvws`, โ€ฆ). Order matches the on-disk order. Empty when
    /// the `stri` body carried only the three group/id fields.
    attribute_list: Vec<[u8; 4]>,
    /// `strd/stsg` Sub Track Sample Group boxes (ยง8.14.6). Zero or more;
    /// order matches the on-disk order.
    sample_groups: Vec<SubTrackSampleGroup>,
}

/// Decoded `cprt` (CopyrightBox, ISO/IEC 14496-12 ยง8.10.2). Carried in a
/// `udta` container โ€” `moov/udta` for a file-wide notice or `trak/udta`
/// for a per-track notice โ€” and surfaced separately from the lumped
/// 3GPP-style `udta` metadata channel because the typed shape exposes
/// the language code alongside the notice (so a multilingual presentation
/// can be reconstructed without re-parsing the box).
///
/// Spec syntax (ยง8.10.2.2): `FullBox('cprt', 0, 0) { bit(1) pad = 0;
/// unsigned int(5)[3] language; string notice; }`. The 16-bit language
/// word packs three lower-case ISO 639-2/T characters, each stored as
/// `(ASCII - 0x60)`; the notice is a NULL-terminated UTF-8 (or
/// UTF-16BE-with-BOM) string.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct CopyrightRecord {
    /// ISO 639-2/T three-letter language code (lower-case ASCII),
    /// decoded from the packed 16-bit `language` word (ยง8.10.2.3).
    /// Each byte equals the literal character `'a'..='z'`. When the box
    /// carries the packed sentinel `\0\0\0` (i.e. `0x0000`, which decodes
    /// to `0x60 0x60 0x60` = backticks rather than letters), the field
    /// is left as ASCII backticks because the spec wording confines
    /// well-formed values to "lower-case letters" only โ€” a producer
    /// that emitted a zero word is signalling "language unspecified"
    /// per the ยง8.10.2.3 well-formedness rule, and the reader leaves
    /// the literal decoded bytes for the caller to recognise.
    language: [u8; 3],
    /// The decoded copyright notice. UTF-8 by default; if the on-wire
    /// string opened with the UTF-16 BOM (0xFE 0xFF) the bytes were
    /// re-decoded as UTF-16BE. The trailing NUL terminator (ยง8.10.2.3)
    /// is stripped before storage.
    notice: String,
}

/// Single entry of an `elst` (EditListBox).
#[derive(Clone, Copy, Debug, Default)]
struct ElstEntry {
    /// In *movie* timescale (per ISO/IEC 14496-12 ยง8.6.6.1).
    segment_duration: u64,
    /// In *track* (media) timescale. `-1` means "empty" (the segment
    /// has no underlying media; play silence/black for the duration).
    media_time: i64,
    /// 16.16 fixed-point. ยง8.6.6.3 allows only 1.0 (normal) and 0.0
    /// (a "dwell": the media at `media_time` is held still for
    /// `segment_duration`); any other value is treated as 1.0 for the
    /// timeline projection.
    media_rate: u32,
}

/// One non-empty, non-dwell edit segment resolved onto the
/// presentation timeline (ยง8.6.6). All fields are in the *media*
/// timescale: `segment_duration` (movie timescale on the wire) is
/// rescaled once at build time so the per-sample mapping is a pair of
/// additions.
#[derive(Clone, Copy, Debug)]
struct ElstMappedSegment {
    /// Presentation (composition) time this segment starts at โ€”
    /// the sum of every earlier segment's duration, including empty
    /// edits and dwells.
    pres_start: i64,
    /// `media_time` โ€” the media composition time this segment maps
    /// from.
    media_start: i64,
    /// Media consumed by this segment (== presentation duration at
    /// rate 1.0). `0` means open-ended: ยง8.6.6.1 allows a zero
    /// `segment_duration` in the initial movie of a fragmented file,
    /// meaning "from `media_time` onwards".
    dur: i64,
}

/// The ยง8.6.6 explicit timeline map, precomputed per track once the
/// movie timescale is known.
///
/// The full multi-segment mapping applies when the edit list is
/// *media-monotonic*: successive non-empty segments have
/// non-decreasing `media_time` and non-decreasing presentation deltas
/// (`pres_start - media_start`), which guarantees decode-order DTS
/// stays monotonic after mapping. Every common shape qualifies โ€”
/// initial empty-edit delay, initial trim (`media_time > 0`),
/// delay + trim, dwell inserts, multi-segment appends. A list that
/// re-orders or repeats media (a delta that moves backwards) falls
/// back to the single leading-shift behaviour so timestamps stay
/// monotonic.
#[derive(Clone, Debug, Default)]
struct ElstTimeline {
    /// Non-empty, non-dwell segments in presentation order.
    segments: Vec<ElstMappedSegment>,
    /// First non-empty edit's `media_time` โ€” the legacy constant
    /// shift, used when `mapped` is false.
    leading_shift: i64,
    /// True when the per-segment mapping applies (see type docs).
    mapped: bool,
}

impl ElstTimeline {
    /// Map a sample's media composition time to `(delta, presented)`:
    /// `delta` is added to the sample's CTS and DTS to land it on the
    /// presentation timeline, and `presented` is false when the edit
    /// list never presents this composition time (decode pre-roll
    /// before the first segment, or media excised between segments) โ€”
    /// surfaced as the packet `discard` flag.
    fn delta_for_cts(&self, cts: i64) -> (i64, bool) {
        if !self.mapped || self.segments.is_empty() {
            // Legacy single-shift behaviour: subtract the first
            // non-empty edit's media_time.
            return (self.leading_shift.saturating_neg(), true);
        }
        let first = &self.segments[0];
        if cts < first.media_start {
            // Decode pre-roll: media before the first mapped
            // composition time is never presented (e.g. priming
            // samples ahead of an initial trim). Extrapolate the first
            // segment's delta so pre-roll timestamps stay ordered
            // (they land before the segment's presentation start).
            return (first.pres_start.saturating_sub(first.media_start), false);
        }
        // Last segment whose media_start <= cts (media-monotonic list,
        // so this is the innermost candidate).
        let mut chosen = 0usize;
        for (i, s) in self.segments.iter().enumerate() {
            if s.media_start <= cts {
                chosen = i;
            } else {
                break;
            }
        }
        let s = &self.segments[chosen];
        let delta = s.pres_start.saturating_sub(s.media_start);
        let in_range = s.dur == 0 || cts < s.media_start.saturating_add(s.dur);
        if in_range {
            (delta, true)
        } else {
            // Past the declared end of the chosen segment. Between two
            // segments the media is excised (not presented); past the
            // *last* segment we keep presenting โ€” real files routinely
            // declare an elst duration a frame or two short of the
            // track, and ยง8.6.6.3 models the tail as an implicit empty
            // edit on the *movie* timeline, not a sample drop.
            (delta, chosen == self.segments.len() - 1)
        }
    }
}

/// Precompute the ยง8.6.6 presentation timeline for one track.
///
/// `segment_duration` is expressed in the movie timescale (ยง8.6.6.3);
/// each is rescaled to the track's media timescale here, with `u128`
/// intermediate math (a v1 entry carries a 64-bit duration) saturating
/// to `i64::MAX` rather than wrapping.
fn build_elst_timeline(
    elst: &[ElstEntry],
    movie_timescale: u32,
    media_timescale: u32,
) -> ElstTimeline {
    let leading_shift = elst_leading_media_time(elst);
    let mut segments: Vec<ElstMappedSegment> = Vec::new();
    let mut pres: i128 = 0;
    for e in elst {
        let dur_media: i64 = if movie_timescale > 0 {
            let d = (e.segment_duration as u128).saturating_mul(media_timescale as u128)
                / movie_timescale as u128;
            i64::try_from(d).unwrap_or(i64::MAX)
        } else {
            0
        };
        let rate_integer = (e.media_rate >> 16) as i16;
        if e.media_time == -1 || rate_integer == 0 {
            // Empty edit or dwell: presentation time advances, no
            // media range is consumed. (A dwell holds the single
            // composition instant `media_time` โ€” repeating a frame is
            // a renderer concern; at the container layer it inserts
            // presentation time exactly like an empty edit.)
            pres = pres.saturating_add(dur_media as i128);
            continue;
        }
        segments.push(ElstMappedSegment {
            pres_start: i64::try_from(pres).unwrap_or(i64::MAX),
            media_start: e.media_time,
            dur: dur_media,
        });
        pres = pres.saturating_add(dur_media as i128);
    }
    // Media-monotonicity: non-decreasing media_start AND
    // non-decreasing delta across successive segments (see type docs).
    let mut mapped = !segments.is_empty();
    for w in segments.windows(2) {
        let d0 = w[0].pres_start.saturating_sub(w[0].media_start);
        let d1 = w[1].pres_start.saturating_sub(w[1].media_start);
        if w[1].media_start < w[0].media_start || d1 < d0 {
            mapped = false;
            break;
        }
    }
    ElstTimeline {
        segments,
        leading_shift,
        mapped,
    }
}

/// Per-track defaults from `mvex/trex` (ISO/IEC 14496-12 ยง8.8.3). All
/// fields zero when the file has no `mvex`. The fragment parser
/// consults these as a fall-back when a `tfhd` lacks the corresponding
/// override flag.
#[derive(Clone, Copy, Debug, Default)]
struct TrexDefaults {
    /// `default_sample_description_index` โ€” almost always 1.
    default_sample_description_index: u32,
    default_sample_duration: u32,
    default_sample_size: u32,
    default_sample_flags: u32,
}

fn parse_moov(moov: &[u8], file_size: u64) -> Result<ParsedMoov> {
    let mut out = ParsedMoov::default();
    let mut cur = std::io::Cursor::new(moov);
    let end = moov.len() as u64;
    // First pass: collect tracks + mvhd + metadata.
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            TRAK => {
                let body = read_bytes_vec(&mut cur, psz)?;
                if let Some(t) = parse_trak(&body, file_size)? {
                    out.tracks.push(t);
                }
            }
            MVHD => {
                let body = read_bytes_vec(&mut cur, psz)?;
                parse_mvhd(&body, &mut out)?;
            }
            UDTA => {
                let body = read_bytes_vec(&mut cur, psz)?;
                parse_udta(&body, &mut out.metadata);
            }
            META => {
                let body = read_bytes_vec(&mut cur, psz)?;
                parse_meta(&body, &mut out.metadata);
            }
            MVEX => {
                let body = read_bytes_vec(&mut cur, psz)?;
                parse_mvex(
                    &body,
                    &mut out.tracks,
                    &mut out.mehd_fragment_duration,
                    &mut out.leva,
                    &mut out.treps,
                )?;
            }
            PSSH => {
                // ISO/IEC 23001-7 ยง8.1 โ€” ProtectionSystemSpecificHeaderBox.
                // Zero or more per moov; each is keyed by a 16-byte
                // SystemID UUID identifying a DRM. Parsed structurally
                // and surfaced through the demuxer's metadata channel
                // (no decryption โ€” this crate only carries the box).
                // A malformed pssh is non-fatal: drop it but keep the
                // file parseable (DRM-free playback may still be
                // intended, and an opaque DRM box should not brick the
                // demuxer).
                let body = read_bytes_vec(&mut cur, psz)?;
                if let Ok(p) = parse_pssh(&body) {
                    out.psshes.push(p);
                }
            }
            // PIFF legacy `uuid` boxes at moov level. The only
            // encryption usertype placed here is the
            // ProtectionSystemSpecificHeaderBox (the pre-CENC `pssh`);
            // its body is byte-identical to a v0 `pssh` payload. Same
            // recovery policy as the 4CC form: a malformed instance is
            // dropped, not fatal. Unknown usertypes are skipped.
            UUID => {
                let body = read_bytes_vec(&mut cur, psz)?;
                if body.len() >= 16 && body[..16] == PIFF_PSSH_USERTYPE {
                    if let Ok(p) = parse_piff_pssh(&body[16..]) {
                        out.piff_psshes.push(p);
                    }
                }
            }
            _ => {
                skip_cursor_bytes(&mut cur, psz);
            }
        }
    }
    Ok(out)
}

/// ยง8.8.1 โ€” `mvex` (MovieExtendsBox). Container for `trex` boxes that
/// supply per-track defaults consumed by the fragment parser, an
/// optional `mehd` MovieExtendsHeaderBox carrying the overall
/// presentation duration of a fragmented movie, and (ยง8.8.13) an
/// optional `leva` LevelAssignmentBox mapping tracks / sample groups /
/// sub-tracks to fragment levels.
fn parse_mvex(
    body: &[u8],
    tracks: &mut [Track],
    mehd_fragment_duration: &mut Option<u64>,
    leva: &mut Option<LevaRecord>,
    treps: &mut Vec<TrepRecord>,
) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            TREX => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_trex(&b, tracks)?;
            }
            // ยง8.8.2 โ€” `mehd` MovieExtendsHeaderBox. Optional FullBox
            // (`Quantity: Zero or one`). v0 โ†’ 32-bit fragment_duration;
            // v1 โ†’ 64-bit. Widened to u64 either way. The recorded
            // value is in the movie timescale (per ยง8.8.2.3
            // "indicated in the Movie Header Box"). A malformed mehd
            // is non-fatal: we drop it but keep the file parseable
            // (the demuxer falls back to mvhd.duration in that case).
            MEHD => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if let Ok(d) = parse_mehd(&b) {
                    // Spec allows only one per mvex; if a second
                    // mehd appears we keep the first (defensive โ€” the
                    // file is malformed and the rest of our parser
                    // also takes the first occurrence of single-shot
                    // boxes).
                    if mehd_fragment_duration.is_none() {
                        *mehd_fragment_duration = Some(d);
                    }
                }
            }
            // ยง8.8.13 โ€” `leva` LevelAssignmentBox. Optional FullBox
            // (quantity zero or one per file). Maps tracks / sample
            // groups / sub-tracks to "levels" inside subsequent moof
            // fragments so a downstream consumer (DASH subsegment
            // selector, scalable-bitstream layer picker) can skip
            // levels it doesn't need. The demuxer captures the first
            // instance seen and surfaces it through
            // `Mp4Demuxer::leva_entries()` plus the flat `leva_count`
            // / `leva_<n>` metadata channel. A malformed leva is
            // non-fatal: dropped, file remains parseable.
            LEVA => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if leva.is_none() {
                    if let Ok(r) = parse_leva(&b) {
                        *leva = Some(r);
                    }
                }
            }
            // ยง8.8.15 โ€” `trep` TrackExtensionPropertiesBox. Optional
            // FullBox (quantity zero or more, zero or one per track).
            // Documents/summarises a track's characteristics in the
            // subsequent movie fragments; its body is `track_id`
            // followed by "any number of boxes". The demuxer records
            // each instance (track_id + the type/length of each child
            // box) and surfaces them through `Mp4Demuxer::treps()` plus
            // the flat `trep_<n>` metadata channel. A malformed trep is
            // non-fatal: dropped, file remains parseable.
            TREP => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if let Ok(r) = parse_trep(&b) {
                    treps.push(r);
                }
            }
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }
    Ok(())
}

/// ยง8.8.2 โ€” `mehd` MovieExtendsHeaderBox.
///
/// Layout: FullBox preamble (4 bytes: version + flags) followed by a
/// single `fragment_duration` field โ€” 4 bytes (v0) or 8 bytes (v1) โ€”
/// in the movie timescale.
///
/// Returns the duration widened to `u64`. v0 values are zero-extended;
/// v1 values are read big-endian directly. An unknown version is
/// treated as malformed (the spec defines only 0 and 1).
fn parse_mehd(body: &[u8]) -> Result<u64> {
    if body.is_empty() {
        return Err(Error::invalid("MP4: mehd empty"));
    }
    let version = body[0];
    match version {
        0 => {
            if body.len() < 8 {
                return Err(Error::invalid("MP4: mehd v0 too short"));
            }
            Ok(u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as u64)
        }
        1 => {
            if body.len() < 12 {
                return Err(Error::invalid("MP4: mehd v1 too short"));
            }
            Ok(u64::from_be_bytes([
                body[4], body[5], body[6], body[7], body[8], body[9], body[10], body[11],
            ]))
        }
        _ => Err(Error::invalid("MP4: mehd unknown version")),
    }
}

/// ยง8.8.3 โ€” `trex` (TrackExtendsBox).
///
/// Layout: FullBox header (4 bytes) + track_ID (u32) +
/// default_sample_description_index (u32) + default_sample_duration (u32) +
/// default_sample_size (u32) + default_sample_flags (u32). 24 payload bytes.
fn parse_trex(body: &[u8], tracks: &mut [Track]) -> Result<()> {
    if body.len() < 24 {
        return Err(Error::invalid("MP4: trex too short"));
    }
    let track_id = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let dsdi = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    let ddur = u32::from_be_bytes([body[12], body[13], body[14], body[15]]);
    let dsiz = u32::from_be_bytes([body[16], body[17], body[18], body[19]]);
    let dflg = u32::from_be_bytes([body[20], body[21], body[22], body[23]]);
    if let Some(t) = tracks.iter_mut().find(|t| t.track_id == track_id) {
        t.trex = TrexDefaults {
            default_sample_description_index: dsdi,
            default_sample_duration: ddur,
            default_sample_size: dsiz,
            default_sample_flags: dflg,
        };
    }
    Ok(())
}

/// ISO/IEC 14496-12 ยง8.2.2 Movie Header box. Carries the movie-wide
/// timescale and duration (in that timescale).
fn parse_mvhd(body: &[u8], out: &mut ParsedMoov) -> Result<()> {
    if body.is_empty() {
        return Err(Error::invalid("MP4: mvhd empty"));
    }
    let version = body[0];
    let (timescale, duration) = if version == 0 {
        if body.len() < 20 {
            return Err(Error::invalid("MP4: mvhd v0 too short"));
        }
        let ts = u32::from_be_bytes([body[12], body[13], body[14], body[15]]);
        let du = u32::from_be_bytes([body[16], body[17], body[18], body[19]]) as u64;
        (ts, du)
    } else {
        if body.len() < 32 {
            return Err(Error::invalid("MP4: mvhd v1 too short"));
        }
        let ts = u32::from_be_bytes([body[20], body[21], body[22], body[23]]);
        let du = u64::from_be_bytes([
            body[24], body[25], body[26], body[27], body[28], body[29], body[30], body[31],
        ]);
        (ts, du)
    };
    out.movie_timescale = timescale;
    out.movie_duration = duration;
    Ok(())
}

/// Parse a `udta` box body. May contain 3GPP-style boxes (titl/auth/cprt/โ€ฆ)
/// and/or an iTunes-style `meta` subtree.
fn parse_udta(body: &[u8], metadata: &mut Vec<(String, String)>) {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        if cur.position() as usize + psz > body.len() {
            break;
        }
        let start = cur.position() as usize;
        cur.set_position((start + psz) as u64);
        let payload = &body[start..start + psz];
        match &hdr.fourcc {
            b"meta" => parse_meta(payload, metadata),
            // 3GPP TS 26.244: titl / auth / cprt / dscp โ€” body is a
            // FullBox (1 version + 3 flags) then 2-byte language code
            // then UTF-8 (or UTF-16 if BOM) string.
            b"titl" | b"auth" | b"cprt" | b"dscp" | b"gnre" | b"albm" | b"yrrc"
                if payload.len() >= 6 =>
            {
                let key = match &hdr.fourcc {
                    b"titl" => "title",
                    b"auth" => "artist",
                    b"cprt" => "copyright",
                    b"dscp" => "description",
                    b"gnre" => "genre",
                    b"albm" => "album",
                    b"yrrc" => "date",
                    _ => unreachable!(),
                };
                let s = decode_utf8_or_utf16(&payload[6..]);
                if !s.is_empty() {
                    metadata.push((key.into(), s));
                }
            }
            _ => {}
        }
    }
}

/// Parse a `meta` box body (iTunes-style or ISO-BMFF). The body is a
/// FullBox (4 bytes of version/flags), then a series of child boxes
/// including `hdlr` (identifies the scheme) and `ilst` (the item list).
fn parse_meta(body: &[u8], metadata: &mut Vec<(String, String)>) {
    if body.len() < 4 {
        return;
    }
    // First 4 bytes are version/flags (FullBox header); skip them.
    let mut cur = std::io::Cursor::new(&body[4..]);
    let end = body.len() as u64 - 4;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let start = cur.position() as usize;
        if start + psz > (body.len() - 4) {
            break;
        }
        cur.set_position((start + psz) as u64);
        if hdr.fourcc == ILST {
            parse_ilst(&body[4 + start..4 + start + psz], metadata);
        }
    }
}

/// Parse an `ilst` (iTunes-style item list). Each child is a FourCC-keyed
/// box whose payload contains a `data` subbox with the value.
fn parse_ilst(body: &[u8], metadata: &mut Vec<(String, String)>) {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let start = cur.position() as usize;
        if start + psz > body.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        // Recurse one level: look for a `data` child.
        let item = &body[start..start + psz];
        let key = ilst_key_for(&hdr.fourcc);
        if key.is_none() {
            continue;
        }
        let key = key.unwrap();
        let mut sub = std::io::Cursor::new(item);
        let sub_end = item.len() as u64;
        while sub.position() < sub_end {
            let sh = match read_box_header(&mut sub).ok().flatten() {
                Some(h) => h,
                None => break,
            };
            let sub_psz = sh.payload_size().unwrap_or(0) as usize;
            let sub_start = sub.position() as usize;
            if sub_start + sub_psz > item.len() {
                break;
            }
            sub.set_position((sub_start + sub_psz) as u64);
            if sh.fourcc == DATA {
                // data box: 4 bytes type_indicator + 4 bytes locale + payload.
                let data_body = &item[sub_start..sub_start + sub_psz];
                if data_body.len() > 8 {
                    let value = String::from_utf8_lossy(&data_body[8..]).trim().to_string();
                    if !value.is_empty() {
                        metadata.push((key.into(), value));
                    }
                }
            }
        }
    }
}

fn ilst_key_for(fourcc: &[u8; 4]) -> Option<&'static str> {
    // The iTunes atoms starting with 0xA9 are the "copyright symbol" keys.
    match fourcc {
        b"\xa9nam" => Some("title"),
        b"\xa9ART" => Some("artist"),
        b"\xa9alb" => Some("album"),
        b"\xa9cmt" => Some("comment"),
        b"\xa9gen" => Some("genre"),
        b"\xa9day" => Some("date"),
        b"\xa9wrt" => Some("composer"),
        b"\xa9too" => Some("encoder"),
        b"\xa9cpy" | b"cprt" => Some("copyright"),
        b"\xa9lyr" => Some("lyrics"),
        b"aART" => Some("album_artist"),
        b"trkn" => Some("track"),
        b"disk" => Some("disc"),
        b"desc" => Some("description"),
        _ => None,
    }
}

fn decode_utf8_or_utf16(buf: &[u8]) -> String {
    if buf.len() >= 2 && buf[0] == 0xFE && buf[1] == 0xFF {
        // UTF-16BE with BOM.
        let pairs = buf[2..].chunks_exact(2);
        let units: Vec<u16> = pairs.map(|p| u16::from_be_bytes([p[0], p[1]])).collect();
        return String::from_utf16_lossy(&units)
            .trim_end_matches('\0')
            .trim()
            .to_string();
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8_lossy(&buf[..end]).trim().to_string()
}

// ===========================================================================
// ISO/IEC 14496-12 ยง8.11 โ€” `meta` item infrastructure (HEIF / MIAF family)
// ===========================================================================
//
// A `meta` box describes a set of untimed *items* (still images, EXIF
// blobs, XMP, derived images, โ€ฆ) rather than timed samples. The item
// catalogue is spread across four sibling boxes inside the `meta`:
//
//   * `pitm` (PrimaryItemBox, ยง8.11.4) โ€” names the primary item;
//   * `iloc` (ItemLocationBox, ยง8.11.3) โ€” where each item's bytes live;
//   * `iinf` (ItemInfoBox, ยง8.11.6) โ€” each item's type code + name;
//   * `iref` (ItemReferenceBox, ยง8.11.12) โ€” typed itemโ†’item links.
//
// This crate is a container: it surfaces the catalogue (so a HEIF reader
// can locate, type and relate items) but does not itself decode an
// item's codec payload. The structured records below are reachable via
// `Mp4Demuxer::meta_items()` and the flat `meta_*` metadata keys.

/// One extent of an item, per the `iloc` (ItemLocationBox, ISO/IEC
/// 14496-12 ยง8.11.3) extent loop. An item's data is the concatenation of
/// its extents in order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IlocExtent {
    /// `extent_index` (ยง8.11.3.3) โ€” only meaningful for
    /// `construction_method == 2` (item_offset); 0 when `index_size` was
    /// 0 or the construction method does not use it.
    pub extent_index: u64,
    /// `extent_offset` โ€” absolute offset of this extent's bytes from the
    /// data origin selected by `construction_method`. 0 when
    /// `offset_size` was 0 (the ยง8.11.3.3 "beginning of source" implied
    /// value).
    pub extent_offset: u64,
    /// `extent_length` โ€” length of this extent in bytes. 0 when
    /// `length_size` was 0 (the ยง8.11.3.3 "entire length of source"
    /// implied value).
    pub extent_length: u64,
}

/// One item's location record, per the `iloc` per-item loop (ISO/IEC
/// 14496-12 ยง8.11.3.2). The on-wire field widths (`offset_size`,
/// `length_size`, `base_offset_size`, `index_size`) are box-global; the
/// decoded values are widened to `u64` here so a consumer sees one type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IlocItem {
    /// `item_ID` โ€” the catalogue key. 16-bit on the wire for versions
    /// 0/1, 32-bit for version 2; widened to `u32`.
    pub item_id: u32,
    /// `construction_method` (versions 1/2 only; 0 for version 0):
    /// 0 = file offset, 1 = idat offset, 2 = item offset (ยง8.11.3.3).
    pub construction_method: u8,
    /// `data_reference_index` โ€” 0 = this file, else a 1-based index into
    /// the `dref` table (ยง8.11.3.3).
    pub data_reference_index: u16,
    /// `base_offset` โ€” added to each extent offset (ยง8.11.3.3). 0 when
    /// `base_offset_size` was 0.
    pub base_offset: u64,
    /// Extents in file order; their lengths sum to the item's total size.
    pub extents: Vec<IlocExtent>,
}

/// Decoded `iloc` (ItemLocationBox, ISO/IEC 14496-12 ยง8.11.3).
///
/// Carries the box-global field-width selectors verbatim (so a consumer
/// can reason about the on-wire encoding) plus one [`IlocItem`] per
/// declared item.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IlocBox {
    /// FullBox version (0, 1, or 2). Versions 1/2 carry
    /// `construction_method`; version 2 widens `item_ID` and `item_count`
    /// to 32-bit.
    pub version: u8,
    /// `offset_size` โ€” byte width of each `extent_offset` ({0, 4, 8}).
    pub offset_size: u8,
    /// `length_size` โ€” byte width of each `extent_length` ({0, 4, 8}).
    pub length_size: u8,
    /// `base_offset_size` โ€” byte width of `base_offset` ({0, 4, 8}).
    pub base_offset_size: u8,
    /// `index_size` โ€” byte width of `extent_index` ({0, 4, 8}); 0 for
    /// version 0 (where the nibble is a reserved field).
    pub index_size: u8,
    /// One record per declared item, in file order.
    pub items: Vec<IlocItem>,
}

/// One item's information entry, decoded from an `infe` (ItemInfoEntry,
/// ISO/IEC 14496-12 ยง8.11.6.2) inside `iinf`.
///
/// The base spec defines four `infe` versions. Versions 0/1 carry a
/// `(protection_index, name, content_type, content_encoding)` shape with
/// no `item_type` code; versions 2/3 carry a 32-bit `item_type` FourCC
/// (e.g. `hvc1`, `Exif`, `mime`, `uri `) plus a name and โ€” for `mime` /
/// `uri ` types โ€” a content-type or URI string. The fields that don't
/// apply to a given version are left empty / zero.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ItemInfoEntry {
    /// `item_ID` โ€” matches an `iloc` `item_ID`.
    pub item_id: u32,
    /// `item_protection_index` โ€” 0 = unprotected, else a 1-based index
    /// into the `ipro` ItemProtectionBox (ยง8.11.6.3).
    pub protection_index: u16,
    /// `item_type` โ€” the 32-bit type code (versions โ‰ฅ 2). All-zero for
    /// versions 0/1 where the field does not exist on the wire.
    pub item_type: [u8; 4],
    /// `item_name` โ€” a human-readable / symbolic name (may be empty).
    pub item_name: String,
    /// `content_type` โ€” MIME type string (versions 0/1 always; versions
    /// โ‰ฅ 2 only when `item_type == "mime"`). Empty when absent.
    pub content_type: String,
    /// `content_encoding` โ€” optional encoding string (e.g. "gzip");
    /// empty when absent. For `uri ` items (versions โ‰ฅ 2) this field
    /// instead carries the `item_uri_type` string.
    pub content_encoding: String,
    /// FullBox version of the source `infe` (0, 1, 2, or 3).
    pub version: u8,
}

/// Decoded `iinf` (ItemInfoBox, ISO/IEC 14496-12 ยง8.11.6).
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct IinfBox {
    /// One entry per `infe` child, in file order (the spec sorts by
    /// increasing `item_ID`, but the demuxer preserves wire order).
    pub entries: Vec<ItemInfoEntry>,
}

/// One typed group of item references sharing a `reference_type`, decoded
/// from a `SingleItemTypeReferenceBox` inside `iref` (ISO/IEC 14496-12
/// ยง8.11.12.2).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItemReference {
    /// The reference type FourCC (e.g. `dimg`, `thmb`, `cdsc`, `auxl`).
    pub reference_type: [u8; 4],
    /// `from_item_ID` โ€” the item that refers to the others.
    pub from_item_id: u32,
    /// `to_item_ID`s โ€” the items referred to, in file order.
    pub to_item_ids: Vec<u32>,
}

/// Decoded `iref` (ItemReferenceBox, ISO/IEC 14496-12 ยง8.11.12).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IrefBox {
    /// FullBox version: 0 โ†’ 16-bit item IDs, 1 โ†’ 32-bit item IDs.
    pub version: u8,
    /// One group per `SingleItemTypeReferenceBox`, in file order.
    pub references: Vec<ItemReference>,
}

/// One decoded item property held in an `ipco` (ItemPropertyContainerBox,
/// ISO/IEC 23008-12 ยง9.3.1). Each property is a `Box` or `FullBox` whose
/// type code names the property; the variants below model the base HEIF
/// property set. Boxes whose syntax is shared with ISO/IEC 14496-12
/// (`pasp` / `clap` / `colr`) reuse this crate's existing typed records.
/// Any property box this layer does not recognise is preserved verbatim as
/// [`ItemProperty::Other`] so its index slot and bytes survive a
/// parseโ†’build round-trip.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ItemProperty {
    /// `ispe` ImageSpatialExtentsProperty (ยง6.5.3) โ€” the reconstructed
    /// image `(width, height)` in pixels.
    Ispe { image_width: u32, image_height: u32 },
    /// `pixi` PixelInformationProperty (ยง6.5.6) โ€” the per-channel bit depth
    /// of the reconstructed image, one entry per colour channel.
    Pixi { bits_per_channel: Vec<u8> },
    /// `rloc` RelativeLocationProperty (ยง6.5.7) โ€” an item's
    /// `(horizontal_offset, vertical_offset)` within the image it has a
    /// `tbas` item reference to.
    Rloc {
        horizontal_offset: u32,
        vertical_offset: u32,
    },
    /// `auxC` AuxiliaryTypeProperty (ยง6.5.8) โ€” a NULL-terminated URN
    /// `aux_type` identifying an auxiliary image (e.g. an alpha plane or
    /// depth map) plus the type-specific `aux_subtype` tail bytes.
    AuxC {
        aux_type: String,
        aux_subtype: Vec<u8>,
    },
    /// `irot` ImageRotation (ยง6.5.10) โ€” a transformative property: the
    /// reconstructed image is rotated anti-clockwise by `angle * 90`
    /// degrees (`angle` โˆˆ `0..=3`).
    Irot { angle: u8 },
    /// `imir` ImageMirror (ยง6.5.12) โ€” a transformative property: the
    /// reconstructed image is mirrored about a vertical (`axis == 0`) or
    /// horizontal (`axis == 1`) axis.
    Imir { axis: u8 },
    /// `lsel` LayerSelectorProperty (ยง6.5.11) โ€” selects one reconstructed
    /// image (`layer_id`) of a multi-layer coded image item.
    Lsel { layer_id: u16 },
    /// `pasp` PixelAspectRatioBox (ยง6.5.4 โ†’ ISO/IEC 14496-12 ยง12.1.4).
    Pasp(PaspRecord),
    /// `clap` CleanApertureBox (ยง6.5.9 โ†’ ISO/IEC 14496-12 ยง12.1.4), a
    /// transformative crop property.
    Clap(ClapRecord),
    /// `colr` ColourInformationBox (ยง6.5.5 โ†’ ISO/IEC 14496-12 ยง12.1.5).
    Colr(ColrRecord),
    /// `udes` UserDescriptionProperty (ยง6.5.20) โ€” four NUL-terminated UTF-8
    /// strings: `lang` (RFC 5646 tag), `name`, `description`, and
    /// comma-separated `tags` (any may be empty).
    Udes {
        lang: String,
        name: String,
        description: String,
        tags: String,
    },
    /// `altt` AccessibilityTextProperty (ยง6.5.21) โ€” an alternate-text
    /// string (HTML `alt`-style) plus its RFC 5646 language tag.
    Altt { alt_text: String, alt_lang: String },
    /// `iscl` ImageScaling (ยง6.5.13) โ€” a transformative property: the
    /// horizontal / vertical scaling ratios as 16-bit numerator/denominator
    /// pairs (a value of 0 is spec-prohibited but preserved verbatim).
    Iscl {
        target_width_numerator: u16,
        target_width_denominator: u16,
        target_height_numerator: u16,
        target_height_denominator: u16,
    },
    /// `rref` RequiredReferenceTypesProperty (ยง6.5.17) โ€” the `iref`
    /// reference-type FourCCs a reader must understand to decode the item
    /// (e.g. `pred` for a predictively-coded image item).
    Rref { reference_types: Vec<[u8; 4]> },
    /// `crtt` CreationTimeProperty (ยง6.5.18) โ€” the item / group creation
    /// time, in microseconds since 1904-01-01 UTC.
    Crtt { creation_time: u64 },
    /// `mdft` ModificationTimeProperty (ยง6.5.19) โ€” the most recent
    /// modification time, in microseconds since 1904-01-01 UTC.
    Mdft { modification_time: u64 },
    /// Any other property box: its FourCC type plus the raw body bytes
    /// (after any FullBox preamble is *included* โ€” the body is the box
    /// payload verbatim). Preserved so the implicit 1-based index slot is
    /// never silently dropped.
    Other { box_type: [u8; 4], body: Vec<u8> },
}

/// One `(essential, property_index)` association from an `ipma`
/// (ItemPropertyAssociation, ISO/IEC 23008-12 ยง9.3.1). `property_index` is
/// the 1-based index into the sibling `ipco` (0 means "no property"); when
/// `essential` is set a reader that does not understand the referenced
/// property must not process the item.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PropertyAssociation {
    /// `essential` (ยง9.3.3) โ€” true โ†’ a reader unable to process the
    /// associated property must reject the item.
    pub essential: bool,
    /// `property_index` (ยง9.3.3) โ€” 1-based index into `ipco`'s implicit
    /// property list, or 0 for "no property".
    pub property_index: u16,
}

/// One item's association list from an `ipma` box (ยง9.3.1): the item ID and
/// the ordered set of property indices associated with it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItemPropertyAssociationEntry {
    /// `item_ID` โ€” matches an `iloc` / `iinf` item ID.
    pub item_id: u32,
    /// The ordered associations (`ipma` preserves writer order, which is
    /// significant: transformative properties apply in sequence โ€” ยง6.5.1).
    pub associations: Vec<PropertyAssociation>,
}

/// Decoded `iprp` (ItemPropertiesBox, ISO/IEC 23008-12 ยง9.3.1) โ€” the
/// `ipco` property list plus every `ipma` association box, merged.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ItemProperties {
    /// The `ipco` property list, in on-wire order. The implicit
    /// `property_index` an `ipma` association references is the 1-based
    /// position in this vec (so `properties[index - 1]`).
    pub properties: Vec<ItemProperty>,
    /// Every itemโ†’property association, accumulated across all `ipma`
    /// boxes in the `iprp`. The spec permits several `ipma` boxes
    /// distinguished by `(version, flags)`; their entries are concatenated
    /// here in encounter order.
    pub associations: Vec<ItemPropertyAssociationEntry>,
}

impl ItemProperties {
    /// True when neither an `ipco` property nor an `ipma` association was
    /// found (an empty / malformed `iprp`).
    pub fn is_empty(&self) -> bool {
        self.properties.is_empty() && self.associations.is_empty()
    }

    /// Look up the property record referenced by a 1-based `property_index`
    /// (the value carried in an `ipma` association). Returns `None` for
    /// index 0 ("no property") or an index past the end of the `ipco` list.
    pub fn property(&self, property_index: u16) -> Option<&ItemProperty> {
        if property_index == 0 {
            return None;
        }
        self.properties.get((property_index - 1) as usize)
    }

    /// The resolved `(essential, &ItemProperty)` pairs associated with an
    /// item, in `ipma` order. Associations whose `property_index` is 0 or
    /// out of range are skipped (a malformed reference contributes nothing
    /// rather than aborting). Returns an empty vec when the item has no
    /// `ipma` entry.
    pub fn properties_for(&self, item_id: u32) -> Vec<(bool, &ItemProperty)> {
        let mut out = Vec::new();
        for entry in &self.associations {
            if entry.item_id != item_id {
                continue;
            }
            for a in &entry.associations {
                if let Some(p) = self.property(a.property_index) {
                    out.push((a.essential, p));
                }
            }
        }
        out
    }
}

/// One entity group decoded from an `EntityToGroupBox` (ISO/IEC 23008-12
/// ยง9.4.3) inside a `grpl` GroupsListBox. The box's FourCC names the
/// `grouping_type` (the semantics โ€” `altr` alternatives, `ster` stereo
/// pair, etc.); the body lists the item / track IDs that share the
/// grouping characteristic.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntityToGroup {
    /// The `grouping_type` FourCC (the `EntityToGroupBox`'s box type) โ€”
    /// e.g. `altr` (alternatives, only one to be played), `ster` (a
    /// two-entity stereo pair, entity 0 = left / entity 1 = right).
    pub grouping_type: [u8; 4],
    /// `group_id` (ยง9.4.3.3) โ€” the group's unique non-negative ID,
    /// distinct from any other group ID, item ID, or track ID at its
    /// hierarchy level.
    pub group_id: u32,
    /// `entity_id`s (ยง9.4.3.3) โ€” the item IDs (or, at file level, track
    /// IDs) mapped to this group, in list order. For `ster` the first is
    /// the left view and the second the right.
    pub entity_ids: Vec<u32>,
}

/// Decoded `grpl` (GroupsListBox, ISO/IEC 23008-12 ยง9.4.2) โ€” every
/// `EntityToGroupBox` it contains, in on-wire order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EntityGroups {
    /// One record per `EntityToGroupBox` child, in file order.
    pub groups: Vec<EntityToGroup>,
}

impl EntityGroups {
    /// True when the `grpl` carried no `EntityToGroupBox` children.
    pub fn is_empty(&self) -> bool {
        self.groups.is_empty()
    }

    /// The entity groups of a given `grouping_type` (e.g. all `altr`
    /// alternative sets), in file order.
    pub fn by_type(&self, grouping_type: [u8; 4]) -> impl Iterator<Item = &EntityToGroup> {
        self.groups
            .iter()
            .filter(move |g| g.grouping_type == grouping_type)
    }

    /// The group with a given `group_id`, if any.
    pub fn by_id(&self, group_id: u32) -> Option<&EntityToGroup> {
        self.groups.iter().find(|g| g.group_id == group_id)
    }
}

/// A `meta` box's item infrastructure (ISO/IEC 14496-12 ยง8.11),
/// collected together. Any of the four child boxes may be absent.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MetaItems {
    /// `pitm` (ยง8.11.4) โ€” the primary item's ID, if a `pitm` is present.
    pub primary_item_id: Option<u32>,
    /// The handler type from the `meta`'s `hdlr` (ยง8.4.3) โ€” e.g. `pict`
    /// for HEIF still images, `mdir` for iTunes metadata. All-zero when
    /// no `hdlr` was found.
    pub handler_type: [u8; 4],
    /// `iloc` (ยง8.11.3), if present.
    pub iloc: Option<IlocBox>,
    /// `iinf` (ยง8.11.6), if present.
    pub iinf: Option<IinfBox>,
    /// `iref` (ยง8.11.12), if present.
    pub iref: Option<IrefBox>,
    /// `idat` (ItemDataBox, ยง8.11.11) bytes, if present. Items whose
    /// `iloc` `construction_method == 1` address their extents relative
    /// to the start of this buffer (the ยง8.11.3.3 idat data origin).
    /// Empty when no `idat` box is present.
    pub idat: Vec<u8>,
    /// `fiin` (FD Item Information Box, ยง8.13.2), if present. Carries the
    /// File Delivery partitioning (`paen` โ†’ `fpar`/`fecr`/`fire`) plus the
    /// optional FD session-group (`segr`) and group-name (`gitn`) boxes.
    /// `None` for a non-FD `meta` (the common HEIF / iTunes case).
    pub fiin: Option<crate::fd::FiinBox>,
    /// `iprp` (ItemPropertiesBox, ISO/IEC 23008-12 ยง9.3.1), if present.
    /// The HEIF item-properties family: the `ipco` property list plus the
    /// `ipma` per-item associations. `None` for a `meta` carrying no
    /// `iprp` (every non-HEIF `meta`, and HEIF files written without
    /// properties). Resolve an item's properties via
    /// [`ItemProperties::properties_for`].
    pub iprp: Option<ItemProperties>,
    /// `grpl` (GroupsListBox, ISO/IEC 23008-12 ยง9.4.2), if present. The
    /// HEIF entity groups (`altr` alternatives, `ster` stereo pairs, โ€ฆ)
    /// mapping item / track IDs into named groups. `None` for a `meta`
    /// carrying no `grpl`.
    pub grpl: Option<EntityGroups>,
}

/// A resolved byte range for one item extent, relative to a data origin
/// determined by the item's `construction_method` (ISO/IEC 14496-12
/// ยง8.11.3.3). For `construction_method == 0` (file) the range is an
/// absolute file offset; for `construction_method == 1` (idat) it is an
/// offset into the `meta` box's `idat` buffer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemByteRange {
    /// Start offset (from the data origin selected by the construction
    /// method). `base_offset + extent_offset`.
    pub offset: u64,
    /// Length in bytes.
    pub length: u64,
}

impl MetaItems {
    /// True when this `meta` box carries no item infrastructure at all
    /// (no `pitm` / `iloc` / `iinf` / `iref` / `idat`) โ€” e.g. a plain
    /// iTunes `meta` whose payload is just `hdlr` + `ilst`.
    pub fn is_empty(&self) -> bool {
        self.primary_item_id.is_none()
            && self.iloc.is_none()
            && self.iinf.is_none()
            && self.iref.is_none()
            && self.idat.is_empty()
            && self.fiin.is_none()
            && self.iprp.is_none()
            && self.grpl.is_none()
    }

    /// Look up an item's `iloc` location record by item ID.
    pub fn iloc_item(&self, item_id: u32) -> Option<&IlocItem> {
        self.iloc
            .as_ref()?
            .items
            .iter()
            .find(|it| it.item_id == item_id)
    }

    /// Look up an item's `iinf` info entry by item ID.
    pub fn item_info(&self, item_id: u32) -> Option<&ItemInfoEntry> {
        self.iinf
            .as_ref()?
            .entries
            .iter()
            .find(|e| e.item_id == item_id)
    }

    /// Resolve the byte ranges of an item's extents, applying the item's
    /// `base_offset` (ยง8.11.3.3) to each extent offset. The returned
    /// ranges are relative to the data origin selected by the item's
    /// `construction_method` (file offset for 0, `idat` offset for 1);
    /// callers using method 0 add the file base, callers using method 1
    /// index into [`MetaItems::idat`].
    ///
    /// Returns `None` when the item ID is not in `iloc`. An empty extent
    /// list yields an empty vec.
    pub fn item_byte_ranges(&self, item_id: u32) -> Option<Vec<ItemByteRange>> {
        let it = self.iloc_item(item_id)?;
        Some(
            it.extents
                .iter()
                .map(|ex| ItemByteRange {
                    offset: it.base_offset.saturating_add(ex.extent_offset),
                    length: ex.extent_length,
                })
                .collect(),
        )
    }

    /// Materialise the bytes of an item whose data is stored inside the
    /// `meta` box's `idat` (ItemDataBox, ยง8.11.11) โ€” i.e. whose `iloc`
    /// `construction_method == 1`. The item's extents are concatenated
    /// in order. Returns `None` when:
    ///   * the item ID is not in `iloc`,
    ///   * the item's construction method is not 1 (idat), or
    ///   * any extent range overruns the available `idat` bytes.
    ///
    /// Items addressed by file offset (`construction_method == 0`) are
    /// not resolved here โ€” the demuxer does not re-read the input for
    /// untimed items; use [`MetaItems::item_byte_ranges`] to obtain
    /// their absolute file offsets and read them externally.
    pub fn item_data_from_idat(&self, item_id: u32) -> Option<Vec<u8>> {
        let it = self.iloc_item(item_id)?;
        if it.construction_method != 1 {
            return None;
        }
        let mut out = Vec::new();
        for ex in &it.extents {
            let start = it.base_offset.checked_add(ex.extent_offset)? as usize;
            // length 0 means "entire source" for a single-extent item
            // (ยง8.11.3.3); for idat that is the rest of the buffer.
            let len = if ex.extent_length == 0 && it.extents.len() == 1 {
                self.idat.len().checked_sub(start)?
            } else {
                ex.extent_length as usize
            };
            let end = start.checked_add(len)?;
            if end > self.idat.len() {
                return None;
            }
            out.extend_from_slice(&self.idat[start..end]);
        }
        Some(out)
    }
}

/// Read a big-endian unsigned integer of `n` bytes (n โˆˆ {0, 4, 8}, the
/// `iloc` field-width set) from `buf` at `pos`, advancing `pos`. A width
/// of 0 yields 0 without consuming bytes (the ยง8.11.3.3 implied-value
/// convention). Returns `None` if the field would overrun `buf`.
fn read_sized_be(buf: &[u8], pos: &mut usize, n: usize) -> Option<u64> {
    if n == 0 {
        return Some(0);
    }
    if *pos + n > buf.len() {
        return None;
    }
    let mut v: u64 = 0;
    for &b in &buf[*pos..*pos + n] {
        v = (v << 8) | b as u64;
    }
    *pos += n;
    Some(v)
}

/// Parse an `iloc` (ItemLocationBox, ISO/IEC 14496-12 ยง8.11.3) body
/// (the bytes after the box header). Returns `None` on a truncated or
/// malformed box rather than aborting the enclosing `meta` walk.
pub fn parse_iloc_box(body: &[u8]) -> Option<IlocBox> {
    if body.len() < 6 {
        return None;
    }
    let version = body[0];
    if version > 2 {
        return None;
    }
    // body[1..4] are flags (must be 0 per ยง8.11.3.2); skipped.
    let mut pos = 4usize;
    let b = body[pos];
    let offset_size = b >> 4;
    let length_size = b & 0x0F;
    pos += 1;
    let b = body[pos];
    let base_offset_size = b >> 4;
    // The low nibble is `index_size` for versions 1/2, reserved (0) for 0.
    let index_size = if version == 1 || version == 2 {
        b & 0x0F
    } else {
        0
    };
    pos += 1;
    // ยง8.11.3.2: each *_size must be one of {0, 4, 8}.
    for &s in &[offset_size, length_size, base_offset_size, index_size] {
        if s != 0 && s != 4 && s != 8 {
            return None;
        }
    }
    let item_count = if version < 2 {
        read_sized_be(body, &mut pos, 2)?
    } else {
        read_sized_be(body, &mut pos, 4)?
    };
    let mut items = Vec::new();
    for _ in 0..item_count {
        let item_id = if version < 2 {
            read_sized_be(body, &mut pos, 2)? as u32
        } else {
            read_sized_be(body, &mut pos, 4)? as u32
        };
        let construction_method = if version == 1 || version == 2 {
            // unsigned int(12) reserved + unsigned int(4) construction_method
            let w = read_sized_be(body, &mut pos, 2)?;
            (w & 0x0F) as u8
        } else {
            0
        };
        let data_reference_index = read_sized_be(body, &mut pos, 2)? as u16;
        let base_offset = read_sized_be(body, &mut pos, base_offset_size as usize)?;
        let extent_count = read_sized_be(body, &mut pos, 2)?;
        let mut extents = Vec::new();
        for _ in 0..extent_count {
            let extent_index = if (version == 1 || version == 2) && index_size > 0 {
                read_sized_be(body, &mut pos, index_size as usize)?
            } else {
                0
            };
            let extent_offset = read_sized_be(body, &mut pos, offset_size as usize)?;
            let extent_length = read_sized_be(body, &mut pos, length_size as usize)?;
            extents.push(IlocExtent {
                extent_index,
                extent_offset,
                extent_length,
            });
        }
        items.push(IlocItem {
            item_id,
            construction_method,
            data_reference_index,
            base_offset,
            extents,
        });
    }
    Some(IlocBox {
        version,
        offset_size,
        length_size,
        base_offset_size,
        index_size,
        items,
    })
}

/// Parse a `pitm` (PrimaryItemBox, ISO/IEC 14496-12 ยง8.11.4) body and
/// return the primary `item_ID`. v0 โ†’ 16-bit, vโ‰ฅ1 โ†’ 32-bit.
pub fn parse_pitm_box(body: &[u8]) -> Option<u32> {
    if body.len() < 4 {
        return None;
    }
    let version = body[0];
    let mut pos = 4usize;
    if version == 0 {
        read_sized_be(body, &mut pos, 2).map(|v| v as u32)
    } else {
        read_sized_be(body, &mut pos, 4).map(|v| v as u32)
    }
}

/// Read a NUL-terminated UTF-8 string starting at `pos`, advancing `pos`
/// past the terminator. If no NUL is found before the end of `buf`, the
/// remaining bytes are taken as the string and `pos` is set to the end.
fn read_c_string_at(buf: &[u8], pos: &mut usize) -> String {
    let start = *pos;
    let mut i = start;
    while i < buf.len() && buf[i] != 0 {
        i += 1;
    }
    let s = String::from_utf8_lossy(&buf[start..i]).into_owned();
    // Advance past the terminator (or to end if none).
    *pos = if i < buf.len() { i + 1 } else { buf.len() };
    s
}

/// Parse a single `infe` (ItemInfoEntry, ISO/IEC 14496-12 ยง8.11.6.2)
/// body (bytes after the `infe` box header). Returns `None` on a
/// truncated header.
fn parse_infe(body: &[u8]) -> Option<ItemInfoEntry> {
    if body.len() < 4 {
        return None;
    }
    let version = body[0];
    let mut pos = 4usize;
    let mut e = ItemInfoEntry {
        version,
        ..Default::default()
    };
    if version == 0 || version == 1 {
        e.item_id = read_sized_be(body, &mut pos, 2)? as u32;
        e.protection_index = read_sized_be(body, &mut pos, 2)? as u16;
        e.item_name = read_c_string_at(body, &mut pos);
        e.content_type = read_c_string_at(body, &mut pos);
        // content_encoding is optional; present only if bytes remain.
        if pos < body.len() {
            e.content_encoding = read_c_string_at(body, &mut pos);
        }
        // version 1 may carry an extension_type + extension; ignored here.
    } else {
        // version >= 2
        e.item_id = if version == 2 {
            read_sized_be(body, &mut pos, 2)? as u32
        } else {
            read_sized_be(body, &mut pos, 4)? as u32
        };
        e.protection_index = read_sized_be(body, &mut pos, 2)? as u16;
        if pos + 4 > body.len() {
            return None;
        }
        e.item_type.copy_from_slice(&body[pos..pos + 4]);
        pos += 4;
        e.item_name = read_c_string_at(body, &mut pos);
        if &e.item_type == b"mime" {
            e.content_type = read_c_string_at(body, &mut pos);
            if pos < body.len() {
                e.content_encoding = read_c_string_at(body, &mut pos);
            }
        } else if &e.item_type == b"uri " {
            // item_uri_type โ†’ carried in content_encoding to avoid a
            // separate field (documented on ItemInfoEntry).
            e.content_encoding = read_c_string_at(body, &mut pos);
        }
    }
    Some(e)
}

/// Parse an `iinf` (ItemInfoBox, ISO/IEC 14496-12 ยง8.11.6) body. Walks
/// the child `infe` boxes. Malformed children are skipped; a truncated
/// header aborts the walk gracefully (returns whatever parsed cleanly).
pub fn parse_iinf_box(body: &[u8]) -> Option<IinfBox> {
    if body.len() < 4 {
        return None;
    }
    let version = body[0];
    let mut pos = 4usize;
    let entry_count = if version == 0 {
        read_sized_be(body, &mut pos, 2)?
    } else {
        read_sized_be(body, &mut pos, 4)?
    };
    let mut out = IinfBox::default();
    let mut cur = std::io::Cursor::new(&body[pos..]);
    let region = &body[pos..];
    let end = region.len() as u64;
    let mut seen = 0u64;
    while cur.position() < end && seen < entry_count {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let start = cur.position() as usize;
        if start + psz > region.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        if hdr.fourcc == INFE {
            if let Some(e) = parse_infe(&region[start..start + psz]) {
                out.entries.push(e);
            }
        }
        seen += 1;
    }
    Some(out)
}

/// Parse an `iref` (ItemReferenceBox, ISO/IEC 14496-12 ยง8.11.12) body.
/// Each child is a `SingleItemTypeReferenceBox` whose box type IS the
/// reference type.
pub fn parse_iref_box(body: &[u8]) -> Option<IrefBox> {
    if body.len() < 4 {
        return None;
    }
    let version = body[0];
    if version > 1 {
        return None;
    }
    let id_bytes = if version == 0 { 2usize } else { 4usize };
    let region = &body[4..];
    let mut cur = std::io::Cursor::new(region);
    let end = region.len() as u64;
    let mut references = Vec::new();
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let start = cur.position() as usize;
        if start + psz > region.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        let sub = &region[start..start + psz];
        let mut p = 0usize;
        let from_item_id = match read_sized_be(sub, &mut p, id_bytes) {
            Some(v) => v as u32,
            None => continue,
        };
        let ref_count = match read_sized_be(sub, &mut p, 2) {
            Some(v) => v,
            None => continue,
        };
        let mut to_item_ids = Vec::new();
        for _ in 0..ref_count {
            match read_sized_be(sub, &mut p, id_bytes) {
                Some(v) => to_item_ids.push(v as u32),
                None => break,
            }
        }
        references.push(ItemReference {
            reference_type: hdr.fourcc,
            from_item_id,
            to_item_ids,
        });
    }
    Some(IrefBox {
        version,
        references,
    })
}

/// Walk a `meta` box body (bytes after its FullBox preamble removed by
/// the caller is NOT assumed โ€” this takes the full body and skips the
/// 4-byte version/flags itself) and collect the ยง8.11 item
/// infrastructure (`pitm` / `iloc` / `iinf` / `iref`) plus the `hdlr`
/// handler type. Returns an all-`None` [`MetaItems`] for a plain iTunes
/// `meta` (which carries only `hdlr` + `ilst`).
pub fn parse_meta_items(body: &[u8]) -> MetaItems {
    let mut out = MetaItems::default();
    if body.len() < 4 {
        return out;
    }
    let region = &body[4..];
    let mut cur = std::io::Cursor::new(region);
    let end = region.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let start = cur.position() as usize;
        if start + psz > region.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        let child = &region[start..start + psz];
        match hdr.fourcc {
            // ยง8.4.3 hdlr body: version/flags(4) + pre_defined(4) +
            // handler_type(4) + โ€ฆ โ€” capture handler_type.
            HDLR if child.len() >= 12 => {
                out.handler_type.copy_from_slice(&child[8..12]);
            }
            PITM => {
                if let Some(id) = parse_pitm_box(child) {
                    out.primary_item_id = Some(id);
                }
            }
            ILOC => out.iloc = parse_iloc_box(child),
            IINF => out.iinf = parse_iinf_box(child),
            IREF => out.iref = parse_iref_box(child),
            // ยง8.11.11 ItemDataBox โ€” raw bytes; the data origin for
            // construction_method 1 (idat) items.
            IDAT => out.idat = child.to_vec(),
            // ยง8.13.2 FD Item Information Box โ€” File Delivery partitioning.
            FIIN => out.fiin = crate::fd::parse_fiin_box(child),
            // ISO/IEC 23008-12 ยง9.3 ItemPropertiesBox โ€” HEIF item
            // properties (`ipco` list + `ipma` associations).
            IPRP => {
                let p = parse_iprp_box(child);
                if !p.is_empty() {
                    out.iprp = Some(p);
                }
            }
            // ISO/IEC 23008-12 ยง9.4 GroupsListBox โ€” HEIF entity groups.
            GRPL => {
                let g = parse_grpl_box(child);
                if !g.is_empty() {
                    out.grpl = Some(g);
                }
            }
            _ => {}
        }
    }
    out
}

// ---------------------------------------------------------------------------
// HEIF / MIAF item-properties parsers (ISO/IEC 23008-12 ยง9.3 / ยง6.5). The
// `iprp` ItemPropertiesBox holds one `ipco` (ItemPropertyContainerBox โ€” an
// implicitly 1-indexed list of property boxes) and one or more `ipma`
// (ItemPropertyAssociation) boxes mapping each item to its property indices.
// ---------------------------------------------------------------------------

/// Parse an `iprp` (ItemPropertiesBox, ISO/IEC 23008-12 ยง9.3.1) body (the
/// bytes after the box header). Walks the single `ipco` child for the
/// property list and every `ipma` child for the per-item associations.
/// A malformed instance yields an empty [`ItemProperties`] (the caller
/// drops it) rather than aborting the enclosing `meta` walk.
pub fn parse_iprp_box(body: &[u8]) -> ItemProperties {
    let mut out = ItemProperties::default();
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = match hdr.payload_size() {
            Some(p) => p as usize,
            None => break,
        };
        let start = cur.position() as usize;
        if start + psz > body.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        let child = &body[start..start + psz];
        match hdr.fourcc {
            IPCO => out.properties = parse_ipco_box(child),
            IPMA => out.associations.extend(parse_ipma_box(child)),
            _ => {}
        }
    }
    out
}

/// Parse an `ipco` (ItemPropertyContainerBox, ISO/IEC 23008-12 ยง9.3.1)
/// body into the implicitly-indexed property list. Each child box is
/// decoded into the typed [`ItemProperty`] variant for its FourCC; an
/// unrecognised box type is preserved verbatim as [`ItemProperty::Other`]
/// so its 1-based index slot is never dropped (the index an `ipma`
/// references must stay stable). A `free` / `skip` box (ยง9.3.1 allows
/// it inside `ipco`, occupying an index value but carrying no meaning) is
/// preserved as `Other` too so subsequent indices stay aligned.
pub fn parse_ipco_box(body: &[u8]) -> Vec<ItemProperty> {
    let mut out = Vec::new();
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = match hdr.payload_size() {
            Some(p) => p as usize,
            None => break,
        };
        let start = cur.position() as usize;
        if start + psz > body.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        let child = &body[start..start + psz];
        out.push(parse_item_property(hdr.fourcc, child));
    }
    out
}

/// Decode one `ipco` child box `(box_type, body)` into a typed
/// [`ItemProperty`]. `body` is the box payload (after the box header). For
/// the `ItemFullProperty` types (`ispe` / `pixi` / `rloc` / `auxC`) the
/// body opens with the 4-byte FullBox version/flags word. A child that is
/// truncated for its declared type falls back to [`ItemProperty::Other`]
/// so the index slot survives.
fn parse_item_property(box_type: [u8; 4], body: &[u8]) -> ItemProperty {
    let other = || ItemProperty::Other {
        box_type,
        body: body.to_vec(),
    };
    match box_type {
        // ยง6.5.3 ispe: FullBox(0,0) + u32 width + u32 height.
        ISPE => {
            if body.len() < 12 {
                return other();
            }
            ItemProperty::Ispe {
                image_width: u32::from_be_bytes([body[4], body[5], body[6], body[7]]),
                image_height: u32::from_be_bytes([body[8], body[9], body[10], body[11]]),
            }
        }
        // ยง6.5.6 pixi: FullBox(0,0) + u8 num_channels + num_channels ร— u8.
        PIXI => {
            if body.len() < 5 {
                return other();
            }
            let num = body[4] as usize;
            if 5 + num > body.len() {
                return other();
            }
            ItemProperty::Pixi {
                bits_per_channel: body[5..5 + num].to_vec(),
            }
        }
        // ยง6.5.7 rloc: FullBox(0,0) + u32 horizontal + u32 vertical.
        RLOC => {
            if body.len() < 12 {
                return other();
            }
            ItemProperty::Rloc {
                horizontal_offset: u32::from_be_bytes([body[4], body[5], body[6], body[7]]),
                vertical_offset: u32::from_be_bytes([body[8], body[9], body[10], body[11]]),
            }
        }
        // ยง6.5.8 auxC: FullBox(0,flags) + null-terminated UTF-8 URN +
        // type-specific aux_subtype tail.
        AUXC => {
            if body.len() < 4 {
                return other();
            }
            let rest = &body[4..];
            let nul = rest.iter().position(|&b| b == 0);
            let (type_bytes, sub) = match nul {
                Some(i) => (&rest[..i], &rest[i + 1..]),
                None => (rest, &rest[rest.len()..]),
            };
            ItemProperty::AuxC {
                aux_type: String::from_utf8_lossy(type_bytes).to_string(),
                aux_subtype: sub.to_vec(),
            }
        }
        // ยง6.5.10 irot: plain Box; 1 byte = 6 reserved + 2-bit angle.
        IROT => {
            if body.is_empty() {
                return other();
            }
            ItemProperty::Irot {
                angle: body[0] & 0x03,
            }
        }
        // ยง6.5.12 imir: plain Box; 1 byte = 7 reserved + 1-bit axis.
        IMIR => {
            if body.is_empty() {
                return other();
            }
            ItemProperty::Imir {
                axis: body[0] & 0x01,
            }
        }
        // ยง6.5.11 lsel: plain Box; u16 layer_id.
        LSEL => {
            if body.len() < 2 {
                return other();
            }
            ItemProperty::Lsel {
                layer_id: u16::from_be_bytes([body[0], body[1]]),
            }
        }
        // ยง6.5.20 udes: FullBox(0,0) + four NUL-terminated UTF-8 strings.
        UDES => {
            if body.len() < 4 {
                return other();
            }
            let mut p = 4usize;
            let lang = read_c_string_at(body, &mut p);
            let name = read_c_string_at(body, &mut p);
            let description = read_c_string_at(body, &mut p);
            let tags = read_c_string_at(body, &mut p);
            ItemProperty::Udes {
                lang,
                name,
                description,
                tags,
            }
        }
        // ยง6.5.21 altt: FullBox(0,0) + alt_text + alt_lang (NUL-terminated).
        ALTT => {
            if body.len() < 4 {
                return other();
            }
            let mut p = 4usize;
            let alt_text = read_c_string_at(body, &mut p);
            let alt_lang = read_c_string_at(body, &mut p);
            ItemProperty::Altt { alt_text, alt_lang }
        }
        // ยง6.5.13 iscl: FullBox(0,0) + four u16 numerator/denominator.
        ISCL => {
            if body.len() < 12 {
                return other();
            }
            ItemProperty::Iscl {
                target_width_numerator: u16::from_be_bytes([body[4], body[5]]),
                target_width_denominator: u16::from_be_bytes([body[6], body[7]]),
                target_height_numerator: u16::from_be_bytes([body[8], body[9]]),
                target_height_denominator: u16::from_be_bytes([body[10], body[11]]),
            }
        }
        // ยง6.5.17 rref: FullBox(0,0) + u8 count + count ร— u32 FourCC.
        RREF => {
            if body.len() < 5 {
                return other();
            }
            let count = body[4] as usize;
            if 5 + count * 4 > body.len() {
                return other();
            }
            let mut reference_types = Vec::with_capacity(count);
            for i in 0..count {
                let o = 5 + i * 4;
                reference_types.push([body[o], body[o + 1], body[o + 2], body[o + 3]]);
            }
            ItemProperty::Rref { reference_types }
        }
        // ยง6.5.18 crtt: FullBox(0,0) + u64 creation_time.
        CRTT => {
            if body.len() < 12 {
                return other();
            }
            ItemProperty::Crtt {
                creation_time: u64::from_be_bytes([
                    body[4], body[5], body[6], body[7], body[8], body[9], body[10], body[11],
                ]),
            }
        }
        // ยง6.5.19 mdft: FullBox(0,0) + u64 modification_time.
        MDFT => {
            if body.len() < 12 {
                return other();
            }
            ItemProperty::Mdft {
                modification_time: u64::from_be_bytes([
                    body[4], body[5], body[6], body[7], body[8], body[9], body[10], body[11],
                ]),
            }
        }
        // ยง6.5.4 / ยง6.5.9 / ยง6.5.5 โ€” same syntax as the 14496-12 boxes.
        _ if &box_type == b"pasp" => parse_pasp(body)
            .map(ItemProperty::Pasp)
            .unwrap_or_else(other),
        _ if &box_type == b"clap" => parse_clap(body)
            .map(ItemProperty::Clap)
            .unwrap_or_else(other),
        _ if &box_type == b"colr" => parse_colr(body)
            .map(ItemProperty::Colr)
            .unwrap_or_else(other),
        _ => other(),
    }
}

/// Parse an `ipma` (ItemPropertyAssociation, ISO/IEC 23008-12 ยง9.3.1)
/// body into per-item association lists. `version` selects the item-ID
/// width (0 โ†’ 16-bit, โ‰ฅ 1 โ†’ 32-bit); `flags & 1` selects the
/// `property_index` width (0 โ†’ 7-bit, 1 โ†’ 15-bit), with the top bit of the
/// field carrying `essential`. A truncated entry ends the walk at what was
/// read rather than inventing associations.
pub fn parse_ipma_box(body: &[u8]) -> Vec<ItemPropertyAssociationEntry> {
    let mut out = Vec::new();
    if body.len() < 8 {
        return out;
    }
    let version = body[0];
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let wide_index = flags & 1 == 1;
    let mut pos = 4usize;
    let entry_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    pos += 4;
    for _ in 0..entry_count {
        let item_id = if version == 0 {
            if pos + 2 > body.len() {
                break;
            }
            let v = u16::from_be_bytes([body[pos], body[pos + 1]]) as u32;
            pos += 2;
            v
        } else {
            if pos + 4 > body.len() {
                break;
            }
            let v = u32::from_be_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);
            pos += 4;
            v
        };
        if pos >= body.len() {
            break;
        }
        let assoc_count = body[pos] as usize;
        pos += 1;
        let mut associations = Vec::with_capacity(assoc_count);
        let mut truncated = false;
        for _ in 0..assoc_count {
            if wide_index {
                if pos + 2 > body.len() {
                    truncated = true;
                    break;
                }
                let w = u16::from_be_bytes([body[pos], body[pos + 1]]);
                pos += 2;
                associations.push(PropertyAssociation {
                    essential: w & 0x8000 != 0,
                    property_index: w & 0x7FFF,
                });
            } else {
                if pos + 1 > body.len() {
                    truncated = true;
                    break;
                }
                let b = body[pos];
                pos += 1;
                associations.push(PropertyAssociation {
                    essential: b & 0x80 != 0,
                    property_index: (b & 0x7F) as u16,
                });
            }
        }
        out.push(ItemPropertyAssociationEntry {
            item_id,
            associations,
        });
        if truncated {
            break;
        }
    }
    out
}

/// Parse a `grpl` (GroupsListBox, ISO/IEC 23008-12 ยง9.4.2) body โ€” a plain
/// `Box` whose payload is a sequence of `EntityToGroupBox`es (each a
/// `FullBox(grouping_type, version, flags)`). Each child's FourCC is the
/// `grouping_type`; its body is `group_id` (u32) + `num_entities_in_group`
/// (u32) + that many `entity_id`s (u32). A child whose declared
/// `num_entities_in_group` overruns its body is dropped (it contributes no
/// group) rather than reading past the end; the walk continues with the
/// next child. A truncated child header ends the walk cleanly.
pub fn parse_grpl_box(body: &[u8]) -> EntityGroups {
    let mut out = EntityGroups::default();
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = match hdr.payload_size() {
            Some(p) => p as usize,
            None => break,
        };
        let start = cur.position() as usize;
        if start + psz > body.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        let child = &body[start..start + psz];
        if let Some(g) = parse_entity_to_group(hdr.fourcc, child) {
            out.groups.push(g);
        }
    }
    out
}

/// Decode one `EntityToGroupBox` (ยง9.4.3.2) `(grouping_type, body)` where
/// `body` opens with the 4-byte FullBox version/flags word. Returns `None`
/// for a body too short for the two fixed u32 fields or whose
/// `num_entities_in_group` overruns the available bytes.
fn parse_entity_to_group(grouping_type: [u8; 4], body: &[u8]) -> Option<EntityToGroup> {
    // FullBox preamble (4) + group_id (4) + num_entities_in_group (4).
    if body.len() < 12 {
        return None;
    }
    let group_id = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let num = u32::from_be_bytes([body[8], body[9], body[10], body[11]]) as usize;
    let mut pos = 12usize;
    if pos + num * 4 > body.len() {
        return None;
    }
    let mut entity_ids = Vec::with_capacity(num);
    for _ in 0..num {
        entity_ids.push(u32::from_be_bytes([
            body[pos],
            body[pos + 1],
            body[pos + 2],
            body[pos + 3],
        ]));
        pos += 4;
    }
    Some(EntityToGroup {
        grouping_type,
        group_id,
        entity_ids,
    })
}

/// Append the flat `meta_*` metadata keys for a parsed file-level `meta`
/// box (ยง8.11). No keys are emitted for an empty / absent `meta`.
fn surface_meta_items(m: &MetaItems, metadata: &mut Vec<(String, String)>) {
    if m.handler_type == [0; 4] && m.is_empty() {
        return;
    }
    if m.handler_type != [0; 4] {
        metadata.push((
            "meta_handler".to_string(),
            String::from_utf8_lossy(&m.handler_type).to_string(),
        ));
    }
    if let Some(id) = m.primary_item_id {
        metadata.push(("meta_primary_item".to_string(), id.to_string()));
    }
    if let Some(iinf) = m.iinf.as_ref() {
        metadata.push((
            "meta_item_count".to_string(),
            iinf.entries.len().to_string(),
        ));
        for (n, e) in iinf.entries.iter().enumerate() {
            let type_tok = if e.version >= 2 {
                String::from_utf8_lossy(&e.item_type).to_string()
            } else {
                format!("v{}", e.version)
            };
            metadata.push((
                format!("meta_item_{n}"),
                format!("id={} type={} name={}", e.item_id, type_tok, e.item_name),
            ));
        }
    }
    if let Some(iloc) = m.iloc.as_ref() {
        metadata.push(("meta_iloc_count".to_string(), iloc.items.len().to_string()));
        // Surface each item's location summary so a HEIF consumer can spot
        // where an item lives (construction method + extent layout +
        // total length) without downcasting to `MetaItems::iloc`. The
        // exact byte ranges remain on the typed record / `item_byte_ranges`.
        for (n, it) in iloc.items.iter().enumerate() {
            let total_len: u64 = it.extents.iter().map(|e| e.extent_length).sum();
            metadata.push((
                format!("meta_iloc_{n}"),
                format!(
                    "id={} method={} extents={} length={}",
                    it.item_id,
                    it.construction_method,
                    it.extents.len(),
                    total_len
                ),
            ));
        }
    }
    if let Some(iref) = m.iref.as_ref() {
        metadata.push((
            "meta_iref_count".to_string(),
            iref.references.len().to_string(),
        ));
        // Surface each typed reference group so the HEIF relationship graph
        // (thumbnail `thmb`, auxiliary `auxl`, derivation `dimg`,
        // description `cdsc`, pre-derived `base`, predictive `pred`,
        // tile-base `tbas`, scalable-base `exbl`, โ€ฆ) is queryable from the
        // flat channel without downcasting to `MetaItems::iref`.
        for (n, r) in iref.references.iter().enumerate() {
            let to: Vec<String> = r.to_item_ids.iter().map(|id| id.to_string()).collect();
            metadata.push((
                format!("meta_iref_{n}"),
                format!(
                    "type={} from={} to={}",
                    String::from_utf8_lossy(&r.reference_type),
                    r.from_item_id,
                    to.join(",")
                ),
            ));
        }
    }
    if !m.idat.is_empty() {
        metadata.push(("meta_idat_len".to_string(), m.idat.len().to_string()));
    }
    if let Some(fiin) = m.fiin.as_ref() {
        // ยง8.13.2 FD Item Information โ€” surface the partition-entry count
        // plus whether the optional session-group / group-name boxes are
        // present, so an FD-aware consumer can spot the box without
        // reaching into the typed `MetaItems::fiin`.
        metadata.push((
            "meta_fiin_partitions".to_string(),
            fiin.partition_entries.len().to_string(),
        ));
        if let Some(segr) = fiin.session_info.as_ref() {
            metadata.push((
                "meta_fiin_session_groups".to_string(),
                segr.session_groups.len().to_string(),
            ));
        }
        if let Some(gitn) = fiin.group_id_to_name.as_ref() {
            metadata.push((
                "meta_fiin_group_names".to_string(),
                gitn.entries.len().to_string(),
            ));
        }
    }
    if let Some(iprp) = m.iprp.as_ref() {
        // ISO/IEC 23008-12 ยง9.3 ItemPropertiesBox โ€” surface a compact
        // summary: the property-list size, a per-property type token, and
        // each item's resolved association list. A consumer wanting the
        // typed records reaches `MetaItems::iprp` / `properties_for`.
        metadata.push((
            "meta_iprp_property_count".to_string(),
            iprp.properties.len().to_string(),
        ));
        for (n, p) in iprp.properties.iter().enumerate() {
            metadata.push((format!("meta_iprp_property_{n}"), item_property_token(p)));
        }
        for (n, e) in iprp.associations.iter().enumerate() {
            // Each association rendered as `idx` or `idx*` (the `*` marks
            // an essential property), space-separated, in `ipma` order.
            let assoc: Vec<String> = e
                .associations
                .iter()
                .map(|a| {
                    if a.essential {
                        format!("{}*", a.property_index)
                    } else {
                        a.property_index.to_string()
                    }
                })
                .collect();
            metadata.push((
                format!("meta_iprp_item_{n}"),
                format!("id={} props={}", e.item_id, assoc.join(",")),
            ));
        }
    }
    if let Some(grpl) = m.grpl.as_ref() {
        // ISO/IEC 23008-12 ยง9.4 GroupsListBox โ€” surface a per-group
        // summary: the group count plus, per group, the grouping type, the
        // group ID, and the mapped entity IDs.
        metadata.push((
            "meta_grpl_group_count".to_string(),
            grpl.groups.len().to_string(),
        ));
        for (n, g) in grpl.groups.iter().enumerate() {
            let ids: Vec<String> = g.entity_ids.iter().map(|e| e.to_string()).collect();
            metadata.push((
                format!("meta_grpl_group_{n}"),
                format!(
                    "type={} id={} entities={}",
                    String::from_utf8_lossy(&g.grouping_type),
                    g.group_id,
                    ids.join(",")
                ),
            ));
        }
    }
}

/// Render one [`ItemProperty`] as a compact metadata token: the property
/// FourCC followed by its salient decoded value(s). Used by the
/// `meta_iprp_property_<n>` summary surface.
fn item_property_token(p: &ItemProperty) -> String {
    match p {
        ItemProperty::Ispe {
            image_width,
            image_height,
        } => format!("ispe {image_width}x{image_height}"),
        ItemProperty::Pixi { bits_per_channel } => {
            let bits: Vec<String> = bits_per_channel.iter().map(|b| b.to_string()).collect();
            format!("pixi {}", bits.join(":"))
        }
        ItemProperty::Rloc {
            horizontal_offset,
            vertical_offset,
        } => format!("rloc {horizontal_offset},{vertical_offset}"),
        ItemProperty::AuxC { aux_type, .. } => format!("auxC {aux_type}"),
        ItemProperty::Irot { angle } => format!("irot {}", *angle as u32 * 90),
        ItemProperty::Imir { axis } => {
            format!("imir {}", if *axis == 0 { "v" } else { "h" })
        }
        ItemProperty::Lsel { layer_id } => format!("lsel {layer_id}"),
        ItemProperty::Pasp(r) => format!("pasp {}:{}", r.h_spacing, r.v_spacing),
        ItemProperty::Clap(r) => format!("clap {}/{}", r.width_n, r.width_d),
        ItemProperty::Colr(c) => match c {
            ColrRecord::Nclx {
                colour_primaries,
                transfer_characteristics,
                matrix_coefficients,
                ..
            } => format!(
                "colr nclx {colour_primaries}/{transfer_characteristics}/{matrix_coefficients}"
            ),
            ColrRecord::RestrictedIcc(d) => format!("colr rICC {}", d.len()),
            ColrRecord::UnrestrictedIcc(d) => format!("colr prof {}", d.len()),
            ColrRecord::Other { colour_type, .. } => {
                format!("colr {}", String::from_utf8_lossy(colour_type))
            }
        },
        ItemProperty::Udes { name, lang, .. } => {
            if lang.is_empty() {
                format!("udes {name}")
            } else {
                format!("udes [{lang}] {name}")
            }
        }
        ItemProperty::Altt { alt_text, .. } => format!("altt {alt_text}"),
        ItemProperty::Iscl {
            target_width_numerator,
            target_width_denominator,
            target_height_numerator,
            target_height_denominator,
        } => format!(
            "iscl {target_width_numerator}/{target_width_denominator}x{target_height_numerator}/{target_height_denominator}"
        ),
        ItemProperty::Rref { reference_types } => {
            let types: Vec<String> = reference_types
                .iter()
                .map(|t| String::from_utf8_lossy(t).to_string())
                .collect();
            format!("rref {}", types.join(","))
        }
        ItemProperty::Crtt { creation_time } => format!("crtt {creation_time}"),
        ItemProperty::Mdft { modification_time } => format!("mdft {modification_time}"),
        ItemProperty::Other { box_type, .. } => String::from_utf8_lossy(box_type).to_string(),
    }
}

// ---------------------------------------------------------------------------
// ยง8.11 meta-item box builders (write counterparts to the parsers above).
// Each builder is the byte-exact inverse of its parser: a record produced
// by `parse_*` re-serialises identically, and the muxer / a caller
// assembling a HEIF `meta` box can emit valid ยง8.11 boxes.
// ---------------------------------------------------------------------------

/// Append `value` as a big-endian integer of `n` bytes (n โˆˆ {0, 4, 8})
/// to `out`. A width of 0 writes nothing (the ยง8.11.3.3 implied-value
/// convention). The low `n*8` bits of `value` are written.
fn write_sized_be(out: &mut Vec<u8>, value: u64, n: usize) {
    if n == 0 {
        return;
    }
    let bytes = value.to_be_bytes();
    out.extend_from_slice(&bytes[8 - n..]);
}

/// Wrap a `body` in a complete `[size:u32][fourcc]` box header (32-bit
/// size form). The ยง4.2 largesize form is not needed for the small meta
/// boxes this module emits.
fn wrap_box(fourcc: &[u8; 4], body: &[u8]) -> Vec<u8> {
    let total = (8 + body.len()) as u32;
    let mut v = Vec::with_capacity(8 + body.len());
    v.extend_from_slice(&total.to_be_bytes());
    v.extend_from_slice(fourcc);
    v.extend_from_slice(body);
    v
}

/// Build a complete `iloc` (ItemLocationBox, ISO/IEC 14496-12 ยง8.11.3)
/// box. Field widths are taken from the record verbatim, so the output
/// round-trips byte-exact through [`parse_iloc_box`].
///
/// Returns `None` when the record is internally inconsistent in a way
/// that would not round-trip: a `*_size` outside {0, 4, 8}, a version 0
/// item carrying a non-zero `construction_method` (the field does not
/// exist on the wire for v0), or an `index_size > 0` on a version 0 box
/// (the index nibble is reserved for v0).
pub fn build_iloc_box(b: &IlocBox) -> Option<Vec<u8>> {
    for &s in &[
        b.offset_size,
        b.length_size,
        b.base_offset_size,
        b.index_size,
    ] {
        if s != 0 && s != 4 && s != 8 {
            return None;
        }
    }
    if b.version > 2 {
        return None;
    }
    if b.version == 0 && b.index_size != 0 {
        return None;
    }
    let mut body = Vec::new();
    body.push(b.version);
    body.extend_from_slice(&[0, 0, 0]); // flags
    body.push((b.offset_size << 4) | (b.length_size & 0x0F));
    let lo = if b.version == 1 || b.version == 2 {
        b.index_size & 0x0F
    } else {
        0
    };
    body.push((b.base_offset_size << 4) | lo);
    if b.version < 2 {
        write_sized_be(&mut body, b.items.len() as u64, 2);
    } else {
        write_sized_be(&mut body, b.items.len() as u64, 4);
    }
    for it in &b.items {
        if b.version < 2 {
            write_sized_be(&mut body, it.item_id as u64, 2);
        } else {
            write_sized_be(&mut body, it.item_id as u64, 4);
        }
        if b.version == 1 || b.version == 2 {
            if it.construction_method > 0x0F {
                return None;
            }
            // 12 reserved bits + 4-bit construction_method.
            write_sized_be(&mut body, it.construction_method as u64, 2);
        } else if it.construction_method != 0 {
            return None;
        }
        write_sized_be(&mut body, it.data_reference_index as u64, 2);
        write_sized_be(&mut body, it.base_offset, b.base_offset_size as usize);
        write_sized_be(&mut body, it.extents.len() as u64, 2);
        for ex in &it.extents {
            if (b.version == 1 || b.version == 2) && b.index_size > 0 {
                write_sized_be(&mut body, ex.extent_index, b.index_size as usize);
            }
            write_sized_be(&mut body, ex.extent_offset, b.offset_size as usize);
            write_sized_be(&mut body, ex.extent_length, b.length_size as usize);
        }
    }
    Some(wrap_box(&ILOC, &body))
}

/// Build a complete `pitm` (PrimaryItemBox, ISO/IEC 14496-12 ยง8.11.4)
/// box. Uses version 0 (16-bit `item_ID`) when the ID fits in 16 bits,
/// else version 1 (32-bit). Round-trips through [`parse_pitm_box`].
pub fn build_pitm_box(item_id: u32) -> Vec<u8> {
    let mut body = Vec::new();
    if item_id <= u16::MAX as u32 {
        body.push(0); // version 0
        body.extend_from_slice(&[0, 0, 0]);
        write_sized_be(&mut body, item_id as u64, 2);
    } else {
        body.push(1); // version 1
        body.extend_from_slice(&[0, 0, 0]);
        write_sized_be(&mut body, item_id as u64, 4);
    }
    wrap_box(&PITM, &body)
}

/// Build a single `infe` (ItemInfoEntry, ISO/IEC 14496-12 ยง8.11.6.2)
/// box from an [`ItemInfoEntry`] record. Returns `None` for an
/// unsupported version (only 0/1/2/3 are defined) or a name/type
/// string containing an embedded NUL (which would corrupt the
/// NUL-terminated framing).
fn build_infe(e: &ItemInfoEntry) -> Option<Vec<u8>> {
    if e.version > 3 {
        return None;
    }
    for s in [&e.item_name, &e.content_type, &e.content_encoding] {
        if s.as_bytes().contains(&0) {
            return None;
        }
    }
    let mut body = vec![e.version, 0, 0, 0];
    if e.version == 0 || e.version == 1 {
        write_sized_be(&mut body, e.item_id as u64, 2);
        write_sized_be(&mut body, e.protection_index as u64, 2);
        body.extend_from_slice(e.item_name.as_bytes());
        body.push(0);
        body.extend_from_slice(e.content_type.as_bytes());
        body.push(0);
        if !e.content_encoding.is_empty() {
            body.extend_from_slice(e.content_encoding.as_bytes());
            body.push(0);
        }
    } else {
        if e.version == 2 {
            write_sized_be(&mut body, e.item_id as u64, 2);
        } else {
            write_sized_be(&mut body, e.item_id as u64, 4);
        }
        write_sized_be(&mut body, e.protection_index as u64, 2);
        body.extend_from_slice(&e.item_type);
        body.extend_from_slice(e.item_name.as_bytes());
        body.push(0);
        if &e.item_type == b"mime" {
            body.extend_from_slice(e.content_type.as_bytes());
            body.push(0);
            if !e.content_encoding.is_empty() {
                body.extend_from_slice(e.content_encoding.as_bytes());
                body.push(0);
            }
        } else if &e.item_type == b"uri " {
            body.extend_from_slice(e.content_encoding.as_bytes());
            body.push(0);
        }
    }
    Some(wrap_box(&INFE, &body))
}

/// Build a complete `iinf` (ItemInfoBox, ISO/IEC 14496-12 ยง8.11.6) box
/// from an [`IinfBox`]. Uses version 0 (16-bit `entry_count`) when the
/// entry count fits in 16 bits, else version 1 (32-bit). Returns `None`
/// if any child `infe` cannot be serialised. Round-trips through
/// [`parse_iinf_box`].
pub fn build_iinf_box(b: &IinfBox) -> Option<Vec<u8>> {
    let mut body = Vec::new();
    if b.entries.len() <= u16::MAX as usize {
        body.push(0); // version 0
        body.extend_from_slice(&[0, 0, 0]);
        write_sized_be(&mut body, b.entries.len() as u64, 2);
    } else {
        body.push(1); // version 1
        body.extend_from_slice(&[0, 0, 0]);
        write_sized_be(&mut body, b.entries.len() as u64, 4);
    }
    for e in &b.entries {
        body.extend_from_slice(&build_infe(e)?);
    }
    Some(wrap_box(&IINF, &body))
}

/// Build a complete `iref` (ItemReferenceBox, ISO/IEC 14496-12 ยง8.11.12)
/// box from an [`IrefBox`]. The record's `version` selects 16-bit (v0)
/// or 32-bit (v1) item IDs. Returns `None` for an unsupported version
/// or a reference group whose `reference_count` overflows 16 bits.
/// Round-trips through [`parse_iref_box`].
pub fn build_iref_box(b: &IrefBox) -> Option<Vec<u8>> {
    if b.version > 1 {
        return None;
    }
    let id_bytes = if b.version == 0 { 2 } else { 4 };
    let mut body = vec![b.version, 0, 0, 0];
    for r in &b.references {
        if r.to_item_ids.len() > u16::MAX as usize {
            return None;
        }
        let mut sub = Vec::new();
        write_sized_be(&mut sub, r.from_item_id as u64, id_bytes);
        write_sized_be(&mut sub, r.to_item_ids.len() as u64, 2);
        for &to in &r.to_item_ids {
            write_sized_be(&mut sub, to as u64, id_bytes);
        }
        body.extend_from_slice(&wrap_box(&r.reference_type, &sub));
    }
    Some(wrap_box(&IREF, &body))
}

/// Build a complete `idat` (ItemDataBox, ISO/IEC 14496-12 ยง8.11.11) box
/// wrapping the raw item bytes.
pub fn build_idat_box(data: &[u8]) -> Vec<u8> {
    wrap_box(&IDAT, data)
}

// ---------------------------------------------------------------------------
// HEIF / MIAF item-properties builders (ISO/IEC 23008-12 ยง9.3 / ยง6.5). The
// byte-exact inverses of `parse_iprp_box` / `parse_ipco_box` /
// `parse_ipma_box` / `parse_item_property`, so a caller assembling a HEIF
// `meta` from typed records re-emits the same bytes the parsers decode.
// ---------------------------------------------------------------------------

/// Serialise one [`ItemProperty`] into a complete property box (header +
/// body). The inverse of [`parse_item_property`]; the `ItemFullProperty`
/// types (`ispe` / `pixi` / `rloc` / `auxC`) emit the 4-byte FullBox
/// version/flags preamble (version 0, flags 0 โ€” `auxC` likewise writes
/// flags 0). [`ItemProperty::Other`] re-emits its preserved bytes verbatim.
pub fn build_item_property(p: &ItemProperty) -> Vec<u8> {
    match p {
        ItemProperty::Ispe {
            image_width,
            image_height,
        } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.extend_from_slice(&image_width.to_be_bytes());
            body.extend_from_slice(&image_height.to_be_bytes());
            wrap_box(&ISPE, &body)
        }
        ItemProperty::Pixi { bits_per_channel } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.push(bits_per_channel.len() as u8);
            body.extend_from_slice(bits_per_channel);
            wrap_box(&PIXI, &body)
        }
        ItemProperty::Rloc {
            horizontal_offset,
            vertical_offset,
        } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.extend_from_slice(&horizontal_offset.to_be_bytes());
            body.extend_from_slice(&vertical_offset.to_be_bytes());
            wrap_box(&RLOC, &body)
        }
        ItemProperty::AuxC {
            aux_type,
            aux_subtype,
        } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.extend_from_slice(aux_type.as_bytes());
            body.push(0); // NULL terminator
            body.extend_from_slice(aux_subtype);
            wrap_box(&AUXC, &body)
        }
        ItemProperty::Irot { angle } => wrap_box(&IROT, &[angle & 0x03]),
        ItemProperty::Imir { axis } => wrap_box(&IMIR, &[axis & 0x01]),
        ItemProperty::Lsel { layer_id } => wrap_box(&LSEL, &layer_id.to_be_bytes()),
        ItemProperty::Pasp(r) => build_pasp_box(r),
        ItemProperty::Clap(r) => build_clap_box(r),
        ItemProperty::Colr(c) => build_colr_box(c),
        ItemProperty::Udes {
            lang,
            name,
            description,
            tags,
        } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            for s in [lang, name, description, tags] {
                body.extend_from_slice(s.as_bytes());
                body.push(0);
            }
            wrap_box(&UDES, &body)
        }
        ItemProperty::Altt { alt_text, alt_lang } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            for s in [alt_text, alt_lang] {
                body.extend_from_slice(s.as_bytes());
                body.push(0);
            }
            wrap_box(&ALTT, &body)
        }
        ItemProperty::Iscl {
            target_width_numerator,
            target_width_denominator,
            target_height_numerator,
            target_height_denominator,
        } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.extend_from_slice(&target_width_numerator.to_be_bytes());
            body.extend_from_slice(&target_width_denominator.to_be_bytes());
            body.extend_from_slice(&target_height_numerator.to_be_bytes());
            body.extend_from_slice(&target_height_denominator.to_be_bytes());
            wrap_box(&ISCL, &body)
        }
        ItemProperty::Rref { reference_types } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.push(reference_types.len() as u8);
            for rt in reference_types {
                body.extend_from_slice(rt);
            }
            wrap_box(&RREF, &body)
        }
        ItemProperty::Crtt { creation_time } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.extend_from_slice(&creation_time.to_be_bytes());
            wrap_box(&CRTT, &body)
        }
        ItemProperty::Mdft { modification_time } => {
            let mut body = vec![0u8; 4]; // FullBox(0,0)
            body.extend_from_slice(&modification_time.to_be_bytes());
            wrap_box(&MDFT, &body)
        }
        ItemProperty::Other { box_type, body } => wrap_box(box_type, body),
    }
}

/// Build an `ipco` (ItemPropertyContainerBox, ISO/IEC 23008-12 ยง9.3.1)
/// from the implicitly-indexed property list โ€” each property box in order.
/// The inverse of [`parse_ipco_box`].
pub fn build_ipco_box(properties: &[ItemProperty]) -> Vec<u8> {
    let mut body = Vec::new();
    for p in properties {
        body.extend_from_slice(&build_item_property(p));
    }
    wrap_box(&IPCO, &body)
}

/// Build a single `ipma` (ItemPropertyAssociation, ISO/IEC 23008-12
/// ยง9.3.1) box covering all `entries`. The item-ID width and
/// `property_index` width are chosen as the narrowest that hold every
/// value: version 1 (32-bit item IDs) when any item ID exceeds 0xFFFF;
/// `flags & 1` (15-bit index) when any `property_index` exceeds 0x7F. The
/// inverse of [`parse_ipma_box`]. Per ยง9.3.1 entries must be ordered by
/// increasing `item_ID`; the builder sorts a copy so a caller need not.
/// Returns `None` if any `property_index` exceeds the 15-bit wire ceiling
/// (0x7FFF) โ€” that would not round-trip.
pub fn build_ipma_box(entries: &[ItemPropertyAssociationEntry]) -> Option<Vec<u8>> {
    let mut sorted: Vec<&ItemPropertyAssociationEntry> = entries.iter().collect();
    sorted.sort_by_key(|e| e.item_id);
    let need_wide_id = sorted.iter().any(|e| e.item_id > 0xFFFF);
    let mut need_wide_index = false;
    for e in &sorted {
        for a in &e.associations {
            if a.property_index > 0x7FFF {
                return None;
            }
            if a.property_index > 0x7F {
                need_wide_index = true;
            }
        }
    }
    let version: u8 = if need_wide_id { 1 } else { 0 };
    let flags: u32 = if need_wide_index { 1 } else { 0 };
    let mut body = Vec::new();
    body.push(version);
    body.extend_from_slice(&flags.to_be_bytes()[1..]); // 24-bit flags
    body.extend_from_slice(&(sorted.len() as u32).to_be_bytes());
    for e in &sorted {
        if version == 0 {
            body.extend_from_slice(&(e.item_id as u16).to_be_bytes());
        } else {
            body.extend_from_slice(&e.item_id.to_be_bytes());
        }
        body.push(e.associations.len() as u8);
        for a in &e.associations {
            if need_wide_index {
                let w = (if a.essential { 0x8000 } else { 0 }) | (a.property_index & 0x7FFF);
                body.extend_from_slice(&w.to_be_bytes());
            } else {
                let b = (if a.essential { 0x80 } else { 0 }) | (a.property_index as u8 & 0x7F);
                body.push(b);
            }
        }
    }
    Some(wrap_box(&IPMA, &body))
}

/// Build a complete `iprp` (ItemPropertiesBox, ISO/IEC 23008-12 ยง9.3.1)
/// box from typed [`ItemProperties`] โ€” the `ipco` property list followed
/// by one `ipma` association box. The byte-exact inverse of
/// [`parse_iprp_box`] for the single-`ipma` shape this builder emits.
/// Returns `None` when the association table cannot round-trip (a
/// `property_index` past the 15-bit ceiling).
pub fn build_iprp_box(p: &ItemProperties) -> Option<Vec<u8>> {
    let mut body = build_ipco_box(&p.properties);
    if !p.associations.is_empty() {
        body.extend_from_slice(&build_ipma_box(&p.associations)?);
    }
    Some(wrap_box(&IPRP, &body))
}

/// Build a single `EntityToGroupBox` (ISO/IEC 23008-12 ยง9.4.3.2) from an
/// [`EntityToGroup`]. The box type is the record's `grouping_type`; the
/// body is the 4-byte FullBox preamble (version 0, flags 0) + `group_id`
/// (u32) + `num_entities_in_group` (u32) + the `entity_id` array. The
/// byte-exact inverse of [`parse_entity_to_group`].
pub fn build_entity_to_group_box(g: &EntityToGroup) -> Vec<u8> {
    let mut body = vec![0u8; 4]; // FullBox(0, 0)
    body.extend_from_slice(&g.group_id.to_be_bytes());
    body.extend_from_slice(&(g.entity_ids.len() as u32).to_be_bytes());
    for &e in &g.entity_ids {
        body.extend_from_slice(&e.to_be_bytes());
    }
    wrap_box(&g.grouping_type, &body)
}

/// Build a complete `grpl` (GroupsListBox, ISO/IEC 23008-12 ยง9.4.2) box
/// from typed [`EntityGroups`] โ€” one `EntityToGroupBox` per group, in
/// slice order. The byte-exact inverse of [`parse_grpl_box`].
pub fn build_grpl_box(g: &EntityGroups) -> Vec<u8> {
    let mut body = Vec::new();
    for grp in &g.groups {
        body.extend_from_slice(&build_entity_to_group_box(grp));
    }
    wrap_box(&GRPL, &body)
}

// ---------------------------------------------------------------------------
// ยง8.11.7 / ยง8.11.8 โ€” Additional Metadata Container Box (`meco`) and
// Metabox Relation Box (`mere`). A `meco` (at File / `moov` / `trak`
// level) holds one or more additional `meta` boxes โ€” each with a distinct
// handler type โ€” that complement the primary `meta`, plus zero or more
// `mere` boxes describing how two same-level `meta` boxes relate.
// ---------------------------------------------------------------------------

/// One `mere` MetaboxRelationBox (ISO/IEC 14496-12 ยง8.11.8). Names two
/// same-level `meta` boxes by their `hdlr` handler types and records the
/// relation between them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MereRelation {
    /// The first related `meta` box's handler type (ยง8.4.3), verbatim.
    pub first_metabox_handler_type: [u8; 4],
    /// The second related `meta` box's handler type, verbatim.
    pub second_metabox_handler_type: [u8; 4],
    /// Relation enum (ยง8.11.8.3): 1 unknown, 2 unrelated, 3 complementary,
    /// 4 overlapping (neither preferred), 5 second is a subset of the
    /// first (first preferred). Carried verbatim โ€” values outside 1..=5
    /// are preserved rather than rejected so a validator can flag them.
    pub metabox_relation: u8,
}

/// Decoded `meco` AdditionalMetadataContainerBox (ISO/IEC 14496-12
/// ยง8.11.7): the additional `meta` boxes plus the `mere` relation boxes
/// that the container holds. The additional `meta` boxes are captured as
/// fully-parsed [`MetaItems`] (handler type + any ยง8.11 item
/// infrastructure they carry); a `meco`-resident `meta` is required to
/// carry a primary item / primary data box (ยง8.11.7.1).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MecoBox {
    /// The additional `meta` boxes, in file order. Each must have a
    /// handler type distinct from the primary `meta` and from each other
    /// (ยง8.11.7.1), but the parser does not enforce that โ€” it captures
    /// whatever is present.
    pub metas: Vec<MetaItems>,
    /// The `mere` relation boxes, in file order.
    pub relations: Vec<MereRelation>,
}

impl MecoBox {
    /// True when the container holds neither an additional `meta` nor a
    /// `mere` โ€” e.g. an empty / malformed `meco`.
    pub fn is_empty(&self) -> bool {
        self.metas.is_empty() && self.relations.is_empty()
    }
}

/// Parse a `mere` body (the bytes after the `[size][mere]` header).
/// `None` on truncation. The ยง8.11.8.2 body is two 32-bit handler-type
/// codes plus a 1-byte relation, after the FullBox preamble.
pub fn parse_mere_box(body: &[u8]) -> Option<MereRelation> {
    // FullBox preamble (4) + first(4) + second(4) + relation(1) = 13.
    if body.len() < 13 {
        return None;
    }
    let mut first = [0u8; 4];
    let mut second = [0u8; 4];
    first.copy_from_slice(&body[4..8]);
    second.copy_from_slice(&body[8..12]);
    Some(MereRelation {
        first_metabox_handler_type: first,
        second_metabox_handler_type: second,
        metabox_relation: body[12],
    })
}

/// Serialise a `mere` box. The byte-exact inverse of [`parse_mere_box`]
/// (FullBox version 0, flags 0).
pub fn build_mere_box(r: &MereRelation) -> Vec<u8> {
    let mut body = Vec::with_capacity(13);
    body.extend_from_slice(&[0u8; 4]); // version/flags
    body.extend_from_slice(&r.first_metabox_handler_type);
    body.extend_from_slice(&r.second_metabox_handler_type);
    body.push(r.metabox_relation);
    wrap_box(&MERE, &body)
}

/// Parse a `meco` body. Walks its child boxes, decoding each `meta` into
/// a [`MetaItems`] and each `mere` into a [`MereRelation`]; other boxes
/// are ignored. A `meta` child's body opens with the FullBox preamble,
/// matching the top-level `meta` walk.
pub fn parse_meco_box(body: &[u8]) -> MecoBox {
    let mut out = MecoBox::default();
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let start = cur.position() as usize;
        if start + psz > body.len() {
            break;
        }
        cur.set_position((start + psz) as u64);
        let child = &body[start..start + psz];
        match hdr.fourcc {
            META => out.metas.push(parse_meta_items(child)),
            MERE => {
                if let Some(r) = parse_mere_box(child) {
                    out.relations.push(r);
                }
            }
            _ => {}
        }
    }
    out
}

fn parse_trak(body: &[u8], file_size: u64) -> Result<Option<Track>> {
    let mut t = Track {
        track_id: 0,
        media_type: MediaType::Unknown,
        codec_id_fourcc: [0; 4],
        timescale: 0,
        duration: None,
        channels: None,
        sample_rate: None,
        sample_size_bits: None,
        width: None,
        height: None,
        extradata: Vec::new(),
        esds_oti: None,
        stts: Vec::new(),
        stsc: Vec::new(),
        stsz: Vec::new(),
        chunk_offsets: Vec::new(),
        stss: Vec::new(),
        ctts: Vec::new(),
        elst: Vec::new(),
        elst_timeline: ElstTimeline::default(),
        trex: TrexDefaults::default(),
        protection_scheme: None,
        tenc: None,
        piff_tenc: None,
        tref: Vec::new(),
        trgr: Vec::new(),
        elng: None,
        kinds: Vec::new(),
        copyrights: Vec::new(),
        tsel: None,
        sub_tracks: Vec::new(),
        cslg: None,
        vmhd: None,
        amve: None,
        stvi: None,
        btrt: None,
        pasp: None,
        clap: None,
        colr: None,
        hmhd: None,
        gmin: None,
        tcmi: None,
        tmcd: None,
        text_entry: None,
        load_settings: None,
        rtp_hint: None,
        mpeg2ts_hint: None,
        hint_stats: crate::hint::HintStatistics::default(),
        dref: None,
        stsh: Vec::new(),
        sbgp: Vec::new(),
        sgpd: Vec::new(),
        csgp: Vec::new(),
        sdtp: Vec::new(),
        stdp: Vec::new(),
        padb: Vec::new(),
        subs: Vec::new(),
        saiz: Vec::new(),
        saio: Vec::new(),
        stsd_entries: Vec::new(),
    };
    let mut has_media = false;
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            TKHD => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_tkhd(&sub, &mut t)?;
            }
            MDIA => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_mdia(&sub, &mut t, file_size)?;
                has_media = true;
            }
            EDTS => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_edts(&sub, &mut t)?;
            }
            TREF => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_tref(&sub, &mut t)?;
            }
            TRGR => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_trgr(&sub, &mut t)?;
            }
            LOAD => {
                // QuickTime Track Load Settings Atom: keep the first
                // parseable instance; a malformed one is dropped
                // (informational) so the trak walk never aborts.
                let sub = read_bytes_vec(&mut cur, psz)?;
                if t.load_settings.is_none() {
                    t.load_settings = parse_load_settings(&sub);
                }
            }
            UDTA => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_track_udta(&sub, &mut t);
            }
            _ => {
                skip_cursor_bytes(&mut cur, psz);
            }
        }
    }
    if has_media {
        Ok(Some(t))
    } else {
        Ok(None)
    }
}

/// Walk a *track-level* `udta` body and pick up any boxes whose semantics
/// are per-track rather than per-movie. The moov-level `udta` parser
/// (`parse_udta`) handles file-wide 3GPP / iTunes metadata; the
/// track-level container additionally hosts `kind` (ยง8.10.4), `tsel`
/// (ยง8.10.3), and `cprt` (ยง8.10.2 โ€” per-track copyright). The `cprt`
/// handler here is the BMFF typed-accessor path that preserves the
/// 16-bit packed ISO 639-2/T language code alongside the notice โ€” the
/// 3GPP-style `udta` aggregator in `parse_udta` lumps `cprt` into the
/// generic `(key, value)` metadata channel and drops the language tag.
/// Other children (e.g. legacy `titl` overrides) are skipped so a
/// future round can add them without changing the entry point.
fn parse_track_udta(body: &[u8], t: &mut Track) {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        if cur.position() as usize + psz > body.len() {
            break;
        }
        let start = cur.position() as usize;
        cur.set_position((start + psz) as u64);
        match hdr.fourcc {
            KIND => parse_kind(&body[start..start + psz], t),
            TSEL => parse_tsel(&body[start..start + psz], t),
            STRK => parse_strk(&body[start..start + psz], t),
            CPRT => parse_cprt(&body[start..start + psz], t),
            // ยง9.1.5 โ€” `hinf` Hint Statistics Box (in a hint track's
            // udta). First one wins.
            HINF if t.hint_stats.is_empty() => {
                t.hint_stats = crate::hint::parse_hinf_box(&body[start..start + psz]);
            }
            _ => {
                // Other track-udta children (e.g. legacy `titl` overrides)
                // are skipped โ€” file-wide metadata is collected from the
                // moov-level udta by `parse_udta`.
            }
        }
    }
}

/// ยง8.10.2 โ€” `cprt` (CopyrightBox) typed accessor. FullBox preamble
/// (1 version + 3 flags) followed by a 16-bit packed language word and
/// then the NULL-terminated notice string.
///
/// Language decoding (ยง8.10.2.3): the 16-bit big-endian word splits as
/// `1 pad bit + 5 * 3` so the three 5-bit fields are read MSB-first; each
/// field equals `(ASCII - 0x60)` for one lower-case ISO 639-2/T character.
/// We reverse the offset to recover the literal character. A value
/// outside `0x01..=0x1A` (i.e. not a valid 'a'..'z' offset) is left in
/// the raw bits โ€” the spec confines well-formed inputs to lowercase
/// letters, so an out-of-range nibble signals a producer that emitted
/// a zero / sentinel word; the reader records the literal decoded bytes
/// for the caller to recognise.
///
/// Notice decoding (ยง8.10.2.3): the bytes immediately after the language
/// word are the C-string notice. When the first two bytes are the
/// UTF-16 BOM (0xFE 0xFF) the remainder is interpreted as UTF-16BE per
/// the spec; otherwise the bytes are UTF-8. In both cases the trailing
/// NUL terminator is stripped before storage. An empty notice (just a
/// terminator) is preserved as an empty string โ€” that still represents
/// a well-formed declaration of language and is not the same as the
/// absence of a `cprt` box.
///
/// Robustness: a non-zero FullBox version is unknown to this spec
/// revision and the box is dropped; a body too short to hold the
/// FullBox + language word is dropped; a notice that fails UTF-8
/// validation is replaced lossily (matching `decode_utf8_or_utf16`'s
/// posture) so a corrupt notice never aborts the demux.
fn parse_cprt(body: &[u8], t: &mut Track) {
    // FullBox preamble (1 version + 3 flags) + 16-bit packed language.
    if body.len() < 6 {
        return;
    }
    let version = body[0];
    if version != 0 {
        // ยง8.10.2.2 pins the box to version 0.
        return;
    }
    // 16-bit packed language word: bit 15 is the pad, then three 5-bit
    // characters. Each 5-bit value is (ASCII - 0x60); reverse the offset
    // to recover the literal lowercase ASCII letter (a..z = 0x61..0x7A,
    // offsets 0x01..0x1A).
    let packed = u16::from_be_bytes([body[4], body[5]]);
    let c0 = ((packed >> 10) & 0x1F) as u8;
    let c1 = ((packed >> 5) & 0x1F) as u8;
    let c2 = (packed & 0x1F) as u8;
    let language = [c0 + 0x60, c1 + 0x60, c2 + 0x60];
    // Notice: UTF-16BE if it opens with the BOM (0xFE 0xFF), UTF-8
    // otherwise. Strip the trailing NUL terminator per ยง8.10.2.3.
    let notice = decode_utf8_or_utf16(&body[6..]);
    t.copyrights.push(CopyrightRecord { language, notice });
}

/// ยง8.10.4 โ€” `kind` (KindBox). FullBox preamble (version 0, flags 0)
/// followed by two NULL-terminated UTF-8 C strings: `schemeURI` then
/// `value`. Per ยง8.10.4.3 the URI alone identifies the kind when no
/// value follows; when a value is present the URI identifies the
/// naming scheme and `value` is the name from that scheme.
///
/// Spec quirk: both strings are stored with their terminators, so a
/// well-formed box body is at least `4 (FullBox) + 1 (URI NUL) +
/// 1 (value NUL) = 6` bytes. A box too short to hold both terminators
/// is tolerated by reading whatever fits โ€” the box is informational
/// and a malformed entry should not abort the demux. Multiple `kind`
/// boxes may appear in a single track-level `udta`; each is appended
/// (the spec explicitly allows "More than one of these" with different
/// schemes โ€” e.g. one DASH role plus one iTunes role).
fn parse_kind(body: &[u8], t: &mut Track) {
    // FullBox preamble (1 version + 3 flags).
    if body.len() < 4 {
        return;
    }
    let s = &body[4..];
    // Split at first NUL: that is the schemeURI terminator. If no NUL
    // is found, treat the entire remainder as the URI and `value` as
    // empty (tolerant read; matches `parse_elng`'s posture).
    let uri_end = s.iter().position(|&b| b == 0).unwrap_or(s.len());
    let uri = match std::str::from_utf8(&s[..uri_end]) {
        Ok(u) => u.to_string(),
        Err(_) => return,
    };
    // The value string starts immediately after the URI's NUL (if any).
    // Take everything up to the next NUL; an absent NUL means "read to
    // end of box". Both an explicitly-empty value (URI\0\0) and an
    // absent value (URI\0 with nothing after) decode to "".
    let value = if uri_end >= s.len() {
        String::new()
    } else {
        let rest = &s[uri_end + 1..];
        let val_end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
        match std::str::from_utf8(&rest[..val_end]) {
            Ok(v) => v.to_string(),
            Err(_) => return,
        }
    };
    // ยง8.10.4.3 โ€” at least the URI must identify *something*. An
    // empty URI yields a useless entry; drop it rather than surfacing
    // a bogus kind on `params.options`.
    if uri.is_empty() {
        return;
    }
    t.kinds.push((uri, value));
}

/// ยง8.10.3 โ€” `tsel` (TrackSelectionBox).
///
/// Spec syntax (ยง8.10.3.3):
/// ```text
/// aligned(8) class TrackSelectionBox
/// extends FullBox('tsel', version = 0, 0) {
///   template int(32) switch_group = 0;
///   unsigned int(32) attribute_list[]; // to end of the box
/// }
/// ```
///
/// Body layout after the 4-byte FullBox preamble:
///   * 4-byte signed big-endian `switch_group`.
///   * Zero or more 4-byte FourCCs (the `attribute_list`).
///
/// A box with an unknown FullBox version (the spec pins it to 0) or a
/// body too short to hold the FullBox + `switch_group` is silently
/// dropped โ€” the box is informational and a corrupted entry should
/// never abort the demux (mirroring `parse_kind`'s posture).
///
/// Trailing bytes that don't make up a complete 4-byte FourCC are
/// ignored: the spec wording is `attribute_list[]` "to end of the box",
/// so a producer that miscalculated the box size is tolerated by
/// taking only the complete entries (matches the ยง8.7.7 `subs` and
/// ยง8.16.3 `sidx` "trailing partial record" handling elsewhere in this
/// crate).
fn parse_tsel(body: &[u8], t: &mut Track) {
    // FullBox preamble (1 version + 3 flags) plus 4-byte switch_group.
    if body.len() < 8 {
        return;
    }
    let version = body[0];
    if version != 0 {
        // Spec pins it to 0. Drop rather than mis-parse a derived-spec
        // extension we don't recognise.
        return;
    }
    let switch_group = i32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let mut attribute_list = Vec::new();
    let mut i = 8;
    while i + 4 <= body.len() {
        let attr: [u8; 4] = [body[i], body[i + 1], body[i + 2], body[i + 3]];
        attribute_list.push(attr);
        i += 4;
    }
    // A trailing 1..3-byte fragment is silently dropped โ€” see doc note.
    t.tsel = Some(TselBox {
        switch_group,
        attribute_list,
    });
}

/// Serialise a `cprt` (CopyrightBox, ISO/IEC 14496-12 ยง8.10.2) โ€” the
/// byte-exact inverse of [`parse_cprt`] (FullBox version 0, flags 0).
///
/// Layout: 4-byte FullBox preamble, then the 16-bit packed `language`
/// word (bit 15 pad, three 5-bit ISO 639-2/T characters each `ASCII -
/// 0x60`, ยง8.10.2.3), then the NUL-terminated UTF-8 `notice` string.
///
/// `language` must be three lower-case ASCII letters (`'a'..='z'`); a
/// byte outside that range cannot be encoded into the 5-bit field and is
/// rejected. A `notice` containing an embedded NUL is rejected (it would
/// truncate on re-parse). The notice is always written as UTF-8 (the
/// parser also accepts a UTF-16BE BOM form, but the canonical write form
/// is UTF-8).
pub fn build_cprt_box(language: &[u8; 3], notice: &str) -> Option<Vec<u8>> {
    let mut packed: u16 = 0;
    for &ch in language {
        if !ch.is_ascii_lowercase() {
            return None;
        }
        packed = (packed << 5) | u16::from(ch - 0x60);
    }
    if notice.as_bytes().contains(&0) {
        return None;
    }
    let mut body = Vec::with_capacity(4 + 2 + notice.len() + 1);
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    body.extend_from_slice(&packed.to_be_bytes());
    body.extend_from_slice(notice.as_bytes());
    body.push(0); // NUL terminator (ยง8.10.2.3)
    Some(wrap_box(&crate::boxes::CPRT, &body))
}

/// Serialise a `kind` (KindBox, ISO/IEC 14496-12 ยง8.10.4) โ€” the byte-exact
/// inverse of [`parse_kind`] (FullBox version 0, flags 0).
///
/// Layout: 4-byte FullBox preamble, then two NUL-terminated UTF-8 C
/// strings โ€” the `schemeURI` then the `value` (ยง8.10.4.2). The `value`
/// terminator is always written even when empty (`URI\0\0`), which the
/// parser accepts as an explicitly-empty value.
///
/// Rejects an empty `schemeURI` (ยง8.10.4.3 requires the URI to identify
/// the kind; the parser drops a URI-less entry) or either string
/// containing an embedded NUL (it would truncate on re-parse).
pub fn build_kind_box(scheme_uri: &str, value: &str) -> Option<Vec<u8>> {
    if scheme_uri.is_empty() || scheme_uri.as_bytes().contains(&0) || value.as_bytes().contains(&0)
    {
        return None;
    }
    let mut body = Vec::with_capacity(4 + scheme_uri.len() + value.len() + 2);
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    body.extend_from_slice(scheme_uri.as_bytes());
    body.push(0);
    body.extend_from_slice(value.as_bytes());
    body.push(0);
    Some(wrap_box(&crate::boxes::KIND, &body))
}

/// Serialise a `tsel` (TrackSelectionBox, ISO/IEC 14496-12 ยง8.10.3) โ€” the
/// byte-exact inverse of [`parse_tsel`] (FullBox version 0, flags 0).
///
/// Layout: 4-byte FullBox preamble, then the 32-bit signed `switch_group`
/// (ยง8.10.3.3), then the `attribute_list` as a sequence of 4-byte FourCCs
/// to the end of the box.
pub fn build_tsel_box(switch_group: i32, attribute_list: &[[u8; 4]]) -> Vec<u8> {
    let mut body = Vec::with_capacity(8 + attribute_list.len() * 4);
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    body.extend_from_slice(&switch_group.to_be_bytes());
    for attr in attribute_list {
        body.extend_from_slice(attr);
    }
    wrap_box(&crate::boxes::TSEL, &body)
}

/// Render a 4-byte FourCC for surfacing on `params.options`: the printable
/// ASCII string when every byte is non-control valid UTF-8, otherwise an
/// 8-digit lowercase hex fallback. Mirrors the inline closure used by the
/// `tsel_attributes` / `tref_<type>` surfacing so the sub-track attribute
/// and grouping-type tokens read identically.
fn fourcc_token(a: &[u8; 4]) -> String {
    std::str::from_utf8(a)
        .ok()
        .filter(|s| s.chars().all(|c| !c.is_control()))
        .map(|s| s.to_string())
        .unwrap_or_else(|| format!("{:02x}{:02x}{:02x}{:02x}", a[0], a[1], a[2], a[3]))
}

/// ยง8.14.3 โ€” `strk` (Sub Track Box).
///
/// Spec syntax (ยง8.14.3.2): `aligned(8) class SubTrack extends
/// Box('strk') {}` โ€” a plain `Box` (no FullBox preamble) whose body is a
/// container. It holds a mandatory `stri` (Sub Track Information,
/// ยง8.14.4) and a mandatory `strd` (Sub Track Definition, ยง8.14.5). We
/// walk the child boxes, parse the `stri` selection metadata, and recurse
/// one level into `strd` to collect its `stsg` (Sub Track Sample Group,
/// ยง8.14.6) children.
///
/// Robustness: `stri` and `strd` are both mandatory (ยง8.14.4.1 /
/// ยง8.14.5.1), but a `strk` missing one of them โ€” or carrying a malformed
/// `stri` โ€” is tolerated rather than aborting the demux (the box is
/// informational, mirroring `parse_tsel` / `parse_kind`). A `strk` whose
/// `stri` fails to parse contributes no `SubTrack` (there is nothing
/// useful to surface without the selection fields); a present `stri` with
/// a missing or empty `strd` still surfaces the selection metadata with
/// an empty `sample_groups`.
fn parse_strk(body: &[u8], t: &mut Track) {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    let mut info: Option<SubTrack> = None;
    let mut sample_groups: Vec<SubTrackSampleGroup> = Vec::new();
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        if cur.position() as usize + psz > body.len() {
            break;
        }
        let start = cur.position() as usize;
        cur.set_position((start + psz) as u64);
        match hdr.fourcc {
            STRI => info = parse_stri(&body[start..start + psz]),
            STRD => sample_groups = parse_strd(&body[start..start + psz]),
            _ => {
                // Other `strk` children (codec-specific definitions, e.g.
                // SVC/MVC tier boxes from ISO/IEC 14496-15) are skipped โ€”
                // ยง8.14.1 leaves the door open for media-specific
                // definitions a future round can recognise.
            }
        }
    }
    // `stri` is mandatory (ยง8.14.4.1); without it we have no selection
    // metadata to surface, so the whole `strk` is dropped. With it, the
    // `strd/stsg` definitions (which may be empty) are attached.
    if let Some(mut st) = info {
        st.sample_groups = sample_groups;
        t.sub_tracks.push(st);
    }
}

/// ยง8.14.4 โ€” `stri` (Sub Track Information Box).
///
/// Spec syntax (ยง8.14.4.2):
/// ```text
/// aligned(8) class SubTrackInformation
///   extends FullBox('stri', version = 0, 0) {
///   template int(16) switch_group = 0;
///   template int(16) alternate_group = 0;
///   template unsigned int(32) sub_track_ID = 0;
///   unsigned int(32) attribute_list[]; // to the end of the box
/// }
/// ```
///
/// Body layout after the 4-byte FullBox preamble:
///   * 2-byte signed big-endian `switch_group`.
///   * 2-byte signed big-endian `alternate_group`.
///   * 4-byte unsigned big-endian `sub_track_ID`.
///   * Zero or more 4-byte FourCCs (the `attribute_list`).
///
/// Returns `None` for an unknown FullBox version (the spec pins it to 0)
/// or a body too short to hold the FullBox + the three fixed fields. A
/// trailing 1..3-byte fragment that doesn't complete a 4-byte FourCC is
/// ignored ("attribute_list[] to the end of the box"), matching the
/// `parse_tsel` posture.
fn parse_stri(body: &[u8]) -> Option<SubTrack> {
    // FullBox preamble (1 version + 3 flags) + 2 + 2 + 4 fixed fields.
    if body.len() < 12 {
        return None;
    }
    let version = body[0];
    if version != 0 {
        // ยง8.14.4.2 pins the box to version 0.
        return None;
    }
    let switch_group = i16::from_be_bytes([body[4], body[5]]);
    let alternate_group = i16::from_be_bytes([body[6], body[7]]);
    let sub_track_id = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    let mut attribute_list = Vec::new();
    let mut i = 12;
    while i + 4 <= body.len() {
        let attr: [u8; 4] = [body[i], body[i + 1], body[i + 2], body[i + 3]];
        attribute_list.push(attr);
        i += 4;
    }
    Some(SubTrack {
        switch_group,
        alternate_group,
        sub_track_id,
        attribute_list,
        sample_groups: Vec::new(),
    })
}

/// ยง8.14.5 โ€” `strd` (Sub Track Definition Box).
///
/// Spec syntax (ยง8.14.5.2): `aligned(8) class SubTrackDefinition extends
/// Box('strd') {}` โ€” a plain `Box` container holding zero or more `stsg`
/// (ยง8.14.6) for the generic (non-codec-specific) sub-track definition
/// mechanism. Walks the children and returns the parsed `stsg` records in
/// on-disk order. Children other than `stsg` (codec-specific definitions)
/// are skipped.
fn parse_strd(body: &[u8]) -> Vec<SubTrackSampleGroup> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    let mut out = Vec::new();
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur).ok().flatten() {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        if cur.position() as usize + psz > body.len() {
            break;
        }
        let start = cur.position() as usize;
        cur.set_position((start + psz) as u64);
        if hdr.fourcc == STSG {
            if let Some(sg) = parse_stsg(&body[start..start + psz]) {
                out.push(sg);
            }
        }
    }
    out
}

/// ยง8.14.6 โ€” `stsg` (Sub Track Sample Group Box).
///
/// Spec syntax (ยง8.14.6.2):
/// ```text
/// aligned(8) class SubTrackSampleGroupBox extends FullBox('stsg', 0, 0) {
///   unsigned int(32) grouping_type;
///   unsigned int(16) item_count;
///   for (i = 0; i < item_count; i++)
///     unsigned int(32) group_description_index;
/// }
/// ```
///
/// Body layout after the 4-byte FullBox preamble:
///   * 4-byte `grouping_type` FourCC.
///   * 2-byte big-endian `item_count`.
///   * `item_count` 4-byte big-endian `group_description_index` values.
///
/// Returns `None` for an unknown FullBox version, a body too short for
/// the FullBox + `grouping_type` + `item_count`, or a declared
/// `item_count` that overruns the bytes actually present (a truncated
/// index list would lie about which sample groups make up the sub track,
/// so it is rejected rather than silently shortened).
fn parse_stsg(body: &[u8]) -> Option<SubTrackSampleGroup> {
    // FullBox preamble (4) + grouping_type (4) + item_count (2).
    if body.len() < 10 {
        return None;
    }
    let version = body[0];
    if version != 0 {
        // ยง8.14.6.2 pins the box to version 0.
        return None;
    }
    let grouping_type: [u8; 4] = [body[4], body[5], body[6], body[7]];
    let item_count = u16::from_be_bytes([body[8], body[9]]) as usize;
    // Each entry is a 4-byte index; reject a count that overruns the body.
    if body.len() < 10 + item_count * 4 {
        return None;
    }
    let mut group_description_indices = Vec::with_capacity(item_count);
    let mut i = 10;
    for _ in 0..item_count {
        group_description_indices.push(u32::from_be_bytes([
            body[i],
            body[i + 1],
            body[i + 2],
            body[i + 3],
        ]));
        i += 4;
    }
    Some(SubTrackSampleGroup {
        grouping_type,
        group_description_indices,
    })
}

/// Serialise an `stsg` (SubTrackSampleGroupBox, ISO/IEC 14496-12 ยง8.14.6)
/// โ€” the byte-exact inverse of [`parse_stsg`] (FullBox version 0, flags 0).
///
/// Layout: 4-byte FullBox preamble, 4-byte `grouping_type` FourCC, 2-byte
/// big-endian `item_count` (= `indices.len()`), then `item_count` 4-byte
/// big-endian `group_description_index` values (ยง8.14.6.2).
///
/// Returns `None` if `indices.len()` exceeds `u16::MAX` (the on-wire
/// `item_count` is 16-bit).
pub fn build_stsg_box(grouping_type: &[u8; 4], indices: &[u32]) -> Option<Vec<u8>> {
    let item_count: u16 = indices.len().try_into().ok()?;
    let mut body = Vec::with_capacity(6 + indices.len() * 4);
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    body.extend_from_slice(grouping_type);
    body.extend_from_slice(&item_count.to_be_bytes());
    for &idx in indices {
        body.extend_from_slice(&idx.to_be_bytes());
    }
    Some(wrap_box(&STSG, &body))
}

/// Serialise an `stri` (SubTrackInformationBox, ISO/IEC 14496-12 ยง8.14.4)
/// โ€” the byte-exact inverse of [`parse_stri`] (FullBox version 0, flags 0).
///
/// Layout: 4-byte FullBox preamble, 2-byte signed `switch_group`, 2-byte
/// signed `alternate_group`, 4-byte unsigned `sub_track_ID`, then the
/// `attribute_list` as a sequence of 4-byte FourCCs to the end of the box
/// (ยง8.14.4.2).
pub fn build_stri_box(
    switch_group: i16,
    alternate_group: i16,
    sub_track_id: u32,
    attribute_list: &[[u8; 4]],
) -> Vec<u8> {
    let mut body = Vec::with_capacity(12 + attribute_list.len() * 4);
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    body.extend_from_slice(&switch_group.to_be_bytes());
    body.extend_from_slice(&alternate_group.to_be_bytes());
    body.extend_from_slice(&sub_track_id.to_be_bytes());
    for attr in attribute_list {
        body.extend_from_slice(attr);
    }
    wrap_box(&STRI, &body)
}

/// Serialise a complete `strk` (SubTrackBox, ISO/IEC 14496-12 ยง8.14.3)
/// from its mandatory `stri` selection fields plus zero or more
/// `(grouping_type, group_description_indices)` sample groups.
///
/// The `strk` is a plain container box (ยง8.14.3.2). It holds the mandatory
/// `stri` (ยง8.14.4) followed โ€” when `sample_groups` is non-empty โ€” by a
/// single `strd` (SubTrackDefinitionBox, ยง8.14.5) wrapping one `stsg`
/// (ยง8.14.6) per `(grouping_type, indices)` pair, in supplied order. When
/// `sample_groups` is empty no `strd` is emitted (the box is optional and
/// would otherwise be a content-free container). The result re-parses
/// through [`parse_strk`] to the same sub-track record.
///
/// Returns `None` if any sample group's index list exceeds the 16-bit
/// `item_count` cap (propagated from [`build_stsg_box`]).
pub fn build_strk_box(
    switch_group: i16,
    alternate_group: i16,
    sub_track_id: u32,
    attribute_list: &[[u8; 4]],
    sample_groups: &[([u8; 4], Vec<u32>)],
) -> Option<Vec<u8>> {
    let mut body = build_stri_box(switch_group, alternate_group, sub_track_id, attribute_list);
    if !sample_groups.is_empty() {
        let mut strd_body = Vec::new();
        for (grouping_type, indices) in sample_groups {
            strd_body.extend_from_slice(&build_stsg_box(grouping_type, indices)?);
        }
        body.extend_from_slice(&wrap_box(&STRD, &strd_body));
    }
    Some(wrap_box(&STRK, &body))
}

/// ยง8.3.2 โ€” `tkhd` (TrackHeaderBox). We only need `track_ID` for
/// fragmented-MP4 traf-to-track matching; the matrix / w/h preview
/// fields are the visual entry's job.
fn parse_tkhd(body: &[u8], t: &mut Track) -> Result<()> {
    if body.is_empty() {
        return Err(Error::invalid("MP4: tkhd empty"));
    }
    let version = body[0];
    // FullBox header is 4 bytes. v0: 4 created + 4 modified + 4 track_ID.
    // v1: 8 + 8 + 4. After-header offsets:
    let off = if version == 0 { 4 + 8 } else { 4 + 16 };
    if body.len() < off + 4 {
        return Err(Error::invalid("MP4: tkhd too short"));
    }
    t.track_id = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
    Ok(())
}

/// ยง8.3.3 โ€” `tref` (TrackReferenceBox).
///
/// Spec syntax (ยง8.3.3.2):
/// ```text
/// aligned(8) class TrackReferenceBox extends Box('tref') {
/// }
/// aligned(8) class TrackReferenceTypeBox (unsigned int(32) reference_type)
///     extends Box(reference_type) {
///   unsigned int(32) track_IDs[];   // array fills the box
/// }
/// ```
///
/// The outer `tref` is a plain container (no FullBox version/flags) whose
/// children are typed reference boxes. Each child's *FourCC* is the
/// `reference_type` (e.g. `hint`, `cdsc`, `font`, `hind`, `vdep`, `vplx`,
/// `subt`, `chap`, `tmcd`) and its body is a packed array of `u32`
/// `track_ID`s (big-endian per ยง4.2 file-format conventions). The array
/// sizes itself by filling the box payload.
///
/// Per ยง8.3.3.3 `track_ID` is "never zero". We tolerate (skip) zero
/// entries rather than rejecting the file outright โ€” some hand-rolled
/// muxers pad the array.
fn parse_tref(body: &[u8], t: &mut Track) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let child = read_bytes_vec(&mut cur, psz)?;
        // ยง8.3.3.2 โ€” child body is "unsigned int(32) track_IDs[]"; size
        // not stored, derived from box length. Reject malformed
        // sub-boxes whose body isn't a whole number of u32s โ€” that's a
        // structural error, not a "skip me" hint.
        if child.len() % 4 != 0 {
            return Err(Error::invalid("MP4: tref child not a multiple of 4 bytes"));
        }
        let mut ids = Vec::with_capacity(child.len() / 4);
        for chunk in child.chunks_exact(4) {
            let id = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
            if id != 0 {
                ids.push(id);
            }
        }
        // Per spec a given reference_type appears at most once. If a
        // file violates that, keep the first occurrence and discard the
        // rest โ€” silently chaining them together would surface bogus
        // (track,reference_type) pairs.
        if !t.tref.iter().any(|(ty, _)| *ty == hdr.fourcc) {
            t.tref.push((hdr.fourcc, ids));
        }
    }
    Ok(())
}

/// Serialise a `tref` (TrackReferenceBox, ISO/IEC 14496-12 ยง8.3.3) from a
/// list of `(reference_type, track_IDs)` pairs โ€” the byte-exact inverse of
/// [`parse_tref`].
///
/// The outer `tref` is a plain container box (no FullBox version/flags).
/// Each pair becomes one `TrackReferenceTypeBox` whose FourCC is the
/// `reference_type` and whose body is the packed big-endian `track_ID`
/// array (ยง8.3.3.2). The pairs are emitted in the supplied order; a given
/// `reference_type` should appear at most once (the spec permits one
/// `TrackReferenceTypeBox` per type) but this builder does not enforce
/// uniqueness โ€” that is the caller's responsibility.
///
/// Per ยง8.3.3.3 a `track_ID` is "never zero"; a pair carrying a zero ID is
/// rejected (a zero would be silently dropped by [`parse_tref`], breaking
/// round-trip). An empty `track_IDs` array for a type is permitted (the
/// box is legal but references nothing). Returns `None` if any pair
/// carries a zero `track_ID`.
pub fn build_tref_box(refs: &[([u8; 4], Vec<u32>)]) -> Option<Vec<u8>> {
    let mut body = Vec::new();
    for (ref_type, ids) in refs {
        let mut child = Vec::with_capacity(ids.len() * 4);
        for &id in ids {
            if id == 0 {
                return None;
            }
            child.extend_from_slice(&id.to_be_bytes());
        }
        body.extend_from_slice(&wrap_box(ref_type, &child));
    }
    Some(wrap_box(&crate::boxes::TREF, &body))
}

/// ยง8.3.4 โ€” `trgr` (TrackGroupBox).
///
/// Spec syntax (ยง8.3.4.2):
/// ```text
/// aligned(8) class TrackGroupBox('trgr') {
/// }
/// aligned(8) class TrackGroupTypeBox (unsigned int(32) track_group_type)
///     extends FullBox(track_group_type, version = 0, flags = 0) {
///   unsigned int(32) track_group_id;
///   // the remaining data may be specified for a particular
///   // track_group_type
/// }
/// ```
///
/// The outer `trgr` is a plain container whose children are typed
/// FullBoxes โ€” each child's FourCC IS the `track_group_type` (the
/// spec-named example is `msrc`, for multi-source presentations).
/// Each child body is a 4-byte `FullBox` preamble (version + 24-bit
/// flags, both fixed to zero per ยง8.3.4.2) followed by the 32-bit
/// `track_group_id`. Any trailing bytes are reserved for a
/// per-`track_group_type` extension and silently ignored at this
/// layer โ€” a future derived spec adding fields can land here without
/// changing the parse contract.
///
/// Two tracks sharing the same `(track_group_type, track_group_id)`
/// pair belong to the same group (ยง8.3.4.3). Per ยง8.3.4.1 a group is
/// **not** a dependency relationship โ€” that role belongs to `tref`
/// (ยง8.3.3).
///
/// The spec does not forbid two children of the same `track_group_type`
/// on the same track, so we preserve encounter order in `t.trgr` rather
/// than de-duplicating by type. A child whose body is shorter than the
/// 8-byte preamble + id is a structural error and aborts the parse
/// (the file is malformed); a child whose preamble has non-zero
/// version is silently skipped (the spec pins version = 0, so a
/// non-zero value is a forward-compatible extension we cannot interpret
/// safely).
fn parse_trgr(body: &[u8], t: &mut Track) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let child = read_bytes_vec(&mut cur, psz)?;
        // FullBox preamble (4) + track_group_id (4) = 8 bytes minimum.
        if child.len() < 8 {
            return Err(Error::invalid(
                "MP4: trgr child too short for FullBox + track_group_id",
            ));
        }
        // ยง8.3.4.2 pins version = 0. A different version means a
        // forward-compatible extension we cannot decode safely; skip
        // the child rather than mis-parsing it.
        let version = child[0];
        if version != 0 {
            continue;
        }
        let track_group_id = u32::from_be_bytes([child[4], child[5], child[6], child[7]]);
        t.trgr.push((hdr.fourcc, track_group_id));
    }
    Ok(())
}

/// Serialise a `trgr` (TrackGroupBox, ISO/IEC 14496-12 ยง8.3.4) from a list
/// of `(track_group_type, track_group_id)` pairs โ€” the byte-exact inverse
/// of [`parse_trgr`].
///
/// The outer `trgr` is a plain container box (no FullBox preamble). Each
/// pair becomes one `TrackGroupTypeBox` whose FourCC is the
/// `track_group_type` and whose body is the 4-byte FullBox preamble
/// (version 0, flags 0) followed by the 32-bit `track_group_id`
/// (ยง8.3.4.2). The per-`track_group_type` extension tail is not emitted
/// (this layer does not model it); pairs are written in supplied order.
pub fn build_trgr_box(groups: &[([u8; 4], u32)]) -> Vec<u8> {
    let mut body = Vec::new();
    for (group_type, group_id) in groups {
        let mut child = Vec::with_capacity(8);
        child.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
        child.extend_from_slice(&group_id.to_be_bytes());
        body.extend_from_slice(&wrap_box(group_type, &child));
    }
    wrap_box(&crate::boxes::TRGR, &body)
}

/// ยง8.6.5 โ€” `edts` (EditBox) container. We only care about the inner
/// `elst` (EditListBox) child; everything else in the container is
/// reserved.
fn parse_edts(body: &[u8], t: &mut Track) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            ELST => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_elst(&b, t)?;
            }
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }
    Ok(())
}

/// ยง8.6.6 โ€” `elst` (EditListBox).
///
/// Each entry is `(segment_duration, media_time, media_rate)`. Width
/// of the first two fields depends on the FullBox `version`:
/// * v0 โ†’ both 32-bit (unsigned dur, signed media_time)
/// * v1 โ†’ both 64-bit (unsigned dur, signed media_time)
///
/// `media_rate` is always a 16.16 fixed-point u32 (high 16 bits
/// integer, low 16 fractional). `0x0001_0000` is normal speed.
///
/// Special values:
/// * `media_time = -1` โ†’ an "empty" edit (no underlying media for the
///   given duration); samples skip this gap on the presentation
///   timeline.
/// * Non-1.0 `media_rate` (slow-motion / reverse) is recorded but the
///   sample-time projection assumes 1.0 โ€” complete fast/slow playback
///   is out of scope for this demuxer.
///
/// Stores the full list so the multi-segment apply path
/// (`build_elst_timeline` / `ElstTimeline::delta_for_cts`) can hop the
/// presentation timeline across each segment correctly.
fn parse_elst(body: &[u8], t: &mut Track) -> Result<()> {
    parse_elst_into(body, &mut t.elst)
}

/// Body parser shared by the track walk ([`parse_elst`]) and the
/// public standalone entry point ([`parse_elst_box`]).
fn parse_elst_into(body: &[u8], out: &mut Vec<ElstEntry>) -> Result<()> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: elst too short"));
    }
    let version = body[0];
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let entry_size = if version == 1 { 20 } else { 12 };
    let mut off = 8;
    let mut entries = Vec::with_capacity(count.min(body.len() / 12));
    for _ in 0..count {
        if off + entry_size > body.len() {
            return Err(Error::invalid("MP4: elst truncated"));
        }
        let (segment_duration, media_time) = if version == 1 {
            let dur = u64::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
                body[off + 4],
                body[off + 5],
                body[off + 6],
                body[off + 7],
            ]);
            let mt = i64::from_be_bytes([
                body[off + 8],
                body[off + 9],
                body[off + 10],
                body[off + 11],
                body[off + 12],
                body[off + 13],
                body[off + 14],
                body[off + 15],
            ]);
            (dur, mt)
        } else {
            let dur =
                u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64;
            let mt =
                i32::from_be_bytes([body[off + 4], body[off + 5], body[off + 6], body[off + 7]])
                    as i64;
            (dur, mt)
        };
        let rate_off = off + if version == 1 { 16 } else { 8 };
        let media_rate = u32::from_be_bytes([
            body[rate_off],
            body[rate_off + 1],
            body[rate_off + 2],
            body[rate_off + 3],
        ]);
        entries.push(ElstEntry {
            segment_duration,
            media_time,
            media_rate,
        });
        off += entry_size;
    }
    *out = entries;
    Ok(())
}

/// Compute the `media_time` shift applied to all samples in the track,
/// using the first non-empty edit segment as the leading shift. This
/// matches the legacy single-segment behaviour and is what B-frame
/// `ctts` offsets compose against to land the first presented frame
/// at pts 0.
fn elst_leading_media_time(elst: &[ElstEntry]) -> i64 {
    for e in elst {
        if e.media_time != -1 {
            return e.media_time;
        }
    }
    0
}

/// One entry of an `elst` EditListBox (ISO/IEC 14496-12 ยง8.6.6) โ€” the
/// public typed form surfaced by [`Mp4Demuxer::edit_list`] and consumed
/// by [`build_elst_box`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EditListEntry {
    /// Duration of this edit segment in units of the *movie* timescale
    /// (`mvhd.timescale`, ยง8.6.6.3).
    pub segment_duration: u64,
    /// Starting composition time within the media of this edit segment
    /// (*media* timescale). `-1` marks an empty edit.
    pub media_time: i64,
    /// ยง8.6.6.3: `1` plays the media normally, `0` is a dwell (the
    /// media at `media_time` is held for `segment_duration`). No other
    /// value is defined.
    pub media_rate_integer: i16,
    /// Specified as 0 by ยง8.6.6.2; preserved verbatim on parse.
    pub media_rate_fraction: i16,
}

impl EditListEntry {
    /// True when this entry is an empty edit (`media_time == -1`).
    pub fn is_empty_edit(&self) -> bool {
        self.media_time == -1
    }

    /// True when this entry is a ยง8.6.6.3 dwell
    /// (`media_rate_integer == 0` on a non-empty edit).
    pub fn is_dwell(&self) -> bool {
        self.media_rate_integer == 0 && !self.is_empty_edit()
    }
}

fn elst_entry_to_public(e: &ElstEntry) -> EditListEntry {
    EditListEntry {
        segment_duration: e.segment_duration,
        media_time: e.media_time,
        media_rate_integer: (e.media_rate >> 16) as i16,
        media_rate_fraction: (e.media_rate & 0xFFFF) as i16,
    }
}

/// Parse an `elst` (EditListBox, ISO/IEC 14496-12 ยง8.6.6) box *body*
/// (FullBox header onwards, excluding the `[size][fourcc]` prefix)
/// into typed entries. Both the v0 (32-bit) and v1 (64-bit) field
/// widths are handled; a body shorter than its declared `entry_count`
/// is rejected.
pub fn parse_elst_box(body: &[u8]) -> Result<Vec<EditListEntry>> {
    let mut t_elst: Vec<ElstEntry> = Vec::new();
    parse_elst_into(body, &mut t_elst)?;
    Ok(t_elst.iter().map(elst_entry_to_public).collect())
}

/// Build a complete `[size]["elst"]` EditListBox from typed entries โ€”
/// the byte-exact inverse of [`parse_elst_box`]. The FullBox `version`
/// is auto-selected: v0 (32-bit widths) when every value fits, v1
/// (64-bit) otherwise. Entries that would not survive a ยง8.6.6
/// round-trip are rejected:
///
/// * `media_rate_integer` outside `{0, 1}` (ยง8.6.6.3 defines no other
///   value),
/// * a final empty edit (ยง8.6.6.3: "The last edit in a track shall
///   never be an empty edit"),
/// * `media_time < -1` (negative times other than the empty-edit
///   sentinel are meaningless),
/// * an empty entry list (write no `edts` at all instead).
pub fn build_elst_box(entries: &[EditListEntry]) -> Result<Vec<u8>> {
    if entries.is_empty() {
        return Err(Error::invalid(
            "MP4: elst with no entries (omit the box instead)",
        ));
    }
    if let Some(last) = entries.last() {
        if last.is_empty_edit() {
            return Err(Error::invalid(
                "MP4: the last edit in a track shall never be an empty edit (ยง8.6.6.3)",
            ));
        }
    }
    let mut use_v1 = false;
    for e in entries {
        if e.media_rate_integer != 0 && e.media_rate_integer != 1 {
            return Err(Error::invalid(format!(
                "MP4: elst media_rate_integer {} not in {{0, 1}} (ยง8.6.6.3)",
                e.media_rate_integer
            )));
        }
        if e.media_time < -1 {
            return Err(Error::invalid(format!(
                "MP4: elst media_time {} below the -1 empty-edit sentinel",
                e.media_time
            )));
        }
        if e.segment_duration > u32::MAX as u64 || e.media_time > i32::MAX as i64 {
            use_v1 = true;
        }
    }
    let mut body = Vec::with_capacity(8 + entries.len() * if use_v1 { 20 } else { 12 });
    body.push(u8::from(use_v1)); // version
    body.extend_from_slice(&[0, 0, 0]); // flags
    body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
    for e in entries {
        if use_v1 {
            body.extend_from_slice(&e.segment_duration.to_be_bytes());
            body.extend_from_slice(&e.media_time.to_be_bytes());
        } else {
            body.extend_from_slice(&(e.segment_duration as u32).to_be_bytes());
            body.extend_from_slice(&(e.media_time as i32).to_be_bytes());
        }
        body.extend_from_slice(&e.media_rate_integer.to_be_bytes());
        body.extend_from_slice(&e.media_rate_fraction.to_be_bytes());
    }
    let mut out = Vec::with_capacity(8 + body.len());
    out.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes());
    out.extend_from_slice(b"elst");
    out.extend_from_slice(&body);
    Ok(out)
}

fn parse_mdia(body: &[u8], t: &mut Track, file_size: u64) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            MDHD => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_mdhd(&b, t)?;
            }
            ELNG => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_elng(&b, t);
            }
            HDLR => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_hdlr(&b, t)?;
            }
            MINF => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_minf(&b, t, file_size)?;
            }
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }
    Ok(())
}

fn parse_mdhd(body: &[u8], t: &mut Track) -> Result<()> {
    if body.len() < 24 {
        return Err(Error::invalid("MP4: mdhd too short"));
    }
    let version = body[0];
    let (timescale, duration) = if version == 0 {
        let ts = u32::from_be_bytes([body[12], body[13], body[14], body[15]]);
        let du = u32::from_be_bytes([body[16], body[17], body[18], body[19]]) as u64;
        (ts, du)
    } else {
        if body.len() < 32 {
            return Err(Error::invalid("MP4: mdhd v1 too short"));
        }
        let ts = u32::from_be_bytes([body[20], body[21], body[22], body[23]]);
        let du = u64::from_be_bytes([
            body[24], body[25], body[26], body[27], body[28], body[29], body[30], body[31],
        ]);
        (ts, du)
    };
    t.timescale = timescale;
    t.duration = Some(duration);
    Ok(())
}

/// Parse an `elng` (ExtendedLanguageBox, ISO/IEC 14496-12 ยง8.4.6).
///
/// Layout: a `FullBox` preamble (1 version byte + 3 flag bytes, both
/// always zero per ยง8.4.6.2) followed by a single NULL-terminated UTF-8
/// C string `extended_language` holding a BCP 47 / RFC 4646 tag
/// (`en-US`, `fr-FR`, `zh-CN`, โ€ฆ). The tag is read up to the first NUL
/// (a trailing NUL is required by the spec but tolerated absent); any
/// bytes after the NUL are ignored. A malformed (too-short or non-UTF-8)
/// box is silently skipped rather than failing the demux โ€” the box is
/// optional and a player can always fall back to `mdhd`'s packed code.
fn parse_elng(body: &[u8], t: &mut Track) {
    // FullBox preamble is 4 bytes; anything shorter has no string.
    if body.len() < 4 {
        return;
    }
    let s = &body[4..];
    // Take everything up to the first NUL terminator (or the whole
    // remainder if no NUL is present).
    let end = s.iter().position(|&b| b == 0).unwrap_or(s.len());
    if let Ok(tag) = std::str::from_utf8(&s[..end]) {
        if !tag.is_empty() {
            t.elng = Some(tag.to_string());
        }
    }
}

fn parse_hdlr(body: &[u8], t: &mut Track) -> Result<()> {
    // FullBox (4 bytes), pre_defined (4 bytes), handler_type (4 bytes
    // at offset 8). ISO/IEC 14496-12 ยง8.4.3.2.
    if body.len() < 12 {
        return Err(Error::invalid("MP4: hdlr too short"));
    }
    let mut handler = [0u8; 4];
    handler.copy_from_slice(&body[8..12]);
    t.media_type = match &handler {
        h if *h == HANDLER_SOUN => MediaType::Audio,
        h if *h == HANDLER_VIDE => MediaType::Video,
        // `subt` (BMFF ยง12.6.1), `sbtl` (QuickTime), `text` (BMFF
        // ยง12.5.1 timed text โ€” `tx3g` lives here). All three are
        // surfaced as MediaType::Subtitle so callers can route them
        // through their subtitle pipeline.
        h if *h == HANDLER_SUBT || *h == HANDLER_SBTL || *h == HANDLER_TEXT => MediaType::Subtitle,
        // `meta` โ€” timed metadata (BMFF ยง8.11). Stays as Data; no
        // subtitle dispatch.
        h if *h == HANDLER_META => MediaType::Data,
        _ => MediaType::Data,
    };
    Ok(())
}

fn parse_minf(body: &[u8], t: &mut Track, file_size: u64) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            STBL => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_stbl(&sub, t, file_size)?;
            }
            VMHD => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                // ยง12.1.2 fixes the quantity at exactly one; keep the
                // first instance seen and ignore any stray duplicates.
                if t.vmhd.is_none() {
                    if let Ok(v) = parse_vmhd(&sub) {
                        t.vmhd = Some(v);
                    }
                }
            }
            HMHD => {
                let sub = read_bytes_vec(&mut cur, psz)?;
                // ยง12.4.2 marks exactly one media header mandatory inside
                // `minf`; keep the first parseable `hmhd` and ignore stray
                // duplicates. A malformed one is dropped (informational โ€”
                // the track still demuxes), so the walk never aborts.
                if t.hmhd.is_none() {
                    if let Ok(h) = parse_hmhd(&sub) {
                        t.hmhd = Some(h);
                    }
                }
            }
            GMHD => {
                // QuickTime Base Media Information Header Atom: a container
                // used in place of a typed media header for base-media
                // tracks (text / timecode / music / generic). Walk it for
                // its `gmin` child (base media info) and, for a timecode
                // track, its `tcmi` child (timecode media info). Keep the
                // first parseable instance of each; a malformed child is
                // dropped (informational โ€” the track still demuxes) so the
                // walk never aborts.
                let sub = read_bytes_vec(&mut cur, psz)?;
                parse_gmhd(&sub, t);
            }
            DINF => {
                // ยง8.7.1: DataInformationBox is a plain container whose
                // sole child of interest is the `dref` DataReferenceBox.
                // ยง8.7.1.1 fixes the quantity at exactly one; keep the
                // first parseable instance and ignore stray duplicates. A
                // malformed `dref` is dropped (informational โ€” the file
                // still demuxes against the single-source default), so the
                // dinf walk never aborts the surrounding `minf` parse.
                let sub = read_bytes_vec(&mut cur, psz)?;
                if t.dref.is_none() {
                    if let Some(d) = parse_dinf(&sub) {
                        t.dref = Some(d);
                    }
                }
            }
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }
    Ok(())
}

/// Walk a `dinf` (DataInformationBox, ยง8.7.1) body for its `dref`
/// (DataReferenceBox) child and parse it. Returns `None` when the `dinf`
/// carries no parseable `dref`.
fn parse_dinf(body: &[u8]) -> Option<DrefBox> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = read_box_header(&mut cur).ok()??;
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let sub = read_bytes_vec(&mut cur, psz).ok()?;
        if hdr.fourcc == DREF {
            return parse_dref(&sub).ok();
        }
    }
    None
}

/// Parse a `dref` (DataReferenceBox, ISO/IEC 14496-12 ยง8.7.2) body.
///
/// Layout after the box header: a 4-byte `FullBox(version=0, flags=0)`
/// preamble, a `unsigned int(32) entry_count`, then `entry_count`
/// `DataEntryBox` children โ€” each a `url ` DataEntryUrlBox or `urn `
/// DataEntryUrnBox FullBox (ยง8.7.2.2). Each child's own 24-bit
/// `entry_flags` carries the ยง8.7.2.3 self-contained bit; when it is set
/// the URL form is used with no string body. A `urn ` entry holds a
/// NULL-terminated `name` followed by an optional NULL-terminated
/// `location`; a `url ` entry holds at most a `location`.
///
/// Robustness mirrors the rest of the demuxer: a forged `entry_count`
/// cannot trigger a large up-front allocation (the smallest possible
/// child is its 8-byte box header), a child whose declared size overruns
/// the remaining body ends the walk at what was read, and an unknown
/// FullBox `version` is tolerated (the spec pins it to 0 but the layout
/// is unambiguous).
fn parse_dref(body: &[u8]) -> Result<DrefBox> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: dref too short"));
    }
    let entry_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let mut cur = std::io::Cursor::new(&body[8..]);
    let avail = (body.len() - 8) as u64;
    // The smallest DataEntryBox is an 8-byte box header (the
    // self-contained `url ` form, 4-byte preamble = the size+type), so
    // the body can hold at most `avail / 8` real entries.
    let max_entries = (avail / 8).max(1);
    let mut entries = Vec::with_capacity(entry_count.min(max_entries as u32) as usize);
    for _ in 0..entry_count {
        if cur.position() >= avail {
            break;
        }
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = match hdr.payload_size() {
            Some(p) => p as usize,
            None => break,
        };
        let child = match read_bytes_vec(&mut cur, psz) {
            Ok(c) => c,
            Err(_) => break,
        };
        // The child body is a FullBox: 1 version byte + 3 flag bytes.
        if child.len() < 4 {
            // A malformed child (no FullBox preamble); skip it rather
            // than aborting the whole table โ€” the rest may be valid.
            continue;
        }
        let flags = u32::from_be_bytes([0, child[1], child[2], child[3]]);
        let payload = &child[4..];
        match hdr.fourcc {
            URL_ => {
                // ยง8.7.2.3: self-contained โ‡’ no string present. Otherwise
                // a single NULL-terminated UTF-8 `location`.
                let location = if flags & 1 != 0 {
                    None
                } else {
                    read_c_string(payload)
                };
                entries.push(DataEntry {
                    kind: URL_,
                    flags,
                    name: None,
                    location,
                });
            }
            URN_ => {
                // ยง8.7.2.2: a NULL-terminated `name` then an optional
                // NULL-terminated `location`. `name` is required for a
                // URN entry; `location` is optional. Self-contained URN
                // entries are not the spec's intent (it directs the URL
                // form for self-contained data), so we still read the
                // strings present.
                let (name, rest) = read_c_string_split(payload);
                let location = read_c_string(rest);
                entries.push(DataEntry {
                    kind: URN_,
                    flags,
                    name,
                    location,
                });
            }
            // ยง8.7.2.1: each DataEntryBox shall be a `url ` or `urn `.
            // Anything else is non-conforming โ€” record nothing for it so
            // the entry index alignment with `data_reference_index` is
            // preserved by skipping (rather than inserting a bogus entry).
            _ => {}
        }
    }
    Ok(DrefBox { entries })
}

/// Read a single NULL-terminated UTF-8 C string from `buf`. Returns
/// `None` when the string is empty (no bytes, or an immediate NUL) so a
/// "present but empty" entry collapses to "no string". A buffer with no
/// NUL terminator is read to its end (a producer slip on the terminator
/// should not lose the string).
fn read_c_string(buf: &[u8]) -> Option<String> {
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    if end == 0 {
        return None;
    }
    Some(String::from_utf8_lossy(&buf[..end]).into_owned())
}

/// Split `buf` at the first NUL: returns the leading C string (or `None`
/// when empty) and the bytes after the terminator (for reading a second
/// C string). When no NUL is present the whole buffer is the string and
/// the remainder is empty.
fn read_c_string_split(buf: &[u8]) -> (Option<String>, &[u8]) {
    match buf.iter().position(|&b| b == 0) {
        Some(pos) => {
            let s = if pos == 0 {
                None
            } else {
                Some(String::from_utf8_lossy(&buf[..pos]).into_owned())
            };
            (s, &buf[pos + 1..])
        }
        None => {
            let s = if buf.is_empty() {
                None
            } else {
                Some(String::from_utf8_lossy(buf).into_owned())
            };
            (s, &[])
        }
    }
}

/// Parse `vmhd` (VideoMediaHeaderBox, ISO/IEC 14496-12 ยง12.1.2 /
/// ยง8.4.5).
///
/// The body is a 4-byte `FullBox(version=0, flags=1)` preamble followed
/// by `unsigned int(16) graphicsmode` and `unsigned int(16)[3] opcolor`
/// โ€” eight payload bytes after the preamble, twelve total. The `version`
/// is not enforced (the spec fixes it at 0, but we tolerate a non-zero
/// value rather than dropping a usable header); `flags` is likewise not
/// required to equal 1. A body shorter than the full 12 bytes is
/// rejected โ€” a partial header would surface an `opcolor` component that
/// is really truncation noise.
fn parse_vmhd(body: &[u8]) -> Result<VmhdBox> {
    if body.len() < 12 {
        return Err(Error::invalid("MP4: vmhd too short"));
    }
    let graphicsmode = u16::from_be_bytes([body[4], body[5]]);
    let opcolor = [
        u16::from_be_bytes([body[6], body[7]]),
        u16::from_be_bytes([body[8], body[9]]),
        u16::from_be_bytes([body[10], body[11]]),
    ];
    Ok(VmhdBox {
        graphicsmode,
        opcolor,
    })
}

/// Parse `hmhd` (HintMediaHeaderBox, ISO/IEC 14496-12 ยง12.4.2 /
/// ยง8.4.5).
///
/// The body is a 4-byte `FullBox(version=0, 0)` preamble followed by
/// `unsigned int(16) maxPDUsize`, `unsigned int(16) avgPDUsize`,
/// `unsigned int(32) maxbitrate`, `unsigned int(32) avgbitrate`, and a
/// reserved `unsigned int(32)` โ€” sixteen payload bytes after the
/// preamble, twenty total. The `version` is not enforced (the spec
/// fixes it at 0, but a non-zero value is tolerated rather than
/// dropping a usable header, matching the `parse_vmhd` posture); the
/// trailing reserved word (required zero by ยง12.4.2.2) is read past but
/// not surfaced. A body shorter than the full 20 bytes is rejected โ€” a
/// partial header would surface a bitrate that is really truncation
/// noise.
fn parse_hmhd(body: &[u8]) -> Result<HmhdBox> {
    if body.len() < 20 {
        return Err(Error::invalid("MP4: hmhd too short"));
    }
    let max_pdu_size = u16::from_be_bytes([body[4], body[5]]);
    let avg_pdu_size = u16::from_be_bytes([body[6], body[7]]);
    let max_bitrate = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    let avg_bitrate = u32::from_be_bytes([body[12], body[13], body[14], body[15]]);
    Ok(HmhdBox {
        max_pdu_size,
        avg_pdu_size,
        max_bitrate,
        avg_bitrate,
    })
}

/// Walk a QuickTime `gmhd` (Base Media Information Header Atom) body,
/// populating `t.gmin` from its `gmin` (Base Media Info Atom) child and,
/// for a timecode track, `t.tcmi` from its `tcmi` (Timecode Media Info
/// Atom) child. The first parseable instance of each wins. A `gmhd` may
/// also carry other media-specific children (e.g. a `text` atom for text
/// media); those are skipped. A malformed child ends the walk at what was
/// read without disturbing the surrounding parse.
fn parse_gmhd(body: &[u8], t: &mut Track) {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur) {
            Ok(Some(h)) => h,
            _ => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let sub = match read_bytes_vec(&mut cur, psz) {
            Ok(s) => s,
            Err(_) => break,
        };
        match hdr.fourcc {
            GMIN if t.gmin.is_none() => {
                if let Some(g) = parse_gmin(&sub) {
                    t.gmin = Some(g);
                }
            }
            TCMI if t.tcmi.is_none() => {
                if let Some(tc) = parse_tcmi(&sub) {
                    t.tcmi = Some(tc);
                }
            }
            _ => {}
        }
    }
}

/// Parse a QuickTime `gmin` (Base Media Info Atom) body.
///
/// The body is a 4-byte `FullBox(version, flags)` preamble followed by
/// `unsigned int(16) graphicsmode`, `unsigned int(16)[3] opcolor`,
/// `int(16) balance`, and a reserved `unsigned int(16)` โ€” twelve payload
/// bytes after the preamble, sixteen total. The `version` / `flags`
/// (specified as 0) are read past but not enforced (a non-zero value is
/// tolerated rather than dropping a usable atom, matching the `parse_vmhd`
/// posture); the trailing reserved word is read past but not surfaced.
/// A body shorter than the full 16 bytes is rejected โ€” a partial atom
/// would surface a `balance` that is really truncation noise.
fn parse_gmin(body: &[u8]) -> Option<GminBox> {
    if body.len() < 16 {
        return None;
    }
    let graphicsmode = u16::from_be_bytes([body[4], body[5]]);
    let opcolor = [
        u16::from_be_bytes([body[6], body[7]]),
        u16::from_be_bytes([body[8], body[9]]),
        u16::from_be_bytes([body[10], body[11]]),
    ];
    let balance = i16::from_be_bytes([body[12], body[13]]);
    Some(GminBox {
        graphicsmode,
        opcolor,
        balance,
    })
}

/// Parse a standalone QuickTime `gmin` (Base Media Info Atom) body from
/// `body` (the 16 bytes after the plain 8-byte box header). Exposed so
/// tooling holding the atom's payload can recover the
/// `(graphicsmode, opcolor, balance)` triple without re-running `open()`.
/// `Err` for a body shorter than the fixed 16-byte layout; trailing bytes
/// are ignored.
pub fn parse_gmin_box(body: &[u8]) -> Result<GminBox> {
    parse_gmin(body).ok_or_else(|| Error::invalid("MP4: gmin too short"))
}

/// Build a complete QuickTime `gmin` (Base Media Info Atom) box from a
/// [`GminBox`]. The byte-exact inverse of [`parse_gmin_box`]: a 4-byte
/// `FullBox(version=0, flags=0)` preamble, the `graphicsmode`, the three
/// `opcolor` components, the `balance`, and the reserved zero word.
pub fn build_gmin_box(r: &GminBox) -> Vec<u8> {
    let mut body = Vec::with_capacity(16);
    body.extend_from_slice(&[0, 0, 0, 0]); // version + flags
    body.extend_from_slice(&r.graphicsmode.to_be_bytes());
    for c in r.opcolor {
        body.extend_from_slice(&c.to_be_bytes());
    }
    body.extend_from_slice(&r.balance.to_be_bytes());
    body.extend_from_slice(&[0, 0]); // reserved
    wrap_box(&GMIN, &body)
}

/// Build a complete QuickTime `gmhd` (Base Media Information Header Atom)
/// box wrapping a single `gmin` (Base Media Info Atom) built from `r`.
/// This is the minimal `gmhd` โ€” the `gmin` child alone โ€” sufficient for
/// a base-media (text / timecode / music / generic) track's `minf`.
pub fn build_gmhd_box(r: &GminBox) -> Vec<u8> {
    wrap_box(&GMHD, &build_gmin_box(r))
}

/// Parse a QuickTime `tcmi` (Timecode Media Info Atom) body.
///
/// The body is a 4-byte `FullBox(version, flags)` preamble followed by
/// `unsigned int(16) text_font`, `unsigned int(16) text_face`,
/// `unsigned int(16) text_size`, a 48-bit (`[u16; 3]`) `text_color`, a
/// 48-bit `background_color`, and a Pascal-string `font_name` (a length
/// byte then that many characters) โ€” a fixed 22-byte prefix after the
/// preamble followed by the variable-length name. The `version` / `flags`
/// (specified as 0) are read past but not enforced. A body shorter than
/// the 22-byte fixed prefix is rejected; a `font_name` whose declared
/// length overruns the remaining bytes is clamped to what is present
/// (rather than dropping the whole atom). Non-UTF-8 name bytes are
/// replaced (lossy) so the record always yields a `String`.
fn parse_tcmi(body: &[u8]) -> Option<TcmiBox> {
    // 4 (preamble) + 2 (font) + 2 (face) + 2 (size) + 6 (text_color)
    // + 6 (background_color) = 22 fixed bytes before the Pascal string.
    if body.len() < 22 {
        return None;
    }
    let text_font = u16::from_be_bytes([body[4], body[5]]);
    let text_face = u16::from_be_bytes([body[6], body[7]]);
    let text_size = u16::from_be_bytes([body[8], body[9]]);
    let text_color = [
        u16::from_be_bytes([body[10], body[11]]),
        u16::from_be_bytes([body[12], body[13]]),
        u16::from_be_bytes([body[14], body[15]]),
    ];
    let background_color = [
        u16::from_be_bytes([body[16], body[17]]),
        u16::from_be_bytes([body[18], body[19]]),
        u16::from_be_bytes([body[20], body[21]]),
    ];
    // Pascal string: a leading length byte, then that many characters.
    // A missing length byte (exactly 22 bytes) means an empty name.
    let font_name = if body.len() > 22 {
        let n = body[22] as usize;
        let avail = body.len().saturating_sub(23);
        let take = n.min(avail);
        String::from_utf8_lossy(&body[23..23 + take]).into_owned()
    } else {
        String::new()
    };
    Some(TcmiBox {
        text_font,
        text_face,
        text_size,
        text_color,
        background_color,
        font_name,
    })
}

/// Parse a standalone QuickTime `tcmi` (Timecode Media Info Atom) body
/// from `body` (the bytes after the plain 8-byte box header). Exposed so
/// tooling holding the atom's payload can recover its rendering
/// parameters without re-running `open()`. `Err` for a body shorter than
/// the fixed 22-byte prefix; a `font_name` length that overruns is
/// clamped to the bytes present.
pub fn parse_tcmi_box(body: &[u8]) -> Result<TcmiBox> {
    parse_tcmi(body).ok_or_else(|| Error::invalid("MP4: tcmi too short"))
}

/// Build a complete QuickTime `tcmi` (Timecode Media Info Atom) box from a
/// [`TcmiBox`]. The byte-exact inverse of [`parse_tcmi_box`]: a 4-byte
/// `FullBox(version=0, flags=0)` preamble, the three 16-bit
/// font/face/size fields, the two 48-bit colours, and the Pascal-string
/// `font_name` (a length byte capped at 255 followed by that many
/// characters).
pub fn build_tcmi_box(r: &TcmiBox) -> Vec<u8> {
    let mut body = Vec::with_capacity(23 + r.font_name.len());
    body.extend_from_slice(&[0, 0, 0, 0]); // version + flags
    body.extend_from_slice(&r.text_font.to_be_bytes());
    body.extend_from_slice(&r.text_face.to_be_bytes());
    body.extend_from_slice(&r.text_size.to_be_bytes());
    for c in r.text_color {
        body.extend_from_slice(&c.to_be_bytes());
    }
    for c in r.background_color {
        body.extend_from_slice(&c.to_be_bytes());
    }
    let name = r.font_name.as_bytes();
    // The Pascal length byte caps the wire name at 255 bytes. A record
    // name can legitimately exceed that (a wire name of up to 255
    // non-UTF-8 bytes expands up to threefold under the parser's lossy
    // replacement), so truncate โ€” but only at a char boundary, so the
    // emitted bytes are valid UTF-8 and reparse cleanly instead of
    // growing a replacement-character tail.
    let mut n = name.len().min(255);
    while n > 0 && !r.font_name.is_char_boundary(n) {
        n -= 1;
    }
    body.push(n as u8);
    body.extend_from_slice(&name[..n]);
    wrap_box(&TCMI, &body)
}

/// Parse a QuickTime `tmcd` (Timecode) sample-description entry from
/// `entry` (the full sample-entry bytes, including the shared 8-byte
/// `reserved[6]` + `data_reference_index` preamble). After the preamble:
/// `unsigned int(32) reserved`, `unsigned int(32) flags`,
/// `unsigned int(32) timescale`, `unsigned int(32) frame_duration`,
/// `unsigned int(8) number_of_frames` โ€” 21 payload bytes after the
/// preamble (29 total up to and including `number_of_frames`). Returns
/// `None` for an entry too short to hold the fixed numeric fields; any
/// trailing reserved / source-reference `udta` bytes are ignored.
fn parse_tmcd_sample_entry(entry: &[u8]) -> Option<TmcdSampleEntry> {
    // 8 (preamble) + 4 (reserved) + 4 (flags) + 4 (timescale)
    // + 4 (frame_duration) + 1 (number_of_frames) = 25 bytes minimum.
    if entry.len() < 25 {
        return None;
    }
    let flags = u32::from_be_bytes([entry[12], entry[13], entry[14], entry[15]]);
    let timescale = u32::from_be_bytes([entry[16], entry[17], entry[18], entry[19]]);
    let frame_duration = u32::from_be_bytes([entry[20], entry[21], entry[22], entry[23]]);
    let number_of_frames = entry[24];
    Some(TmcdSampleEntry {
        flags,
        timescale,
        frame_duration,
        number_of_frames,
    })
}

/// Parse a standalone QuickTime `tmcd` (Timecode) sample-description entry
/// body from `entry` (the full sample-entry bytes including the shared
/// 8-byte preamble). Exposed so tooling holding the entry's bytes can
/// recover the `(flags, timescale, frame_duration, number_of_frames)`
/// fields without re-running `open()`. `Err` for an entry too short to
/// hold the fixed numeric fields.
pub fn parse_tmcd_sample_entry_box(entry: &[u8]) -> Result<TmcdSampleEntry> {
    parse_tmcd_sample_entry(entry).ok_or_else(|| Error::invalid("MP4: tmcd sample entry too short"))
}

/// Build a complete QuickTime `tmcd` (Timecode) sample-description entry
/// box from a [`TmcdSampleEntry`], with `data_reference_index`. The
/// byte-exact inverse of [`parse_tmcd_sample_entry_box`]: the shared
/// 8-byte preamble (`reserved[6]` + `data_reference_index`), a reserved
/// u32, the `flags`, `timescale`, `frame_duration`, `number_of_frames`,
/// and a reserved u8. The optional source-reference `udta` is not emitted.
pub fn build_tmcd_sample_entry(r: &TmcdSampleEntry, data_reference_index: u16) -> Vec<u8> {
    let mut body = Vec::with_capacity(26);
    body.extend_from_slice(&[0u8; 6]); // reserved
    body.extend_from_slice(&data_reference_index.to_be_bytes());
    body.extend_from_slice(&[0u8; 4]); // reserved
    body.extend_from_slice(&r.flags.to_be_bytes());
    body.extend_from_slice(&r.timescale.to_be_bytes());
    body.extend_from_slice(&r.frame_duration.to_be_bytes());
    body.push(r.number_of_frames);
    body.push(0); // reserved
    wrap_box(&TMCD, &body)
}

/// Parse a QuickTime `text` (Text) sample-description entry from `entry`
/// (the full sample-entry bytes including the shared 8-byte preamble).
/// Fixed field offsets (from `entry` start): `display_flags` [8..12],
/// `text_justification` [12..16], `background_color` [16..22],
/// `default_text_box` [22..30], reserved [30..38], `font_number`
/// [38..40], `font_face` [40..42], reserved [42..43], reserved [43..45],
/// `foreground_color` [45..51], then a Pascal-string `text_name` at
/// [51..]. Returns `None` for an entry shorter than the 51-byte fixed
/// prefix; a `text_name` length that overruns the body is clamped to the
/// bytes present. Non-UTF-8 name bytes are replaced (lossy).
fn parse_text_sample_entry(entry: &[u8]) -> Option<TextSampleEntry> {
    if entry.len() < 51 {
        return None;
    }
    let display_flags = u32::from_be_bytes([entry[8], entry[9], entry[10], entry[11]]);
    let text_justification = i32::from_be_bytes([entry[12], entry[13], entry[14], entry[15]]);
    let background_color = [
        u16::from_be_bytes([entry[16], entry[17]]),
        u16::from_be_bytes([entry[18], entry[19]]),
        u16::from_be_bytes([entry[20], entry[21]]),
    ];
    let default_text_box = [
        i16::from_be_bytes([entry[22], entry[23]]),
        i16::from_be_bytes([entry[24], entry[25]]),
        i16::from_be_bytes([entry[26], entry[27]]),
        i16::from_be_bytes([entry[28], entry[29]]),
    ];
    // reserved int(64) at [30..38]
    let font_number = u16::from_be_bytes([entry[38], entry[39]]);
    let font_face = u16::from_be_bytes([entry[40], entry[41]]);
    // reserved int(8) at [42], reserved int(16) at [43..45]
    let foreground_color = [
        u16::from_be_bytes([entry[45], entry[46]]),
        u16::from_be_bytes([entry[47], entry[48]]),
        u16::from_be_bytes([entry[49], entry[50]]),
    ];
    // Pascal string text_name: a leading length byte then that many
    // characters. Absent (exactly 51 bytes) โ†’ empty name.
    let text_name = if entry.len() > 51 {
        let n = entry[51] as usize;
        let avail = entry.len().saturating_sub(52);
        let take = n.min(avail);
        String::from_utf8_lossy(&entry[52..52 + take]).into_owned()
    } else {
        String::new()
    };
    Some(TextSampleEntry {
        display_flags,
        text_justification,
        background_color,
        default_text_box,
        font_number,
        font_face,
        foreground_color,
        text_name,
    })
}

/// Parse a standalone QuickTime `text` (Text) sample-description entry
/// body from `entry` (the full sample-entry bytes including the shared
/// 8-byte preamble). Exposed so tooling holding the entry's bytes can
/// recover the display / colour / font fields without re-running
/// `open()`. `Err` for an entry shorter than the 51-byte fixed prefix.
pub fn parse_text_sample_entry_box(entry: &[u8]) -> Result<TextSampleEntry> {
    parse_text_sample_entry(entry).ok_or_else(|| Error::invalid("MP4: text sample entry too short"))
}

/// Build a complete QuickTime `text` (Text) sample-description entry box
/// from a [`TextSampleEntry`], with `data_reference_index`. The byte-exact
/// inverse of [`parse_text_sample_entry_box`]: the shared 8-byte preamble,
/// the fixed numeric fields (with the spec's reserved zeros), and the
/// Pascal-string `text_name` (a length byte capped at 255 followed by
/// that many characters).
pub fn build_text_sample_entry(r: &TextSampleEntry, data_reference_index: u16) -> Vec<u8> {
    let mut body = Vec::with_capacity(52 + r.text_name.len());
    body.extend_from_slice(&[0u8; 6]); // reserved
    body.extend_from_slice(&data_reference_index.to_be_bytes());
    body.extend_from_slice(&r.display_flags.to_be_bytes());
    body.extend_from_slice(&r.text_justification.to_be_bytes());
    for c in r.background_color {
        body.extend_from_slice(&c.to_be_bytes());
    }
    for v in r.default_text_box {
        body.extend_from_slice(&v.to_be_bytes());
    }
    body.extend_from_slice(&[0u8; 8]); // reserved int(64)
    body.extend_from_slice(&r.font_number.to_be_bytes());
    body.extend_from_slice(&r.font_face.to_be_bytes());
    body.push(0); // reserved int(8)
    body.extend_from_slice(&[0u8; 2]); // reserved int(16)
    for c in r.foreground_color {
        body.extend_from_slice(&c.to_be_bytes());
    }
    let name = r.text_name.as_bytes();
    // Pascal length byte: cap at 255 wire bytes, truncating only at a
    // char boundary (see `build_tcmi_box` โ€” over-long names arise from
    // the parser's lossy replacement of non-UTF-8 wire names).
    let mut n = name.len().min(255);
    while n > 0 && !r.text_name.is_char_boundary(n) {
        n -= 1;
    }
    body.push(n as u8);
    body.extend_from_slice(&name[..n]);
    wrap_box(b"text", &body)
}

/// Parse a QuickTime `load` (Track Load Settings Atom) body from `body`
/// (the 16 bytes after the plain 8-byte box header โ€” `load` is a plain
/// `Box`, no FullBox preamble): `int(32) preload_start_time`, `int(32)
/// preload_duration`, `int(32) preload_flags`, `int(32) default_hints`.
/// Returns `None` for a body shorter than the fixed 16 bytes; trailing
/// bytes are ignored.
fn parse_load_settings(body: &[u8]) -> Option<LoadSettingsBox> {
    if body.len() < 16 {
        return None;
    }
    let preload_start_time = i32::from_be_bytes([body[0], body[1], body[2], body[3]]);
    let preload_duration = i32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let preload_flags = i32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    let default_hints = i32::from_be_bytes([body[12], body[13], body[14], body[15]]);
    Some(LoadSettingsBox {
        preload_start_time,
        preload_duration,
        preload_flags,
        default_hints,
    })
}

/// Parse a standalone QuickTime `load` (Track Load Settings Atom) body
/// from `body` (the 16 bytes after the plain 8-byte box header). Exposed
/// so tooling holding the atom's payload can recover the preload / hint
/// fields without re-running `open()`. `Err` for a body shorter than the
/// fixed 16-byte layout; trailing bytes are ignored.
pub fn parse_load_settings_box(body: &[u8]) -> Result<LoadSettingsBox> {
    parse_load_settings(body).ok_or_else(|| Error::invalid("MP4: load too short"))
}

/// Build a complete QuickTime `load` (Track Load Settings Atom) box from a
/// [`LoadSettingsBox`]. The byte-exact inverse of
/// [`parse_load_settings_box`]: the four 32-bit fields with no FullBox
/// preamble.
pub fn build_load_settings_box(r: &LoadSettingsBox) -> Vec<u8> {
    let mut body = Vec::with_capacity(16);
    body.extend_from_slice(&r.preload_start_time.to_be_bytes());
    body.extend_from_slice(&r.preload_duration.to_be_bytes());
    body.extend_from_slice(&r.preload_flags.to_be_bytes());
    body.extend_from_slice(&r.default_hints.to_be_bytes());
    wrap_box(&LOAD, &body)
}

fn parse_stbl(body: &[u8], t: &mut Track, file_size: u64) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let b = read_bytes_vec(&mut cur, psz)?;
        match hdr.fourcc {
            STSD => parse_stsd(&b, t)?,
            STTS => t.stts = parse_stts(&b)?,
            STSC => t.stsc = parse_stsc(&b)?,
            STSZ => t.stsz = parse_stsz(&b, file_size)?,
            STZ2 => t.stsz = parse_stz2(&b)?,
            STCO => t.chunk_offsets = parse_stco(&b)?,
            CO64 => t.chunk_offsets = parse_co64(&b)?,
            STSS => t.stss = parse_stss(&b)?,
            STSH => t.stsh = parse_stsh(&b)?,
            SDTP => t.sdtp = parse_sdtp(&b)?,
            STDP => t.stdp = parse_stdp(&b)?,
            PADB => t.padb = parse_padb(&b)?,
            CTTS => t.ctts = parse_ctts(&b)?,
            CSLG => t.cslg = Some(parse_cslg(&b)?),
            SBGP => t.sbgp.push(parse_sbgp(&b)?),
            SGPD => t.sgpd.push(parse_sgpd(&b)?),
            CSGP => t.csgp.push(parse_csgp(&b)?),
            SUBS => t.subs.push(parse_subs(&b)?),
            SAIZ => t.saiz.push(parse_saiz(&b)?),
            SAIO => t.saio.push(parse_saio(&b)?),
            _ => {}
        }
    }
    Ok(())
}

fn parse_stsd(body: &[u8], t: &mut Track) -> Result<()> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: stsd too short"));
    }
    let entry_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    if entry_count == 0 {
        return Ok(());
    }
    // ISO/IEC 14496-12 ยง8.5.2: walk **all** SampleEntry instances, not
    // just the first. The first entry drives active decode dispatch; the
    // rest are recorded so callers can resolve a `stsc` / `tfhd`
    // `sample_description_index` โ‰ฅ 2 to the FourCC of the description it
    // selects. Each SampleEntry shares the ยง8.5.2.2 8-byte preamble
    // (`reserved[6]` + `data_reference_index`), which we capture per
    // entry; the codec-specific tail of entry [0] is parsed below.
    let mut cur = std::io::Cursor::new(&body[8..]);
    let mut first_entry: Option<(BoxHeader, Vec<u8>)> = None;
    // Bound the recorded-entries vector by the byte budget so a forged
    // `entry_count` can't trigger a giant up-front allocation: the
    // smallest possible SampleEntry is its 8-byte box header plus the
    // 8-byte preamble (16 bytes), so the body can hold at most
    // `body.len() / 16` real entries.
    let max_entries = (body.len() / 16).max(1);
    t.stsd_entries
        .reserve(entry_count.min(max_entries as u32) as usize);
    for i in 0..entry_count {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => {
                if i == 0 {
                    return Err(Error::invalid("MP4: stsd first entry missing"));
                }
                // A truncated trailing entry: the declared `entry_count`
                // over-counts the bytes actually present. Stop at what we
                // could read rather than inventing entries.
                break;
            }
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let entry = read_bytes_vec(&mut cur, psz)?;
        // ยง8.5.2.2 preamble: 6 reserved bytes then a 16-bit
        // data_reference_index. Entries shorter than 8 bytes are
        // malformed; record a zero index rather than failing the whole
        // box (the FourCC alone is still useful metadata).
        let data_reference_index = if entry.len() >= 8 {
            u16::from_be_bytes([entry[6], entry[7]])
        } else {
            0
        };
        t.stsd_entries.push(StsdEntry {
            format: hdr.fourcc,
            data_reference_index,
        });
        if i == 0 {
            first_entry = Some((hdr, entry));
        }
    }
    let (hdr, entry) = match first_entry {
        Some(pair) => pair,
        None => return Err(Error::invalid("MP4: stsd first entry missing")),
    };
    t.codec_id_fourcc = hdr.fourcc;
    // ISO/IEC 14496-12 ยง8.12 โ€” protected sample entries (`encv`, `enca`,
    // `enct`, `encs`) wrap the original sample description: the original
    // FourCC and the encryption parameters move into a child `sinf` box
    // while the outer FourCC becomes one of the `enc*` placeholders. We
    // peek into the sinf to recover the original FourCC + scheme type
    // so downstream codec dispatch sees the un-transformed type (and
    // callers can read `protection_scheme` on the stream to learn how
    // to decrypt). The bytes inside the sample entry stay laid out as
    // if the original FourCC were present โ€” preamble (28 for audio /
    // 78 for video) then codec config boxes โ€” which is exactly what
    // ยง8.12.0 mandates ("leaving all other boxes unmodified").
    if matches!(hdr.fourcc, ENCV | ENCA | ENCT | ENCS) {
        let unwrap = parse_sinf_for_original_format(&entry, t.media_type)?;
        if let Some(fourcc) = unwrap.original_format {
            t.codec_id_fourcc = fourcc;
        }
        t.protection_scheme = unwrap.scheme_type;
        t.tenc = unwrap.tenc;
        t.piff_tenc = unwrap.piff_tenc;
        if t.stvi.is_none() {
            t.stvi = unwrap.stvi;
        }
    }
    parse_sample_entry(&entry, t)?;
    Ok(())
}

/// Result of unwrapping an `enc*` sample entry. Each field is
/// independently `None` when the corresponding child box was absent
/// from the sinf:
///
/// * `original_format` โ€” un-transformed sample-entry FourCC from
///   `sinf/frma` (ยง8.12.2).
/// * `scheme_type` โ€” protection scheme FourCC from `sinf/schm`
///   (ยง8.12.5). Per spec a `sinf` may carry `frma` without `schm` in
///   IPMP-only signalling.
/// * `tenc` โ€” parsed CENC TrackEncryptionBox payload from
///   `sinf/schi/tenc` (ISO/IEC 23001-7 ยง8.2). Absent when the file
///   uses a non-CENC scheme or omits the (CENC-mandatory) tenc.
struct SinfUnwrap {
    original_format: Option<[u8; 4]>,
    scheme_type: Option<[u8; 4]>,
    tenc: Option<TencBox>,
    /// PIFF legacy `uuid` TrackEncryptionBox recovered from
    /// `sinf/schi` (the pre-CENC `tenc` predecessor). Absent for
    /// modern CENC files and for non-encryption schemes.
    piff_tenc: Option<PiffTencBox>,
    /// `stvi` (StereoVideoBox, ยง8.15.4.2) recovered from `sinf/schi`
    /// when the SchemeType is `stvi` (stereoscopic video, ยง8.15.4.1).
    /// `None` for non-stereo schemes (the common case) or a malformed
    /// box.
    stvi: Option<StviRecord>,
}

impl SinfUnwrap {
    fn empty() -> Self {
        SinfUnwrap {
            original_format: None,
            scheme_type: None,
            tenc: None,
            piff_tenc: None,
            stvi: None,
        }
    }
}

/// Walk a protected sample entry (`enc*`) to find its `sinf` child
/// container, then pull out the original (un-transformed) FourCC from
/// `frma` and the scheme type from `schm`. Returns
/// `(Some(original_fourcc), Some(scheme_type))` when both are present
/// in well-formed input; either field is `None` when the corresponding
/// child box is absent. The latter is permitted by ยง8.12: in IPMP-only
/// signalling a `sinf` may carry `frma` without `schm`.
///
/// The preamble length depends on the original media-type (recorded on
/// the track via the `hdlr`): 28 bytes for audio (AudioSampleEntry v0)
/// or 78 bytes for video (VisualSampleEntry). We skip that, then walk
/// child boxes until we hit `sinf`.
fn parse_sinf_for_original_format(entry: &[u8], media_type: MediaType) -> Result<SinfUnwrap> {
    let preamble = match media_type {
        MediaType::Audio => 28,
        MediaType::Video => 78,
        // Other media types we don't currently surface as `enc*`; bail
        // gracefully without claiming anything.
        _ => return Ok(SinfUnwrap::empty()),
    };
    if entry.len() <= preamble {
        return Ok(SinfUnwrap::empty());
    }
    let mut cur = std::io::Cursor::new(&entry[preamble..]);
    let end = (entry.len() - preamble) as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let body = read_bytes_vec(&mut cur, psz)?;
        if hdr.fourcc == SINF {
            return parse_sinf_body(&body);
        }
    }
    Ok(SinfUnwrap::empty())
}

/// Inner sinf walker โ€” at the sinf level we're looking for `frma`
/// (original_format, ยง8.12.2), `schm` (scheme_type, ยง8.12.5), and
/// `schi` (SchemeInformationBox, ยง8.12.6). Per ISO/IEC 23001-7 ยง4.1
/// the `schi` of a CENC-protected track contains a `tenc`
/// TrackEncryptionBox; we descend one level into `schi` to pick that
/// up alongside the ยง8.12 fields.
fn parse_sinf_body(body: &[u8]) -> Result<SinfUnwrap> {
    let mut out = SinfUnwrap::empty();
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let inner = read_bytes_vec(&mut cur, psz)?;
        match hdr.fourcc {
            FRMA if inner.len() >= 4 => {
                out.original_format = Some([inner[0], inner[1], inner[2], inner[3]]);
            }
            SCHM if inner.len() >= 8 => {
                // FullBox header (4 bytes) + scheme_type (4 bytes) +
                // scheme_version (4 bytes) + optional URI. We only need
                // scheme_type at offset 4.
                out.scheme_type = Some([inner[4], inner[5], inner[6], inner[7]]);
            }
            SCHI => {
                // ISO/IEC 23001-7 ยง4.1 โ€” descend into schi to find
                // `tenc` (CENC), and ISO/IEC 14496-12 ยง8.15.4.2 โ€” the
                // `stvi` (StereoVideoBox) of a `stvi`-scheme restricted
                // entry. A malformed child inside an otherwise valid
                // schi should not abort sinf parsing (it still has
                // structural meaning via frma + schm), so each is
                // swallowed independently and left `None` on error.
                let children = walk_schi(&inner);
                out.tenc = children.tenc;
                out.piff_tenc = children.piff_tenc;
                out.stvi = children.stvi;
            }
            _ => {}
        }
    }
    Ok(out)
}

/// Scheme-specific children recovered from a `schi`
/// (SchemeInformationBox, ISO/IEC 14496-12 ยง8.12.6). Each field is
/// independently `None` when its box was absent or malformed โ€” a `schi`
/// carries whichever children the active SchemeType defines.
#[derive(Default)]
struct SchiChildren {
    /// `tenc` (TrackEncryptionBox, ISO/IEC 23001-7 ยง8.2) โ€” CENC scheme.
    tenc: Option<TencBox>,
    /// PIFF legacy `uuid` TrackEncryptionBox โ€” the pre-CENC `tenc`
    /// predecessor, dispatched on
    /// [`crate::cenc::PIFF_TENC_USERTYPE`].
    piff_tenc: Option<PiffTencBox>,
    /// `stvi` (StereoVideoBox, ยง8.15.4.2) โ€” `stvi` stereoscopic scheme.
    stvi: Option<StviRecord>,
}

/// Walk a `schi` (SchemeInformationBox, ISO/IEC 14496-12 ยง8.12.6)
/// body collecting the scheme-specific children this crate understands:
/// the CENC `tenc` (TrackEncryptionBox, ISO/IEC 23001-7 ยง8.2) and the
/// stereoscopic-video `stvi` (StereoVideoBox, ยง8.15.4.2). A `schi` is
/// scheme-specific so it may legitimately carry neither (or other
/// children we don't model); a malformed child is dropped without
/// aborting the walk. The walk ends cleanly on a truncated header.
fn walk_schi(body: &[u8]) -> SchiChildren {
    let mut out = SchiChildren::default();
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur) {
            Ok(Some(h)) => h,
            _ => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let inner = match read_bytes_vec(&mut cur, psz) {
            Ok(b) => b,
            Err(_) => break,
        };
        match hdr.fourcc {
            TENC if out.tenc.is_none() => out.tenc = parse_tenc(&inner).ok(),
            // PIFF legacy `uuid` TrackEncryptionBox โ€” the 16-byte
            // usertype leads the body; only the PIFF tenc usertype is
            // meaningful inside a `schi`. Same drop-on-malformed
            // policy as the 4CC `tenc`.
            UUID if out.piff_tenc.is_none()
                && inner.len() >= 16
                && inner[..16] == PIFF_TENC_USERTYPE =>
            {
                out.piff_tenc = parse_piff_tenc(&inner[16..]).ok();
            }
            STVI if out.stvi.is_none() => out.stvi = parse_stvi(&inner),
            _ => {}
        }
    }
    out
}

fn parse_sample_entry(entry: &[u8], t: &mut Track) -> Result<()> {
    if entry.len() < 8 {
        return Ok(());
    }
    // ยง9.1.2 / ยง9.4.1.2 / ยง9.4.2.3 โ€” RTP / SRTP / RTP-reception / RTCP-
    // reception hint sample entries. A hint track's handler maps to
    // MediaType::Data, so dispatch on the active stsd FourCC before the
    // media-type switch. A malformed entry leaves `rtp_hint` None rather
    // than aborting the open. `rtcp` shares the `rtp ` body (ยง9.4.2.3).
    if matches!(
        t.codec_id_fourcc,
        RTP_HINT | SRTP_HINT | RRTP_HINT | RTCP_HINT
    ) {
        t.rtp_hint = crate::hint::parse_rtp_hint_sample_entry(t.codec_id_fourcc, entry);
        return Ok(());
    }
    // ยง9.3.3.2 โ€” MPEG-2 TS server (`sm2t`) / reception (`rm2t`) hint
    // sample entries.
    if matches!(t.codec_id_fourcc, SM2T | RM2T) {
        t.mpeg2ts_hint = crate::hint::parse_mpeg2ts_hint_sample_entry(t.codec_id_fourcc, entry);
        return Ok(());
    }
    // QuickTime timecode media (`tmcd`): its handler maps to
    // MediaType::Data, so dispatch on the FourCC before the media-type
    // switch. A malformed entry leaves `tmcd` None rather than aborting.
    if t.codec_id_fourcc == TMCD {
        t.tmcd = parse_tmcd_sample_entry(entry);
        return Ok(());
    }
    match t.media_type {
        MediaType::Audio => parse_audio_sample_entry(entry, t),
        MediaType::Video => parse_video_sample_entry(entry, t),
        MediaType::Subtitle => parse_subtitle_sample_entry(entry, t),
        _ => Ok(()),
    }
}

/// Parse a subtitle / timed-text sample entry. Layout per
/// ISO/IEC 14496-12 ยง12.5โ€“6 and 3GPP TS 26.245 (for `tx3g`).
///
/// Common to every subtitle sample entry: 8 reserved bytes (6 + 2
/// data_reference_index). After that, the per-codec body varies:
///
/// * `wvtt` (WebVTT): the spec defines an inner `vttC` box (config) and
///   an optional `vlab` (label). We capture `vttC` as extradata.
/// * `stpp` (XML subtitle / TTML, BMFF ยง12.6.3.2): null-terminated
///   UTF-8 strings โ€” namespace, schema_location (optional),
///   auxiliary_mime_types (optional) โ€” then optional `btrt`. We store
///   `namespace\0schema_location\0aux_mime_types` as extradata so
///   callers can recover them.
/// * `sbtt`/`stxt` (BMFF ยง12.5โ€“6): content_encoding\0mime_format\0
///   plus optional `btrt`/`txtC`. Surface the strings as extradata.
/// * `tx3g` (3GPP TS 26.245): 18 bytes of display flags + colour +
///   default text box + style record, then optional `ftab` etc. The
///   3GPP TS 26.245 spec is not in `docs/`; we don't parse the body
///   today, but the FourCC dispatch / codec id (`mov_text`) is enough
///   for round-trip carriage through the demuxer.
/// * `text` (QuickTime plain text): same situation โ€” surfaced as a
///   subtitle stream without decoding.
/// * `c608` / `c708`: CEA-608/708 closed captions. Sample bytes carry
///   the raw caption packets; no extradata to surface.
fn parse_subtitle_sample_entry(entry: &[u8], t: &mut Track) -> Result<()> {
    // 8-byte preamble (6 reserved + 2 data_reference_index).
    if entry.len() < 8 {
        return Ok(());
    }
    // For BMFF text subtitle entries (`stpp`, `sbtt`, `stxt`) the
    // body after the preamble is a series of null-terminated UTF-8
    // strings. Capture them verbatim โ€” the demuxer doesn't interpret
    // their semantics, but consumers (e.g. a TTML renderer) do.
    match &t.codec_id_fourcc {
        b"stpp" | b"sbtt" | b"stxt" => {
            // Strings + optional child boxes. We need to skip the
            // strings before walking child boxes. Find the last null
            // terminator that ends the string-only region: stpp has up
            // to three strings (namespace, schema_location?,
            // auxiliary_mime_types?), sbtt/stxt have up to two
            // (content_encoding?, mime_format). All optional fields
            // are present as bare null-bytes when empty, so we walk to
            // the first byte that *could* be a box header (size+type).
            //
            // The simplest correct behaviour: copy the entire post-
            // preamble payload as extradata, including any trailing
            // `btrt`/`txtC` sub-boxes. Callers that need to extract
            // the strings can parse them with `splitn('\0')`.
            t.extradata = entry[8..].to_vec();
        }
        b"wvtt" => {
            // WebVTT in MP4: walk for the `vttC` config box (and
            // optional `vlab` label). The spec lives in ISO/IEC
            // 14496-30; we treat the entire post-preamble payload as
            // extradata so consumers can find the embedded `vttC`
            // header without re-parsing the BMFF surface.
            t.extradata = entry[8..].to_vec();
        }
        b"text" => {
            // QuickTime plain-text sample description: a fixed header
            // (display flags + justification + colours + default text box
            // + font) followed by a Pascal-string font name. Parse the
            // fixed numeric fields into a structured record; keep the raw
            // post-preamble bytes as extradata too (a renderer may want
            // the trailing font name / any nonstandard tail verbatim).
            t.text_entry = parse_text_sample_entry(entry);
            t.extradata = entry[8..].to_vec();
        }
        b"tx3g" | b"c608" | b"c708" => {
            // `tx3g` carries an 18-byte fixed header (display flags +
            // colours + default text box + default style record) plus
            // optional `ftab` font table. Treat the entire post-
            // preamble payload as extradata so a downstream renderer
            // can pick the colour / style defaults out of it.
            //
            // For `c608` / `c708` no useful per-track header is defined;
            // the post-preamble bytes are still preserved as extradata
            // for any nonstandard carriage.
            t.extradata = entry[8..].to_vec();
        }
        _ => {}
    }
    Ok(())
}

fn parse_audio_sample_entry(entry: &[u8], t: &mut Track) -> Result<()> {
    // AudioSampleEntryV0 layout:
    //   6 bytes reserved
    //   2 bytes data_reference_index
    //   8 bytes reserved (or version/revision/vendor in QT-style)
    //   2 bytes channel_count
    //   2 bytes sample_size
    //   4 bytes reserved
    //   4 bytes sample_rate (16.16 fixed)
    // = 28 bytes, followed by child boxes.
    if entry.len() < 28 {
        return Ok(());
    }
    let channels = u16::from_be_bytes([entry[16], entry[17]]);
    let sample_size = u16::from_be_bytes([entry[18], entry[19]]);
    let sample_rate = u32::from_be_bytes([entry[24], entry[25], entry[26], entry[27]]) >> 16;
    t.channels = Some(channels);
    t.sample_size_bits = Some(sample_size);
    t.sample_rate = Some(sample_rate);

    // Child boxes (dfLa, dOps, esds, ...).
    let mut cur = std::io::Cursor::new(&entry[28..]);
    let end = (entry.len() - 28) as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let body = read_bytes_vec(&mut cur, psz)?;
        match &hdr.fourcc {
            // FLAC-in-MP4 dfLa: 1 byte version + 3 bytes flags + metadata blocks.
            // Our FLAC decoder wants just the metadata blocks.
            b"dfLa" if body.len() > 4 => {
                t.extradata = body[4..].to_vec();
            }
            // Opus-in-MP4 dOps: a subset of OpusHead without the 8-byte magic.
            // We rebuild OpusHead so our downstream code can treat it uniformly.
            b"dOps" if body.len() >= 11 => {
                let mut oh = Vec::with_capacity(body.len() + 8);
                oh.extend_from_slice(b"OpusHead");
                oh.extend_from_slice(&body);
                t.extradata = oh;
            }
            // ES Descriptor box for MPEG-4 audio (mp4a): strip the nested
            // descriptor wrappers and hand the DecoderSpecificInfo (the AAC
            // AudioSpecificConfig) straight to the decoder via extradata.
            // We also capture the `objectTypeIndication` so the codec-id
            // resolver can disambiguate MP3-in-mp4a vs. AAC-in-mp4a.
            b"esds" if body.len() >= 4 => {
                if let Some(parsed) = parse_esds(&body[4..]) {
                    if !parsed.dsi.is_empty() {
                        t.extradata = parsed.dsi;
                    }
                    t.esds_oti = parsed.oti;
                }
            }
            // ALAC magic cookie (`alac` config child inside an `alac`
            // entry): a FullBox โ€” 4 bytes version/flags then the cookie.
            // Surface the cookie bytes (mirroring the dfLa convention);
            // the muxer's `alac_entry` re-wraps them byte-exact.
            b"alac" if body.len() > 4 => {
                t.extradata = body[4..].to_vec();
            }
            // AC-3 specific config (`dac3`, ETSI TS 102 366 Annex F.4)
            // and E-AC-3 specific config (`dec3`, Annex G.4). Keep the
            // raw box payload as extradata so downstream decoders that
            // care about `fscod`/`bsid`/`acmod`/`lfeon`/etc. can parse
            // it themselves. For decoders that don't need it the bytes
            // are harmless extra context.
            b"dac3" | b"dec3" => t.extradata = body,
            // BitRateBox (ISO/IEC 14496-12 ยง8.5.2) โ€” optional, at the end
            // of any sample entry including audio. First wins; short body
            // dropped (informational).
            b"btrt" if t.btrt.is_none() => {
                if let Some(rec) = parse_btrt(&body) {
                    t.btrt = Some(rec);
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// What we extract from an esds box: the DecoderSpecificInfo (empty when
/// absent) and the DecoderConfigDescriptor's `objectTypeIndication` byte.
#[derive(Default)]
struct EsdsInfo {
    dsi: Vec<u8>,
    oti: Option<u8>,
}

/// Parse an esds `ES_Descriptor` payload (the part after the `FullBox`
/// version+flags) and return its DecoderSpecificInfo bytes together with
/// the `objectTypeIndication` byte from the DecoderConfigDescriptor.
///
/// ES_Descriptor layout (ISO/IEC 14496-1 ยง7.2.6):
///   tag 0x03, BER length,
///   ES_ID (u16), flags (u8) โ€” plus optional dependsOn/URL/OCR fields,
///   DecoderConfigDescriptor (tag 0x04) {
///     objectTypeIndication (u8),
///     streamType+upstream+reserved (u8),
///     bufferSizeDB (u24),
///     maxBitrate (u32),
///     avgBitrate (u32),
///     DecoderSpecificInfo (tag 0x05) โ€” the ASC (or whatever the codec
///     uses as its setup header),
///   },
///   SLConfigDescriptor (tag 0x06).
///
/// Returns `None` only if the outer ES_Descriptor itself is malformed.
/// A well-formed ES_Descriptor with no DCD returns `EsdsInfo::default()`.
fn parse_esds(buf: &[u8]) -> Option<EsdsInfo> {
    let mut info = EsdsInfo::default();
    let mut cur = 0usize;
    let (tag, len, hdr_bytes) = read_descr(buf, cur)?;
    if tag != 0x03 {
        return None;
    }
    cur += hdr_bytes;
    let es_end = cur.checked_add(len)?;
    if es_end > buf.len() {
        return None;
    }
    // ES_ID + flags byte (3 bytes). Flags byte bit 7 = streamDependenceFlag,
    // bit 6 = URL_Flag, bit 5 = OCRstreamFlag โ€” each enables extra fields.
    if cur + 3 > es_end {
        return None;
    }
    let flags = buf[cur + 2];
    cur += 3;
    if flags & 0x80 != 0 {
        cur = cur.checked_add(2)?; // dependsOn_ES_ID
    }
    if flags & 0x40 != 0 {
        // URL: 1-byte length + that many bytes.
        if cur >= es_end {
            return None;
        }
        let url_len = buf[cur] as usize;
        cur = cur.checked_add(1 + url_len)?;
    }
    if flags & 0x20 != 0 {
        cur = cur.checked_add(2)?; // OCR_ES_ID
    }

    // Walk sub-descriptors looking for DecoderConfigDescriptor.
    while cur < es_end {
        let (sub_tag, sub_len, sub_hdr) = read_descr(buf, cur)?;
        cur += sub_hdr;
        let sub_end = cur.checked_add(sub_len)?;
        if sub_end > es_end {
            return None;
        }
        if sub_tag == 0x04 {
            // DecoderConfigDescriptor: 13 fixed bytes then nested descriptors.
            // First byte is the objectTypeIndication we care about.
            if sub_len < 13 {
                return None;
            }
            info.oti = Some(buf[cur]);
            if sub_len > 13 {
                let mut inner = cur + 13;
                while inner < sub_end {
                    let (dsi_tag, dsi_len, dsi_hdr) = read_descr(buf, inner)?;
                    inner += dsi_hdr;
                    let dsi_end = inner.checked_add(dsi_len)?;
                    if dsi_end > sub_end {
                        return None;
                    }
                    if dsi_tag == 0x05 {
                        info.dsi = buf[inner..dsi_end].to_vec();
                        break;
                    }
                    inner = dsi_end;
                }
            }
        }
        cur = sub_end;
    }
    Some(info)
}

/// Back-compat thin wrapper โ€” returns just the DSI bytes.
#[cfg(test)]
fn parse_esds_dsi(buf: &[u8]) -> Option<Vec<u8>> {
    let info = parse_esds(buf)?;
    if info.dsi.is_empty() {
        None
    } else {
        Some(info.dsi)
    }
}

/// Read one MPEG-4 descriptor header (tag + BER-encoded length). Returns
/// `(tag, content_length, header_bytes_consumed)`. Length bytes use the
/// standard 7-bit varint with a continuation flag in bit 7; caps at 4 bytes.
fn read_descr(buf: &[u8], off: usize) -> Option<(u8, usize, usize)> {
    if off >= buf.len() {
        return None;
    }
    let tag = buf[off];
    let mut len: usize = 0;
    let mut consumed = 1usize;
    for _ in 0..4 {
        let p = off + consumed;
        if p >= buf.len() {
            return None;
        }
        let b = buf[p];
        consumed += 1;
        len = (len << 7) | (b & 0x7F) as usize;
        if b & 0x80 == 0 {
            return Some((tag, len, consumed));
        }
    }
    None
}

fn parse_video_sample_entry(entry: &[u8], t: &mut Track) -> Result<()> {
    // VisualSampleEntry: 6 reserved + 2 data_ref_idx + 16 pre_defined +
    // 2 width + 2 height + ... = 78 bytes total payload. Offsets per
    // ISO/IEC 14496-12.
    if entry.len() < 28 {
        return Ok(());
    }
    let width = u16::from_be_bytes([entry[24], entry[25]]);
    let height = u16::from_be_bytes([entry[26], entry[27]]);
    t.width = Some(width as u32);
    t.height = Some(height as u32);

    // Walk the codec-specific child boxes that sit after the 78-byte
    // VisualSampleEntry preamble. We surface configuration records as
    // extradata so downstream codec crates can bootstrap from them.
    if entry.len() <= 78 {
        return Ok(());
    }
    let mut cur = std::io::Cursor::new(&entry[78..]);
    let end = (entry.len() - 78) as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        let body = read_bytes_vec(&mut cur, psz)?;
        match &hdr.fourcc {
            // AVCConfigurationRecord (ISO/IEC 14496-15 ยง5.3.3) โ€” for
            // h264, our decoder consumes this verbatim.
            b"avcC" => t.extradata = body,
            // HEVCDecoderConfigurationRecord (ISO/IEC 14496-15 ยง8.3.3).
            b"hvcC" => t.extradata = body,
            // AV1CodecConfigurationRecord โ€” av1C box per the AV1 ISOBMFF spec.
            b"av1C" => t.extradata = body,
            // VPCodecConfigurationRecord โ€” vpcC box for VP8 / VP9.
            b"vpcC" => t.extradata = body,
            // H.263 decoder configuration (`d263`, the 3GPP MP4 packaging's
            // config child inside an `s263` entry). Kept verbatim as opaque
            // extradata โ€” the muxer's `h263_entry` re-emits it byte-exact.
            b"d263" => t.extradata = body,
            // esds for `mp4v` sample entries. Same shape as the audio variant.
            // We keep the DSI (MPEG-4 VOL header for Part 2, etc.) as
            // extradata and remember the OTI so `from_sample_entry_with_oti`
            // can refine `mp4v` into `mpeg1video` / `mpeg2video` / etc.
            b"esds" if body.len() >= 4 => {
                if let Some(parsed) = parse_esds(&body[4..]) {
                    if !parsed.dsi.is_empty() {
                        t.extradata = parsed.dsi;
                    }
                    t.esds_oti = parsed.oti;
                }
            }
            // AmbientViewingEnvironmentBox (ISO/IEC 14496-12 post-2015) โ€”
            // the file-format carriage of the ambient_viewing_environment
            // SEI / ISO/IEC 23091-3 parameters. A plain Box (no FullBox
            // version/flags), fixed 8-byte body. First one on the track
            // wins; a malformed (short) body is dropped (informational โ€”
            // it never aborts the open).
            b"amve" if t.amve.is_none() => {
                if let Some(rec) = parse_amve(&body) {
                    t.amve = Some(rec);
                }
            }
            // BitRateBox (ISO/IEC 14496-12 ยง8.5.2) โ€” an optional plain
            // Box (no FullBox version/flags) at the end of the sample
            // entry carrying `bufferSizeDB` / `maxBitrate` / `avgBitrate`.
            // First one on the active entry wins; a short body is dropped
            // (informational โ€” it never aborts the open).
            b"btrt" if t.btrt.is_none() => {
                if let Some(rec) = parse_btrt(&body) {
                    t.btrt = Some(rec);
                }
            }
            // PixelAspectRatioBox (ยง12.1.4) โ€” a plain Box (no FullBox
            // preamble), 8-byte body (hSpacing / vSpacing). First one on
            // the active entry wins; a short body is dropped.
            b"pasp" if t.pasp.is_none() => {
                if let Some(rec) = parse_pasp(&body) {
                    t.pasp = Some(rec);
                }
            }
            // CleanApertureBox (ยง12.1.4) โ€” a plain Box, 32-byte body of
            // four (N, D) fractions. First one wins; short body dropped.
            b"clap" if t.clap.is_none() => {
                if let Some(rec) = parse_clap(&body) {
                    t.clap = Some(rec);
                }
            }
            // ColourInformationBox (ยง12.1.5) โ€” a plain Box; the spec
            // allows several (most-accurate first), the first wins here.
            b"colr" if t.colr.is_none() => {
                if let Some(rec) = parse_colr(&body) {
                    t.colr = Some(rec);
                }
            }
            // Restricted-scheme (ยง8.15) video โ€” a non-encrypted
            // `VisualSampleEntry` (e.g. a `resv` whose original FourCC is
            // already preserved here, or any entry signalling a
            // restricted scheme) carries its `sinf` directly as a child
            // box rather than wrapped by an `enc*` outer FourCC. Descend
            // it to recover an `stvi` (StereoVideoBox, ยง8.15.4.2) from
            // the `schi` when the SchemeType is `stvi`. The `enc*` path
            // (handled before `parse_sample_entry`) already populated
            // `t.stvi` for protected entries โ€” first one wins.
            b"sinf" if t.stvi.is_none() => {
                if let Ok(unwrap) = parse_sinf_body(&body) {
                    t.stvi = unwrap.stvi;
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// Parse an `amve` (AmbientViewingEnvironmentBox) body โ€” the 8 bytes
/// after the plain 8-byte box header (`amve` is a `Box`, not a
/// `FullBox`, so there is no version/flags preamble).
///
/// Returns `None` for a body shorter than the fixed 8-byte layout
/// (`ambient_illuminance` u32 + `ambient_light_x` u16 +
/// `ambient_light_y` u16). Trailing bytes beyond byte 8 โ€” reserved for a
/// future edition โ€” are ignored so an extended box still parses.
fn parse_amve(body: &[u8]) -> Option<AmveRecord> {
    if body.len() < 8 {
        return None;
    }
    let ambient_illuminance = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
    let ambient_light_x = u16::from_be_bytes([body[4], body[5]]);
    let ambient_light_y = u16::from_be_bytes([body[6], body[7]]);
    Some(AmveRecord {
        ambient_illuminance,
        ambient_light_x,
        ambient_light_y,
    })
}

/// Parse a `btrt` (BitRateBox, ISO/IEC 14496-12 ยง8.5.2) body โ€” the 12
/// bytes after the plain 8-byte box header (`btrt` is a `Box`, not a
/// `FullBox`, so there is no version/flags preamble).
///
/// The body is exactly three big-endian `u32`s: `bufferSizeDB`,
/// `maxBitrate`, `avgBitrate`. Returns `None` for a body shorter than
/// 12 bytes (a truncated box). Trailing bytes beyond byte 12 โ€” none are
/// defined by ยง8.5.2, but a future edition could append fields โ€” are
/// ignored so an extended box still parses, matching the `parse_amve`
/// posture.
fn parse_btrt(body: &[u8]) -> Option<BtrtRecord> {
    if body.len() < 12 {
        return None;
    }
    let buffer_size_db = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
    let max_bitrate = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let avg_bitrate = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    Some(BtrtRecord {
        buffer_size_db,
        max_bitrate,
        avg_bitrate,
    })
}

/// Parse a `pasp` (PixelAspectRatioBox, ISO/IEC 14496-12 ยง12.1.4) body โ€”
/// the 8 bytes after the plain box header (`pasp` is a `Box`, not a
/// `FullBox`). `None` for a body shorter than 8 bytes.
pub fn parse_pasp(body: &[u8]) -> Option<PaspRecord> {
    if body.len() < 8 {
        return None;
    }
    Some(PaspRecord {
        h_spacing: u32::from_be_bytes([body[0], body[1], body[2], body[3]]),
        v_spacing: u32::from_be_bytes([body[4], body[5], body[6], body[7]]),
    })
}

/// Parse a `clap` (CleanApertureBox, ISO/IEC 14496-12 ยง12.1.4) body โ€”
/// the 32 bytes (eight u32s) after the plain box header. `None` for a
/// body shorter than 32 bytes.
pub fn parse_clap(body: &[u8]) -> Option<ClapRecord> {
    if body.len() < 32 {
        return None;
    }
    let u = |i: usize| u32::from_be_bytes([body[i], body[i + 1], body[i + 2], body[i + 3]]);
    Some(ClapRecord {
        width_n: u(0),
        width_d: u(4),
        height_n: u(8),
        height_d: u(12),
        horiz_off_n: u(16),
        horiz_off_d: u(20),
        vert_off_n: u(24),
        vert_off_d: u(28),
    })
}

/// Parse a `colr` (ColourInformationBox, ISO/IEC 14496-12 ยง12.1.5) body
/// โ€” the bytes after the plain box header (`colr` is a `Box`). The first
/// four bytes are the `colour_type`; the remaining payload depends on
/// it (ยง12.1.5.2). `None` for a body shorter than the 4-byte type, or a
/// truncated `nclx` payload.
pub fn parse_colr(body: &[u8]) -> Option<ColrRecord> {
    if body.len() < 4 {
        return None;
    }
    let colour_type = [body[0], body[1], body[2], body[3]];
    let rest = &body[4..];
    match &colour_type {
        b"nclx" => {
            // colour_primaries(16) + transfer(16) + matrix(16) +
            // full_range_flag(1) + reserved(7).
            if rest.len() < 7 {
                return None;
            }
            Some(ColrRecord::Nclx {
                colour_primaries: u16::from_be_bytes([rest[0], rest[1]]),
                transfer_characteristics: u16::from_be_bytes([rest[2], rest[3]]),
                matrix_coefficients: u16::from_be_bytes([rest[4], rest[5]]),
                full_range: rest[6] & 0x80 != 0,
            })
        }
        b"rICC" => Some(ColrRecord::RestrictedIcc(rest.to_vec())),
        b"prof" => Some(ColrRecord::UnrestrictedIcc(rest.to_vec())),
        _ => Some(ColrRecord::Other {
            colour_type,
            data: rest.to_vec(),
        }),
    }
}

/// Parse an `stvi` (StereoVideoBox, ISO/IEC 14496-12 ยง8.15.4.2) body โ€”
/// the bytes after the 4-byte FullBox version/flags preamble.
///
/// Layout (ยง8.15.4.2.2):
///
/// ```text
/// template int(30) reserved = 0;
/// int(2)  single_view_allowed;
/// int(32) stereo_scheme;
/// int(32) length;
/// int(8)[length] stereo_indication_type;
/// Box[] any_box;  // optional, ignored at this layer
/// ```
///
/// The first 32-bit word packs the 30-bit reserved field (high bits)
/// and the 2-bit `single_view_allowed` (low bits). The reserved bits
/// are masked off so a producer slip on them does not corrupt the
/// surfaced value. `length` is validated against the bytes actually
/// present; a `length` that overruns the body is rejected (`None`)
/// rather than reading past the end. Trailing `any_box` bytes after the
/// `stereo_indication_type` array are ignored. Returns `None` for a
/// body too short to hold the fixed 12-byte (preamble-relative) header.
fn parse_stvi(body: &[u8]) -> Option<StviRecord> {
    // 4-byte FullBox preamble + 4 (single_view_allowed word) + 4
    // (stereo_scheme) + 4 (length) = 16 bytes minimum.
    if body.len() < 16 {
        return None;
    }
    // FullBox preamble: version (1) + flags (3). ยง8.15.4.2.2 pins
    // version 0; we tolerate a non-zero version (the layout is
    // unambiguous), matching the `parse_pdin` / `parse_padb` posture.
    let svw = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    // Low 2 bits are `single_view_allowed`; the upper 30 are reserved.
    let single_view_allowed = (svw & 0x3) as u8;
    let stereo_scheme = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    let length = u32::from_be_bytes([body[12], body[13], body[14], body[15]]) as usize;
    let sit_start: usize = 16;
    // `length` must not run past the bytes present (a truncated /
    // forged length would otherwise read trailing `any_box` content or
    // off the end).
    let sit_end = sit_start.checked_add(length)?;
    if sit_end > body.len() {
        return None;
    }
    let stereo_indication_type = body[sit_start..sit_end].to_vec();
    Some(StviRecord {
        single_view_allowed,
        stereo_scheme,
        stereo_indication_type,
    })
}

fn parse_stts(body: &[u8]) -> Result<Vec<(u32, u32)>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: stts too short"));
    }
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    // 8 bytes per entry on the wire โ€” cap the reservation at what the
    // body can back.
    let mut out = Vec::with_capacity(count.min(body.len() / 8));
    let mut off = 8;
    for _ in 0..count {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: stts truncated"));
        }
        let cnt = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        let dlt = u32::from_be_bytes([body[off + 4], body[off + 5], body[off + 6], body[off + 7]]);
        out.push((cnt, dlt));
        off += 8;
    }
    Ok(out)
}

fn parse_stsc(body: &[u8]) -> Result<Vec<(u32, u32, u32)>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: stsc too short"));
    }
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let mut out = Vec::with_capacity(count.min(body.len() / 12));
    let mut off = 8;
    for _ in 0..count {
        if off + 12 > body.len() {
            return Err(Error::invalid("MP4: stsc truncated"));
        }
        let fc = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        let spc = u32::from_be_bytes([body[off + 4], body[off + 5], body[off + 6], body[off + 7]]);
        let sdi =
            u32::from_be_bytes([body[off + 8], body[off + 9], body[off + 10], body[off + 11]]);
        out.push((fc, spc, sdi));
        off += 12;
    }
    Ok(out)
}

fn parse_stsz(body: &[u8], file_size: u64) -> Result<Vec<u32>> {
    if body.len() < 12 {
        return Err(Error::invalid("MP4: stsz too short"));
    }
    let uniform = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let count = u32::from_be_bytes([body[8], body[9], body[10], body[11]]) as usize;
    if uniform != 0 {
        // Constant-size shape: the count is backed by no table bytes,
        // but every claimed sample must occupy `uniform` bytes of this
        // file's mdat โ€” so `count ร— uniform` can never exceed the file
        // size. Rejecting beyond that stops a forged 32-bit count from
        // driving a multi-GiB materialisation from a tiny input.
        if (count as u64).saturating_mul(uniform as u64) > file_size {
            return Err(Error::invalid(
                "MP4: stsz constant-size sample_count exceeds what the file can back",
            ));
        }
        return Ok(vec![uniform; count]);
    }
    // Per-sample shape: one u32 per sample โ€” cap the reservation at
    // what the table bytes can back (the loop still reports precise
    // truncation).
    let mut out = Vec::with_capacity(count.min(body.len() / 4));
    let mut off = 12;
    for _ in 0..count {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: stsz truncated"));
        }
        out.push(u32::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
        ]));
        off += 4;
    }
    Ok(out)
}

fn parse_stz2(body: &[u8]) -> Result<Vec<u32>> {
    if body.len() < 12 {
        return Err(Error::invalid("MP4: stz2 too short"));
    }
    let field_size = body[7];
    let count = u32::from_be_bytes([body[8], body[9], body[10], body[11]]) as usize;
    let mut out = Vec::with_capacity(count.min(body.len().saturating_mul(2)));
    let off = 12;
    match field_size {
        4 => {
            for i in 0..count {
                if off + i / 2 >= body.len() {
                    return Err(Error::invalid("MP4: stz2 4-bit truncated"));
                }
                let b = body[off + i / 2];
                let v = if i % 2 == 0 { b >> 4 } else { b & 0x0F };
                out.push(v as u32);
            }
        }
        8 => {
            if off + count > body.len() {
                return Err(Error::invalid("MP4: stz2 8-bit truncated"));
            }
            for i in 0..count {
                out.push(body[off + i] as u32);
            }
        }
        16 => {
            if off + count * 2 > body.len() {
                return Err(Error::invalid("MP4: stz2 16-bit truncated"));
            }
            for i in 0..count {
                out.push(u16::from_be_bytes([body[off + 2 * i], body[off + 2 * i + 1]]) as u32);
            }
        }
        _ => return Err(Error::invalid("MP4: stz2 invalid field size")),
    }
    Ok(out)
}

fn parse_stss(body: &[u8]) -> Result<Vec<u32>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: stss too short"));
    }
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let mut out = Vec::with_capacity(count.min(body.len() / 4));
    let mut off = 8;
    for _ in 0..count {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: stss truncated"));
        }
        out.push(u32::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
        ]));
        off += 4;
    }
    Ok(out)
}

/// Parse `stsh` (ShadowSyncSampleBox, ISO/IEC 14496-12 ยง8.6.3).
///
/// `FullBox(version = 0, flags = 0)` whose body is a `u32` `entry_count`
/// followed by that many `(shadowed_sample_number, sync_sample_number)`
/// pairs, each a big-endian `u32`. The first member names a (normally
/// non-sync) sample; the second names a sync sample that can be decoded
/// in its place when seeking to or before the shadowed sample. The
/// table is ordered by `shadowed_sample_number` per ยง8.6.3.1, but we
/// keep on-wire order so the bytes round-trip without assuming the
/// producer honoured the ordering recommendation.
///
/// `with_capacity` is bounded by the byte budget (`(len - 8) / 8`) so an
/// adversarial `entry_count` can't trigger a giant up-front allocation;
/// the per-entry bounds check rejects a body that is shorter than the
/// claimed count.
fn parse_stsh(body: &[u8]) -> Result<Vec<(u32, u32)>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: stsh too short"));
    }
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let max_entries = (body.len() - 8) / 8;
    let mut out = Vec::with_capacity(count.min(max_entries));
    let mut off = 8;
    for _ in 0..count {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: stsh truncated"));
        }
        let shadowed = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        let sync = u32::from_be_bytes([body[off + 4], body[off + 5], body[off + 6], body[off + 7]]);
        out.push((shadowed, sync));
        off += 8;
    }
    Ok(out)
}

/// Parse `sdtp` (SampleDependencyTypeBox, ISO/IEC 14496-12 ยง8.6.4).
///
/// `FullBox(version = 0, flags = 0)` whose body, after the 4-byte
/// FullBox preamble, is one byte per sample. The `sample_count` is
/// taken from `stsz` / `stz2` and is *not* re-stated in the box, so
/// the table's length is simply `body.len() - 4`. Each byte is four
/// 2-bit fields packed MSB-first per ยง8.6.4.2:
///
/// ```text
///     unsigned int(2) is_leading;
///     unsigned int(2) sample_depends_on;
///     unsigned int(2) sample_is_depended_on;
///     unsigned int(2) sample_has_redundancy;
/// ```
///
/// Each 2-bit value's permitted set is in ยง8.6.4.3 (e.g.
/// `sample_depends_on = 2` โ†’ "I-picture"; `sample_is_depended_on = 2`
/// โ†’ "disposable"). The container preserves the raw small ints; a
/// trick-mode renderer or seek heuristic interprets them.
///
/// If the producer wrote a table longer than the track's
/// `sample_count`, the trailing bytes are still parsed โ€” callers
/// that care about alignment between the table and the sample list
/// cross-check the lengths themselves.
fn parse_sdtp(body: &[u8]) -> Result<Vec<SdtpEntry>> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: sdtp too short"));
    }
    // ยง8.6.4.2 fixes version = 0 and the FullBox preamble carries no
    // useful flags; tolerate both rather than rejecting a wrong-version
    // table, since the byte format is unambiguous.
    let payload = &body[4..];
    let mut out = Vec::with_capacity(payload.len());
    for &byte in payload {
        out.push(SdtpEntry {
            is_leading: (byte >> 6) & 0x03,
            sample_depends_on: (byte >> 4) & 0x03,
            sample_is_depended_on: (byte >> 2) & 0x03,
            sample_has_redundancy: byte & 0x03,
        });
    }
    Ok(out)
}

/// Parse `stdp` (DegradationPriorityBox, ISO/IEC 14496-12 ยง8.5.3).
///
/// `FullBox(version = 0, flags = 0)` whose body, after the 4-byte
/// FullBox preamble, is a packed array of big-endian `unsigned int(16)
/// priority` entries โ€” one per sample. The `sample_count` is taken
/// from `stsz` / `stz2` and is *not* re-stated in the box (ยง8.5.3.1),
/// so the table's length is simply `(body.len() - 4) / 2`. A trailing
/// odd byte (the spec never produces one โ€” `priority` is always
/// 16-bit) is silently ignored rather than rejecting the whole box.
///
/// The exact meaning and acceptable range of `priority` are defined
/// by derived specifications (ยง8.5.3.3 "Specifications derived from
/// this define the exact meaning and acceptable range of the
/// `priority` field"); the container preserves the raw u16 values
/// without interpreting them. A renderer that needs to drop samples
/// under bitrate / CPU pressure consults the carrying spec for the
/// priority ordering.
fn parse_stdp(body: &[u8]) -> Result<Vec<u16>> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: stdp too short"));
    }
    // ยง8.5.3.2 pins version = 0 and there are no defined flags; the
    // FullBox preamble carries no information beyond that, so tolerate
    // whatever the producer wrote โ€” the per-sample u16 layout is
    // unambiguous.
    let payload = &body[4..];
    let count = payload.len() / 2;
    let mut out = Vec::with_capacity(count);
    for i in 0..count {
        let off = i * 2;
        out.push(u16::from_be_bytes([payload[off], payload[off + 1]]));
    }
    Ok(out)
}

/// ยง8.7.6 โ€” `padb` (PaddingBitsBox) typed accessor.
///
/// `FullBox(version = 0, flags = 0)` whose body is:
///
/// ```text
///     unsigned int(32) sample_count
///     for i in 0 .. (sample_count + 1) / 2 {
///         bit(1) reserved = 0; bit(3) pad1;   // top nibble
///         bit(1) reserved = 0; bit(3) pad2;   // bottom nibble
///     }
/// ```
///
/// Each nibble's reserved bit is required to be 0 per ยง8.7.6.2 but is
/// not enforced here โ€” the container layer surfaces what the producer
/// wrote rather than rejecting on a reserved-bit slip; a strict
/// validator can re-check by walking the raw box bytes.
///
/// `pad1` is the padding-bit count for sample number `(i * 2) + 1`,
/// `pad2` for sample `(i * 2) + 2` (ยง8.7.6.3 โ€” sample numbering is
/// 1-based on the wire; the returned vec is 0-indexed so entry `n` is
/// the padding-bit count for the `n+1`-th sample). When `sample_count`
/// is odd the trailing `pad2` nibble is unused and dropped: the
/// returned vec is exactly `sample_count` long.
///
/// `sample_count == 0` is permitted (a zero-sample padb yields an empty
/// vec). A body too short for the declared `sample_count` is rejected
/// rather than silently truncated โ€” the spec mandates the box carry
/// `(sample_count + 1) / 2` bytes of data.
///
/// Unlike `sdtp` / `stdp` (whose sample count is implicit from
/// `stsz` / `stz2`), `padb` re-declares its own `sample_count` on the
/// wire and the table is self-contained; if a producer wrote a
/// `sample_count` larger than the track's actual sample count the
/// trailing entries are still returned โ€” a length mismatch is the
/// producer's bug, not ours to invent zeros for.
fn parse_padb(body: &[u8]) -> Result<Vec<u8>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: padb too short"));
    }
    // ยง8.7.6.2 pins version = 0 and there are no defined flags; the
    // FullBox preamble carries no useful information beyond that.
    let sample_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let need = sample_count.div_ceil(2);
    if body.len() < 8 + need {
        return Err(Error::invalid(
            "MP4: padb body shorter than declared sample_count",
        ));
    }
    let payload = &body[8..8 + need];
    let mut out = Vec::with_capacity(sample_count);
    for (i, &byte) in payload.iter().enumerate() {
        // Top nibble = pad1 (sample (i*2)+1); bottom nibble = pad2
        // (sample (i*2)+2). The low 3 bits of each nibble carry the
        // padding-bit count; the high bit is a reserved zero per
        // ยง8.7.6.2 and is masked off here so a producer slip on the
        // reserved bit does not corrupt the count.
        let pad1 = (byte >> 4) & 0x07;
        out.push(pad1);
        if out.len() == sample_count {
            break;
        }
        let pad2 = byte & 0x07;
        out.push(pad2);
        if out.len() == sample_count {
            break;
        }
        // Suppress the unused-binding warning when no break fires (i
        // is the byte index but we don't need it here โ€” kept for
        // future per-byte diagnostics).
        let _ = i;
    }
    Ok(out)
}

/// Parse `sbgp` (SampleToGroupBox, ISO/IEC 14496-12 ยง8.9.2).
///
/// `FullBox(version, 0)`:
///
/// ```text
///     unsigned int(32) grouping_type
///     if (version == 1) unsigned int(32) grouping_type_parameter
///     unsigned int(32) entry_count
///     entry_count ร— {
///         unsigned int(32) sample_count
///         unsigned int(32) group_description_index
///     }
/// ```
///
/// The table is a run-length map: each entry covers `sample_count`
/// consecutive decode-order samples that all share
/// `group_description_index`. An index of 0 means "member of no group of
/// this type" (ยง8.9.2.3); indices โ‰ฅ 0x10001 are movie-fragment-local
/// references (ยง8.9.4) and are preserved verbatim โ€” the demuxer does not
/// resolve them against a fragment's own `sgpd`.
///
/// `with_capacity` is bounded by the byte budget so an adversarial
/// `entry_count` cannot trigger a giant up-front allocation; the
/// per-entry bounds check rejects a truncated body.
fn parse_sbgp(body: &[u8]) -> Result<SbgpBox> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: sbgp too short"));
    }
    let version = body[0];
    let mut off = 4;
    let read_u32 = |b: &[u8], o: usize| -> Option<u32> {
        b.get(o..o + 4)
            .map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
    };
    let grouping_type_raw =
        read_u32(body, off).ok_or_else(|| Error::invalid("MP4: sbgp grouping_type truncated"))?;
    let grouping_type = grouping_type_raw.to_be_bytes();
    off += 4;
    let grouping_type_parameter = if version == 1 {
        let p = read_u32(body, off)
            .ok_or_else(|| Error::invalid("MP4: sbgp grouping_type_parameter truncated"))?;
        off += 4;
        Some(p)
    } else {
        None
    };
    let count = read_u32(body, off)
        .ok_or_else(|| Error::invalid("MP4: sbgp entry_count truncated"))? as usize;
    off += 4;
    let max_entries = body.len().saturating_sub(off) / 8;
    let mut entries = Vec::with_capacity(count.min(max_entries));
    for _ in 0..count {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: sbgp entries truncated"));
        }
        let sample_count =
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        let gdi = u32::from_be_bytes([body[off + 4], body[off + 5], body[off + 6], body[off + 7]]);
        entries.push((sample_count, gdi));
        off += 8;
    }
    Ok(SbgpBox {
        grouping_type,
        grouping_type_parameter,
        entries,
    })
}

/// Parse `sgpd` (SampleGroupDescriptionBox, ISO/IEC 14496-12 ยง8.9.3).
///
/// `FullBox(version, 0)`:
///
/// ```text
///     unsigned int(32) grouping_type
///     if (version == 1) unsigned int(32) default_length
///     if (version >= 2) unsigned int(32) default_sample_description_index
///     unsigned int(32) entry_count
///     entry_count ร— {
///         if (version == 1 && default_length == 0)
///             unsigned int(32) description_length
///         SampleGroupEntry(grouping_type)   // grouping-type-specific blob
///     }
/// ```
///
/// The per-entry `SampleGroupEntry` payload is grouping-type-specific and
/// opaque to the container โ€” we capture its raw bytes verbatim and leave
/// interpretation to the layer that knows the `grouping_type` semantics.
///
/// Entry sizing follows ยง8.9.3.2:
/// * version 1 with `default_length > 0`: every entry is `default_length`
///   bytes.
/// * version 1 with `default_length == 0`: each entry is preceded by a
///   `u32` `description_length`.
/// * version 0 / version โ‰ฅ 2 with no per-entry length: the spec notes
///   version-0 entries carry no signalled size (ยง8.9.3.3 NOTE โ€” their use
///   is deprecated precisely because they cannot be scanned). When the
///   box gives us no length to chunk by, we fall back to treating the
///   remaining body as a single combined entry blob rather than guessing
///   a fixed entry size we cannot know โ€” callers that recognise the
///   `grouping_type` can re-split it.
fn parse_sgpd(body: &[u8]) -> Result<SgpdBox> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: sgpd too short"));
    }
    let version = body[0];
    let mut off = 4;
    let read_u32 = |b: &[u8], o: usize| -> Option<u32> {
        b.get(o..o + 4)
            .map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
    };
    let grouping_type_raw =
        read_u32(body, off).ok_or_else(|| Error::invalid("MP4: sgpd grouping_type truncated"))?;
    let grouping_type = grouping_type_raw.to_be_bytes();
    off += 4;
    let default_length = if version == 1 {
        let dl = read_u32(body, off)
            .ok_or_else(|| Error::invalid("MP4: sgpd default_length truncated"))?;
        off += 4;
        dl
    } else {
        0
    };
    let default_sample_description_index = if version >= 2 {
        let d = read_u32(body, off).ok_or_else(|| {
            Error::invalid("MP4: sgpd default_sample_description_index truncated")
        })?;
        off += 4;
        Some(d)
    } else {
        None
    };
    let count = read_u32(body, off)
        .ok_or_else(|| Error::invalid("MP4: sgpd entry_count truncated"))? as usize;
    off += 4;

    let mut entries: Vec<Vec<u8>> = Vec::new();
    if version == 1 && default_length == 0 {
        // Each entry prefixed with its own u32 description_length.
        for _ in 0..count {
            let len = read_u32(body, off)
                .ok_or_else(|| Error::invalid("MP4: sgpd description_length truncated"))?
                as usize;
            off += 4;
            if off + len > body.len() {
                return Err(Error::invalid("MP4: sgpd variable entry truncated"));
            }
            entries.push(body[off..off + len].to_vec());
            off += len;
        }
    } else if default_length > 0 {
        // Fixed-size entries (version 1 with a non-zero default, or any
        // version that supplied a default_length). Every entry is
        // `default_length` bytes.
        let len = default_length as usize;
        for _ in 0..count {
            if off + len > body.len() {
                return Err(Error::invalid("MP4: sgpd fixed entry truncated"));
            }
            entries.push(body[off..off + len].to_vec());
            off += len;
        }
    } else {
        // No per-entry length available (version 0, or version โ‰ฅ 2 with no
        // default_length field): we cannot determine per-entry boundaries
        // from the container alone. Capture the remaining body as one
        // combined blob so no bytes are lost; a grouping-type-aware caller
        // can re-split it. Empty when entry_count is 0.
        if count > 0 && off < body.len() {
            entries.push(body[off..].to_vec());
        }
    }

    Ok(SgpdBox {
        grouping_type,
        default_sample_description_index,
        entries,
    })
}

/// MSB-first big-endian bit cursor over a byte slice, used for the
/// bit-packed variable-width fields of `csgp` (ยง8.9.5). Reads up to 32
/// bits per call; returns `None` when the request would run past the end
/// of the slice (the caller maps that to a "truncated" parse error).
struct BitCursor<'a> {
    data: &'a [u8],
    /// Absolute bit position from the start of `data`.
    bit_pos: usize,
}

impl<'a> BitCursor<'a> {
    /// Anchor the cursor at byte offset `byte_off` (bit `byte_off * 8`).
    fn new(data: &'a [u8], byte_off: usize) -> Self {
        BitCursor {
            data,
            bit_pos: byte_off * 8,
        }
    }

    /// Read `n` bits (0..=32) MSB-first as a big-endian unsigned value.
    /// `n == 0` yields `0` without consuming any bits. Returns `None`
    /// when fewer than `n` bits remain.
    fn read(&mut self, n: u32) -> Option<u32> {
        debug_assert!(n <= 32);
        if n == 0 {
            return Some(0);
        }
        let total_bits = self.data.len() * 8;
        if self.bit_pos + n as usize > total_bits {
            return None;
        }
        let mut value: u32 = 0;
        for _ in 0..n {
            let byte = self.data[self.bit_pos >> 3];
            let bit = (byte >> (7 - (self.bit_pos & 7))) & 1;
            value = (value << 1) | bit as u32;
            self.bit_pos += 1;
        }
        Some(value)
    }
}

/// Parse `csgp` (CompactSampleToGroupBox, ISO/IEC 14496-12:2020 ยง8.9.5).
///
/// The compact alternative to `sbgp`. `FullBox(version=0, flags)` where
/// the 24-bit `flags` is overloaded to carry four sub-fields (LSB-first
/// bit numbering):
///
/// ```text
///     index_size_code                = flags[0..1]   (2 bits)
///     count_size_code                = flags[2..3]   (2 bits)
///     pattern_size_code              = flags[4..5]   (2 bits)
///     grouping_type_parameter_present = flags[6]     (1 bit)
/// ```
///
/// Each 2-bit size code selects a field width via `width = 4 << code`
/// (code 0โ†’4, 1โ†’8, 2โ†’16, 3โ†’32 bits). The body is then:
///
/// ```text
///     unsigned int(32) grouping_type
///     if (grouping_type_parameter_present)
///         unsigned int(32) grouping_type_parameter
///     unsigned int(32) pattern_count
///     for i in 1..=pattern_count {
///         unsigned int(f(pattern_size_code)) pattern_length[i]
///         unsigned int(f(count_size_code))   sample_count[i]
///     }
///     for j in 1..=pattern_count {
///         for k in 1..=pattern_length[j] {
///             unsigned int(f(index_size_code))
///                 sample_group_description_index[j][k]
///         }
///     }
/// ```
///
/// The `pattern_length`/`sample_count` array and the index array are two
/// separate runs (all lengths first, then all indices) โ€” the index run's
/// total width is `sum(pattern_length[j]) * f(index_size_code)` bits. The
/// 4- and 8-bit field widths mean fields are bit-packed (not byte
/// aligned) across the array; we read MSB-first from a running bit
/// cursor, matching the `unsigned int(N)` big-endian bit-field
/// convention used throughout 14496-12.
///
/// `sample_group_description_index` values are kept verbatim: 0 = "no
/// group of this type"; in a `traf` the field's most-significant bit
/// distinguishes a fragment-local description (set) from a global one
/// (clear). The demuxer does not resolve fragment-local references.
pub fn parse_csgp(body: &[u8]) -> Result<CsgpBox> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: csgp too short"));
    }
    // FullBox: version(8) then 24-bit flags carrying the size codes.
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let index_size_code = (flags & 0x3) as u8;
    let count_size_code = ((flags >> 2) & 0x3) as u8;
    let pattern_size_code = ((flags >> 4) & 0x3) as u8;
    // ยง8.9.5 constraint: `pattern_size_code` and `count_size_code` must
    // agree on whether the 4-bit width (code 0) is used โ€” a 4-bit/non-4-bit
    // mix is an invalid file. Reject it rather than mis-pack the interleaved
    // (pattern_length, sample_count) pairs at disagreeing widths.
    if (pattern_size_code == 0) != (count_size_code == 0) {
        return Err(Error::invalid(
            "MP4: csgp pattern_size_code/count_size_code disagree on 4-bit width",
        ));
    }
    let gtpp = (flags >> 6) & 0x1 == 1;
    // Flag layout bit 7 (ยง8.9.5): when set, the MSB of each index is a
    // fragment-local-vs-global source selector (only legal in a `traf`).
    let index_msb_indicates_fragment_local_description = (flags >> 7) & 0x1 == 1;
    let width = |code: u8| -> u32 { 4u32 << code };
    let index_w = width(index_size_code);
    let count_w = width(count_size_code);
    let pattern_w = width(pattern_size_code);

    let read_u32 = |b: &[u8], o: usize| -> Option<u32> {
        b.get(o..o + 4)
            .map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
    };
    let mut off = 4usize;
    let grouping_type_raw =
        read_u32(body, off).ok_or_else(|| Error::invalid("MP4: csgp grouping_type truncated"))?;
    let grouping_type = grouping_type_raw.to_be_bytes();
    off += 4;
    let grouping_type_parameter = if gtpp {
        let p = read_u32(body, off)
            .ok_or_else(|| Error::invalid("MP4: csgp grouping_type_parameter truncated"))?;
        off += 4;
        Some(p)
    } else {
        None
    };
    let pattern_count = read_u32(body, off)
        .ok_or_else(|| Error::invalid("MP4: csgp pattern_count truncated"))?
        as usize;
    off += 4;

    // From here on, fields are bit-packed (4-/8-/16-/32-bit widths) with
    // no byte alignment between them. Read MSB-first from a bit cursor
    // anchored at the current byte offset.
    let mut bits = BitCursor::new(body, off);
    // Bound the up-front pattern allocation by the remaining bit budget:
    // every pattern needs at least `pattern_w + count_w` bits here. Both
    // widths are `4 << code`, hence โ‰ฅ 4, so the divisor is always โ‰ฅ 8.
    let remaining_bits = body.len().saturating_sub(off).saturating_mul(8);
    let min_pattern_bits = (pattern_w + count_w) as usize;
    let cap = pattern_count.min(remaining_bits / min_pattern_bits);
    let mut lengths: Vec<(u32, u32)> = Vec::with_capacity(cap);
    for _ in 0..pattern_count {
        let pattern_length = bits
            .read(pattern_w)
            .ok_or_else(|| Error::invalid("MP4: csgp pattern_length truncated"))?;
        let sample_count = bits
            .read(count_w)
            .ok_or_else(|| Error::invalid("MP4: csgp sample_count truncated"))?;
        lengths.push((pattern_length, sample_count));
    }

    let mut patterns: Vec<CsgpPattern> = Vec::with_capacity(lengths.len());
    for (pattern_length, sample_count) in lengths {
        let mut indices = Vec::with_capacity(pattern_length.min(remaining_bits as u32) as usize);
        for _ in 0..pattern_length {
            let idx = bits
                .read(index_w)
                .ok_or_else(|| Error::invalid("MP4: csgp index truncated"))?;
            indices.push(idx);
        }
        patterns.push(CsgpPattern {
            sample_count,
            indices,
        });
    }

    Ok(CsgpBox {
        grouping_type,
        grouping_type_parameter,
        index_msb_indicates_fragment_local_description,
        index_field_bits: index_w as u8,
        patterns,
    })
}

/// Parse `ctts` (CompositionOffsetBox, ISO/IEC 14496-12 ยง8.6.1.3).
///
/// Run-length pairs of `(sample_count, sample_offset)` mapping the
/// decoding-order index to the composition-time offset that converts
/// the sample's DTS into its CTS (CTS = DTS + offset). The header is
/// the standard FullBox: `version(8) flags(24) entry_count(32)`.
///
/// * Version 0 (the common case) stores `sample_offset` as `u32`,
///   permitting only non-negative offsets.
/// * Version 1 stores it as `i32`, allowing negative offsets โ€” used
///   when the encoder shifts the entire CTS timeline below DTS so
///   the first frame's CTS can sit at zero (Apple-style negative
///   composition shift).
///
/// We always return `i32` so callers can apply the offset uniformly.
fn parse_ctts(body: &[u8]) -> Result<Vec<(u32, i32)>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: ctts too short"));
    }
    let version = body[0];
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let mut out = Vec::with_capacity(count.min(body.len() / 8));
    let mut off = 8;
    for _ in 0..count {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: ctts truncated"));
        }
        let cnt = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        let raw = [body[off + 4], body[off + 5], body[off + 6], body[off + 7]];
        let dlt: i32 = if version == 0 {
            // Spec says u32 here, but real-world v0 files routinely
            // emit large unsigned values that exceed i32::MAX only
            // when the timescale is itself huge โ€” `as i32` preserves
            // bit-pattern, and a sane v0 producer keeps the offset
            // representable.
            u32::from_be_bytes(raw) as i32
        } else {
            i32::from_be_bytes(raw)
        };
        out.push((cnt, dlt));
        off += 8;
    }
    Ok(out)
}

/// Parse `subs` (SubSampleInformationBox, ISO/IEC 14496-12 ยง8.7.7).
///
/// `FullBox(version, flags)`:
///
/// ```text
///     unsigned int(32) entry_count
///     entry_count ร— {
///         unsigned int(32) sample_delta
///         unsigned int(16) subsample_count
///         subsample_count ร— {
///             if (version == 1) unsigned int(32) subsample_size
///             else              unsigned int(16) subsample_size
///             unsigned int(8)  subsample_priority
///             unsigned int(8)  discardable
///             unsigned int(32) codec_specific_parameters
///         }
///     }
/// ```
///
/// Per ยง8.7.7.1 the table is *sparse*: each entry's `sample_delta` is
/// the difference between this entry's target sample and the previous
/// entry's (or sample 0 for the first entry), so a `subs` documents only
/// the samples that genuinely have sub-sample structure. A
/// `subsample_count` of 0 is legal: the entry still consumes one row
/// (advances the delta cursor) but produces no per-sub-sample fields.
///
/// The codec-specific semantics of `subsample_priority`, `discardable`,
/// `codec_specific_parameters`, and `flags` are deliberately preserved
/// verbatim โ€” the container does not interpret them. For H.264
/// (ISO/IEC 14496-15) `codec_specific_parameters` encodes per-NAL-unit
/// dependency information; we surface the raw u32 so a codec-aware
/// layer can decode it.
///
/// `with_capacity` is bounded by the byte budget so an adversarial
/// `entry_count` cannot force a giant up-front allocation; per-entry
/// bounds checks reject a truncated body.
fn parse_subs(body: &[u8]) -> Result<SubsBox> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: subs too short"));
    }
    let version = body[0];
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let entry_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    // Minimum bytes per row, used as a guard on `with_capacity`:
    //   sample_delta (4) + subsample_count (2) = 6 even for an
    //   empty-subsample entry.
    let max_entries = body.len().saturating_sub(8) / 6;
    let mut entries: Vec<SubsEntry> = Vec::with_capacity(entry_count.min(max_entries));
    let size_width = if version == 1 { 4 } else { 2 };
    let per_sub_min = size_width + 1 + 1 + 4; // size + priority + discardable + csp
    let mut off = 8;
    for _ in 0..entry_count {
        if off + 6 > body.len() {
            return Err(Error::invalid("MP4: subs entry header truncated"));
        }
        let sample_delta =
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
        let subsample_count = u16::from_be_bytes([body[off], body[off + 1]]) as usize;
        off += 2;
        // Cap per-entry capacity by remaining byte budget so an inflated
        // `subsample_count` can't allocate ahead of the available bytes.
        let max_subs = (body.len().saturating_sub(off)) / per_sub_min;
        let mut subs_vec: Vec<SubSampleEntry> = Vec::with_capacity(subsample_count.min(max_subs));
        for _ in 0..subsample_count {
            if off + per_sub_min > body.len() {
                return Err(Error::invalid("MP4: subs subsample truncated"));
            }
            let subsample_size = if version == 1 {
                let v =
                    u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
                off += 4;
                v
            } else {
                let v = u16::from_be_bytes([body[off], body[off + 1]]) as u32;
                off += 2;
                v
            };
            let subsample_priority = body[off];
            off += 1;
            let discardable = body[off];
            off += 1;
            let codec_specific_parameters =
                u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
            off += 4;
            subs_vec.push(SubSampleEntry {
                subsample_size,
                subsample_priority,
                discardable,
                codec_specific_parameters,
            });
        }
        entries.push(SubsEntry {
            sample_delta,
            subsamples: subs_vec,
        });
    }
    Ok(SubsBox {
        version,
        flags,
        entries,
    })
}

/// Parse a standalone `subs` (SubSampleInformationBox, ISO/IEC 14496-12
/// ยง8.7.7) body (the bytes after the box header) into a [`SubsBox`].
///
/// Exposed as a public entry point so a codec-aware layer (e.g. an AVC
/// NAL-unit splitter reading `codec_specific_parameters`) can decode a
/// `subs` table it already has in hand without re-running `open()`.
/// Returns `Err` for a body shorter than the FullBox preamble +
/// `entry_count`, or a body truncated mid-entry / mid-subsample.
pub fn parse_subs_box(body: &[u8]) -> Result<SubsBox> {
    parse_subs(body)
}

/// Serialise a `subs` (SubSampleInformationBox, ISO/IEC 14496-12 ยง8.7.7)
/// from a [`SubsBox`] โ€” the byte-exact inverse of [`parse_subs_box`].
///
/// Layout (ยง8.7.7.2): a FullBox preamble carrying the record's `version`
/// (0 or 1) and its codec-owned 24-bit `flags` verbatim, the 32-bit
/// `entry_count`, then per entry the 32-bit `sample_delta`, the 16-bit
/// `subsample_count`, and per sub-sample the `subsample_size` (16-bit at
/// version 0, 32-bit at version 1), `subsample_priority` (8-bit),
/// `discardable` (8-bit) and `codec_specific_parameters` (32-bit).
///
/// Returns `None` when the record cannot be expressed on the wire and
/// re-parse identically: a `version` other than 0/1; an `entry_count` or
/// any `subsample_count` exceeding its 32-/16-bit field; or โ€” at version
/// 0 โ€” a `subsample_size` exceeding `u16::MAX` (the v0 size field is
/// 16-bit; the caller must use version 1).
pub fn build_subs_box(record: &SubsBox) -> Option<Vec<u8>> {
    if record.version > 1 {
        return None;
    }
    let entry_count: u32 = record.entries.len().try_into().ok()?;
    let mut body = Vec::with_capacity(8 + record.entries.len() * 6);
    body.push(record.version);
    body.extend_from_slice(&record.flags.to_be_bytes()[1..4]); // 24-bit flags
    body.extend_from_slice(&entry_count.to_be_bytes());
    for entry in &record.entries {
        let subsample_count: u16 = entry.subsamples.len().try_into().ok()?;
        body.extend_from_slice(&entry.sample_delta.to_be_bytes());
        body.extend_from_slice(&subsample_count.to_be_bytes());
        for sub in &entry.subsamples {
            if record.version == 0 {
                let size: u16 = sub.subsample_size.try_into().ok()?;
                body.extend_from_slice(&size.to_be_bytes());
            } else {
                body.extend_from_slice(&sub.subsample_size.to_be_bytes());
            }
            body.push(sub.subsample_priority);
            body.push(sub.discardable);
            body.extend_from_slice(&sub.codec_specific_parameters.to_be_bytes());
        }
    }
    Some(wrap_box(&SUBS, &body))
}

/// Parse `saiz` (SampleAuxiliaryInformationSizesBox, ISO/IEC 14496-12
/// ยง8.7.8).
///
/// On-wire layout (ยง8.7.8.2):
///
/// ```text
/// FullBox header  : 4 bytes  (version + flags)
/// if (flags & 1) {
///     aux_info_type           : u32   (FourCC)
///     aux_info_type_parameter : u32
/// }
/// default_sample_info_size : u8
/// sample_count             : u32
/// if (default_sample_info_size == 0) {
///     sample_info_size[sample_count] : u8 each
/// }
/// ```
///
/// The `aux_info_type` block is gated by the FullBox `flags`'s low bit;
/// when absent the implied value is the protection scheme type (for
/// transformed sample entries) or the sample-entry FourCC (ยง8.7.8.3).
/// We surface `Option`s rather than materialise the fallback so the
/// caller's higher-level context (sinf/sample-entry FourCC) decides.
fn parse_saiz(body: &[u8]) -> Result<SaizBox> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: saiz too short"));
    }
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let mut off = 4usize;
    let mut aux_info_type: Option<[u8; 4]> = None;
    let mut aux_info_type_parameter: Option<u32> = None;
    if flags & 1 != 0 {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: saiz aux_info_type truncated"));
        }
        aux_info_type = Some([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
        aux_info_type_parameter = Some(u32::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
        ]));
        off += 4;
    }
    if off + 5 > body.len() {
        return Err(Error::invalid("MP4: saiz header truncated"));
    }
    let default_sample_info_size = body[off];
    off += 1;
    let sample_count = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
    off += 4;
    let mut per_sample: Vec<u8> = Vec::new();
    if default_sample_info_size == 0 {
        let want = sample_count as usize;
        // Cap allocation by the remaining byte budget so a forged
        // `sample_count` cannot pre-allocate ahead of the truncated body.
        let avail = body.len().saturating_sub(off);
        per_sample = Vec::with_capacity(want.min(avail));
        if off + want > body.len() {
            return Err(Error::invalid("MP4: saiz sample_info_size truncated"));
        }
        per_sample.extend_from_slice(&body[off..off + want]);
    }
    Ok(SaizBox {
        aux_info_type,
        aux_info_type_parameter,
        default_sample_info_size,
        sample_count,
        per_sample,
    })
}

/// Parse `saio` (SampleAuxiliaryInformationOffsetsBox, ISO/IEC 14496-12
/// ยง8.7.9).
///
/// On-wire layout (ยง8.7.9.2):
///
/// ```text
/// FullBox header  : 4 bytes  (version + flags)
/// if (flags & 1) {
///     aux_info_type           : u32   (FourCC)
///     aux_info_type_parameter : u32
/// }
/// entry_count : u32
/// if (version == 0) { offset[entry_count] : u32 each }
/// else             { offset[entry_count] : u64 each }
/// ```
///
/// All offsets are widened to `u64` so callers handle one shape.
/// `version` is preserved so a producer can re-emit the original width.
fn parse_saio(body: &[u8]) -> Result<SaioBox> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: saio too short"));
    }
    let version = body[0];
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let mut off = 4usize;
    let mut aux_info_type: Option<[u8; 4]> = None;
    let mut aux_info_type_parameter: Option<u32> = None;
    if flags & 1 != 0 {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: saio aux_info_type truncated"));
        }
        aux_info_type = Some([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
        aux_info_type_parameter = Some(u32::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
        ]));
        off += 4;
    }
    if off + 4 > body.len() {
        return Err(Error::invalid("MP4: saio entry_count truncated"));
    }
    let entry_count =
        u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as usize;
    off += 4;
    let off_width = if version == 1 { 8 } else { 4 };
    // Cap capacity by remaining byte budget so a forged `entry_count`
    // cannot pre-allocate ahead of the truncated body.
    let avail = body.len().saturating_sub(off);
    let max_entries = avail / off_width;
    let mut offsets: Vec<u64> = Vec::with_capacity(entry_count.min(max_entries));
    for _ in 0..entry_count {
        if off + off_width > body.len() {
            return Err(Error::invalid("MP4: saio offset truncated"));
        }
        let v = if version == 1 {
            u64::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
                body[off + 4],
                body[off + 5],
                body[off + 6],
                body[off + 7],
            ])
        } else {
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64
        };
        offsets.push(v);
        off += off_width;
    }
    Ok(SaioBox {
        version,
        aux_info_type,
        aux_info_type_parameter,
        offsets,
    })
}

/// Parse a standalone `saiz` (SampleAuxiliaryInformationSizesBox, ISO/IEC
/// 14496-12 ยง8.7.8) body (the bytes after the box header) into a
/// [`SaizBox`]. Public entry point for CENC / DRM tooling that already
/// holds the box payload.
pub fn parse_saiz_box(body: &[u8]) -> Result<SaizBox> {
    parse_saiz(body)
}

/// Parse a standalone `saio` (SampleAuxiliaryInformationOffsetsBox,
/// ISO/IEC 14496-12 ยง8.7.9) body into a [`SaioBox`]. Public entry point
/// paired with [`build_saio_box`].
pub fn parse_saio_box(body: &[u8]) -> Result<SaioBox> {
    parse_saio(body)
}

/// Serialise a `saiz` (SampleAuxiliaryInformationSizesBox, ISO/IEC
/// 14496-12 ยง8.7.8) from a [`SaizBox`] โ€” the byte-exact inverse of
/// [`parse_saiz_box`].
///
/// The `aux_info_type` / `aux_info_type_parameter` key is written only
/// when `aux_info_type` is `Some` (which sets `flags & 1`); the parameter
/// defaults to 0 when omitted (ยง8.7.8.3). The body then carries the 8-bit
/// `default_sample_info_size`, the 32-bit `sample_count`, and โ€” only when
/// `default_sample_info_size == 0` โ€” the `per_sample` size table.
///
/// Returns `None` when the record cannot round-trip: a non-zero
/// `default_sample_info_size` paired with a non-empty `per_sample` (the
/// constant-size shortcut and the per-sample table are mutually
/// exclusive), or โ€” for a variable-size table โ€” a `sample_count` that
/// does not match `per_sample.len()`.
pub fn build_saiz_box(record: &SaizBox) -> Option<Vec<u8>> {
    if record.default_sample_info_size != 0 && !record.per_sample.is_empty() {
        return None;
    }
    if record.default_sample_info_size == 0
        && record.sample_count as usize != record.per_sample.len()
    {
        return None;
    }
    let mut body = Vec::new();
    let flags: u32 = if record.aux_info_type.is_some() { 1 } else { 0 };
    body.push(0); // version 0 (ยง8.7.8.2 defines only version 0)
    body.extend_from_slice(&flags.to_be_bytes()[1..4]);
    if let Some(t) = record.aux_info_type {
        body.extend_from_slice(&t);
        body.extend_from_slice(&record.aux_info_type_parameter.unwrap_or(0).to_be_bytes());
    }
    body.push(record.default_sample_info_size);
    body.extend_from_slice(&record.sample_count.to_be_bytes());
    if record.default_sample_info_size == 0 {
        body.extend_from_slice(&record.per_sample);
    }
    Some(wrap_box(&SAIZ, &body))
}

/// Serialise a `saio` (SampleAuxiliaryInformationOffsetsBox, ISO/IEC
/// 14496-12 ยง8.7.9) from a [`SaioBox`] โ€” the byte-exact inverse of
/// [`parse_saio_box`].
///
/// The `aux_info_type` key is written only when present (setting
/// `flags & 1`), the parameter defaulting to 0 when omitted. The body
/// then carries the 32-bit `entry_count` followed by the offset array,
/// each written as a 32-bit field for version 0 or a 64-bit field for
/// version 1 (ยง8.7.9.2).
///
/// Returns `None` for a `version` other than 0/1, an `offsets` count
/// exceeding the 32-bit `entry_count`, or โ€” at version 0 โ€” an offset
/// exceeding `u32::MAX` (the caller must use version 1).
pub fn build_saio_box(record: &SaioBox) -> Option<Vec<u8>> {
    if record.version > 1 {
        return None;
    }
    let entry_count: u32 = record.offsets.len().try_into().ok()?;
    let mut body = Vec::new();
    let flags: u32 = if record.aux_info_type.is_some() { 1 } else { 0 };
    body.push(record.version);
    body.extend_from_slice(&flags.to_be_bytes()[1..4]);
    if let Some(t) = record.aux_info_type {
        body.extend_from_slice(&t);
        body.extend_from_slice(&record.aux_info_type_parameter.unwrap_or(0).to_be_bytes());
    }
    body.extend_from_slice(&entry_count.to_be_bytes());
    for &offset in &record.offsets {
        if record.version == 0 {
            let o: u32 = offset.try_into().ok()?;
            body.extend_from_slice(&o.to_be_bytes());
        } else {
            body.extend_from_slice(&offset.to_be_bytes());
        }
    }
    Some(wrap_box(&SAIO, &body))
}

/// Parse `cslg` (CompositionToDecodeBox, ISO/IEC 14496-12 ยง8.6.1.4).
///
/// `FullBox(version, 0)` whose body is five signed integers. Version 0
/// stores them as 32-bit, version 1 as 64-bit (used only when at least
/// one value exceeds the 32-bit range, per ยง8.6.1.4.1). The fields are,
/// in order: `compositionToDTSShift`, `leastDecodeToDisplayDelta`,
/// `greatestDecodeToDisplayDelta`, `compositionStartTime`,
/// `compositionEndTime`. All five are widened to `i64` so callers see
/// one shape regardless of the on-wire version.
fn parse_cslg(body: &[u8]) -> Result<CslgBox> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: cslg too short"));
    }
    let version = body[0];
    let mut off = 4;
    let mut take = |width: usize, b: &[u8]| -> Result<i64> {
        if off + width > b.len() {
            return Err(Error::invalid("MP4: cslg truncated"));
        }
        let v = if width == 4 {
            i32::from_be_bytes([b[off], b[off + 1], b[off + 2], b[off + 3]]) as i64
        } else {
            i64::from_be_bytes([
                b[off],
                b[off + 1],
                b[off + 2],
                b[off + 3],
                b[off + 4],
                b[off + 5],
                b[off + 6],
                b[off + 7],
            ])
        };
        off += width;
        Ok(v)
    };
    let w = if version == 0 { 4 } else { 8 };
    Ok(CslgBox {
        composition_to_dts_shift: take(w, body)?,
        least_decode_to_display_delta: take(w, body)?,
        greatest_decode_to_display_delta: take(w, body)?,
        composition_start_time: take(w, body)?,
        composition_end_time: take(w, body)?,
    })
}

fn parse_stco(body: &[u8]) -> Result<Vec<u64>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: stco too short"));
    }
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let mut out = Vec::with_capacity(count.min(body.len() / 4));
    let mut off = 8;
    for _ in 0..count {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: stco truncated"));
        }
        out.push(
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64,
        );
        off += 4;
    }
    Ok(out)
}

fn parse_co64(body: &[u8]) -> Result<Vec<u64>> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: co64 too short"));
    }
    let count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let mut out = Vec::with_capacity(count.min(body.len() / 8));
    let mut off = 8;
    for _ in 0..count {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: co64 truncated"));
        }
        out.push(u64::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
            body[off + 4],
            body[off + 5],
            body[off + 6],
            body[off + 7],
        ]));
        off += 8;
    }
    Ok(out)
}

// --- Movie-fragment parsing (ISO/IEC 14496-12 ยง8.8) ----------------------

/// One per-fragment CENC SampleEncryptionBox record. Collected during
/// the moof walk so a downstream layer can replay per-sample IVs and
/// subsample maps without re-parsing the file. `track_idx` is the
/// 0-based index into the demuxer's `streams()`; `senc` carries the
/// payload exactly as parsed.
#[derive(Clone, Debug)]
pub struct SencRecord {
    /// `track_idx` of the matching stream in the demuxer's
    /// `streams()` list (0-based).
    pub track_idx: u32,
    /// `mfhd.sequence_number` of the containing `moof`. Surfaced so a
    /// caller that interleaves multiple sources or replays out of
    /// order can re-key.
    pub moof_sequence: u32,
    /// Parsed CENC SampleEncryptionBox.
    pub senc: SencBox,
}

/// One per-fragment PIFF legacy `uuid` SampleEncryptionBox record โ€”
/// the pre-CENC predecessor of `senc`, carried in `traf` as a `uuid`
/// box with [`crate::cenc::PIFF_SENC_USERTYPE`]. Keyed like
/// [`SencRecord`] by `(track_idx, moof_sequence)`.
///
/// When a `traf` carries **only** the PIFF form, the demuxer also
/// bridges it into the standard [`Mp4Demuxer::senc_records`] surface
/// (via [`PiffSencBox::to_senc`] โ€” the per-sample table is
/// byte-compatible) so an existing CENC decryption layer consumes
/// legacy PIFF fragments unchanged; the typed record here additionally
/// preserves the PIFF-only `flags & 1` override triple
/// ([`PiffSencBox::override_params`]) that replaces the track defaults
/// for this fragment. A `traf` carrying both forms (a dual-branded
/// packager) surfaces the 4CC box in `senc_records` and the `uuid` box
/// here only โ€” no duplicate.
#[derive(Clone, Debug)]
pub struct PiffSencRecord {
    /// `track_idx` of the matching stream in the demuxer's
    /// `streams()` list (0-based).
    pub track_idx: u32,
    /// `mfhd.sequence_number` of the containing `moof`.
    pub moof_sequence: u32,
    /// Parsed PIFF SampleEncryptionBox (per-sample IVs, optional
    /// subsample map, optional override triple).
    pub senc: PiffSencBox,
}

/// Parse one contiguous CENC auxiliary-information run (ISO/IEC
/// 23001-7 ยง7.1 cells, one per sample) fetched via a `saiz`+`saio`
/// pair. `sizes[i]` is sample `i`'s declared aux-info size; each cell
/// is an `InitializationVector` of `iv_size` bytes, followed โ€” iff the
/// cell is larger than the IV โ€” by a `u16` subsample count and that
/// many `(u16 BytesOfClearData, u32 BytesOfProtectedData)` runs, and
/// must consume its declared size exactly. A zero-size cell yields an
/// empty entry (constant-IV sample with no subsample map). Returns
/// `None` when any cell fails to parse โ€” the caller then leaves the
/// record unsynthesised rather than surfacing half a table.
fn parse_aux_info_run(buf: &[u8], sizes: &[usize], iv_size: usize) -> Option<crate::cenc::SencBox> {
    let mut cursor = 0usize;
    let mut samples = Vec::with_capacity(sizes.len());
    let mut any_subsamples = false;
    for &size in sizes {
        let cell = buf.get(cursor..cursor.checked_add(size)?)?;
        cursor += size;
        if size == 0 {
            samples.push(crate::cenc::SencSample {
                initialization_vector: Vec::new(),
                subsamples: Vec::new(),
            });
            continue;
        }
        if size < iv_size {
            return None;
        }
        let iv = cell[..iv_size].to_vec();
        let mut subsamples = Vec::new();
        if size > iv_size {
            let rest = &cell[iv_size..];
            if rest.len() < 2 {
                return None;
            }
            let n = u16::from_be_bytes([rest[0], rest[1]]) as usize;
            // The cell must be exactly IV + count + n entries โ€” a
            // mismatch means these bytes are not ยง7.1 aux info.
            if rest.len() != 2 + n * 6 {
                return None;
            }
            subsamples.reserve_exact(n);
            for k in 0..n {
                let e = &rest[2 + k * 6..2 + k * 6 + 6];
                subsamples.push(crate::cenc::SubsampleEntry {
                    bytes_of_clear_data: u16::from_be_bytes([e[0], e[1]]),
                    bytes_of_protected_data: u32::from_be_bytes([e[2], e[3], e[4], e[5]]),
                });
            }
            any_subsamples = true;
        }
        samples.push(crate::cenc::SencSample {
            initialization_vector: iv,
            subsamples,
        });
    }
    Some(crate::cenc::SencBox {
        flags: if any_subsamples { 0x0000_0002 } else { 0 },
        samples,
    })
}

/// One ยง8.8.7 `duration-is-empty` track fragment (tfhd flag 0x010000)
/// encountered during the moof walk. The traf contributed no samples;
/// instead it inserted `duration` ticks of empty time (in the track's
/// media timescale) into the track's decode timeline โ€” ยง8.8.6.1's
/// "empty inserts can be used in audio tracks doing silence
/// suppression, for example". The demuxer advances the track's running
/// decode time by `duration` (so a subsequent `tfdt`-less fragment
/// lands after the gap) and records the gap here; surfaced flat as
/// `frag_empty_duration_<n>` metadata and typed via
/// [`Mp4Demuxer::empty_duration_records`].
#[derive(Clone, Copy, Debug)]
pub struct EmptyDurationRecord {
    /// `track_idx` of the matching stream in the demuxer's
    /// `streams()` list (0-based).
    pub track_idx: u32,
    /// `mfhd.sequence_number` of the containing `moof`.
    pub moof_sequence: u32,
    /// Length of the empty interval, in the track's media timescale โ€”
    /// the effective default sample duration (ยง8.8.7.1: "the duration
    /// provided in either default-sample-duration, or by the
    /// default-duration in the Track Extends Box").
    pub duration: u32,
}

/// One per-fragment ISO/IEC 14496-12 ยง8.7.8 / ยง8.7.9 record. Each
/// `traf` may carry zero or more `(saiz, saio)` pairs (keyed by
/// `(aux_info_type, aux_info_type_parameter)`); the demuxer collects
/// them as `SaiRecord` so a downstream layer can replay per-sample
/// auxiliary-info pointers (most commonly CENC IV / subsample-map
/// material when `senc` is absent and the IV stream is carried via
/// auxiliary-info pointers per ยง8.8.14 + ISO/IEC 23001-7 ยง7.3) without
/// re-parsing the file. `aux_info_type` semantics determine pairing;
/// the demuxer does not interpret the bytes the offsets point at.
#[derive(Clone, Debug)]
pub struct SaiRecord {
    /// `track_idx` of the matching stream in the demuxer's
    /// `streams()` list (0-based).
    pub track_idx: u32,
    /// `mfhd.sequence_number` of the containing `moof`. Surfaced so a
    /// caller that interleaves multiple sources or replays out of
    /// order can re-key.
    pub moof_sequence: u32,
    /// Parsed `(saiz, saio)` pairs from this `traf`, in disk order.
    /// The spec permits multiple pairs per `traf` keyed by
    /// `(aux_info_type, aux_info_type_parameter)`; a caller pairs
    /// each `saiz` with the `saio` of the matching key. We do not
    /// pre-pair here so an unmatched box (a producer slip) is
    /// preserved verbatim for inspection.
    pub saiz: Vec<TrafSaiz>,
    pub saio: Vec<TrafSaio>,
    /// The traf's effective base data offset โ€” `tfhd.base_data_offset`
    /// when explicit, else the position of the enclosing `moof`
    /// (`default-base-is-moof` and the ยง8.8.7.1 first-traf fall-back
    /// collapse to the same anchor here). ยง8.8.14: "In a track
    /// fragment box, this value is relative to the base offset
    /// established by the track fragment header box" โ€” so
    /// `base_data_offset + saio.offsets[n]` is the absolute file
    /// position of the auxiliary information. Stored so a consumer
    /// (or [`Mp4Demuxer::resolve_sai_aux_info`]) can resolve the
    /// relative offsets without re-walking the moof.
    pub base_data_offset: u64,
}

/// One `saiz` (SampleAuxiliaryInformationSizesBox) found in a `traf`.
/// The on-wire layout matches the stbl-level box; the only semantic
/// difference is that the matching `saio.offset[]` is base_data_offset
/// relative (per ยง8.8.14) rather than absolute.
#[derive(Clone, Debug, Default)]
pub struct TrafSaiz {
    /// ยง8.7.8.3 โ€” `aux_info_type` (present only when `flags & 1`).
    pub aux_info_type: Option<[u8; 4]>,
    /// ยง8.7.8.3 โ€” `aux_info_type_parameter` (present only when
    /// `flags & 1`).
    pub aux_info_type_parameter: Option<u32>,
    /// ยง8.7.8.3 โ€” `default_sample_info_size`.
    pub default_sample_info_size: u8,
    /// ยง8.7.8.3 โ€” `sample_count`.
    pub sample_count: u32,
    /// ยง8.7.8.2 โ€” `sample_info_size[]` (populated only when
    /// `default_sample_info_size == 0`).
    pub per_sample: Vec<u8>,
}

/// One `saio` (SampleAuxiliaryInformationOffsetsBox) found in a `traf`.
/// `version` selects 32-bit / 64-bit on-disk offset width. Offsets are
/// widened to `u64` and are *relative* to the `tfhd.base_data_offset`
/// established for this traf (or the `moof` start when
/// `default-base-is-moof` is set, per ยง8.8.14).
#[derive(Clone, Debug, Default)]
pub struct TrafSaio {
    /// FullBox version.
    pub version: u8,
    /// ยง8.7.9.3 โ€” `aux_info_type`.
    pub aux_info_type: Option<[u8; 4]>,
    /// ยง8.7.9.3 โ€” `aux_info_type_parameter`.
    pub aux_info_type_parameter: Option<u32>,
    /// ยง8.7.9.2 โ€” `offset[]` widened to u64; base_data_offset relative
    /// inside a traf per ยง8.8.14.
    pub offsets: Vec<u64>,
}

/// One per-fragment ISO/IEC 23001-7 ยง8.1 `pssh`
/// ProtectionSystemSpecificHeaderBox record collected from inside a
/// `moof`. The spec (ยง8.1.1) instructs readers to examine pssh boxes
/// "in the Movie Box and in the Movie Fragment Box associated with
/// the sample (but not those in other Movie Fragment Boxes)", so a
/// decrypting layer keys each record by `moof_sequence` to scope
/// SystemID matches to the right fragment.
///
/// `pssh` carries the parsed PsshBox; `moof_sequence` is the
/// `mfhd.sequence_number` of the enclosing `moof`.
#[derive(Clone, Debug)]
pub struct MoofPsshRecord {
    /// `mfhd.sequence_number` of the enclosing `moof`. Surfaced so a
    /// decrypting layer can scope SystemID matches to the right
    /// fragment without re-walking the file.
    pub moof_sequence: u32,
    /// Parsed ProtectionSystemSpecificHeaderBox.
    pub pssh: PsshBox,
}

/// One per-fragment ISO/IEC 14496-12 ยง8.9 sample-group record collected
/// from inside a `traf` (Track Fragment Box).
///
/// ยง8.9.2 / ยง8.9.3 / ยง8.9.5 permit `sbgp` / `csgp` and `sgpd` to live in
/// a `traf` as well as in `stbl`: a movie fragment can carry its own
/// **fragment-local** group descriptions (its own `sgpd`) and a
/// per-sample mapping (`sbgp` or `csgp`) into either the fragment-local
/// `sgpd` or the `trak`-level (global) one. The `csgp` bit-7
/// `index_msb_indicates_fragment_local_description` flag exists precisely
/// for this `traf` case (ยง8.9.5: "legal only inside a `traf`"). The
/// demuxer collects each `traf`'s sample-group boxes verbatim, keyed by
/// `(track_idx, moof_sequence)`, so a downstream layer can resolve
/// per-fragment grouping (most commonly CENC `seig` key rotation across
/// a fragment's samples) without re-walking the file. The bytes are not
/// interpreted here โ€” the parsed `SampleToGroup` / `CompactSampleToGroup`
/// / `SampleGroupDescription` records preserve their on-wire values and
/// the grouping-type semantics belong to the caller (mirroring the
/// `stbl`-level surface).
#[derive(Clone, Debug)]
pub struct TrafSampleGroupRecord {
    /// `track_idx` of the matching stream in the demuxer's `streams()`
    /// list (0-based).
    pub track_idx: u32,
    /// `mfhd.sequence_number` of the enclosing `moof`. Surfaced so a
    /// caller replaying out of order can re-key.
    pub moof_sequence: u32,
    /// Fragment-local `sgpd` (SampleGroupDescriptionBox ยง8.9.3)
    /// descriptions, in `traf` order. These shadow the `trak`-level
    /// `sgpd` of the same `grouping_type` for samples in this fragment
    /// whose mapping selects the fragment-local source.
    pub sgpd: Vec<SgpdBox>,
    /// `sbgp` (SampleToGroupBox ยง8.9.2) per-sample run-length maps, in
    /// `traf` order.
    pub sbgp: Vec<SbgpBox>,
    /// `csgp` (CompactSampleToGroupBox ยง8.9.5) compact maps, in `traf`
    /// order. The MSB-fragment-local convention (bit 7) is meaningful
    /// here โ€” see [`CsgpBox::index_msb_indicates_fragment_local_description`].
    pub csgp: Vec<CsgpBox>,
}

/// Walk one `moof` box, locating its `traf` children and stitching the
/// fragmented samples into the per-track sample list.
///
/// `next_dts` carries each track's running base_media_decode_time so a
/// `traf` without `tfdt` continues seamlessly from the previous
/// fragment (or from the moov-derived sample tail).
///
/// `senc_records` accumulates per-fragment ISO/IEC 23001-7 ยง7.2 senc
/// payloads keyed by `(track_idx, moof_sequence)` so a decrypting
/// layer can recover them without re-parsing the file.
///
/// `sai_records` accumulates per-fragment ISO/IEC 14496-12 ยง8.7.8โ€“9
/// `(saiz, saio)` pairs, keyed the same way. The auxiliary-information
/// bytes themselves remain in the mdat at the offsets the `saio`
/// names; the demuxer doesn't fetch them (their semantics belong to
/// the carried `aux_info_type`, e.g. CENC `cenc`/`cbcs`).
///
/// `moof_psshes` accumulates ISO/IEC 23001-7 ยง8.1 `pssh` boxes that
/// live directly inside this `moof` (ยง8.1.1 permits pssh in either
/// `moov` or `moof`). Each captured PsshBox is keyed by the enclosing
/// `mfhd.sequence_number` so a downstream DRM layer can scope SystemID
/// matches per ยง8.1.1 ("readers SHALL examine all Protection System
/// Specific Header boxes in the Movie Box and in the Movie Fragment
/// Box associated with the sample (but not those in other Movie
/// Fragment Boxes)"). A malformed pssh inside a moof is dropped
/// without failing the fragment, mirroring the moov-level recovery
/// policy.
#[allow(clippy::too_many_arguments)] // per-fragment record sinks are independent vectors threaded through one moof walk; bundling them obscures which box populates which sink
fn parse_moof(
    moof: &MoofRecord,
    tracks: &[Track],
    samples: &mut Vec<SampleRef>,
    next_dts: &mut [i64],
    senc_records: &mut Vec<SencRecord>,
    sai_records: &mut Vec<SaiRecord>,
    moof_psshes: &mut Vec<MoofPsshRecord>,
    traf_sample_groups: &mut Vec<TrafSampleGroupRecord>,
    piff_senc_records: &mut Vec<PiffSencRecord>,
    piff_moof_psshes: &mut Vec<MoofPsshRecord>,
    empty_durations: &mut Vec<EmptyDurationRecord>,
    sample_budget: &mut u64,
) -> Result<()> {
    let mut cur = std::io::Cursor::new(&moof.body);
    let end = moof.body.len() as u64;
    let mut moof_sequence: u32 = 0;
    // ยง8.1.1 allows pssh boxes at moof level; collect their bodies as
    // we walk so a pssh that precedes `mfhd` (rare but spec-legal โ€”
    // ยง8.8 doesn't fix the relative order between `mfhd` and `pssh`)
    // still binds to the correct sequence_number once we've seen
    // mfhd. Finalised below. The PIFF `uuid` form of the same box gets
    // the identical deferred treatment.
    let mut pending_pssh_bodies: Vec<Vec<u8>> = Vec::new();
    let mut pending_piff_pssh_bodies: Vec<Vec<u8>> = Vec::new();
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            // ยง8.8.5 โ€” `mfhd` MovieFragmentHeaderBox. Carries the
            // monotonically-increasing sequence_number. Capture it
            // so per-traf SencRecords get an ordering key.
            MFHD => {
                let body = read_bytes_vec(&mut cur, psz)?;
                // FullBox header (4 bytes) + sequence_number (u32).
                if body.len() >= 8 {
                    moof_sequence = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
                }
            }
            TRAF => {
                let body = read_bytes_vec(&mut cur, psz)?;
                parse_traf(
                    &body,
                    moof.moof_start,
                    tracks,
                    samples,
                    next_dts,
                    moof_sequence,
                    senc_records,
                    sai_records,
                    traf_sample_groups,
                    piff_senc_records,
                    empty_durations,
                    sample_budget,
                )?;
            }
            PSSH => {
                // ISO/IEC 23001-7 ยง8.1 โ€” ProtectionSystemSpecificHeaderBox
                // at moof level. Buffer the body until the whole moof has
                // been walked (we need the captured `moof_sequence` from
                // `mfhd` to key the record). A malformed pssh body is
                // dropped without failing the fragment โ€” mirrors the
                // moov-level recovery policy and matches the spec's
                // opaque-SystemID treatment.
                let body = read_bytes_vec(&mut cur, psz)?;
                pending_pssh_bodies.push(body);
            }
            // PIFF legacy `uuid` boxes at moof level: the pre-CENC
            // ProtectionSystemSpecificHeaderBox (PIFF places it in
            // `moov` and/or `moof`). Deferred like the 4CC `pssh` so
            // a box preceding `mfhd` still binds to the right
            // sequence number. Unknown usertypes are skipped.
            UUID => {
                let body = read_bytes_vec(&mut cur, psz)?;
                if body.len() >= 16 && body[..16] == PIFF_PSSH_USERTYPE {
                    pending_piff_pssh_bodies.push(body);
                }
            }
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }
    for body in pending_pssh_bodies {
        if let Ok(pssh) = parse_pssh(&body) {
            moof_psshes.push(MoofPsshRecord {
                moof_sequence,
                pssh,
            });
        }
    }
    for body in pending_piff_pssh_bodies {
        if let Ok(pssh) = parse_piff_pssh(&body[16..]) {
            piff_moof_psshes.push(MoofPsshRecord {
                moof_sequence,
                pssh,
            });
        }
    }
    Ok(())
}

/// One track-fragment scratch record built from `tfhd` + `tfdt` before
/// any `trun` is walked.
#[derive(Default)]
struct TrafState {
    track_idx: usize,
    /// `tfhd.flags` โ€” selects which optional fields are present.
    tfhd_flags: u32,
    /// Effective base offset for `trun` entries that have no explicit
    /// per-sample offset. Built from `tfhd.base_data_offset` when
    /// present, or the start of the containing `moof` when the
    /// `default-base-is-moof` flag (0x020000) is set, or โ€” failing
    /// both โ€” the start of the first `mdat` after this `moof`. The
    /// last fall-back is rare in practice; we approximate it by
    /// using the moof start, which matches every fragment in our
    /// test corpus and the ยง8.8.7.1 spec text "either the first byte
    /// of the enclosing Movie Fragment Box".
    base_data_offset: u64,
    /// Per-track defaults from `tfhd`, falling back to `trex`.
    default_sample_duration: u32,
    default_sample_size: u32,
    default_sample_flags: u32,
    /// `tfdt.base_media_decode_time` โ€” first sample's DTS in this
    /// fragment, in the track's media timescale. `None` when no
    /// `tfdt` is present (then the running `next_dts` is used).
    base_media_decode_time: Option<i64>,
    /// ยง8.8.7 `sample_description_index` for every sample in this
    /// traf โ€” from `tfhd` when its 0x000002 flag is set, else the
    /// `trex` default. 1-based; 0 only when the file supplied 0 (a
    /// spec violation preserved verbatim).
    sample_description_index: u32,
}

/// `tfhd` flag bits (ISO/IEC 14496-12 ยง8.8.7.1).
const TFHD_BASE_DATA_OFFSET_PRESENT: u32 = 0x000001;
const TFHD_SAMPLE_DESCRIPTION_INDEX_PRESENT: u32 = 0x000002;
const TFHD_DEFAULT_SAMPLE_DURATION_PRESENT: u32 = 0x000008;
const TFHD_DEFAULT_SAMPLE_SIZE_PRESENT: u32 = 0x000010;
const TFHD_DEFAULT_SAMPLE_FLAGS_PRESENT: u32 = 0x000020;
/// `duration-is-empty` (ยง8.8.7.1, 0x010000): the traf adds "empty
/// time" to the track โ€” the effective default sample duration (tfhd
/// override, else the trex default) names an interval for which there
/// are no samples, and per ยง8.8.8.1 "If the duration-is-empty flag is
/// set in the tf_flags, there are no track runs".
const TFHD_DURATION_IS_EMPTY: u32 = 0x010000;
// `default-base-is-moof` (0x020000) is implicit in our base resolution:
// when no explicit `base_data_offset` is present we already use
// `moof_start`, which matches both the 0x020000 semantic and the
// "first byte of the enclosing Movie Fragment Box" spec fall-back.
#[allow(dead_code)]
const TFHD_DEFAULT_BASE_IS_MOOF: u32 = 0x020000;

/// `trun` flag bits (ISO/IEC 14496-12 ยง8.8.8.1).
const TRUN_DATA_OFFSET_PRESENT: u32 = 0x000001;
const TRUN_FIRST_SAMPLE_FLAGS_PRESENT: u32 = 0x000004;
const TRUN_SAMPLE_DURATION_PRESENT: u32 = 0x000100;
const TRUN_SAMPLE_SIZE_PRESENT: u32 = 0x000200;
const TRUN_SAMPLE_FLAGS_PRESENT: u32 = 0x000400;
const TRUN_SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT: u32 = 0x000800;

/// `sample_flags` `sample_is_non_sync_sample` bit
/// (ISO/IEC 14496-12 ยง8.8.3.1, byte 3 bit 0 of the 32-bit field).
const SAMPLE_IS_NON_SYNC: u32 = 0x0001_0000;

/// Decoded `sample_flags` (ISO/IEC 14496-12 ยง8.8.3.1) โ€” the 32-bit
/// field that appears as `default_sample_flags` in `trex` (ยง8.8.3) and
/// `tfhd` (ยง8.8.7), and as `first_sample_flags` / per-sample
/// `sample_flags` in `trun` (ยง8.8.8). All four sites share one packing.
///
/// On-wire layout, MSB to LSB (ยง8.8.3.1):
///
/// ```text
/// bit(4)            reserved = 0;
/// unsigned int(2)   is_leading;                  // bits 27..26
/// unsigned int(2)   sample_depends_on;           // bits 25..24
/// unsigned int(2)   sample_is_depended_on;       // bits 23..22
/// unsigned int(2)   sample_has_redundancy;       // bits 21..20
/// bit(3)            sample_padding_value;        // bits 19..17
/// bit(1)            sample_is_non_sync_sample;   // bit  16
/// unsigned int(16)  sample_degradation_priority; // bits 15..0
/// ```
///
/// The four 2-bit fields (`is_leading`, `sample_depends_on`,
/// `sample_is_depended_on`, `sample_has_redundancy`) share their
/// value semantics with the `sdtp` (SampleDependencyTypeBox) entries โ€”
/// ยง8.8.3.1 says they are "defined as documented in the Independent
/// and Disposable Samples Box" (ยง8.6.4). `sample_is_non_sync_sample`
/// inverts the ยง8.6.2 sync-sample table semantics: when the flag is 0
/// the sample is a sync (key) sample. `sample_padding_value` and
/// `sample_degradation_priority` carry the same meanings as the
/// `padb` / `stdp` (Padding / DegradationPriority) box entries.
///
/// The fields preserve the on-wire small-integer encoding rather than
/// being mapped to typed enums: ยง8.6.4.3's value tables use `0` as
/// "unknown" with format-specific overrides, and surfacing the raw
/// values keeps callers in charge of those overrides (matching the
/// approach taken for the private `SdtpEntry` already in this module).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SampleFlags {
    /// 2 bits (bits 27..26). ยง8.6.4.3 / ยง8.8.3.1.
    /// `0` = leading nature unknown, `1` = leading with a dependency
    /// before the referenced I-picture (not decodable),
    /// `2` = not a leading sample, `3` = leading without that
    /// dependency (decodable).
    pub is_leading: u8,
    /// 2 bits (bits 25..24). ยง8.6.4.3 / ยง8.8.3.1.
    /// `0` = dependency unknown, `1` = depends on others (not an
    /// I-picture), `2` = does not depend on others (I-picture),
    /// `3` = reserved.
    pub sample_depends_on: u8,
    /// 2 bits (bits 23..22). ยง8.6.4.3 / ยง8.8.3.1.
    /// `0` = unknown, `1` = other samples may depend on this one
    /// (not disposable), `2` = no other sample depends on this one
    /// (disposable), `3` = reserved.
    pub sample_is_depended_on: u8,
    /// 2 bits (bits 21..20). ยง8.6.4.3 / ยง8.8.3.1.
    /// `0` = redundancy unknown, `1` = redundant coding present,
    /// `2` = no redundant coding, `3` = reserved.
    pub sample_has_redundancy: u8,
    /// 3 bits (bits 19..17). ยง8.8.3.1 โ€” "defined as for the padding
    /// bits". Carried verbatim without further interpretation.
    pub sample_padding_value: u8,
    /// 1 bit (bit 16). ยง8.8.3.1 โ€” when `false` the sample is a sync
    /// (key) sample, mirroring the ยง8.6.2 sync-sample table absence
    /// semantics ("as if โ€ฆ all samples are sync samples, the sync
    /// sample table were absent").
    pub sample_is_non_sync_sample: bool,
    /// 16 bits (bits 15..0). ยง8.8.3.1 โ€” "defined as for the
    /// degradation priority table" (ยง8.5.3). Producers that don't
    /// carry per-sample priority leave this zero.
    pub sample_degradation_priority: u16,
}

impl SampleFlags {
    /// Decode the 32-bit packed `sample_flags` field per ยง8.8.3.1.
    ///
    /// The top 4 reserved bits are not surfaced โ€” ยง8.8.3.1 fixes them
    /// to zero, but we accept non-zero reserved bits without rejecting
    /// (the spec is silent on producer-side enforcement, and a
    /// well-formed reader should tolerate them rather than refuse the
    /// fragment).
    pub fn from_u32(raw: u32) -> Self {
        Self {
            is_leading: ((raw >> 26) & 0x03) as u8,
            sample_depends_on: ((raw >> 24) & 0x03) as u8,
            sample_is_depended_on: ((raw >> 22) & 0x03) as u8,
            sample_has_redundancy: ((raw >> 20) & 0x03) as u8,
            sample_padding_value: ((raw >> 17) & 0x07) as u8,
            sample_is_non_sync_sample: (raw & SAMPLE_IS_NON_SYNC) != 0,
            sample_degradation_priority: (raw & 0xFFFF) as u16,
        }
    }

    /// Round-trip helper โ€” pack the typed fields back into the on-wire
    /// 32-bit form. Reserved bits 31..28 are emitted as zero per
    /// ยง8.8.3.1. Field widths are masked so out-of-range values do not
    /// bleed into neighbouring fields.
    pub fn to_u32(self) -> u32 {
        ((self.is_leading as u32 & 0x03) << 26)
            | ((self.sample_depends_on as u32 & 0x03) << 24)
            | ((self.sample_is_depended_on as u32 & 0x03) << 22)
            | ((self.sample_has_redundancy as u32 & 0x03) << 20)
            | ((self.sample_padding_value as u32 & 0x07) << 17)
            | (if self.sample_is_non_sync_sample {
                SAMPLE_IS_NON_SYNC
            } else {
                0
            })
            | self.sample_degradation_priority as u32
    }

    /// `true` when this is a sync (key) sample โ€” the inverse of
    /// `sample_is_non_sync_sample` per ยง8.8.3.1. Provided as a
    /// convenience because ยง8.6.2 / ยง8.8.3.1 / ยง8.8.8 all use the
    /// "absence = sync" convention and downstream code typically
    /// wants the positive predicate.
    pub fn is_sync_sample(self) -> bool {
        !self.sample_is_non_sync_sample
    }
}

/// Public ยง8.8.3.1 typed-accessor convenience โ€” `pub` re-export of
/// [`SampleFlags::from_u32`] for callers that have the raw on-wire
/// `u32` from a `trex` / `tfhd` / `trun` parse.
pub fn parse_sample_flags(raw: u32) -> SampleFlags {
    SampleFlags::from_u32(raw)
}

#[allow(clippy::too_many_arguments)]
// tfhd / tfdt / senc / saiz / saio / sample-group inputs are independent state carried through the same walk; bundling them into a struct hides the per-box ownership and obscures the moofโ†’traf data flow
fn parse_traf(
    body: &[u8],
    moof_start: u64,
    tracks: &[Track],
    samples: &mut Vec<SampleRef>,
    next_dts: &mut [i64],
    moof_sequence: u32,
    senc_records: &mut Vec<SencRecord>,
    sai_records: &mut Vec<SaiRecord>,
    traf_sample_groups: &mut Vec<TrafSampleGroupRecord>,
    piff_senc_records: &mut Vec<PiffSencRecord>,
    empty_durations: &mut Vec<EmptyDurationRecord>,
    sample_budget: &mut u64,
) -> Result<()> {
    // First pass: read tfhd + tfdt before the trun(s) so each trun
    // has the full default context. Also pick up senc (ISO/IEC 23001-7
    // ยง7.2) โ€” it has no on-wire ordering dependency on tfhd/tfdt, but
    // parsing it needs the matching track's tenc.default_Per_Sample_IV_Size
    // to know how many IV bytes to consume per sample.
    let mut state = TrafState::default();
    let mut tfhd_seen = false;
    let mut senc_body: Option<Vec<u8>> = None;
    // PIFF legacy `uuid` SampleEncryptionBox body (usertype already
    // stripped) โ€” deferred for the same reason as `senc`: when the
    // box has no `flags & 1` override triple, its IV width comes from
    // the track's (PIFF or CENC) tenc default, and the track is only
    // known after `tfhd`.
    let mut piff_senc_body: Option<Vec<u8>> = None;
    let mut frag_saiz: Vec<TrafSaiz> = Vec::new();
    let mut frag_saio: Vec<TrafSaio> = Vec::new();
    // ยง8.9 โ€” fragment-local sample-group boxes. A `traf` may carry its
    // own `sgpd` descriptions plus `sbgp` / `csgp` per-sample maps (the
    // `csgp` bit-7 fragment-local convention is only legal here). Collect
    // them verbatim; the grouping-type semantics belong to the caller.
    let mut frag_sgpd: Vec<SgpdBox> = Vec::new();
    let mut frag_sbgp: Vec<SbgpBox> = Vec::new();
    let mut frag_csgp: Vec<CsgpBox> = Vec::new();

    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            TFHD => {
                let b = read_bytes_vec(&mut cur, psz)?;
                parse_tfhd(&b, moof_start, tracks, &mut state)?;
                tfhd_seen = true;
            }
            TFDT => {
                let b = read_bytes_vec(&mut cur, psz)?;
                state.base_media_decode_time = Some(parse_tfdt(&b)?);
            }
            // ยง7.2 senc โ€” keep the bytes; we need the track's tenc
            // first (via state.track_idx, populated by tfhd) before we
            // can interpret the per-sample IV width.
            SENC => {
                senc_body = Some(read_bytes_vec(&mut cur, psz)?);
            }
            // PIFF legacy `uuid` boxes inside `traf`: the pre-CENC
            // SampleEncryptionBox is the only encryption usertype
            // placed here. Keep the body (sans usertype) for the
            // post-tfhd parse; unknown usertypes (e.g. the Smooth
            // Streaming tfxd/tfrf fragment-timing boxes) are skipped.
            UUID => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if b.len() >= 16 && b[..16] == PIFF_SENC_USERTYPE {
                    piff_senc_body = Some(b[16..].to_vec());
                }
            }
            // ยง8.7.8 / ยง8.7.9 โ€” `saiz` / `saio` inside `traf`.
            // Promote the parsed `SaizBox` / `SaioBox` to the public
            // fragment-record shape (`TrafSaiz` / `TrafSaio`) so the
            // demuxer surface exposes the per-fragment auxiliary-info
            // table to a downstream CENC layer that needs it as a
            // `senc` alternative (per ยง8.8.14: in a `traf`, `saio`
            // offsets are relative to `tfhd.base_data_offset`).
            SAIZ => {
                let b = read_bytes_vec(&mut cur, psz)?;
                let sb = parse_saiz(&b)?;
                frag_saiz.push(TrafSaiz {
                    aux_info_type: sb.aux_info_type,
                    aux_info_type_parameter: sb.aux_info_type_parameter,
                    default_sample_info_size: sb.default_sample_info_size,
                    sample_count: sb.sample_count,
                    per_sample: sb.per_sample,
                });
            }
            SAIO => {
                let b = read_bytes_vec(&mut cur, psz)?;
                let sb = parse_saio(&b)?;
                frag_saio.push(TrafSaio {
                    version: sb.version,
                    aux_info_type: sb.aux_info_type,
                    aux_info_type_parameter: sb.aux_info_type_parameter,
                    offsets: sb.offsets,
                });
            }
            // ยง8.9.3 / ยง8.9.2 / ยง8.9.5 โ€” fragment-local sample-group
            // boxes. A malformed box is dropped (the fragment's samples
            // are still usable); a well-formed one is preserved verbatim.
            SGPD => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if let Ok(g) = parse_sgpd(&b) {
                    frag_sgpd.push(g);
                }
            }
            SBGP => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if let Ok(g) = parse_sbgp(&b) {
                    frag_sbgp.push(g);
                }
            }
            CSGP => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if let Ok(g) = parse_csgp(&b) {
                    frag_csgp.push(g);
                }
            }
            // We only resolve trun's in the second pass; skip here.
            TRUN => skip_cursor_bytes(&mut cur, psz),
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }

    if !tfhd_seen {
        return Err(Error::invalid("MP4: traf missing tfhd"));
    }

    // ยง8.8.7.1 duration-is-empty (0x010000): this traf adds "empty
    // time" โ€” there are no samples for the interval (ยง8.8.6.1), whose
    // length is the effective default sample duration (tfhd override,
    // else trex). Per ยง8.8.8.1 "If the duration-is-empty flag is set
    // in the tf_flags, there are no track runs" โ€” so the trun walk is
    // skipped entirely: honouring a trun a non-conforming producer
    // left behind would both fabricate samples the flag says don't
    // exist and double-count the interval. The track's running decode
    // time advances by the empty duration (a tfdt in this traf, if
    // present, re-anchors it first), so a subsequent tfdt-less
    // fragment lands after the gap. Per-sample carriers (senc / saiz
    // / saio / sample-group maps) are meaningless without samples and
    // are not recorded for an empty traf.
    if state.tfhd_flags & TFHD_DURATION_IS_EMPTY != 0 {
        let start = state
            .base_media_decode_time
            .unwrap_or(next_dts[state.track_idx]);
        empty_durations.push(EmptyDurationRecord {
            track_idx: state.track_idx as u32,
            moof_sequence,
            duration: state.default_sample_duration,
        });
        next_dts[state.track_idx] = start.saturating_add(state.default_sample_duration as i64);
        return Ok(());
    }

    let track = &tracks[state.track_idx];

    // ISO/IEC 23001-7 ยง7.2 โ€” now that we know which track this traf
    // refers to, we can recover the per-sample IV width from the
    // track's tenc default and parse the captured senc body. Tracks
    // without tenc (non-CENC protection scheme, or no protection at
    // all) drop the senc on the floor โ€” a malformed file may carry
    // it without the matching scheme box, but there's nothing the
    // demuxer can do with it without an IV-size key.
    let mut standard_senc_recorded = false;
    if let Some(body) = senc_body {
        if let Some(tenc) = &track.tenc {
            if let Ok(senc) = parse_senc(&body, tenc.default_per_sample_iv_size) {
                senc_records.push(SencRecord {
                    track_idx: state.track_idx as u32,
                    moof_sequence,
                    senc,
                });
                standard_senc_recorded = true;
            }
        }
    }

    // PIFF legacy `uuid` SampleEncryptionBox. The IV width resolves
    // from the box's own `flags & 1` override triple when present;
    // otherwise from the track's PIFF tenc default (or the CENC tenc
    // of a dual-branded file). A box with neither source is
    // unparseable (same drop policy as an IV-size-less `senc`) โ€”
    // `parse_piff_senc` is handed width 0 and the entry table then
    // either fails or the box legitimately carries subsample-only
    // entries. On success the typed record is always surfaced; it is
    // additionally bridged into the standard `senc_records` surface
    // (per-sample tables are byte-compatible) when this `traf` carried
    // no parseable 4CC `senc`, so a CENC decryption layer consumes
    // PIFF-only fragments unchanged without double-reporting
    // dual-branded ones.
    if let Some(body) = piff_senc_body {
        let default_iv_size = track
            .piff_tenc
            .as_ref()
            .map(|p| p.iv_size)
            .or_else(|| track.tenc.as_ref().map(|t| t.default_per_sample_iv_size))
            .unwrap_or(0);
        if let Ok(piff) = parse_piff_senc(&body, default_iv_size) {
            if !standard_senc_recorded {
                senc_records.push(SencRecord {
                    track_idx: state.track_idx as u32,
                    moof_sequence,
                    senc: piff.to_senc(),
                });
            }
            piff_senc_records.push(PiffSencRecord {
                track_idx: state.track_idx as u32,
                moof_sequence,
                senc: piff,
            });
        }
    }

    // ยง8.7.8โ€“9 โ€” if this `traf` carried any auxiliary-information
    // boxes, record them as one `SaiRecord` keyed by the same
    // `(track_idx, moof_sequence)` pair as the senc record. The
    // demuxer leaves pairing (`saiz` โ†” `saio` by `(aux_info_type,
    // aux_info_type_parameter)`) to the consumer, so even an
    // unmatched box (a producer slip โ€” `saiz` without `saio` or vice
    // versa) is preserved verbatim for inspection.
    if !frag_saiz.is_empty() || !frag_saio.is_empty() {
        sai_records.push(SaiRecord {
            track_idx: state.track_idx as u32,
            moof_sequence,
            saiz: frag_saiz,
            saio: frag_saio,
            base_data_offset: state.base_data_offset,
        });
    }

    // ยง8.9 โ€” record this traf's fragment-local sample-group boxes (if
    // any) keyed by `(track_idx, moof_sequence)`, so a downstream layer
    // can resolve per-fragment grouping (e.g. CENC `seig` key rotation)
    // without re-walking the file.
    if !frag_sgpd.is_empty() || !frag_sbgp.is_empty() || !frag_csgp.is_empty() {
        traf_sample_groups.push(TrafSampleGroupRecord {
            track_idx: state.track_idx as u32,
            moof_sequence,
            sgpd: frag_sgpd,
            sbgp: frag_sbgp,
            csgp: frag_csgp,
        });
    }

    // Each trun walks samples from its own data_offset relative to
    // base_data_offset. Track running data offset across multiple
    // truns within a single traf โ€” per spec, when a trun has no
    // explicit data_offset it picks up where the previous trun left
    // off (sequential append).
    //
    // Running DTS within this fragment starts at base_media_decode_time
    // (or the carried-over next_dts when tfdt is absent).
    let mut frag_dts: i64 = state
        .base_media_decode_time
        .unwrap_or(next_dts[state.track_idx]);
    let mut next_data_offset_within_traf: u64 = state.base_data_offset;

    let mut cur = std::io::Cursor::new(body);
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        if hdr.fourcc != TRUN {
            skip_cursor_bytes(&mut cur, psz);
            continue;
        }
        let b = read_bytes_vec(&mut cur, psz)?;
        let parsed = parse_trun(&b, sample_budget)?;

        // Resolve the run's starting data offset:
        // * explicit data_offset present โ†’ relative to base_data_offset
        //   (for the first trun in a traf) or to start of moof when
        //   that's how base was derived. The spec defines `data_offset`
        //   as relative to the position of `moof.start + offset` when
        //   `tfhd.base_data_offset` is absent and default-base-is-moof
        //   is set; relative to `tfhd.base_data_offset` otherwise.
        //   We've already collapsed both into `state.base_data_offset`,
        //   so it's `base + data_offset`.
        // * absent โ†’ continue from end of previous trun's data.
        let mut sample_off = if let Some(d) = parsed.data_offset {
            // i32 โ†’ wrap into u64 by sign-extending so a negative
            // offset (rare but legal) backs up into the moof.
            (state.base_data_offset as i64).wrapping_add(d as i64) as u64
        } else {
            next_data_offset_within_traf
        };

        for (i, s) in parsed.samples.iter().enumerate() {
            let dur = s.duration.unwrap_or(state.default_sample_duration) as i64;
            let size = s.size.unwrap_or(state.default_sample_size);
            // Per-sample flags: explicit > first_sample_flags (i==0)
            // > tfhd default > trex default. The is-sync bit is
            // 0x0001_0000 when the sample is **non**-sync.
            let flags = s.flags.unwrap_or_else(|| {
                if i == 0 {
                    parsed
                        .first_sample_flags
                        .unwrap_or(state.default_sample_flags)
                } else {
                    state.default_sample_flags
                }
            });
            let keyframe = (flags & SAMPLE_IS_NON_SYNC) == 0;
            let cts_off = s.composition_time_offset.unwrap_or(0) as i64;
            // ยง8.6.6 edit-list mapping โ€” same per-segment delta +
            // discard semantics as the moov sample-table path (the
            // elst lives in the moov and spans the fragments).
            let media_cts = frag_dts.saturating_add(cts_off);
            let (elst_delta, presented) = track.elst_timeline.delta_for_cts(media_cts);
            let dts_v = frag_dts.saturating_add(elst_delta);
            let cts_v = media_cts.saturating_add(elst_delta);

            samples.push(SampleRef {
                track_idx: state.track_idx as u32,
                offset: sample_off,
                size,
                pts: cts_v,
                dts: dts_v,
                duration: dur,
                keyframe,
                discard: !presented,
                sdi: state.sample_description_index,
            });

            sample_off = sample_off.saturating_add(size as u64);
            frag_dts = frag_dts.saturating_add(dur);
        }
        next_data_offset_within_traf = sample_off;
    }

    next_dts[state.track_idx] = frag_dts;
    Ok(())
}

/// ยง8.8.7 โ€” `tfhd` (TrackFragmentHeaderBox).
///
/// Layout: FullBox header (4 bytes) + track_ID (u32). Then optional
/// fields gated by the flag bits in the lower 24 bits of the FullBox
/// header (in the order they appear in the spec table).
fn parse_tfhd(body: &[u8], moof_start: u64, tracks: &[Track], state: &mut TrafState) -> Result<()> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: tfhd too short"));
    }
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let track_id = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let track_idx = tracks
        .iter()
        .position(|t| t.track_id == track_id)
        .ok_or_else(|| {
            Error::invalid(format!("MP4: tfhd refers to unknown track_ID {track_id}"))
        })?;

    let mut off = 8;
    let trex = tracks[track_idx].trex;

    // Initial defaults from trex; tfhd flags will overwrite.
    state.track_idx = track_idx;
    state.tfhd_flags = flags;
    state.default_sample_duration = trex.default_sample_duration;
    state.default_sample_size = trex.default_sample_size;
    state.default_sample_flags = trex.default_sample_flags;
    state.sample_description_index = trex.default_sample_description_index;

    // Reset the per-traf bmdt โ€” it'll be set by tfdt if present.
    state.base_media_decode_time = None;

    // Establish base_data_offset.
    let mut explicit_base: Option<u64> = None;
    if flags & TFHD_BASE_DATA_OFFSET_PRESENT != 0 {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: tfhd base_data_offset truncated"));
        }
        let v = u64::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
            body[off + 4],
            body[off + 5],
            body[off + 6],
            body[off + 7],
        ]);
        explicit_base = Some(v);
        off += 8;
    }
    if flags & TFHD_SAMPLE_DESCRIPTION_INDEX_PRESENT != 0 {
        if off + 4 > body.len() {
            return Err(Error::invalid(
                "MP4: tfhd sample_description_index truncated",
            ));
        }
        // ยง8.8.7: overrides the trex default for every sample in this
        // traf. Decode still uses stsd entry [0]; the index is carried
        // per sample so callers can detect a mid-stream description
        // switch (surfaced via `Mp4Demuxer::sample_description_index_of_last_packet`).
        state.sample_description_index =
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
    }
    if flags & TFHD_DEFAULT_SAMPLE_DURATION_PRESENT != 0 {
        if off + 4 > body.len() {
            return Err(Error::invalid(
                "MP4: tfhd default_sample_duration truncated",
            ));
        }
        state.default_sample_duration =
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
    }
    if flags & TFHD_DEFAULT_SAMPLE_SIZE_PRESENT != 0 {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: tfhd default_sample_size truncated"));
        }
        state.default_sample_size =
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
    }
    if flags & TFHD_DEFAULT_SAMPLE_FLAGS_PRESENT != 0 {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: tfhd default_sample_flags truncated"));
        }
        state.default_sample_flags =
            u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        // off += 4; // last optional, no further reads
    }

    // Resolve effective base_data_offset:
    // 1. explicit base_data_offset wins.
    // 2. otherwise, default-base-is-moof flag (0x020000) โ†’ moof_start.
    // 3. otherwise, per spec the "first byte of the enclosing Movie
    //    Fragment Box" โ€” same as moof_start. (Spec actually says
    //    "first byte of the enclosing Movie Fragment Box" for the
    //    *first* traf in the moof, and "end of the previous traf's
    //    data" for subsequent ones, but every real fragmented file we
    //    care about either sets explicit base or default-base-is-moof.)
    state.base_data_offset = explicit_base.unwrap_or(moof_start);

    Ok(())
}

/// ยง8.8.12 โ€” `tfdt` (TrackFragmentDecodeTimeBox).
///
/// Layout: FullBox header (4 bytes) + base_media_decode_time
/// (u32 if version=0, u64 if version=1).
fn parse_tfdt(body: &[u8]) -> Result<i64> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: tfdt too short"));
    }
    let version = body[0];
    if version == 1 {
        if body.len() < 12 {
            return Err(Error::invalid("MP4: tfdt v1 too short"));
        }
        Ok(u64::from_be_bytes([
            body[4], body[5], body[6], body[7], body[8], body[9], body[10], body[11],
        ]) as i64)
    } else {
        if body.len() < 8 {
            return Err(Error::invalid("MP4: tfdt v0 too short"));
        }
        Ok(u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as i64)
    }
}

/// One sample's optional per-sample fields from a `trun` entry. Each
/// `Some` carries the explicit value; `None` defers to the per-traf
/// or per-track defaults.
#[derive(Clone, Copy, Debug, Default)]
struct TrunSample {
    duration: Option<u32>,
    size: Option<u32>,
    flags: Option<u32>,
    composition_time_offset: Option<i32>,
}

#[derive(Default)]
struct ParsedTrun {
    /// `data_offset` (i32) when the `data-offset-present` flag is set.
    /// Relative to the effective base_data_offset.
    data_offset: Option<i32>,
    /// Override flags for the *first* sample of the run when the
    /// `first-sample-flags-present` flag is set.
    first_sample_flags: Option<u32>,
    samples: Vec<TrunSample>,
}

/// ยง8.8.8 โ€” `trun` (TrackRunBox).
///
/// Layout: FullBox header (4 bytes), sample_count (u32),
/// optional data_offset (i32), optional first_sample_flags (u32),
/// then sample_count repeats of the per-sample optional fields in the
/// fixed order: duration, size, flags, composition_time_offset.
fn parse_trun(body: &[u8], sample_budget: &mut u64) -> Result<ParsedTrun> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: trun too short"));
    }
    let version = body[0];
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let sample_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    // ยง8.8.8.2 `sample_count` is attacker-controlled and โ€” in the
    // defaults-only shape, where no per-sample field flag is set โ€”
    // backed by zero wire bytes, so it must clear the whole-file
    // sample budget before anything is allocated for it. Runs with
    // per-sample fields are additionally validated against the body
    // length below.
    if sample_count as u64 > *sample_budget {
        return Err(Error::invalid(
            "MP4: trun sample_count exceeds input-backed sample budget",
        ));
    }
    let mut off = 8usize;

    let mut out = ParsedTrun::default();

    if flags & TRUN_DATA_OFFSET_PRESENT != 0 {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: trun data_offset truncated"));
        }
        out.data_offset = Some(i32::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
        ]));
        off += 4;
    }
    if flags & TRUN_FIRST_SAMPLE_FLAGS_PRESENT != 0 {
        if off + 4 > body.len() {
            return Err(Error::invalid("MP4: trun first_sample_flags truncated"));
        }
        out.first_sample_flags = Some(u32::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
        ]));
        off += 4;
    }

    let per_sample_fields = ((flags & TRUN_SAMPLE_DURATION_PRESENT) != 0) as usize
        + ((flags & TRUN_SAMPLE_SIZE_PRESENT) != 0) as usize
        + ((flags & TRUN_SAMPLE_FLAGS_PRESENT) != 0) as usize
        + ((flags & TRUN_SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT) != 0) as usize;
    let needed = sample_count.saturating_mul(4 * per_sample_fields);
    if off + needed > body.len() {
        return Err(Error::invalid("MP4: trun samples truncated"));
    }
    // Both validations passed โ€” charge the budget and reserve.
    *sample_budget -= sample_count as u64;
    out.samples.reserve(sample_count);

    for _ in 0..sample_count {
        let mut s = TrunSample::default();
        if flags & TRUN_SAMPLE_DURATION_PRESENT != 0 {
            s.duration = Some(u32::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
            ]));
            off += 4;
        }
        if flags & TRUN_SAMPLE_SIZE_PRESENT != 0 {
            s.size = Some(u32::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
            ]));
            off += 4;
        }
        if flags & TRUN_SAMPLE_FLAGS_PRESENT != 0 {
            s.flags = Some(u32::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
            ]));
            off += 4;
        }
        if flags & TRUN_SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT != 0 {
            // v0: u32, v1: i32 (ยง8.8.8.2 โ€” one shared 32-bit width,
            // unsigned in v0 and signed in v1). We always store i32,
            // preserving the bit pattern; a v0 value above i32::MAX
            // (beyond any practical composition offset) wraps.
            let raw = [body[off], body[off + 1], body[off + 2], body[off + 3]];
            let v = if version == 0 {
                u32::from_be_bytes(raw) as i32
            } else {
                i32::from_be_bytes(raw)
            };
            s.composition_time_offset = Some(v);
            off += 4;
        }
        out.samples.push(s);
    }
    Ok(out)
}

// --- Random-access index parsers (ยง8.16.3 sidx, ยง8.8.10โ€“11 mfra/tfra) ----

/// ยง8.16.3 โ€” `sidx` SegmentIndexBox.
///
/// Layout (FullBox 4 bytes already consumed by caller):
///   reference_ID (u32),
///   timescale (u32),
///   if version==0: earliest_presentation_time (u32) + first_offset (u32)
///   if version==1: earliest_presentation_time (u64) + first_offset (u64)
///   reserved (u16) = 0
///   reference_count (u16)
///   for each ref:
///     [bit 31] reference_type (1 = sidx, 0 = media subseg)
///     [bits 30..0] referenced_size (u31)
///     subsegment_duration (u32)
///     [bit 31] starts_with_SAP (1 bit)
///     [bits 30..28] SAP_type (3 bits)
///     [bits 27..0] SAP_delta_time (u28) โ€” we don't surface
///
/// `sidx_end_offset` is the absolute file offset of the first byte AFTER
/// the sidx box (its body's spec-defined anchor for `first_offset`).
fn parse_sidx(body: &[u8], sidx_end_offset: u64) -> Result<Option<SidxRecord>> {
    if body.len() < 12 {
        return Err(Error::invalid("MP4: sidx too short"));
    }
    let version = body[0];
    let mut off = 4usize; // skip version + 3-byte flags
    let reference_id = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
    off += 4;
    let timescale = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
    off += 4;
    let (ept, first_offset) = if version == 0 {
        if off + 8 > body.len() {
            return Err(Error::invalid("MP4: sidx v0 truncated"));
        }
        let e = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64;
        off += 4;
        let f = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64;
        off += 4;
        (e, f)
    } else {
        if off + 16 > body.len() {
            return Err(Error::invalid("MP4: sidx v1 truncated"));
        }
        let e = u64::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
            body[off + 4],
            body[off + 5],
            body[off + 6],
            body[off + 7],
        ]);
        off += 8;
        let f = u64::from_be_bytes([
            body[off],
            body[off + 1],
            body[off + 2],
            body[off + 3],
            body[off + 4],
            body[off + 5],
            body[off + 6],
            body[off + 7],
        ]);
        off += 8;
        (e, f)
    };
    if off + 4 > body.len() {
        return Err(Error::invalid("MP4: sidx header truncated"));
    }
    // skip 2-byte reserved
    let reference_count = u16::from_be_bytes([body[off + 2], body[off + 3]]) as usize;
    off += 4;
    let needed = reference_count.saturating_mul(12);
    if off + needed > body.len() {
        return Err(Error::invalid("MP4: sidx references truncated"));
    }
    let mut references = Vec::with_capacity(reference_count);
    for _ in 0..reference_count {
        let r0 = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
        let r1 = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
        let r2 = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
        off += 4;
        let is_sidx = (r0 & 0x8000_0000) != 0;
        let referenced_size = r0 & 0x7FFF_FFFF;
        let starts_with_sap = (r2 & 0x8000_0000) != 0;
        let sap_type = ((r2 >> 28) & 0x7) as u8;
        references.push(SidxReference {
            is_sidx,
            referenced_size,
            subsegment_duration: r1,
            starts_with_sap,
            sap_type,
        });
    }
    Ok(Some(SidxRecord {
        reference_id,
        timescale,
        earliest_presentation_time: ept,
        first_byte_offset: sidx_end_offset.saturating_add(first_offset),
        references,
    }))
}

/// ยง8.16.4 โ€” `ssix` SubsegmentIndexBox.
///
/// Layout (ยง8.16.4.2):
///
/// ```text
///     FullBox(ssix, version = 0, flags = 0)
///     unsigned int(32) subsegment_count;
///     for (i = 1; i <= subsegment_count; i++) {
///         unsigned int(32) range_count;
///         for (j = 1; j <= range_count; j++) {
///             unsigned int(8)  level;
///             unsigned int(24) range_size;
///         }
///     }
/// }
/// ```
///
/// Only version 0 is defined; a different version byte is rejected
/// rather than mis-read against the v0 layout. `subsegment_count` and
/// each `range_count` are attacker-controlled u32s, so capacity is
/// pre-allocated against the bytes actually remaining (4 per range,
/// โ‰ฅ 4 per subsegment), never against the declared counts; any count
/// that outruns the body is a truncation error.
fn parse_ssix(body: &[u8]) -> Result<SsixRecord> {
    if body.len() < 8 {
        return Err(Error::invalid("MP4: ssix too short"));
    }
    if body[0] != 0 {
        return Err(Error::invalid("MP4: ssix unsupported version"));
    }
    // bytes 1..4 are flags (always 0 per ยง8.16.4.2) โ€” not consumed.
    let subsegment_count = u32::from_be_bytes([body[4], body[5], body[6], body[7]]) as usize;
    let mut cursor = 8usize;
    let mut subsegments =
        Vec::with_capacity(subsegment_count.min(body.len().saturating_sub(cursor) / 4));
    for _ in 0..subsegment_count {
        if body.len() - cursor < 4 {
            return Err(Error::invalid("MP4: ssix subsegment truncated"));
        }
        let range_count = u32::from_be_bytes([
            body[cursor],
            body[cursor + 1],
            body[cursor + 2],
            body[cursor + 3],
        ]) as usize;
        cursor += 4;
        if (body.len() - cursor) / 4 < range_count {
            return Err(Error::invalid("MP4: ssix range list truncated"));
        }
        let mut ranges = Vec::with_capacity(range_count);
        for _ in 0..range_count {
            let level = body[cursor];
            let range_size =
                u32::from_be_bytes([0, body[cursor + 1], body[cursor + 2], body[cursor + 3]]);
            cursor += 4;
            ranges.push(SsixRange { level, range_size });
        }
        subsegments.push(SsixSubsegment { ranges });
    }
    Ok(SsixRecord { subsegments })
}

/// ยง8.16.5 โ€” `prft` ProducerReferenceTimeBox.
///
/// Layout (FullBox 4 bytes already consumed by caller):
///   reference_track_ID (u32),
///   ntp_timestamp (u64 โ€” NTP-format UTC time, RFC 5905),
///   if version == 0: media_time (u32)
///   if version == 1: media_time (u64)
///
/// Total body length: 16 bytes (v0) or 20 bytes (v1).
///
/// Per ยง8.16.5.3, `media_time` is on the reference track's media
/// clock and corresponds to the same instant as `ntp_timestamp`. The
/// box is associated with the NEXT `moof` in file order (ยง8.16.5.1
/// placement rule); we don't enforce that ordering at parse time โ€”
/// callers correlate by file position.
/// Parse a `pdin` (ProgressiveDownloadInfoBox, ISO/IEC 14496-12 ยง8.1.3)
/// body. The body is the bytes after the 8/16-byte box header.
///
/// Layout (ยง8.1.3.2):
///
/// ```text
///     FullBox(pdin, version = 0, flags = 0)
///     for (i = 0; ; i++) {        // to end of box
///         unsigned int(32) rate;
///         unsigned int(32) initial_delay;
///     }
/// ```
///
/// The 4-byte FullBox preamble is consumed and verified to fit. The
/// remaining payload must be a multiple of 8 bytes (one u32 pair per
/// entry); a body whose post-preamble length is not a multiple of 8
/// is rejected as malformed rather than silently truncated to the
/// nearest pair. A zero-pair body is permitted and yields an empty
/// `entries` vec โ€” the box is informational and an empty table is
/// the producer's way of saying "no progressive-download hints
/// available".
///
/// Version is pinned to 0 by ยง8.1.3.2; a non-zero version is tolerated
/// (the on-wire layout is unambiguous) rather than rejected, mirroring
/// `parse_padb` / `parse_stdp` posture for FullBox version-bit slips.
fn parse_pdin(body: &[u8]) -> Result<PdinRecord> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: pdin too short"));
    }
    // Skip the 4-byte FullBox preamble (version + flags). ยง8.1.3.2 pins
    // version = 0 and flags = 0; we tolerate anything the producer
    // wrote because the payload layout is unambiguous.
    let payload = &body[4..];
    if payload.len() % 8 != 0 {
        return Err(Error::invalid(
            "MP4: pdin payload not a multiple of 8 bytes (rate + initial_delay pairs)",
        ));
    }
    let count = payload.len() / 8;
    let mut entries = Vec::with_capacity(count);
    for i in 0..count {
        let off = i * 8;
        let rate = u32::from_be_bytes([
            payload[off],
            payload[off + 1],
            payload[off + 2],
            payload[off + 3],
        ]);
        let initial_delay = u32::from_be_bytes([
            payload[off + 4],
            payload[off + 5],
            payload[off + 6],
            payload[off + 7],
        ]);
        entries.push(PdinEntry {
            rate,
            initial_delay,
        });
    }
    Ok(PdinRecord { entries })
}

/// Parse a `trep` TrackExtensionPropertiesBox body (ISO/IEC 14496-12
/// ยง8.8.15).
///
/// Wire layout (ยง8.8.15.2):
/// ```text
/// class TrackExtensionPropertiesBox extends FullBox('trep', 0, 0) {
///     unsigned int(32) track_id;
///     // Any number of boxes may follow
/// }
/// ```
///
/// The body is a 4-byte FullBox preamble (version + flags), a 4-byte
/// `track_id`, then "any number of boxes" (ยง8.8.15.2). Those trailing
/// children โ€” e.g. `assp` (ยง8.8.16) โ€” are recorded by type + payload
/// length only ([`TrepChild`]); this parser does not recurse into them.
///
/// Version is pinned to 0 by ยง8.8.15.2; a non-zero version is tolerated
/// (the layout up to `track_id` is unambiguous) rather than rejected,
/// matching the `parse_leva` / `parse_pdin` posture for FullBox
/// version-bit slips.
///
/// A child box whose declared size overruns the remaining `trep` body
/// is clamped to the bytes available and recorded with the clamped
/// length; parsing then stops (a child can't legally extend past its
/// parent, and continuing would desynchronise the walk). A child header
/// that itself doesn't fit (fewer than 8 bytes left) ends the child
/// loop. Neither case rejects the box โ€” the `track_id` is still useful.
fn parse_trep(body: &[u8]) -> Result<TrepRecord> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: trep too short for FullBox preamble"));
    }
    // Skip the 4-byte FullBox preamble (version + flags). ยง8.8.15.2
    // pins version = 0 and flags = 0; tolerated otherwise (the layout
    // up to track_id is fixed regardless).
    let payload = &body[4..];
    if payload.len() < 4 {
        return Err(Error::invalid("MP4: trep truncated track_id"));
    }
    let track_id = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);

    // Walk the trailing "any number of boxes" recording each child's
    // type + payload length. We parse the child headers inline rather
    // than via `read_box_header` so a clamped/over-long child can't
    // abort the whole parse (the demuxer treats trep as informational).
    let mut children = Vec::new();
    let mut off = 4usize;
    while off + 8 <= payload.len() {
        let size32 = u32::from_be_bytes([
            payload[off],
            payload[off + 1],
            payload[off + 2],
            payload[off + 3],
        ]) as usize;
        let fourcc = [
            payload[off + 4],
            payload[off + 5],
            payload[off + 6],
            payload[off + 7],
        ];
        // ยง4.2 box-size semantics: size 0 means "to end of enclosing
        // box"; size 1 means a 64-bit largesize follows. trep children
        // are small property boxes, so we read the 64-bit largesize
        // when present and treat size 0 as "rest of the trep body".
        let (header_len, box_size) = match size32 {
            0 => (8usize, payload.len() - off),
            1 => {
                if off + 16 > payload.len() {
                    // largesize header doesn't fit โ€” stop the walk.
                    break;
                }
                let large = u64::from_be_bytes([
                    payload[off + 8],
                    payload[off + 9],
                    payload[off + 10],
                    payload[off + 11],
                    payload[off + 12],
                    payload[off + 13],
                    payload[off + 14],
                    payload[off + 15],
                ]) as usize;
                (16usize, large)
            }
            n => (8usize, n),
        };
        // A box can't be smaller than its own header. A malformed
        // small size ends the walk rather than looping forever.
        if box_size < header_len {
            break;
        }
        // Clamp an over-long child to the bytes that remain in the
        // trep body โ€” a child legally can't extend past its parent.
        let available = payload.len() - off;
        let effective = box_size.min(available);
        let payload_len = effective - header_len;
        // The one base-spec-defined `trep` child is `assp` (ยง8.8.16);
        // decode its body into a typed record. A malformed `assp` still
        // contributes its type + length (assp = None) so the child list
        // stays faithful to the wire and never aborts the trep parse.
        let assp = if &fourcc == b"assp" {
            parse_assp(&payload[off + header_len..off + effective]).ok()
        } else {
            None
        };
        children.push(TrepChild {
            fourcc,
            payload_len,
            assp,
        });
        off += effective;
        // If we clamped (the declared size ran past the parent), there
        // are no further siblings โ€” stop cleanly.
        if effective < box_size {
            break;
        }
    }

    Ok(TrepRecord { track_id, children })
}

/// Parse an `assp` (AlternativeStartupSequencePropertiesBox, ISO/IEC
/// 14496-12 ยง8.8.16) body โ€” the bytes after the 8/16-byte box header.
///
/// Wire layout (ยง8.8.16.2):
/// ```text
/// FullBox('assp', version, 0) {
///     if (version == 0) {
///         signed int(32) min_initial_alt_startup_offset;
///     } else if (version == 1) {
///         unsigned int(32) num_entries;
///         for (j = 1; j <= num_entries; j++) {
///             unsigned int(32) grouping_type_parameter;
///             signed int(32)   min_initial_alt_startup_offset;
///         }
///     }
/// }
/// ```
///
/// Only versions 0 and 1 are defined (ยง8.8.16.1 ties the box version to
/// the `alst` `sbgp` version); any other version is rejected rather than
/// mis-read. A truncated body โ€” too short for the v0 fixed offset, the
/// v1 `num_entries`, or a declared entry's 8 bytes โ€” is rejected so a
/// partial table never lies about the recorded bounds. `num_entries` is
/// validated against the bytes actually present before allocation.
fn parse_assp(body: &[u8]) -> Result<AsspRecord> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: assp too short for FullBox preamble"));
    }
    let version = body[0];
    // flags (body[1..4]) are pinned to 0 by ยง8.8.16.2 and unused here.
    let payload = &body[4..];
    match version {
        0 => {
            if payload.len() < 4 {
                return Err(Error::invalid("MP4: assp v0 truncated offset"));
            }
            let off = i32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
            Ok(AsspRecord {
                version,
                entries: vec![AsspEntry {
                    grouping_type_parameter: None,
                    min_initial_alt_startup_offset: off,
                }],
            })
        }
        1 => {
            if payload.len() < 4 {
                return Err(Error::invalid("MP4: assp v1 truncated num_entries"));
            }
            let num_entries =
                u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize;
            // Each entry is two 32-bit words (8 bytes). Reject a count
            // that can't be backed by the remaining bytes before
            // allocating.
            let entries_bytes = &payload[4..];
            if num_entries.saturating_mul(8) > entries_bytes.len() {
                return Err(Error::invalid("MP4: assp v1 num_entries overruns body"));
            }
            let mut entries = Vec::with_capacity(num_entries);
            let mut p = 0usize;
            for _ in 0..num_entries {
                let gtp = u32::from_be_bytes([
                    entries_bytes[p],
                    entries_bytes[p + 1],
                    entries_bytes[p + 2],
                    entries_bytes[p + 3],
                ]);
                let off = i32::from_be_bytes([
                    entries_bytes[p + 4],
                    entries_bytes[p + 5],
                    entries_bytes[p + 6],
                    entries_bytes[p + 7],
                ]);
                entries.push(AsspEntry {
                    grouping_type_parameter: Some(gtp),
                    min_initial_alt_startup_offset: off,
                });
                p += 8;
            }
            Ok(AsspRecord { version, entries })
        }
        v => Err(Error::invalid(format!("MP4: assp unsupported version {v}"))),
    }
}

/// Parse a `leva` LevelAssignmentBox body (ISO/IEC 14496-12 ยง8.8.13).
///
/// Wire layout (ยง8.8.13.2):
/// ```text
/// FullBox('leva', 0, 0) {
///     unsigned int(8)  level_count;
///     for (j = 1; j <= level_count; j++) {
///         unsigned int(32) track_id;
///         unsigned int(1)  padding_flag;
///         unsigned int(7)  assignment_type;
///         if (assignment_type == 0)      { unsigned int(32) grouping_type; }
///         else if (assignment_type == 1) { unsigned int(32) grouping_type;
///                                          unsigned int(32) grouping_type_parameter; }
///         else if (assignment_type == 2) {}
///         else if (assignment_type == 3) {}
///         else if (assignment_type == 4) { unsigned int(32) sub_track_id; }
///     }
/// }
/// ```
///
/// Each entry is 4 (track_id) + 1 (padding_flag + assignment_type) + the
/// type-specific tail (0/4/8/0/0/4 bytes for type 2/0/1/2/3/4
/// respectively); a truncated tail rejects the whole box rather than
/// silently dropping the rest of the table โ€” a partial table would lie
/// about which levels exist.
///
/// Version is pinned to 0 by ยง8.8.13.2; a non-zero version is tolerated
/// (the on-wire layout is unambiguous) rather than rejected, mirroring
/// the `parse_pdin` / `parse_padb` / `parse_stdp` posture for FullBox
/// version-bit slips.
///
/// The ยง8.8.13.3 "level_count โ‰ฅ 2" rule is **not** enforced โ€” the spec
/// pins a minimum but the demuxer carries whatever the producer wrote
/// so downstream validators can flag it. A `level_count` of 0 yields an
/// empty `entries` vec.
///
/// Reserved `assignment_type` values (> 4) are carried verbatim with
/// the variant-specific fields left at 0; the spec says they're
/// reserved so this parser doesn't attempt to consume an unknown tail
/// (any non-empty tail for a reserved type would desynchronise the
/// loop). A reserved value therefore takes 5 bytes.
fn parse_leva(body: &[u8]) -> Result<LevaRecord> {
    if body.len() < 4 {
        return Err(Error::invalid("MP4: leva too short for FullBox preamble"));
    }
    // Skip the 4-byte FullBox preamble (version + flags). ยง8.8.13.2 pins
    // version = 0 and flags = 0; tolerated otherwise (layout is fixed).
    let payload = &body[4..];
    if payload.is_empty() {
        return Err(Error::invalid("MP4: leva missing level_count byte"));
    }
    let level_count = payload[0] as usize;
    let mut cursor = 1usize;
    let mut entries = Vec::with_capacity(level_count);
    for _ in 0..level_count {
        // Need at least 5 bytes for track_id (4) + padding+assignment (1).
        if cursor + 5 > payload.len() {
            return Err(Error::invalid(
                "MP4: leva truncated entry header (need 5 bytes for track_id+padding+assignment)",
            ));
        }
        let track_id = u32::from_be_bytes([
            payload[cursor],
            payload[cursor + 1],
            payload[cursor + 2],
            payload[cursor + 3],
        ]);
        let packed = payload[cursor + 4];
        // ยง8.8.13.2: high bit is padding_flag, low 7 bits are
        // assignment_type.
        let padding_flag = (packed & 0x80) != 0;
        let assignment_type = packed & 0x7f;
        cursor += 5;

        let mut grouping_type = 0u32;
        let mut grouping_type_parameter = 0u32;
        let mut sub_track_id = 0u32;
        match assignment_type {
            0 => {
                if cursor + 4 > payload.len() {
                    return Err(Error::invalid(
                        "MP4: leva truncated grouping_type for assignment_type=0",
                    ));
                }
                grouping_type = u32::from_be_bytes([
                    payload[cursor],
                    payload[cursor + 1],
                    payload[cursor + 2],
                    payload[cursor + 3],
                ]);
                cursor += 4;
            }
            1 => {
                if cursor + 8 > payload.len() {
                    return Err(Error::invalid(
                        "MP4: leva truncated grouping_type/parameter for assignment_type=1",
                    ));
                }
                grouping_type = u32::from_be_bytes([
                    payload[cursor],
                    payload[cursor + 1],
                    payload[cursor + 2],
                    payload[cursor + 3],
                ]);
                grouping_type_parameter = u32::from_be_bytes([
                    payload[cursor + 4],
                    payload[cursor + 5],
                    payload[cursor + 6],
                    payload[cursor + 7],
                ]);
                cursor += 8;
            }
            2 | 3 => {
                // ยง8.8.13.2 explicitly defines no further syntax
                // elements for assignment_type 2 (level assignment by
                // track) and 3 (by track-subsegment). The five-byte
                // header is the whole entry.
            }
            4 => {
                if cursor + 4 > payload.len() {
                    return Err(Error::invalid(
                        "MP4: leva truncated sub_track_id for assignment_type=4",
                    ));
                }
                sub_track_id = u32::from_be_bytes([
                    payload[cursor],
                    payload[cursor + 1],
                    payload[cursor + 2],
                    payload[cursor + 3],
                ]);
                cursor += 4;
            }
            _ => {
                // ยง8.8.13.3 โ€” values > 4 are reserved. The spec doesn't
                // define a tail length so we can't safely consume any
                // extra bytes; the entry stands as the 5-byte header.
                // A downstream validator can flag the reserved type.
            }
        }
        entries.push(LevaEntry {
            track_id,
            padding_flag,
            assignment_type,
            grouping_type,
            grouping_type_parameter,
            sub_track_id,
        });
    }
    Ok(LevaRecord { entries })
}

fn parse_prft(body: &[u8]) -> Result<Option<PrftRecord>> {
    if body.len() < 16 {
        return Err(Error::invalid("MP4: prft too short"));
    }
    let version = body[0];
    // 24-bit flags: 0 in the 2015 edition, named annotation bits in the
    // 2022 edition (the body layout is identical either way). Captured so
    // a 2022-aware consumer can interpret what the NTP time represents.
    let flags = u32::from_be_bytes([0, body[1], body[2], body[3]]);
    let reference_track_id = u32::from_be_bytes([body[4], body[5], body[6], body[7]]);
    let ntp_timestamp = u64::from_be_bytes([
        body[8], body[9], body[10], body[11], body[12], body[13], body[14], body[15],
    ]);
    let media_time: u64 = if version == 0 {
        if body.len() < 20 {
            return Err(Error::invalid("MP4: prft v0 truncated"));
        }
        u32::from_be_bytes([body[16], body[17], body[18], body[19]]) as u64
    } else {
        // Per ยง8.16.5.2, version 1 widens media_time to 64-bit. Any
        // version != 0 we treat as v1 (no other version is defined).
        if body.len() < 24 {
            return Err(Error::invalid("MP4: prft v1 truncated"));
        }
        u64::from_be_bytes([
            body[16], body[17], body[18], body[19], body[20], body[21], body[22], body[23],
        ])
    };
    Ok(Some(PrftRecord {
        reference_track_id,
        ntp_timestamp,
        media_time,
        version,
        flags,
    }))
}

/// ยง8.8.10 โ€” `mfra` MovieFragmentRandomAccessBox. Container for one
/// `tfra` per track-with-random-access plus the size-of-mfra `mfro`
/// trailer. We collect the tfra entries; mfro is not consumed (we
/// already know the mfra size from the box header).
fn parse_mfra(body: &[u8], out: &mut Vec<TfraRecord>, mfro_size: &mut Option<u32>) -> Result<()> {
    let mut cur = std::io::Cursor::new(body);
    let end = body.len() as u64;
    while cur.position() < end {
        let hdr = match read_box_header(&mut cur)? {
            Some(h) => h,
            None => break,
        };
        let psz = hdr.payload_size().unwrap_or(0) as usize;
        match hdr.fourcc {
            TFRA => {
                let b = read_bytes_vec(&mut cur, psz)?;
                if let Some(r) = parse_tfra(&b)? {
                    out.push(r);
                }
            }
            MFRO => {
                // ยง8.8.12 โ€” mfro: FullBox (4 bytes) + `size` (u32),
                // the size of the enclosing `mfra` box. Redundant for
                // this parse (the mfra header already told us), but a
                // player locating the mfra from the last 16 bytes of
                // the file depends on it being right โ€” capture the
                // declared value so it can be surfaced and checked.
                let b = read_bytes_vec(&mut cur, psz)?;
                if b.len() >= 8 && mfro_size.is_none() {
                    *mfro_size = Some(u32::from_be_bytes([b[4], b[5], b[6], b[7]]));
                }
            }
            _ => skip_cursor_bytes(&mut cur, psz),
        }
    }
    Ok(())
}

/// ยง8.8.11 โ€” `tfra` TrackFragmentRandomAccessBox.
///
/// Layout (FullBox 4 bytes consumed by caller):
///   track_ID (u32),
///   reserved (28-bit zero) + length_size_of_traf_num (2 bits) +
///     length_size_of_trun_num (2 bits) + length_size_of_sample_num (2 bits)
///   number_of_entry (u32)
///   for each entry:
///     time         โ€” u32 (v0) or u64 (v1)
///     moof_offset  โ€” u32 (v0) or u64 (v1)
///     traf_number  โ€” variable (1..=4 bytes)
///     trun_number  โ€” variable (1..=4 bytes)
///     sample_number โ€” variable (1..=4 bytes)
fn parse_tfra(body: &[u8]) -> Result<Option<TfraRecord>> {
    if body.len() < 12 {
        return Err(Error::invalid("MP4: tfra too short"));
    }
    let version = body[0];
    let mut off = 4usize;
    let track_id = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
    off += 4;
    let lengths = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]);
    off += 4;
    // Per spec: each `length_size_of_*` is 2 bits encoding (0..=3),
    // and the actual byte length is value+1.
    let len_traf = (((lengths >> 4) & 0x3) as usize) + 1;
    let len_trun = (((lengths >> 2) & 0x3) as usize) + 1;
    let len_sample = ((lengths & 0x3) as usize) + 1;
    if off + 4 > body.len() {
        return Err(Error::invalid("MP4: tfra entry_count truncated"));
    }
    let n = u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as usize;
    off += 4;
    let entry_size = if version == 1 { 16 } else { 8 } + len_traf + len_trun + len_sample;
    if off + n.saturating_mul(entry_size) > body.len() {
        return Err(Error::invalid("MP4: tfra entries truncated"));
    }
    // Reserve only after the count is validated against the body โ€”
    // a forged 32-bit entry_count must not drive the allocation.
    let mut entries = Vec::with_capacity(n);
    for _ in 0..n {
        let (time, moof_offset) = if version == 1 {
            let t = u64::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
                body[off + 4],
                body[off + 5],
                body[off + 6],
                body[off + 7],
            ]);
            off += 8;
            let m = u64::from_be_bytes([
                body[off],
                body[off + 1],
                body[off + 2],
                body[off + 3],
                body[off + 4],
                body[off + 5],
                body[off + 6],
                body[off + 7],
            ]);
            off += 8;
            (t, m)
        } else {
            let t =
                u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64;
            off += 4;
            let m =
                u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]) as u64;
            off += 4;
            (t, m)
        };
        let traf_number = read_var_u32(&body[off..off + len_traf]);
        off += len_traf;
        let trun_number = read_var_u32(&body[off..off + len_trun]);
        off += len_trun;
        let sample_number = read_var_u32(&body[off..off + len_sample]);
        off += len_sample;
        entries.push(TfraEntry {
            time,
            moof_offset,
            traf_number,
            trun_number,
            sample_number,
        });
    }
    Ok(Some(TfraRecord { track_id, entries }))
}

/// Read a 1..=4 byte big-endian unsigned integer into a u32.
fn read_var_u32(buf: &[u8]) -> u32 {
    let mut v: u32 = 0;
    for &b in buf {
        v = (v << 8) | b as u32;
    }
    v
}

// --- Sample-table expansion ----------------------------------------------

#[derive(Clone, Copy, Debug)]
struct SampleRef {
    track_idx: u32,
    offset: u64,
    size: u32,
    /// Composition-time stamp (CTS), media timescale. Equals DTS for
    /// streams without a `ctts` box (e.g. audio, intra-only video);
    /// otherwise CTS = DTS + ctts_offset, see ISO/IEC 14496-12 ยง8.6.1.3.
    pts: i64,
    /// Decoding-time stamp, media timescale. Carried separately so the
    /// packet can advertise both โ€” the codec consumes the buffer in
    /// decode order (`dts`) and the player paces presentation by `pts`.
    dts: i64,
    duration: i64,
    keyframe: bool,
    /// True when the ยง8.6.6 edit list never presents this sample's
    /// composition time (decode pre-roll before the first edit
    /// segment, or media excised between segments). Surfaced as the
    /// packet `discard` flag: the sample must still be decoded (it may
    /// be a reference frame / priming input) but its output is not
    /// shown.
    discard: bool,
    /// 1-based `sample_description_index` naming the `stsd` entry this
    /// sample decodes against โ€” from the covering `stsc` entry
    /// (ยง8.7.4) for moov-resident samples, or `tfhd` / `trex`
    /// (ยง8.8.7) for fragment samples. Decode always uses entry [0];
    /// this is surfaced so callers can detect a mid-stream switch.
    sdi: u32,
}

fn expand_samples(t: &Track, track_idx: u32, out: &mut Vec<SampleRef>) -> Result<()> {
    if t.stsz.is_empty() {
        return Ok(());
    }
    let n_samples = t.stsz.len();

    // Build per-sample DTS by scanning stts (cumulative).
    // ISO/IEC 14496-12 ยง8.6.1.2 โ€” stts maps decoding-order index to
    // a per-sample delta in the media timescale, so the running sum
    // is the sample's DTS.
    let mut pts = Vec::with_capacity(n_samples);
    {
        let mut i = 0;
        let mut t_accum: i64 = 0;
        for &(count, delta) in &t.stts {
            for _ in 0..count {
                if i >= n_samples {
                    break;
                }
                pts.push((t_accum, delta as i64));
                t_accum += delta as i64;
                i += 1;
            }
        }
        while pts.len() < n_samples {
            pts.push((t_accum, 0));
        }
    }

    // Apply ctts (ยง8.6.1.3) to convert DTS โ†’ CTS. Without this the
    // packets we hand the codec carry DTS as `pts`, and any codec
    // that reorders for display (B-frames in H.264 / H.265 / AV1)
    // emits frames in display order with decode-time pts attached
    // โ€” i.e. monotonic-decreasing pts at every B-frame boundary.
    // The CTS is what downstream pacing wants.
    let mut cts_offsets: Vec<i64> = vec![0; n_samples];
    if !t.ctts.is_empty() {
        let mut i = 0usize;
        for &(count, off) in &t.ctts {
            for _ in 0..count {
                if i >= n_samples {
                    break;
                }
                cts_offsets[i] = off as i64;
                i += 1;
            }
        }
    }

    // Determine which chunk each sample belongs to using stsc.
    // stsc is run-length: each entry says "starting at first_chunk, every
    // chunk has `samples_per_chunk` samples" until the next entry's first_chunk.
    // We need to know, for each sample, (chunk_index, index_within_chunk).
    //
    // Defensive: clamp `samples_per_chunk` to `n_samples` per entry so a
    // malicious file claiming `spc = u32::MAX` doesn't burn CPU spinning
    // an inner `for 0..spc` loop that the `sample_i >= n_samples` break
    // inside it would otherwise terminate only after ~4 billion iterations.
    // With the clamp the inner loop walks at most `n_samples` iterations
    // per stsc entry, matching what any well-formed file already does.
    let mut chunk_of_sample = Vec::with_capacity(n_samples);
    let mut sample_within_chunk = Vec::with_capacity(n_samples);
    // ยง8.7.4: each stsc run also names the 1-based stsd entry its
    // samples decode against; carried per sample so callers can detect
    // a mid-stream sample-description switch.
    let mut sdi_of_sample: Vec<u32> = Vec::with_capacity(n_samples);
    {
        let mut sample_i = 0;
        let mut chunk_i = 1u32;
        let n_samples_u32 = u32::try_from(n_samples).unwrap_or(u32::MAX);
        for entry_i in 0..t.stsc.len() {
            let (fc, spc, sdi) = t.stsc[entry_i];
            let next_fc = t
                .stsc
                .get(entry_i + 1)
                .map(|e| e.0)
                .unwrap_or(t.chunk_offsets.len() as u32 + 1);
            let spc_clamped = spc.min(n_samples_u32);
            // `next_fc - fc` runs of `spc` samples each.
            let mut ch = chunk_i.max(fc);
            while ch < next_fc && sample_i < n_samples {
                for s_in_ch in 0..spc_clamped {
                    if sample_i >= n_samples {
                        break;
                    }
                    chunk_of_sample.push(ch);
                    sample_within_chunk.push(s_in_ch);
                    sdi_of_sample.push(sdi);
                    sample_i += 1;
                }
                ch += 1;
            }
            chunk_i = ch;
        }
        // Fallback: if stsc didn't cover all samples, place the remainder in
        // the last chunk. (Invalid files โ€” but don't crash.)
        while sample_within_chunk.len() < n_samples {
            chunk_of_sample.push(*chunk_of_sample.last().unwrap_or(&1));
            sample_within_chunk.push(0);
            sdi_of_sample.push(*sdi_of_sample.last().unwrap_or(&1));
        }
    }

    // Per-sample keyframe flags. Per ISO/IEC 14496-12, an absent or empty
    // stss means every sample is a sync frame (this is the norm for audio
    // and intra-only video). Otherwise only the 1-based indices listed in
    // stss are sync frames.
    let stss_all_keyframes = t.stss.is_empty();
    let stss_set: std::collections::HashSet<u32> = t.stss.iter().copied().collect();

    // Compute each sample's absolute offset.
    for i in 0..n_samples {
        let chunk = chunk_of_sample[i] as usize;
        if chunk == 0 || chunk > t.chunk_offsets.len() {
            return Err(Error::invalid(format!(
                "MP4: chunk index {chunk} out of range (track {track_idx})"
            )));
        }
        let chunk_off = t.chunk_offsets[chunk - 1];
        // Sum sizes of preceding samples in this chunk.
        let chunk_start_sample = i - sample_within_chunk[i] as usize;
        let mut preceding: u64 = 0;
        for j in chunk_start_sample..i {
            preceding += t.stsz[j] as u64;
        }
        let size = t.stsz[i];
        let (dts_v, dur) = pts[i];
        // CTS = DTS + ctts_offset (ยง8.6.1.3). Streams without a ctts
        // box leave `cts_offsets` zero-filled, so audio + intra-only
        // video continue to take the DTS path unchanged.
        //
        // The edit list (ยง8.6.6) maps the media composition time onto
        // the presentation timeline: each edit segment contributes a
        // constant delta (empty edits and dwells push later segments
        // out), and media the list never presents is delivered with
        // the discard flag set. Tracks without an elst take the
        // identity mapping.
        let media_cts = dts_v.saturating_add(cts_offsets[i]);
        let (elst_delta, presented) = t.elst_timeline.delta_for_cts(media_cts);
        let cts_v = media_cts.saturating_add(elst_delta);
        let dts_v_shifted = dts_v.saturating_add(elst_delta);
        let one_based = (i as u32) + 1;
        let keyframe = stss_all_keyframes || stss_set.contains(&one_based);
        out.push(SampleRef {
            track_idx,
            offset: chunk_off + preceding,
            size,
            pts: cts_v,
            dts: dts_v_shifted,
            duration: dur,
            keyframe,
            discard: !presented,
            sdi: sdi_of_sample[i],
        });
    }
    Ok(())
}

fn build_ctx<'a>(tag: &'a CodecTag, t: &'a Track) -> ProbeContext<'a> {
    let mut ctx = ProbeContext::new(tag);
    if !t.extradata.is_empty() {
        ctx = ctx.header(&t.extradata);
    }
    if let Some(b) = t.sample_size_bits {
        ctx = ctx.bits(b);
    }
    if let Some(c) = t.channels {
        ctx = ctx.channels(c);
    }
    if let Some(sr) = t.sample_rate {
        ctx = ctx.sample_rate(sr);
    }
    if let Some(w) = t.width {
        ctx = ctx.width(w);
    }
    if let Some(h) = t.height {
        ctx = ctx.height(h);
    }
    ctx
}

fn build_stream_info(index: u32, t: &Track, codecs: &dyn CodecResolver) -> StreamInfo {
    // Try the shared CodecResolver registry first โ€” this lets codec crates
    // own their sample-entry FourCCs / OTI mapping. For `mp4a` / `mp4v`
    // entries we prefer the OTI-aware tag (more specific) over the bare
    // FourCC, then fall back to the static `from_sample_entry*` tables.
    let codec_id = {
        // Fill a ProbeContext with the hints we've already parsed so
        // codec probes can disambiguate (e.g. PCM flavours by bit depth).
        let mut resolved: Option<CodecId> = None;
        if let Some(oti) = t.esds_oti {
            let tag = CodecTag::mp4_object_type(oti);
            let ctx = build_ctx(&tag, t);
            resolved = codecs.resolve_tag(&ctx);
        }
        if resolved.is_none() {
            let tag = CodecTag::fourcc(&t.codec_id_fourcc);
            let ctx = build_ctx(&tag, t);
            resolved = codecs.resolve_tag(&ctx);
        }
        resolved.unwrap_or_else(|| match t.esds_oti {
            Some(oti) => from_sample_entry_with_oti(&t.codec_id_fourcc, oti),
            None => from_sample_entry(&t.codec_id_fourcc),
        })
    };
    let mut params = match t.media_type {
        MediaType::Audio => CodecParameters::audio(codec_id),
        MediaType::Video => CodecParameters::video(codec_id),
        MediaType::Subtitle => CodecParameters::subtitle(codec_id),
        _ => {
            let mut p = CodecParameters::audio(codec_id);
            p.media_type = MediaType::Data;
            p
        }
    };
    params.channels = t.channels;
    params.sample_rate = t.sample_rate;
    params.sample_format = match (params.codec_id.as_str(), t.sample_size_bits) {
        ("flac", Some(8)) => Some(SampleFormat::U8),
        ("flac", Some(16)) => Some(SampleFormat::S16),
        ("flac", Some(24)) => Some(SampleFormat::S24),
        ("flac", Some(32)) => Some(SampleFormat::S32),
        ("pcm_s16le", _) => Some(SampleFormat::S16),
        _ => None,
    };
    params.width = t.width;
    params.height = t.height;
    params.extradata = t.extradata.clone();

    // ISO/IEC 14496-12 ยง8.12: when the track's sample entry was wrapped
    // as `enc*`, surface the recovered scheme type so callers can
    // detect (and refuse, or hand off to a CENC layer) protected
    // tracks. The codec id has already been remapped to the original
    // un-transformed FourCC via `sinf/frma` so this is the only place
    // the protection is visible on the public stream surface.
    if let Some(scheme) = t.protection_scheme {
        let scheme_str = std::str::from_utf8(&scheme).unwrap_or("????").to_string();
        params.options.insert("protection_scheme", scheme_str);
    }

    // ISO/IEC 23001-7 ยง8.2: when a CENC TrackEncryptionBox was
    // present inside `sinf/schi`, surface its defaults on
    // `params.options` so a downstream decryption layer can recover
    // them without a second pass. Keys:
    //
    //   cenc_default_kid               16-byte KID, lowercase hex
    //   cenc_default_is_protected      "0" or "1"
    //   cenc_default_iv_size           0 / 8 / 16
    //   cenc_default_crypt_byte_block  v1 only, decimal (omitted on v0)
    //   cenc_default_skip_byte_block   v1 only, decimal (omitted on v0)
    //   cenc_default_constant_iv       lowercase hex, only when
    //                                  isProtected==1 && iv_size==0
    //   cenc_tenc_version              "0" or "1"
    //
    // All keys are absent for unprotected (or non-CENC-protected)
    // tracks. Hex encoding mirrors the `pssh_<n>` SystemID surface.
    if let Some(tenc) = &t.tenc {
        let kid_hex: String = tenc
            .default_kid
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        params.options.insert("cenc_default_kid", kid_hex);
        params.options.insert(
            "cenc_default_is_protected",
            tenc.default_is_protected.to_string(),
        );
        params.options.insert(
            "cenc_default_iv_size",
            tenc.default_per_sample_iv_size.to_string(),
        );
        params
            .options
            .insert("cenc_tenc_version", tenc.version.to_string());
        if tenc.version >= 1 {
            params.options.insert(
                "cenc_default_crypt_byte_block",
                tenc.default_crypt_byte_block.to_string(),
            );
            params.options.insert(
                "cenc_default_skip_byte_block",
                tenc.default_skip_byte_block.to_string(),
            );
        }
        if let Some(civ) = &tenc.default_constant_iv {
            let iv_hex: String = civ.iter().map(|b| format!("{b:02x}")).collect();
            params.options.insert("cenc_default_constant_iv", iv_hex);
        }
    }

    // PIFF legacy `uuid` TrackEncryptionBox (the pre-CENC `tenc`
    // predecessor, carried in `sinf/schi`): surface its track defaults
    // under dedicated `piff_*` keys so a consumer can tell the legacy
    // carriage from a real CENC `tenc` (whose `cenc_*` keys above stay
    // reserved for the 4CC box). Keys:
    //
    //   piff_algorithm_id   decimal (0 = none, 1 = AES-CTR, 2 = AES-CBC)
    //   piff_iv_size        0 / 8 / 16
    //   piff_kid            16-byte KID, lowercase hex
    //
    // The typed record (and its CENC bridges) is reachable via
    // `Mp4Demuxer::piff_tencs`.
    if let Some(piff) = &t.piff_tenc {
        let kid_hex: String = piff.kid.iter().map(|b| format!("{b:02x}")).collect();
        params
            .options
            .insert("piff_algorithm_id", piff.algorithm_id.to_string());
        params
            .options
            .insert("piff_iv_size", piff.iv_size.to_string());
        params.options.insert("piff_kid", kid_hex);
    }

    // ISO/IEC 14496-12 ยง8.4.6: when the track carries an `elng`
    // ExtendedLanguageBox, surface its BCP 47 (RFC 4646) tag on
    // `params.options["language"]` (e.g. `en-US`, `zh-Hant`). This is
    // richer than `mdhd`'s packed 3-character ISO 639-2 code (which
    // can't express region/script/variant subtags) and overrides it
    // per ยง8.4.6.1 when the two disagree.
    if let Some(tag) = &t.elng {
        params.options.insert("language", tag.clone());
    }

    // ISO/IEC 14496-12 ยง8.6.6: surface the declared edit list as
    // `elst_entry_count` + `elst_<n>` (0-based entry index) with value
    // `"dur=<segment_duration> media_time=<media_time> rate=<int>"`
    // (`segment_duration` in the movie timescale, `media_time` in the
    // media timescale, `-1` = empty edit; `rate` is the
    // ยง8.6.6.3 media_rate_integer โ€” 1 normal, 0 dwell). The demuxer
    // has already applied the mapping to packet timestamps; these keys
    // expose the declaration for remuxers / validators. The typed form
    // is `Mp4Demuxer::edit_list`. Absent `elst`, no keys are emitted.
    if !t.elst.is_empty() {
        params
            .options
            .insert("elst_entry_count", t.elst.len().to_string());
        for (i, e) in t.elst.iter().enumerate() {
            let p = elst_entry_to_public(e);
            params.options.insert(
                format!("elst_{}", i),
                format!(
                    "dur={} media_time={} rate={}",
                    p.segment_duration, p.media_time, p.media_rate_integer
                ),
            );
        }
    }

    // ISO/IEC 14496-12 ยง8.3.3: surface track references as
    // `tref_<type>` โ†’ space-separated track IDs. Callers use this to
    // wire up subtitleโ†’video (`subt`), chapter (`chap`), content
    // description (`cdsc`), font (`font`), hint (`hint`), depth/parallax
    // auxiliary video (`vdep` / `vplx`), and dependency (`hind`)
    // relationships. Reference types whose FourCC contains non-printable
    // bytes are still surfaced (the key is utf8-lossy so they don't
    // panic), but downstream callers should treat unknown types as
    // opaque.
    for (ref_type, ids) in &t.tref {
        if ids.is_empty() {
            continue;
        }
        let type_str = std::str::from_utf8(ref_type)
            .map(|s| s.to_string())
            .unwrap_or_else(|_| {
                format!(
                    "{:02x}{:02x}{:02x}{:02x}",
                    ref_type[0], ref_type[1], ref_type[2], ref_type[3]
                )
            });
        let value = ids
            .iter()
            .map(|id| id.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        params.options.insert(format!("tref_{}", type_str), value);
    }

    // ISO/IEC 14496-12 ยง8.3.4: surface each `trgr` (TrackGroupBox)
    // child as `trgr_<n>` where `<n>` is the 0-based encounter index.
    // Value is `"<track_group_type> <track_group_id>"` โ€” the FourCC
    // type and the 32-bit identifier, space-separated, mirroring the
    // `kind_<n>` two-field shape. Tracks sharing the same
    // `(type, id)` pair belong to the same group (ยง8.3.4.3); this is
    // a track-group membership signal, not a dependency relationship
    // (use `tref_<type>` for the latter). Reference types whose
    // FourCC contains non-printable bytes fall back to an 8-digit hex
    // representation, matching the `tref_<type>` convention.
    for (i, (group_type, group_id)) in t.trgr.iter().enumerate() {
        let type_str = std::str::from_utf8(group_type)
            .map(|s| s.to_string())
            .unwrap_or_else(|_| {
                format!(
                    "{:02x}{:02x}{:02x}{:02x}",
                    group_type[0], group_type[1], group_type[2], group_type[3]
                )
            });
        params
            .options
            .insert(format!("trgr_{}", i), format!("{} {}", type_str, group_id));
    }

    // ISO/IEC 14496-12 ยง8.10.4: surface each track-level `kind`
    // (KindBox) on `params.options` as `kind_<n>` where `<n>` is the
    // 0-based encounter index. Value is the URI alone when the box
    // carried no name (URI uniquely identifies the kind), or
    // "URI value" (space-separated, mirroring the `tref_<type>`
    // surface convention) when both fields are populated. Multiple
    // schemes (e.g. one DASH role + one iTunes role) co-label the
    // same track with distinct keys.
    for (i, (uri, value)) in t.kinds.iter().enumerate() {
        let v = if value.is_empty() {
            uri.clone()
        } else {
            format!("{} {}", uri, value)
        };
        params.options.insert(format!("kind_{}", i), v);
    }

    // ISO/IEC 14496-12 ยง8.10.2: surface each track-level `cprt`
    // (CopyrightBox) on `params.options` as a pair: `copyright_<n>`
    // carries the decoded notice string and `copyright_<n>_lang` carries
    // the 3-letter ISO 639-2/T language code. The key is omitted when
    // the notice is empty, mirroring the `kind_<n>` posture that a
    // value-less informational box does not pollute the option map; the
    // accompanying `_lang` key is still emitted for a present-but-empty
    // notice when the language tag itself is well-formed ASCII letters,
    // so a consumer can tell "track declares an empty notice in `eng`"
    // from "track has no `cprt` at all". When the decoded language
    // bytes are outside the spec's `'a'..='z'` range (a malformed or
    // zero-packed source word) the `_lang` key falls back to 8-digit
    // hex of the raw 16-bit packed value, matching the `tref_<type>` /
    // `trgr_<n>` non-printable fallback convention.
    for (i, c) in t.copyrights.iter().enumerate() {
        let lang_str = if c.language.iter().all(|&b| b.is_ascii_lowercase()) {
            std::str::from_utf8(&c.language).unwrap().to_string()
        } else {
            // Reverse the packed-language decode to recover the original
            // 16-bit word for a stable surface even when the bytes are
            // out of the spec's lowercase-letter range.
            let raw: u32 = ((c.language[0].wrapping_sub(0x60) as u32) << 10)
                | ((c.language[1].wrapping_sub(0x60) as u32) << 5)
                | (c.language[2].wrapping_sub(0x60) as u32);
            format!("{:08x}", raw)
        };
        if !c.notice.is_empty() {
            params
                .options
                .insert(format!("copyright_{}", i), c.notice.clone());
        }
        params
            .options
            .insert(format!("copyright_{}_lang", i), lang_str);
    }

    // ISO/IEC 14496-12 ยง8.10.3: surface the optional `tsel`
    // (TrackSelectionBox) โ€” when present, emit two `params.options`
    // keys. `tsel_switch_group` is the signed 32-bit identifier
    // grouping interchangeable-during-playback tracks (ยง8.10.3.4); a
    // value of 0 still surfaces because it lets a consumer tell a
    // present-but-zero `tsel` from an absent one. `tsel_attributes`
    // is the space-separated list of FourCC tags from
    // `attribute_list[]` (ยง8.10.3.5: descriptive `tesc` / `fgsc` /
    // `cgsc` / `spsc` / `resc` / `vwsc` and differentiating `bitr` /
    // `cdec` / `lang` / โ€ฆ); the key is omitted when the list is
    // empty. FourCCs whose bytes contain non-printable values fall
    // back to 8-digit hex (matching the `tref_<type>` / `trgr_<n>`
    // convention). Absent `tsel`, neither key is emitted.
    if let Some(tsel) = &t.tsel {
        params
            .options
            .insert("tsel_switch_group", tsel.switch_group.to_string());
        if !tsel.attribute_list.is_empty() {
            let v = tsel
                .attribute_list
                .iter()
                .map(|a| {
                    std::str::from_utf8(a)
                        .ok()
                        .filter(|s| s.chars().all(|c| !c.is_control()))
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| {
                            format!("{:02x}{:02x}{:02x}{:02x}", a[0], a[1], a[2], a[3])
                        })
                })
                .collect::<Vec<_>>()
                .join(" ");
            params.options.insert("tsel_attributes", v);
        }
    }

    // ISO/IEC 14496-12 ยง8.14: surface each Sub Track (`strk`) the track
    // declared. A sub track assigns *part* of a track to alternate /
    // switch groups for layered-codec media selection (ยง8.14.1). Each is
    // emitted on `params.options` as `subtrack_<n>` (0-based encounter
    // index) carrying the `stri` (ยง8.14.4) selection fields:
    //   `"id=<sub_track_ID> switch=<switch_group> alt=<alternate_group>
    //     [attrs=<fourcc...>] [stsg=<grouping_type>:<idx>,<idx>;...]"`
    // The `switch` / `alt` fields are always emitted (0 is meaningful โ€”
    // it distinguishes present-but-unassigned from a missing field); the
    // `attrs=` block lists the ยง8.14.4.3 attribute FourCCs (descriptive
    // `tesc`/`fgsc`/โ€ฆ and differentiating `bitr`/`frar`/`nvws`/โ€ฆ) and is
    // omitted when empty; the `stsg=` block lists each `strd/stsg`
    // (ยง8.14.6) sub-track sample-group definition as
    // `<grouping_type>:<index>,<index>,โ€ฆ` and is omitted when the sub
    // track declared none. FourCCs whose bytes are non-printable fall
    // back to 8-digit hex (matching the `tsel_attributes` convention).
    // Absent `strk`, no keys are emitted.
    for (n, st) in t.sub_tracks.iter().enumerate() {
        use std::fmt::Write;
        let mut s = format!(
            "id={} switch={} alt={}",
            st.sub_track_id, st.switch_group, st.alternate_group
        );
        if !st.attribute_list.is_empty() {
            let attrs = st
                .attribute_list
                .iter()
                .map(fourcc_token)
                .collect::<Vec<_>>()
                .join(" ");
            let _ = write!(s, " attrs={attrs}");
        }
        if !st.sample_groups.is_empty() {
            let groups = st
                .sample_groups
                .iter()
                .map(|sg| {
                    let idxs = sg
                        .group_description_indices
                        .iter()
                        .map(|i| i.to_string())
                        .collect::<Vec<_>>()
                        .join(",");
                    format!("{}:{}", fourcc_token(&sg.grouping_type), idxs)
                })
                .collect::<Vec<_>>()
                .join(";");
            let _ = write!(s, " stsg={groups}");
        }
        params.options.insert(format!("subtrack_{n}"), s);
    }

    // ISO/IEC 14496-12 ยง8.6.1.4: when the track carries a `cslg`
    // (CompositionToDecodeBox), surface its five timeline-relation
    // fields on `params.options` as `cslg_<field>`. These document the
    // compositionโ†”decode relationship implied by a signed (v1) `ctts`:
    // the DTS shift that guarantees CTS โ‰ฅ DTS, the least/greatest
    // composition offsets, and the composition start/end times. Callers
    // building an accurate presentation timeline (e.g. to size an output
    // edit or clamp the leading gap) can read these instead of scanning
    // the whole `ctts`. All values are in the track media timescale.
    if let Some(c) = &t.cslg {
        params.options.insert(
            "cslg_composition_to_dts_shift",
            c.composition_to_dts_shift.to_string(),
        );
        params.options.insert(
            "cslg_least_decode_to_display_delta",
            c.least_decode_to_display_delta.to_string(),
        );
        params.options.insert(
            "cslg_greatest_decode_to_display_delta",
            c.greatest_decode_to_display_delta.to_string(),
        );
        params.options.insert(
            "cslg_composition_start_time",
            c.composition_start_time.to_string(),
        );
        params.options.insert(
            "cslg_composition_end_time",
            c.composition_end_time.to_string(),
        );
    }

    // ISO/IEC 14496-12 ยง12.1.2 / ยง8.4.5: when the track carries a
    // `vmhd` (VideoMediaHeaderBox) โ€” i.e. a video track โ€” surface its
    // composition mode and operation colour on `params.options`.
    // `vmhd_graphicsmode` is the decimal composition mode (0 = copy);
    // `vmhd_opcolor` is the three (red, green, blue) 16-bit components
    // space-separated, decimal. Callers that compose this track over an
    // existing image read these instead of re-walking `minf`.
    if let Some(v) = &t.vmhd {
        params
            .options
            .insert("vmhd_graphicsmode", v.graphicsmode.to_string());
        params.options.insert(
            "vmhd_opcolor",
            format!("{} {} {}", v.opcolor[0], v.opcolor[1], v.opcolor[2]),
        );
    }

    // QuickTime Base Media Info Atom (`minf/gmhd/gmin`): when the track
    // carries a `gmhd` in place of a typed media header (a base-media
    // track โ€” text / timecode / music / generic), surface its control
    // information on `params.options`. `gmin_graphicsmode` is the decimal
    // composition mode (0 = copy); `gmin_opcolor` is the three
    // (red, green, blue) 16-bit components space-separated, decimal; and
    // `gmin_balance` is the signed stereo sound balance. Absent `gmhd`,
    // none of the keys are emitted.
    if let Some(g) = &t.gmin {
        params
            .options
            .insert("gmin_graphicsmode", g.graphicsmode.to_string());
        params.options.insert(
            "gmin_opcolor",
            format!("{} {} {}", g.opcolor[0], g.opcolor[1], g.opcolor[2]),
        );
        params.options.insert("gmin_balance", g.balance.to_string());
    }

    // QuickTime Timecode Media Info Atom (`minf/gmhd/tcmi`): when a
    // timecode track (media type `tmcd`) carries a `tcmi`, surface its
    // text-rendering parameters on `params.options`. `tcmi_text_font` /
    // `tcmi_text_face` / `tcmi_text_size` are decimal; `tcmi_text_color`
    // and `tcmi_background_color` are the three space-separated 16-bit RGB
    // components; and `tcmi_font_name` is the font name (omitted when
    // empty). Absent `tcmi`, none of the keys are emitted.
    if let Some(tc) = &t.tcmi {
        params
            .options
            .insert("tcmi_text_font", tc.text_font.to_string());
        params
            .options
            .insert("tcmi_text_face", tc.text_face.to_string());
        params
            .options
            .insert("tcmi_text_size", tc.text_size.to_string());
        params.options.insert(
            "tcmi_text_color",
            format!(
                "{} {} {}",
                tc.text_color[0], tc.text_color[1], tc.text_color[2]
            ),
        );
        params.options.insert(
            "tcmi_background_color",
            format!(
                "{} {} {}",
                tc.background_color[0], tc.background_color[1], tc.background_color[2]
            ),
        );
        if !tc.font_name.is_empty() {
            params
                .options
                .insert("tcmi_font_name", tc.font_name.clone());
        }
    }

    // QuickTime Timecode sample description (`stsd` `tmcd` entry): when the
    // track is a timecode track, surface the fields that define how its
    // timecode samples are read. `tmcd_flags` is the decimal flag word;
    // `tmcd_drop_frame` / `tmcd_24hour_max` / `tmcd_negative_ok` /
    // `tmcd_counter` are the decoded booleans; `tmcd_timescale`,
    // `tmcd_frame_duration`, and `tmcd_number_of_frames` are decimal.
    // Absent a `tmcd` entry, none of the keys are emitted.
    if let Some(tm) = &t.tmcd {
        params.options.insert("tmcd_flags", tm.flags.to_string());
        params
            .options
            .insert("tmcd_drop_frame", tm.drop_frame().to_string());
        params
            .options
            .insert("tmcd_24hour_max", tm.twenty_four_hour_max().to_string());
        params
            .options
            .insert("tmcd_negative_ok", tm.negative_times_ok().to_string());
        params
            .options
            .insert("tmcd_counter", tm.counter().to_string());
        params
            .options
            .insert("tmcd_timescale", tm.timescale.to_string());
        params
            .options
            .insert("tmcd_frame_duration", tm.frame_duration.to_string());
        params
            .options
            .insert("tmcd_number_of_frames", tm.number_of_frames.to_string());
    }

    // QuickTime Text sample description (`stsd` `text` entry): when a
    // QuickTime text track carries a structured `text` entry, surface its
    // draw parameters on `params.options`. `text_display_flags` is the
    // decimal flag word; `text_justification` is the signed alignment
    // (0 left / 1 centered / -1 right); `text_background_color` and
    // `text_foreground_color` are the three space-separated 16-bit RGB
    // components; `text_default_text_box` is top/left/bottom/right
    // space-separated; `text_font_number` / `text_font_face` are decimal;
    // and `text_font_name` is the font name (omitted when empty). Absent a
    // structured `text` entry, none of the keys are emitted.
    if let Some(tx) = &t.text_entry {
        params
            .options
            .insert("text_display_flags", tx.display_flags.to_string());
        params
            .options
            .insert("text_justification", tx.text_justification.to_string());
        params.options.insert(
            "text_background_color",
            format!(
                "{} {} {}",
                tx.background_color[0], tx.background_color[1], tx.background_color[2]
            ),
        );
        params.options.insert(
            "text_foreground_color",
            format!(
                "{} {} {}",
                tx.foreground_color[0], tx.foreground_color[1], tx.foreground_color[2]
            ),
        );
        params.options.insert(
            "text_default_text_box",
            format!(
                "{} {} {} {}",
                tx.default_text_box[0],
                tx.default_text_box[1],
                tx.default_text_box[2],
                tx.default_text_box[3]
            ),
        );
        params
            .options
            .insert("text_font_number", tx.font_number.to_string());
        params
            .options
            .insert("text_font_face", tx.font_face.to_string());
        if !tx.text_name.is_empty() {
            params
                .options
                .insert("text_font_name", tx.text_name.clone());
        }
    }

    // QuickTime Track Load Settings Atom (`trak/load`): when the track
    // carries a `load`, surface its preload / hint fields on
    // `params.options`. `load_preload_start_time` / `load_preload_duration`
    // / `load_preload_flags` / `load_default_hints` are decimal; the
    // decoded booleans `load_preload_always` / `load_preload_if_enabled` /
    // `load_double_buffer` / `load_high_quality` expose the flag / hint
    // bits. Absent `load`, none of the keys are emitted.
    if let Some(ls) = &t.load_settings {
        params
            .options
            .insert("load_preload_start_time", ls.preload_start_time.to_string());
        params
            .options
            .insert("load_preload_duration", ls.preload_duration.to_string());
        params
            .options
            .insert("load_preload_flags", ls.preload_flags.to_string());
        params
            .options
            .insert("load_default_hints", ls.default_hints.to_string());
        params
            .options
            .insert("load_preload_always", ls.preload_always().to_string());
        params.options.insert(
            "load_preload_if_enabled",
            ls.preload_if_enabled().to_string(),
        );
        params
            .options
            .insert("load_double_buffer", ls.double_buffer().to_string());
        params
            .options
            .insert("load_high_quality", ls.high_quality().to_string());
    }

    // ISO/IEC 14496-12 (post-2015): when the track's `VisualSampleEntry`
    // carried an `amve` (AmbientViewingEnvironmentBox), surface its three
    // raw fields on `params.options` as `amve_ambient_illuminance`
    // (0.0001 lux per unit), `amve_ambient_light_x`, and
    // `amve_ambient_light_y` (0.00002 CIE 1931 chromaticity per unit),
    // all decimal. The raw integers are preserved verbatim โ€” a downstream
    // HDR pipeline applies the unit scaling and can populate the matching
    // `ambient_viewing_environment` SEI field-for-field with no
    // conversion. Absent `amve`, none of the keys are emitted.
    if let Some(a) = &t.amve {
        params.options.insert(
            "amve_ambient_illuminance",
            a.ambient_illuminance.to_string(),
        );
        params
            .options
            .insert("amve_ambient_light_x", a.ambient_light_x.to_string());
        params
            .options
            .insert("amve_ambient_light_y", a.ambient_light_y.to_string());
    }

    // ISO/IEC 14496-12 ยง8.15.4.2: when the track's sample-entry
    // `sinf/schi` carried an `stvi` (StereoVideoBox) โ€” i.e. the
    // restricted-scheme SchemeType is `stvi` (stereoscopic video,
    // ยง8.15.4.1) โ€” surface its three fields on `params.options`:
    // `stvi_single_view_allowed` (the 2-bit monoscopic-display
    // permission), `stvi_stereo_scheme` (1 = 14496-10 frame-packing
    // SEI, 2 = 13818-2 Annex L, 3 = 23000-11), both decimal, and
    // `stvi_indication` (the raw `stereo_indication_type` bytes as
    // lowercase hex โ€” its meaning is `stereo_scheme`-specific, so it is
    // preserved verbatim for a downstream consumer). The
    // `stvi_indication` key is omitted when the indication is empty
    // (`length == 0`). Absent `stvi`, none of the keys are emitted.
    if let Some(s) = &t.stvi {
        params.options.insert(
            "stvi_single_view_allowed",
            s.single_view_allowed.to_string(),
        );
        params
            .options
            .insert("stvi_stereo_scheme", s.stereo_scheme.to_string());
        if !s.stereo_indication_type.is_empty() {
            let mut hex = String::with_capacity(s.stereo_indication_type.len() * 2);
            for b in &s.stereo_indication_type {
                use std::fmt::Write as _;
                let _ = write!(hex, "{b:02x}");
            }
            params.options.insert("stvi_indication", hex);
        }
    }

    // ISO/IEC 14496-12 ยง8.5.2: when the track's active `SampleEntry`
    // carried a `btrt` (BitRateBox), surface its three bandwidth fields
    // on `params.options` as `btrt_buffer_size_db` (decoding buffer size
    // in bytes), `btrt_max_bitrate`, and `btrt_avg_bitrate` (bits/second,
    // over any one-second window / the whole presentation), all decimal.
    // An ABR packager or buffer-sizing player reads these directly
    // without parsing an `esds` (the box is codec-agnostic and present on
    // sample entries that carry no MPEG-4 descriptor). Absent `btrt`,
    // none of the keys are emitted.
    if let Some(b) = &t.btrt {
        params
            .options
            .insert("btrt_buffer_size_db", b.buffer_size_db.to_string());
        params
            .options
            .insert("btrt_max_bitrate", b.max_bitrate.to_string());
        params
            .options
            .insert("btrt_avg_bitrate", b.avg_bitrate.to_string());
    }

    // ISO/IEC 14496-12 ยง12.1.4 โ€” `pasp` (PixelAspectRatioBox): surface
    // the pixel aspect ratio on `params.options` as `pasp_h_spacing` /
    // `pasp_v_spacing` (decimal). A renderer multiplies the stored
    // sample dimensions by this ratio to obtain the display aspect.
    // Absent `pasp`, square pixels are implied and no keys are emitted.
    if let Some(p) = &t.pasp {
        params
            .options
            .insert("pasp_h_spacing", p.h_spacing.to_string());
        params
            .options
            .insert("pasp_v_spacing", p.v_spacing.to_string());
    }

    // ISO/IEC 14496-12 ยง12.1.4 โ€” `clap` (CleanApertureBox): surface the
    // clean-aperture rectangle as four `N/D` fractions on
    // `params.options` (`clap_width` / `clap_height` / `clap_horiz_off`
    // / `clap_vert_off`, each "<N>/<D>"). The active picture region after
    // overscan / edge artefacts are cropped. Absent `clap`, no keys.
    if let Some(c) = &t.clap {
        params
            .options
            .insert("clap_width", format!("{}/{}", c.width_n, c.width_d));
        params
            .options
            .insert("clap_height", format!("{}/{}", c.height_n, c.height_d));
        params.options.insert(
            "clap_horiz_off",
            format!("{}/{}", c.horiz_off_n, c.horiz_off_d),
        );
        params.options.insert(
            "clap_vert_off",
            format!("{}/{}", c.vert_off_n, c.vert_off_d),
        );
    }

    // ISO/IEC 14496-12 ยง12.1.5 โ€” `colr` (ColourInformationBox): surface
    // the colour description on `params.options`. For an `nclx` box the
    // three 16-bit ISO/IEC 23091-2 codes + the range flag are emitted as
    // `colr_type=nclx`, `colr_primaries`, `colr_transfer`, `colr_matrix`
    // (decimal), and `colr_full_range` ("0"/"1"). For an ICC profile
    // (`rICC` / `prof`) only `colr_type` + `colr_icc_len` (profile byte
    // length) are emitted (the raw profile is reachable via the typed
    // record). An unknown colour type emits `colr_type=<fourcc>`.
    if let Some(c) = &t.colr {
        match c {
            ColrRecord::Nclx {
                colour_primaries,
                transfer_characteristics,
                matrix_coefficients,
                full_range,
            } => {
                params.options.insert("colr_type", "nclx".to_string());
                params
                    .options
                    .insert("colr_primaries", colour_primaries.to_string());
                params
                    .options
                    .insert("colr_transfer", transfer_characteristics.to_string());
                params
                    .options
                    .insert("colr_matrix", matrix_coefficients.to_string());
                params
                    .options
                    .insert("colr_full_range", (*full_range as u8).to_string());
            }
            ColrRecord::RestrictedIcc(d) => {
                params.options.insert("colr_type", "rICC".to_string());
                params.options.insert("colr_icc_len", d.len().to_string());
            }
            ColrRecord::UnrestrictedIcc(d) => {
                params.options.insert("colr_type", "prof".to_string());
                params.options.insert("colr_icc_len", d.len().to_string());
            }
            ColrRecord::Other { colour_type, .. } => {
                params.options.insert(
                    "colr_type",
                    String::from_utf8_lossy(colour_type).to_string(),
                );
            }
        }
    }

    // ISO/IEC 14496-12 ยง12.4.2 / ยง8.4.5: when the track carries an
    // `hmhd` (HintMediaHeaderBox) โ€” i.e. a hint track โ€” surface its
    // protocol-independent streaming statistics on `params.options`:
    // `hmhd_max_pdu_size` / `hmhd_avg_pdu_size` (byte sizes of the
    // largest / average Protocol Data Unit) and `hmhd_max_bitrate` /
    // `hmhd_avg_bitrate` (bits/second over any one-second window / the
    // whole presentation), all decimal. A streaming server pacing
    // delivery or sizing buffers reads these instead of re-walking
    // `minf`. Absent `hmhd`, none of the keys are emitted.
    if let Some(h) = &t.hmhd {
        params
            .options
            .insert("hmhd_max_pdu_size", h.max_pdu_size.to_string());
        params
            .options
            .insert("hmhd_avg_pdu_size", h.avg_pdu_size.to_string());
        params
            .options
            .insert("hmhd_max_bitrate", h.max_bitrate.to_string());
        params
            .options
            .insert("hmhd_avg_bitrate", h.avg_bitrate.to_string());
    }

    // ISO/IEC 14496-12 ยง9.1.2 / ยง9.4.1.2: when the track's active stsd
    // entry is an RTP / SRTP / reception hint sample entry (`rtp ` /
    // `srtp` / `rrtp`), surface its packetisation parameters on
    // `params.options`: `rtp_hint_format` (the entry FourCC),
    // `rtp_hint_max_packet_size` (the largest packet this track
    // generates), `rtp_hint_timescale` (the `tims` RTP clock), and the
    // optional `rtp_hint_time_offset` / `rtp_hint_sequence_offset` (`tsro`
    // / `snro`, signed, decimal โ€” omitted when the box is absent). An
    // `srtp` entry also emits `rtp_hint_srtp = "true"`. A streaming server
    // reads these to reconstruct the RTP stream without re-walking `stsd`.
    if let Some(r) = &t.rtp_hint {
        params.options.insert(
            "rtp_hint_format",
            String::from_utf8_lossy(&r.format).to_string(),
        );
        params
            .options
            .insert("rtp_hint_max_packet_size", r.max_packet_size.to_string());
        if let Some(ts) = r.timescale {
            params.options.insert("rtp_hint_timescale", ts.to_string());
        }
        if let Some(off) = r.time_offset {
            params
                .options
                .insert("rtp_hint_time_offset", off.to_string());
        }
        if let Some(off) = r.sequence_offset {
            params
                .options
                .insert("rtp_hint_sequence_offset", off.to_string());
        }
        if r.srpp.is_some() {
            params.options.insert("rtp_hint_srtp", "true".to_string());
        }
    }

    // ISO/IEC 14496-12 ยง9.3.3.2: when the track's active stsd entry is an
    // MPEG-2 TS server / reception hint sample entry (`sm2t` / `rm2t`),
    // surface its per-TS-packet framing on `params.options`:
    // `m2t_hint_format` (the entry FourCC), `m2t_hint_preceding_bytes` /
    // `m2t_hint_trailing_bytes` (recording-device bytes wrapped around
    // each 188-byte TS packet), and `m2t_hint_precomputed` (`"true"` when
    // the precomputed-only flag is set). A de-hinter reads these to strip
    // the wrapping bytes before reassembling the TS.
    if let Some(m) = &t.mpeg2ts_hint {
        params.options.insert(
            "m2t_hint_format",
            String::from_utf8_lossy(&m.format).to_string(),
        );
        params.options.insert(
            "m2t_hint_preceding_bytes",
            m.preceding_bytes_len.to_string(),
        );
        params
            .options
            .insert("m2t_hint_trailing_bytes", m.trailing_bytes_len.to_string());
        if m.precomputed_only {
            params
                .options
                .insert("m2t_hint_precomputed", "true".to_string());
        }
    }

    // ISO/IEC 14496-12 ยง9.1.5: when the hint track's `udta` carried a
    // `hinf` Hint Statistics Box, surface its present statistics on
    // `params.options` (each key emitted only when the corresponding
    // sub-box was present): `hinf_bytes_sent` (`trpy`, incl. RTP
    // headers), `hinf_packets_sent` (`nump`), `hinf_payload_bytes`
    // (`tpyl`, excl. RTP headers), `hinf_media_bytes` (`dmed`),
    // `hinf_immediate_bytes` (`dimm`), `hinf_repeated_bytes` (`drep`),
    // `hinf_largest_packet` (`pmax`), `hinf_maxr_count` (number of `maxr`
    // windows), and `hinf_payload_count` (number of `payt` entries). A
    // streaming server / analytics tool reads delivery totals without
    // walking `udta`. The u32 variants (`totl`/`npck`/`tpay`) prefer the
    // u64 fields when both forms are present.
    {
        let h = &t.hint_stats;
        if let Some(v) = h
            .bytes_sent_with_rtp_64
            .or(h.bytes_sent_with_rtp_32.map(u64::from))
        {
            params.options.insert("hinf_bytes_sent", v.to_string());
        }
        if let Some(v) = h.packets_sent_64.or(h.packets_sent_32.map(u64::from)) {
            params.options.insert("hinf_packets_sent", v.to_string());
        }
        if let Some(v) = h
            .bytes_sent_no_rtp_64
            .or(h.bytes_sent_no_rtp_32.map(u64::from))
        {
            params.options.insert("hinf_payload_bytes", v.to_string());
        }
        if let Some(v) = h.media_bytes_sent {
            params.options.insert("hinf_media_bytes", v.to_string());
        }
        if let Some(v) = h.immediate_bytes_sent {
            params.options.insert("hinf_immediate_bytes", v.to_string());
        }
        if let Some(v) = h.repeated_bytes_sent {
            params.options.insert("hinf_repeated_bytes", v.to_string());
        }
        if let Some(v) = h.largest_packet {
            params.options.insert("hinf_largest_packet", v.to_string());
        }
        if !h.max_rates.is_empty() {
            params
                .options
                .insert("hinf_maxr_count", h.max_rates.len().to_string());
        }
        if !h.payload_ids.is_empty() {
            params
                .options
                .insert("hinf_payload_count", h.payload_ids.len().to_string());
        }
    }

    // ISO/IEC 14496-12 ยง8.7.2: surface the DataReferenceBox (`dref`) so a
    // caller can resolve where each sample description's media data lives.
    // The 1-based `data_reference_index` on every sample entry (ยง8.5.2.2)
    // indexes this table. The overwhelmingly common case โ€” a single
    // self-contained `url ` entry, i.e. all samples in this same file โ€” is
    // surfaced compactly as `dref_self_contained = "true"` with no
    // per-entry keys, so a consumer can confirm "no external resources" in
    // one lookup. When the table has more than one entry, or any entry is
    // *not* self-contained (an external `url `/`urn ` split-source track),
    // every entry is surfaced:
    //   * `dref_count` โ€” total entries.
    //   * `dref_self_contained` โ€” "true" only when *every* entry is
    //     self-contained, else "false".
    //   * `dref_<n>` (1-based, matching `data_reference_index`) โ€”
    //     `<kind> self=<true|false>[ name=<urn>][ loc=<url>]`. `kind` is
    //     `url ` or `urn `; the `name=` token appears only for a `urn `
    //     with a name; `loc=` only when a location string is present.
    // Absent / unparseable `dref`, none of the keys are emitted.
    if let Some(d) = &t.dref {
        let all_self_contained =
            !d.entries.is_empty() && d.entries.iter().all(|e| e.is_self_contained());
        let single_self_contained = d.entries.len() == 1 && all_self_contained;
        params.options.insert(
            "dref_self_contained",
            if all_self_contained { "true" } else { "false" }.to_string(),
        );
        if !single_self_contained {
            params
                .options
                .insert("dref_count".to_string(), d.entries.len().to_string());
            for (i, e) in d.entries.iter().enumerate() {
                let mut s = format!("{} self={}", fourcc_token(&e.kind), e.is_self_contained());
                if let Some(name) = &e.name {
                    s.push_str(" name=");
                    s.push_str(name);
                }
                if let Some(loc) = &e.location {
                    s.push_str(" loc=");
                    s.push_str(loc);
                }
                params.options.insert(format!("dref_{}", i + 1), s);
            }
        }
    }

    // ISO/IEC 14496-12 ยง8.6.3: surface the optional ShadowSyncSampleBox
    // (`stsh`) as `stsh_<n>` options keys (0-based encounter index),
    // each `"shadowed sync"` โ€” the 1-based shadowed sample number and
    // the 1-based sync sample that may replace it when seeking to (or
    // before) that sample. The convention mirrors `tref_<type>` /
    // `kind_<n>`. The table is a seek optimisation only; a track with no
    // `stsh` emits none of the keys.
    for (i, (shadowed, sync)) in t.stsh.iter().enumerate() {
        params
            .options
            .insert(format!("stsh_{}", i), format!("{} {}", shadowed, sync));
    }

    // ISO/IEC 14496-12 ยง8.5.2: surface the full SampleDescriptionBox
    // entry list when a track carries more than one sample description.
    // Entry [0] always drives active decode (its FourCC is the track's
    // `codec` / `codec_id_fourcc`), so for the overwhelmingly common
    // single-entry case there is nothing extra to say and no keys are
    // emitted. When `entry_count > 1` the track can switch descriptions
    // mid-stream via a per-chunk `stsc.sample_description_index` (โ‰ฅ 2) or
    // a fragment's `tfhd` / `trex` `sample_description_index`; the
    // alternatives are surfaced so a caller can map such an index to the
    // FourCC it selects:
    //   * `stsd_count` โ€” the total number of sample-description entries.
    //   * `stsd_<n>` (1-based, matching the spec's 1-based
    //     `sample_description_index`) โ€” `<fourcc> dref=<data_reference_index>`
    //     for every entry. Entry 1 is the active one (also reflected in
    //     `codec`); entries โ‰ฅ 2 are the alternates. The 1-based key index
    //     lets a `sample_description_index` value be looked up directly as
    //     `stsd_<index>`.
    // Absent multiple entries, none of these keys are emitted.
    if t.stsd_entries.len() > 1 {
        params
            .options
            .insert("stsd_count".to_string(), t.stsd_entries.len().to_string());
        for (i, e) in t.stsd_entries.iter().enumerate() {
            params.options.insert(
                format!("stsd_{}", i + 1),
                format!(
                    "{} dref={}",
                    fourcc_token(&e.format),
                    e.data_reference_index
                ),
            );
        }
    }

    // ISO/IEC 14496-12 ยง8.9.2/ยง8.9.3: surface sample groupings. Each
    // `sbgp` (SampleToGroupBox) becomes one `sbgp_<n>` key (0-based
    // encounter index) whose value is the grouping type, an optional
    // `param=<P>` (v1 grouping_type_parameter), then the run-length
    // `count:index` pairs (`group_description_index` 0 = "no group";
    // โ‰ฅ 0x10001 = movie-fragment-local index, kept verbatim). Each
    // `sgpd` (SampleGroupDescriptionBox) becomes one `sgpd_<n>` key
    // whose value is the grouping type, an optional `default=<D>`
    // (v2 default_sample_description_index), then the per-group entry
    // payloads rendered as lowercase hex (grouping-type-specific blobs
    // the container does not interpret). The two share `grouping_type`
    // so a caller can pair an `sbgp_<n>` with the `sgpd_<m>` of the
    // same type. Absent both boxes, none of the keys are emitted.
    let render_grouping_type = |gt: &[u8; 4]| -> String {
        std::str::from_utf8(gt)
            .ok()
            .filter(|s| s.chars().all(|c| !c.is_control()))
            .map(|s| s.to_string())
            .unwrap_or_else(|| format!("{:02x}{:02x}{:02x}{:02x}", gt[0], gt[1], gt[2], gt[3]))
    };
    for (i, sb) in t.sbgp.iter().enumerate() {
        let mut v = render_grouping_type(&sb.grouping_type);
        if let Some(p) = sb.grouping_type_parameter {
            v.push_str(&format!(" param={}", p));
        }
        for (count, idx) in &sb.entries {
            v.push_str(&format!(" {}:{}", count, idx));
        }
        params.options.insert(format!("sbgp_{}", i), v);
    }
    for (i, sg) in t.sgpd.iter().enumerate() {
        let mut v = render_grouping_type(&sg.grouping_type);
        if let Some(d) = sg.default_sample_description_index {
            v.push_str(&format!(" default={}", d));
        }
        for entry in &sg.entries {
            v.push(' ');
            for byte in entry {
                v.push_str(&format!("{:02x}", byte));
            }
        }
        params.options.insert(format!("sgpd_{}", i), v);
    }

    // ISO/IEC 14496-12:2020 ยง8.9.5: surface CompactSampleToGroupBox
    // (`csgp`) instances. Each becomes one `csgp_<n>` key whose value is
    // the grouping type, an optional `param=<P>` (when the flag layout's
    // grouping_type_parameter_present bit is set), then one
    // space-separated token per pattern of the form
    // `count*idx0,idx1,...,idxN` โ€” `count` is the pattern's
    // `sample_count` (how many times the index run replays) and the
    // comma-list is the per-sample `sample_group_description_index`
    // values of the pattern (0 = "no group"; fragment-local indices kept
    // verbatim with their high bit set). Shares `grouping_type` with the
    // matching `sgpd_<m>` exactly like `sbgp`. Absent `csgp`, no keys.
    for (i, cg) in t.csgp.iter().enumerate() {
        let mut v = render_grouping_type(&cg.grouping_type);
        if let Some(p) = cg.grouping_type_parameter {
            v.push_str(&format!(" param={}", p));
        }
        // ยง8.9.5 flag bit 7: when set, the high bit of each index is a
        // fragment-local-vs-global source selector. Mark it so tooling
        // reading the flat surface knows the indices need MSB resolution.
        if cg.index_msb_indicates_fragment_local_description {
            v.push_str(" fraglocal");
        }
        for pat in &cg.patterns {
            v.push(' ');
            v.push_str(&format!("{}*", pat.sample_count));
            let idx_list = pat
                .indices
                .iter()
                .map(|x| x.to_string())
                .collect::<Vec<_>>()
                .join(",");
            v.push_str(&idx_list);
        }
        params.options.insert(format!("csgp_{}", i), v);
    }

    // ISO/IEC 14496-12 ยง8.6.4: surface the optional SampleDependencyTypeBox
    // (`sdtp`) as a small summary on `params.options` rather than
    // per-sample (per-sample would flood the map for a typical track).
    // Five keys per track-with-sdtp:
    //   * `sdtp_count` โ€” total per-sample entries.
    //   * `sdtp_leading_count` โ€” samples flagged as a leading sample
    //     (is_leading โˆˆ {1, 3} โ€” value 1 = leading-with-prior-dependency,
    //     not decodable from this point; value 3 = leading without prior
    //     dependency, decodable).
    //   * `sdtp_independent_count` โ€” samples with sample_depends_on = 2
    //     (an I-picture per dependency hint โ€” does not depend on others).
    //   * `sdtp_disposable_count` โ€” samples with sample_is_depended_on = 2
    //     (no other sample depends on this; safe to drop during fast
    //     forward).
    //   * `sdtp_redundant_count` โ€” samples with sample_has_redundancy = 1
    //     (the sample carries redundant coding).
    // Absent `sdtp`, none of the keys are emitted.
    if !t.sdtp.is_empty() {
        let mut leading = 0u32;
        let mut independent = 0u32;
        let mut disposable = 0u32;
        let mut redundant = 0u32;
        for e in &t.sdtp {
            if e.is_leading == 1 || e.is_leading == 3 {
                leading += 1;
            }
            if e.sample_depends_on == 2 {
                independent += 1;
            }
            if e.sample_is_depended_on == 2 {
                disposable += 1;
            }
            if e.sample_has_redundancy == 1 {
                redundant += 1;
            }
        }
        params
            .options
            .insert("sdtp_count".to_string(), t.sdtp.len().to_string());
        params
            .options
            .insert("sdtp_leading_count".to_string(), leading.to_string());
        params.options.insert(
            "sdtp_independent_count".to_string(),
            independent.to_string(),
        );
        params
            .options
            .insert("sdtp_disposable_count".to_string(), disposable.to_string());
        params
            .options
            .insert("sdtp_redundant_count".to_string(), redundant.to_string());
    }

    // ISO/IEC 14496-12 ยง8.5.3: surface the optional DegradationPriorityBox
    // (`stdp`) as a small summary on `params.options` rather than the raw
    // per-sample table (a typical track has thousands of samples; the
    // whole `priority` array would dominate the options map). The spec
    // leaves the value semantics to derived specifications โ€” we cannot
    // bucket priorities into named tiers at the container layer, so the
    // summary is the count plus min/max/sum so a consumer can recover the
    // mean and check the value spread without scanning. Four keys per
    // track-with-stdp:
    //   * `stdp_count` โ€” total per-sample priority entries.
    //   * `stdp_min` โ€” minimum `priority` value across the table (decimal).
    //   * `stdp_max` โ€” maximum `priority` value across the table (decimal).
    //   * `stdp_sum` โ€” sum of all `priority` values (u64 decimal โ€” a u16
    //     priority ร— 2^32 samples still fits comfortably).
    // Absent `stdp`, none of the keys are emitted.
    if !t.stdp.is_empty() {
        let mut lo = u16::MAX;
        let mut hi = 0u16;
        let mut sum: u64 = 0;
        for &p in &t.stdp {
            if p < lo {
                lo = p;
            }
            if p > hi {
                hi = p;
            }
            sum += p as u64;
        }
        params
            .options
            .insert("stdp_count".to_string(), t.stdp.len().to_string());
        params
            .options
            .insert("stdp_min".to_string(), lo.to_string());
        params
            .options
            .insert("stdp_max".to_string(), hi.to_string());
        params
            .options
            .insert("stdp_sum".to_string(), sum.to_string());
    }

    // ISO/IEC 14496-12 ยง8.7.6: surface the optional PaddingBitsBox
    // (`padb`) as a small summary on `params.options` rather than the
    // raw per-sample table โ€” a track with `padb` typically has every
    // sample's pad count packed densely and the raw nibble stream would
    // dominate the options map. Each pad count is bounded 0..=7 by
    // ยง8.7.6.3 so a fixed-width histogram fits in one short string;
    // keys emitted per track-with-padb:
    //   * `padb_count` โ€” total sample entries in the parsed table.
    //   * `padb_max` โ€” maximum pad count seen (0..=7).
    //   * `padb_nonzero_count` โ€” number of samples whose pad count is
    //     non-zero (the count a bitstream consumer actually cares about
    //     โ€” a track with all-zero pad counts is byte-aligned and the
    //     `padb` box is informational only).
    //   * `padb_hist` โ€” eight-element histogram `n0:n1:n2:n3:n4:n5:n6:n7`
    //     where `nK` is the count of samples whose pad count is K
    //     (decimal). The colon-separated form keeps the key compact and
    //     lets a consumer recover the full per-bucket count without
    //     parsing variable-length JSON.
    // Absent `padb`, none of the keys are emitted.
    if !t.padb.is_empty() {
        let mut hist = [0u64; 8];
        let mut max_pad = 0u8;
        let mut nonzero: u64 = 0;
        for &p in &t.padb {
            let bucket = (p & 0x07) as usize;
            hist[bucket] = hist[bucket].saturating_add(1);
            if p > max_pad {
                max_pad = p;
            }
            if p != 0 {
                nonzero += 1;
            }
        }
        params
            .options
            .insert("padb_count".to_string(), t.padb.len().to_string());
        params
            .options
            .insert("padb_max".to_string(), max_pad.to_string());
        params
            .options
            .insert("padb_nonzero_count".to_string(), nonzero.to_string());
        params.options.insert(
            "padb_hist".to_string(),
            format!(
                "{}:{}:{}:{}:{}:{}:{}:{}",
                hist[0], hist[1], hist[2], hist[3], hist[4], hist[5], hist[6], hist[7]
            ),
        );
    }

    // ISO/IEC 14496-12 ยง8.7.7: surface each `subs` (SubSampleInformationBox)
    // present on the track. Each `subs` becomes one `subs_<n>` key whose
    // value starts with `"v<version> flags=<f>"` (the FullBox preamble โ€”
    // version selects `subsample_size` width on disk; `flags` distinguishes
    // co-resident `subs` boxes per ยง8.7.7.1) followed by space-separated
    // per-sample blocks of the form
    //   `delta=<d>[:size,priority,discardable,csp[;size,priority,discardable,csp ...]]`
    // (the trailing colon and per-sub-sample list are omitted when the
    // entry has zero sub-samples). Decimal for `delta`, `size`,
    // `priority`, `discardable`; lowercase 8-digit hex for
    // `codec_specific_parameters` (it is a codec-defined u32 blob).
    //
    // Sub-sample semantics (e.g. which NAL unit a row indexes for H.264
    // per ISO/IEC 14496-15) belong to the codec layer; the container
    // surfaces the raw rows so a codec-aware consumer can decode them.
    // Absent `subs`, no keys are emitted.
    for (i, sb) in t.subs.iter().enumerate() {
        let mut v = format!("v{} flags={}", sb.version, sb.flags);
        for ent in &sb.entries {
            v.push_str(&format!(" delta={}", ent.sample_delta));
            if !ent.subsamples.is_empty() {
                v.push(':');
                let mut first = true;
                for s in &ent.subsamples {
                    if !first {
                        v.push(';');
                    }
                    first = false;
                    v.push_str(&format!(
                        "{},{},{},{:08x}",
                        s.subsample_size,
                        s.subsample_priority,
                        s.discardable,
                        s.codec_specific_parameters
                    ));
                }
            }
        }
        params.options.insert(format!("subs_{}", i), v);
    }

    // ISO/IEC 14496-12 ยง8.7.8 / ยง8.7.9 โ€” surface each `saiz` /
    // `saio` (Sample Auxiliary Information Sizes / Offsets) found
    // inside `stbl` on `params.options`. Each `saiz` becomes one
    // `saiz_<n>` key (0-based encounter index); each `saio` becomes
    // one `saio_<n>` key. The pair is keyed by `(aux_info_type,
    // aux_info_type_parameter)` โ€” a caller pairs an `saiz_<n>` with
    // the `saio_<m>` whose key matches. The most common consumer is
    // CENC: when `senc` is absent, the per-sample IV + subsample map
    // is carried in an auxiliary-information stream of type `cenc` /
    // `cbc1` / `cens` / `cbcs`, and the `saiz`+`saio` pair points to
    // the bytes in the mdat (ISO/IEC 23001-7 ยง7.3).
    //
    // Format conventions (decimal unless noted, mirroring the
    // sbgp/sgpd/subs surface):
    //
    //   saiz_<n> = "[type=<fourcc>] [param=<P>] default_size=<D> count=<N> [sizes=<s0>,<s1>,โ€ฆ]"
    //   saio_<n> = "v<version> [type=<fourcc>] [param=<P>] offsets=<o0>,<o1>,โ€ฆ"
    //
    // The `type=` / `param=` blocks are omitted when the FullBox
    // `flags & 1` bit was zero on disk (implied type is the scheme
    // type for protected content or the sample-entry FourCC
    // otherwise โ€” see ยง8.7.8.3). The `sizes=` block is omitted when
    // `default_sample_info_size != 0` (every sample has size
    // `default_size`). Offsets are decimal; in `stbl` they are
    // absolute file positions.
    for (i, sz) in t.saiz.iter().enumerate() {
        let mut v = String::new();
        if let Some(t4) = &sz.aux_info_type {
            v.push_str(&format!(
                "type={} ",
                std::str::from_utf8(t4).unwrap_or("????")
            ));
        }
        if let Some(p) = sz.aux_info_type_parameter {
            v.push_str(&format!("param={p} "));
        }
        v.push_str(&format!(
            "default_size={} count={}",
            sz.default_sample_info_size, sz.sample_count
        ));
        if !sz.per_sample.is_empty() {
            v.push_str(" sizes=");
            let mut first = true;
            for s in &sz.per_sample {
                if !first {
                    v.push(',');
                }
                first = false;
                v.push_str(&format!("{s}"));
            }
        }
        params.options.insert(format!("saiz_{}", i), v);
    }
    for (i, so) in t.saio.iter().enumerate() {
        let mut v = format!("v{}", so.version);
        if let Some(t4) = &so.aux_info_type {
            v.push_str(&format!(
                " type={}",
                std::str::from_utf8(t4).unwrap_or("????")
            ));
        }
        if let Some(p) = so.aux_info_type_parameter {
            v.push_str(&format!(" param={p}"));
        }
        v.push_str(" offsets=");
        let mut first = true;
        for o in &so.offsets {
            if !first {
                v.push(',');
            }
            first = false;
            v.push_str(&format!("{o}"));
        }
        params.options.insert(format!("saio_{}", i), v);
    }

    let timescale = if t.timescale == 0 { 1 } else { t.timescale };
    // ยง8.6.6: a mapped edit list places the track's first presented
    // sample at the first edit segment's presentation start (a leading
    // empty edit delays the track; a plain trim starts at 0). Without
    // an elst โ€” or under the non-monotonic fallback โ€” the track starts
    // at presentation time 0 as before.
    let start_time = if t.elst_timeline.mapped {
        t.elst_timeline
            .segments
            .first()
            .map(|s| s.pres_start)
            .unwrap_or(0)
    } else {
        0
    };
    StreamInfo {
        index,
        time_base: TimeBase::new(1, timescale as i64),
        duration: t.duration.map(|d| d as i64),
        start_time: Some(start_time),
        params,
    }
}

// --- Demuxer state --------------------------------------------------------

/// The concrete MP4 / ISOBMFF demuxer behind [`open`].
///
/// Constructed via [`open_typed`] when a caller needs the structured
/// inherent accessors (`sidxes` / `ssixes` / `psshes` / `senc_records` /
/// `sai_records` / `traf_sample_groups` / โ€ฆ) that don't fit the
/// [`Demuxer`] trait โ€” most notably a CENC decrypting layer replaying
/// per-sample IVs and subsample maps from the per-fragment `senc`
/// records. All fields are private; the trait implementation is
/// identical through either construction path.
pub struct Mp4Demuxer {
    input: Box<dyn ReadSeek>,
    /// Total input length in bytes (established at `open`). Used to
    /// reject sample sizes the input cannot back before allocating.
    input_len: u64,
    streams: Vec<StreamInfo>,
    samples: Vec<SampleRef>,
    cursor: usize,
    metadata: Vec<(String, String)>,
    duration_micros: i64,
    /// Parsed `sidx` SegmentIndexBoxes; one per top-level sidx encountered.
    /// Consulted by `seek_to` as a secondary fast-path when no `tfra`
    /// covers the requested track: a `sidx` carries per-subsegment
    /// `(earliest_presentation_time, subsegment_duration, byte size)`
    /// triples (ISO/IEC 14496-12 ยง8.16.3), which lets us pick the
    /// subsegment whose decode-time range contains `pts` in O(log N)
    /// without expanding the moofs. The hit is converted to a file
    /// offset; the sample-list scan then snaps to the first keyframe
    /// at or after that offset, bounded by one subsegment.
    sidxes: Vec<SidxRecord>,
    /// Parsed `ssix` SubsegmentIndexBoxes (ยง8.16.4), in file order.
    /// Each maps levels (per the `leva` LevelAssignmentBox) to byte
    /// ranges of the subsegments indexed by the associated `sidx`.
    /// Surfaced as `ssix_<n>` flat-metadata summaries and through the
    /// public `Mp4Demuxer::ssixes` accessor; not consulted by
    /// `next_packet` / `seek_to` (we seek whole subsegments, not
    /// partial ones).
    #[allow(dead_code)]
    ssixes: Vec<SsixRecord>,
    /// Parsed `tfra` random-access tables, one per track that the file's
    /// `mfra` indexes. Each holds (presentation time, moof offset) pairs
    /// for keyframes โ€” `seek_to` walks these to land directly on a moof
    /// boundary instead of scanning every sample.
    tfras: Vec<TfraRecord>,
    /// Parsed `prft` ProducerReferenceTimeBoxes (ยง8.16.5), in file
    /// order. Each is also surfaced as a `prft_<n>` flat-metadata entry;
    /// the structured list is kept for downstream tooling (low-latency
    /// DASH live edge tracking, wall-clock-to-pts mapping). Currently
    /// not consulted by `next_packet` / `seek_to`.
    #[allow(dead_code)]
    prfts: Vec<PrftRecord>,
    /// Parsed `pdin` ProgressiveDownloadInfoBox (ยง8.1.3), if the file
    /// carries one. Quantity is zero or one per file (ยง8.1.3.1); the
    /// structured record is reachable via the public
    /// `Mp4Demuxer::pdin_entries` accessor (downcast) and the flat
    /// metadata channel surfaces it as `pdin_count` + `pdin_<n>` keys.
    /// Informational only โ€” the demuxer does not consult it.
    #[allow(dead_code)]
    pdin: Option<PdinRecord>,
    /// Parsed QuickTime Preview Atom (`pnot`), if the file carries one at
    /// the top level. Reachable via the public `Mp4Demuxer::pnot`
    /// accessor and surfaced on the flat metadata channel as `pnot`.
    /// Informational only โ€” the demuxer does not consult it.
    #[allow(dead_code)]
    pnot: Option<PnotRecord>,
    /// Parsed `leva` LevelAssignmentBox (ยง8.8.13), if the file carries
    /// one. Quantity is zero or one per file (ยง8.8.13.1); the
    /// structured record is reachable via the public
    /// `Mp4Demuxer::leva_entries` accessor (downcast) and the flat
    /// metadata channel surfaces it as `leva_count` + `leva_<n>` keys.
    /// Informational only โ€” the demuxer does not consult it.
    #[allow(dead_code)]
    leva: Option<LevaRecord>,
    /// Parsed `trep` TrackExtensionPropertiesBoxes (ยง8.8.15), in file
    /// order. Quantity is zero or more (zero or one per track); each
    /// documents one track's characteristics in the subsequent movie
    /// fragments. The structured records are reachable via the public
    /// `Mp4Demuxer::treps` accessor (downcast) and the flat metadata
    /// channel surfaces them as `trep_<n>` keys. Informational only โ€”
    /// the demuxer does not consult them.
    #[allow(dead_code)]
    treps: Vec<TrepRecord>,
    /// ISO/IEC 23001-7 ยง8.1 pssh entries collected from moov. One per
    /// DRM system signalled in the file; the demuxer does not consume
    /// them but a downstream decryption layer can look up its
    /// SystemID match here.
    #[allow(dead_code)]
    psshes: Vec<PsshBox>,
    /// ISO/IEC 23001-7 ยง8.1 pssh entries collected from inside
    /// individual `moof` boxes. Each record is keyed by the enclosing
    /// `mfhd.sequence_number` so a decrypting layer can scope SystemID
    /// matches to the right fragment per ยง8.1.1 ("readers SHALL
    /// examine all Protection System Specific Header boxes in the
    /// Movie Box and in the Movie Fragment Box associated with the
    /// sample (but not those in other Movie Fragment Boxes)"). Empty
    /// in non-fragmented files and in fragmented files that signal
    /// protection only at moov level (the common case).
    #[allow(dead_code)]
    moof_psshes: Vec<MoofPsshRecord>,
    /// ISO/IEC 23001-7 ยง7.2 senc records, one per `traf` that carried
    /// a SampleEncryptionBox. Each holds the parsed per-sample IVs
    /// and (when `UseSubSampleEncryption` was set) the subsample map,
    /// keyed by `(track_idx, moof_sequence)` for downstream
    /// reassembly. Empty in non-CENC files (the common case).
    #[allow(dead_code)]
    senc_records: Vec<SencRecord>,
    /// ISO/IEC 14496-12 ยง8.7.8โ€“9 per-fragment auxiliary-information
    /// records. One per `traf` that carried at least one `saiz` or
    /// `saio` box, keyed by `(track_idx, moof_sequence)`. Empty in
    /// files that don't use auxiliary-information offsets (the common
    /// case โ€” most CENC files use `senc` instead, and unprotected
    /// files have no aux-info at all).
    #[allow(dead_code)]
    sai_records: Vec<SaiRecord>,
    /// ISO/IEC 14496-12 ยง8.8.7 duration-is-empty records. One per
    /// empty-time `traf` (tfhd flag 0x010000), in moof-walk order.
    /// Empty for files without empty-time inserts (the common case).
    #[allow(dead_code)]
    empty_durations: Vec<EmptyDurationRecord>,
    /// Per-track ISO/IEC 23001-7 ยง8.2 `tenc.default_Per_Sample_IV_Size`
    /// (`None` for tracks without a `tenc`). Needed by
    /// [`Mp4Demuxer::resolve_sai_aux_info`] to parse fetched ยง7.1
    /// auxiliary-information bytes into per-sample IV / subsample
    /// records.
    track_tenc_iv_sizes: Vec<Option<u8>>,
    /// ISO/IEC 14496-12 ยง8.9 per-fragment sample-group records. One per
    /// `traf` that carried at least one `sgpd` / `sbgp` / `csgp` box,
    /// keyed by `(track_idx, moof_sequence)`. Empty in non-fragmented
    /// files and in fragmented files that carry sample groups only at
    /// `trak`/`stbl` level (the common case).
    #[allow(dead_code)]
    traf_sample_groups: Vec<TrafSampleGroupRecord>,
    /// PIFF legacy `uuid` ProtectionSystemSpecificHeaderBox entries
    /// collected at moov level โ€” the pre-CENC `pssh` predecessor.
    /// Kept separate from `psshes` so dual-branded files don't
    /// double-report; empty for modern (or unprotected) files.
    #[allow(dead_code)]
    piff_psshes: Vec<PsshBox>,
    /// PIFF legacy `uuid` ProtectionSystemSpecificHeaderBox entries
    /// collected from inside individual `moof` boxes, keyed by the
    /// enclosing `mfhd.sequence_number` like `moof_psshes`.
    #[allow(dead_code)]
    piff_moof_psshes: Vec<MoofPsshRecord>,
    /// PIFF legacy `uuid` SampleEncryptionBox records, one per `traf`
    /// that carried the pre-CENC `senc` predecessor. PIFF-only trafs
    /// are additionally bridged into `senc_records` (see
    /// [`PiffSencRecord`]); this vector preserves the PIFF-specific
    /// `flags & 1` override triples.
    #[allow(dead_code)]
    piff_senc_records: Vec<PiffSencRecord>,
    /// Per-track PIFF legacy `uuid` TrackEncryptionBox defaults
    /// (parallel to `streams()`, `None` per unprotected / modern-CENC
    /// track). The typed record bridges into the CENC decryption
    /// router via [`PiffTencBox::scheme_decision`].
    #[allow(dead_code)]
    piff_tencs: Vec<Option<PiffTencBox>>,
    /// ISO/IEC 23009-1 ยง5.10.3.3 โ€” `emsg` DASH Event Message Boxes
    /// captured during the top-level walk, in file order, each keyed
    /// by the index of the `moof` it preceded. Informational โ€” the
    /// demuxer does not consume the events; also surfaced as
    /// `emsg_<n>` flat-metadata summaries.
    #[allow(dead_code)]
    emsgs: Vec<EmsgRecord>,
    /// Per-moof earliest presentation time `(pts, track_timescale)`,
    /// indexed like `EmsgRecord::next_moof_index` โ€” the anchor a v0
    /// emsg's `presentation_time_delta` is relative to. `None` per
    /// moof that contributed no timed samples. Consumed by
    /// [`Mp4Demuxer::emsg_absolute_time`].
    #[allow(dead_code)]
    moof_earliest: Vec<Option<(i64, u32)>>,
    /// ISO/IEC 14496-12 ยง8.11 โ€” the file-level `meta` box item
    /// infrastructure (HEIF / MIAF item catalogue), if the file carries
    /// one. Holds the primary item, item-location directory, item-info
    /// entries, and item references. `MetaItems::default()` (all-`None`)
    /// for a non-HEIF file or a plain iTunes-metadata `meta`. Reachable
    /// via the public `Mp4Demuxer::meta_items()` accessor; also surfaced
    /// on the flat metadata channel as `meta_*` keys.
    #[allow(dead_code)]
    meta_items: MetaItems,
    /// ยง8.11.7 file-level `meco` AdditionalMetadataContainerBox โ€” the
    /// additional `meta` boxes (distinct handler types) plus `mere`
    /// relations that complement the primary `meta`. `MecoBox::default()`
    /// (empty) when no `meco` is present. Reachable via the public
    /// `Mp4Demuxer::meco()` accessor; also surfaced on the flat metadata
    /// channel as `meco_*` keys.
    #[allow(dead_code)]
    meco: MecoBox,
    /// Per-track media timescale (1-based parallel to `track_ids`),
    /// needed to translate `tfra.time` (track timescale) to the seek-to
    /// caller's pts (also track timescale, but this lets us add unit
    /// asserts later if they diverge).
    #[allow(dead_code)]
    movie_timescale: u32,
    track_timescales: Vec<u32>,
    track_ids: Vec<u32>,
    /// Per-stream ยง8.6.6 edit lists in typed form (empty Vec = no
    /// `edts`/`elst` on that track). The demuxer has already applied
    /// the timeline mapping to packet timestamps; this surface is for
    /// tooling that wants the declared list itself (e.g. a remuxer
    /// carrying the elst across, or a validator).
    edit_lists: Vec<Vec<EditListEntry>>,
    /// `sample_description_index` of the packet most recently returned
    /// by `next_packet` (`None` before the first packet). See
    /// [`Self::sample_description_index_of_last_packet`].
    last_sdi: Option<u32>,
}

impl Mp4Demuxer {
    /// ISO/IEC 23001-7 ยง8.1 โ€” all `pssh`
    /// ProtectionSystemSpecificHeaderBox entries discovered at moov
    /// level, in file order. Each is keyed by a 16-byte SystemID UUID;
    /// a downstream DRM layer that matches the SystemID consumes the
    /// `data` blob (and v1 `kids` list). Empty for unprotected files.
    ///
    /// `pssh` entries inside individual `moof` boxes are surfaced via
    /// the parallel [`Mp4Demuxer::moof_psshes`] accessor, keyed by the
    /// enclosing `mfhd.sequence_number` per ยง8.1.1.
    #[allow(dead_code)]
    pub fn psshes(&self) -> &[PsshBox] {
        &self.psshes
    }

    /// ISO/IEC 23001-7 ยง8.1 โ€” `pssh` entries collected from inside
    /// individual `moof` boxes, in moof-walk order. Each record is
    /// keyed by the enclosing `mfhd.sequence_number` (the
    /// `MoofPsshRecord::moof_sequence` field) so a decrypting layer
    /// can scope SystemID lookups to the right fragment per the
    /// ยง8.1.1 normative-reader rule: "examine all Protection System
    /// Specific Header boxes in the Movie Box and in the Movie
    /// Fragment Box associated with the sample (but not those in
    /// other Movie Fragment Boxes)". Empty for non-fragmented files
    /// and for fragmented files that signal protection only at moov
    /// level (the common case).
    #[allow(dead_code)]
    pub fn moof_psshes(&self) -> &[MoofPsshRecord] {
        &self.moof_psshes
    }

    /// ISO/IEC 23001-7 ยง7.2 โ€” per-fragment `senc`
    /// SampleEncryptionBox records collected from every `traf` whose
    /// matching track carried a `tenc` default (so the per-sample IV
    /// width was recoverable). Indexed in moof-encounter order; the
    /// `track_idx` field references this demuxer's `streams()` list,
    /// and `moof_sequence` is the `mfhd.sequence_number` of the
    /// containing movie fragment. Empty for unfragmented files and
    /// for fragmented files without per-fragment encryption metadata.
    #[allow(dead_code)]
    pub fn senc_records(&self) -> &[SencRecord] {
        &self.senc_records
    }

    /// ISO/IEC 14496-12 ยง8.1.3 โ€” `pdin` ProgressiveDownloadInfoBox
    /// pairs, if the file carries one. Each entry is a
    /// `(rate, initial_delay)` u32 pair recommending an initial
    /// playback delay (milliseconds) for a given effective download
    /// rate (bytes/second); a receiver picks adjacent entries that
    /// bracket its observed throughput and linearly interpolates the
    /// delay (or extrapolates from the first / last entry).
    /// Returns `None` when the file has no `pdin` box; returns
    /// `Some(&[])` for an explicitly empty box (a producer's way of
    /// saying "no hints available"). The structured record is
    /// surfaced separately from the flat `pdin_count` / `pdin_<n>`
    /// metadata keys so tooling can choose the shape it prefers.
    #[allow(dead_code)]
    pub fn pdin_entries(&self) -> Option<&[PdinEntry]> {
        self.pdin.as_ref().map(|p| p.entries.as_slice())
    }

    /// The parsed QuickTime Preview Atom (`pnot`), if the file carried one
    /// at the top level. Locates the movie's preview (poster) image: the
    /// FourCC of the atom holding the preview data, which instance of that
    /// type to use, and the Macintosh-format modification date. `None`
    /// when no `pnot` was present. Also surfaced on the flat metadata
    /// channel as `pnot`.
    #[allow(dead_code)]
    pub fn pnot(&self) -> Option<&PnotRecord> {
        self.pnot.as_ref()
    }

    /// ISO/IEC 14496-12 ยง8.8.13 โ€” `leva` LevelAssignmentBox entries,
    /// if the file carries one. Each entry maps one fragment level to
    /// a `track_id` (plus a `padding_flag` and an `assignment_type`
    /// that discriminates among sample-group / track / track-subsegment
    /// / sub-track variants per ยง8.8.13.2). Returns `None` when the
    /// file has no `leva` box; returns `Some(&[])` for an explicit
    /// `level_count = 0` (the spec pins a minimum of 2 in ยง8.8.13.3
    /// but the demuxer carries whatever the producer wrote so a
    /// validator can flag a short table). The structured record is
    /// surfaced separately from the flat `leva_count` / `leva_<n>`
    /// metadata keys so tooling can choose the shape it prefers.
    #[allow(dead_code)]
    pub fn leva_entries(&self) -> Option<&[LevaEntry]> {
        self.leva.as_ref().map(|l| l.entries.as_slice())
    }

    /// ISO/IEC 14496-12 ยง8.8.15 โ€” all `trep`
    /// TrackExtensionPropertiesBoxes discovered inside `mvex`, in file
    /// order. Each names the `track_id` it describes and carries the
    /// type + payload length of any child boxes it nests (e.g. an
    /// `assp` Alternative Startup Sequence Properties Box, ยง8.8.16).
    /// Empty for files without `trep` boxes (which is most of the
    /// corpus โ€” `trep` is a fragmented-movie hint). The flat metadata
    /// channel carries `trep_<n>` summaries; this accessor returns the
    /// structured records.
    #[allow(dead_code)]
    pub fn treps(&self) -> &[TrepRecord] {
        &self.treps
    }

    /// ISO/IEC 14496-12 ยง8.16.4 โ€” all `ssix` SubsegmentIndexBoxes
    /// discovered during the top-level walk, in file order. Each maps
    /// levels (per the `leva` LevelAssignmentBox, ยง8.8.13 โ€” see
    /// [`Mp4Demuxer::leva_entries`]) to byte ranges of the subsegments
    /// indexed by the `sidx` the ssix follows. Empty for files without
    /// subsegment indexes (which is most of the corpus). The flat
    /// metadata channel carries `ssix_<n>` shape summaries; this
    /// accessor returns the structured table.
    #[allow(dead_code)]
    pub fn ssixes(&self) -> &[SsixRecord] {
        &self.ssixes
    }

    /// ISO/IEC 14496-12 ยง8.7.8โ€“9 โ€” per-fragment Sample Auxiliary
    /// Information records. One per `traf` that carried at least one
    /// `saiz` or `saio` box; the `track_idx` references this
    /// demuxer's `streams()` list and `moof_sequence` is the
    /// containing `mfhd.sequence_number`. The auxiliary-information
    /// bytes themselves stay in the mdat at the offsets the `saio`
    /// names (base_data_offset relative inside a traf per ยง8.8.14) โ€”
    /// the demuxer doesn't fetch or interpret them; their semantics
    /// belong to the carried `aux_info_type` (e.g. CENC `cenc` /
    /// `cbc1` / `cens` / `cbcs` per ISO/IEC 23001-7 ยง7.3, or any
    /// other registered aux-info type). Empty for files without
    /// auxiliary-info offsets (which is most of the corpus).
    #[allow(dead_code)]
    pub fn sai_records(&self) -> &[SaiRecord] {
        &self.sai_records
    }

    /// Fetch the mdat-resident CENC auxiliary information that this
    /// file's per-fragment `saiz` / `saio` pairs (ISO/IEC 14496-12
    /// ยง8.7.8โ€“9, in-`traf` carriage per ยง8.8.14) point at, and bridge
    /// it into the [`Self::senc_records`] surface.
    ///
    /// A CENC file may carry its per-sample IVs + subsample maps
    /// either in a `senc` SampleEncryptionBox or as a sample
    /// auxiliary-information stream the `saiz`+`saio` pair locates
    /// (the two carriages are byte-compatible per sample: an
    /// `InitializationVector` of the track's
    /// `tenc.default_Per_Sample_IV_Size` bytes, then โ€” when the
    /// sample's declared aux-info size exceeds the IV width โ€” a
    /// `u16` subsample count followed by `(u16 clear, u32 protected)`
    /// runs; this crate's own fragmented muxer writes `saio` offsets
    /// that point straight at its `senc` entry table). For each
    /// [`SaiRecord`] whose `(track, fragment)` has **no** parsed
    /// `senc` (the `senc`-less carriage), this method resolves the
    /// single `saio` offset against the traf's base data offset
    /// (ยง8.8.14), reads the run from the input, parses it with the
    /// track's `tenc` IV width, and appends a synthesised
    /// [`SencRecord`] โ€” after which a decryption layer replaying
    /// `senc_records` consumes both carriages identically.
    ///
    /// Returns the number of records added. Conservative skips (no
    /// error): fragments that already have a `senc`, tracks without a
    /// `tenc`, `saiz`/`saio` pairs whose `aux_info_type` is present
    /// but not a ยง10 scheme FourCC, multi-offset `saio` boxes (the
    /// per-trun split โ€” offsets one per track run), an aux-info total
    /// over 16 MiB, and runs whose bytes don't parse as ยง7.1 cells
    /// (each cell must consume its declared size exactly). I/O errors
    /// reading a resolvable run abort with the error. The input
    /// cursor is restored, so packet reading is unaffected; the flat
    /// `senc_<n>` metadata (rendered at `open`) does not retroactively
    /// gain keys for synthesised records.
    pub fn resolve_sai_aux_info(&mut self) -> Result<usize> {
        use std::io::SeekFrom;
        let have_senc: Vec<(u32, u32)> = self
            .senc_records
            .iter()
            .map(|r| (r.track_idx, r.moof_sequence))
            .collect();
        let saved_pos = self.input.stream_position()?;
        let mut new_records: Vec<SencRecord> = Vec::new();
        for r in &self.sai_records {
            if have_senc.contains(&(r.track_idx, r.moof_sequence)) {
                continue;
            }
            let Some(iv_size) = self
                .track_tenc_iv_sizes
                .get(r.track_idx as usize)
                .copied()
                .flatten()
            else {
                continue;
            };
            for sz in &r.saiz {
                // ยง8.7.8.3: absent aux_info_type (flags & 1 clear)
                // means the type implied by the sample entry's
                // protection scheme; an explicit type must be a ยง10
                // scheme FourCC to be CENC aux info.
                let is_cenc_type = match &sz.aux_info_type {
                    None => true,
                    Some(t) => matches!(t, b"cenc" | b"cbc1" | b"cens" | b"cbcs"),
                };
                if !is_cenc_type {
                    continue;
                }
                let Some(so) = r.saio.iter().find(|so| {
                    so.aux_info_type == sz.aux_info_type
                        && so.aux_info_type_parameter == sz.aux_info_type_parameter
                }) else {
                    continue;
                };
                // ยง8.7.9.3 in-traf: entry_count is 1 (contiguous, run
                // order) or one per trun. Only the contiguous shape is
                // resolvable without per-trun sample counts.
                if so.offsets.len() != 1 {
                    continue;
                }
                let count = sz.sample_count as usize;
                // ยง7.1 empty-aux (constant-IV, no subsamples) carries
                // nothing to fetch; a forged multi-GiB total is rejected
                // BEFORE any allocation โ€” including the sizes scratch
                // vector itself, whose length is the attacker-controlled
                // sample_count in the constant-size shape (u8-wide cells
                // legitimately cap at 255 bytes/sample).
                const MAX_AUX_TOTAL: usize = 16 * 1024 * 1024;
                let sizes: Vec<usize> = if sz.default_sample_info_size != 0 {
                    let cell = sz.default_sample_info_size as usize;
                    match count.checked_mul(cell) {
                        Some(total) if total <= MAX_AUX_TOTAL => {}
                        _ => continue,
                    }
                    vec![cell; count]
                } else {
                    if sz.per_sample.len() < count {
                        continue;
                    }
                    sz.per_sample[..count].iter().map(|&b| b as usize).collect()
                };
                let total: usize = sizes.iter().sum();
                if total == 0 || total > MAX_AUX_TOTAL {
                    continue;
                }
                let Some(abs) = r.base_data_offset.checked_add(so.offsets[0]) else {
                    continue;
                };
                self.input.seek(SeekFrom::Start(abs))?;
                let mut buf = vec![0u8; total];
                if self.input.read_exact(&mut buf).is_err() {
                    // Truncated file: the run lies past EOF. Skip the
                    // record rather than failing the whole resolve.
                    continue;
                }
                if let Some(senc) = parse_aux_info_run(&buf, &sizes, iv_size as usize) {
                    new_records.push(SencRecord {
                        track_idx: r.track_idx,
                        moof_sequence: r.moof_sequence,
                        senc,
                    });
                    break; // one senc per (track, fragment)
                }
            }
        }
        self.input.seek(SeekFrom::Start(saved_pos))?;
        let added = new_records.len();
        self.senc_records.extend(new_records);
        Ok(added)
    }

    /// ISO/IEC 14496-12 ยง8.8.7 โ€” `duration-is-empty` records, one per
    /// empty-time `traf` (tfhd flag 0x010000) in moof-walk order. Each
    /// names the track, the containing fragment's
    /// `mfhd.sequence_number`, and the length of the inserted empty
    /// interval in the track's media timescale (ยง8.8.6.1 โ€” e.g. audio
    /// silence suppression). The demuxer has already advanced the
    /// track's running decode timeline past each gap; the records let
    /// a remuxer or validator reconstruct where the gaps were. Empty
    /// for files without empty-time inserts. The flat metadata channel
    /// carries the same information as `frag_empty_duration_<n>` keys.
    pub fn empty_duration_records(&self) -> &[EmptyDurationRecord] {
        &self.empty_durations
    }

    /// ISO/IEC 14496-12 ยง8.9 โ€” per-fragment sample-group records, one
    /// per `traf` that carried at least one `sgpd` / `sbgp` / `csgp`
    /// box. A movie fragment may declare its own **fragment-local**
    /// group descriptions (ยง8.9.3 `sgpd` inside `traf`) and map its
    /// samples into either those or the `trak`-level descriptions via a
    /// `sbgp` (ยง8.9.2) or `csgp` (ยง8.9.5) โ€” the `csgp` bit-7
    /// `index_msb_indicates_fragment_local_description` flag selects the
    /// source per index and is only legal in this `traf` context. Each
    /// record references this demuxer's `streams()` list via `track_idx`
    /// and the containing `mfhd.sequence_number` via `moof_sequence`; the
    /// parsed boxes preserve their on-wire values verbatim (grouping-type
    /// semantics belong to the caller, mirroring the `stbl`-level
    /// surface). Most commonly populated for CENC `seig` key rotation
    /// across a fragment's samples. Empty in non-fragmented files and in
    /// fragmented files carrying sample groups only at `trak`/`stbl`
    /// level (the common case).
    #[allow(dead_code)]
    pub fn traf_sample_groups(&self) -> &[TrafSampleGroupRecord] {
        &self.traf_sample_groups
    }

    /// PIFF legacy `uuid` ProtectionSystemSpecificHeaderBox entries
    /// discovered at moov level, in file order โ€” the pre-CENC
    /// predecessor of `pssh`, carried as a `uuid` box with
    /// [`crate::cenc::PIFF_PSSH_USERTYPE`] by Smooth Streaming /
    /// PlayReady-era packagers. The body is byte-identical to a v0
    /// `pssh` payload, so the record shape is the shared [`PsshBox`];
    /// the pool is kept separate from [`Mp4Demuxer::psshes`] so a
    /// dual-branded file (carrying both forms for the same SystemID)
    /// doesn't double-report. Empty for modern or unprotected files.
    #[allow(dead_code)]
    pub fn piff_psshes(&self) -> &[PsshBox] {
        &self.piff_psshes
    }

    /// PIFF legacy `uuid` ProtectionSystemSpecificHeaderBox entries
    /// collected from inside individual `moof` boxes (PIFF permits the
    /// box in `moov` and/or `moof`), keyed by the enclosing
    /// `mfhd.sequence_number` โ€” the legacy counterpart of
    /// [`Mp4Demuxer::moof_psshes`].
    #[allow(dead_code)]
    pub fn piff_moof_psshes(&self) -> &[MoofPsshRecord] {
        &self.piff_moof_psshes
    }

    /// PIFF legacy `uuid` SampleEncryptionBox records, one per `traf`
    /// that carried the pre-CENC `senc` predecessor
    /// ([`crate::cenc::PIFF_SENC_USERTYPE`]), in moof-encounter order.
    /// Each preserves the PIFF-only `flags & 1` override triple
    /// alongside the per-sample IV / subsample table. A `traf` whose
    /// only sample-encryption carrier was the PIFF form is *also*
    /// bridged into [`Mp4Demuxer::senc_records`] (the tables are
    /// byte-compatible) so an existing CENC decryption layer consumes
    /// legacy fragments unchanged โ€” see [`PiffSencRecord`] for the
    /// dual-branding rules.
    #[allow(dead_code)]
    pub fn piff_senc_records(&self) -> &[PiffSencRecord] {
        &self.piff_senc_records
    }

    /// Per-track PIFF legacy `uuid` TrackEncryptionBox defaults,
    /// parallel to [`Demuxer::streams`] (`None` for tracks without the
    /// box). The pre-CENC predecessor of `tenc`, carried in
    /// `sinf/schi` with [`crate::cenc::PIFF_TENC_USERTYPE`]; a
    /// decrypting layer bridges it into the CENC router via
    /// [`PiffTencBox::scheme_decision`] / [`PiffTencBox::to_tenc`].
    /// The same defaults are surfaced as `piff_algorithm_id` /
    /// `piff_iv_size` / `piff_kid` stream options.
    #[allow(dead_code)]
    pub fn piff_tencs(&self) -> &[Option<PiffTencBox>] {
        &self.piff_tencs
    }

    /// ISO/IEC 23009-1 ยง5.10.3.3 โ€” `emsg` DASH Event Message Boxes
    /// captured during the top-level walk, in file order. Each record
    /// carries the parsed event (scheme URI + value, timing triple,
    /// id, opaque `message_data`) plus the index of the `moof` the box
    /// preceded โ€” the segment the event applies to (a v0
    /// `presentation_time_delta` is relative to that fragment's
    /// earliest presentation time). Empty for files without in-band
    /// events (which is most of the corpus). The flat metadata channel
    /// carries `emsg_<n>` summaries; this accessor returns the
    /// structured records.
    #[allow(dead_code)]
    pub fn emsgs(&self) -> &[EmsgRecord] {
        &self.emsgs
    }

    /// Resolve an [`EmsgRecord`]'s event start to an **absolute**
    /// position on the media presentation timeline, in the emsg's own
    /// `timescale` units.
    ///
    /// * A **v1** record carries the absolute `presentation_time`
    ///   directly โ€” returned as-is (its `next_moof_index` plays no
    ///   part).
    /// * A **v0** record carries a `presentation_time_delta` relative
    ///   to "the earliest presentation time of the segment"
    ///   (ISO/IEC 23009-1 ยง5.10.3.3) โ€” resolved against the earliest
    ///   presentation time of the samples contributed by the `moof`
    ///   the box preceded, rescaled from that track's timescale into
    ///   the emsg timescale (truncating division), plus the delta.
    ///
    /// Returns `None` when a v0 record cannot be anchored: the box
    /// preceded no moof (a producer slip placed it after the last
    /// fragment), the anchoring moof contributed no timed samples, a
    /// timescale is zero, or the resolved value falls outside `u64`.
    #[allow(dead_code)]
    pub fn emsg_absolute_time(&self, record: &EmsgRecord) -> Option<u64> {
        match record.emsg.presentation {
            crate::emsg::EmsgTime::Absolute(t) => Some(t),
            crate::emsg::EmsgTime::Delta(delta) => {
                let (pts, track_ts) = (*self.moof_earliest.get(record.next_moof_index)?)?;
                if track_ts == 0 || record.emsg.timescale == 0 {
                    return None;
                }
                let anchor = (pts as i128) * (record.emsg.timescale as i128) / (track_ts as i128);
                u64::try_from(anchor + delta as i128).ok()
            }
        }
    }

    /// ISO/IEC 14496-12 ยง8.11 โ€” the file-level `meta` box item
    /// infrastructure (HEIF / MIAF item catalogue): the primary item ID
    /// (`pitm`), the item-location directory (`iloc`), item-info entries
    /// (`iinf` / `infe`), and typed item references (`iref`), plus the
    /// `meta`'s handler type. Returns an all-`None` [`MetaItems`] (via
    /// [`MetaItems::is_empty`]) for a non-HEIF file or a `meta` that
    /// carries only iTunes-style `hdlr` + `ilst`. The same data is also
    /// surfaced on the flat metadata channel as `meta_*` keys.
    #[allow(dead_code)]
    pub fn meta_items(&self) -> &MetaItems {
        &self.meta_items
    }

    /// The file-level `meco` AdditionalMetadataContainerBox (ISO/IEC
    /// 14496-12 ยง8.11.7), if one was present. The additional `meta` boxes
    /// (each a fully-parsed [`MetaItems`] with a handler type distinct
    /// from the primary `meta`) plus the `mere` relation boxes
    /// (ยง8.11.8) describing how the same-level `meta` boxes relate.
    /// Returns an empty [`MecoBox`] ([`MecoBox::is_empty`]) when no
    /// `meco` was present. The same data is surfaced on the flat
    /// metadata channel as `meco_*` keys.
    #[allow(dead_code)]
    pub fn meco(&self) -> &MecoBox {
        &self.meco
    }

    /// The ยง8.6.6 edit list declared on `stream_index`'s track, in
    /// typed form (empty slice = no `edts`/`elst`, or the index is out
    /// of range). Packet timestamps have already been mapped through
    /// this list; the raw entries are surfaced for tooling that wants
    /// the declaration itself โ€” a remuxer carrying the elst across
    /// (feed the slice to [`build_elst_box`]), or a validator checking
    /// ยง8.6.6.3 constraints. The same data appears on the stream's
    /// `params.options` as `elst_entry_count` + `elst_<n>` flat keys.
    #[allow(dead_code)]
    pub fn edit_list(&self, stream_index: u32) -> &[EditListEntry] {
        self.edit_lists
            .get(stream_index as usize)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    /// The 1-based ยง8.5.2 `sample_description_index` of the packet
    /// most recently returned by `next_packet` (`None` before the
    /// first packet). Resolved from the covering `stsc` entry (ยง8.7.4)
    /// for moov-resident samples and from `tfhd` / `trex` (ยง8.8.7) for
    /// fragment samples.
    ///
    /// Active decode always uses `stsd` entry `[0]` (index 1); a value
    /// โ‰ฅ 2 tells the caller this packet was authored against a
    /// different sample description โ€” look it up via the stream's
    /// `stsd_<n>` options (or re-open a decoder against that entry's
    /// config) before feeding the packet on. Files that switch
    /// descriptions mid-stream are rare but ยง8.5.2.3 permits them;
    /// this surface closes the detection half of that gap (automatic
    /// mid-stream codec re-dispatch remains out of scope).
    #[allow(dead_code)]
    pub fn sample_description_index_of_last_packet(&self) -> Option<u32> {
        self.last_sdi
    }
}

impl Demuxer for Mp4Demuxer {
    fn format_name(&self) -> &str {
        "mp4"
    }

    fn streams(&self) -> &[StreamInfo] {
        &self.streams
    }

    fn next_packet(&mut self) -> Result<Packet> {
        if self.cursor >= self.samples.len() {
            return Err(Error::Eof);
        }
        let s = self.samples[self.cursor];
        self.cursor += 1;
        self.last_sdi = Some(s.sdi);
        // A forged sample size (stsz / trun) cannot exceed what the
        // input actually holds past the sample's offset โ€” reject
        // before allocating the payload buffer (`read_exact` would
        // fail anyway, but only after a potentially multi-GiB
        // allocation the file could never back). The cursor has
        // already advanced, so โ€” exactly as with a short read โ€” the
        // next call moves on to the following sample.
        match s.offset.checked_add(s.size as u64) {
            Some(end) if end <= self.input_len => {}
            _ => {
                return Err(Error::invalid(format!(
                    "MP4: sample at offset {} with size {} exceeds input length {}",
                    s.offset, s.size, self.input_len
                )));
            }
        }
        self.input.seek(SeekFrom::Start(s.offset))?;
        let mut data = vec![0u8; s.size as usize];
        self.input.read_exact(&mut data)?;
        let stream = &self.streams[s.track_idx as usize];
        let mut pkt = Packet::new(s.track_idx, stream.time_base, data);
        // CTS for `pts` (display order), DTS for `dts` (decode order).
        // For tracks without a ctts box `pts == dts` because the
        // demuxer fills `cts_offsets[i]` with zero (ยง8.6.1.3).
        pkt.pts = Some(s.pts);
        pkt.dts = Some(s.dts);
        pkt.duration = Some(s.duration);
        pkt.flags.keyframe = s.keyframe;
        // ยง8.6.6: media the edit list never presents (decode pre-roll
        // / excised ranges) is delivered for decoding but flagged so a
        // player drops the decoded output instead of showing it.
        pkt.flags.discard = s.discard;
        Ok(pkt)
    }

    fn seek_to(&mut self, stream_index: u32, pts: i64) -> Result<i64> {
        if stream_index as usize >= self.streams.len() {
            return Err(Error::invalid(format!(
                "MP4: stream index {stream_index} out of range"
            )));
        }

        // Optional fast-path: if we have a `tfra` random-access index
        // for this track, use it to locate the moof byte offset of the
        // last keyframe at-or-before `pts`. We then convert the
        // `moof_offset` back to a sample index by looking up the first
        // sample of this track whose `offset >= moof_offset`. This is
        // O(log N) on the tfra (binary search by time) + O(N) on the
        // sample list (linear scan from the moof boundary), where the
        // sample list scan is bounded by one fragment's worth of
        // samples โ€” far better than the full O(N) walk below.
        //
        // The tfra entries' `time` field is in this track's media
        // timescale, same as the caller's `pts`.
        if let Some(target) = self.tfra_seek_target(stream_index, pts) {
            // Find the cursor: first sample of this track whose offset
            // matches the moof's first sample. The moof's samples land
            // in mdat, which starts after the moof box; the first one
            // belongs to this track (single-track sidx) or the first
            // traf for this track.
            for (i, s) in self.samples.iter().enumerate() {
                if s.track_idx != stream_index {
                    continue;
                }
                if s.offset >= target.moof_offset && s.keyframe {
                    self.cursor = i;
                    return Ok(s.pts);
                }
            }
            // Fall through to the linear scan if the tfra entry didn't
            // resolve cleanly (e.g. mdat layout the file lied about).
        }

        // Secondary fast-path: if `tfra` didn't apply (no mfra in the
        // file, or none of the file's tfras index this track), but the
        // file carries a `sidx` (typical for DASH on-demand profile,
        // ยง8.16.3), use it to find the subsegment whose decode-time
        // range contains `pts` and snap to the first keyframe at or
        // after that subsegment's byte offset. The sample-list scan is
        // bounded by one subsegment's samples.
        if let Some(target_offset) = self.sidx_seek_target(stream_index, pts) {
            for (i, s) in self.samples.iter().enumerate() {
                if s.track_idx != stream_index {
                    continue;
                }
                if s.offset >= target_offset && s.keyframe {
                    self.cursor = i;
                    return Ok(s.pts);
                }
            }
            // Fall through to the linear scan if no keyframe lands at
            // or after the sidx-pointed offset (corrupt sidx, etc.).
        }

        // Default linear scan: find the last keyframe of this stream
        // with pts <= target.
        let mut best_cursor: Option<usize> = None;
        let mut best_pts: i64 = 0;
        for (i, s) in self.samples.iter().enumerate() {
            if s.track_idx != stream_index || !s.keyframe {
                continue;
            }
            if s.pts <= pts {
                if best_cursor.is_none() || s.pts >= best_pts {
                    best_cursor = Some(i);
                    best_pts = s.pts;
                }
            } else {
                break;
            }
        }
        // If no keyframe at-or-before target but there is any keyframe,
        // fall back to the first keyframe of this stream (pts 0).
        if best_cursor.is_none() {
            for (i, s) in self.samples.iter().enumerate() {
                if s.track_idx == stream_index && s.keyframe {
                    best_cursor = Some(i);
                    best_pts = s.pts;
                    break;
                }
            }
        }
        let cursor = best_cursor.ok_or_else(|| {
            Error::unsupported(format!(
                "MP4: no keyframes in stream {stream_index} to seek to"
            ))
        })?;
        self.cursor = cursor;
        Ok(best_pts)
    }

    fn metadata(&self) -> &[(String, String)] {
        &self.metadata
    }

    fn duration_micros(&self) -> Option<i64> {
        if self.duration_micros > 0 {
            Some(self.duration_micros)
        } else {
            None
        }
    }
}

impl Mp4Demuxer {
    /// Look up the latest tfra entry for `stream_index` whose `time`
    /// is `<= pts`. Returns the `TfraEntry` or `None` when no tfra
    /// covers this track or no entry is at-or-before `pts`.
    fn tfra_seek_target(&self, stream_index: u32, pts: i64) -> Option<TfraEntry> {
        if self.tfras.is_empty() {
            return None;
        }
        let track_id = self.track_ids.get(stream_index as usize)?;
        let tfra = self.tfras.iter().find(|t| t.track_id == *track_id)?;
        if tfra.entries.is_empty() {
            return None;
        }
        let _ts = self.track_timescales.get(stream_index as usize)?;
        // tfra entries are sorted by `time` per spec. Binary search for
        // the largest `time <= pts`. We treat negative pts as "before
        // any keyframe" โ†’ return the first entry.
        if pts < 0 {
            return Some(tfra.entries[0]);
        }
        let target = pts as u64;
        match tfra.entries.binary_search_by_key(&target, |e| e.time) {
            Ok(i) => Some(tfra.entries[i]),
            Err(i) => {
                if i == 0 {
                    Some(tfra.entries[0])
                } else {
                    Some(tfra.entries[i - 1])
                }
            }
        }
    }

    /// Look up the byte offset of the subsegment that covers `pts` for
    /// this track, using parsed `sidx` (ISO/IEC 14496-12 ยง8.16.3) records.
    ///
    /// Two on-the-wire shapes are handled, both spec-conformant:
    ///
    /// 1. **Single `sidx` indexing N subsegments** (DASH on-demand
    ///    profile). One sidx record at the start of the file lists
    ///    every fragment's `(EPT, duration, size)`. We binary-search
    ///    that table by decode time.
    ///
    /// 2. **One `sidx` per fragment, each indexing one subsegment**
    ///    (DASH live profile / our own muxer's output). Each sidx
    ///    immediately precedes a `(styp? + moof + mdat)` and reports
    ///    `EPT` = that fragment's `tfdt`. We pick the latest sidx
    ///    whose EPT โ‰ค `pts`.
    ///
    /// Both shapes converge on the same return: a byte offset the
    /// `seek_to` caller can match against `SampleRef::offset` to find
    /// the first keyframe at-or-after that fragment's first byte. The
    /// sample-list scan that follows is bounded by one subsegment.
    ///
    /// Hierarchical (nested) sidx references are skipped โ€” we keep
    /// walking media references only. Returns `None` when no sidx
    /// covers this track, or no reference is at or before `pts`.
    fn sidx_seek_target(&self, stream_index: u32, pts: i64) -> Option<u64> {
        if self.sidxes.is_empty() {
            return None;
        }
        let track_id = *self.track_ids.get(stream_index as usize)?;
        let track_ts = *self.track_timescales.get(stream_index as usize)? as u64;
        if track_ts == 0 {
            return None;
        }
        let pts_u = if pts < 0 { 0u64 } else { pts as u64 };

        // Walk every sidx whose reference_id matches the track. For
        // each one, expand its reference list into virtual
        // `(time_in_sidx_scale, byte_offset)` anchors and remember the
        // latest anchor whose time โ‰ค pts (translated into sidx scale).
        let mut best: Option<u64> = None;
        let mut first_media_offset: Option<u64> = None;
        for sidx in self.sidxes.iter().filter(|s| s.reference_id == track_id) {
            if sidx.references.is_empty() || sidx.timescale == 0 {
                continue;
            }
            let target_sidx_time = if track_ts == sidx.timescale as u64 {
                pts_u
            } else {
                // Multiply with u128 to avoid overflow on long durations.
                ((pts_u as u128) * (sidx.timescale as u128) / (track_ts as u128)) as u64
            };
            let mut cur_time = sidx.earliest_presentation_time;
            let mut cur_offset = sidx.first_byte_offset;
            for r in &sidx.references {
                if r.is_sidx {
                    // Hierarchical sidx: consumes byte range, no
                    // media-time anchor to land on.
                    cur_offset = cur_offset.saturating_add(r.referenced_size as u64);
                    continue;
                }
                if first_media_offset.is_none() {
                    first_media_offset = Some(cur_offset);
                }
                if cur_time <= target_sidx_time {
                    // Later anchors override earlier ones (we're picking
                    // the LAST subsegment whose start โ‰ค pts).
                    best = Some(cur_offset);
                }
                cur_time = cur_time.saturating_add(r.subsegment_duration as u64);
                cur_offset = cur_offset.saturating_add(r.referenced_size as u64);
            }
        }
        // If pts predates every sidx-indexed subsegment, snap to the
        // first media reference's offset so the caller still lands on
        // a keyframe boundary rather than falling through to the slow
        // path.
        best.or(first_media_offset)
    }
}

// --- Public parser entry points (tests + diagnostic tools) ---------------

/// Parse a standalone `sidx` (SegmentIndexBox, ยง8.16.3) body from
/// `body` (the bytes after the 8/16-byte box header). `sidx_end_offset`
/// is the absolute file offset of the first byte AFTER the sidx box;
/// it anchors `first_offset` per spec.
///
/// Exposed as a public entry point so tooling can read DASH segment
/// indexes without re-running `open()`.
pub fn parse_sidx_box(body: &[u8], sidx_end_offset: u64) -> Result<Option<SidxRecord>> {
    parse_sidx(body, sidx_end_offset)
}

/// Parse a standalone `ssix` (SubsegmentIndexBox, ยง8.16.4) body from
/// `body` (the bytes after the 8/16-byte box header).
///
/// Exposed as a public entry point so DASH tooling can map levels to
/// partial-subsegment byte ranges without re-running `open()` โ€” the
/// ssix sits immediately after the `sidx` it documents (ยง8.16.4.1), so
/// a segment fetcher that already walked to the sidx has the ssix
/// bytes in hand.
///
/// Returns `Err` for a body shorter than the 8-byte floor (4-byte
/// FullBox preamble + `subsegment_count`), for a version byte other
/// than 0 (the only defined layout), and for any subsegment or range
/// list that outruns the body. A `subsegment_count` of zero yields an
/// empty record.
pub fn parse_ssix_box(body: &[u8]) -> Result<SsixRecord> {
    parse_ssix(body)
}

/// Serialise a [`SsixRecord`] into a complete `ssix` box โ€” 8-byte
/// header (`[size:u32]['ssix']`) plus the ยง8.16.4.2 v0 body โ€” for
/// segment-index emitters that pair it with a `sidx`.
///
/// The caller owns the ยง8.16.4.1 conformance constraints the record
/// type cannot express: the box must immediately follow the `sidx` it
/// documents, `subsegments.len()` must equal that sidx's
/// `reference_count`, every byte of each subsegment must be covered
/// (ranges partition the subsegment), and each subsegment should carry
/// at least two ranges. `range_size` values are 24-bit on the wire;
/// values above 0xFF_FFFF are rejected rather than silently masked.
pub fn build_ssix_box(record: &SsixRecord) -> Result<Vec<u8>> {
    let mut body = Vec::with_capacity(
        8 + record
            .subsegments
            .iter()
            .map(|s| 4 + 4 * s.ranges.len())
            .sum::<usize>(),
    );
    body.extend_from_slice(&[0u8; 4]); // FullBox(version = 0, flags = 0)
    body.extend_from_slice(&(record.subsegments.len() as u32).to_be_bytes());
    for s in &record.subsegments {
        body.extend_from_slice(&(s.ranges.len() as u32).to_be_bytes());
        for r in &s.ranges {
            if r.range_size > 0xFF_FFFF {
                return Err(Error::invalid("MP4: ssix range_size exceeds 24 bits"));
            }
            let b = r.range_size.to_be_bytes();
            body.extend_from_slice(&[r.level, b[1], b[2], b[3]]);
        }
    }
    let mut out = Vec::with_capacity(8 + body.len());
    out.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes());
    out.extend_from_slice(b"ssix");
    out.extend_from_slice(&body);
    Ok(out)
}

/// Parse a standalone `mfra` (MovieFragmentRandomAccessBox, ยง8.8.10)
/// body, returning the per-track `tfra` tables (one per track that the
/// file's mfra indexes).
pub fn parse_mfra_box(body: &[u8]) -> Result<Vec<TfraRecord>> {
    let mut out = Vec::new();
    parse_mfra(body, &mut out, &mut None)?;
    Ok(out)
}

/// Parse a standalone `prft` (ProducerReferenceTimeBox, ยง8.16.5) body
/// from `body` (the bytes after the 8/16-byte box header).
///
/// Exposed as a public entry point so low-latency DASH / CMAF tooling
/// can correlate wall-clock NTP timestamps with media decoding time
/// for one reference track without re-running `open()`.
///
/// Returns `Err` for a truncated body (less than 16 bytes for v0 or
/// 20 bytes for v1). Multiple `prft` boxes may appear in one file
/// (each annotates the following moof per ยง8.16.5.1), in which case
/// callers should walk the top-level box list themselves and call
/// this entry per occurrence.
pub fn parse_prft_box(body: &[u8]) -> Result<Option<PrftRecord>> {
    parse_prft(body)
}

/// Serialise a `prft` (ProducerReferenceTimeBox, ISO/IEC 14496-12
/// ยง8.16.5) from a [`PrftRecord`] โ€” the byte-exact inverse of
/// [`parse_prft_box`].
///
/// Layout (ยง8.16.5.2): a FullBox preamble carrying the record's `version`
/// (0 or 1) and its 24-bit `flags` (verbatim โ€” `0` in the 2015 edition,
/// the named NTP-annotation bits in the 2022 edition), then the 32-bit
/// `reference_track_ID`, the 64-bit NTP `ntp_timestamp`, and the
/// `media_time` โ€” written as a 32-bit field for version 0 and a 64-bit
/// field for version 1.
///
/// Returns `None` when `version == 0` but `media_time` exceeds
/// `u32::MAX` (it would not fit the v0 32-bit field and re-parse
/// identically โ€” the caller must bump the record to version 1), or for a
/// `version` other than 0/1 (no other version is defined).
pub fn build_prft_box(record: &PrftRecord) -> Option<Vec<u8>> {
    if record.version > 1 {
        return None;
    }
    let mut body = Vec::with_capacity(24);
    // FullBox preamble: 1-byte version + the 24-bit flags (low 3 bytes).
    body.push(record.version);
    body.extend_from_slice(&record.flags.to_be_bytes()[1..4]);
    body.extend_from_slice(&record.reference_track_id.to_be_bytes());
    body.extend_from_slice(&record.ntp_timestamp.to_be_bytes());
    if record.version == 0 {
        let mt: u32 = record.media_time.try_into().ok()?;
        body.extend_from_slice(&mt.to_be_bytes());
    } else {
        body.extend_from_slice(&record.media_time.to_be_bytes());
    }
    Some(wrap_box(&crate::boxes::PRFT, &body))
}

/// Parse a standalone `pdin` (ProgressiveDownloadInfoBox, ISO/IEC
/// 14496-12 ยง8.1.3) body from `body` (the bytes after the 8/16-byte
/// box header).
///
/// Exposed as a public entry point so tooling that already has the
/// box's payload bytes in hand (a DASH packager, a manifest emitter,
/// a fixture validator) can recover the `(rate, initial_delay)` pairs
/// without re-running `open()`. Returns `Err` for a body shorter than
/// the 4-byte FullBox preamble or whose post-preamble length is not a
/// multiple of 8 bytes (one `(rate, initial_delay)` u32 pair per
/// entry); returns `Ok(PdinRecord { entries: vec![] })` for an
/// explicitly empty box (preamble only, zero pairs).
pub fn parse_pdin_box(body: &[u8]) -> Result<PdinRecord> {
    parse_pdin(body)
}

/// Serialise a `pdin` (ProgressiveDownloadInfoBox, ISO/IEC 14496-12
/// ยง8.1.3) from its `(rate, initial_delay)` entries โ€” the byte-exact
/// inverse of [`parse_pdin_box`] (FullBox version 0, flags 0).
///
/// Layout (ยง8.1.3.2): the 4-byte FullBox preamble followed by one
/// `(rate, initial_delay)` u32 pair per entry, each big-endian. `rate`
/// is a download bitrate in bytes/second; `initial_delay` is the
/// suggested initial playback delay (in the file's time-scale ticks)
/// when downloading at that rate. The entries are written in supplied
/// order โ€” ยง8.1.3.3 expects them sorted by ascending `rate`, but this
/// builder preserves the caller's order rather than re-sorting. An empty
/// entry list yields a preamble-only box (a legal, content-free `pdin`).
pub fn build_pdin_box(record: &PdinRecord) -> Vec<u8> {
    let mut body = Vec::with_capacity(4 + record.entries.len() * 8);
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    for e in &record.entries {
        body.extend_from_slice(&e.rate.to_be_bytes());
        body.extend_from_slice(&e.initial_delay.to_be_bytes());
    }
    wrap_box(&crate::boxes::PDIN, &body)
}

/// Parse a QuickTime `pnot` (Preview Atom) body from `body` (the 12 bytes
/// after the plain 8-byte box header โ€” `pnot` is a plain `Box`, no FullBox
/// preamble): `unsigned int(32) modification_date`, `unsigned int(16)
/// version`, `unsigned int(32) atom_type`, `unsigned int(16) atom_index`.
/// Returns `None` for a body shorter than the fixed 12 bytes; trailing
/// bytes are ignored.
fn parse_pnot(body: &[u8]) -> Option<PnotRecord> {
    if body.len() < 12 {
        return None;
    }
    let modification_date = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
    let version = u16::from_be_bytes([body[4], body[5]]);
    let atom_type = [body[6], body[7], body[8], body[9]];
    let atom_index = u16::from_be_bytes([body[10], body[11]]);
    Some(PnotRecord {
        modification_date,
        version,
        atom_type,
        atom_index,
    })
}

/// Parse a standalone QuickTime `pnot` (Preview Atom) body from `body`
/// (the 12 bytes after the plain 8-byte box header). Exposed so tooling
/// holding the atom's payload can recover the preview locator without
/// re-running `open()`. `Err` for a body shorter than the fixed 12-byte
/// layout; trailing bytes are ignored.
pub fn parse_pnot_box(body: &[u8]) -> Result<PnotRecord> {
    parse_pnot(body).ok_or_else(|| Error::invalid("MP4: pnot too short"))
}

/// Build a complete QuickTime `pnot` (Preview Atom) box from a
/// [`PnotRecord`]. The byte-exact inverse of [`parse_pnot_box`]: the four
/// fields with no FullBox preamble.
pub fn build_pnot_box(r: &PnotRecord) -> Vec<u8> {
    let mut body = Vec::with_capacity(12);
    body.extend_from_slice(&r.modification_date.to_be_bytes());
    body.extend_from_slice(&r.version.to_be_bytes());
    body.extend_from_slice(&r.atom_type);
    body.extend_from_slice(&r.atom_index.to_be_bytes());
    wrap_box(&crate::boxes::PNOT, &body)
}

/// Parse a standalone `leva` (LevelAssignmentBox, ISO/IEC 14496-12
/// ยง8.8.13) body from `body` (the bytes after the 8/16-byte box
/// header).
///
/// Exposed as a public entry point so tooling that already has the
/// box's payload bytes in hand (a DASH packager, a manifest emitter, a
/// fragment-level extractor) can recover the per-level table without
/// re-running `open()`. Returns `Err` for a body shorter than the
/// 4-byte FullBox preamble, a body missing its `level_count` byte, or
/// any truncated per-entry tail; returns
/// `Ok(LevaRecord { entries: vec![] })` for a body with the preamble +
/// `level_count = 0`.
pub fn parse_leva_box(body: &[u8]) -> Result<LevaRecord> {
    parse_leva(body)
}

/// Serialise a [`LevaRecord`] into a complete `leva` box โ€” 8-byte header
/// (`[size:u32]['leva']`) plus the ยง8.8.13.2 v0 body โ€” for fragmented-MP4
/// emitters that declare per-level sample assignments in `mvex`.
///
/// The body is the ยง8.8.13.2 `FullBox(version = 0, flags = 0)` preamble,
/// the one-byte `level_count`, then one variable-length entry per
/// [`LevaEntry`]: `track_id`(u32), a packed
/// `padding_flag<<7 | assignment_type` byte, and the assignment-type
/// tail (`grouping_type` for type 0; `grouping_type` +
/// `grouping_type_parameter` for type 1; nothing for types 2/3;
/// `sub_track_id` for type 4; nothing for reserved types > 4 โ€” the spec
/// defines no tail length there, so none is written).
///
/// The caller owns the ยง8.8.13.3 conformance constraints the record type
/// cannot express: `level_count` should be โ‰ฅ 2, and the
/// `assignment_type` sequence should be "zero or more of type 2 or 3,
/// followed by zero or more of exactly one type." `assignment_type`
/// values above the 7-bit field (> 127) are rejected rather than
/// silently truncated into the `padding_flag` bit.
pub fn build_leva_box(record: &LevaRecord) -> Result<Vec<u8>> {
    let mut body = Vec::with_capacity(8 + record.entries.len() * 9);
    body.extend_from_slice(&[0u8; 4]); // FullBox(version = 0, flags = 0)
    if record.entries.len() > u8::MAX as usize {
        return Err(Error::invalid("MP4: leva level_count exceeds 255"));
    }
    body.push(record.entries.len() as u8);
    for e in &record.entries {
        if e.assignment_type > 0x7f {
            return Err(Error::invalid(
                "MP4: leva assignment_type exceeds the 7-bit field",
            ));
        }
        body.extend_from_slice(&e.track_id.to_be_bytes());
        let packed = (if e.padding_flag { 0x80 } else { 0 }) | (e.assignment_type & 0x7f);
        body.push(packed);
        match e.assignment_type {
            0 => body.extend_from_slice(&e.grouping_type.to_be_bytes()),
            1 => {
                body.extend_from_slice(&e.grouping_type.to_be_bytes());
                body.extend_from_slice(&e.grouping_type_parameter.to_be_bytes());
            }
            2 | 3 => {}
            4 => body.extend_from_slice(&e.sub_track_id.to_be_bytes()),
            _ => {}
        }
    }
    let mut out = Vec::with_capacity(8 + body.len());
    out.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes());
    out.extend_from_slice(b"leva");
    out.extend_from_slice(&body);
    Ok(out)
}

/// Parse a standalone `csgp` (CompactSampleToGroupBox, ISO/IEC
/// 14496-12:2020 ยง8.9.5) body from `body` (the bytes after the 8/16-byte
/// box header).
///
/// Exposed as a public entry point so tooling that already has the box's
/// payload bytes in hand (a DASH packager, a sample-group editor, a
/// fixture validator) can recover the bit-packed pattern table without
/// re-running `open()`, and so the write side
/// (`sample_groups::build_csgp`) can be round-trip tested against the
/// canonical reader. Returns `Err` for a body shorter than the 4-byte
/// FullBox preamble or with any truncated bit-packed field. The returned
/// [`CsgpBox`] preserves every `sample_group_description_index` verbatim
/// (including the fragment-local high bit when the box came from a
/// `traf`).
pub fn parse_csgp_box(body: &[u8]) -> Result<CsgpBox> {
    parse_csgp(body)
}

/// Parse a standalone `trep` (TrackExtensionPropertiesBox, ISO/IEC
/// 14496-12 ยง8.8.15) body from `body` (the bytes after the 8/16-byte
/// box header).
///
/// Exposed as a public entry point so tooling that already has the
/// box's payload bytes in hand can recover the `track_id` and the
/// type/length list of nested child boxes without re-running `open()`.
/// Returns `Err` for a body shorter than the 4-byte FullBox preamble or
/// one missing its 4-byte `track_id`; returns
/// `Ok(TrepRecord { children: vec![], .. })` for a `trep` carrying just
/// its `track_id` with no child boxes.
pub fn parse_trep_box(body: &[u8]) -> Result<TrepRecord> {
    parse_trep(body)
}

/// Serialise a [`TrepRecord`] into a complete `trep`
/// (TrackExtensionPropertiesBox, ISO/IEC 14496-12 ยง8.8.15) box โ€” 8-byte
/// header (`[size:u32]['trep']`) plus the ยง8.8.15.2 `FullBox(version = 0,
/// flags = 0)` body โ€” for a muxer placing it inside the init-segment
/// `mvex`.
///
/// The body is the FullBox preamble, the 4-byte `track_id`, then each
/// child box in order. The one base-spec-defined child is `assp`
/// (ยง8.8.16): when a [`TrepChild`] carries a `Some(AsspRecord)`, that
/// record is serialised via [`build_assp_box`] (its `fourcc` is then
/// required to be `assp`, and its `payload_len` is ignored โ€” the bytes
/// come from the typed record). A child with `assp == None` is emitted as
/// an empty placeholder box of its `fourcc` with no payload; since this
/// crate does not model arbitrary child payloads, a non-`assp` child with
/// a non-zero `payload_len` is rejected rather than emitting a box whose
/// declared length would not match its (absent) content.
///
/// A round-trip `parse_trep_box(&build_trep_box(rec)?[8..])` reproduces
/// `rec` for records built from typed `assp` children (and bare-track-id
/// records).
pub fn build_trep_box(record: &TrepRecord) -> Result<Vec<u8>> {
    let mut body = Vec::new();
    body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
    body.extend_from_slice(&record.track_id.to_be_bytes());
    for child in &record.children {
        match &child.assp {
            Some(a) => {
                if &child.fourcc != b"assp" {
                    return Err(Error::invalid(
                        "MP4: trep child carries an AsspRecord but its fourcc is not 'assp'",
                    ));
                }
                body.extend_from_slice(&build_assp_box(a)?);
            }
            None => {
                if child.payload_len != 0 {
                    return Err(Error::invalid(
                        "MP4: trep child without a typed record must have payload_len == 0",
                    ));
                }
                // Empty placeholder box: 8-byte header, no payload.
                body.extend_from_slice(&8u32.to_be_bytes());
                body.extend_from_slice(&child.fourcc);
            }
        }
    }
    let total = 8 + body.len();
    let mut out = Vec::with_capacity(total);
    out.extend_from_slice(&(total as u32).to_be_bytes());
    out.extend_from_slice(b"trep");
    out.extend_from_slice(&body);
    Ok(out)
}

/// Parse a standalone `assp` (AlternativeStartupSequencePropertiesBox,
/// ISO/IEC 14496-12 ยง8.8.16) body from `body` (the bytes after the
/// 8/16-byte box header โ€” `assp` is a `FullBox`, so the body opens with
/// the 4-byte version/flags preamble).
///
/// Exposed as a public entry point so tooling that already has the box's
/// payload bytes in hand (an alternative-startup-sequence analyser
/// pairing this with the ยง10.3.2 `alst` sample group, a DASH packager,
/// a fixture validator) can recover the typed [`AsspRecord`] without
/// re-running `open()`. The demuxer also fills this in automatically for
/// the `assp` child of any parsed `trep` (see [`TrepChild::assp`]).
///
/// Returns `Err` for a body shorter than the 4-byte FullBox preamble, a
/// truncated v0 offset / v1 `num_entries`, a v1 `num_entries` that
/// overruns the body, or an unsupported version (only 0 and 1 are
/// defined by ยง8.8.16.1).
pub fn parse_assp_box(body: &[u8]) -> Result<AsspRecord> {
    parse_assp(body)
}

/// Serialise an [`AsspRecord`] into a complete `assp` box โ€” 8-byte
/// header (`[size:u32]['assp']`) plus the ยง8.8.16.2 `FullBox(version,
/// flags = 0)` body โ€” for a muxer placing it inside a `trep`
/// (TrackExtensionPropertiesBox, ยง8.8.15).
///
/// The byte-exact inverse of [`parse_assp_box`]: a v0 record writes the
/// single entry's `min_initial_alt_startup_offset`; a v1 record writes
/// `num_entries` followed by each entry's `(grouping_type_parameter,
/// min_initial_alt_startup_offset)` pair. Rejects a record whose
/// `version` is neither 0 nor 1, a v0 record that does not carry exactly
/// one entry, or a v0 entry that carries a `grouping_type_parameter`
/// (which has no slot in the v0 wire layout) โ€” the builder never emits a
/// box that would not round-trip.
pub fn build_assp_box(record: &AsspRecord) -> Result<Vec<u8>> {
    let body: Vec<u8> = match record.version {
        0 => {
            if record.entries.len() != 1 {
                return Err(Error::invalid("MP4: assp v0 must carry exactly one entry"));
            }
            let e = &record.entries[0];
            if e.grouping_type_parameter.is_some() {
                return Err(Error::invalid(
                    "MP4: assp v0 entry must not carry grouping_type_parameter",
                ));
            }
            let mut b = Vec::with_capacity(4 + 4);
            b.extend_from_slice(&[0, 0, 0, 0]); // version 0 + flags 0
            b.extend_from_slice(&e.min_initial_alt_startup_offset.to_be_bytes());
            b
        }
        1 => {
            let num_entries = record.entries.len();
            if num_entries > u32::MAX as usize {
                return Err(Error::invalid("MP4: assp v1 num_entries exceeds u32"));
            }
            let mut b = Vec::with_capacity(4 + 4 + num_entries * 8);
            b.extend_from_slice(&[1, 0, 0, 0]); // version 1 + flags 0
            b.extend_from_slice(&(num_entries as u32).to_be_bytes());
            for e in &record.entries {
                let gtp = e.grouping_type_parameter.unwrap_or(0);
                b.extend_from_slice(&gtp.to_be_bytes());
                b.extend_from_slice(&e.min_initial_alt_startup_offset.to_be_bytes());
            }
            b
        }
        v => {
            return Err(Error::invalid(format!("MP4: assp unsupported version {v}")));
        }
    };
    let total = 8 + body.len();
    let mut out = Vec::with_capacity(total);
    out.extend_from_slice(&(total as u32).to_be_bytes());
    out.extend_from_slice(b"assp");
    out.extend_from_slice(&body);
    Ok(out)
}

/// Parse a standalone `amve` (AmbientViewingEnvironmentBox, ISO/IEC
/// 14496-12 post-2015 addition) body from `body` (the 8 bytes after the
/// plain 8-byte box header โ€” `amve` is a `Box`, not a `FullBox`, so
/// there is no version/flags preamble).
///
/// Exposed as a public entry point so tooling that already has the box's
/// payload bytes in hand (an HDR-metadata extractor, a HEIF/AVIF
/// item-property reader carrying the same box, a fixture validator) can
/// recover the `(ambient_illuminance, ambient_light_x, ambient_light_y)`
/// triple without re-running `open()`. Returns `Err` for a body shorter
/// than the fixed 8-byte layout; trailing bytes beyond byte 8 (reserved
/// for a future edition) are ignored.
pub fn parse_amve_box(body: &[u8]) -> Result<AmveRecord> {
    parse_amve(body).ok_or_else(|| Error::invalid("MP4: amve too short"))
}

/// Parse a standalone `btrt` (BitRateBox, ISO/IEC 14496-12 ยง8.5.2) body
/// from `body` (the 12 bytes after the plain 8-byte box header โ€” `btrt`
/// is a `Box`, not a `FullBox`, so there is no version/flags preamble).
///
/// Exposed as a public entry point so tooling that already has the box's
/// payload bytes in hand (a bitrate / bandwidth extractor, an ABR
/// packager validating a producer's declared rates, a fixture checker)
/// can recover the `(buffer_size_db, max_bitrate, avg_bitrate)` triple
/// without re-running `open()`. Returns `Err` for a body shorter than
/// the fixed 12-byte layout; trailing bytes beyond byte 12 are ignored.
pub fn parse_btrt_box(body: &[u8]) -> Result<BtrtRecord> {
    parse_btrt(body).ok_or_else(|| Error::invalid("MP4: btrt too short"))
}

/// Parse a standalone `pasp` (PixelAspectRatioBox, ISO/IEC 14496-12
/// ยง12.1.4) body. `Err` for a body shorter than the fixed 8-byte
/// layout; trailing bytes are ignored.
pub fn parse_pasp_box(body: &[u8]) -> Result<PaspRecord> {
    parse_pasp(body).ok_or_else(|| Error::invalid("MP4: pasp too short"))
}

/// Parse a standalone `clap` (CleanApertureBox, ISO/IEC 14496-12
/// ยง12.1.4) body. `Err` for a body shorter than the fixed 32-byte
/// (eight u32) layout; trailing bytes are ignored.
pub fn parse_clap_box(body: &[u8]) -> Result<ClapRecord> {
    parse_clap(body).ok_or_else(|| Error::invalid("MP4: clap too short"))
}

/// Parse a standalone `colr` (ColourInformationBox, ISO/IEC 14496-12
/// ยง12.1.5) body. `Err` for a body shorter than the 4-byte
/// `colour_type` or with a truncated `nclx` payload.
pub fn parse_colr_box(body: &[u8]) -> Result<ColrRecord> {
    parse_colr(body).ok_or_else(|| Error::invalid("MP4: colr malformed"))
}

/// Build a complete `pasp` (PixelAspectRatioBox, ISO/IEC 14496-12
/// ยง12.1.4) box from a [`PaspRecord`]. The byte-exact inverse of
/// [`parse_pasp_box`].
pub fn build_pasp_box(r: &PaspRecord) -> Vec<u8> {
    let mut body = r.h_spacing.to_be_bytes().to_vec();
    body.extend_from_slice(&r.v_spacing.to_be_bytes());
    wrap_box(b"pasp", &body)
}

/// Build a complete `clap` (CleanApertureBox, ISO/IEC 14496-12 ยง12.1.4)
/// box from a [`ClapRecord`]. The byte-exact inverse of
/// [`parse_clap_box`].
pub fn build_clap_box(r: &ClapRecord) -> Vec<u8> {
    let mut body = Vec::with_capacity(32);
    for v in [
        r.width_n,
        r.width_d,
        r.height_n,
        r.height_d,
        r.horiz_off_n,
        r.horiz_off_d,
        r.vert_off_n,
        r.vert_off_d,
    ] {
        body.extend_from_slice(&v.to_be_bytes());
    }
    wrap_box(b"clap", &body)
}

/// Build a complete `colr` (ColourInformationBox, ISO/IEC 14496-12
/// ยง12.1.5) box from a [`ColrRecord`]. The byte-exact inverse of
/// [`parse_colr_box`] (an `nclx` box's seven reserved low bits are
/// written as 0, matching the parser's mask).
pub fn build_colr_box(r: &ColrRecord) -> Vec<u8> {
    let mut body = Vec::new();
    match r {
        ColrRecord::Nclx {
            colour_primaries,
            transfer_characteristics,
            matrix_coefficients,
            full_range,
        } => {
            body.extend_from_slice(b"nclx");
            body.extend_from_slice(&colour_primaries.to_be_bytes());
            body.extend_from_slice(&transfer_characteristics.to_be_bytes());
            body.extend_from_slice(&matrix_coefficients.to_be_bytes());
            body.push(if *full_range { 0x80 } else { 0x00 });
        }
        ColrRecord::RestrictedIcc(d) => {
            body.extend_from_slice(b"rICC");
            body.extend_from_slice(d);
        }
        ColrRecord::UnrestrictedIcc(d) => {
            body.extend_from_slice(b"prof");
            body.extend_from_slice(d);
        }
        ColrRecord::Other { colour_type, data } => {
            body.extend_from_slice(colour_type);
            body.extend_from_slice(data);
        }
    }
    wrap_box(b"colr", &body)
}

/// Parse a standalone `stvi` (StereoVideoBox, ISO/IEC 14496-12
/// ยง8.15.4.2) body from `body` (the bytes after the 4-byte FullBox
/// version/flags preamble โ€” `stvi` is a `FullBox`).
///
/// Exposed as a public entry point so tooling that already has the box's
/// payload bytes in hand (a stereoscopic-video extractor, a
/// restricted-scheme inspector, a fixture validator) can recover the
/// `(single_view_allowed, stereo_scheme, stereo_indication_type)` triple
/// without re-running `open()`. Returns `Err` for a body too short to
/// hold the fixed header, or one whose `length` field overruns the bytes
/// present; trailing optional `any_box` bytes after the
/// `stereo_indication_type` array are ignored.
pub fn parse_stvi_box(body: &[u8]) -> Result<StviRecord> {
    parse_stvi(body).ok_or_else(|| Error::invalid("MP4: stvi malformed"))
}

/// Serialise a [`StviRecord`] into a complete `stvi` box โ€” 8-byte header
/// (`[size:u32]['stvi']`) plus the ยง8.15.4.2.2 `FullBox(version = 0,
/// flags = 0)` body โ€” for a restricted-scheme (`stvi` SchemeType) muxer
/// that places it inside a sample entry's `sinf/schi`.
///
/// The body is the packed `reserved(30)` / `single_view_allowed(2)`
/// word (only the low 2 bits of `single_view_allowed` are written; the
/// reserved bits are zero per ยง8.15.4.2.3), the `stereo_scheme` u32, the
/// `length` u32 derived from `stereo_indication_type.len()`, and the
/// `stereo_indication_type` bytes verbatim. No trailing `any_box` is
/// emitted. The byte-exact inverse of [`parse_stvi_box`] (which consumes
/// the body after the 8-byte header) โ€” a round-trip through the two
/// preserves every field. `length` must fit a `u32`; an indication
/// longer than `u32::MAX` is rejected.
pub fn build_stvi_box(record: &StviRecord) -> Result<Vec<u8>> {
    let length = record.stereo_indication_type.len();
    if length > u32::MAX as usize {
        return Err(Error::invalid("MP4: stvi indication exceeds u32 length"));
    }
    let body_len = 4 + 4 + 4 + 4 + length; // preamble + word + scheme + length + array
    let mut out = Vec::with_capacity(8 + body_len);
    out.extend_from_slice(&((8 + body_len) as u32).to_be_bytes());
    out.extend_from_slice(b"stvi");
    out.extend_from_slice(&[0u8; 4]); // FullBox version 0, flags 0
                                      // First word: reserved(30) = 0 in the high bits, single_view_allowed
                                      // in the low 2 bits.
    out.extend_from_slice(&((record.single_view_allowed as u32) & 0x3).to_be_bytes());
    out.extend_from_slice(&record.stereo_scheme.to_be_bytes());
    out.extend_from_slice(&(length as u32).to_be_bytes());
    out.extend_from_slice(&record.stereo_indication_type);
    Ok(out)
}

use std::io::Read;

fn read_bytes_vec<R: Read + ?Sized>(r: &mut R, n: usize) -> Result<Vec<u8>> {
    // `n` derives from a box size field that is attacker-controlled
    // (`size32` is up to 4 GiB, `largesize` up to 2^64 โˆ’ 1). Don't
    // pre-allocate against an unverified declared length; let
    // `Read::take` cap the read at whatever the input can deliver and
    // grow the buffer to match, then surface a truncation as
    // `Error::invalid`.
    let mut buf = Vec::new();
    r.take(n as u64).read_to_end(&mut buf)?;
    if buf.len() != n {
        return Err(Error::invalid("MP4: truncated box payload"));
    }
    Ok(buf)
}

/// Advance an in-memory `Cursor` by `psz` bytes, clamped at the
/// cursor's end. The intra-box walkers in this module repeatedly do
/// `cur.set_position(cur.position() + psz)` to skip an unknown box's
/// payload, where `psz` derives from an attacker-controlled box-size
/// field. A raw `+` panics on overflow when `psz` is u32::MAX-class
/// and the cursor is already several gigabytes in; a saturating clamp
/// to the buffer end keeps the loop bounded and lets the surrounding
/// `while cur.position() < end` terminate cleanly on the next
/// iteration without dereferencing past the buffer.
fn skip_cursor_bytes<T: AsRef<[u8]>>(cur: &mut std::io::Cursor<T>, psz: usize) {
    let end = cur.get_ref().as_ref().len() as u64;
    let pos = cur.position();
    let next = pos.saturating_add(psz as u64).min(end);
    cur.set_position(next);
}

// Silence unused-import warnings for HashSet / SeekFrom if they become unused later.
#[allow(dead_code)]
fn _unused() -> (HashSet<u32>, SeekFrom) {
    (HashSet::new(), SeekFrom::Start(0))
}

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

    /// Build a minimal esds ES_Descriptor payload that wraps a
    /// DecoderConfigDescriptor whose DecoderSpecificInfo equals `asc`.
    fn build_esds_payload(asc: &[u8]) -> Vec<u8> {
        // DecoderSpecificInfo: tag 0x05, length = asc.len(), body = asc.
        let mut dsi = Vec::new();
        dsi.push(0x05);
        dsi.push(asc.len() as u8);
        dsi.extend_from_slice(asc);

        // DecoderConfigDescriptor: tag 0x04, length = 13 + dsi.len().
        let mut dcd = vec![
            0x04,
            (13 + dsi.len()) as u8,
            0x40,               // object type: AAC
            (0x05 << 2) | 0x01, // stream type audio
        ];
        dcd.extend_from_slice(&[0, 0, 0]); // bufferSizeDB
        dcd.extend_from_slice(&[0, 0, 0, 0]); // maxBitrate
        dcd.extend_from_slice(&[0, 0, 0, 0]); // avgBitrate
        dcd.extend_from_slice(&dsi);

        // SLConfigDescriptor: tag 0x06, length 1, body 0x02.
        let slc = vec![0x06, 0x01, 0x02];

        // ES_Descriptor: tag 0x03, length = 3 + dcd + slc.
        let mut esd = Vec::new();
        esd.push(0x03);
        esd.push((3 + dcd.len() + slc.len()) as u8);
        esd.extend_from_slice(&[0, 0, 0]); // ES_ID + flags
        esd.extend_from_slice(&dcd);
        esd.extend_from_slice(&slc);
        esd
    }

    #[test]
    fn extracts_asc_from_esds() {
        // Typical AAC-LC 44.1 kHz stereo ASC: 0x12, 0x10.
        let asc = [0x12, 0x10];
        let payload = build_esds_payload(&asc);
        let got = parse_esds_dsi(&payload).expect("dsi");
        assert_eq!(got, asc);
    }

    #[test]
    fn handles_ber_multi_byte_length() {
        // Exercise the BER varint path by padding a descriptor length encoded
        // as 0x80 0x02 (two continuation bytes encoding the value 2).
        let asc = [0x11, 0x90];
        // Manually craft: tag 0x03, length encoded as 0x80|0x00, 0x80|0x00, 0x7F & len
        // Build the same ES_Descriptor body and then prefix tag/length directly.
        let mut body = Vec::new();
        body.extend_from_slice(&[0, 0, 0]); // ES_ID + flags

        // DCD with single-byte BER length
        let mut dsi = vec![0x05, asc.len() as u8];
        dsi.extend_from_slice(&asc);
        let mut dcd = vec![0x04, (13 + dsi.len()) as u8, 0x40, (0x05 << 2) | 0x01];
        dcd.extend_from_slice(&[0, 0, 0]);
        dcd.extend_from_slice(&[0, 0, 0, 0]);
        dcd.extend_from_slice(&[0, 0, 0, 0]);
        dcd.extend_from_slice(&dsi);
        body.extend_from_slice(&dcd);
        body.extend_from_slice(&[0x06, 0x01, 0x02]);

        // Prepend ES_Descriptor tag + 2-byte BER length.
        let body_len = body.len();
        assert!(body_len < 128);
        let hi = (body_len >> 7) as u8 | 0x80;
        let lo = (body_len & 0x7F) as u8;
        let mut payload = vec![0x03, hi, lo];
        payload.extend_from_slice(&body);

        let got = parse_esds_dsi(&payload).expect("dsi");
        assert_eq!(got, asc);
    }

    #[test]
    fn rejects_non_es_descriptor() {
        let payload = vec![0x04, 0x01, 0x00];
        assert!(parse_esds_dsi(&payload).is_none());
    }

    /// Build a minimal AudioSampleEntryV0 (28-byte preamble) followed by
    /// an arbitrary child box. Channels 2, sample-size 16, sample-rate
    /// 48000, then `child_fourcc` carrying `child_body`.
    fn build_audio_sample_entry(child_fourcc: &[u8; 4], child_body: &[u8]) -> Vec<u8> {
        let mut out = Vec::with_capacity(28 + 8 + child_body.len());
        // 28-byte preamble: 6 reserved + 2 data_ref_idx + 8 reserved
        // + 2 channels + 2 sample_size + 2 pre_defined + 2 reserved
        // + 4 sample_rate (16.16 fixed).
        out.extend_from_slice(&[0u8; 6]);
        out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
        out.extend_from_slice(&[0u8; 8]); // reserved
        out.extend_from_slice(&2u16.to_be_bytes()); // channels
        out.extend_from_slice(&16u16.to_be_bytes()); // sample_size
        out.extend_from_slice(&[0u8; 4]); // pre_defined + reserved
        out.extend_from_slice(&((48_000u32) << 16).to_be_bytes()); // sample_rate 16.16
                                                                   // Child box: 4-byte size + 4-byte fourcc + body.
        let total = (8 + child_body.len()) as u32;
        out.extend_from_slice(&total.to_be_bytes());
        out.extend_from_slice(child_fourcc);
        out.extend_from_slice(child_body);
        out
    }

    fn fresh_track() -> super::Track {
        super::Track {
            track_id: 0,
            media_type: oxideav_core::MediaType::Audio,
            codec_id_fourcc: [0; 4],
            timescale: 0,
            duration: None,
            channels: None,
            sample_rate: None,
            sample_size_bits: None,
            width: None,
            height: None,
            extradata: Vec::new(),
            esds_oti: None,
            stts: Vec::new(),
            stsc: Vec::new(),
            stsz: Vec::new(),
            chunk_offsets: Vec::new(),
            stss: Vec::new(),
            ctts: Vec::new(),
            elst: Vec::new(),
            elst_timeline: super::ElstTimeline::default(),
            trex: super::TrexDefaults::default(),
            protection_scheme: None,
            tenc: None,
            piff_tenc: None,
            tref: Vec::new(),
            trgr: Vec::new(),
            elng: None,
            kinds: Vec::new(),
            copyrights: Vec::new(),
            tsel: None,
            sub_tracks: Vec::new(),
            cslg: None,
            vmhd: None,
            amve: None,
            stvi: None,
            btrt: None,
            pasp: None,
            clap: None,
            colr: None,
            hmhd: None,
            gmin: None,
            tcmi: None,
            tmcd: None,
            text_entry: None,
            load_settings: None,
            rtp_hint: None,
            mpeg2ts_hint: None,
            hint_stats: crate::hint::HintStatistics::default(),
            dref: None,
            stsh: Vec::new(),
            sbgp: Vec::new(),
            sgpd: Vec::new(),
            csgp: Vec::new(),
            sdtp: Vec::new(),
            stdp: Vec::new(),
            padb: Vec::new(),
            subs: Vec::new(),
            saiz: Vec::new(),
            saio: Vec::new(),
            stsd_entries: Vec::new(),
        }
    }

    /// Build an `enca`-wrapped audio sample entry: the 28-byte audio
    /// preamble (channels 2, 16-bit, 48 kHz) followed by a `sinf` box
    /// carrying `frma` (original FourCC) + `schm` (scheme type). This
    /// mirrors what a CENC-protected AAC track looks like on disk
    /// (ISO/IEC 14496-12 ยง8.12).
    fn build_enca_with_sinf(original: &[u8; 4], scheme: &[u8; 4]) -> Vec<u8> {
        // Preamble: 28 bytes.
        let mut out = Vec::new();
        out.extend_from_slice(&[0u8; 6]);
        out.extend_from_slice(&1u16.to_be_bytes());
        out.extend_from_slice(&[0u8; 8]);
        out.extend_from_slice(&2u16.to_be_bytes());
        out.extend_from_slice(&16u16.to_be_bytes());
        out.extend_from_slice(&[0u8; 4]);
        out.extend_from_slice(&((48_000u32) << 16).to_be_bytes());

        // Build sinf body: frma + schm.
        let mut sinf_body = Vec::new();
        // frma: 8 byte header + 4 byte data_format.
        sinf_body.extend_from_slice(&12u32.to_be_bytes());
        sinf_body.extend_from_slice(b"frma");
        sinf_body.extend_from_slice(original);
        // schm: 8 byte header + 4 byte FullBox version/flags + 4 byte
        // scheme_type + 4 byte scheme_version.
        sinf_body.extend_from_slice(&20u32.to_be_bytes());
        sinf_body.extend_from_slice(b"schm");
        sinf_body.extend_from_slice(&[0u8; 4]); // version + flags
        sinf_body.extend_from_slice(scheme);
        sinf_body.extend_from_slice(&[0u8; 4]); // scheme_version

        // sinf box header + body.
        let sinf_total = (8 + sinf_body.len()) as u32;
        out.extend_from_slice(&sinf_total.to_be_bytes());
        out.extend_from_slice(b"sinf");
        out.extend_from_slice(&sinf_body);
        out
    }

    #[test]
    fn enca_sample_entry_recovers_original_format() {
        // CENC-style: outer FourCC `enca`, original `mp4a` (AAC), scheme
        // `cenc`. Drive the full parse_stsd pathway: build an stsd
        // payload with entry_count=1 and one `enca` entry containing
        // the audio preamble + sinf.
        let entry_body = build_enca_with_sinf(b"mp4a", b"cenc");
        let mut stsd = Vec::new();
        stsd.extend_from_slice(&[0u8; 4]); // FullBox version/flags
        stsd.extend_from_slice(&1u32.to_be_bytes()); // entry_count
        let total = (8 + entry_body.len()) as u32;
        stsd.extend_from_slice(&total.to_be_bytes());
        stsd.extend_from_slice(b"enca");
        stsd.extend_from_slice(&entry_body);

        let mut t = fresh_track();
        super::parse_stsd(&stsd, &mut t).unwrap();
        // Original FourCC recovered from sinf/frma.
        assert_eq!(&t.codec_id_fourcc, b"mp4a");
        // Scheme type from sinf/schm.
        assert_eq!(t.protection_scheme, Some(*b"cenc"));
        // Preamble still parsed (channels populated despite the enc wrap).
        assert_eq!(t.channels, Some(2));
    }

    #[test]
    fn encv_sample_entry_recovers_h264_original() {
        // Video variant: 78-byte preamble + sinf with frma=avc1, schm=cbcs.
        let mut entry_body = Vec::new();
        entry_body.extend_from_slice(&[0u8; 6]);
        entry_body.extend_from_slice(&1u16.to_be_bytes());
        entry_body.extend_from_slice(&[0u8; 16]); // pre_defined/reserved
        entry_body.extend_from_slice(&1280u16.to_be_bytes()); // width
        entry_body.extend_from_slice(&720u16.to_be_bytes()); // height
        entry_body.extend_from_slice(&((72u32) << 16).to_be_bytes()); // horizresolution
        entry_body.extend_from_slice(&((72u32) << 16).to_be_bytes()); // vertresolution
        entry_body.extend_from_slice(&[0u8; 4]); // reserved
        entry_body.extend_from_slice(&1u16.to_be_bytes()); // frame_count
        entry_body.extend_from_slice(&[0u8; 32]); // compressorname
        entry_body.extend_from_slice(&0x0018u16.to_be_bytes()); // depth
        entry_body.extend_from_slice(&(-1i16).to_be_bytes()); // pre_defined
                                                              // Total preamble: 78 bytes.
        assert_eq!(entry_body.len(), 78);

        let mut sinf_body = Vec::new();
        sinf_body.extend_from_slice(&12u32.to_be_bytes());
        sinf_body.extend_from_slice(b"frma");
        sinf_body.extend_from_slice(b"avc1");
        sinf_body.extend_from_slice(&20u32.to_be_bytes());
        sinf_body.extend_from_slice(b"schm");
        sinf_body.extend_from_slice(&[0u8; 4]);
        sinf_body.extend_from_slice(b"cbcs");
        sinf_body.extend_from_slice(&[0u8; 4]);

        let sinf_total = (8 + sinf_body.len()) as u32;
        entry_body.extend_from_slice(&sinf_total.to_be_bytes());
        entry_body.extend_from_slice(b"sinf");
        entry_body.extend_from_slice(&sinf_body);

        let mut stsd = Vec::new();
        stsd.extend_from_slice(&[0u8; 4]);
        stsd.extend_from_slice(&1u32.to_be_bytes());
        let total = (8 + entry_body.len()) as u32;
        stsd.extend_from_slice(&total.to_be_bytes());
        stsd.extend_from_slice(b"encv");
        stsd.extend_from_slice(&entry_body);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_stsd(&stsd, &mut t).unwrap();
        assert_eq!(&t.codec_id_fourcc, b"avc1");
        assert_eq!(t.protection_scheme, Some(*b"cbcs"));
        assert_eq!(t.width, Some(1280));
        assert_eq!(t.height, Some(720));
    }

    /// Build a minimal audio `SampleEntry` body (no codec config children):
    /// the ยง8.5.2.2 8-byte preamble (`reserved[6]` + `data_reference_index`)
    /// followed by the 20-byte AudioSampleEntry v0 tail. `dref` sets the
    /// `data_reference_index`. The returned bytes are the *body* (no box
    /// header).
    fn audio_sample_entry_body(channels: u16, dref: u16) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&[0u8; 6]); // reserved
        out.extend_from_slice(&dref.to_be_bytes()); // data_reference_index
        out.extend_from_slice(&[0u8; 8]); // reserved (2 ร— u32)
        out.extend_from_slice(&channels.to_be_bytes()); // channelcount
        out.extend_from_slice(&16u16.to_be_bytes()); // samplesize
        out.extend_from_slice(&[0u8; 4]); // pre_defined + reserved
        out.extend_from_slice(&((48_000u32) << 16).to_be_bytes()); // samplerate
        out
    }

    /// Wrap a SampleEntry body in its box header (size + FourCC).
    fn boxed_sample_entry(fourcc: &[u8; 4], body: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        let total = (8 + body.len()) as u32;
        out.extend_from_slice(&total.to_be_bytes());
        out.extend_from_slice(fourcc);
        out.extend_from_slice(body);
        out
    }

    /// Assemble a `stsd` body (FullBox header + entry_count + entries).
    fn build_stsd(entries: &[Vec<u8>]) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&[0u8; 4]); // version + flags
        out.extend_from_slice(&(entries.len() as u32).to_be_bytes());
        for e in entries {
            out.extend_from_slice(e);
        }
        out
    }

    #[test]
    fn stsd_records_all_entries_first_drives_active_codec() {
        // Three sample descriptions: mp4a (active), then ac-3 and a
        // hex-rendered non-printable FourCC. ISO/IEC 14496-12 ยง8.5.2 โ€”
        // entry [0] is the active description, [1..] are alternates.
        let e0 = boxed_sample_entry(b"mp4a", &audio_sample_entry_body(2, 1));
        let e1 = boxed_sample_entry(b"ac-3", &audio_sample_entry_body(6, 1));
        let e2 = boxed_sample_entry(&[0x00, 0x01, 0x02, 0x03], &audio_sample_entry_body(1, 2));
        let stsd = build_stsd(&[e0, e1, e2]);

        let mut t = fresh_track();
        super::parse_stsd(&stsd, &mut t).unwrap();

        // Active codec is entry [0].
        assert_eq!(&t.codec_id_fourcc, b"mp4a");
        // Active entry's preamble still drives the audio fields.
        assert_eq!(t.channels, Some(2));

        // All three entries recorded in order with their FourCC + dref.
        assert_eq!(t.stsd_entries.len(), 3);
        assert_eq!(&t.stsd_entries[0].format, b"mp4a");
        assert_eq!(t.stsd_entries[0].data_reference_index, 1);
        assert_eq!(&t.stsd_entries[1].format, b"ac-3");
        assert_eq!(t.stsd_entries[1].data_reference_index, 1);
        assert_eq!(t.stsd_entries[2].format, [0x00, 0x01, 0x02, 0x03]);
        assert_eq!(t.stsd_entries[2].data_reference_index, 2);
    }

    #[test]
    fn build_stream_info_surfaces_multi_stsd_on_options() {
        let e0 = boxed_sample_entry(b"mp4a", &audio_sample_entry_body(2, 1));
        let e1 = boxed_sample_entry(b"ac-3", &audio_sample_entry_body(6, 3));
        let stsd = build_stsd(&[e0, e1]);

        let mut t = fresh_track();
        t.timescale = 48_000;
        super::parse_stsd(&stsd, &mut t).unwrap();

        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        // entry_count surfaced.
        assert_eq!(info.params.options.get("stsd_count"), Some("2"));
        // 1-based keys matching the spec's sample_description_index, with
        // the data_reference_index per entry.
        assert_eq!(info.params.options.get("stsd_1"), Some("mp4a dref=1"));
        assert_eq!(info.params.options.get("stsd_2"), Some("ac-3 dref=3"));
        // No phantom third key.
        assert_eq!(info.params.options.get("stsd_3"), None);
    }

    #[test]
    fn build_stream_info_single_stsd_emits_no_keys() {
        // The overwhelmingly common single-description track surfaces no
        // stsd_* keys โ€” the active codec already carries that info.
        let e0 = boxed_sample_entry(b"mp4a", &audio_sample_entry_body(2, 1));
        let stsd = build_stsd(&[e0]);

        let mut t = fresh_track();
        super::parse_stsd(&stsd, &mut t).unwrap();
        assert_eq!(t.stsd_entries.len(), 1);

        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stsd_count"), None);
        assert_eq!(info.params.options.get("stsd_1"), None);
    }

    #[test]
    fn stsd_overcount_stops_at_present_entries() {
        // A forged entry_count larger than the bytes present: parse stops
        // at what it could read rather than inventing entries or erroring.
        let e0 = boxed_sample_entry(b"mp4a", &audio_sample_entry_body(2, 1));
        let e1 = boxed_sample_entry(b"ac-3", &audio_sample_entry_body(6, 1));
        let mut stsd = Vec::new();
        stsd.extend_from_slice(&[0u8; 4]); // version + flags
        stsd.extend_from_slice(&9u32.to_be_bytes()); // lie: claim 9 entries
        stsd.extend_from_slice(&e0);
        stsd.extend_from_slice(&e1);

        let mut t = fresh_track();
        super::parse_stsd(&stsd, &mut t).unwrap();
        // Only the two real entries are recorded.
        assert_eq!(t.stsd_entries.len(), 2);
        assert_eq!(&t.codec_id_fourcc, b"mp4a");
    }

    /// Build a `tenc` box (ISO/IEC 23001-7 ยง8.2) including its 8-byte
    /// box header (size + `tenc` fourcc).
    fn build_tenc_box_v0(kid: &[u8; 16], iv_size: u8) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version=0 + flags
        body.push(0); // reserved
        body.push(0); // reserved
        body.push(1); // default_isProtected
        body.push(iv_size);
        body.extend_from_slice(kid);
        let mut out = Vec::with_capacity(8 + body.len());
        out.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes());
        out.extend_from_slice(b"tenc");
        out.extend_from_slice(&body);
        out
    }

    fn build_tenc_box_v1_constant_iv(
        kid: &[u8; 16],
        crypt: u8,
        skip: u8,
        const_iv: &[u8],
    ) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 0]); // version=1 + flags
        body.push(0); // reserved
        body.push((crypt << 4) | (skip & 0x0F));
        body.push(1); // default_isProtected
        body.push(0); // default_Per_Sample_IV_Size = 0 โ‡’ constant IV
        body.extend_from_slice(kid);
        body.push(const_iv.len() as u8);
        body.extend_from_slice(const_iv);
        let mut out = Vec::with_capacity(8 + body.len());
        out.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes());
        out.extend_from_slice(b"tenc");
        out.extend_from_slice(&body);
        out
    }

    /// Build a `schi` box containing the given child box bytes
    /// (already framed with their own 8-byte header).
    fn build_schi_box(child: &[u8]) -> Vec<u8> {
        let mut out = Vec::with_capacity(8 + child.len());
        out.extend_from_slice(&((8 + child.len()) as u32).to_be_bytes());
        out.extend_from_slice(b"schi");
        out.extend_from_slice(child);
        out
    }

    /// Build a sinf body with frma + schm + schi (where schi contains
    /// `schi_child` โ€” typically a `tenc`). Mirrors the on-disk shape
    /// for a CENC-protected sample entry's protection scheme info.
    fn build_sinf_body_with_schi(
        original: &[u8; 4],
        scheme: &[u8; 4],
        schi_child: &[u8],
    ) -> Vec<u8> {
        let mut sinf_body = Vec::new();
        // frma
        sinf_body.extend_from_slice(&12u32.to_be_bytes());
        sinf_body.extend_from_slice(b"frma");
        sinf_body.extend_from_slice(original);
        // schm
        sinf_body.extend_from_slice(&20u32.to_be_bytes());
        sinf_body.extend_from_slice(b"schm");
        sinf_body.extend_from_slice(&[0u8; 4]);
        sinf_body.extend_from_slice(scheme);
        sinf_body.extend_from_slice(&[0u8; 4]);
        // schi (containing tenc)
        let schi = build_schi_box(schi_child);
        sinf_body.extend_from_slice(&schi);
        sinf_body
    }

    fn build_enca_with_full_sinf(original: &[u8; 4], scheme: &[u8; 4], tenc_box: &[u8]) -> Vec<u8> {
        // 28-byte audio preamble.
        let mut out = Vec::new();
        out.extend_from_slice(&[0u8; 6]);
        out.extend_from_slice(&1u16.to_be_bytes());
        out.extend_from_slice(&[0u8; 8]);
        out.extend_from_slice(&2u16.to_be_bytes());
        out.extend_from_slice(&16u16.to_be_bytes());
        out.extend_from_slice(&[0u8; 4]);
        out.extend_from_slice(&((48_000u32) << 16).to_be_bytes());
        let sinf_body = build_sinf_body_with_schi(original, scheme, tenc_box);
        let sinf_total = (8 + sinf_body.len()) as u32;
        out.extend_from_slice(&sinf_total.to_be_bytes());
        out.extend_from_slice(b"sinf");
        out.extend_from_slice(&sinf_body);
        out
    }

    #[test]
    fn enca_sample_entry_with_sinf_schi_tenc_populates_track_tenc_v0() {
        // Outer FourCC `enca`, original `mp4a`, scheme `cenc`, with a
        // v0 tenc carrying a 16-byte IV and a synthetic KID.
        let kid: [u8; 16] = [
            0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
            0x88, 0x99,
        ];
        let tenc_box = build_tenc_box_v0(&kid, 16);
        let entry_body = build_enca_with_full_sinf(b"mp4a", b"cenc", &tenc_box);
        let mut stsd = Vec::new();
        stsd.extend_from_slice(&[0u8; 4]);
        stsd.extend_from_slice(&1u32.to_be_bytes());
        let total = (8 + entry_body.len()) as u32;
        stsd.extend_from_slice(&total.to_be_bytes());
        stsd.extend_from_slice(b"enca");
        stsd.extend_from_slice(&entry_body);

        let mut t = fresh_track();
        super::parse_stsd(&stsd, &mut t).unwrap();
        assert_eq!(&t.codec_id_fourcc, b"mp4a");
        assert_eq!(t.protection_scheme, Some(*b"cenc"));
        let tenc = t.tenc.expect("tenc parsed from sinf/schi/tenc");
        assert_eq!(tenc.version, 0);
        assert_eq!(tenc.default_is_protected, 1);
        assert_eq!(tenc.default_per_sample_iv_size, 16);
        assert_eq!(tenc.default_kid, kid);
        assert!(tenc.default_constant_iv.is_none());
    }

    #[test]
    fn encv_sample_entry_v1_pattern_with_constant_iv_lands_on_track() {
        // Build a v1 tenc with pattern 1:9 and an 8-byte constant IV,
        // wrap it in schi/sinf and an `encv` sample entry with scheme
        // `cbcs` (the typical CBC-S + pattern-encryption configuration).
        let kid = [0x01u8; 16];
        let civ = [0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE];
        let tenc_box = build_tenc_box_v1_constant_iv(&kid, 1, 9, &civ);

        // 78-byte video preamble.
        let mut entry_body = Vec::new();
        entry_body.extend_from_slice(&[0u8; 6]);
        entry_body.extend_from_slice(&1u16.to_be_bytes());
        entry_body.extend_from_slice(&[0u8; 16]);
        entry_body.extend_from_slice(&1280u16.to_be_bytes());
        entry_body.extend_from_slice(&720u16.to_be_bytes());
        entry_body.extend_from_slice(&((72u32) << 16).to_be_bytes());
        entry_body.extend_from_slice(&((72u32) << 16).to_be_bytes());
        entry_body.extend_from_slice(&[0u8; 4]);
        entry_body.extend_from_slice(&1u16.to_be_bytes());
        entry_body.extend_from_slice(&[0u8; 32]);
        entry_body.extend_from_slice(&0x0018u16.to_be_bytes());
        entry_body.extend_from_slice(&(-1i16).to_be_bytes());
        assert_eq!(entry_body.len(), 78);

        let sinf_body = build_sinf_body_with_schi(b"avc1", b"cbcs", &tenc_box);
        let sinf_total = (8 + sinf_body.len()) as u32;
        entry_body.extend_from_slice(&sinf_total.to_be_bytes());
        entry_body.extend_from_slice(b"sinf");
        entry_body.extend_from_slice(&sinf_body);

        let mut stsd = Vec::new();
        stsd.extend_from_slice(&[0u8; 4]);
        stsd.extend_from_slice(&1u32.to_be_bytes());
        let total = (8 + entry_body.len()) as u32;
        stsd.extend_from_slice(&total.to_be_bytes());
        stsd.extend_from_slice(b"encv");
        stsd.extend_from_slice(&entry_body);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_stsd(&stsd, &mut t).unwrap();
        assert_eq!(&t.codec_id_fourcc, b"avc1");
        assert_eq!(t.protection_scheme, Some(*b"cbcs"));
        let tenc = t.tenc.expect("tenc parsed from sinf/schi/tenc");
        assert_eq!(tenc.version, 1);
        assert_eq!(tenc.default_crypt_byte_block, 1);
        assert_eq!(tenc.default_skip_byte_block, 9);
        assert_eq!(tenc.default_per_sample_iv_size, 0);
        assert_eq!(tenc.default_constant_iv.as_deref(), Some(&civ[..]));
    }

    #[test]
    fn enca_sample_entry_without_tenc_leaves_track_tenc_none() {
        // Original frma+schm shape (no schi/tenc) โ€” must still parse,
        // and `track.tenc` stays None.
        let entry_body = build_enca_with_sinf(b"mp4a", b"cenc");
        let mut stsd = Vec::new();
        stsd.extend_from_slice(&[0u8; 4]);
        stsd.extend_from_slice(&1u32.to_be_bytes());
        let total = (8 + entry_body.len()) as u32;
        stsd.extend_from_slice(&total.to_be_bytes());
        stsd.extend_from_slice(b"enca");
        stsd.extend_from_slice(&entry_body);

        let mut t = fresh_track();
        super::parse_stsd(&stsd, &mut t).unwrap();
        assert_eq!(&t.codec_id_fourcc, b"mp4a");
        assert_eq!(t.protection_scheme, Some(*b"cenc"));
        assert!(t.tenc.is_none());
    }

    #[test]
    fn subtitle_handler_dispatches_subtitle_media_type() {
        // hdlr body layout: 4 bytes FullBox + 4 bytes pre_defined +
        // 4 bytes handler_type + 12 bytes reserved + name (null-term).
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(&[0u8; 4]); // pre_defined
        body.extend_from_slice(b"subt"); // handler_type
        body.extend_from_slice(&[0u8; 12]); // reserved
        body.extend_from_slice(b"\0");

        let mut t = fresh_track();
        super::parse_hdlr(&body, &mut t).unwrap();
        assert_eq!(t.media_type, oxideav_core::MediaType::Subtitle);

        // And `text` (timed text) also lands on Subtitle.
        let mut body2 = Vec::new();
        body2.extend_from_slice(&[0u8; 4]);
        body2.extend_from_slice(&[0u8; 4]);
        body2.extend_from_slice(b"text");
        body2.extend_from_slice(&[0u8; 12]);
        body2.extend_from_slice(b"\0");

        let mut t2 = fresh_track();
        super::parse_hdlr(&body2, &mut t2).unwrap();
        assert_eq!(t2.media_type, oxideav_core::MediaType::Subtitle);

        // And `sbtl` (QuickTime subtitle handler) also lands on Subtitle.
        let mut body3 = Vec::new();
        body3.extend_from_slice(&[0u8; 4]);
        body3.extend_from_slice(&[0u8; 4]);
        body3.extend_from_slice(b"sbtl");
        body3.extend_from_slice(&[0u8; 12]);
        body3.extend_from_slice(b"\0");

        let mut t3 = fresh_track();
        super::parse_hdlr(&body3, &mut t3).unwrap();
        assert_eq!(t3.media_type, oxideav_core::MediaType::Subtitle);
    }

    #[test]
    fn tx3g_sample_entry_preserves_payload_as_extradata() {
        // tx3g (3GPP TS 26.245) sample entry layout starts with a
        // 6-byte reserved + 2-byte data_reference_index preamble, then
        // 18 bytes of display flags / colours / default text box /
        // default style record. We don't decode the 18 bytes (no
        // 26.245 in docs/) but we preserve them so renderers can.
        let mut entry = Vec::new();
        entry.extend_from_slice(&[0u8; 6]);
        entry.extend_from_slice(&1u16.to_be_bytes());
        // 18 bytes of "tx3g header" โ€” arbitrary recognisable pattern.
        let tx3g_header = [
            0x00, 0x00, 0x00, 0x00, // display_flags
            0x00, 0x00, // horizontal/vertical justification
            0xFF, 0xFF, 0xFF, 0xFF, // background_color_rgba (white)
            0x00, 0x00, 0x00, 0x00, // default text box (top/left)
            0x00, 0x10, 0x00, 0x10, // default text box (bot/right)
        ];
        entry.extend_from_slice(&tx3g_header);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        t.codec_id_fourcc = *b"tx3g";
        super::parse_subtitle_sample_entry(&entry, &mut t).unwrap();
        // Post-preamble bytes preserved verbatim.
        assert_eq!(t.extradata, tx3g_header);
    }

    #[test]
    fn stpp_sample_entry_preserves_xml_namespace_strings() {
        // stpp body: namespace\0schema_location\0auxiliary_mime_types\0
        // โ€” UTF-8 null-terminated strings. We don't split them; we
        // hand the whole post-preamble blob to extradata so the caller
        // can `split('\0')`.
        let mut entry = Vec::new();
        entry.extend_from_slice(&[0u8; 6]);
        entry.extend_from_slice(&1u16.to_be_bytes());
        entry.extend_from_slice(b"http://www.w3.org/ns/ttml\0\0\0");

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        t.codec_id_fourcc = *b"stpp";
        super::parse_subtitle_sample_entry(&entry, &mut t).unwrap();
        assert!(t.extradata.starts_with(b"http://www.w3.org/ns/ttml"));
    }

    #[test]
    fn surfaces_dac3_box_as_extradata() {
        // ETSI TS 102 366 ยงF.4 dac3 specific box body: 3 bytes packing
        // fscod/bsid/bsmod/acmod/lfeon/bit_rate_code. Use a recognisable
        // pattern so the round-trip is visible.
        let dac3 = [0x10, 0x4C, 0x40];
        let entry = build_audio_sample_entry(b"dac3", &dac3);
        let mut t = fresh_track();
        super::parse_audio_sample_entry(&entry, &mut t).unwrap();
        assert_eq!(t.extradata, dac3, "dac3 body should be surfaced verbatim");
        assert_eq!(t.channels, Some(2));
        assert_eq!(t.sample_rate, Some(48_000));
    }

    #[test]
    fn surfaces_dec3_box_as_extradata() {
        // ETSI TS 102 366 ยงG.4 dec3 specific box body โ€” variable length,
        // but the demuxer treats it opaquely. Pick 5 bytes.
        let dec3 = [0x07, 0xC0, 0x20, 0x00, 0x00];
        let entry = build_audio_sample_entry(b"dec3", &dec3);
        let mut t = fresh_track();
        super::parse_audio_sample_entry(&entry, &mut t).unwrap();
        assert_eq!(t.extradata, dec3, "dec3 body should be surfaced verbatim");
    }

    /// Adversarial stsc with `samples_per_chunk = u32::MAX` used to spin
    /// the inner `for 0..spc` loop ~4 billion times per chunk, freezing
    /// the demuxer for an unbounded period on a tiny `n_samples`. The
    /// clamp limits the inner loop to `n_samples` iterations per entry,
    /// so this test must complete in milliseconds, not minutes.
    #[test]
    fn expand_samples_clamps_giant_samples_per_chunk() {
        let mut t = fresh_track();
        t.stsz = vec![1, 1, 1, 1]; // 4 samples
        t.stts = vec![(4, 100)]; // 4 samples ร— delta 100
        t.stsc = vec![(1, u32::MAX, 1)]; // adversarial: spc = 2^32 - 1
        t.chunk_offsets = vec![0, 100, 200, 300]; // 4 chunks
        let mut out = Vec::new();
        let start = std::time::Instant::now();
        super::expand_samples(&t, 0, &mut out).unwrap();
        let elapsed = start.elapsed();
        assert_eq!(out.len(), 4, "should yield exactly 4 samples");
        // 4 chunks ร— 4-sample clamp = 16 inner iterations, well under
        // 1ms. The pre-clamp version takes ~minutes (n_chunks * 4G โ‰ˆ
        // 16 billion iterations). 100ms gives us plenty of headroom
        // while still catching any regression that re-introduces the
        // unbounded loop.
        assert!(
            elapsed.as_millis() < 100,
            "expand_samples spun on adversarial spc: took {elapsed:?}",
        );
    }

    /// `tfdt` v0 carries `base_media_decode_time` as a 32-bit field.
    #[test]
    fn parse_tfdt_v0_carries_32bit_bmdt() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0, 0, 0, 0]); // version 0 + flags
        body.extend_from_slice(&12_345u32.to_be_bytes());
        let bmdt = super::parse_tfdt(&body).unwrap();
        assert_eq!(bmdt, 12_345);
    }

    /// `tfdt` v1 carries `base_media_decode_time` as a 64-bit field.
    #[test]
    fn parse_tfdt_v1_carries_64bit_bmdt() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1, 0, 0, 0]); // version 1 + flags
        body.extend_from_slice(&0x0000_0001_2345_6789u64.to_be_bytes());
        let bmdt = super::parse_tfdt(&body).unwrap();
        assert_eq!(bmdt, 0x0000_0001_2345_6789);
    }

    /// `trun` with explicit per-sample sizes / durations.
    #[test]
    fn parse_trun_extracts_sample_count_size_duration() {
        // flags: data-offset (0x000001) + sample-duration (0x000100)
        //      + sample-size (0x000200) = 0x000301
        let flags: u32 =
            TRUN_DATA_OFFSET_PRESENT | TRUN_SAMPLE_DURATION_PRESENT | TRUN_SAMPLE_SIZE_PRESENT;
        let mut body = Vec::new();
        body.push(0); // version
        body.extend_from_slice(&flags.to_be_bytes()[1..4]); // 24-bit flags
        body.extend_from_slice(&3u32.to_be_bytes()); // sample_count
        body.extend_from_slice(&0x12345678i32.to_be_bytes()); // data_offset
        for (dur, sz) in [(100u32, 50u32), (200, 60), (300, 70)] {
            body.extend_from_slice(&dur.to_be_bytes());
            body.extend_from_slice(&sz.to_be_bytes());
        }
        let mut budget = u64::MAX;
        let parsed = super::parse_trun(&body, &mut budget).unwrap();
        assert_eq!(parsed.data_offset, Some(0x12345678));
        assert_eq!(parsed.samples.len(), 3);
        assert_eq!(parsed.samples[0].duration, Some(100));
        assert_eq!(parsed.samples[0].size, Some(50));
        assert_eq!(parsed.samples[2].duration, Some(300));
        assert_eq!(parsed.samples[2].size, Some(70));
    }

    use super::{TRUN_DATA_OFFSET_PRESENT, TRUN_SAMPLE_DURATION_PRESENT, TRUN_SAMPLE_SIZE_PRESENT};

    /// `trun` with composition-time-offset (B-frames). v1 negative
    /// offsets must be sign-extended.
    #[test]
    fn parse_trun_v1_signed_composition_offset() {
        let flags: u32 = TRUN_SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT;
        let mut body = Vec::new();
        body.push(1); // version 1 โ€” signed cts offsets
        body.extend_from_slice(&flags.to_be_bytes()[1..4]);
        body.extend_from_slice(&2u32.to_be_bytes()); // sample_count
        body.extend_from_slice(&(-50i32).to_be_bytes());
        body.extend_from_slice(&(75i32).to_be_bytes());
        let mut budget = u64::MAX;
        let parsed = super::parse_trun(&body, &mut budget).unwrap();
        assert_eq!(parsed.samples[0].composition_time_offset, Some(-50));
        assert_eq!(parsed.samples[1].composition_time_offset, Some(75));
    }

    use super::TRUN_SAMPLE_COMPOSITION_TIME_OFFSETS_PRESENT;

    /// `trex` populates per-track defaults that the fragment parser
    /// reads when a `tfhd` doesn't override them.
    #[test]
    fn parse_trex_populates_track_defaults() {
        let mut t = fresh_track();
        t.track_id = 7;
        let mut tracks = vec![t];
        // FullBox header + track_ID(7) + DSDI(1) + ddur(1024) + dsiz(0) + dflg(0)
        let mut body = Vec::new();
        body.extend_from_slice(&[0, 0, 0, 0]); // version + flags
        body.extend_from_slice(&7u32.to_be_bytes()); // track_ID
        body.extend_from_slice(&1u32.to_be_bytes()); // DSDI
        body.extend_from_slice(&1024u32.to_be_bytes()); // default_sample_duration
        body.extend_from_slice(&0u32.to_be_bytes()); // default_sample_size
        body.extend_from_slice(&0u32.to_be_bytes()); // default_sample_flags
        super::parse_trex(&body, &mut tracks).unwrap();
        assert_eq!(tracks[0].trex.default_sample_duration, 1024);
        assert_eq!(tracks[0].trex.default_sample_description_index, 1);
    }

    /// Multi-segment `elst` records every entry; the leading-shift
    /// helper picks the first non-empty `media_time`.
    #[test]
    fn parse_elst_v0_multi_segment() {
        // version 0, 2 entries:
        //   (dur=1000, media_time=-1, media_rate=0x10000)  // empty edit
        //   (dur=2000, media_time=500, media_rate=0x10000)
        let mut body = Vec::new();
        body.extend_from_slice(&[0, 0, 0, 0]); // version 0 + flags
        body.extend_from_slice(&2u32.to_be_bytes());
        // entry 1
        body.extend_from_slice(&1000u32.to_be_bytes());
        body.extend_from_slice(&(-1i32).to_be_bytes());
        body.extend_from_slice(&0x0001_0000u32.to_be_bytes());
        // entry 2
        body.extend_from_slice(&2000u32.to_be_bytes());
        body.extend_from_slice(&500i32.to_be_bytes());
        body.extend_from_slice(&0x0001_0000u32.to_be_bytes());
        let mut t = fresh_track();
        super::parse_elst(&body, &mut t).unwrap();
        assert_eq!(t.elst.len(), 2);
        assert_eq!(t.elst[0].media_time, -1);
        assert_eq!(t.elst[1].media_time, 500);
        assert_eq!(t.elst[1].segment_duration, 2000);
        assert_eq!(super::elst_leading_media_time(&t.elst), 500);
    }

    fn elst_entry(dur: u64, mt: i64, rate: u32) -> super::ElstEntry {
        super::ElstEntry {
            segment_duration: dur,
            media_time: mt,
            media_rate: rate,
        }
    }

    const RATE_1: u32 = 0x0001_0000;
    const RATE_0: u32 = 0;

    /// No elst โ†’ identity mapping, everything presented.
    #[test]
    fn elst_timeline_identity_when_absent() {
        let tl = super::build_elst_timeline(&[], 1000, 48_000);
        assert_eq!(tl.delta_for_cts(0), (0, true));
        assert_eq!(tl.delta_for_cts(123_456), (0, true));
    }

    /// Single trim (`media_time > 0`): the mapped delta is `-media_time`
    /// and composition times before it are decode pre-roll (discard).
    #[test]
    fn elst_timeline_initial_trim() {
        let tl = super::build_elst_timeline(&[elst_entry(2000, 1024, RATE_1)], 1000, 48_000);
        assert!(tl.mapped);
        assert_eq!(tl.delta_for_cts(1024), (-1024, true));
        assert_eq!(tl.delta_for_cts(5000), (-1024, true));
        // Pre-roll before the trim point: same delta, not presented.
        assert_eq!(tl.delta_for_cts(0), (-1024, false));
        assert_eq!(tl.delta_for_cts(1023), (-1024, false));
    }

    /// Delay + trim: a leading empty edit pushes the presentation start
    /// out by its (rescaled) duration; movie timescale 1000 vs media
    /// 48000 โ†’ 500 movie ticks = 24000 media ticks.
    #[test]
    fn elst_timeline_empty_edit_delay_rescales_movie_timescale() {
        let elst = [elst_entry(500, -1, RATE_1), elst_entry(3000, 100, RATE_1)];
        let tl = super::build_elst_timeline(&elst, 1000, 48_000);
        assert!(tl.mapped);
        // delta = pres_start(24000) - media_time(100).
        assert_eq!(tl.delta_for_cts(100), (23_900, true));
        assert_eq!(tl.delta_for_cts(0), (23_900, false)); // pre-roll
    }

    /// A dwell (`media_rate` 0) inserts presentation time exactly like
    /// an empty edit: later segments shift out by its duration.
    #[test]
    fn elst_timeline_dwell_inserts_presentation_time() {
        // Movie ts == media ts (1:1 rescale). Segment A maps media
        // [0, 100); a 50-tick dwell holds; segment B maps media
        // [100, 200) starting at presentation 150.
        let elst = [
            elst_entry(100, 0, RATE_1),
            elst_entry(50, 100, RATE_0),
            elst_entry(100, 100, RATE_1),
        ];
        let tl = super::build_elst_timeline(&elst, 1000, 1000);
        assert!(tl.mapped);
        assert_eq!(tl.delta_for_cts(0), (0, true));
        assert_eq!(tl.delta_for_cts(99), (0, true));
        // Media 100 belongs to segment B (pres 150): delta +50.
        assert_eq!(tl.delta_for_cts(100), (50, true));
        assert_eq!(tl.delta_for_cts(199), (50, true));
    }

    /// Media excised between two segments with an inserted empty edit
    /// (deltas stay non-decreasing): the gap samples are delivered
    /// with `presented == false`.
    #[test]
    fn elst_timeline_interior_gap_discards() {
        // Segment A media [0, 100) โ†’ pres [0, 100); empty edit 150;
        // segment B media [200, 300) โ†’ pres [250, 350). Media
        // [100, 200) is never presented.
        let elst = [
            elst_entry(100, 0, RATE_1),
            elst_entry(150, -1, RATE_1),
            elst_entry(100, 200, RATE_1),
        ];
        let tl = super::build_elst_timeline(&elst, 1000, 1000);
        assert!(tl.mapped);
        assert_eq!(tl.delta_for_cts(50), (0, true));
        // Interior gap: previous segment's delta, not presented.
        assert_eq!(tl.delta_for_cts(100), (0, false));
        assert_eq!(tl.delta_for_cts(199), (0, false));
        // Segment B: delta = 250 - 200 = +50.
        assert_eq!(tl.delta_for_cts(200), (50, true));
        // Past the last segment's declared end: tolerated (sloppy
        // durations), still presented.
        assert_eq!(tl.delta_for_cts(305), (50, true));
    }

    /// A media-reordering list (delta moves backwards) falls back to
    /// the leading-shift mapping so DTS stays monotonic.
    #[test]
    fn elst_timeline_non_monotonic_falls_back_to_leading_shift() {
        // Excision with NO padding: seg A media [0,100) โ†’ pres
        // [0,100), seg B media [200,300) โ†’ pres [100,200): delta drops
        // from 0 to -100 โ†’ fallback.
        let elst = [elst_entry(100, 0, RATE_1), elst_entry(100, 200, RATE_1)];
        let tl = super::build_elst_timeline(&elst, 1000, 1000);
        assert!(!tl.mapped);
        // Leading shift = first non-empty media_time = 0 โ†’ identity.
        assert_eq!(tl.delta_for_cts(150), (0, true));
        assert_eq!(tl.delta_for_cts(250), (0, true));
    }

    /// ยง8.6.6.1 zero-duration edit in the initial movie of a
    /// fragmented file: open-ended "from media_time onwards".
    #[test]
    fn elst_timeline_zero_duration_open_ended() {
        let tl = super::build_elst_timeline(&[elst_entry(0, 20, RATE_1)], 1000, 1000);
        assert!(tl.mapped);
        assert_eq!(tl.delta_for_cts(20), (-20, true));
        assert_eq!(tl.delta_for_cts(1_000_000), (-20, true));
        assert_eq!(tl.delta_for_cts(0), (-20, false)); // pre-roll
    }

    /// Hostile v1 magnitudes: u64::MAX segment_duration must saturate,
    /// not wrap or panic, through the movieโ†’media rescale and the
    /// presentation accumulator.
    #[test]
    fn elst_timeline_saturates_on_giant_durations() {
        let elst = [
            elst_entry(u64::MAX, -1, RATE_1),
            elst_entry(u64::MAX, 10, RATE_1),
        ];
        let tl = super::build_elst_timeline(&elst, 1, 48_000);
        // Must not panic; the mapped delta saturates.
        let (d, _) = tl.delta_for_cts(10);
        assert!(d >= 0, "saturated positive delta, got {d}");
        let _ = tl.delta_for_cts(i64::MAX);
        let _ = tl.delta_for_cts(i64::MIN);
    }

    /// A zero movie timescale (malformed mvhd) must not divide by zero;
    /// all durations collapse to 0 (open-ended first segment wins).
    #[test]
    fn elst_timeline_zero_movie_timescale() {
        let tl = super::build_elst_timeline(&[elst_entry(1000, 30, RATE_1)], 0, 48_000);
        assert_eq!(tl.delta_for_cts(30), (-30, true));
        assert_eq!(tl.delta_for_cts(29), (-30, false));
    }

    /// An all-empty edit list (spec-prohibited: the last edit shall
    /// never be empty) degrades to the leading-shift fallback.
    #[test]
    fn elst_timeline_all_empty_list_falls_back() {
        let tl = super::build_elst_timeline(&[elst_entry(100, -1, RATE_1)], 1000, 1000);
        assert!(!tl.mapped);
        assert_eq!(tl.delta_for_cts(0), (0, true));
    }

    /// `build_elst_box` โ†’ `parse_elst_box` round-trips typed entries
    /// through the v0 (32-bit) layout when every value fits.
    #[test]
    fn elst_box_roundtrip_v0() {
        let entries = [
            super::EditListEntry {
                segment_duration: 500,
                media_time: -1,
                media_rate_integer: 1,
                media_rate_fraction: 0,
            },
            super::EditListEntry {
                segment_duration: 3000,
                media_time: 1024,
                media_rate_integer: 1,
                media_rate_fraction: 0,
            },
        ];
        let built = super::build_elst_box(&entries).unwrap();
        assert_eq!(&built[4..8], b"elst");
        assert_eq!(built[8], 0, "v0 when values fit 32 bits");
        let parsed = super::parse_elst_box(&built[8..]).unwrap();
        assert_eq!(parsed, entries);
    }

    /// Values past the 32-bit widths auto-promote the box to v1 and
    /// still round-trip.
    #[test]
    fn elst_box_roundtrip_v1_promotion() {
        let entries = [super::EditListEntry {
            segment_duration: u32::MAX as u64 + 1,
            media_time: i32::MAX as i64 + 7,
            media_rate_integer: 1,
            media_rate_fraction: 0,
        }];
        let built = super::build_elst_box(&entries).unwrap();
        assert_eq!(built[8], 1, "v1 for over-32-bit values");
        let parsed = super::parse_elst_box(&built[8..]).unwrap();
        assert_eq!(parsed, entries);
    }

    /// A dwell entry (`media_rate_integer = 0`) is legal and preserved.
    #[test]
    fn elst_box_roundtrip_dwell() {
        let entries = [
            super::EditListEntry {
                segment_duration: 100,
                media_time: 0,
                media_rate_integer: 1,
                media_rate_fraction: 0,
            },
            super::EditListEntry {
                segment_duration: 50,
                media_time: 100,
                media_rate_integer: 0,
                media_rate_fraction: 0,
            },
            super::EditListEntry {
                segment_duration: 100,
                media_time: 100,
                media_rate_integer: 1,
                media_rate_fraction: 0,
            },
        ];
        let built = super::build_elst_box(&entries).unwrap();
        let parsed = super::parse_elst_box(&built[8..]).unwrap();
        assert_eq!(parsed, entries);
    }

    /// ยง8.6.6.3 round-trip rejections: bad rate, trailing empty edit,
    /// sub-sentinel media_time, empty list.
    #[test]
    fn elst_box_build_rejections() {
        let normal = super::EditListEntry {
            segment_duration: 100,
            media_time: 0,
            media_rate_integer: 1,
            media_rate_fraction: 0,
        };
        // media_rate_integer outside {0, 1}.
        let mut bad_rate = normal;
        bad_rate.media_rate_integer = 2;
        assert!(super::build_elst_box(&[bad_rate]).is_err());
        let mut neg_rate = normal;
        neg_rate.media_rate_integer = -1;
        assert!(super::build_elst_box(&[neg_rate]).is_err());
        // Final empty edit.
        let empty_edit = super::EditListEntry {
            segment_duration: 100,
            media_time: -1,
            media_rate_integer: 1,
            media_rate_fraction: 0,
        };
        assert!(super::build_elst_box(&[normal, empty_edit]).is_err());
        // Leading empty edit is fine.
        assert!(super::build_elst_box(&[empty_edit, normal]).is_ok());
        // media_time below the -1 sentinel.
        let mut sub_sentinel = normal;
        sub_sentinel.media_time = -2;
        assert!(super::build_elst_box(&[sub_sentinel]).is_err());
        // Empty list.
        assert!(super::build_elst_box(&[]).is_err());
    }

    /// `parse_elst_box` rejects truncated bodies: shorter than the
    /// FullBox+count header, and shorter than the declared entries.
    #[test]
    fn elst_box_parse_truncation() {
        assert!(super::parse_elst_box(&[]).is_err());
        assert!(super::parse_elst_box(&[0u8; 7]).is_err());
        // Declares 2 v0 entries but carries bytes for 1.
        let mut body = vec![0u8; 4];
        body.extend_from_slice(&2u32.to_be_bytes());
        body.extend_from_slice(&[0u8; 12]);
        assert!(super::parse_elst_box(&body).is_err());
    }

    /// ยง8.3.3 โ€” `tref` carrying a single `chap` reference resolves to one
    /// child box of body `[u32 track_ID]`. The reference type is the
    /// child's FourCC; the body is a packed big-endian u32 array.
    #[test]
    fn parse_tref_chap_single_id() {
        // Inner TrackReferenceTypeBox: size(12) "chap" track_ID(3)
        let inner = wrap_box_full_size(b"chap", &3u32.to_be_bytes());
        // Outer `tref` body is just the concatenation of inner boxes.
        let mut t = fresh_track();
        super::parse_tref(&inner, &mut t).unwrap();
        assert_eq!(t.tref.len(), 1);
        assert_eq!(&t.tref[0].0, b"chap");
        assert_eq!(t.tref[0].1, vec![3]);
    }

    /// Multiple typed references in one `tref` are surfaced in order.
    #[test]
    fn parse_tref_multiple_types() {
        let mut body = Vec::new();
        // subt โ†’ tracks 4, 5
        let mut subt_payload = Vec::new();
        subt_payload.extend_from_slice(&4u32.to_be_bytes());
        subt_payload.extend_from_slice(&5u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"subt", &subt_payload));
        // cdsc โ†’ track 2
        body.extend(wrap_box_full_size(b"cdsc", &2u32.to_be_bytes()));
        let mut t = fresh_track();
        super::parse_tref(&body, &mut t).unwrap();
        assert_eq!(t.tref.len(), 2);
        assert_eq!(&t.tref[0].0, b"subt");
        assert_eq!(t.tref[0].1, vec![4, 5]);
        assert_eq!(&t.tref[1].0, b"cdsc");
        assert_eq!(t.tref[1].1, vec![2]);
    }

    /// ยง8.3.3.3 โ€” `track_ID` is never zero; we silently drop zeros from
    /// the array rather than rejecting the file.
    #[test]
    fn parse_tref_drops_zero_track_ids() {
        let mut payload = Vec::new();
        payload.extend_from_slice(&0u32.to_be_bytes());
        payload.extend_from_slice(&7u32.to_be_bytes());
        let body = wrap_box_full_size(b"font", &payload);
        let mut t = fresh_track();
        super::parse_tref(&body, &mut t).unwrap();
        assert_eq!(t.tref.len(), 1);
        assert_eq!(t.tref[0].1, vec![7]);
    }

    /// Sub-box body that isn't a multiple of 4 bytes is a structural
    /// error โ€” we surface it as `Error::Invalid` rather than silently
    /// padding or truncating.
    #[test]
    fn parse_tref_misaligned_child_rejected() {
        let body = wrap_box_full_size(b"hint", &[0u8, 0, 0, 1, 0xFF]); // 5 bytes
        let mut t = fresh_track();
        let err = super::parse_tref(&body, &mut t).unwrap_err();
        assert!(matches!(err, oxideav_core::Error::InvalidData(_)));
    }

    /// Spec says at most one TrackReferenceTypeBox per reference_type
    /// inside a `tref`. If a malformed file repeats one, the first wins
    /// and subsequent duplicates are ignored.
    #[test]
    fn parse_tref_duplicate_type_keeps_first() {
        let mut body = Vec::new();
        body.extend(wrap_box_full_size(b"subt", &1u32.to_be_bytes()));
        body.extend(wrap_box_full_size(b"subt", &2u32.to_be_bytes()));
        let mut t = fresh_track();
        super::parse_tref(&body, &mut t).unwrap();
        assert_eq!(t.tref.len(), 1);
        assert_eq!(t.tref[0].1, vec![1]);
    }

    /// Empty outer `tref` (no inner boxes) parses cleanly and yields no
    /// references.
    #[test]
    fn parse_tref_empty_body_is_ok() {
        let mut t = fresh_track();
        super::parse_tref(&[], &mut t).unwrap();
        assert!(t.tref.is_empty());
    }

    /// `build_tref_box` is the byte-exact inverse of `parse_tref`: a
    /// multi-type reference set re-parses to the same `(type, ids)` pairs.
    #[test]
    fn build_tref_round_trips_multiple_types() {
        let refs = vec![
            (*b"subt", vec![4u32, 5]),
            (*b"cdsc", vec![2u32]),
            (*b"chap", vec![3u32]),
        ];
        let boxed = super::build_tref_box(&refs).unwrap();
        // Outer box is a plain `tref` container (8-byte header).
        assert_eq!(&boxed[4..8], b"tref");
        let mut t = fresh_track();
        super::parse_tref(&boxed[8..], &mut t).unwrap();
        assert_eq!(t.tref, refs);
    }

    /// An empty `track_IDs` array for a type is legal (box references
    /// nothing) and round-trips to an empty list.
    #[test]
    fn build_tref_empty_id_array() {
        let refs = vec![(*b"hint", Vec::<u32>::new())];
        let boxed = super::build_tref_box(&refs).unwrap();
        let mut t = fresh_track();
        super::parse_tref(&boxed[8..], &mut t).unwrap();
        // An all-empty child contributes a `(type, [])` pair.
        assert_eq!(t.tref.len(), 1);
        assert_eq!(&t.tref[0].0, b"hint");
        assert!(t.tref[0].1.is_empty());
    }

    /// ยง8.3.3.3 โ€” a zero `track_ID` is rejected (it would be dropped by
    /// the parser, breaking round-trip).
    #[test]
    fn build_tref_rejects_zero_id() {
        let refs = vec![(*b"font", vec![0u32])];
        assert!(super::build_tref_box(&refs).is_none());
    }

    /// No reference pairs yields a bare empty `tref` container.
    #[test]
    fn build_tref_empty_set() {
        let boxed = super::build_tref_box(&[]).unwrap();
        assert_eq!(boxed.len(), 8);
        assert_eq!(&boxed[4..8], b"tref");
    }

    /// Track references surface on `StreamInfo.params.options` as
    /// `tref_<type>` keys whose value is a space-separated track-ID
    /// list. Reference types with no IDs (after dropping zeros) are
    /// suppressed.
    #[test]
    fn build_stream_info_surfaces_tref_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        t.codec_id_fourcc = *b"tx3g";
        t.timescale = 1000;
        t.tref.push((*b"subt", vec![10, 11]));
        t.tref.push((*b"font", vec![20]));
        t.tref.push((*b"hint", vec![])); // empty after-zero strip: suppressed.
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("tref_subt"), Some("10 11"));
        assert_eq!(info.params.options.get("tref_font"), Some("20"));
        assert_eq!(info.params.options.get("tref_hint"), None);
    }

    /// ยง8.3.4 โ€” `trgr` carrying a single `msrc` TrackGroupTypeBox child
    /// produces one `(track_group_type, track_group_id)` entry on the
    /// track. The FullBox preamble is 4 bytes of zeros (version + 24-bit
    /// flags, both spec-pinned to 0), followed by the 32-bit
    /// `track_group_id`.
    #[test]
    fn parse_trgr_msrc_single_child() {
        // Inner TrackGroupTypeBox: size(16) "msrc" [v+flags=0] track_group_id=42
        let mut inner_body = Vec::new();
        inner_body.extend_from_slice(&[0u8; 4]); // FullBox v0 + flags=0
        inner_body.extend_from_slice(&42u32.to_be_bytes());
        let body = wrap_box_full_size(b"msrc", &inner_body);
        let mut t = fresh_track();
        super::parse_trgr(&body, &mut t).unwrap();
        assert_eq!(t.trgr.len(), 1);
        assert_eq!(&t.trgr[0].0, b"msrc");
        assert_eq!(t.trgr[0].1, 42);
    }

    /// Multiple typed children inside one `trgr` are surfaced in
    /// encounter order. Different types coexist: `msrc` (spec-named) plus
    /// a hypothetical derived-spec FourCC.
    #[test]
    fn parse_trgr_multiple_types() {
        let mut body = Vec::new();
        let mut msrc_payload = Vec::new();
        msrc_payload.extend_from_slice(&[0u8; 4]); // FullBox
        msrc_payload.extend_from_slice(&7u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"msrc", &msrc_payload));
        let mut foo_payload = Vec::new();
        foo_payload.extend_from_slice(&[0u8; 4]); // FullBox
        foo_payload.extend_from_slice(&99u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"foo ", &foo_payload));
        let mut t = fresh_track();
        super::parse_trgr(&body, &mut t).unwrap();
        assert_eq!(t.trgr.len(), 2);
        assert_eq!(&t.trgr[0].0, b"msrc");
        assert_eq!(t.trgr[0].1, 7);
        assert_eq!(&t.trgr[1].0, b"foo ");
        assert_eq!(t.trgr[1].1, 99);
    }

    /// Spec leaves the door open for two children of the same
    /// `track_group_type` on the same track; we preserve both rather
    /// than de-duplicating (unlike `tref` where the spec explicitly
    /// caps at one entry per type).
    #[test]
    fn parse_trgr_repeated_type_kept_in_order() {
        let mut body = Vec::new();
        let mut p1 = Vec::new();
        p1.extend_from_slice(&[0u8; 4]);
        p1.extend_from_slice(&1u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"msrc", &p1));
        let mut p2 = Vec::new();
        p2.extend_from_slice(&[0u8; 4]);
        p2.extend_from_slice(&2u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"msrc", &p2));
        let mut t = fresh_track();
        super::parse_trgr(&body, &mut t).unwrap();
        assert_eq!(t.trgr.len(), 2);
        assert_eq!(t.trgr[0].1, 1);
        assert_eq!(t.trgr[1].1, 2);
    }

    /// A child whose body is shorter than the 8-byte preamble + id is a
    /// structural error. We surface it as `Error::InvalidData` rather
    /// than silently skipping (which would mask corruption).
    #[test]
    fn parse_trgr_short_child_rejected() {
        // 7-byte body: FullBox preamble + only 3 bytes where the id
        // should go.
        let body = wrap_box_full_size(b"msrc", &[0u8, 0, 0, 0, 0, 0, 0]);
        let mut t = fresh_track();
        let err = super::parse_trgr(&body, &mut t).unwrap_err();
        assert!(matches!(err, oxideav_core::Error::InvalidData(_)));
    }

    /// ยง8.3.4.2 pins `version = 0`. A non-zero version is a
    /// forward-compatible extension we cannot decode safely โ€” skip the
    /// child rather than mis-parsing it. The remaining children of the
    /// same `trgr` continue to be processed.
    #[test]
    fn parse_trgr_skips_unknown_version_child() {
        let mut body = Vec::new();
        // Child 1: version = 1, skip.
        let mut p1 = Vec::new();
        p1.extend_from_slice(&[1u8, 0, 0, 0]); // version = 1
        p1.extend_from_slice(&5u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"msrc", &p1));
        // Child 2: version = 0, kept.
        let mut p2 = Vec::new();
        p2.extend_from_slice(&[0u8; 4]);
        p2.extend_from_slice(&8u32.to_be_bytes());
        body.extend(wrap_box_full_size(b"msrc", &p2));
        let mut t = fresh_track();
        super::parse_trgr(&body, &mut t).unwrap();
        assert_eq!(t.trgr.len(), 1);
        assert_eq!(t.trgr[0].1, 8);
    }

    /// Trailing bytes beyond `track_group_id` are reserved for derived
    /// specs. We ignore them at this layer โ€” the file is still valid and
    /// the id is still recovered.
    #[test]
    fn parse_trgr_ignores_trailing_extension_bytes() {
        let mut inner_body = Vec::new();
        inner_body.extend_from_slice(&[0u8; 4]); // FullBox
        inner_body.extend_from_slice(&13u32.to_be_bytes());
        inner_body.extend_from_slice(&[0xCA, 0xFE, 0xBA, 0xBE]); // extension
        let body = wrap_box_full_size(b"msrc", &inner_body);
        let mut t = fresh_track();
        super::parse_trgr(&body, &mut t).unwrap();
        assert_eq!(t.trgr.len(), 1);
        assert_eq!(t.trgr[0].1, 13);
    }

    /// Empty outer `trgr` (no inner boxes) parses cleanly and yields no
    /// entries.
    #[test]
    fn parse_trgr_empty_body_is_ok() {
        let mut t = fresh_track();
        super::parse_trgr(&[], &mut t).unwrap();
        assert!(t.trgr.is_empty());
    }

    /// `build_trgr_box` is the byte-exact inverse of `parse_trgr`: a
    /// multi-type group set re-parses to the same `(type, id)` pairs.
    #[test]
    fn build_trgr_round_trips() {
        let groups = vec![(*b"msrc", 17u32), (*b"ster", 42u32)];
        let boxed = super::build_trgr_box(&groups);
        assert_eq!(&boxed[4..8], b"trgr");
        let mut t = fresh_track();
        super::parse_trgr(&boxed[8..], &mut t).unwrap();
        assert_eq!(t.trgr, groups);
    }

    /// No group pairs yields a bare empty `trgr` container.
    #[test]
    fn build_trgr_empty_set() {
        let boxed = super::build_trgr_box(&[]);
        assert_eq!(boxed.len(), 8);
        assert_eq!(&boxed[4..8], b"trgr");
        let mut t = fresh_track();
        super::parse_trgr(&boxed[8..], &mut t).unwrap();
        assert!(t.trgr.is_empty());
    }

    /// `parse_trak` accepts a `trgr` box nested under `trak` and lands
    /// its child entries on the resulting Track. Confirms the routing
    /// glue inside `parse_trak`'s box match (not just the standalone
    /// parser).
    #[test]
    fn parse_trak_picks_up_nested_trgr() {
        // Build a minimal trak: tkhd + mdia (mdhd + hdlr + minf/stbl
        // pre-baked elsewhere is not needed โ€” parse_trak only requires
        // an mdia to consider the track "has_media", and parse_mdia
        // walks its own children). Mirror the kind-nested test setup.
        let mut tkhd = vec![0u8; 92]; // FullBox v0 + 84 bytes
        tkhd[12..16].copy_from_slice(&1u32.to_be_bytes()); // track_id = 1

        let mut mdhd = vec![0u8; 24];
        mdhd[12..16].copy_from_slice(&1000u32.to_be_bytes()); // timescale

        let mut hdlr = Vec::new();
        hdlr.extend_from_slice(&[0u8; 8]); // FullBox + pre_defined
        hdlr.extend_from_slice(b"vide"); // handler_type
        hdlr.extend_from_slice(&[0u8; 12]); // reserved[3]
        hdlr.extend_from_slice(b"\0"); // name (empty C string)

        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"hdlr", &hdlr));

        // trgr containing one msrc child with track_group_id = 555.
        let mut trgr_body = Vec::new();
        let mut msrc_body = Vec::new();
        msrc_body.extend_from_slice(&[0u8; 4]); // FullBox
        msrc_body.extend_from_slice(&555u32.to_be_bytes());
        trgr_body.extend(wrap_box_full_size(b"msrc", &msrc_body));

        let mut trak = Vec::new();
        trak.extend(wrap_box_full_size(b"tkhd", &tkhd));
        trak.extend(wrap_box_full_size(b"mdia", &mdia));
        trak.extend(wrap_box_full_size(b"trgr", &trgr_body));

        let t = super::parse_trak(&trak, 1 << 30).unwrap().unwrap();
        assert_eq!(t.trgr.len(), 1);
        assert_eq!(&t.trgr[0].0, b"msrc");
        assert_eq!(t.trgr[0].1, 555);
    }

    /// Track groups surface on `StreamInfo.params.options` as
    /// `trgr_<n>` keys whose value is `"<type> <id>"`. Mirrors the
    /// `kind_<n>` two-field convention.
    #[test]
    fn build_stream_info_surfaces_trgr_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90_000;
        t.trgr.push((*b"msrc", 7));
        t.trgr.push((*b"msrc", 42)); // second of same type still surfaced.
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("trgr_0"), Some("msrc 7"));
        assert_eq!(info.params.options.get("trgr_1"), Some("msrc 42"));
    }

    /// `elng` (ExtendedLanguageBox ยง8.4.6): FullBox preamble + a
    /// NULL-terminated BCP 47 tag. The parsed tag (without the NUL) is
    /// stored on the track.
    #[test]
    fn parse_elng_reads_bcp47_tag() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox version+flags
        body.extend_from_slice(b"en-US\0"); // NULL-terminated tag
        let mut t = fresh_track();
        super::parse_elng(&body, &mut t);
        assert_eq!(t.elng.as_deref(), Some("en-US"));
    }

    /// A tag with region+script subtags (`zh-Hant-HK`) round-trips, and a
    /// tag without an explicit NUL terminator (technically malformed but
    /// tolerated) still parses.
    #[test]
    fn parse_elng_subtags_and_missing_nul() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"zh-Hant-HK\0");
        let mut t = fresh_track();
        super::parse_elng(&body, &mut t);
        assert_eq!(t.elng.as_deref(), Some("zh-Hant-HK"));

        // No trailing NUL: read to end of body.
        let mut body2 = Vec::new();
        body2.extend_from_slice(&[0u8; 4]);
        body2.extend_from_slice(b"fr-FR");
        let mut t2 = fresh_track();
        super::parse_elng(&body2, &mut t2);
        assert_eq!(t2.elng.as_deref(), Some("fr-FR"));
    }

    /// A too-short or empty-string `elng` leaves the track with no
    /// extended language and never panics.
    #[test]
    fn parse_elng_malformed_is_silently_skipped() {
        // Only 3 bytes โ€” shorter than the FullBox preamble.
        let mut t = fresh_track();
        super::parse_elng(&[0, 0, 0], &mut t);
        assert_eq!(t.elng, None);

        // FullBox preamble then an immediate NUL (empty tag).
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.push(0);
        let mut t2 = fresh_track();
        super::parse_elng(&body, &mut t2);
        assert_eq!(t2.elng, None);
    }

    /// The extended language tag surfaces on
    /// `StreamInfo.params.options["language"]`.
    #[test]
    fn build_stream_info_surfaces_elng_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        t.elng = Some("de-DE".to_string());
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("language"), Some("de-DE"));
    }

    /// No `elng` box โ†’ no `language` option (caller falls back to mdhd).
    #[test]
    fn build_stream_info_no_elng_no_language_option() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("language"), None);
    }

    /// End-to-end: an `elng` box nested inside `mdia` is picked up by
    /// `parse_mdia` and lands on the track.
    #[test]
    fn parse_mdia_picks_up_nested_elng() {
        // Minimal mdhd (v0, 24 bytes) so timescale is set, then elng.
        let mut mdhd = Vec::new();
        mdhd.extend_from_slice(&[0u8; 4]); // version+flags
        mdhd.extend_from_slice(&[0u8; 8]); // creation+modification time
        mdhd.extend_from_slice(&1000u32.to_be_bytes()); // timescale
        mdhd.extend_from_slice(&0u32.to_be_bytes()); // duration
        mdhd.extend_from_slice(&[0u8; 4]); // language + pre_defined

        let mut elng = Vec::new();
        elng.extend_from_slice(&[0u8; 4]);
        elng.extend_from_slice(b"es-419\0");

        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"elng", &elng));

        let mut t = fresh_track();
        super::parse_mdia(&mdia, &mut t, 1 << 30).unwrap();
        assert_eq!(t.timescale, 1000);
        assert_eq!(t.elng.as_deref(), Some("es-419"));
    }

    /// Build a self-contained Box (size + FourCC + payload, 32-bit
    /// size field). Used as a building block for stuffing typed
    /// reference children into a synthetic `tref` body.
    fn wrap_box_full_size(fourcc: &[u8; 4], payload: &[u8]) -> Vec<u8> {
        let total = (8 + payload.len()) as u32;
        let mut out = Vec::with_capacity(total as usize);
        out.extend_from_slice(&total.to_be_bytes());
        out.extend_from_slice(fourcc);
        out.extend_from_slice(payload);
        out
    }

    /// ยง8.10.4 โ€” `kind` (KindBox): FullBox preamble + NULL-terminated
    /// schemeURI + NULL-terminated value. When the value is empty
    /// (URI alone identifies the kind) the body is `<FullBox><URI>\0\0`.
    #[test]
    fn parse_kind_uri_only() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox version+flags
        body.extend_from_slice(b"urn:mpeg:dash:role:2011\0");
        body.extend_from_slice(b"\0"); // empty value
        let mut t = fresh_track();
        super::parse_kind(&body, &mut t);
        assert_eq!(t.kinds.len(), 1);
        assert_eq!(t.kinds[0].0, "urn:mpeg:dash:role:2011");
        assert_eq!(t.kinds[0].1, "");
    }

    /// A kind with both URI and value: the URI identifies the naming
    /// scheme and the value is the kind name within that scheme. The
    /// canonical DASH example: scheme = `urn:mpeg:dash:role:2011`,
    /// value = `main`.
    #[test]
    fn parse_kind_uri_and_value() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"urn:mpeg:dash:role:2011\0");
        body.extend_from_slice(b"main\0");
        let mut t = fresh_track();
        super::parse_kind(&body, &mut t);
        assert_eq!(t.kinds.len(), 1);
        assert_eq!(t.kinds[0].0, "urn:mpeg:dash:role:2011");
        assert_eq!(t.kinds[0].1, "main");
    }

    /// A box that lacks the trailing value NUL is tolerated โ€” the
    /// value string is taken up to the end of the box. Matches the
    /// `parse_elng` posture for optional-string boxes.
    #[test]
    fn parse_kind_missing_value_nul_tolerated() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"urn:example:role\0");
        body.extend_from_slice(b"alt"); // no trailing NUL
        let mut t = fresh_track();
        super::parse_kind(&body, &mut t);
        assert_eq!(t.kinds.len(), 1);
        assert_eq!(t.kinds[0].0, "urn:example:role");
        assert_eq!(t.kinds[0].1, "alt");
    }

    /// Empty URI (just two NULs) yields no kind โ€” a kind with no URI
    /// has nothing to identify.
    #[test]
    fn parse_kind_empty_uri_dropped() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"\0\0");
        let mut t = fresh_track();
        super::parse_kind(&body, &mut t);
        assert!(t.kinds.is_empty());
    }

    /// A too-short body (smaller than the FullBox preamble) is
    /// silently skipped โ€” the box is informational and a malformed
    /// entry should never abort the demux.
    #[test]
    fn parse_kind_too_short_is_silently_skipped() {
        let mut t = fresh_track();
        super::parse_kind(&[0, 0, 0], &mut t);
        assert!(t.kinds.is_empty());
    }

    /// Track-level `udta` may carry multiple `kind` boxes from
    /// different naming schemes โ€” the spec note allows it ("two
    /// schemes that both define a kind that indicates sub-titles").
    /// Each lands as a distinct entry, preserved in encounter order.
    #[test]
    fn parse_track_udta_collects_multiple_kinds() {
        // Two kinds: a DASH role and a custom scheme.
        let mut k1 = Vec::new();
        k1.extend_from_slice(&[0u8; 4]);
        k1.extend_from_slice(b"urn:mpeg:dash:role:2011\0");
        k1.extend_from_slice(b"caption\0");
        let mut k2 = Vec::new();
        k2.extend_from_slice(&[0u8; 4]);
        k2.extend_from_slice(b"urn:apple:hap:subtitles\0\0");

        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"kind", &k1));
        udta.extend(wrap_box_full_size(b"kind", &k2));

        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        assert_eq!(t.kinds.len(), 2);
        assert_eq!(t.kinds[0].0, "urn:mpeg:dash:role:2011");
        assert_eq!(t.kinds[0].1, "caption");
        assert_eq!(t.kinds[1].0, "urn:apple:hap:subtitles");
        assert_eq!(t.kinds[1].1, "");
    }

    #[test]
    fn parse_track_udta_picks_up_hinf() {
        let stats = crate::hint::HintStatistics {
            bytes_sent_with_rtp_64: Some(123_456),
            packets_sent_64: Some(789),
            ..crate::hint::HintStatistics::default()
        };
        let hinf = crate::hint::build_hinf_box(&stats);
        let mut udta = Vec::new();
        udta.extend_from_slice(&hinf);
        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        assert_eq!(t.hint_stats, stats);
        assert_eq!(t.hint_stats.bytes_sent_with_rtp_64, Some(123_456));
    }

    /// Non-`kind` children inside a track-level `udta` are skipped
    /// (file-wide metadata is the moov-level `udta` parser's job).
    #[test]
    fn parse_track_udta_ignores_non_kind_children() {
        // A `titl` (3GPP title) inside a track-level udta: not a kind,
        // shouldn't crash, and shouldn't populate the kinds list.
        let mut titl = Vec::new();
        titl.extend_from_slice(&[0u8; 6]); // FullBox + 2-byte lang
        titl.extend_from_slice(b"My Track\0");
        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"titl", &titl));

        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        assert!(t.kinds.is_empty());
    }

    /// Surfacing: each parsed kind shows up as `kind_<n>` on
    /// `params.options`. URI-only kinds emit just the URI; URI+value
    /// kinds emit `"URI value"` (space-separated, mirroring the
    /// `tref_<type>` value convention).
    #[test]
    fn build_stream_info_surfaces_kinds_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        t.codec_id_fourcc = *b"wvtt";
        t.timescale = 1000;
        t.kinds
            .push(("urn:mpeg:dash:role:2011".to_string(), "caption".to_string()));
        t.kinds
            .push(("urn:apple:hap:subtitles".to_string(), String::new()));
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("kind_0"),
            Some("urn:mpeg:dash:role:2011 caption")
        );
        assert_eq!(
            info.params.options.get("kind_1"),
            Some("urn:apple:hap:subtitles")
        );
        assert_eq!(info.params.options.get("kind_2"), None);
    }

    /// A track with no `kind` boxes surfaces no `kind_*` options.
    #[test]
    fn build_stream_info_no_kind_no_kind_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("kind_0"), None);
    }

    /// End-to-end: a `kind` box nested inside `trak/udta` is picked up
    /// by `parse_trak` and lands on the track.
    #[test]
    fn parse_trak_picks_up_nested_kind() {
        // Minimal tkhd (v0): FullBox (4) + created (4) + modified (4) +
        // track_ID (4) + reserved (4) + duration (4) + reserved (8) +
        // layer (2) + alt_group (2) + volume (2) + reserved (2) +
        // matrix (36) + width (4) + height (4) = 84 bytes.
        let mut tkhd = vec![0u8; 84];
        // Set track_ID at offset 4+4+4 = 12.
        tkhd[12..16].copy_from_slice(&7u32.to_be_bytes());
        // Minimal mdhd (v0, 24 bytes).
        let mut mdhd = Vec::new();
        mdhd.extend_from_slice(&[0u8; 4]); // version+flags
        mdhd.extend_from_slice(&[0u8; 8]); // created+modified
        mdhd.extend_from_slice(&1000u32.to_be_bytes()); // timescale
        mdhd.extend_from_slice(&0u32.to_be_bytes()); // duration
        mdhd.extend_from_slice(&[0u8; 4]); // language + pre_defined
                                           // Minimal hdlr identifying a video track.
        let mut hdlr = Vec::new();
        hdlr.extend_from_slice(&[0u8; 4]); // FullBox
        hdlr.extend_from_slice(&[0u8; 4]); // pre_defined
        hdlr.extend_from_slice(b"vide"); // handler_type
        hdlr.extend_from_slice(&[0u8; 12]); // reserved
        hdlr.push(0); // name (empty C string)
                      // Wrap the mdhd + hdlr into a minimal mdia.
        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"hdlr", &hdlr));
        // Minimal `kind` box: URI = "urn:mpeg:dash:role:2011", value = "main".
        let mut kind = Vec::new();
        kind.extend_from_slice(&[0u8; 4]);
        kind.extend_from_slice(b"urn:mpeg:dash:role:2011\0");
        kind.extend_from_slice(b"main\0");
        // Wrap kind in a track-level udta.
        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"kind", &kind));
        // Assemble the trak body.
        let mut trak = Vec::new();
        trak.extend(wrap_box_full_size(b"tkhd", &tkhd));
        trak.extend(wrap_box_full_size(b"mdia", &mdia));
        trak.extend(wrap_box_full_size(b"udta", &udta));

        let t = super::parse_trak(&trak, 1 << 30).unwrap().unwrap();
        assert_eq!(t.track_id, 7);
        assert_eq!(t.kinds.len(), 1);
        assert_eq!(t.kinds[0].0, "urn:mpeg:dash:role:2011");
        assert_eq!(t.kinds[0].1, "main");
    }

    /// Builds the 16-bit packed language word of an ISO/IEC 14496-12
    /// ยง8.10.2.3 `cprt` box from a 3-letter ASCII lowercase tag.
    /// Each character contributes 5 bits of `(c - 0x60)` and the
    /// padding bit at position 15 is 0.
    fn pack_lang(tag: &[u8; 3]) -> [u8; 2] {
        let c0 = (tag[0] - 0x60) as u16;
        let c1 = (tag[1] - 0x60) as u16;
        let c2 = (tag[2] - 0x60) as u16;
        let packed = (c0 << 10) | (c1 << 5) | c2;
        packed.to_be_bytes()
    }

    /// ยง8.10.2 โ€” `cprt` (CopyrightBox) ASCII case: FullBox preamble +
    /// packed `eng` language + NULL-terminated UTF-8 notice. The decoded
    /// record carries the 3-letter language tag and the notice without
    /// the trailing NUL.
    #[test]
    fn parse_cprt_ascii_eng_notice() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox version 0 + flags 0
        body.extend_from_slice(&pack_lang(b"eng"));
        body.extend_from_slice(b"(c) 2026 Example\0");
        let mut t = fresh_track();
        super::parse_cprt(&body, &mut t);
        assert_eq!(t.copyrights.len(), 1);
        assert_eq!(&t.copyrights[0].language, b"eng");
        assert_eq!(t.copyrights[0].notice, "(c) 2026 Example");
    }

    /// ยง8.10.2 โ€” `cprt` with a UTF-16BE notice (the spec's
    /// "if UTF-16 is used, the string shall start with the BYTE ORDER
    /// MARK (0xFEFF)" path). The BOM is consumed and the notice is
    /// decoded to a native String โ€” the UTF-16 NUL-terminator pair at
    /// the end is also stripped.
    #[test]
    fn parse_cprt_utf16be_notice_with_bom() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(&pack_lang(b"jpn"));
        // BOM + "ใ‚" (U+3042) + NULL terminator (U+0000).
        body.extend_from_slice(&[0xFE, 0xFF]);
        body.extend_from_slice(&[0x30, 0x42]);
        body.extend_from_slice(&[0x00, 0x00]);
        let mut t = fresh_track();
        super::parse_cprt(&body, &mut t);
        assert_eq!(t.copyrights.len(), 1);
        assert_eq!(&t.copyrights[0].language, b"jpn");
        assert_eq!(t.copyrights[0].notice, "ใ‚");
    }

    /// A `cprt` box with a non-zero FullBox version is unknown to the
    /// ยง8.10.2.2 syntax (which pins it to 0); the box is silently
    /// dropped โ€” a forward-incompatible layout should not abort the
    /// demux nor inject an entry with potentially-wrong byte offsets.
    #[test]
    fn parse_cprt_unknown_version_is_dropped() {
        let mut body = Vec::new();
        body.push(1); // version = 1 (not defined by ยง8.10.2.2)
        body.extend_from_slice(&[0u8; 3]); // flags
        body.extend_from_slice(&pack_lang(b"eng"));
        body.extend_from_slice(b"ignored\0");
        let mut t = fresh_track();
        super::parse_cprt(&body, &mut t);
        assert!(t.copyrights.is_empty());
    }

    /// A `cprt` body shorter than the FullBox + language word (6 bytes)
    /// is silently dropped โ€” the box is informational and a malformed
    /// entry should never abort the demux (mirrors `parse_kind`'s
    /// posture).
    #[test]
    fn parse_cprt_too_short_is_silently_dropped() {
        let mut t = fresh_track();
        super::parse_cprt(&[0, 0, 0, 0, 0], &mut t);
        assert!(t.copyrights.is_empty());
    }

    /// A `cprt` with an empty notice (just the FullBox + language +
    /// terminator) is preserved as an empty-string entry. The decoded
    /// language tag is still meaningful โ€” "the track declares an empty
    /// notice for this language" is not the same as the absence of
    /// any `cprt` box.
    #[test]
    fn parse_cprt_empty_notice_preserves_language() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(&pack_lang(b"fra"));
        body.push(0); // notice is just the terminator
        let mut t = fresh_track();
        super::parse_cprt(&body, &mut t);
        assert_eq!(t.copyrights.len(), 1);
        assert_eq!(&t.copyrights[0].language, b"fra");
        assert_eq!(t.copyrights[0].notice, "");
    }

    /// `build_cprt_box` is the byte-exact inverse of `parse_cprt`: a
    /// language + UTF-8 notice re-parses to the same record.
    #[test]
    fn build_cprt_round_trips() {
        let boxed = super::build_cprt_box(b"eng", "(c) 2026 Example").unwrap();
        assert_eq!(&boxed[4..8], b"cprt");
        let mut t = fresh_track();
        super::parse_cprt(&boxed[8..], &mut t);
        assert_eq!(t.copyrights.len(), 1);
        assert_eq!(&t.copyrights[0].language, b"eng");
        assert_eq!(t.copyrights[0].notice, "(c) 2026 Example");
    }

    /// An empty notice round-trips while preserving the language.
    #[test]
    fn build_cprt_empty_notice() {
        let boxed = super::build_cprt_box(b"fra", "").unwrap();
        let mut t = fresh_track();
        super::parse_cprt(&boxed[8..], &mut t);
        assert_eq!(&t.copyrights[0].language, b"fra");
        assert_eq!(t.copyrights[0].notice, "");
    }

    /// A non-lowercase language byte cannot be encoded into the 5-bit
    /// field; an embedded NUL in the notice would truncate on re-parse.
    #[test]
    fn build_cprt_rejects_bad_inputs() {
        assert!(super::build_cprt_box(b"EN1", "x").is_none());
        assert!(super::build_cprt_box(b"eng", "bad\0notice").is_none());
    }

    /// `build_kind_box` is the byte-exact inverse of `parse_kind`.
    #[test]
    fn build_kind_round_trips() {
        let boxed = super::build_kind_box("urn:mpeg:dash:role:2011", "subtitle").unwrap();
        assert_eq!(&boxed[4..8], b"kind");
        let mut t = fresh_track();
        super::parse_kind(&boxed[8..], &mut t);
        assert_eq!(t.kinds.len(), 1);
        assert_eq!(t.kinds[0].0, "urn:mpeg:dash:role:2011");
        assert_eq!(t.kinds[0].1, "subtitle");
    }

    /// An empty `value` round-trips (URI-only kind).
    #[test]
    fn build_kind_empty_value() {
        let boxed = super::build_kind_box("urn:scheme", "").unwrap();
        let mut t = fresh_track();
        super::parse_kind(&boxed[8..], &mut t);
        assert_eq!(t.kinds[0].0, "urn:scheme");
        assert_eq!(t.kinds[0].1, "");
    }

    /// An empty scheme URI (ยง8.10.4.3) or an embedded NUL is rejected.
    #[test]
    fn build_kind_rejects_bad_inputs() {
        assert!(super::build_kind_box("", "x").is_none());
        assert!(super::build_kind_box("urn:a\0b", "x").is_none());
        assert!(super::build_kind_box("urn:a", "x\0y").is_none());
    }

    /// `build_tsel_box` is the byte-exact inverse of `parse_tsel`,
    /// preserving the signed switch_group and the FourCC attribute list.
    #[test]
    fn build_tsel_round_trips() {
        let boxed = super::build_tsel_box(-5, &[*b"bitr", *b"frar"]);
        assert_eq!(&boxed[4..8], b"tsel");
        let mut t = fresh_track();
        super::parse_tsel(&boxed[8..], &mut t);
        let sel = t.tsel.unwrap();
        assert_eq!(sel.switch_group, -5);
        assert_eq!(sel.attribute_list, vec![*b"bitr", *b"frar"]);
    }

    /// Multiple `cprt` boxes inside the same track-level `udta` โ€”
    /// ยง8.10.2.1's "Quantity: Zero or more" โ€” each lands as a distinct
    /// record in encounter order. The canonical use-case is a
    /// multilingual copyright (one box per language).
    #[test]
    fn parse_track_udta_collects_multiple_cprts() {
        let mut c1 = Vec::new();
        c1.extend_from_slice(&[0u8; 4]);
        c1.extend_from_slice(&pack_lang(b"eng"));
        c1.extend_from_slice(b"(c) 2026 Example\0");
        let mut c2 = Vec::new();
        c2.extend_from_slice(&[0u8; 4]);
        c2.extend_from_slice(&pack_lang(b"fra"));
        c2.extend_from_slice(b"(c) 2026 Exemple\0");

        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"cprt", &c1));
        udta.extend(wrap_box_full_size(b"cprt", &c2));

        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        assert_eq!(t.copyrights.len(), 2);
        assert_eq!(&t.copyrights[0].language, b"eng");
        assert_eq!(t.copyrights[0].notice, "(c) 2026 Example");
        assert_eq!(&t.copyrights[1].language, b"fra");
        assert_eq!(t.copyrights[1].notice, "(c) 2026 Exemple");
    }

    /// Surfacing: each parsed `cprt` record shows up on `params.options`
    /// as the pair `copyright_<n>` (notice) + `copyright_<n>_lang`
    /// (3-letter language tag), keyed by 0-based encounter index. An
    /// empty notice omits the notice key but keeps the `_lang` key so
    /// a consumer can still tell "track declares an empty notice in
    /// `eng`" from "track has no `cprt`".
    #[test]
    fn build_stream_info_surfaces_copyrights_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        t.copyrights.push(super::CopyrightRecord {
            language: *b"eng",
            notice: "(c) 2026 Example".to_string(),
        });
        t.copyrights.push(super::CopyrightRecord {
            language: *b"jpn",
            notice: "".to_string(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("copyright_0"),
            Some("(c) 2026 Example")
        );
        assert_eq!(info.params.options.get("copyright_0_lang"), Some("eng"));
        assert_eq!(info.params.options.get("copyright_1"), None);
        assert_eq!(info.params.options.get("copyright_1_lang"), Some("jpn"));
        assert_eq!(info.params.options.get("copyright_2"), None);
    }

    /// A track with no `cprt` records surfaces no `copyright_*` options.
    #[test]
    fn build_stream_info_no_copyrights_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("copyright_0"), None);
        assert_eq!(info.params.options.get("copyright_0_lang"), None);
    }

    /// End-to-end: a `cprt` box nested inside `trak/udta` is picked up
    /// by `parse_trak` and lands on the track's `copyrights` list.
    #[test]
    fn parse_trak_picks_up_nested_cprt() {
        // Minimal tkhd (v0): 84 bytes; set track_ID at offset 12.
        let mut tkhd = vec![0u8; 84];
        tkhd[12..16].copy_from_slice(&11u32.to_be_bytes());
        // Minimal mdhd (v0, 24 bytes).
        let mut mdhd = Vec::new();
        mdhd.extend_from_slice(&[0u8; 4]); // version+flags
        mdhd.extend_from_slice(&[0u8; 8]); // created+modified
        mdhd.extend_from_slice(&1000u32.to_be_bytes()); // timescale
        mdhd.extend_from_slice(&0u32.to_be_bytes()); // duration
        mdhd.extend_from_slice(&[0u8; 4]); // language + pre_defined
                                           // Minimal hdlr identifying a video track.
        let mut hdlr = Vec::new();
        hdlr.extend_from_slice(&[0u8; 4]); // FullBox
        hdlr.extend_from_slice(&[0u8; 4]); // pre_defined
        hdlr.extend_from_slice(b"vide"); // handler_type
        hdlr.extend_from_slice(&[0u8; 12]); // reserved
        hdlr.push(0); // name (empty C string)
                      // Wrap mdhd + hdlr into a minimal mdia.
        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"hdlr", &hdlr));
        // Minimal `cprt` box: language `eng`, notice "(c) 2026 Example".
        let mut cprt = Vec::new();
        cprt.extend_from_slice(&[0u8; 4]);
        cprt.extend_from_slice(&pack_lang(b"eng"));
        cprt.extend_from_slice(b"(c) 2026 Example\0");
        // Wrap cprt in a track-level udta.
        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"cprt", &cprt));
        // Assemble the trak body.
        let mut trak = Vec::new();
        trak.extend(wrap_box_full_size(b"tkhd", &tkhd));
        trak.extend(wrap_box_full_size(b"mdia", &mdia));
        trak.extend(wrap_box_full_size(b"udta", &udta));

        let t = super::parse_trak(&trak, 1 << 30).unwrap().unwrap();
        assert_eq!(t.track_id, 11);
        assert_eq!(t.copyrights.len(), 1);
        assert_eq!(&t.copyrights[0].language, b"eng");
        assert_eq!(t.copyrights[0].notice, "(c) 2026 Example");
    }

    /// ยง8.10.3 โ€” `tsel` (TrackSelectionBox): FullBox preamble + signed
    /// 32-bit `switch_group` + zero or more 4-byte FourCC attributes
    /// running to the end of the box. The canonical bitrate-adaptation
    /// rendition: `switch_group = 1` + `bitr` (differentiating attribute
    /// = bitrate).
    #[test]
    fn parse_tsel_switch_group_and_one_attribute() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox version 0 + flags 0
        body.extend_from_slice(&1i32.to_be_bytes()); // switch_group = 1
        body.extend_from_slice(b"bitr"); // attribute_list[0]
        let mut t = fresh_track();
        super::parse_tsel(&body, &mut t);
        let tsel = t.tsel.as_ref().unwrap();
        assert_eq!(tsel.switch_group, 1);
        assert_eq!(tsel.attribute_list, vec![*b"bitr"]);
    }

    /// `tsel` with multiple attributes: each 4-byte chunk after the
    /// `switch_group` is one FourCC. Order matches on-disk order
    /// (the spec writes "list" without forcing a particular sort).
    #[test]
    fn parse_tsel_multiple_attributes_preserve_order() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(&42i32.to_be_bytes()); // switch_group = 42
        body.extend_from_slice(b"bitr"); // bitrate (differentiating)
        body.extend_from_slice(b"cdec"); // codec (differentiating)
        body.extend_from_slice(b"lang"); // language (differentiating)
        let mut t = fresh_track();
        super::parse_tsel(&body, &mut t);
        let tsel = t.tsel.as_ref().unwrap();
        assert_eq!(tsel.switch_group, 42);
        assert_eq!(tsel.attribute_list, vec![*b"bitr", *b"cdec", *b"lang"]);
    }

    /// `tsel` with `switch_group = 0` and an empty attribute list is the
    /// minimal legal body: 4-byte FullBox + 4-byte `switch_group`. The
    /// box must still parse โ€” surfacing a zero switch group lets a
    /// consumer tell "present but no information" from "absent".
    #[test]
    fn parse_tsel_zero_switch_group_no_attributes() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(&0i32.to_be_bytes()); // switch_group = 0
        let mut t = fresh_track();
        super::parse_tsel(&body, &mut t);
        let tsel = t.tsel.as_ref().unwrap();
        assert_eq!(tsel.switch_group, 0);
        assert!(tsel.attribute_list.is_empty());
    }

    /// `template int(32) switch_group` is signed โ€” a negative value must
    /// be preserved. The spec doesn't reserve negative space, but the
    /// declared type is signed so we read it as signed (a hand-crafted
    /// authoring tool emitting `switch_group = -1` round-trips cleanly).
    #[test]
    fn parse_tsel_negative_switch_group_preserved() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(&(-7i32).to_be_bytes()); // switch_group = -7
        let mut t = fresh_track();
        super::parse_tsel(&body, &mut t);
        let tsel = t.tsel.as_ref().unwrap();
        assert_eq!(tsel.switch_group, -7);
    }

    /// A body shorter than `FullBox + switch_group` (8 bytes) is silently
    /// dropped โ€” `tsel` is informational and a malformed entry should
    /// never abort the demux (mirroring `parse_kind`).
    #[test]
    fn parse_tsel_too_short_silently_dropped() {
        let mut t = fresh_track();
        super::parse_tsel(&[0u8; 7], &mut t);
        assert!(t.tsel.is_none());
    }

    /// Unknown FullBox `version` (the spec pins it to 0): silently
    /// dropped so a future derived-spec extension never mis-parses on
    /// pre-extension demuxers.
    #[test]
    fn parse_tsel_unknown_version_silently_dropped() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1, 0, 0, 0]); // version 1 + flags 0
        body.extend_from_slice(&5i32.to_be_bytes()); // switch_group = 5
        let mut t = fresh_track();
        super::parse_tsel(&body, &mut t);
        assert!(t.tsel.is_none());
    }

    /// Trailing bytes that don't make up a complete 4-byte FourCC
    /// (1โ€“3 bytes after the last full attribute) are ignored โ€”
    /// matches the existing "trailing partial record" handling
    /// elsewhere in the crate (`subs`, `sidx`).
    #[test]
    fn parse_tsel_trailing_partial_fourcc_ignored() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(&3i32.to_be_bytes()); // switch_group
        body.extend_from_slice(b"bitr"); // one complete attribute
        body.extend_from_slice(b"xy"); // 2 trailing bytes โ€” dropped
        let mut t = fresh_track();
        super::parse_tsel(&body, &mut t);
        let tsel = t.tsel.as_ref().unwrap();
        assert_eq!(tsel.switch_group, 3);
        assert_eq!(tsel.attribute_list, vec![*b"bitr"]);
    }

    /// End-to-end: a `tsel` nested inside `trak/udta` is picked up by
    /// `parse_track_udta` (alongside `kind`).
    #[test]
    fn parse_track_udta_picks_up_tsel() {
        let mut tsel = Vec::new();
        tsel.extend_from_slice(&[0u8; 4]); // FullBox
        tsel.extend_from_slice(&9i32.to_be_bytes()); // switch_group = 9
        tsel.extend_from_slice(b"bitr");
        tsel.extend_from_slice(b"lang");
        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"tsel", &tsel));

        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        let tb = t.tsel.as_ref().unwrap();
        assert_eq!(tb.switch_group, 9);
        assert_eq!(tb.attribute_list, vec![*b"bitr", *b"lang"]);
    }

    /// `tsel` coexists with `kind` inside the same track-level `udta`.
    /// Both children are picked up and land on their respective fields.
    #[test]
    fn parse_track_udta_collects_tsel_alongside_kind() {
        let mut kind = Vec::new();
        kind.extend_from_slice(&[0u8; 4]);
        kind.extend_from_slice(b"urn:mpeg:dash:role:2011\0");
        kind.extend_from_slice(b"alternate\0");

        let mut tsel = Vec::new();
        tsel.extend_from_slice(&[0u8; 4]);
        tsel.extend_from_slice(&2i32.to_be_bytes());
        tsel.extend_from_slice(b"cdec");

        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"kind", &kind));
        udta.extend(wrap_box_full_size(b"tsel", &tsel));

        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        assert_eq!(t.kinds.len(), 1);
        assert_eq!(t.kinds[0].1, "alternate");
        let tb = t.tsel.as_ref().unwrap();
        assert_eq!(tb.switch_group, 2);
        assert_eq!(tb.attribute_list, vec![*b"cdec"]);
    }

    /// Surfacing: a present `tsel` emits `tsel_switch_group` (always,
    /// even when zero) and `tsel_attributes` (only when the list is
    /// non-empty). The attributes render as space-separated FourCC
    /// strings, matching the `tref_<type>` value convention.
    #[test]
    fn build_stream_info_surfaces_tsel_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90000;
        t.tsel = Some(super::TselBox {
            switch_group: 11,
            attribute_list: vec![*b"bitr", *b"cdec"],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("tsel_switch_group"), Some("11"));
        assert_eq!(
            info.params.options.get("tsel_attributes"),
            Some("bitr cdec")
        );
    }

    /// A `tsel` with `switch_group = 0` and an empty attribute list
    /// still emits the `tsel_switch_group` key (present-but-zero is
    /// distinguishable from absent at the caller layer) but omits
    /// `tsel_attributes`.
    #[test]
    fn build_stream_info_tsel_zero_no_attributes() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        t.tsel = Some(super::TselBox {
            switch_group: 0,
            attribute_list: Vec::new(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("tsel_switch_group"), Some("0"));
        assert_eq!(info.params.options.get("tsel_attributes"), None);
    }

    /// A track with no `tsel` surfaces no `tsel_*` options at all.
    #[test]
    fn build_stream_info_no_tsel_no_tsel_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("tsel_switch_group"), None);
        assert_eq!(info.params.options.get("tsel_attributes"), None);
    }

    /// A `tsel` attribute that contains non-printable bytes falls back
    /// to 8-digit hex on the rendered surface, matching the
    /// `tref_<type>` convention for unusual FourCCs.
    #[test]
    fn build_stream_info_tsel_attribute_non_printable_renders_as_hex() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90000;
        t.tsel = Some(super::TselBox {
            switch_group: 1,
            attribute_list: vec![[0x00, 0x01, 0x02, 0x03], *b"bitr"],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("tsel_attributes"),
            Some("00010203 bitr")
        );
    }

    /// End-to-end: a `tsel` nested inside `trak/udta` is picked up by
    /// `parse_trak` and lands on the track field.
    #[test]
    fn parse_trak_picks_up_nested_tsel() {
        let mut tkhd = vec![0u8; 84];
        tkhd[12..16].copy_from_slice(&13u32.to_be_bytes());
        let mut mdhd = Vec::new();
        mdhd.extend_from_slice(&[0u8; 4]);
        mdhd.extend_from_slice(&[0u8; 8]);
        mdhd.extend_from_slice(&1000u32.to_be_bytes());
        mdhd.extend_from_slice(&0u32.to_be_bytes());
        mdhd.extend_from_slice(&[0u8; 4]);
        let mut hdlr = Vec::new();
        hdlr.extend_from_slice(&[0u8; 4]);
        hdlr.extend_from_slice(&[0u8; 4]);
        hdlr.extend_from_slice(b"soun");
        hdlr.extend_from_slice(&[0u8; 12]);
        hdlr.push(0);
        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"hdlr", &hdlr));

        let mut tsel = Vec::new();
        tsel.extend_from_slice(&[0u8; 4]);
        tsel.extend_from_slice(&100i32.to_be_bytes());
        tsel.extend_from_slice(b"bitr");
        tsel.extend_from_slice(b"lang");

        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"tsel", &tsel));

        let mut trak = Vec::new();
        trak.extend(wrap_box_full_size(b"tkhd", &tkhd));
        trak.extend(wrap_box_full_size(b"mdia", &mdia));
        trak.extend(wrap_box_full_size(b"udta", &udta));

        let t = super::parse_trak(&trak, 1 << 30).unwrap().unwrap();
        assert_eq!(t.track_id, 13);
        let tb = t.tsel.as_ref().unwrap();
        assert_eq!(tb.switch_group, 100);
        assert_eq!(tb.attribute_list, vec![*b"bitr", *b"lang"]);
    }

    // --- ยง8.14 Sub tracks (strk / stri / strd / stsg) ---

    /// Build a minimal `stri` (ยง8.14.4) body: FullBox preamble +
    /// `switch_group` (i16) + `alternate_group` (i16) + `sub_track_ID`
    /// (u32) + zero or more attribute FourCCs.
    fn stri_body(switch: i16, alt: i16, id: u32, attrs: &[&[u8; 4]]) -> Vec<u8> {
        let mut b = Vec::new();
        b.extend_from_slice(&[0u8; 4]); // FullBox version 0 + flags 0
        b.extend_from_slice(&switch.to_be_bytes());
        b.extend_from_slice(&alt.to_be_bytes());
        b.extend_from_slice(&id.to_be_bytes());
        for a in attrs {
            b.extend_from_slice(*a);
        }
        b
    }

    /// Build a `stsg` (ยง8.14.6) body: FullBox preamble + `grouping_type`
    /// FourCC + `item_count` (u16) + that many `group_description_index`
    /// (u32) values.
    fn stsg_body(grouping_type: &[u8; 4], indices: &[u32]) -> Vec<u8> {
        let mut b = Vec::new();
        b.extend_from_slice(&[0u8; 4]); // FullBox
        b.extend_from_slice(grouping_type);
        b.extend_from_slice(&(indices.len() as u16).to_be_bytes());
        for i in indices {
            b.extend_from_slice(&i.to_be_bytes());
        }
        b
    }

    /// ยง8.14.4 โ€” `stri`: the three fixed fields plus a two-entry
    /// `attribute_list`. The canonical view-scalable sub track:
    /// `switch_group = 1`, `alternate_group = 1`, `sub_track_ID = 2`,
    /// attributes `vwsc` (view scalability, descriptive) + `nvws`
    /// (number of views, differentiating).
    #[test]
    fn parse_stri_fields_and_attributes() {
        let body = stri_body(1, 1, 2, &[b"vwsc", b"nvws"]);
        let st = super::parse_stri(&body).unwrap();
        assert_eq!(st.switch_group, 1);
        assert_eq!(st.alternate_group, 1);
        assert_eq!(st.sub_track_id, 2);
        assert_eq!(st.attribute_list, vec![*b"vwsc", *b"nvws"]);
        assert!(st.sample_groups.is_empty());
    }

    /// `stri` group fields are signed 16-bit (`template int(16)`); a
    /// negative value must round-trip. The minimal legal body carries the
    /// three fixed fields and an empty attribute list.
    #[test]
    fn parse_stri_negative_groups_no_attributes() {
        let body = stri_body(-3, -5, 0, &[]);
        let st = super::parse_stri(&body).unwrap();
        assert_eq!(st.switch_group, -3);
        assert_eq!(st.alternate_group, -5);
        assert_eq!(st.sub_track_id, 0);
        assert!(st.attribute_list.is_empty());
    }

    /// A `stri` body shorter than `FullBox + switch + alt + id` (12 bytes)
    /// is rejected โ€” without the fixed fields there is no usable selection
    /// metadata.
    #[test]
    fn parse_stri_too_short_rejected() {
        assert!(super::parse_stri(&[0u8; 11]).is_none());
    }

    /// Unknown FullBox `version` (the spec pins `stri` to 0) is rejected
    /// so a future derived-spec extension never mis-parses.
    #[test]
    fn parse_stri_unknown_version_rejected() {
        let mut body = stri_body(1, 1, 1, &[b"bitr"]);
        body[0] = 1; // version 1
        assert!(super::parse_stri(&body).is_none());
    }

    /// A trailing 1โ€“3 byte fragment after the last complete attribute
    /// FourCC is ignored ("attribute_list[] to the end of the box"),
    /// matching the `parse_tsel` posture.
    #[test]
    fn parse_stri_trailing_partial_fourcc_ignored() {
        let mut body = stri_body(7, 0, 9, &[b"frar"]);
        body.extend_from_slice(b"xy"); // 2 trailing bytes โ€” dropped
        let st = super::parse_stri(&body).unwrap();
        assert_eq!(st.attribute_list, vec![*b"frar"]);
    }

    /// ยง8.14.6 โ€” `stsg`: grouping_type + item_count + index list.
    #[test]
    fn parse_stsg_grouping_and_indices() {
        let body = stsg_body(b"tele", &[1, 3, 7]);
        let sg = super::parse_stsg(&body).unwrap();
        assert_eq!(&sg.grouping_type, b"tele");
        assert_eq!(sg.group_description_indices, vec![1, 3, 7]);
    }

    /// `stsg` with `item_count = 0` is a legal empty definition (the box
    /// names the grouping type but no description indices yet).
    #[test]
    fn parse_stsg_empty_index_list() {
        let body = stsg_body(b"roll", &[]);
        let sg = super::parse_stsg(&body).unwrap();
        assert_eq!(&sg.grouping_type, b"roll");
        assert!(sg.group_description_indices.is_empty());
    }

    /// A declared `item_count` that overruns the bytes present is rejected
    /// โ€” a truncated index list would lie about the sub track's groups.
    #[test]
    fn parse_stsg_overrunning_item_count_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox
        body.extend_from_slice(b"tele");
        body.extend_from_slice(&3u16.to_be_bytes()); // claims 3 indices
        body.extend_from_slice(&1u32.to_be_bytes()); // only 1 present
        assert!(super::parse_stsg(&body).is_none());
    }

    /// Unknown FullBox version on `stsg` is rejected.
    #[test]
    fn parse_stsg_unknown_version_rejected() {
        let mut body = stsg_body(b"tele", &[1]);
        body[0] = 2;
        assert!(super::parse_stsg(&body).is_none());
    }

    /// ยง8.14.3 โ€” `strk`: full assembly with a `stri` plus a `strd`
    /// holding two `stsg` boxes. The whole sub track lands on
    /// `t.sub_tracks` with its sample-group definitions attached in
    /// on-disk order.
    #[test]
    fn parse_strk_with_stri_and_strd_stsg() {
        let stri = stri_body(2, 2, 5, &[b"tesc"]);
        let stsg0 = stsg_body(b"tele", &[1, 2]);
        let stsg1 = stsg_body(b"roll", &[4]);
        let mut strd = Vec::new();
        strd.extend(wrap_box_full_size(b"stsg", &stsg0));
        strd.extend(wrap_box_full_size(b"stsg", &stsg1));
        let mut strk = Vec::new();
        strk.extend(wrap_box_full_size(b"stri", &stri));
        strk.extend(wrap_box_full_size(b"strd", &strd));

        let mut t = fresh_track();
        super::parse_strk(&strk, &mut t);
        assert_eq!(t.sub_tracks.len(), 1);
        let st = &t.sub_tracks[0];
        assert_eq!(st.switch_group, 2);
        assert_eq!(st.alternate_group, 2);
        assert_eq!(st.sub_track_id, 5);
        assert_eq!(st.attribute_list, vec![*b"tesc"]);
        assert_eq!(st.sample_groups.len(), 2);
        assert_eq!(&st.sample_groups[0].grouping_type, b"tele");
        assert_eq!(st.sample_groups[0].group_description_indices, vec![1, 2]);
        assert_eq!(&st.sample_groups[1].grouping_type, b"roll");
        assert_eq!(st.sample_groups[1].group_description_indices, vec![4]);
    }

    /// A `strk` with a `stri` but no `strd` still surfaces the selection
    /// metadata (with an empty `sample_groups`). `strd` is mandatory per
    /// ยง8.14.5.1, but a producer slip is tolerated rather than aborting.
    #[test]
    fn parse_strk_stri_only_no_strd() {
        let stri = stri_body(1, 0, 3, &[]);
        let mut strk = Vec::new();
        strk.extend(wrap_box_full_size(b"stri", &stri));
        let mut t = fresh_track();
        super::parse_strk(&strk, &mut t);
        assert_eq!(t.sub_tracks.len(), 1);
        assert_eq!(t.sub_tracks[0].sub_track_id, 3);
        assert!(t.sub_tracks[0].sample_groups.is_empty());
    }

    /// A `strk` missing its mandatory `stri` contributes no sub track โ€”
    /// there is no selection metadata to surface.
    #[test]
    fn parse_strk_without_stri_dropped() {
        let strd = Vec::new();
        let mut strk = Vec::new();
        strk.extend(wrap_box_full_size(b"strd", &strd));
        let mut t = fresh_track();
        super::parse_strk(&strk, &mut t);
        assert!(t.sub_tracks.is_empty());
    }

    /// `build_stsg_box` is the byte-exact inverse of `parse_stsg`.
    #[test]
    fn build_stsg_round_trips() {
        let boxed = super::build_stsg_box(b"tele", &[1, 2, 3]).unwrap();
        assert_eq!(&boxed[4..8], b"stsg");
        let sg = super::parse_stsg(&boxed[8..]).unwrap();
        assert_eq!(&sg.grouping_type, b"tele");
        assert_eq!(sg.group_description_indices, vec![1, 2, 3]);
    }

    /// An empty index list yields `item_count == 0`.
    #[test]
    fn build_stsg_empty_indices() {
        let boxed = super::build_stsg_box(b"roll", &[]).unwrap();
        let sg = super::parse_stsg(&boxed[8..]).unwrap();
        assert_eq!(&sg.grouping_type, b"roll");
        assert!(sg.group_description_indices.is_empty());
    }

    /// `build_stri_box` is the byte-exact inverse of `parse_stri`,
    /// including signed group fields and the FourCC attribute list.
    #[test]
    fn build_stri_round_trips() {
        let boxed = super::build_stri_box(-2, 7, 9, &[*b"tesc", *b"bitr"]);
        assert_eq!(&boxed[4..8], b"stri");
        let st = super::parse_stri(&boxed[8..]).unwrap();
        assert_eq!(st.switch_group, -2);
        assert_eq!(st.alternate_group, 7);
        assert_eq!(st.sub_track_id, 9);
        assert_eq!(st.attribute_list, vec![*b"tesc", *b"bitr"]);
    }

    /// `build_strk_box` composes a full `strk` (stri + strd/stsg) that
    /// re-parses through `parse_strk` to the same sub-track record.
    #[test]
    fn build_strk_full_round_trips() {
        let groups = vec![(*b"tele", vec![1u32, 2]), (*b"roll", vec![4u32])];
        let boxed = super::build_strk_box(2, 2, 5, &[*b"tesc"], &groups).unwrap();
        assert_eq!(&boxed[4..8], b"strk");
        let mut t = fresh_track();
        super::parse_strk(&boxed[8..], &mut t);
        assert_eq!(t.sub_tracks.len(), 1);
        let st = &t.sub_tracks[0];
        assert_eq!(st.switch_group, 2);
        assert_eq!(st.alternate_group, 2);
        assert_eq!(st.sub_track_id, 5);
        assert_eq!(st.attribute_list, vec![*b"tesc"]);
        assert_eq!(st.sample_groups.len(), 2);
        assert_eq!(&st.sample_groups[0].grouping_type, b"tele");
        assert_eq!(st.sample_groups[0].group_description_indices, vec![1, 2]);
        assert_eq!(&st.sample_groups[1].grouping_type, b"roll");
        assert_eq!(st.sample_groups[1].group_description_indices, vec![4]);
    }

    /// With no sample groups, `build_strk_box` emits a `stri`-only `strk`
    /// (no empty `strd` container).
    #[test]
    fn build_strk_stri_only_omits_strd() {
        let boxed = super::build_strk_box(1, 0, 3, &[], &[]).unwrap();
        let mut t = fresh_track();
        super::parse_strk(&boxed[8..], &mut t);
        assert_eq!(t.sub_tracks.len(), 1);
        assert_eq!(t.sub_tracks[0].sub_track_id, 3);
        assert!(t.sub_tracks[0].sample_groups.is_empty());
        // The only child is the `stri` box: no `strd` container present.
        assert!(!boxed.windows(4).any(|w| w == b"strd"));
    }

    /// Multiple `strk` boxes per track (ยง8.14.3.1 "Zero or more") are all
    /// collected in on-disk order via `parse_track_udta`.
    #[test]
    fn parse_track_udta_collects_multiple_strk() {
        let strk_a = {
            let stri = stri_body(1, 1, 1, &[b"tesc"]);
            wrap_box_full_size(b"stri", &stri)
        };
        let strk_b = {
            let stri = stri_body(2, 1, 2, &[b"spsc"]);
            wrap_box_full_size(b"stri", &stri)
        };
        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"strk", &strk_a));
        udta.extend(wrap_box_full_size(b"strk", &strk_b));
        let mut t = fresh_track();
        super::parse_track_udta(&udta, &mut t);
        assert_eq!(t.sub_tracks.len(), 2);
        assert_eq!(t.sub_tracks[0].sub_track_id, 1);
        assert_eq!(t.sub_tracks[0].attribute_list, vec![*b"tesc"]);
        assert_eq!(t.sub_tracks[1].sub_track_id, 2);
        assert_eq!(t.sub_tracks[1].attribute_list, vec![*b"spsc"]);
    }

    /// Surfacing: a sub track emits `subtrack_<n>` carrying the three
    /// selection fields plus optional `attrs=` / `stsg=` blocks.
    #[test]
    fn build_stream_info_surfaces_subtrack_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90000;
        t.sub_tracks.push(super::SubTrack {
            switch_group: 4,
            alternate_group: 2,
            sub_track_id: 7,
            attribute_list: vec![*b"tesc", *b"bitr"],
            sample_groups: vec![super::SubTrackSampleGroup {
                grouping_type: *b"tele",
                group_description_indices: vec![1, 2],
            }],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("subtrack_0"),
            Some("id=7 switch=4 alt=2 attrs=tesc bitr stsg=tele:1,2")
        );
    }

    /// A sub track with no attributes and no sample groups surfaces only
    /// the three always-present fixed fields.
    #[test]
    fn build_stream_info_subtrack_minimal() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        t.sub_tracks.push(super::SubTrack {
            switch_group: 0,
            alternate_group: 0,
            sub_track_id: 0,
            attribute_list: Vec::new(),
            sample_groups: Vec::new(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("subtrack_0"),
            Some("id=0 switch=0 alt=0")
        );
    }

    /// A track with no `strk` surfaces no `subtrack_*` options.
    #[test]
    fn build_stream_info_no_strk_no_subtrack_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 90000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("subtrack_0"), None);
    }

    /// End-to-end: a `strk` nested inside `trak/udta` is picked up by
    /// `parse_trak` and lands on the track field.
    #[test]
    fn parse_trak_picks_up_nested_strk() {
        let mut tkhd = vec![0u8; 84];
        tkhd[12..16].copy_from_slice(&21u32.to_be_bytes());
        let mut mdhd = Vec::new();
        mdhd.extend_from_slice(&[0u8; 4]);
        mdhd.extend_from_slice(&[0u8; 8]);
        mdhd.extend_from_slice(&1000u32.to_be_bytes());
        mdhd.extend_from_slice(&0u32.to_be_bytes());
        mdhd.extend_from_slice(&[0u8; 4]);
        let mut hdlr = Vec::new();
        hdlr.extend_from_slice(&[0u8; 4]);
        hdlr.extend_from_slice(&[0u8; 4]);
        hdlr.extend_from_slice(b"vide");
        hdlr.extend_from_slice(&[0u8; 12]);
        hdlr.push(0);
        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"hdlr", &hdlr));

        let stri = stri_body(5, 5, 8, &[b"spsc"]);
        let stsg = stsg_body(b"tele", &[2]);
        let mut strd = Vec::new();
        strd.extend(wrap_box_full_size(b"stsg", &stsg));
        let mut strk = Vec::new();
        strk.extend(wrap_box_full_size(b"stri", &stri));
        strk.extend(wrap_box_full_size(b"strd", &strd));
        let mut udta = Vec::new();
        udta.extend(wrap_box_full_size(b"strk", &strk));

        let mut trak = Vec::new();
        trak.extend(wrap_box_full_size(b"tkhd", &tkhd));
        trak.extend(wrap_box_full_size(b"mdia", &mdia));
        trak.extend(wrap_box_full_size(b"udta", &udta));

        let t = super::parse_trak(&trak, 1 << 30).unwrap().unwrap();
        assert_eq!(t.track_id, 21);
        assert_eq!(t.sub_tracks.len(), 1);
        let st = &t.sub_tracks[0];
        assert_eq!(st.switch_group, 5);
        assert_eq!(st.alternate_group, 5);
        assert_eq!(st.sub_track_id, 8);
        assert_eq!(st.attribute_list, vec![*b"spsc"]);
        assert_eq!(st.sample_groups.len(), 1);
        assert_eq!(&st.sample_groups[0].grouping_type, b"tele");
        assert_eq!(st.sample_groups[0].group_description_indices, vec![2]);
    }

    /// ยง8.6.1.4 โ€” `cslg` version 0: five signed 32-bit fields after the
    /// FullBox preamble. Exercises a typical Apple-style negative
    /// composition shift (`compositionToDTSShift` positive, least delta
    /// negative).
    #[test]
    fn parse_cslg_v0() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
        body.extend_from_slice(&512i32.to_be_bytes()); // compositionToDTSShift
        body.extend_from_slice(&(-512i32).to_be_bytes()); // leastDecodeToDisplayDelta
        body.extend_from_slice(&1024i32.to_be_bytes()); // greatestDecodeToDisplayDelta
        body.extend_from_slice(&0i32.to_be_bytes()); // compositionStartTime
        body.extend_from_slice(&48000i32.to_be_bytes()); // compositionEndTime
        let c = super::parse_cslg(&body).unwrap();
        assert_eq!(c.composition_to_dts_shift, 512);
        assert_eq!(c.least_decode_to_display_delta, -512);
        assert_eq!(c.greatest_decode_to_display_delta, 1024);
        assert_eq!(c.composition_start_time, 0);
        assert_eq!(c.composition_end_time, 48000);
    }

    /// ยง8.6.1.4 โ€” `cslg` version 1: five signed 64-bit fields. Used when
    /// at least one value exceeds the 32-bit range. Verifies a value
    /// past `i32::MAX` round-trips, and that signed 64-bit is honoured.
    #[test]
    fn parse_cslg_v1_64bit() {
        let big = (i32::MAX as i64) + 1_000; // > 2^31, needs 64 bits
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 0]); // version 1 + flags 0
        body.extend_from_slice(&0i64.to_be_bytes()); // compositionToDTSShift
        body.extend_from_slice(&(-1_000i64).to_be_bytes()); // leastDecodeToDisplayDelta
        body.extend_from_slice(&2_000i64.to_be_bytes()); // greatestDecodeToDisplayDelta
        body.extend_from_slice(&0i64.to_be_bytes()); // compositionStartTime
        body.extend_from_slice(&big.to_be_bytes()); // compositionEndTime
        let c = super::parse_cslg(&body).unwrap();
        assert_eq!(c.composition_to_dts_shift, 0);
        assert_eq!(c.least_decode_to_display_delta, -1_000);
        assert_eq!(c.greatest_decode_to_display_delta, 2_000);
        assert_eq!(c.composition_start_time, 0);
        assert_eq!(c.composition_end_time, big);
    }

    /// A `cslg` with no room for even the FullBox preamble is rejected.
    #[test]
    fn parse_cslg_too_short() {
        assert!(super::parse_cslg(&[0u8, 0, 0]).is_err());
    }

    /// A `cslg` whose body is cut off mid-field (here a v0 box missing
    /// its last 32-bit field) is rejected rather than silently zero-filled.
    #[test]
    fn parse_cslg_truncated() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags
        body.extend_from_slice(&0i32.to_be_bytes()); // 1/5
        body.extend_from_slice(&0i32.to_be_bytes()); // 2/5
        body.extend_from_slice(&0i32.to_be_bytes()); // 3/5
        body.extend_from_slice(&0i32.to_be_bytes()); // 4/5 โ€” 5th missing
        assert!(super::parse_cslg(&body).is_err());
    }

    /// `parse_stbl` lands the `cslg` on the track alongside the other
    /// sample-table boxes.
    #[test]
    fn parse_stbl_picks_up_cslg() {
        let mut cslg = Vec::new();
        cslg.extend_from_slice(&[0u8; 4]); // v0
        cslg.extend_from_slice(&100i32.to_be_bytes());
        cslg.extend_from_slice(&(-100i32).to_be_bytes());
        cslg.extend_from_slice(&200i32.to_be_bytes());
        cslg.extend_from_slice(&0i32.to_be_bytes());
        cslg.extend_from_slice(&5000i32.to_be_bytes());
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"cslg", &cslg));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        let c = t.cslg.expect("cslg should be parsed");
        assert_eq!(c.composition_to_dts_shift, 100);
        assert_eq!(c.least_decode_to_display_delta, -100);
        assert_eq!(c.greatest_decode_to_display_delta, 200);
        assert_eq!(c.composition_start_time, 0);
        assert_eq!(c.composition_end_time, 5000);
    }

    /// ยง12.1.2 โ€” `vmhd` body after the FullBox preamble is a 16-bit
    /// `graphicsmode` plus three 16-bit `opcolor` components. Decode a
    /// typical `copy`-mode header with a non-zero opcolor.
    #[test]
    fn parse_vmhd_graphicsmode_and_opcolor() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 1]); // version 0, flags 1
        body.extend_from_slice(&0u16.to_be_bytes()); // graphicsmode = copy
        body.extend_from_slice(&0x1234u16.to_be_bytes()); // opcolor red
        body.extend_from_slice(&0x5678u16.to_be_bytes()); // opcolor green
        body.extend_from_slice(&0x9abcu16.to_be_bytes()); // opcolor blue
        let v = super::parse_vmhd(&body).unwrap();
        assert_eq!(v.graphicsmode, 0);
        assert_eq!(v.opcolor, [0x1234, 0x5678, 0x9abc]);
    }

    /// A non-zero `graphicsmode` (a derived-spec composition mode) is
    /// preserved verbatim, not normalised to `copy`.
    #[test]
    fn parse_vmhd_nonzero_graphicsmode_preserved() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 1]);
        body.extend_from_slice(&0x0100u16.to_be_bytes()); // graphicsmode
        body.extend_from_slice(&[0u8; 6]); // opcolor all zero
        let v = super::parse_vmhd(&body).unwrap();
        assert_eq!(v.graphicsmode, 0x0100);
        assert_eq!(v.opcolor, [0, 0, 0]);
    }

    /// The parser does not require `version == 0` โ€” a stray non-zero
    /// version byte still yields a usable header rather than a drop.
    #[test]
    fn parse_vmhd_tolerates_nonzero_version() {
        let mut body = Vec::new();
        body.extend_from_slice(&[3u8, 0, 0, 1]); // version 3
        body.extend_from_slice(&7u16.to_be_bytes());
        body.extend_from_slice(&[0u8; 6]);
        let v = super::parse_vmhd(&body).unwrap();
        assert_eq!(v.graphicsmode, 7);
    }

    /// A body shorter than the full 12 bytes (preamble + graphicsmode +
    /// 3ร—opcolor) is rejected โ€” a truncated tail would surface noise as
    /// an opcolor component.
    #[test]
    fn parse_vmhd_too_short_is_rejected() {
        // 11 bytes: one short of the final opcolor-blue byte.
        let body = vec![0u8; 11];
        assert!(super::parse_vmhd(&body).is_err());
    }

    /// ยง12.4.2 โ€” `hmhd` body after the FullBox preamble is two 16-bit
    /// PDU sizes, two 32-bit bitrates, and a reserved 32-bit word.
    /// Decode a typical hint-track header.
    #[test]
    fn parse_hmhd_pdu_sizes_and_bitrates() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0]); // version 0, flags 0
        body.extend_from_slice(&1500u16.to_be_bytes()); // maxPDUsize
        body.extend_from_slice(&820u16.to_be_bytes()); // avgPDUsize
        body.extend_from_slice(&3_000_000u32.to_be_bytes()); // maxbitrate
        body.extend_from_slice(&1_200_000u32.to_be_bytes()); // avgbitrate
        body.extend_from_slice(&0u32.to_be_bytes()); // reserved
        let h = super::parse_hmhd(&body).unwrap();
        assert_eq!(h.max_pdu_size, 1500);
        assert_eq!(h.avg_pdu_size, 820);
        assert_eq!(h.max_bitrate, 3_000_000);
        assert_eq!(h.avg_bitrate, 1_200_000);
    }

    /// The parser does not require `version == 0` โ€” a stray non-zero
    /// version byte still yields a usable header rather than a drop
    /// (mirroring `parse_vmhd`).
    #[test]
    fn parse_hmhd_tolerates_nonzero_version() {
        let mut body = Vec::new();
        body.extend_from_slice(&[2u8, 0, 0, 0]); // version 2
        body.extend_from_slice(&64u16.to_be_bytes());
        body.extend_from_slice(&64u16.to_be_bytes());
        body.extend_from_slice(&500u32.to_be_bytes());
        body.extend_from_slice(&500u32.to_be_bytes());
        body.extend_from_slice(&0u32.to_be_bytes());
        let h = super::parse_hmhd(&body).unwrap();
        assert_eq!(h.max_pdu_size, 64);
        assert_eq!(h.max_bitrate, 500);
    }

    /// A non-zero reserved trailing word is read past, not surfaced โ€”
    /// the parse still succeeds with the four real fields intact.
    #[test]
    fn parse_hmhd_nonzero_reserved_tolerated() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0]);
        body.extend_from_slice(&10u16.to_be_bytes());
        body.extend_from_slice(&20u16.to_be_bytes());
        body.extend_from_slice(&30u32.to_be_bytes());
        body.extend_from_slice(&40u32.to_be_bytes());
        body.extend_from_slice(&0xDEAD_BEEFu32.to_be_bytes()); // reserved != 0
        let h = super::parse_hmhd(&body).unwrap();
        assert_eq!(h.avg_bitrate, 40);
    }

    /// A body shorter than the full 20 bytes (preamble + 2ร—u16 +
    /// 2ร—u32 + reserved u32) is rejected โ€” a truncated tail would
    /// surface noise as a bitrate.
    #[test]
    fn parse_hmhd_too_short_is_rejected() {
        // 19 bytes: one short of the reserved word.
        let body = vec![0u8; 19];
        assert!(super::parse_hmhd(&body).is_err());
    }

    /// `parse_minf` lands the `hmhd` on the track.
    #[test]
    fn parse_minf_picks_up_hmhd() {
        let mut hmhd = Vec::new();
        hmhd.extend_from_slice(&[0u8, 0, 0, 0]);
        hmhd.extend_from_slice(&1400u16.to_be_bytes());
        hmhd.extend_from_slice(&700u16.to_be_bytes());
        hmhd.extend_from_slice(&2_500_000u32.to_be_bytes());
        hmhd.extend_from_slice(&900_000u32.to_be_bytes());
        hmhd.extend_from_slice(&0u32.to_be_bytes());
        let mut minf = Vec::new();
        minf.extend(wrap_box_full_size(b"hmhd", &hmhd));

        let mut t = fresh_track();
        super::parse_minf(&minf, &mut t, 1 << 30).unwrap();
        let h = t.hmhd.expect("hmhd should be parsed");
        assert_eq!(h.max_pdu_size, 1400);
        assert_eq!(h.avg_pdu_size, 700);
        assert_eq!(h.max_bitrate, 2_500_000);
        assert_eq!(h.avg_bitrate, 900_000);
    }

    /// ยง12.4.2 fixes the quantity at one โ€” `parse_minf` keeps the first
    /// `hmhd` and ignores a stray duplicate.
    #[test]
    fn parse_minf_keeps_first_hmhd_ignores_duplicate() {
        let mut first = Vec::new();
        first.extend_from_slice(&[0u8, 0, 0, 0]);
        first.extend_from_slice(&111u16.to_be_bytes());
        first.extend_from_slice(&[0u8; 14]);
        let mut second = Vec::new();
        second.extend_from_slice(&[0u8, 0, 0, 0]);
        second.extend_from_slice(&222u16.to_be_bytes());
        second.extend_from_slice(&[0u8; 14]);
        let mut minf = Vec::new();
        minf.extend(wrap_box_full_size(b"hmhd", &first));
        minf.extend(wrap_box_full_size(b"hmhd", &second));

        let mut t = fresh_track();
        super::parse_minf(&minf, &mut t, 1 << 30).unwrap();
        let h = t.hmhd.expect("hmhd should be parsed");
        assert_eq!(h.max_pdu_size, 111);
    }

    /// `parse_minf` lands the `vmhd` on the track.
    #[test]
    fn parse_minf_picks_up_vmhd() {
        let mut vmhd = Vec::new();
        vmhd.extend_from_slice(&[0u8, 0, 0, 1]);
        vmhd.extend_from_slice(&0u16.to_be_bytes());
        vmhd.extend_from_slice(&10u16.to_be_bytes());
        vmhd.extend_from_slice(&20u16.to_be_bytes());
        vmhd.extend_from_slice(&30u16.to_be_bytes());
        let mut minf = Vec::new();
        minf.extend(wrap_box_full_size(b"vmhd", &vmhd));

        let mut t = fresh_track();
        super::parse_minf(&minf, &mut t, 1 << 30).unwrap();
        let v = t.vmhd.expect("vmhd should be parsed");
        assert_eq!(v.graphicsmode, 0);
        assert_eq!(v.opcolor, [10, 20, 30]);
    }

    /// ยง12.1.2 fixes the quantity at one โ€” `parse_minf` keeps the first
    /// `vmhd` and ignores a stray duplicate.
    #[test]
    fn parse_minf_keeps_first_vmhd_ignores_duplicate() {
        let mut first = Vec::new();
        first.extend_from_slice(&[0u8, 0, 0, 1]);
        first.extend_from_slice(&1u16.to_be_bytes());
        first.extend_from_slice(&[0u8; 6]);
        let mut second = Vec::new();
        second.extend_from_slice(&[0u8, 0, 0, 1]);
        second.extend_from_slice(&2u16.to_be_bytes());
        second.extend_from_slice(&[0u8; 6]);
        let mut minf = Vec::new();
        minf.extend(wrap_box_full_size(b"vmhd", &first));
        minf.extend(wrap_box_full_size(b"vmhd", &second));

        let mut t = fresh_track();
        super::parse_minf(&minf, &mut t, 1 << 30).unwrap();
        assert_eq!(t.vmhd.unwrap().graphicsmode, 1);
    }

    /// A malformed `vmhd` (too short) inside `minf` is dropped silently โ€”
    /// the walker continues and the track simply has no video header,
    /// rather than failing the whole `minf` parse.
    #[test]
    fn parse_minf_drops_malformed_vmhd() {
        let short = vec![0u8; 5]; // far too short
        let mut minf = Vec::new();
        minf.extend(wrap_box_full_size(b"vmhd", &short));

        let mut t = fresh_track();
        super::parse_minf(&minf, &mut t, 1 << 30).unwrap();
        assert!(t.vmhd.is_none());
    }

    /// Surfacing: a parsed `cslg` exposes its five fields on
    /// `params.options` as `cslg_<field>` decimal strings.
    #[test]
    fn build_stream_info_surfaces_cslg_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.cslg = Some(super::CslgBox {
            composition_to_dts_shift: 512,
            least_decode_to_display_delta: -512,
            greatest_decode_to_display_delta: 1024,
            composition_start_time: 0,
            composition_end_time: 90000,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("cslg_composition_to_dts_shift"),
            Some("512")
        );
        assert_eq!(
            info.params
                .options
                .get("cslg_least_decode_to_display_delta"),
            Some("-512")
        );
        assert_eq!(
            info.params
                .options
                .get("cslg_greatest_decode_to_display_delta"),
            Some("1024")
        );
        assert_eq!(
            info.params.options.get("cslg_composition_start_time"),
            Some("0")
        );
        assert_eq!(
            info.params.options.get("cslg_composition_end_time"),
            Some("90000")
        );
    }

    /// Absence: a track with no `cslg` emits none of the `cslg_*`
    /// options keys.
    #[test]
    fn build_stream_info_no_cslg_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("cslg_composition_to_dts_shift"),
            None
        );
        assert_eq!(info.params.options.get("cslg_composition_end_time"), None);
    }

    /// Surfacing: a parsed `vmhd` exposes `vmhd_graphicsmode` (decimal)
    /// and `vmhd_opcolor` (three space-separated decimal components) on
    /// `params.options`.
    #[test]
    fn build_stream_info_surfaces_vmhd_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.vmhd = Some(super::VmhdBox {
            graphicsmode: 0,
            opcolor: [10, 20, 30],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("vmhd_graphicsmode"), Some("0"));
        assert_eq!(info.params.options.get("vmhd_opcolor"), Some("10 20 30"));
    }

    /// Absence: a track with no `vmhd` emits neither `vmhd_*` key.
    #[test]
    fn build_stream_info_no_vmhd_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("vmhd_graphicsmode"), None);
        assert_eq!(info.params.options.get("vmhd_opcolor"), None);
    }

    /// `parse_gmin` decodes the QuickTime Base Media Info Atom body
    /// (graphicsmode + opcolor + balance) after its FullBox preamble.
    #[test]
    fn parse_gmin_fields() {
        let mut body = vec![0u8, 0, 0, 0]; // version + flags
        body.extend_from_slice(&0x0040u16.to_be_bytes()); // graphicsmode = dither copy
        body.extend_from_slice(&0x8000u16.to_be_bytes()); // opcolor R
        body.extend_from_slice(&0x8001u16.to_be_bytes()); // opcolor G
        body.extend_from_slice(&0x8002u16.to_be_bytes()); // opcolor B
        body.extend_from_slice(&(-256i16).to_be_bytes()); // balance = -1.0 (8.8)
        body.extend_from_slice(&[0u8, 0]); // reserved
        let g = super::parse_gmin(&body).expect("gmin should parse");
        assert_eq!(g.graphicsmode, 0x0040);
        assert_eq!(g.opcolor, [0x8000, 0x8001, 0x8002]);
        assert_eq!(g.balance, -256);
    }

    /// A `gmin` body shorter than the fixed 16 bytes is rejected rather
    /// than surfacing truncation noise.
    #[test]
    fn parse_gmin_too_short_is_rejected() {
        assert!(super::parse_gmin(&[0u8; 15]).is_none());
        assert!(super::parse_gmin_box(&[0u8; 15]).is_err());
    }

    /// `build_gmin_box` โ†’ `parse_gmin_box` is a byte-exact round-trip, and
    /// the built box carries the correct 8-byte `gmin` header + 16-byte
    /// body (24 bytes total).
    #[test]
    fn build_gmin_box_round_trips() {
        let g = super::GminBox {
            graphicsmode: 0x0100,
            opcolor: [0x1234, 0x5678, 0x9abc],
            balance: 128,
        };
        let boxed = super::build_gmin_box(&g);
        assert_eq!(boxed.len(), 24);
        assert_eq!(&boxed[4..8], b"gmin");
        assert_eq!(
            u32::from_be_bytes([boxed[0], boxed[1], boxed[2], boxed[3]]),
            24
        );
        let back = super::parse_gmin_box(&boxed[8..]).expect("round-trip parse");
        assert_eq!(back, g);
    }

    /// `build_gmhd_box` wraps a single built `gmin`; `parse_gmhd` walks it
    /// back to the same record.
    #[test]
    fn build_gmhd_box_wraps_gmin() {
        let g = super::GminBox {
            graphicsmode: 0,
            opcolor: [0, 0, 0],
            balance: 0,
        };
        let gmhd = super::build_gmhd_box(&g);
        assert_eq!(&gmhd[4..8], b"gmhd");
        // total = 8 (gmhd header) + 24 (gmin box) = 32
        assert_eq!(gmhd.len(), 32);
        let mut t = fresh_track();
        super::parse_gmhd(&gmhd[8..], &mut t);
        assert_eq!(t.gmin, Some(g));
        assert_eq!(t.tcmi, None);
    }

    /// A `gmhd` carrying an unrelated child before `gmin` still resolves
    /// the `gmin` (media-specific children are skipped).
    #[test]
    fn parse_gmhd_skips_foreign_children() {
        let g = super::GminBox {
            graphicsmode: 0x0040,
            opcolor: [1, 2, 3],
            balance: -64,
        };
        // A `text` media-info child (arbitrary bytes) before the `gmin`.
        let mut inner = super::wrap_box(b"text", &[0xAAu8; 20]);
        inner.extend_from_slice(&super::build_gmin_box(&g));
        let mut t = fresh_track();
        super::parse_gmhd(&inner, &mut t);
        assert_eq!(t.gmin, Some(g));
    }

    /// A timecode-track `gmhd` carrying both a `gmin` and a `tcmi` resolves
    /// each into its own track field.
    #[test]
    fn parse_gmhd_captures_gmin_and_tcmi() {
        let g = super::GminBox {
            graphicsmode: 0,
            opcolor: [0, 0, 0],
            balance: 0,
        };
        let tc = super::TcmiBox {
            text_font: 0,
            text_face: 0,
            text_size: 12,
            text_color: [0xFFFF, 0xFFFF, 0xFFFF],
            background_color: [0, 0, 0],
            font_name: "Chicago".to_string(),
        };
        let mut inner = super::build_gmin_box(&g);
        inner.extend_from_slice(&super::build_tcmi_box(&tc));
        let mut t = fresh_track();
        super::parse_gmhd(&inner, &mut t);
        assert_eq!(t.gmin, Some(g));
        assert_eq!(t.tcmi, Some(tc));
    }

    /// `build_tcmi_box` โ†’ `parse_tcmi_box` is a byte-exact round-trip,
    /// including the Pascal-string font name.
    #[test]
    fn build_tcmi_box_round_trips() {
        let tc = super::TcmiBox {
            text_font: 3,
            text_face: 0x01, // Bold
            text_size: 18,
            text_color: [0x1234, 0x5678, 0x9abc],
            background_color: [0xdead, 0xbeef, 0xcafe],
            font_name: "Monaco".to_string(),
        };
        let boxed = super::build_tcmi_box(&tc);
        assert_eq!(&boxed[4..8], b"tcmi");
        let back = super::parse_tcmi_box(&boxed[8..]).expect("round-trip parse");
        assert_eq!(back, tc);
    }

    /// A `tcmi` with an empty font name round-trips to an empty `String`.
    #[test]
    fn build_tcmi_box_empty_name_round_trips() {
        let tc = super::TcmiBox {
            text_font: 0,
            text_face: 0,
            text_size: 10,
            text_color: [0, 0, 0],
            background_color: [0xFFFF, 0xFFFF, 0xFFFF],
            font_name: String::new(),
        };
        let boxed = super::build_tcmi_box(&tc);
        let back = super::parse_tcmi_box(&boxed[8..]).expect("round-trip parse");
        assert_eq!(back, tc);
    }

    /// Regression (r443 box_parsers fuzz): a `font_name` longer than the
    /// 255-byte Pascal ceiling โ€” which arises when the parser lossily
    /// replaces non-UTF-8 wire bytes (each expands to a 3-byte U+FFFD) โ€”
    /// must truncate at a char boundary so the rebuilt box reparses
    /// cleanly to a prefix, never a body whose declared length slices a
    /// multi-byte char (which grew a replacement-character tail).
    #[test]
    fn build_tcmi_box_truncates_overlong_name_on_char_boundary() {
        // 100 replacement chars = 300 bytes > 255; the 255-byte cut
        // lands mid-char (each U+FFFD is 3 bytes; 255 = 85*3, a clean
        // boundary โ€” so use 86 chars * 3 = 258 and force an 85.33 cut).
        let name: String = "\u{FFFD}".repeat(90);
        let tc = super::TcmiBox {
            text_font: 1,
            text_face: 2,
            text_size: 3,
            text_color: [1, 2, 3],
            background_color: [4, 5, 6],
            font_name: name.clone(),
        };
        let boxed = super::build_tcmi_box(&tc);
        let back = super::parse_tcmi_box(&boxed[8..]).expect("reparse after truncating build");
        // Emitted name is a valid-UTF-8 prefix of the original, โ‰ค 255 B.
        assert!(back.font_name.len() <= 255);
        assert!(name.starts_with(&back.font_name));
        assert_eq!(back.font_name.len() % 3, 0, "cut on a U+FFFD boundary");
        // Idempotent: rebuilding the (now representable) record is exact.
        let boxed2 = super::build_tcmi_box(&back);
        let back2 = super::parse_tcmi_box(&boxed2[8..]).unwrap();
        assert_eq!(back2, back);
    }

    /// A `tcmi` body shorter than the fixed 22-byte prefix is rejected;
    /// a font-name length that overruns the body is clamped rather than
    /// dropping the whole atom.
    #[test]
    fn parse_tcmi_short_and_overrun() {
        assert!(super::parse_tcmi(&[0u8; 21]).is_none());
        assert!(super::parse_tcmi_box(&[0u8; 21]).is_err());
        // 22 fixed bytes + a length byte claiming 200 chars but only 3
        // present โ†’ the name is clamped to the 3 available bytes.
        let mut body = vec![0u8; 22];
        body.push(200);
        body.extend_from_slice(b"abc");
        let tc = super::parse_tcmi(&body).expect("clamped parse");
        assert_eq!(tc.font_name, "abc");
    }

    /// Surfacing: a parsed `tcmi` exposes its rendering parameters on
    /// `params.options` for a timecode track.
    #[test]
    fn build_stream_info_surfaces_tcmi_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"tmcd";
        t.timescale = 1000;
        t.tcmi = Some(super::TcmiBox {
            text_font: 0,
            text_face: 1,
            text_size: 24,
            text_color: [0xFFFF, 0xFFFF, 0xFFFF],
            background_color: [0, 0, 0],
            font_name: "Helvetica".to_string(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("tcmi_text_font"), Some("0"));
        assert_eq!(info.params.options.get("tcmi_text_face"), Some("1"));
        assert_eq!(info.params.options.get("tcmi_text_size"), Some("24"));
        assert_eq!(
            info.params.options.get("tcmi_text_color"),
            Some("65535 65535 65535")
        );
        assert_eq!(
            info.params.options.get("tcmi_background_color"),
            Some("0 0 0")
        );
        assert_eq!(info.params.options.get("tcmi_font_name"), Some("Helvetica"));
    }

    /// `build_tmcd_sample_entry` โ†’ `parse_tmcd_sample_entry_box` is a
    /// byte-exact round-trip; the drop-frame example (29.97 fps NTSC:
    /// timescale 30000, frame_duration 1001, 30 nominal frames, drop-frame
    /// flag) decodes field-for-field.
    #[test]
    fn tmcd_sample_entry_round_trips_ntsc_drop_frame() {
        let e = super::TmcdSampleEntry {
            flags: 0x0001 | 0x0002, // drop-frame + 24-hour max
            timescale: 30_000,
            frame_duration: 1001,
            number_of_frames: 30,
        };
        let boxed = super::build_tmcd_sample_entry(&e, 1);
        assert_eq!(&boxed[4..8], b"tmcd");
        // data_reference_index at preamble offset 6..8 (box header + 6).
        assert_eq!(u16::from_be_bytes([boxed[8 + 6], boxed[8 + 7]]), 1);
        let back = super::parse_tmcd_sample_entry_box(&boxed[8..]).expect("round-trip");
        assert_eq!(back, e);
        assert!(back.drop_frame());
        assert!(back.twenty_four_hour_max());
        assert!(!back.negative_times_ok());
        assert!(!back.counter());
    }

    /// A `tmcd` entry too short to hold the fixed numeric fields is
    /// rejected rather than surfacing truncation noise.
    #[test]
    fn tmcd_sample_entry_too_short_is_rejected() {
        assert!(super::parse_tmcd_sample_entry(&[0u8; 24]).is_none());
        assert!(super::parse_tmcd_sample_entry_box(&[0u8; 24]).is_err());
    }

    /// A `tmcd` entry parsed through `parse_stsd` populates `t.tmcd` and
    /// leaves the FourCC/media-type handling intact.
    #[test]
    fn parse_stsd_captures_tmcd_entry() {
        let e = super::TmcdSampleEntry {
            flags: 0x0008, // counter
            timescale: 25,
            frame_duration: 1,
            number_of_frames: 25,
        };
        let entry = super::build_tmcd_sample_entry(&e, 1);
        // stsd: FullBox preamble (4) + entry_count(=1) + the entry box.
        let mut stsd = vec![0u8, 0, 0, 0];
        stsd.extend_from_slice(&1u32.to_be_bytes());
        stsd.extend_from_slice(&entry);
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        super::parse_stsd(&stsd, &mut t).expect("stsd parse");
        assert_eq!(t.codec_id_fourcc, *b"tmcd");
        assert_eq!(t.tmcd, Some(e));
        assert!(t.tmcd.unwrap().counter());
    }

    /// Surfacing: a parsed `tmcd` sample entry exposes its fields (flags,
    /// decoded booleans, timescale, frame_duration, number_of_frames) on
    /// `params.options`.
    #[test]
    fn build_stream_info_surfaces_tmcd_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"tmcd";
        t.timescale = 30_000;
        t.tmcd = Some(super::TmcdSampleEntry {
            flags: 0x0001,
            timescale: 30_000,
            frame_duration: 1001,
            number_of_frames: 30,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("tmcd_flags"), Some("1"));
        assert_eq!(info.params.options.get("tmcd_drop_frame"), Some("true"));
        assert_eq!(info.params.options.get("tmcd_24hour_max"), Some("false"));
        assert_eq!(info.params.options.get("tmcd_timescale"), Some("30000"));
        assert_eq!(info.params.options.get("tmcd_frame_duration"), Some("1001"));
        assert_eq!(info.params.options.get("tmcd_number_of_frames"), Some("30"));
    }

    /// `build_text_sample_entry` โ†’ `parse_text_sample_entry_box` is a
    /// byte-exact round-trip, including the signed justification, the
    /// signed default-text-box rectangle, and the Pascal-string font name.
    #[test]
    fn text_sample_entry_round_trips() {
        let e = super::TextSampleEntry {
            display_flags: 0x2000 | 0x1000, // anti-alias + drop-shadow
            text_justification: -1,         // right-justified
            background_color: [0x1111, 0x2222, 0x3333],
            default_text_box: [0, 0, 60, 320],
            font_number: 0,
            font_face: 0x02, // italic
            foreground_color: [0xFFFF, 0xFFFF, 0xFFFF],
            text_name: "Geneva".to_string(),
        };
        let boxed = super::build_text_sample_entry(&e, 1);
        assert_eq!(&boxed[4..8], b"text");
        assert_eq!(u16::from_be_bytes([boxed[8 + 6], boxed[8 + 7]]), 1);
        let back = super::parse_text_sample_entry_box(&boxed[8..]).expect("round-trip");
        assert_eq!(back, e);
    }

    /// A `text` entry shorter than the 51-byte fixed prefix is rejected.
    #[test]
    fn text_sample_entry_too_short_is_rejected() {
        assert!(super::parse_text_sample_entry(&[0u8; 50]).is_none());
        assert!(super::parse_text_sample_entry_box(&[0u8; 50]).is_err());
    }

    /// A `text` entry with a font-name length that overruns the body is
    /// clamped to the bytes present rather than dropping the whole entry.
    #[test]
    fn text_sample_entry_name_overrun_clamped() {
        let mut e = vec![0u8; 51];
        e.push(200); // claim 200 chars
        e.extend_from_slice(b"xy");
        let tx = super::parse_text_sample_entry(&e).expect("clamped parse");
        assert_eq!(tx.text_name, "xy");
    }

    /// A `text` entry parsed through `parse_stsd` populates `t.text_entry`
    /// and keeps the raw post-preamble bytes as extradata.
    #[test]
    fn parse_stsd_captures_text_entry() {
        let e = super::TextSampleEntry {
            display_flags: 0,
            text_justification: 1, // centered
            background_color: [0, 0, 0],
            default_text_box: [0, 0, 0, 0],
            font_number: 0,
            font_face: 0,
            foreground_color: [0xFFFF, 0xFFFF, 0xFFFF],
            text_name: String::new(),
        };
        let entry = super::build_text_sample_entry(&e, 1);
        let mut stsd = vec![0u8, 0, 0, 0];
        stsd.extend_from_slice(&1u32.to_be_bytes());
        stsd.extend_from_slice(&entry);
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        super::parse_stsd(&stsd, &mut t).expect("stsd parse");
        assert_eq!(t.codec_id_fourcc, *b"text");
        assert_eq!(t.text_entry, Some(e));
        assert!(!t.extradata.is_empty());
    }

    /// Surfacing: a parsed `text` sample entry exposes its draw parameters
    /// on `params.options`.
    #[test]
    fn build_stream_info_surfaces_text_entry_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        t.codec_id_fourcc = *b"text";
        t.timescale = 1000;
        t.text_entry = Some(super::TextSampleEntry {
            display_flags: 0x2000,
            text_justification: -1,
            background_color: [0, 0, 0],
            default_text_box: [1, 2, 3, 4],
            font_number: 0,
            font_face: 1,
            foreground_color: [0xFFFF, 0xFFFF, 0xFFFF],
            text_name: "Courier".to_string(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("text_display_flags"), Some("8192"));
        assert_eq!(info.params.options.get("text_justification"), Some("-1"));
        assert_eq!(
            info.params.options.get("text_default_text_box"),
            Some("1 2 3 4")
        );
        assert_eq!(
            info.params.options.get("text_foreground_color"),
            Some("65535 65535 65535")
        );
        assert_eq!(info.params.options.get("text_font_face"), Some("1"));
        assert_eq!(info.params.options.get("text_font_name"), Some("Courier"));
    }

    /// `build_load_settings_box` โ†’ `parse_load_settings_box` is a
    /// byte-exact round-trip; the signed `-1` "preload to end of track"
    /// sentinel and the flag / hint decoders behave as specified.
    #[test]
    fn load_settings_round_trips_and_decodes_flags() {
        let ls = super::LoadSettingsBox {
            preload_start_time: 0,
            preload_duration: -1, // to end of track
            preload_flags: 2,     // preload only if enabled
            default_hints: 0x0020 | 0x0100,
        };
        let boxed = super::build_load_settings_box(&ls);
        assert_eq!(&boxed[4..8], b"load");
        assert_eq!(boxed.len(), 24);
        let back = super::parse_load_settings_box(&boxed[8..]).expect("round-trip");
        assert_eq!(back, ls);
        assert!(!back.preload_always());
        assert!(back.preload_if_enabled());
        assert!(back.double_buffer());
        assert!(back.high_quality());
    }

    /// A `load` body shorter than the fixed 16 bytes is rejected.
    #[test]
    fn load_settings_too_short_is_rejected() {
        assert!(super::parse_load_settings(&[0u8; 15]).is_none());
        assert!(super::parse_load_settings_box(&[0u8; 15]).is_err());
    }

    /// A `load` atom nested in a `trak` is picked up by `parse_trak`.
    #[test]
    fn parse_trak_picks_up_nested_load() {
        let ls = super::LoadSettingsBox {
            preload_start_time: 100,
            preload_duration: 5000,
            preload_flags: 1,
            default_hints: 0,
        };
        let mut tkhd = vec![0u8; 92]; // FullBox v0 + 84 bytes
        tkhd[12..16].copy_from_slice(&1u32.to_be_bytes()); // track_id = 1

        let mut mdhd = vec![0u8; 24];
        mdhd[12..16].copy_from_slice(&1000u32.to_be_bytes()); // timescale

        let mut hdlr = Vec::new();
        hdlr.extend_from_slice(&[0u8; 8]);
        hdlr.extend_from_slice(b"vide");
        hdlr.extend_from_slice(&[0u8; 12]);
        hdlr.extend_from_slice(b"\0");

        let mut mdia = Vec::new();
        mdia.extend(wrap_box_full_size(b"mdhd", &mdhd));
        mdia.extend(wrap_box_full_size(b"hdlr", &hdlr));

        let mut trak = Vec::new();
        trak.extend(wrap_box_full_size(b"tkhd", &tkhd));
        trak.extend(wrap_box_full_size(b"mdia", &mdia));
        // `load` is a plain Box: its body is the 16 numeric bytes.
        trak.extend_from_slice(&super::build_load_settings_box(&ls));

        let t = super::parse_trak(&trak, 1 << 30).unwrap().unwrap();
        assert_eq!(t.load_settings, Some(ls));
    }

    /// Surfacing: a parsed `load` exposes its preload / hint fields and the
    /// decoded flag booleans on `params.options`.
    #[test]
    fn build_stream_info_surfaces_load_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.load_settings = Some(super::LoadSettingsBox {
            preload_start_time: 0,
            preload_duration: -1,
            preload_flags: 1,
            default_hints: 0x0100,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("load_preload_duration"), Some("-1"));
        assert_eq!(info.params.options.get("load_preload_flags"), Some("1"));
        assert_eq!(info.params.options.get("load_preload_always"), Some("true"));
        assert_eq!(
            info.params.options.get("load_preload_if_enabled"),
            Some("false")
        );
        assert_eq!(info.params.options.get("load_high_quality"), Some("true"));
        assert_eq!(info.params.options.get("load_double_buffer"), Some("false"));
    }

    /// Surfacing: a parsed `gmin` exposes `gmin_graphicsmode` (decimal),
    /// `gmin_opcolor` (three space-separated decimal components), and
    /// `gmin_balance` (signed decimal) on `params.options`.
    #[test]
    fn build_stream_info_surfaces_gmin_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Subtitle;
        t.codec_id_fourcc = *b"text";
        t.timescale = 1000;
        t.gmin = Some(super::GminBox {
            graphicsmode: 64,
            opcolor: [1, 2, 3],
            balance: -256,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("gmin_graphicsmode"), Some("64"));
        assert_eq!(info.params.options.get("gmin_opcolor"), Some("1 2 3"));
        assert_eq!(info.params.options.get("gmin_balance"), Some("-256"));
    }

    /// Absent `gmin`, none of the `gmin_*` keys are emitted.
    #[test]
    fn build_stream_info_no_gmin_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("gmin_graphicsmode"), None);
        assert_eq!(info.params.options.get("gmin_opcolor"), None);
        assert_eq!(info.params.options.get("gmin_balance"), None);
    }

    /// Build an 8-byte `amve` body (AmbientViewingEnvironmentBox):
    /// `ambient_illuminance` u32 + `ambient_light_x` u16 +
    /// `ambient_light_y` u16, all big-endian.
    fn amve_body(illum: u32, x: u16, y: u16) -> Vec<u8> {
        let mut out = Vec::with_capacity(8);
        out.extend_from_slice(&illum.to_be_bytes());
        out.extend_from_slice(&x.to_be_bytes());
        out.extend_from_slice(&y.to_be_bytes());
        out
    }

    /// Build a 78-byte `VisualSampleEntry` preamble with `width` /
    /// `height` set, followed by any child boxes already in `children`.
    fn video_sample_entry_body(width: u16, height: u16, children: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&[0u8; 6]); // reserved
        out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
        out.extend_from_slice(&[0u8; 16]); // pre_defined + reserved
        out.extend_from_slice(&width.to_be_bytes());
        out.extend_from_slice(&height.to_be_bytes());
        out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // horizresolution 72dpi
        out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // vertresolution 72dpi
        out.extend_from_slice(&[0u8; 4]); // reserved
        out.extend_from_slice(&1u16.to_be_bytes()); // frame_count
        out.extend_from_slice(&[0u8; 32]); // compressorname
        out.extend_from_slice(&0x0018u16.to_be_bytes()); // depth
        out.extend_from_slice(&0xFFFFu16.to_be_bytes()); // pre_defined = -1
        debug_assert_eq!(out.len(), 78);
        out.extend_from_slice(children);
        out
    }

    /// `parse_amve` decodes the BT.2035 reference-environment worked
    /// example (10 lux, D65 chromaticity) field-for-field.
    #[test]
    fn parse_amve_bt2035_example() {
        // 10 lux โ†’ 100000 (0.0001 lux/unit); x = 0.3127 โ†’ 15635; y =
        // 0.3290 โ†’ 16450 (0.00002/unit).
        let body = amve_body(100_000, 15_635, 16_450);
        let rec = super::parse_amve(&body).expect("amve should parse");
        assert_eq!(rec.ambient_illuminance, 100_000);
        assert_eq!(rec.ambient_light_x, 15_635);
        assert_eq!(rec.ambient_light_y, 16_450);
    }

    /// `parse_amve` ignores bytes past the fixed 8-byte body (reserved for
    /// a future edition) rather than failing.
    #[test]
    fn parse_amve_tolerates_trailing_bytes() {
        let mut body = amve_body(7, 1, 2);
        body.extend_from_slice(&[0xAA, 0xBB, 0xCC]);
        let rec = super::parse_amve(&body).expect("amve should parse");
        assert_eq!(rec.ambient_illuminance, 7);
        assert_eq!(rec.ambient_light_x, 1);
        assert_eq!(rec.ambient_light_y, 2);
    }

    /// A body shorter than the fixed 8-byte layout is rejected.
    #[test]
    fn parse_amve_rejects_short_body() {
        assert!(super::parse_amve(&[0u8; 7]).is_none());
        assert!(super::parse_amve(&[]).is_none());
        // The public entry returns Err for the same case.
        assert!(super::parse_amve_box(&[0u8; 7]).is_err());
    }

    /// The public `parse_amve_box` entry decodes a well-formed body.
    #[test]
    fn parse_amve_box_public_entry() {
        let body = amve_body(50_000, 25_000, 30_000);
        let rec = super::parse_amve_box(&body).expect("amve should parse");
        assert_eq!(rec.ambient_illuminance, 50_000);
        assert_eq!(rec.ambient_light_x, 25_000);
        assert_eq!(rec.ambient_light_y, 30_000);
    }

    /// `parse_video_sample_entry` lands an `amve` child box on the track.
    #[test]
    fn parse_video_sample_entry_picks_up_amve() {
        let amve = wrap_box_full_size(b"amve", &amve_body(100_000, 15_635, 16_450));
        let entry = video_sample_entry_body(1920, 1080, &amve);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();

        assert_eq!(t.width, Some(1920));
        assert_eq!(t.height, Some(1080));
        let a = t.amve.expect("amve should be parsed");
        assert_eq!(a.ambient_illuminance, 100_000);
        assert_eq!(a.ambient_light_x, 15_635);
        assert_eq!(a.ambient_light_y, 16_450);
    }

    /// First `amve` wins when two sample-entry child boxes carry one.
    #[test]
    fn parse_video_sample_entry_amve_first_wins() {
        let mut children = wrap_box_full_size(b"amve", &amve_body(1, 2, 3));
        children.extend(wrap_box_full_size(b"amve", &amve_body(9, 9, 9)));
        let entry = video_sample_entry_body(640, 480, &children);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();
        let a = t.amve.expect("amve should be parsed");
        assert_eq!(a.ambient_illuminance, 1);
        assert_eq!(a.ambient_light_x, 2);
        assert_eq!(a.ambient_light_y, 3);
    }

    /// A malformed (too-short) `amve` child box is dropped silently โ€” the
    /// sample entry still parses (width/height land) with no `amve`.
    #[test]
    fn parse_video_sample_entry_drops_malformed_amve() {
        let amve = wrap_box_full_size(b"amve", &[0u8; 4]); // too short
        let entry = video_sample_entry_body(1280, 720, &amve);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();
        assert_eq!(t.width, Some(1280));
        assert!(t.amve.is_none());
    }

    /// Surfacing: a parsed `amve` exposes the three raw fields (decimal)
    /// on `params.options`.
    #[test]
    fn build_stream_info_surfaces_amve_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"hvc1";
        t.timescale = 1000;
        t.amve = Some(super::AmveRecord {
            ambient_illuminance: 100_000,
            ambient_light_x: 15_635,
            ambient_light_y: 16_450,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("amve_ambient_illuminance"),
            Some("100000")
        );
        assert_eq!(
            info.params.options.get("amve_ambient_light_x"),
            Some("15635")
        );
        assert_eq!(
            info.params.options.get("amve_ambient_light_y"),
            Some("16450")
        );
    }

    /// Absence: a track with no `amve` emits none of the `amve_*` keys.
    #[test]
    fn build_stream_info_no_amve_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("amve_ambient_illuminance"), None);
        assert_eq!(info.params.options.get("amve_ambient_light_x"), None);
        assert_eq!(info.params.options.get("amve_ambient_light_y"), None);
    }

    /// Build a 12-byte `btrt` body (BitRateBox): `bufferSizeDB` +
    /// `maxBitrate` + `avgBitrate`, all big-endian u32.
    fn btrt_body(buf: u32, max: u32, avg: u32) -> Vec<u8> {
        let mut out = Vec::with_capacity(12);
        out.extend_from_slice(&buf.to_be_bytes());
        out.extend_from_slice(&max.to_be_bytes());
        out.extend_from_slice(&avg.to_be_bytes());
        out
    }

    /// `parse_btrt` decodes the three big-endian u32 fields field-for-field.
    #[test]
    fn parse_btrt_three_u32_fields() {
        let body = btrt_body(65_536, 5_000_000, 3_200_000);
        let rec = super::parse_btrt(&body).expect("btrt should parse");
        assert_eq!(rec.buffer_size_db, 65_536);
        assert_eq!(rec.max_bitrate, 5_000_000);
        assert_eq!(rec.avg_bitrate, 3_200_000);
    }

    /// `parse_btrt` ignores bytes past the fixed 12-byte body rather than
    /// failing, matching the `parse_amve` posture.
    #[test]
    fn parse_btrt_tolerates_trailing_bytes() {
        let mut body = btrt_body(1, 2, 3);
        body.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
        let rec = super::parse_btrt(&body).expect("btrt should parse");
        assert_eq!(rec.buffer_size_db, 1);
        assert_eq!(rec.max_bitrate, 2);
        assert_eq!(rec.avg_bitrate, 3);
    }

    /// A body shorter than the fixed 12 bytes is rejected; the public
    /// entry returns `Err` for the same input.
    #[test]
    fn parse_btrt_rejects_short_body() {
        assert!(super::parse_btrt(&[0u8; 11]).is_none());
        assert!(super::parse_btrt(&[]).is_none());
        assert!(super::parse_btrt_box(&[0u8; 11]).is_err());
    }

    /// The public `parse_btrt_box` entry decodes a well-formed body.
    #[test]
    fn parse_btrt_box_public_entry() {
        let body = btrt_body(8_192, 1_500_000, 900_000);
        let rec = super::parse_btrt_box(&body).expect("btrt should parse");
        assert_eq!(rec.buffer_size_db, 8_192);
        assert_eq!(rec.max_bitrate, 1_500_000);
        assert_eq!(rec.avg_bitrate, 900_000);
    }

    /// `parse_video_sample_entry` lands a `btrt` child box on the track.
    #[test]
    fn parse_video_sample_entry_picks_up_btrt() {
        let btrt = wrap_box_full_size(b"btrt", &btrt_body(131_072, 8_000_000, 6_000_000));
        let entry = video_sample_entry_body(3840, 2160, &btrt);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();

        assert_eq!(t.width, Some(3840));
        let b = t.btrt.expect("btrt should be parsed");
        assert_eq!(b.buffer_size_db, 131_072);
        assert_eq!(b.max_bitrate, 8_000_000);
        assert_eq!(b.avg_bitrate, 6_000_000);
    }

    fn pasp_body(h: u32, v: u32) -> Vec<u8> {
        let mut b = h.to_be_bytes().to_vec();
        b.extend_from_slice(&v.to_be_bytes());
        b
    }

    fn clap_body(vals: [u32; 8]) -> Vec<u8> {
        let mut b = Vec::new();
        for v in vals {
            b.extend_from_slice(&v.to_be_bytes());
        }
        b
    }

    #[test]
    fn parse_pasp_clap_colr_bodies() {
        let p = super::parse_pasp(&pasp_body(16, 15)).unwrap();
        assert_eq!(p.h_spacing, 16);
        assert_eq!(p.v_spacing, 15);
        assert!(super::parse_pasp(&[0u8; 4]).is_none());

        let c = super::parse_clap(&clap_body([1920, 1, 1080, 1, 0, 1, 0, 1])).unwrap();
        assert_eq!(c.width_n, 1920);
        assert_eq!(c.height_n, 1080);
        assert_eq!(c.horiz_off_d, 1);
        assert!(super::parse_clap(&[0u8; 16]).is_none());

        // nclx: BT.709 primaries(1)/transfer(1)/matrix(1), full-range set.
        let mut nclx = b"nclx".to_vec();
        nclx.extend_from_slice(&1u16.to_be_bytes());
        nclx.extend_from_slice(&1u16.to_be_bytes());
        nclx.extend_from_slice(&1u16.to_be_bytes());
        nclx.push(0x80); // full_range_flag=1
        match super::parse_colr(&nclx).unwrap() {
            super::ColrRecord::Nclx {
                colour_primaries,
                transfer_characteristics,
                matrix_coefficients,
                full_range,
            } => {
                assert_eq!(colour_primaries, 1);
                assert_eq!(transfer_characteristics, 1);
                assert_eq!(matrix_coefficients, 1);
                assert!(full_range);
            }
            other => panic!("expected nclx, got {other:?}"),
        }

        // prof: an ICC profile (raw bytes preserved).
        let mut prof = b"prof".to_vec();
        prof.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
        match super::parse_colr(&prof).unwrap() {
            super::ColrRecord::UnrestrictedIcc(d) => {
                assert_eq!(d, vec![0xDE, 0xAD, 0xBE, 0xEF])
            }
            other => panic!("expected prof, got {other:?}"),
        }

        // unknown colour type โ†’ Other.
        let mut other = b"xxxx".to_vec();
        other.push(9);
        match super::parse_colr(&other).unwrap() {
            super::ColrRecord::Other { colour_type, data } => {
                assert_eq!(&colour_type, b"xxxx");
                assert_eq!(data, vec![9]);
            }
            o => panic!("expected Other, got {o:?}"),
        }
        assert!(super::parse_colr(&[1, 2, 3]).is_none());
    }

    #[test]
    fn build_pasp_clap_colr_round_trip() {
        let p = super::PaspRecord {
            h_spacing: 64,
            v_spacing: 45,
        };
        let built = super::build_pasp_box(&p);
        assert_eq!(super::parse_pasp_box(&built[8..]).unwrap(), p);

        let c = super::ClapRecord {
            width_n: 1920,
            width_d: 1,
            height_n: 1080,
            height_d: 1,
            horiz_off_n: 3,
            horiz_off_d: 2,
            vert_off_n: 5,
            vert_off_d: 4,
        };
        let built = super::build_clap_box(&c);
        assert_eq!(super::parse_clap_box(&built[8..]).unwrap(), c);

        for colr in [
            super::ColrRecord::Nclx {
                colour_primaries: 9,
                transfer_characteristics: 16,
                matrix_coefficients: 9,
                full_range: true,
            },
            super::ColrRecord::UnrestrictedIcc(vec![1, 2, 3, 4]),
            super::ColrRecord::RestrictedIcc(vec![9, 8, 7]),
            super::ColrRecord::Other {
                colour_type: *b"zzzz",
                data: vec![0, 1, 2],
            },
        ] {
            let built = super::build_colr_box(&colr);
            assert_eq!(super::parse_colr_box(&built[8..]).unwrap(), colr);
        }
    }

    #[test]
    fn parse_video_sample_entry_picks_up_pasp_clap_colr() {
        let mut children = wrap_box_full_size(b"pasp", &pasp_body(40, 33));
        children.extend(wrap_box_full_size(
            b"clap",
            &clap_body([1280, 1, 720, 1, 0, 1, 0, 1]),
        ));
        let mut nclx = b"nclx".to_vec();
        nclx.extend_from_slice(&9u16.to_be_bytes()); // primaries BT.2020
        nclx.extend_from_slice(&16u16.to_be_bytes()); // transfer PQ
        nclx.extend_from_slice(&9u16.to_be_bytes()); // matrix BT.2020-NC
        nclx.push(0x00); // full_range = 0
        children.extend(wrap_box_full_size(b"colr", &nclx));
        let entry = video_sample_entry_body(1280, 720, &children);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();

        assert_eq!(t.pasp.unwrap().h_spacing, 40);
        assert_eq!(t.clap.unwrap().width_n, 1280);
        match t.colr.unwrap() {
            super::ColrRecord::Nclx {
                colour_primaries,
                full_range,
                ..
            } => {
                assert_eq!(colour_primaries, 9);
                assert!(!full_range);
            }
            o => panic!("expected nclx, got {o:?}"),
        }
    }

    #[test]
    fn build_stream_info_surfaces_pasp_clap_colr_options() {
        let mut children = wrap_box_full_size(b"pasp", &pasp_body(64, 45));
        children.extend(wrap_box_full_size(
            b"clap",
            &clap_body([1920, 1, 1080, 1, 0, 1, 0, 1]),
        ));
        let mut nclx = b"nclx".to_vec();
        nclx.extend_from_slice(&1u16.to_be_bytes());
        nclx.extend_from_slice(&1u16.to_be_bytes());
        nclx.extend_from_slice(&1u16.to_be_bytes());
        nclx.push(0x80);
        children.extend(wrap_box_full_size(b"colr", &nclx));
        let entry = video_sample_entry_body(1920, 1080, &children);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        super::parse_video_sample_entry(&entry, &mut t).unwrap();
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        let o = &info.params.options;
        assert_eq!(o.get("pasp_h_spacing"), Some("64"));
        assert_eq!(o.get("pasp_v_spacing"), Some("45"));
        assert_eq!(o.get("clap_width"), Some("1920/1"));
        assert_eq!(o.get("clap_horiz_off"), Some("0/1"));
        assert_eq!(o.get("colr_type"), Some("nclx"));
        assert_eq!(o.get("colr_primaries"), Some("1"));
        assert_eq!(o.get("colr_full_range"), Some("1"));
    }

    /// First `btrt` wins when two sample-entry child boxes carry one.
    #[test]
    fn parse_video_sample_entry_btrt_first_wins() {
        let mut children = wrap_box_full_size(b"btrt", &btrt_body(1, 2, 3));
        children.extend(wrap_box_full_size(b"btrt", &btrt_body(9, 9, 9)));
        let entry = video_sample_entry_body(640, 480, &children);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();
        let b = t.btrt.expect("btrt should be parsed");
        assert_eq!(b.buffer_size_db, 1);
        assert_eq!(b.max_bitrate, 2);
        assert_eq!(b.avg_bitrate, 3);
    }

    /// A malformed (too-short) `btrt` child box is dropped silently โ€” the
    /// sample entry still parses (width/height land) with no `btrt`.
    #[test]
    fn parse_video_sample_entry_drops_malformed_btrt() {
        let btrt = wrap_box_full_size(b"btrt", &[0u8; 8]); // too short
        let entry = video_sample_entry_body(1280, 720, &btrt);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();
        assert_eq!(t.width, Some(1280));
        assert!(t.btrt.is_none());
    }

    /// `parse_audio_sample_entry` also lands a `btrt` (the box is
    /// codec-agnostic and may follow any sample entry, ยง8.5.2).
    #[test]
    fn parse_audio_sample_entry_picks_up_btrt() {
        let btrt = wrap_box_full_size(b"btrt", &btrt_body(4_096, 256_000, 192_000));
        let mut entry = audio_sample_entry_body(2, 1);
        entry.extend_from_slice(&btrt);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        super::parse_audio_sample_entry(&entry, &mut t).unwrap();

        assert_eq!(t.channels, Some(2));
        let b = t.btrt.expect("btrt should be parsed");
        assert_eq!(b.buffer_size_db, 4_096);
        assert_eq!(b.max_bitrate, 256_000);
        assert_eq!(b.avg_bitrate, 192_000);
    }

    /// Surfacing: a parsed `btrt` exposes the three fields (decimal) on
    /// `params.options`.
    #[test]
    fn build_stream_info_surfaces_btrt_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.btrt = Some(super::BtrtRecord {
            buffer_size_db: 131_072,
            max_bitrate: 8_000_000,
            avg_bitrate: 6_000_000,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("btrt_buffer_size_db"),
            Some("131072")
        );
        assert_eq!(info.params.options.get("btrt_max_bitrate"), Some("8000000"));
        assert_eq!(info.params.options.get("btrt_avg_bitrate"), Some("6000000"));
    }

    /// Absence: a track with no `btrt` emits none of the `btrt_*` keys.
    #[test]
    fn build_stream_info_no_btrt_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("btrt_buffer_size_db"), None);
        assert_eq!(info.params.options.get("btrt_max_bitrate"), None);
        assert_eq!(info.params.options.get("btrt_avg_bitrate"), None);
    }

    /// Build an `stvi` (StereoVideoBox) body, FullBox-preamble-relative:
    /// `int(30) reserved | int(2) single_view_allowed` (one big-endian
    /// u32 word) + `int(32) stereo_scheme` + `int(32) length` +
    /// `int(8)[length] stereo_indication_type`. The 4-byte FullBox
    /// version/flags preamble is prepended (version 0, flags 0).
    fn stvi_body(single_view_allowed: u8, stereo_scheme: u32, indication: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        // FullBox version 0, flags 0.
        out.extend_from_slice(&[0u8; 4]);
        // First word: reserved(30) high bits zero, single_view_allowed(2)
        // low bits.
        let word = (single_view_allowed as u32) & 0x3;
        out.extend_from_slice(&word.to_be_bytes());
        out.extend_from_slice(&stereo_scheme.to_be_bytes());
        out.extend_from_slice(&(indication.len() as u32).to_be_bytes());
        out.extend_from_slice(indication);
        out
    }

    /// `parse_stvi` decodes a scheme-1 (14496-10 frame-packing) box: a
    /// 4-byte `stereo_indication_type` carrying a u32 arrangement type.
    #[test]
    fn parse_stvi_scheme1_frame_packing() {
        // single_view_allowed = 3 (both views OK on monoscopic);
        // stereo_scheme = 1; indication = side-by-side type (3) as u32.
        let body = stvi_body(3, 1, &3u32.to_be_bytes());
        let rec = super::parse_stvi(&body).expect("stvi should parse");
        assert_eq!(rec.single_view_allowed, 3);
        assert_eq!(rec.stereo_scheme, 1);
        assert_eq!(rec.stereo_indication_type, vec![0, 0, 0, 3]);
        assert!(rec.right_view_monoscopic_allowed());
        assert!(rec.left_view_monoscopic_allowed());
    }

    /// `parse_stvi` masks the 30 reserved high bits off the first word so
    /// a producer slip on them does not corrupt `single_view_allowed`.
    #[test]
    fn parse_stvi_masks_reserved_bits() {
        // scheme 3, 2-byte indication. The helper wrote 0x0000_0000 in
        // the first word (bytes 4..8) for single_view_allowed = 0; set
        // some reserved high bits there to prove they are masked off.
        let mut body = stvi_body(0, 3, &[0x01, 0x00]);
        body[4] = 0xFF;
        body[5] = 0xFF;
        body[6] = 0xFF;
        body[7] = 0xFE; // low 2 bits = 0b10 โ†’ single_view_allowed = 2
        let rec = super::parse_stvi(&body).expect("stvi should parse");
        assert_eq!(rec.single_view_allowed, 2);
        assert!(!rec.right_view_monoscopic_allowed());
        assert!(rec.left_view_monoscopic_allowed());
        assert_eq!(rec.stereo_scheme, 3);
        assert_eq!(rec.stereo_indication_type, vec![0x01, 0x00]);
    }

    /// `parse_stvi` ignores trailing optional `any_box` bytes after the
    /// `stereo_indication_type` array.
    #[test]
    fn parse_stvi_ignores_trailing_any_box() {
        let mut body = stvi_body(1, 1, &4u32.to_be_bytes());
        // Append a fake trailing box.
        body.extend_from_slice(&8u32.to_be_bytes());
        body.extend_from_slice(b"free");
        let rec = super::parse_stvi(&body).expect("stvi should parse");
        assert_eq!(rec.single_view_allowed, 1);
        assert_eq!(rec.stereo_indication_type, vec![0, 0, 0, 4]);
    }

    /// A `length` that overruns the bytes present is rejected rather than
    /// reading past the end or into trailing box content.
    #[test]
    fn parse_stvi_rejects_overrunning_length() {
        let mut body = stvi_body(0, 1, &[]);
        // Body now has length = 0; rewrite the length field (bytes 12..16)
        // to claim 16 indication bytes that are not present.
        body[12..16].copy_from_slice(&16u32.to_be_bytes());
        assert!(super::parse_stvi(&body).is_none());
    }

    /// A body too short to hold the fixed header is rejected; the public
    /// entry returns `Err` for the same input.
    #[test]
    fn parse_stvi_rejects_short_body() {
        assert!(super::parse_stvi(&[0u8; 15]).is_none());
        assert!(super::parse_stvi_box(&[0u8; 15]).is_err());
    }

    /// The public `parse_stvi_box` entry decodes a well-formed body.
    #[test]
    fn parse_stvi_box_public_entry() {
        let body = stvi_body(2, 2, &7u32.to_be_bytes());
        let rec = super::parse_stvi_box(&body).expect("stvi should parse");
        assert_eq!(rec.single_view_allowed, 2);
        assert_eq!(rec.stereo_scheme, 2);
        assert_eq!(rec.stereo_indication_type, vec![0, 0, 0, 7]);
    }

    /// An empty `stereo_indication_type` (length 0) parses with an empty
    /// byte vec.
    #[test]
    fn parse_stvi_empty_indication() {
        let body = stvi_body(0, 99, &[]);
        let rec = super::parse_stvi(&body).expect("stvi should parse");
        assert_eq!(rec.stereo_scheme, 99);
        assert!(rec.stereo_indication_type.is_empty());
    }

    /// `walk_schi` recovers an `stvi` child from a `schi` body.
    #[test]
    fn walk_schi_picks_up_stvi() {
        let stvi = wrap_box_full_size(b"stvi", &stvi_body(1, 1, &3u32.to_be_bytes()));
        let children = super::walk_schi(&stvi);
        let s = children.stvi.expect("stvi should be parsed");
        assert_eq!(s.single_view_allowed, 1);
        assert_eq!(s.stereo_scheme, 1);
        assert!(children.tenc.is_none());
    }

    /// A non-encrypted restricted-scheme video sample entry carries its
    /// `sinf` directly as a child box: `parse_video_sample_entry`
    /// descends it into `schi` and lands the `stvi` on the track.
    #[test]
    fn parse_video_sample_entry_picks_up_stvi_via_sinf() {
        let stvi = wrap_box_full_size(b"stvi", &stvi_body(3, 1, &3u32.to_be_bytes()));
        let schi = wrap_box_full_size(b"schi", &stvi);
        let sinf = wrap_box_full_size(b"sinf", &schi);
        let entry = video_sample_entry_body(1920, 1080, &sinf);

        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        super::parse_video_sample_entry(&entry, &mut t).unwrap();

        assert_eq!(t.width, Some(1920));
        let s = t.stvi.expect("stvi should be parsed");
        assert_eq!(s.single_view_allowed, 3);
        assert_eq!(s.stereo_scheme, 1);
        assert_eq!(s.stereo_indication_type, vec![0, 0, 0, 3]);
    }

    /// Surfacing: a parsed `stvi` exposes its fields on `params.options`,
    /// with the indication bytes as lowercase hex.
    #[test]
    fn build_stream_info_surfaces_stvi_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.stvi = Some(super::StviRecord {
            single_view_allowed: 3,
            stereo_scheme: 1,
            stereo_indication_type: vec![0x00, 0x00, 0x00, 0x03],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("stvi_single_view_allowed"),
            Some("3")
        );
        assert_eq!(info.params.options.get("stvi_stereo_scheme"), Some("1"));
        assert_eq!(info.params.options.get("stvi_indication"), Some("00000003"));
    }

    /// An empty indication omits the `stvi_indication` key (the two
    /// fixed-field keys still emit).
    #[test]
    fn build_stream_info_stvi_empty_indication_omits_hex() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.stvi = Some(super::StviRecord {
            single_view_allowed: 0,
            stereo_scheme: 2,
            stereo_indication_type: Vec::new(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("stvi_single_view_allowed"),
            Some("0")
        );
        assert_eq!(info.params.options.get("stvi_stereo_scheme"), Some("2"));
        assert_eq!(info.params.options.get("stvi_indication"), None);
    }

    #[test]
    fn build_stream_info_surfaces_rtp_hint_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"rtp ";
        t.timescale = 90_000;
        t.rtp_hint = Some(crate::hint::RtpHintSampleEntry {
            format: *b"rtp ",
            data_reference_index: 1,
            hint_track_version: 1,
            highest_compatible_version: 1,
            max_packet_size: 1450,
            timescale: Some(90_000),
            time_offset: Some(-100),
            sequence_offset: Some(42),
            srpp: None,
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("rtp_hint_format"), Some("rtp "));
        assert_eq!(
            info.params.options.get("rtp_hint_max_packet_size"),
            Some("1450")
        );
        assert_eq!(info.params.options.get("rtp_hint_timescale"), Some("90000"));
        assert_eq!(
            info.params.options.get("rtp_hint_time_offset"),
            Some("-100")
        );
        assert_eq!(
            info.params.options.get("rtp_hint_sequence_offset"),
            Some("42")
        );
        assert_eq!(info.params.options.get("rtp_hint_srtp"), None);
    }

    #[test]
    fn build_stream_info_srtp_hint_marks_srtp() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"srtp";
        t.timescale = 90_000;
        t.rtp_hint = Some(crate::hint::RtpHintSampleEntry {
            format: *b"srtp",
            data_reference_index: 1,
            hint_track_version: 1,
            highest_compatible_version: 1,
            max_packet_size: 1400,
            timescale: Some(90_000),
            time_offset: None,
            sequence_offset: None,
            srpp: Some(crate::hint::SrppBox {
                version: 0,
                encryption_algorithm_rtp: 0x2020_2020,
                encryption_algorithm_rtcp: 0x2020_2020,
                integrity_algorithm_rtp: 0x2020_2020,
                integrity_algorithm_rtcp: 0x2020_2020,
                scheme_bytes: vec![],
            }),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("rtp_hint_format"), Some("srtp"));
        assert_eq!(info.params.options.get("rtp_hint_srtp"), Some("true"));
        // tsro/snro absent โ†’ keys omitted.
        assert_eq!(info.params.options.get("rtp_hint_time_offset"), None);
        assert_eq!(info.params.options.get("rtp_hint_sequence_offset"), None);
    }

    #[test]
    fn build_stream_info_no_rtp_hint_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("rtp_hint_format"), None);
        assert_eq!(info.params.options.get("rtp_hint_max_packet_size"), None);
    }

    #[test]
    fn build_stream_info_surfaces_mpeg2ts_hint_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"sm2t";
        t.timescale = 90_000;
        t.mpeg2ts_hint = Some(crate::hint::Mpeg2TsHintSampleEntry {
            format: *b"sm2t",
            data_reference_index: 1,
            hint_track_version: 1,
            highest_compatible_version: 1,
            preceding_bytes_len: 4,
            trailing_bytes_len: 16,
            precomputed_only: true,
            additional_data: vec![],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("m2t_hint_format"), Some("sm2t"));
        assert_eq!(
            info.params.options.get("m2t_hint_preceding_bytes"),
            Some("4")
        );
        assert_eq!(
            info.params.options.get("m2t_hint_trailing_bytes"),
            Some("16")
        );
        assert_eq!(
            info.params.options.get("m2t_hint_precomputed"),
            Some("true")
        );
    }

    #[test]
    fn build_stream_info_surfaces_hinf_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"rtp ";
        t.timescale = 90_000;
        t.hint_stats = crate::hint::HintStatistics {
            bytes_sent_with_rtp_64: Some(1_000_000),
            packets_sent_64: Some(5000),
            bytes_sent_no_rtp_64: Some(940_000),
            media_bytes_sent: Some(800_000),
            largest_packet: Some(1452),
            max_rates: vec![
                crate::hint::MaxRate {
                    period: 1000,
                    bytes: 64_000,
                },
                crate::hint::MaxRate {
                    period: 2000,
                    bytes: 120_000,
                },
            ],
            payload_ids: vec![crate::hint::PayloadId {
                payload_id: 96,
                rtpmap: "H264/90000".to_string(),
            }],
            ..crate::hint::HintStatistics::default()
        };
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("hinf_bytes_sent"), Some("1000000"));
        assert_eq!(info.params.options.get("hinf_packets_sent"), Some("5000"));
        assert_eq!(
            info.params.options.get("hinf_payload_bytes"),
            Some("940000")
        );
        assert_eq!(info.params.options.get("hinf_media_bytes"), Some("800000"));
        assert_eq!(info.params.options.get("hinf_largest_packet"), Some("1452"));
        assert_eq!(info.params.options.get("hinf_maxr_count"), Some("2"));
        assert_eq!(info.params.options.get("hinf_payload_count"), Some("1"));
        // Absent sub-boxes omit their keys.
        assert_eq!(info.params.options.get("hinf_immediate_bytes"), None);
    }

    #[test]
    fn build_stream_info_no_hinf_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("hinf_bytes_sent"), None);
        assert_eq!(info.params.options.get("hinf_maxr_count"), None);
    }

    #[test]
    fn build_stream_info_mpeg2ts_hint_no_precomputed_omits_key() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Data;
        t.codec_id_fourcc = *b"rm2t";
        t.timescale = 90_000;
        t.mpeg2ts_hint = Some(crate::hint::Mpeg2TsHintSampleEntry {
            format: *b"rm2t",
            data_reference_index: 1,
            hint_track_version: 1,
            highest_compatible_version: 1,
            preceding_bytes_len: 0,
            trailing_bytes_len: 0,
            precomputed_only: false,
            additional_data: vec![],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("m2t_hint_format"), Some("rm2t"));
        assert_eq!(info.params.options.get("m2t_hint_precomputed"), None);
    }

    /// Absence: a track with no `stvi` emits none of the `stvi_*` keys.
    #[test]
    fn build_stream_info_no_stvi_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stvi_single_view_allowed"), None);
        assert_eq!(info.params.options.get("stvi_stereo_scheme"), None);
        assert_eq!(info.params.options.get("stvi_indication"), None);
    }

    /// Build a `dref` body: FullBox(0,0) preamble + entry_count + the
    /// concatenated child boxes.
    fn build_dref(children: &[Vec<u8>]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0, flags 0
        body.extend_from_slice(&(children.len() as u32).to_be_bytes());
        for c in children {
            body.extend_from_slice(c);
        }
        body
    }

    /// A self-contained `url ` entry: 4-byte FullBox preamble with the
    /// low flag bit set, no string body.
    fn url_self_contained() -> Vec<u8> {
        wrap_box_full_size(b"url ", &[0u8, 0, 0, 1])
    }

    /// An external `url ` entry: flags = 0, then a NULL-terminated URL.
    fn url_external(loc: &str) -> Vec<u8> {
        let mut payload = vec![0u8; 4]; // version 0, flags 0
        payload.extend_from_slice(loc.as_bytes());
        payload.push(0);
        wrap_box_full_size(b"url ", &payload)
    }

    /// ยง8.7.2.2: the canonical single self-contained `url ` entry โ€” the
    /// overwhelmingly common shape. Parses to one entry, self-contained,
    /// no location string.
    #[test]
    fn parse_dref_single_self_contained_url() {
        let body = build_dref(&[url_self_contained()]);
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(&d.entries[0].kind, b"url ");
        assert!(d.entries[0].is_self_contained());
        assert_eq!(d.entries[0].location, None);
        assert_eq!(d.entries[0].name, None);
    }

    /// ยง8.7.2.3: a `url ` entry whose self-contained bit is clear carries
    /// a NULL-terminated `location` URL naming the external resource.
    #[test]
    fn parse_dref_external_url_location() {
        let body = build_dref(&[url_external("http://example.com/a.mp4")]);
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert!(!d.entries[0].is_self_contained());
        assert_eq!(
            d.entries[0].location.as_deref(),
            Some("http://example.com/a.mp4")
        );
    }

    /// ยง8.7.2.2: a `urn ` entry carries a NULL-terminated `name` (the URN)
    /// followed by an optional NULL-terminated `location`.
    #[test]
    fn parse_dref_urn_name_and_location() {
        let mut payload = vec![0u8; 4]; // version 0, flags 0
        payload.extend_from_slice(b"urn:example:res");
        payload.push(0);
        payload.extend_from_slice(b"ftp://host/res");
        payload.push(0);
        let body = build_dref(&[wrap_box_full_size(b"urn ", &payload)]);
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(&d.entries[0].kind, b"urn ");
        assert_eq!(d.entries[0].name.as_deref(), Some("urn:example:res"));
        assert_eq!(d.entries[0].location.as_deref(), Some("ftp://host/res"));
    }

    /// ยง8.7.2.3: `location` is optional for a `urn ` โ€” a name with no
    /// trailing location string parses with `location == None`.
    #[test]
    fn parse_dref_urn_name_only() {
        let mut payload = vec![0u8; 4];
        payload.extend_from_slice(b"urn:example:res");
        payload.push(0);
        let body = build_dref(&[wrap_box_full_size(b"urn ", &payload)]);
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries[0].name.as_deref(), Some("urn:example:res"));
        assert_eq!(d.entries[0].location, None);
    }

    /// ยง8.7.2: a split-source track โ€” two entries, the first
    /// self-contained, the second external. The 1-based entry order is
    /// preserved (it aligns with `data_reference_index`).
    #[test]
    fn parse_dref_multiple_entries_order_preserved() {
        let body = build_dref(&[url_self_contained(), url_external("rel/path.bin")]);
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries.len(), 2);
        assert!(d.entries[0].is_self_contained());
        assert!(!d.entries[1].is_self_contained());
        assert_eq!(d.entries[1].location.as_deref(), Some("rel/path.bin"));
    }

    /// ยง8.7.2.1: a non-`url `/`urn ` child is non-conforming and is
    /// dropped (no bogus entry inserted), but conforming siblings around
    /// it still parse.
    #[test]
    fn parse_dref_drops_unknown_child() {
        let bogus = wrap_box_full_size(b"foo ", &[0u8; 4]);
        let body = build_dref(&[bogus, url_self_contained()]);
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert!(d.entries[0].is_self_contained());
    }

    /// A `dref` body shorter than the 8-byte FullBox + entry_count floor
    /// is rejected.
    #[test]
    fn parse_dref_too_short_is_rejected() {
        assert!(super::parse_dref(&[0u8; 7]).is_err());
    }

    /// A forged `entry_count` far larger than the bytes present does not
    /// over-allocate and does not invent entries โ€” parsing stops at the
    /// real data.
    #[test]
    fn parse_dref_forged_count_does_not_overrun() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(&0xFFFF_FFFFu32.to_be_bytes()); // forged count
        body.extend_from_slice(&url_self_contained());
        let d = super::parse_dref(&body).unwrap();
        assert_eq!(d.entries.len(), 1);
    }

    /// `parse_minf` walks `dinf` โ†’ `dref` and lands the table on the
    /// track.
    #[test]
    fn parse_minf_picks_up_dref_via_dinf() {
        let dref = build_dref(&[url_external("http://h/v.mp4")]);
        let dref_box = wrap_box_full_size(b"dref", &dref);
        let dinf = wrap_box_full_size(b"dinf", &dref_box);

        let mut t = fresh_track();
        super::parse_minf(&dinf, &mut t, 1 << 30).unwrap();
        let d = t.dref.expect("dref should be parsed");
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].location.as_deref(), Some("http://h/v.mp4"));
    }

    /// Surfacing: a single self-contained `url ` (the common case)
    /// collapses to `dref_self_contained = "true"` with no per-entry
    /// or count keys.
    #[test]
    fn build_stream_info_surfaces_single_self_contained_dref() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.dref = Some(super::DrefBox {
            entries: vec![super::DataEntry {
                kind: *b"url ",
                flags: 1,
                name: None,
                location: None,
            }],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("dref_self_contained"), Some("true"));
        assert_eq!(info.params.options.get("dref_count"), None);
        assert_eq!(info.params.options.get("dref_1"), None);
    }

    /// Surfacing: an external split-source `dref` emits `dref_count`,
    /// `dref_self_contained = "false"`, and a `dref_<n>` per entry.
    #[test]
    fn build_stream_info_surfaces_external_dref_entries() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.dref = Some(super::DrefBox {
            entries: vec![
                super::DataEntry {
                    kind: *b"url ",
                    flags: 1,
                    name: None,
                    location: None,
                },
                super::DataEntry {
                    kind: *b"urn ",
                    flags: 0,
                    name: Some("urn:x".to_string()),
                    location: Some("http://h/r".to_string()),
                },
            ],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("dref_self_contained"),
            Some("false")
        );
        assert_eq!(info.params.options.get("dref_count"), Some("2"));
        assert_eq!(info.params.options.get("dref_1"), Some("url  self=true"));
        assert_eq!(
            info.params.options.get("dref_2"),
            Some("urn  self=false name=urn:x loc=http://h/r")
        );
    }

    /// Absence: a track with no `dref` emits none of the `dref_*` keys.
    #[test]
    fn build_stream_info_no_dref_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("dref_self_contained"), None);
        assert_eq!(info.params.options.get("dref_count"), None);
    }

    /// ยง8.6.3 โ€” `stsh` with two `(shadowed, sync)` pairs. Verifies both
    /// big-endian u32 members of each entry are read in order.
    #[test]
    fn parse_stsh_two_entries() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
        body.extend_from_slice(&2u32.to_be_bytes()); // entry_count
        body.extend_from_slice(&7u32.to_be_bytes()); // shadowed_sample_number
        body.extend_from_slice(&1u32.to_be_bytes()); // sync_sample_number
        body.extend_from_slice(&13u32.to_be_bytes());
        body.extend_from_slice(&10u32.to_be_bytes());
        let v = super::parse_stsh(&body).unwrap();
        assert_eq!(v, vec![(7, 1), (13, 10)]);
    }

    /// A zero-entry `stsh` (header only) parses to an empty table rather
    /// than failing.
    #[test]
    fn parse_stsh_empty_table() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
        body.extend_from_slice(&0u32.to_be_bytes()); // entry_count = 0
        let v = super::parse_stsh(&body).unwrap();
        assert!(v.is_empty());
    }

    /// An `stsh` with no room for even the FullBox + count preamble is
    /// rejected.
    #[test]
    fn parse_stsh_too_short() {
        assert!(super::parse_stsh(&[0u8, 0, 0, 0, 0, 0, 0]).is_err());
    }

    /// An `stsh` whose body is cut off mid-entry (here a count of 2 but
    /// only one full pair of bytes) is rejected rather than truncated to
    /// the bytes present.
    #[test]
    fn parse_stsh_truncated() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags
        body.extend_from_slice(&2u32.to_be_bytes()); // claims 2 entries
        body.extend_from_slice(&7u32.to_be_bytes()); // shadowed (entry 1)
        body.extend_from_slice(&1u32.to_be_bytes()); // sync (entry 1)
        body.extend_from_slice(&13u32.to_be_bytes()); // shadowed (entry 2) โ€” sync missing
        assert!(super::parse_stsh(&body).is_err());
    }

    /// An adversarial `entry_count` far larger than the body cannot
    /// trigger a giant up-front allocation: `with_capacity` is clamped to
    /// the byte budget and the per-entry bounds check rejects the box.
    #[test]
    fn parse_stsh_huge_count_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags
        body.extend_from_slice(&u32::MAX.to_be_bytes()); // claims ~4 billion entries
        body.extend_from_slice(&1u32.to_be_bytes()); // only one u32 of payload
        assert!(super::parse_stsh(&body).is_err());
    }

    /// `parse_stbl` lands the `stsh` on the track alongside the other
    /// sample-table boxes.
    #[test]
    fn parse_stbl_picks_up_stsh() {
        let mut stsh = Vec::new();
        stsh.extend_from_slice(&[0u8; 4]); // v0
        stsh.extend_from_slice(&1u32.to_be_bytes()); // one entry
        stsh.extend_from_slice(&5u32.to_be_bytes()); // shadowed
        stsh.extend_from_slice(&2u32.to_be_bytes()); // sync
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"stsh", &stsh));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.stsh, vec![(5, 2)]);
    }

    /// Surfacing: a parsed `stsh` exposes its pairs on `params.options`
    /// as `stsh_<n>` = `"shadowed sync"` decimal strings.
    #[test]
    fn build_stream_info_surfaces_stsh_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.stsh = vec![(7, 1), (13, 10)];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stsh_0"), Some("7 1"));
        assert_eq!(info.params.options.get("stsh_1"), Some("13 10"));
    }

    /// Absence: a track with no `stsh` emits none of the `stsh_*` keys.
    #[test]
    fn build_stream_info_no_stsh_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stsh_0"), None);
    }

    // --- ยง8.9 sample groups (sbgp / sgpd) ---------------------------------

    /// ยง8.9.2 โ€” `sbgp` version 0: grouping_type + entry_count + run-length
    /// `(sample_count, group_description_index)` pairs. No
    /// grouping_type_parameter in v0.
    #[test]
    fn parse_sbgp_v0_two_runs() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
        body.extend_from_slice(b"roll"); // grouping_type
        body.extend_from_slice(&2u32.to_be_bytes()); // entry_count
        body.extend_from_slice(&10u32.to_be_bytes()); // sample_count
        body.extend_from_slice(&1u32.to_be_bytes()); // group_description_index
        body.extend_from_slice(&5u32.to_be_bytes());
        body.extend_from_slice(&0u32.to_be_bytes()); // index 0 = "no group"
        let sb = super::parse_sbgp(&body).unwrap();
        assert_eq!(&sb.grouping_type, b"roll");
        assert_eq!(sb.grouping_type_parameter, None);
        assert_eq!(sb.entries, vec![(10, 1), (5, 0)]);
    }

    /// ยง8.9.2 โ€” `sbgp` version 1 carries an extra grouping_type_parameter
    /// between grouping_type and entry_count.
    #[test]
    fn parse_sbgp_v1_with_parameter() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 0]); // version 1 + flags 0
        body.extend_from_slice(b"rap "); // grouping_type
        body.extend_from_slice(&7u32.to_be_bytes()); // grouping_type_parameter
        body.extend_from_slice(&1u32.to_be_bytes()); // entry_count
        body.extend_from_slice(&3u32.to_be_bytes()); // sample_count
        body.extend_from_slice(&2u32.to_be_bytes()); // group_description_index
        let sb = super::parse_sbgp(&body).unwrap();
        assert_eq!(&sb.grouping_type, b"rap ");
        assert_eq!(sb.grouping_type_parameter, Some(7));
        assert_eq!(sb.entries, vec![(3, 2)]);
    }

    /// A movie-fragment-local group index (โ‰ฅ 0x10001, ยง8.9.4) is preserved
    /// verbatim โ€” the demuxer does not resolve it.
    #[test]
    fn parse_sbgp_keeps_fragment_local_index() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"sync");
        body.extend_from_slice(&1u32.to_be_bytes());
        body.extend_from_slice(&1u32.to_be_bytes()); // sample_count
        body.extend_from_slice(&0x1_0001u32.to_be_bytes()); // fragment-local idx
        let sb = super::parse_sbgp(&body).unwrap();
        assert_eq!(sb.entries, vec![(1, 0x1_0001)]);
    }

    /// A zero-entry `sbgp` (header only) parses to an empty table.
    #[test]
    fn parse_sbgp_empty_table() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"roll");
        body.extend_from_slice(&0u32.to_be_bytes()); // entry_count = 0
        let sb = super::parse_sbgp(&body).unwrap();
        assert!(sb.entries.is_empty());
    }

    /// An `sbgp` cut off mid-entry is rejected rather than truncated.
    #[test]
    fn parse_sbgp_truncated_entry_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(b"roll");
        body.extend_from_slice(&2u32.to_be_bytes()); // claims 2 entries
        body.extend_from_slice(&1u32.to_be_bytes()); // only one full pair
        body.extend_from_slice(&1u32.to_be_bytes());
        assert!(super::parse_sbgp(&body).is_err());
    }

    /// An `sbgp` too short for the grouping_type is rejected.
    #[test]
    fn parse_sbgp_too_short() {
        assert!(super::parse_sbgp(&[0u8, 0, 0, 0, b'r']).is_err());
    }

    /// ยง8.9.3 โ€” `sgpd` version 1 with a fixed `default_length`: every
    /// entry is `default_length` bytes; no per-entry length prefix.
    #[test]
    fn parse_sgpd_v1_fixed_length() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 0]); // version 1 + flags 0
        body.extend_from_slice(b"roll"); // grouping_type
        body.extend_from_slice(&2u32.to_be_bytes()); // default_length = 2
        body.extend_from_slice(&2u32.to_be_bytes()); // entry_count = 2
        body.extend_from_slice(&[0xFF, 0xFB]); // entry 0 (roll_distance)
        body.extend_from_slice(&[0x00, 0x05]); // entry 1
        let sg = super::parse_sgpd(&body).unwrap();
        assert_eq!(&sg.grouping_type, b"roll");
        assert_eq!(sg.default_sample_description_index, None);
        assert_eq!(sg.entries, vec![vec![0xFF, 0xFB], vec![0x00, 0x05]]);
    }

    /// ยง8.9.3 โ€” `sgpd` version 1 with `default_length == 0`: each entry is
    /// preceded by its own `u32` description_length.
    #[test]
    fn parse_sgpd_v1_variable_length() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 0]); // version 1 + flags 0
        body.extend_from_slice(b"prol"); // grouping_type
        body.extend_from_slice(&0u32.to_be_bytes()); // default_length = 0
        body.extend_from_slice(&2u32.to_be_bytes()); // entry_count = 2
        body.extend_from_slice(&3u32.to_be_bytes()); // description_length 0 = 3
        body.extend_from_slice(&[0xAA, 0xBB, 0xCC]);
        body.extend_from_slice(&1u32.to_be_bytes()); // description_length 1 = 1
        body.extend_from_slice(&[0xDD]);
        let sg = super::parse_sgpd(&body).unwrap();
        assert_eq!(&sg.grouping_type, b"prol");
        assert_eq!(sg.entries, vec![vec![0xAA, 0xBB, 0xCC], vec![0xDD]]);
    }

    /// ยง8.9.3 โ€” `sgpd` version 2 supplies a
    /// `default_sample_description_index` before entry_count.
    #[test]
    fn parse_sgpd_v2_default_index() {
        let mut body = Vec::new();
        body.extend_from_slice(&[2u8, 0, 0, 0]); // version 2 + flags 0
        body.extend_from_slice(b"alst"); // grouping_type
        body.extend_from_slice(&1u32.to_be_bytes()); // default_sample_description_index
        body.extend_from_slice(&0u32.to_be_bytes()); // entry_count = 0
        let sg = super::parse_sgpd(&body).unwrap();
        assert_eq!(&sg.grouping_type, b"alst");
        assert_eq!(sg.default_sample_description_index, Some(1));
        assert!(sg.entries.is_empty());
    }

    /// ยง8.9.3 โ€” `sgpd` version 0 carries no per-entry length signalling
    /// (ยง8.9.3.3 NOTE). With no length to chunk by, the remaining body is
    /// captured as a single combined blob so no bytes are lost.
    #[test]
    fn parse_sgpd_v0_combined_blob_fallback() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version 0 + flags 0
        body.extend_from_slice(b"roll"); // grouping_type
        body.extend_from_slice(&2u32.to_be_bytes()); // entry_count = 2
        body.extend_from_slice(&[0x11, 0x22, 0x33, 0x44]); // opaque tail
        let sg = super::parse_sgpd(&body).unwrap();
        assert_eq!(sg.entries, vec![vec![0x11, 0x22, 0x33, 0x44]]);
    }

    /// A variable-length `sgpd` whose declared description_length runs past
    /// the body is rejected.
    #[test]
    fn parse_sgpd_variable_truncated_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 0]);
        body.extend_from_slice(b"roll");
        body.extend_from_slice(&0u32.to_be_bytes()); // default_length = 0
        body.extend_from_slice(&1u32.to_be_bytes()); // entry_count = 1
        body.extend_from_slice(&8u32.to_be_bytes()); // claims 8 bytes
        body.extend_from_slice(&[0x01, 0x02]); // only 2 present
        assert!(super::parse_sgpd(&body).is_err());
    }

    /// The MSB-first `BitCursor` reads big-endian bit fields across byte
    /// boundaries, including a zero-width read.
    #[test]
    fn bit_cursor_reads_msb_first() {
        // 0b1010_0110 0b1100_0001
        let data = [0xA6u8, 0xC1];
        let mut c = super::BitCursor::new(&data, 0);
        assert_eq!(c.read(0), Some(0)); // zero width consumes nothing
        assert_eq!(c.read(4), Some(0b1010));
        assert_eq!(c.read(4), Some(0b0110));
        assert_eq!(c.read(8), Some(0b1100_0001));
        assert_eq!(c.read(1), None); // exhausted
    }

    /// The cursor honours a non-zero byte anchor and rejects an
    /// over-long read.
    #[test]
    fn bit_cursor_anchor_and_overrun() {
        let data = [0x00, 0xFF, 0x0F];
        let mut c = super::BitCursor::new(&data, 1); // start at byte 1
        assert_eq!(c.read(12), Some(0xFF0)); // 0xFF then top nibble of 0x0F
        assert_eq!(c.read(8), None); // only 4 bits left
        assert_eq!(c.read(4), Some(0x0F));
    }

    /// ยง8.9.5 โ€” `csgp` with 16-bit field widths (byte-aligned): two
    /// patterns of one and two samples. flags encode all three size
    /// codes as `2` (16-bit) with no grouping_type_parameter.
    #[test]
    fn parse_csgp_16bit_widths() {
        // index_size_code=2, count_size_code=2, pattern_size_code=2,
        // gtpp=0  โ†’  flags = 2 | (2<<2) | (2<<4) = 0x2A.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x2A]); // version 0 + flags
        body.extend_from_slice(b"roll"); // grouping_type
        body.extend_from_slice(&2u32.to_be_bytes()); // pattern_count = 2
                                                     // pattern 1: length 1, sample_count 3
        body.extend_from_slice(&1u16.to_be_bytes());
        body.extend_from_slice(&3u16.to_be_bytes());
        // pattern 2: length 2, sample_count 1
        body.extend_from_slice(&2u16.to_be_bytes());
        body.extend_from_slice(&1u16.to_be_bytes());
        // indices: pattern 1 โ†’ [5]; pattern 2 โ†’ [0, 7]
        body.extend_from_slice(&5u16.to_be_bytes());
        body.extend_from_slice(&0u16.to_be_bytes());
        body.extend_from_slice(&7u16.to_be_bytes());
        let cg = super::parse_csgp(&body).unwrap();
        assert_eq!(&cg.grouping_type, b"roll");
        assert_eq!(cg.grouping_type_parameter, None);
        assert_eq!(cg.patterns.len(), 2);
        assert_eq!(cg.patterns[0].sample_count, 3);
        assert_eq!(cg.patterns[0].indices, vec![5]);
        assert_eq!(cg.patterns[1].sample_count, 1);
        assert_eq!(cg.patterns[1].indices, vec![0, 7]);
    }

    /// ยง8.9.5 โ€” 4-bit bit-packed fields (the densest form). All three
    /// size codes are `0` (width 4). A single pattern of three samples
    /// packs `pattern_length`+`sample_count` into one byte and the three
    /// indices into 12 bits.
    #[test]
    fn parse_csgp_4bit_packed() {
        // size codes all 0 โ†’ flags 0; gtpp=0.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0]); // version 0 + flags 0
        body.extend_from_slice(b"sync"); // grouping_type
        body.extend_from_slice(&1u32.to_be_bytes()); // pattern_count = 1
                                                     // pattern_length=3 (0b0011), sample_count=2 (0b0010) โ†’ 0x32
                                                     // indices [1, 2, 4] โ†’ 0b0001 0010 0100 = 0x12 0x4_ (12 bits,
                                                     // padded to a byte boundary by the box's size).
        body.push(0x32);
        body.push(0x12);
        body.push(0x40); // top nibble = index 4, low nibble padding
        let cg = super::parse_csgp(&body).unwrap();
        assert_eq!(&cg.grouping_type, b"sync");
        assert_eq!(cg.patterns.len(), 1);
        assert_eq!(cg.patterns[0].sample_count, 2);
        assert_eq!(cg.patterns[0].indices, vec![1, 2, 4]);
    }

    /// ยง8.9.5 โ€” the flag presence bit (bit 6) adds a 32-bit
    /// `grouping_type_parameter` after `grouping_type`.
    #[test]
    fn parse_csgp_with_grouping_type_parameter() {
        // size codes all 2 (16-bit) plus presence bit (1<<6 = 0x40):
        // flags = 0x2A | 0x40 = 0x6A.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x6A]);
        body.extend_from_slice(b"rap ");
        body.extend_from_slice(&9u32.to_be_bytes()); // grouping_type_parameter
        body.extend_from_slice(&1u32.to_be_bytes()); // pattern_count = 1
        body.extend_from_slice(&1u16.to_be_bytes()); // pattern_length
        body.extend_from_slice(&4u16.to_be_bytes()); // sample_count
        body.extend_from_slice(&2u16.to_be_bytes()); // index
        let cg = super::parse_csgp(&body).unwrap();
        assert_eq!(&cg.grouping_type, b"rap ");
        assert_eq!(cg.grouping_type_parameter, Some(9));
        assert_eq!(cg.patterns[0].sample_count, 4);
        assert_eq!(cg.patterns[0].indices, vec![2]);
    }

    /// ยง8.9.5 โ€” a fragment-local index keeps its high bit verbatim. With
    /// a 32-bit index width, bit 31 set marks fragment-local.
    #[test]
    fn parse_csgp_fragment_local_index_preserved() {
        // index_size_code=3 (32-bit), count/pattern codes 2 (16-bit):
        // flags = 3 | (2<<2) | (2<<4) = 0x2B.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x2B]);
        body.extend_from_slice(b"seig");
        body.extend_from_slice(&1u32.to_be_bytes()); // pattern_count
        body.extend_from_slice(&1u16.to_be_bytes()); // pattern_length
        body.extend_from_slice(&1u16.to_be_bytes()); // sample_count
        body.extend_from_slice(&0x8000_0001u32.to_be_bytes()); // frag-local idx
        let cg = super::parse_csgp(&body).unwrap();
        assert_eq!(cg.patterns[0].indices, vec![0x8000_0001]);
    }

    /// ยง8.9.5 flag bit 7 โ€” `index_msb_indicates_fragment_local_description`
    /// is captured from `flags & 0x80`, the index field width is recorded,
    /// and the per-index resolver splits the source-selector MSB off the
    /// stored value while leaving the raw index verbatim.
    #[test]
    fn parse_csgp_captures_fragment_local_flag_and_resolves_msb() {
        // 8-bit index width (index_size_code=1) + bit 7 set:
        // flags = 1 | (0<<2) | (0<<4) | (1<<7) = 0x81. count/pattern at
        // 4-bit (code 0). pattern_length=3, sample_count=2 โ†’ 0x32 byte.
        // indices 0x80,0x01,0x83 each one byte (8-bit width).
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x81]);
        body.extend_from_slice(b"seig");
        body.extend_from_slice(&1u32.to_be_bytes()); // pattern_count
        body.push(0x32); // pattern_length=3 (4b) | sample_count=2 (4b)
        body.extend_from_slice(&[0x80, 0x01, 0x83]); // three 8-bit indices
        let cg = super::parse_csgp(&body).unwrap();

        assert!(cg.index_msb_indicates_fragment_local_description);
        assert_eq!(cg.index_field_bits, 8);
        // Raw values preserved.
        assert_eq!(cg.patterns[0].indices, vec![0x80, 0x01, 0x83]);

        let pat = &cg.patterns[0];
        let r0 = pat
            .resolve_index(
                0,
                cg.index_msb_indicates_fragment_local_description,
                cg.index_field_bits,
            )
            .unwrap();
        assert!(r0.fragment_local);
        assert_eq!(r0.value, 0);
        let r1 = pat
            .resolve_index(
                1,
                cg.index_msb_indicates_fragment_local_description,
                cg.index_field_bits,
            )
            .unwrap();
        assert!(!r1.fragment_local);
        assert_eq!(r1.value, 1);
        let r2 = pat
            .resolve_index(
                2,
                cg.index_msb_indicates_fragment_local_description,
                cg.index_field_bits,
            )
            .unwrap();
        assert!(r2.fragment_local);
        assert_eq!(r2.value, 3);
    }

    /// The resolver passes indices through verbatim when the flag is clear,
    /// and handles every documented width's MSB position.
    #[test]
    fn resolve_csgp_index_width_aware() {
        // Flag clear โ†’ verbatim, never fragment-local.
        let r = super::resolve_csgp_index(0x8000_0001, false, 32);
        assert!(!r.fragment_local);
        assert_eq!(r.value, 0x8000_0001);

        // 4-bit width: MSB at bit 3 (mask 0x8).
        let r = super::resolve_csgp_index(0x9, true, 4);
        assert!(r.fragment_local);
        assert_eq!(r.value, 0x1);

        // 16-bit width: MSB at bit 15 (mask 0x8000).
        let r = super::resolve_csgp_index(0x8001, true, 16);
        assert!(r.fragment_local);
        assert_eq!(r.value, 0x1);

        // 32-bit width: MSB at bit 31.
        let r = super::resolve_csgp_index(0x8000_0005, true, 32);
        assert!(r.fragment_local);
        assert_eq!(r.value, 5);

        // Degenerate width 0 โ†’ no MSB, verbatim.
        let r = super::resolve_csgp_index(0xFF, true, 0);
        assert!(!r.fragment_local);
        assert_eq!(r.value, 0xFF);
    }

    /// ยง8.9.5 pattern โ†’ sample expansion: a pattern whose `sample_count`
    /// exceeds its `pattern_length` cycles its index entries across the
    /// samples, ending mid-pattern when the count does not divide evenly.
    #[test]
    fn csgp_resolve_samples_cycles_pattern() {
        // Single pattern: indices [10, 20, 30], sample_count = 7. The
        // length-3 run cycles: 10,20,30,10,20,30,10.
        let cg = super::CsgpBox {
            grouping_type: *b"roll",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: false,
            index_field_bits: 16,
            patterns: vec![super::CsgpPattern {
                sample_count: 7,
                indices: vec![10, 20, 30],
            }],
        };
        let resolved = cg.resolve_samples(7);
        let values: Vec<u32> = resolved.iter().map(|r| r.value).collect();
        assert_eq!(values, vec![10, 20, 30, 10, 20, 30, 10]);
        assert!(resolved.iter().all(|r| !r.fragment_local));
    }

    /// ยง8.9.5: two patterns concatenate, each cycled across its own
    /// `sample_count`, and `sample_count == pattern_length` uses the
    /// pattern once un-repeated.
    #[test]
    fn csgp_resolve_samples_multi_pattern() {
        let cg = super::CsgpBox {
            grouping_type: *b"roll",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: false,
            index_field_bits: 16,
            patterns: vec![
                // length 2, count 2 โ†’ used once: 1,2
                super::CsgpPattern {
                    sample_count: 2,
                    indices: vec![1, 2],
                },
                // length 1, count 3 โ†’ cycled: 9,9,9
                super::CsgpPattern {
                    sample_count: 3,
                    indices: vec![9],
                },
            ],
        };
        let values: Vec<u32> = cg.resolve_samples(5).iter().map(|r| r.value).collect();
        assert_eq!(values, vec![1, 2, 9, 9, 9]);
    }

    /// ยง8.9.5: when the patterns cover fewer than `total_samples` samples,
    /// the trailing samples take the `sgpd` default โ€” surfaced as value 0.
    #[test]
    fn csgp_resolve_samples_pads_trailing_default() {
        let cg = super::CsgpBox {
            grouping_type: *b"roll",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: false,
            index_field_bits: 16,
            patterns: vec![super::CsgpPattern {
                sample_count: 2,
                indices: vec![5],
            }],
        };
        // 2 mapped + 3 trailing defaults = 5.
        let values: Vec<u32> = cg.resolve_samples(5).iter().map(|r| r.value).collect();
        assert_eq!(values, vec![5, 5, 0, 0, 0]);
    }

    /// ยง8.9.5: a sum of `sample_count` exceeding `total_samples` is clamped
    /// so the output never overruns the track's real sample count.
    #[test]
    fn csgp_resolve_samples_clamps_overflow() {
        let cg = super::CsgpBox {
            grouping_type: *b"roll",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: false,
            index_field_bits: 16,
            patterns: vec![super::CsgpPattern {
                sample_count: 100,
                indices: vec![7],
            }],
        };
        let resolved = cg.resolve_samples(3);
        assert_eq!(resolved.len(), 3);
        assert!(resolved.iter().all(|r| r.value == 7));
    }

    /// ยง8.9.5 expansion honours the fragment-local MSB convention: each
    /// emitted index is split into (fragment_local, value) per the box's
    /// flag and field width.
    #[test]
    fn csgp_resolve_samples_resolves_fragment_local_msb() {
        // 8-bit indices, bit-7 flag set: 0x81 = frag-local value 1,
        // 0x02 = global value 2.
        let cg = super::CsgpBox {
            grouping_type: *b"seig",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: true,
            index_field_bits: 8,
            patterns: vec![super::CsgpPattern {
                sample_count: 4,
                indices: vec![0x81, 0x02],
            }],
        };
        let resolved = cg.resolve_samples(4);
        assert_eq!(resolved.len(), 4);
        assert!(resolved[0].fragment_local);
        assert_eq!(resolved[0].value, 1);
        assert!(!resolved[1].fragment_local);
        assert_eq!(resolved[1].value, 2);
        // Cycle repeats.
        assert!(resolved[2].fragment_local);
        assert_eq!(resolved[2].value, 1);
        assert!(!resolved[3].fragment_local);
        assert_eq!(resolved[3].value, 2);
    }

    /// ยง8.9.5: a pattern with an empty index run cannot be cycled and
    /// contributes nothing โ€” its `sample_count` is skipped without panic.
    #[test]
    fn csgp_resolve_samples_empty_pattern_skipped() {
        let cg = super::CsgpBox {
            grouping_type: *b"roll",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: false,
            index_field_bits: 16,
            patterns: vec![
                super::CsgpPattern {
                    sample_count: 5,
                    indices: vec![],
                },
                super::CsgpPattern {
                    sample_count: 2,
                    indices: vec![3],
                },
            ],
        };
        // Empty pattern maps nothing; second pattern maps 3,3; the rest
        // of total_samples=4 pads with the default 0.
        let values: Vec<u32> = cg.resolve_samples(4).iter().map(|r| r.value).collect();
        assert_eq!(values, vec![3, 3, 0, 0]);
    }

    /// A `csgp` truncated mid-index is rejected, not silently shortened.
    #[test]
    fn parse_csgp_truncated_index_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x2A]); // 16-bit widths
        body.extend_from_slice(b"roll");
        body.extend_from_slice(&1u32.to_be_bytes()); // pattern_count
        body.extend_from_slice(&2u16.to_be_bytes()); // pattern_length = 2
        body.extend_from_slice(&1u16.to_be_bytes()); // sample_count
        body.extend_from_slice(&5u16.to_be_bytes()); // only one of two indices
        assert!(super::parse_csgp(&body).is_err());
    }

    /// A `csgp` too short even for the FullBox header is rejected.
    #[test]
    fn parse_csgp_too_short() {
        assert!(super::parse_csgp(&[0u8, 0]).is_err());
    }

    /// ยง8.9.5: `pattern_size_code` and `count_size_code` must agree on
    /// whether the 4-bit width is used. A box with `pattern_size_code = 0`
    /// (4-bit) but `count_size_code = 1` (8-bit) is an invalid file and is
    /// rejected rather than mis-decoded.
    #[test]
    fn parse_csgp_mixed_4bit_width_rejected() {
        // flags = count_size_code(1) << 2 = 0x04: pattern_size_code = 0,
        // count_size_code = 1, index_size_code = 0 โ†’ a 4/non-4 mix.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x04]);
        body.extend_from_slice(b"roll");
        body.extend_from_slice(&0u32.to_be_bytes()); // pattern_count = 0
        let err = super::parse_csgp(&body);
        assert!(err.is_err(), "mixed 4-bit/non-4-bit width must be rejected");
    }

    /// The mirror case โ€” `pattern_size_code = 1` (8-bit), `count_size_code
    /// = 0` (4-bit) โ€” is equally invalid and rejected.
    #[test]
    fn parse_csgp_mixed_4bit_width_rejected_other_way() {
        // flags = pattern_size_code(1) << 4 = 0x10.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 0x10]);
        body.extend_from_slice(b"roll");
        body.extend_from_slice(&0u32.to_be_bytes()); // pattern_count = 0
        assert!(super::parse_csgp(&body).is_err());
    }

    /// Both codes at 0 (4-bit) agree and parse fine; both โ‰ฅ 1 agree and
    /// parse fine. (Guards against the constraint check over-rejecting.)
    #[test]
    fn parse_csgp_agreeing_widths_accepted() {
        // both 4-bit (flags = 0), pattern_count = 0.
        let mut both_4 = Vec::new();
        both_4.extend_from_slice(&[0u8, 0, 0, 0]);
        both_4.extend_from_slice(b"roll");
        both_4.extend_from_slice(&0u32.to_be_bytes());
        assert!(super::parse_csgp(&both_4).is_ok());

        // both 8-bit: pattern_size_code = 1 (<<4 = 0x10), count_size_code =
        // 1 (<<2 = 0x04) โ†’ flags = 0x14, pattern_count = 0.
        let mut both_8 = Vec::new();
        both_8.extend_from_slice(&[0u8, 0, 0, 0x14]);
        both_8.extend_from_slice(b"roll");
        both_8.extend_from_slice(&0u32.to_be_bytes());
        assert!(super::parse_csgp(&both_8).is_ok());
    }

    /// `parse_stbl` accumulates multiple `sbgp`/`sgpd` instances (one per
    /// grouping type) on the track rather than overwriting.
    #[test]
    fn parse_stbl_accumulates_sample_groups() {
        // sbgp(roll)
        let mut sbgp = Vec::new();
        sbgp.extend_from_slice(&[0u8; 4]);
        sbgp.extend_from_slice(b"roll");
        sbgp.extend_from_slice(&1u32.to_be_bytes());
        sbgp.extend_from_slice(&4u32.to_be_bytes());
        sbgp.extend_from_slice(&1u32.to_be_bytes());
        // sgpd(roll) v1 fixed length 2
        let mut sgpd = Vec::new();
        sgpd.extend_from_slice(&[1u8, 0, 0, 0]);
        sgpd.extend_from_slice(b"roll");
        sgpd.extend_from_slice(&2u32.to_be_bytes()); // default_length
        sgpd.extend_from_slice(&1u32.to_be_bytes()); // entry_count
        sgpd.extend_from_slice(&[0xFF, 0xFB]);

        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"sbgp", &sbgp));
        stbl.extend(wrap_box_full_size(b"sgpd", &sgpd));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.sbgp.len(), 1);
        assert_eq!(&t.sbgp[0].grouping_type, b"roll");
        assert_eq!(t.sbgp[0].entries, vec![(4, 1)]);
        assert_eq!(t.sgpd.len(), 1);
        assert_eq!(&t.sgpd[0].grouping_type, b"roll");
        assert_eq!(t.sgpd[0].entries, vec![vec![0xFF, 0xFB]]);
    }

    /// Surfacing: a parsed `sbgp` exposes its run-length map on
    /// `params.options` as `sbgp_<n>` (grouping type, optional `param=`,
    /// then `count:index` pairs); `sgpd` exposes `sgpd_<n>` (grouping
    /// type, optional `default=`, then hex entry payloads).
    #[test]
    fn build_stream_info_surfaces_sample_groups_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48000;
        t.sbgp = vec![
            super::SbgpBox {
                grouping_type: *b"roll",
                grouping_type_parameter: None,
                entries: vec![(10, 1), (5, 0)],
            },
            super::SbgpBox {
                grouping_type: *b"rap ",
                grouping_type_parameter: Some(7),
                entries: vec![(3, 2)],
            },
        ];
        t.sgpd = vec![super::SgpdBox {
            grouping_type: *b"roll",
            default_sample_description_index: Some(1),
            entries: vec![vec![0xFF, 0xFB], vec![0x00, 0x05]],
        }];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("sbgp_0"), Some("roll 10:1 5:0"));
        assert_eq!(info.params.options.get("sbgp_1"), Some("rap  param=7 3:2"));
        assert_eq!(
            info.params.options.get("sgpd_0"),
            Some("roll default=1 fffb 0005")
        );
    }

    /// Absence: a track with no sample groups emits none of the
    /// `sbgp_*` / `sgpd_*` keys.
    #[test]
    fn build_stream_info_no_sample_groups_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("sbgp_0"), None);
        assert_eq!(info.params.options.get("sgpd_0"), None);
    }

    // --- ยง8.6.4 sdtp (SampleDependencyTypeBox) ------------------------------

    /// Helper: pack the four 2-bit dependency fields into the on-wire
    /// `sdtp` byte layout (MSB-first per ยง8.6.4.2).
    fn pack_sdtp(is_leading: u8, depends_on: u8, depended_on: u8, redundancy: u8) -> u8 {
        ((is_leading & 0x03) << 6)
            | ((depends_on & 0x03) << 4)
            | ((depended_on & 0x03) << 2)
            | (redundancy & 0x03)
    }

    /// ยง8.6.4 โ€” `sdtp` round-trip: an I-picture (depends_on=2,
    /// depended_on=1, redundancy=2, not leading) and a disposable
    /// B-frame (depends_on=1, depended_on=2, redundancy=2, leading
    /// with prior dependency=1) both decode to the expected per-field
    /// 2-bit values.
    #[test]
    fn parse_sdtp_two_entries() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble (version 0 + flags 0)
        body.push(pack_sdtp(2, 2, 1, 2)); // I-picture
        body.push(pack_sdtp(1, 1, 2, 2)); // disposable leading
        let v = super::parse_sdtp(&body).unwrap();
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].is_leading, 2);
        assert_eq!(v[0].sample_depends_on, 2);
        assert_eq!(v[0].sample_is_depended_on, 1);
        assert_eq!(v[0].sample_has_redundancy, 2);
        assert_eq!(v[1].is_leading, 1);
        assert_eq!(v[1].sample_depends_on, 1);
        assert_eq!(v[1].sample_is_depended_on, 2);
        assert_eq!(v[1].sample_has_redundancy, 2);
    }

    /// A zero-sample `sdtp` (FullBox preamble only) parses to an empty
    /// table rather than failing โ€” implied `sample_count` from `stsz`
    /// may legitimately be zero (an empty track).
    #[test]
    fn parse_sdtp_empty_table() {
        let body = vec![0u8; 4]; // FullBox preamble only
        let v = super::parse_sdtp(&body).unwrap();
        assert!(v.is_empty());
    }

    /// An `sdtp` too short for even the FullBox preamble is rejected.
    #[test]
    fn parse_sdtp_too_short() {
        assert!(super::parse_sdtp(&[0u8, 0, 0]).is_err());
    }

    /// Bit-packing decode: a single byte `0b11_10_01_00` must unpack
    /// to (3, 2, 1, 0) โ€” MSB pair first per ยง8.6.4.2. This is the
    /// pivot test for getting the shift order right.
    #[test]
    fn parse_sdtp_field_order() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.push(0b11_10_01_00); // is_leading=3 depends_on=2 depended_on=1 redundancy=0
        let v = super::parse_sdtp(&body).unwrap();
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].is_leading, 3);
        assert_eq!(v[0].sample_depends_on, 2);
        assert_eq!(v[0].sample_is_depended_on, 1);
        assert_eq!(v[0].sample_has_redundancy, 0);
    }

    /// Every field in a single byte that's all zeros parses to all-zero
    /// "unknown" entries (the default state when a producer fills the
    /// table but has no real information per ยง8.6.4.3 value `0`).
    #[test]
    fn parse_sdtp_all_unknowns() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.push(0u8);
        body.push(0u8);
        body.push(0u8);
        let v = super::parse_sdtp(&body).unwrap();
        assert_eq!(v.len(), 3);
        for e in &v {
            assert_eq!(e.is_leading, 0);
            assert_eq!(e.sample_depends_on, 0);
            assert_eq!(e.sample_is_depended_on, 0);
            assert_eq!(e.sample_has_redundancy, 0);
        }
    }

    /// `parse_stbl` lands the `sdtp` on the track alongside the other
    /// sample-table boxes (proves the dispatch arm is wired).
    #[test]
    fn parse_stbl_picks_up_sdtp() {
        let mut sdtp = Vec::new();
        sdtp.extend_from_slice(&[0u8; 4]); // FullBox preamble
        sdtp.push(pack_sdtp(2, 2, 1, 2)); // I-picture
        sdtp.push(pack_sdtp(0, 1, 2, 0)); // disposable
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"sdtp", &sdtp));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.sdtp.len(), 2);
        assert_eq!(t.sdtp[0].sample_depends_on, 2);
        assert_eq!(t.sdtp[1].sample_is_depended_on, 2);
    }

    /// Surfacing: a parsed `sdtp` exposes its summary counts on
    /// `params.options` as the five `sdtp_*_count` keys. We construct
    /// a 4-entry table covering one I-picture (independent), one
    /// disposable B-frame, one leading B-frame, and one sample with
    /// redundant coding so every counter increments at least once.
    #[test]
    fn build_stream_info_surfaces_sdtp_summary_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.sdtp = vec![
            // I-picture: depends_on=2 (independent), depended_on=1 (not
            // disposable), not leading, no redundancy.
            super::SdtpEntry {
                is_leading: 2,
                sample_depends_on: 2,
                sample_is_depended_on: 1,
                sample_has_redundancy: 0,
            },
            // Disposable B-frame: depended_on=2.
            super::SdtpEntry {
                is_leading: 2,
                sample_depends_on: 1,
                sample_is_depended_on: 2,
                sample_has_redundancy: 0,
            },
            // Leading decodable B-frame: is_leading=3.
            super::SdtpEntry {
                is_leading: 3,
                sample_depends_on: 1,
                sample_is_depended_on: 2,
                sample_has_redundancy: 0,
            },
            // Sample with redundant coding: has_redundancy=1.
            super::SdtpEntry {
                is_leading: 2,
                sample_depends_on: 1,
                sample_is_depended_on: 1,
                sample_has_redundancy: 1,
            },
        ];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("sdtp_count"), Some("4"));
        assert_eq!(info.params.options.get("sdtp_leading_count"), Some("1"));
        assert_eq!(info.params.options.get("sdtp_independent_count"), Some("1"));
        assert_eq!(info.params.options.get("sdtp_disposable_count"), Some("2"));
        assert_eq!(info.params.options.get("sdtp_redundant_count"), Some("1"));
    }

    /// Absence: a track with no `sdtp` emits none of the summary keys.
    #[test]
    fn build_stream_info_no_sdtp_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("sdtp_count"), None);
        assert_eq!(info.params.options.get("sdtp_leading_count"), None);
        assert_eq!(info.params.options.get("sdtp_independent_count"), None);
        assert_eq!(info.params.options.get("sdtp_disposable_count"), None);
        assert_eq!(info.params.options.get("sdtp_redundant_count"), None);
    }

    // --- ยง8.5.3 stdp (DegradationPriorityBox) -------------------------------

    /// ยง8.5.3 โ€” `stdp` round-trip: a 3-sample priority table laid out
    /// big-endian after the FullBox preamble decodes to the same three
    /// u16 values.
    #[test]
    fn parse_stdp_three_entries() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble (version 0 + flags 0)
        body.extend_from_slice(&0x0001u16.to_be_bytes());
        body.extend_from_slice(&0x0102u16.to_be_bytes());
        body.extend_from_slice(&0xFFFFu16.to_be_bytes());
        let v = super::parse_stdp(&body).unwrap();
        assert_eq!(v, vec![0x0001u16, 0x0102, 0xFFFF]);
    }

    /// A zero-sample `stdp` (FullBox preamble only) parses to an empty
    /// table rather than failing โ€” the implied `sample_count` from
    /// `stsz` may legitimately be zero.
    #[test]
    fn parse_stdp_empty_table() {
        let body = vec![0u8; 4];
        let v = super::parse_stdp(&body).unwrap();
        assert!(v.is_empty());
    }

    /// An `stdp` too short for even the FullBox preamble is rejected.
    #[test]
    fn parse_stdp_too_short() {
        assert!(super::parse_stdp(&[0u8, 0, 0]).is_err());
    }

    /// A trailing odd byte (the spec never produces one โ€” `priority`
    /// is always a 16-bit value) is silently ignored rather than
    /// failing. Two `priority` u16s + one trailing byte yields a
    /// 2-entry table.
    #[test]
    fn parse_stdp_trailing_odd_byte_ignored() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.extend_from_slice(&0x0001u16.to_be_bytes());
        body.extend_from_slice(&0x0002u16.to_be_bytes());
        body.push(0xAA); // stray byte
        let v = super::parse_stdp(&body).unwrap();
        assert_eq!(v, vec![0x0001u16, 0x0002]);
    }

    /// `parse_stbl` lands the `stdp` on the track alongside the other
    /// sample-table boxes (proves the dispatch arm is wired).
    #[test]
    fn parse_stbl_picks_up_stdp() {
        let mut stdp = Vec::new();
        stdp.extend_from_slice(&[0u8; 4]); // FullBox preamble
        stdp.extend_from_slice(&0x0001u16.to_be_bytes());
        stdp.extend_from_slice(&0x0005u16.to_be_bytes());
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"stdp", &stdp));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.stdp, vec![0x0001u16, 0x0005]);
    }

    /// Surfacing: a parsed `stdp` exposes its summary on `params.options`
    /// as four `stdp_*` keys (count + min + max + sum). The spec leaves
    /// the value semantics to derived specifications, so we surface the
    /// raw aggregates rather than a named-bucket breakdown like `sdtp`.
    #[test]
    fn build_stream_info_surfaces_stdp_summary_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        // Four samples with priorities {1, 5, 7, 3}: min=1, max=7, sum=16.
        t.stdp = vec![1u16, 5, 7, 3];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stdp_count"), Some("4"));
        assert_eq!(info.params.options.get("stdp_min"), Some("1"));
        assert_eq!(info.params.options.get("stdp_max"), Some("7"));
        assert_eq!(info.params.options.get("stdp_sum"), Some("16"));
    }

    /// A single-entry `stdp` exposes `min == max == sum == priority`.
    #[test]
    fn build_stream_info_stdp_single_entry_min_eq_max() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.stdp = vec![42u16];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stdp_count"), Some("1"));
        assert_eq!(info.params.options.get("stdp_min"), Some("42"));
        assert_eq!(info.params.options.get("stdp_max"), Some("42"));
        assert_eq!(info.params.options.get("stdp_sum"), Some("42"));
    }

    /// Absence: a track with no `stdp` emits none of the summary keys.
    #[test]
    fn build_stream_info_no_stdp_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("stdp_count"), None);
        assert_eq!(info.params.options.get("stdp_min"), None);
        assert_eq!(info.params.options.get("stdp_max"), None);
        assert_eq!(info.params.options.get("stdp_sum"), None);
    }

    /// Pack two ยง8.7.6 `padb` nibble values into one byte: top nibble is
    /// `pad1` (sample (i*2)+1), bottom nibble is `pad2` (sample (i*2)+2).
    /// Each nibble's high bit is the reserved zero (ยง8.7.6.2) and the low
    /// three bits carry the pad count in 0..=7.
    fn pack_padb(pad1: u8, pad2: u8) -> u8 {
        ((pad1 & 0x07) << 4) | (pad2 & 0x07)
    }

    /// `padb` with four samples (one byte holding two pairs of pad
    /// counts) round-trips through the typed accessor and yields the
    /// per-sample u8 vec in decode order.
    #[test]
    fn parse_padb_four_samples_two_bytes() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble (v0, flags 0)
        body.extend_from_slice(&4u32.to_be_bytes()); // sample_count = 4
        body.push(pack_padb(1, 2)); // samples 1, 2
        body.push(pack_padb(3, 7)); // samples 3, 4
        let v = super::parse_padb(&body).unwrap();
        assert_eq!(v, vec![1u8, 2, 3, 7]);
    }

    /// `padb` with an odd sample_count discards the unused trailing
    /// nibble (ยง8.7.6.2 โ€” `(sample_count + 1) / 2` bytes total, last
    /// byte's bottom nibble is unused when sample_count is odd).
    #[test]
    fn parse_padb_odd_sample_count_drops_trailing_nibble() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.extend_from_slice(&3u32.to_be_bytes()); // sample_count = 3
        body.push(pack_padb(2, 4)); // samples 1, 2
        body.push(pack_padb(6, 5)); // sample 3; pad2 unused
        let v = super::parse_padb(&body).unwrap();
        assert_eq!(v, vec![2u8, 4, 6]);
    }

    /// `padb` with `sample_count == 0` (zero-sample table) is permitted
    /// and yields an empty vec.
    #[test]
    fn parse_padb_zero_samples() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.extend_from_slice(&0u32.to_be_bytes()); // sample_count = 0
        let v = super::parse_padb(&body).unwrap();
        assert!(v.is_empty());
    }

    /// A `padb` body too short for even the FullBox + sample_count
    /// preamble (8 bytes) is rejected outright.
    #[test]
    fn parse_padb_too_short_preamble() {
        assert!(super::parse_padb(&[0u8; 4]).is_err());
        assert!(super::parse_padb(&[0u8; 7]).is_err());
    }

    /// A `padb` whose declared `sample_count` would need more bytes than
    /// the body carries is rejected โ€” the spec mandates the box carry
    /// `(sample_count + 1) / 2` bytes of payload data.
    #[test]
    fn parse_padb_truncated_payload() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.extend_from_slice(&10u32.to_be_bytes()); // sample_count = 10
        body.push(0); // only 1 of the 5 needed bytes
        body.push(0);
        assert!(super::parse_padb(&body).is_err());
    }

    /// The reserved high bit of each nibble (ยง8.7.6.2) is masked off
    /// rather than carried into the returned pad value โ€” a producer
    /// slip on the reserved bit does not corrupt the count.
    #[test]
    fn parse_padb_masks_reserved_bit() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(&2u32.to_be_bytes()); // sample_count = 2
                                                     // pad1 = 5 (0b101) with reserved bit set: nibble = 0b1101 = 0xD
                                                     // pad2 = 2 (0b010) with reserved bit set: nibble = 0b1010 = 0xA
        body.push(0xDA);
        let v = super::parse_padb(&body).unwrap();
        assert_eq!(v, vec![5u8, 2]);
    }

    /// `parse_stbl` lands the `padb` on the track alongside the other
    /// sample-table boxes (proves the dispatch arm is wired).
    #[test]
    fn parse_stbl_picks_up_padb() {
        let mut padb = Vec::new();
        padb.extend_from_slice(&[0u8; 4]); // FullBox preamble
        padb.extend_from_slice(&2u32.to_be_bytes()); // sample_count = 2
        padb.push(pack_padb(4, 1));
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"padb", &padb));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.padb, vec![4u8, 1]);
    }

    /// Surfacing: a parsed `padb` exposes its summary on `params.options`
    /// as four `padb_*` keys (count + max + nonzero_count + 8-bucket
    /// histogram). The histogram fully captures the value distribution
    /// in a single key; consumers can recover any aggregate from it.
    #[test]
    fn build_stream_info_surfaces_padb_summary_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48_000;
        // Eight samples with pad counts {0, 0, 1, 2, 2, 7, 7, 7}:
        // count=8, max=7, nonzero=6
        // histogram = [2,1,2,0,0,0,0,3]
        t.padb = vec![0u8, 0, 1, 2, 2, 7, 7, 7];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("padb_count"), Some("8"));
        assert_eq!(info.params.options.get("padb_max"), Some("7"));
        assert_eq!(info.params.options.get("padb_nonzero_count"), Some("6"));
        assert_eq!(
            info.params.options.get("padb_hist"),
            Some("2:1:2:0:0:0:0:3")
        );
    }

    /// A `padb` whose every entry is zero (the byte-aligned-bitstream
    /// case) still emits the summary keys โ€” the box's presence is the
    /// signal that the producer accounted for padding, even if every
    /// sample happens to be byte-aligned.
    #[test]
    fn build_stream_info_padb_all_zero_emits_keys() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48_000;
        t.padb = vec![0u8; 5];
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("padb_count"), Some("5"));
        assert_eq!(info.params.options.get("padb_max"), Some("0"));
        assert_eq!(info.params.options.get("padb_nonzero_count"), Some("0"));
        assert_eq!(
            info.params.options.get("padb_hist"),
            Some("5:0:0:0:0:0:0:0")
        );
    }

    /// Absence: a track with no `padb` emits none of the summary keys.
    #[test]
    fn build_stream_info_no_padb_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48_000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("padb_count"), None);
        assert_eq!(info.params.options.get("padb_max"), None);
        assert_eq!(info.params.options.get("padb_nonzero_count"), None);
        assert_eq!(info.params.options.get("padb_hist"), None);
    }

    /// Build a `pdin` (ISO/IEC 14496-12 ยง8.1.3) body: 4-byte FullBox
    /// preamble followed by N `(rate, initial_delay)` u32 pairs in big
    /// endian. Helper for the round 259 pdin tests.
    fn build_pdin(entries: &[(u32, u32)]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox(v=0, flags=0)
        for (rate, delay) in entries {
            body.extend_from_slice(&rate.to_be_bytes());
            body.extend_from_slice(&delay.to_be_bytes());
        }
        body
    }

    /// `pdin` with a representative two-entry table round-trips through
    /// the typed accessor in file order, with both u32 fields preserved
    /// verbatim.
    #[test]
    fn parse_pdin_two_entries_preserves_order() {
        let body = build_pdin(&[(125_000, 2_500), (250_000, 1_200)]);
        let r = super::parse_pdin(&body).unwrap();
        assert_eq!(r.entries.len(), 2);
        assert_eq!(
            r.entries[0],
            super::PdinEntry {
                rate: 125_000,
                initial_delay: 2_500,
            }
        );
        assert_eq!(
            r.entries[1],
            super::PdinEntry {
                rate: 250_000,
                initial_delay: 1_200,
            }
        );
    }

    /// `pdin` with zero pairs (preamble only, 4-byte body) is permitted:
    /// a producer's way of signalling "no progressive-download hints".
    #[test]
    fn parse_pdin_empty_body_yields_empty_entries() {
        let body = build_pdin(&[]);
        let r = super::parse_pdin(&body).unwrap();
        assert!(r.entries.is_empty());
    }

    /// `build_pdin_box` is the byte-exact inverse of `parse_pdin_box`: a
    /// two-entry table re-parses to the same `(rate, initial_delay)` pairs
    /// in order.
    #[test]
    fn build_pdin_box_round_trips() {
        let record = super::PdinRecord {
            entries: vec![
                super::PdinEntry {
                    rate: 125_000,
                    initial_delay: 2_500,
                },
                super::PdinEntry {
                    rate: 250_000,
                    initial_delay: 1_200,
                },
            ],
        };
        let boxed = super::build_pdin_box(&record);
        assert_eq!(&boxed[4..8], b"pdin");
        let r = super::parse_pdin_box(&boxed[8..]).unwrap();
        assert_eq!(r.entries, record.entries);
    }

    /// An empty entry list yields a preamble-only `pdin` (12 bytes:
    /// 8-byte header + 4-byte FullBox preamble).
    #[test]
    fn build_pdin_box_empty() {
        let boxed = super::build_pdin_box(&super::PdinRecord { entries: vec![] });
        assert_eq!(boxed.len(), 12);
        let r = super::parse_pdin_box(&boxed[8..]).unwrap();
        assert!(r.entries.is_empty());
    }

    /// `build_pnot_box` โ†’ `parse_pnot_box` is a byte-exact round-trip; the
    /// typical `PICT` / index-1 poster locator decodes field-for-field.
    #[test]
    fn pnot_box_round_trips() {
        let r = super::PnotRecord {
            modification_date: 0xC0FF_EE00,
            version: 0,
            atom_type: *b"PICT",
            atom_index: 1,
        };
        let boxed = super::build_pnot_box(&r);
        assert_eq!(&boxed[4..8], b"pnot");
        assert_eq!(boxed.len(), 20); // 8 header + 12 body
        let back = super::parse_pnot_box(&boxed[8..]).expect("round-trip");
        assert_eq!(back, r);
    }

    /// A `pnot` body shorter than the fixed 12 bytes is rejected.
    #[test]
    fn pnot_box_too_short_is_rejected() {
        assert!(super::parse_pnot(&[0u8; 11]).is_none());
        assert!(super::parse_pnot_box(&[0u8; 11]).is_err());
    }

    /// `build_prft_box` is the byte-exact inverse of `parse_prft_box` for
    /// a version-0 (32-bit media_time) record, including the 2022-edition
    /// `flags` annotation bits.
    #[test]
    fn build_prft_box_v0_round_trips() {
        let record = super::PrftRecord {
            reference_track_id: 1,
            ntp_timestamp: 0x1234_5678_9ABC_DEF0,
            media_time: 90_000,
            version: 0,
            flags: 0x00_0001, // encoder_input_output
        };
        let boxed = super::build_prft_box(&record).unwrap();
        assert_eq!(&boxed[4..8], b"prft");
        let r = super::parse_prft_box(&boxed[8..]).unwrap().unwrap();
        assert_eq!(r.reference_track_id, 1);
        assert_eq!(r.ntp_timestamp, 0x1234_5678_9ABC_DEF0);
        assert_eq!(r.media_time, 90_000);
        assert_eq!(r.version, 0);
        assert_eq!(r.flags, 0x00_0001);
        assert!(r.is_encoder_input_output());
    }

    /// A version-1 record (64-bit media_time beyond u32 range) round-trips.
    #[test]
    fn build_prft_box_v1_round_trips() {
        let record = super::PrftRecord {
            reference_track_id: 3,
            ntp_timestamp: 0xDEAD_BEEF_CAFE_F00D,
            media_time: 0x1_0000_0001,
            version: 1,
            flags: 0,
        };
        let boxed = super::build_prft_box(&record).unwrap();
        let r = super::parse_prft_box(&boxed[8..]).unwrap().unwrap();
        assert_eq!(r.version, 1);
        assert_eq!(r.media_time, 0x1_0000_0001);
        assert_eq!(r.reference_track_id, 3);
    }

    /// A version-0 record whose media_time overflows the 32-bit field is
    /// rejected (the caller must bump to version 1); an unknown version
    /// is rejected.
    #[test]
    fn build_prft_box_rejects_inconsistent() {
        let overflow = super::PrftRecord {
            reference_track_id: 1,
            ntp_timestamp: 0,
            media_time: 0x1_0000_0000,
            version: 0,
            flags: 0,
        };
        assert!(super::build_prft_box(&overflow).is_none());
        let bad_version = super::PrftRecord {
            version: 2,
            ..overflow
        };
        assert!(super::build_prft_box(&bad_version).is_none());
    }

    /// A `pdin` body shorter than the 4-byte FullBox preamble is
    /// rejected outright โ€” `parse_pdin` cannot recover the version bits.
    #[test]
    fn parse_pdin_too_short_preamble() {
        for n in 0..4 {
            let body = vec![0u8; n];
            assert!(super::parse_pdin(&body).is_err(), "len {n} must err");
        }
    }

    /// A `pdin` body whose post-preamble length is not a multiple of 8
    /// (one u32 pair per entry) is rejected โ€” the spec's loop body is
    /// exactly 8 bytes (ยง8.1.3.2) and a truncated tail is the
    /// producer's bug, not ours to silently round down.
    #[test]
    fn parse_pdin_unaligned_payload_is_rejected() {
        // 4-byte preamble + 12 bytes (1.5 pairs) โ†’ unaligned.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(&[0u8; 12]);
        assert!(super::parse_pdin(&body).is_err());

        // 4-byte preamble + 9 bytes (just past one pair) โ†’ unaligned.
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]);
        body.extend_from_slice(&[0u8; 9]);
        assert!(super::parse_pdin(&body).is_err());
    }

    /// `parse_pdin` tolerates a non-zero version byte: ยง8.1.3.2 pins
    /// version to 0 but the payload layout is unambiguous (no
    /// version-dependent branching), so we surface whatever the
    /// producer wrote rather than rejecting on a version-bit slip โ€”
    /// matching `parse_padb` / `parse_stdp` posture.
    #[test]
    fn parse_pdin_tolerates_nonzero_version() {
        let mut body = Vec::new();
        body.push(0xAA); // bogus version
        body.extend_from_slice(&[0u8; 3]); // flags
        body.extend_from_slice(&1u32.to_be_bytes());
        body.extend_from_slice(&2u32.to_be_bytes());
        let r = super::parse_pdin(&body).unwrap();
        assert_eq!(
            r.entries,
            vec![super::PdinEntry {
                rate: 1,
                initial_delay: 2,
            }]
        );
    }

    /// `parse_pdin` reads u32s in big-endian byte order per the spec
    /// (every multi-byte field in ISOBMFF is big-endian, ยง4.2 and
    /// ยง8.1.3.2). A naรฏve little-endian read would surface
    /// `u32::from_le_bytes` semantics instead, which this test pins.
    #[test]
    fn parse_pdin_big_endian_byte_order() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
                                           // rate = 0x01_02_03_04, initial_delay = 0x05_06_07_08 in big-endian.
        body.extend_from_slice(&[0x01, 0x02, 0x03, 0x04]);
        body.extend_from_slice(&[0x05, 0x06, 0x07, 0x08]);
        let r = super::parse_pdin(&body).unwrap();
        assert_eq!(r.entries.len(), 1);
        assert_eq!(r.entries[0].rate, 0x01_02_03_04);
        assert_eq!(r.entries[0].initial_delay, 0x05_06_07_08);
    }

    /// `parse_pdin_box` (the public wrapper) routes through the same
    /// `parse_pdin` impl as the internal call, so tooling that has the
    /// payload bytes in hand recovers the same `PdinRecord`.
    #[test]
    fn parse_pdin_box_public_entry_matches_internal() {
        let body = build_pdin(&[(64_000, 5_000), (128_000, 2_400), (256_000, 1_000)]);
        let r_public = super::parse_pdin_box(&body).unwrap();
        let r_internal = super::parse_pdin(&body).unwrap();
        assert_eq!(r_public.entries, r_internal.entries);
        assert_eq!(r_public.entries.len(), 3);
    }

    /// One per-level entry to feed `build_leva`. The variant-specific
    /// trailing fields are tagged on the assignment_type discriminant:
    /// 0 โ†’ `Some(grouping_type)` only, 1 โ†’ both, 4 โ†’ sub_track_id, 2/3
    /// โ†’ none.
    #[derive(Clone, Copy, Debug)]
    struct LevaBuild {
        track_id: u32,
        padding_flag: bool,
        assignment_type: u8,
        grouping_type: u32,
        grouping_type_parameter: u32,
        sub_track_id: u32,
    }

    /// Build a `leva` (ISO/IEC 14496-12 ยง8.8.13) body: 4-byte FullBox
    /// preamble + `level_count` u8 + N per-level entries laid out per
    /// ยง8.8.13.2. Reserved assignment_type values (> 4) emit only the
    /// 5-byte header โ€” the spec doesn't define their tail length.
    fn build_leva(entries: &[LevaBuild]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox(v=0, flags=0)
        body.push(entries.len() as u8); // level_count
        for e in entries {
            body.extend_from_slice(&e.track_id.to_be_bytes());
            let packed = (if e.padding_flag { 0x80 } else { 0 }) | (e.assignment_type & 0x7f);
            body.push(packed);
            match e.assignment_type {
                0 => body.extend_from_slice(&e.grouping_type.to_be_bytes()),
                1 => {
                    body.extend_from_slice(&e.grouping_type.to_be_bytes());
                    body.extend_from_slice(&e.grouping_type_parameter.to_be_bytes());
                }
                2 | 3 => {}
                4 => body.extend_from_slice(&e.sub_track_id.to_be_bytes()),
                _ => {}
            }
        }
        body
    }

    /// `leva` with a representative two-entry mix (one type-0, one
    /// type-4) round-trips through `parse_leva` in file order, with
    /// all variant-specific fields preserved verbatim.
    #[test]
    fn parse_leva_mixed_assignment_types_preserved() {
        let entries = vec![
            LevaBuild {
                track_id: 1,
                padding_flag: false,
                assignment_type: 0,
                grouping_type: u32::from_be_bytes(*b"roll"),
                grouping_type_parameter: 0,
                sub_track_id: 0,
            },
            LevaBuild {
                track_id: 7,
                padding_flag: true,
                assignment_type: 4,
                grouping_type: 0,
                grouping_type_parameter: 0,
                sub_track_id: 0xAABB_CCDD,
            },
        ];
        let body = build_leva(&entries);
        let r = super::parse_leva(&body).unwrap();
        assert_eq!(r.entries.len(), 2);

        assert_eq!(r.entries[0].track_id, 1);
        assert!(!r.entries[0].padding_flag);
        assert_eq!(r.entries[0].assignment_type, 0);
        assert_eq!(r.entries[0].grouping_type, u32::from_be_bytes(*b"roll"));
        assert_eq!(r.entries[0].grouping_type_parameter, 0);
        assert_eq!(r.entries[0].sub_track_id, 0);

        assert_eq!(r.entries[1].track_id, 7);
        assert!(r.entries[1].padding_flag);
        assert_eq!(r.entries[1].assignment_type, 4);
        assert_eq!(r.entries[1].sub_track_id, 0xAABB_CCDD);
    }

    /// `leva` with assignment_type = 1 carries both `grouping_type`
    /// and `grouping_type_parameter`; the parser must consume both
    /// (8 bytes of tail) per ยง8.8.13.2.
    #[test]
    fn parse_leva_assignment_type_one_carries_both_grouping_fields() {
        let entries = vec![LevaBuild {
            track_id: 42,
            padding_flag: false,
            assignment_type: 1,
            grouping_type: u32::from_be_bytes(*b"sync"),
            grouping_type_parameter: 0xDEAD_BEEF,
            sub_track_id: 0,
        }];
        let body = build_leva(&entries);
        let r = super::parse_leva(&body).unwrap();
        assert_eq!(r.entries.len(), 1);
        assert_eq!(r.entries[0].assignment_type, 1);
        assert_eq!(r.entries[0].grouping_type, u32::from_be_bytes(*b"sync"));
        assert_eq!(r.entries[0].grouping_type_parameter, 0xDEAD_BEEF);
    }

    /// `leva` with assignment_type 2 or 3 (level by track / by
    /// track-subsegment) is just the 5-byte header โ€” no variant tail.
    /// Two back-to-back type-2 / type-3 entries round-trip cleanly.
    #[test]
    fn parse_leva_assignment_types_two_three_have_no_tail() {
        let entries = vec![
            LevaBuild {
                track_id: 11,
                padding_flag: false,
                assignment_type: 2,
                grouping_type: 0,
                grouping_type_parameter: 0,
                sub_track_id: 0,
            },
            LevaBuild {
                track_id: 12,
                padding_flag: true,
                assignment_type: 3,
                grouping_type: 0,
                grouping_type_parameter: 0,
                sub_track_id: 0,
            },
        ];
        let body = build_leva(&entries);
        // Body: 4 preamble + 1 level_count + 2*5 entry bytes = 15 total.
        assert_eq!(body.len(), 4 + 1 + 2 * 5);
        let r = super::parse_leva(&body).unwrap();
        assert_eq!(r.entries.len(), 2);
        assert_eq!(r.entries[0].assignment_type, 2);
        assert_eq!(r.entries[0].track_id, 11);
        assert_eq!(r.entries[1].assignment_type, 3);
        assert_eq!(r.entries[1].track_id, 12);
        assert!(r.entries[1].padding_flag);
    }

    /// `leva` with `level_count = 0` is permitted by this parser
    /// (the spec pins a minimum of 2 in ยง8.8.13.3 but we carry whatever
    /// the producer wrote so a validator can flag it). Body is 4-byte
    /// preamble + 1-byte zero level_count.
    #[test]
    fn parse_leva_zero_level_count_yields_empty_entries() {
        let body = build_leva(&[]);
        let r = super::parse_leva(&body).unwrap();
        assert!(r.entries.is_empty());
    }

    /// A `leva` body shorter than the 4-byte FullBox preamble is
    /// rejected โ€” `parse_leva` can't recover the version bits.
    #[test]
    fn parse_leva_too_short_preamble() {
        for n in 0..4 {
            let body = vec![0u8; n];
            assert!(super::parse_leva(&body).is_err(), "len {n} must err");
        }
    }

    /// A `leva` body with the FullBox preamble but no `level_count`
    /// byte is rejected.
    #[test]
    fn parse_leva_missing_level_count_byte() {
        let body = vec![0u8; 4];
        assert!(super::parse_leva(&body).is_err());
    }

    /// A `leva` body that claims `level_count = 1` but stops before
    /// the entry's 5-byte header is rejected as truncated rather than
    /// silently treated as zero entries โ€” a short table would lie
    /// about which levels exist.
    #[test]
    fn parse_leva_truncated_entry_header_is_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
        body.push(1); // level_count = 1
                      // Only 4 bytes of the 5-byte header (track_id but no packed byte).
        body.extend_from_slice(&[0u8; 4]);
        assert!(super::parse_leva(&body).is_err());
    }

    /// `leva` assignment_type = 0 with a truncated `grouping_type` (3
    /// bytes instead of 4) is rejected.
    #[test]
    fn parse_leva_truncated_grouping_type_for_at0_is_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
        body.push(1); // level_count
        body.extend_from_slice(&5u32.to_be_bytes()); // track_id
        body.push(0); // padding=0 | at=0
                      // Only 3 of 4 grouping_type bytes.
        body.extend_from_slice(&[0u8; 3]);
        assert!(super::parse_leva(&body).is_err());
    }

    /// `leva` assignment_type = 1 with a truncated tail (4 of 8
    /// bytes) is rejected.
    #[test]
    fn parse_leva_truncated_grouping_parameter_for_at1_is_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
        body.push(1); // level_count
        body.extend_from_slice(&5u32.to_be_bytes()); // track_id
        body.push(1); // padding=0 | at=1
        body.extend_from_slice(&7u32.to_be_bytes()); // grouping_type
                                                     // Missing the 4-byte grouping_type_parameter.
        assert!(super::parse_leva(&body).is_err());
    }

    /// `leva` assignment_type = 4 with a truncated `sub_track_id` (2
    /// bytes instead of 4) is rejected.
    #[test]
    fn parse_leva_truncated_sub_track_id_for_at4_is_rejected() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
        body.push(1); // level_count
        body.extend_from_slice(&5u32.to_be_bytes()); // track_id
        body.push(4); // padding=0 | at=4
        body.extend_from_slice(&[0u8; 2]); // only 2 of 4 sub_track_id bytes
        assert!(super::parse_leva(&body).is_err());
    }

    /// `leva` reserved assignment_type values (> 4) are carried as
    /// 5-byte headers with all variant-specific fields zero. The
    /// spec doesn't define their tail, so the parser must not eat
    /// any extra bytes โ€” a downstream entry must still be reachable.
    #[test]
    fn parse_leva_reserved_assignment_type_consumes_no_tail() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
        body.push(2); // level_count = 2
                      // Entry 0: track_id = 9, padding = 1, at = 5 (reserved).
        body.extend_from_slice(&9u32.to_be_bytes());
        body.push(0x80 | 5);
        // Entry 1: track_id = 10, padding = 0, at = 2 (no tail).
        body.extend_from_slice(&10u32.to_be_bytes());
        body.push(2);
        let r = super::parse_leva(&body).unwrap();
        assert_eq!(r.entries.len(), 2);
        assert_eq!(r.entries[0].track_id, 9);
        assert!(r.entries[0].padding_flag);
        assert_eq!(r.entries[0].assignment_type, 5);
        assert_eq!(r.entries[0].grouping_type, 0);
        assert_eq!(r.entries[0].grouping_type_parameter, 0);
        assert_eq!(r.entries[0].sub_track_id, 0);
        // The second entry must have parsed cleanly, proving the
        // reserved entry didn't consume the next header's bytes.
        assert_eq!(r.entries[1].track_id, 10);
        assert_eq!(r.entries[1].assignment_type, 2);
    }

    /// `parse_leva` tolerates a non-zero FullBox version byte
    /// (ยง8.8.13.2 pins it to 0). The layout is unambiguous so we
    /// surface whatever the producer wrote โ€” same posture as
    /// `parse_pdin` / `parse_padb` / `parse_stdp`.
    #[test]
    fn parse_leva_tolerates_nonzero_version() {
        let mut body = Vec::new();
        body.push(0xCC); // bogus version
        body.extend_from_slice(&[0u8; 3]); // flags
        body.push(1); // level_count
        body.extend_from_slice(&42u32.to_be_bytes()); // track_id
        body.push(0x80 | 3); // padding=1 | at=3 (no tail)
        let r = super::parse_leva(&body).unwrap();
        assert_eq!(r.entries.len(), 1);
        assert_eq!(r.entries[0].track_id, 42);
        assert!(r.entries[0].padding_flag);
        assert_eq!(r.entries[0].assignment_type, 3);
    }

    /// `parse_leva` reads u32s in big-endian byte order per ยง4.2 and
    /// ยง8.8.13.2. A naรฏve little-endian read would surface
    /// `u32::from_le_bytes` semantics; this test pins the BE choice.
    #[test]
    fn parse_leva_big_endian_byte_order() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // preamble
        body.push(1); // level_count
        body.extend_from_slice(&[0x11, 0x22, 0x33, 0x44]); // track_id
        body.push(0); // packed byte: padding=0 | at=0
        body.extend_from_slice(&[0xAB, 0xCD, 0xEF, 0x01]); // grouping_type
        let r = super::parse_leva(&body).unwrap();
        assert_eq!(r.entries.len(), 1);
        assert_eq!(r.entries[0].track_id, 0x1122_3344);
        assert_eq!(r.entries[0].grouping_type, 0xABCD_EF01);
    }

    /// `parse_leva` masks the 7-bit `assignment_type` against the
    /// `padding_flag` high bit โ€” both halves of the packed byte are
    /// independently recoverable.
    #[test]
    fn parse_leva_packed_byte_splits_padding_and_assignment_type() {
        for padding in [false, true] {
            for at in 0u8..=4 {
                let mut body = Vec::new();
                body.extend_from_slice(&[0u8; 4]);
                body.push(1);
                body.extend_from_slice(&3u32.to_be_bytes());
                body.push((if padding { 0x80 } else { 0 }) | at);
                match at {
                    0 => body.extend_from_slice(&0u32.to_be_bytes()),
                    1 => body.extend_from_slice(&[0u8; 8]),
                    2 | 3 => {}
                    4 => body.extend_from_slice(&0u32.to_be_bytes()),
                    _ => {}
                }
                let r = super::parse_leva(&body).unwrap();
                assert_eq!(r.entries.len(), 1);
                assert_eq!(r.entries[0].padding_flag, padding);
                assert_eq!(r.entries[0].assignment_type, at);
            }
        }
    }

    /// `parse_leva_box` (the public wrapper) routes through the same
    /// `parse_leva` impl as the internal call, so tooling that has
    /// the payload bytes in hand recovers the same `LevaRecord`.
    #[test]
    fn parse_leva_box_public_entry_matches_internal() {
        let entries = vec![
            LevaBuild {
                track_id: 1,
                padding_flag: true,
                assignment_type: 0,
                grouping_type: u32::from_be_bytes(*b"rap "),
                grouping_type_parameter: 0,
                sub_track_id: 0,
            },
            LevaBuild {
                track_id: 2,
                padding_flag: false,
                assignment_type: 1,
                grouping_type: u32::from_be_bytes(*b"alst"),
                grouping_type_parameter: 0x1234_5678,
                sub_track_id: 0,
            },
            LevaBuild {
                track_id: 3,
                padding_flag: false,
                assignment_type: 4,
                grouping_type: 0,
                grouping_type_parameter: 0,
                sub_track_id: 99,
            },
        ];
        let body = build_leva(&entries);
        let r_public = super::parse_leva_box(&body).unwrap();
        let r_internal = super::parse_leva(&body).unwrap();
        assert_eq!(r_public.entries, r_internal.entries);
        assert_eq!(r_public.entries.len(), 3);
    }

    // ---- trep (TrackExtensionPropertiesBox, ยง8.8.15) -------------------

    /// Build a child box (8-byte header + payload) for embedding in a
    /// `trep` body.
    fn build_child_box(fourcc: &[u8; 4], payload: &[u8]) -> Vec<u8> {
        let size = 8 + payload.len();
        let mut v = Vec::with_capacity(size);
        v.extend_from_slice(&(size as u32).to_be_bytes());
        v.extend_from_slice(fourcc);
        v.extend_from_slice(payload);
        v
    }

    /// Build a `trep` body: 4-byte FullBox preamble + 4-byte track_id +
    /// the concatenated child boxes.
    fn build_trep(track_id: u32, children: &[Vec<u8>]) -> Vec<u8> {
        let mut v = Vec::new();
        v.extend_from_slice(&[0u8; 4]); // version + flags = 0
        v.extend_from_slice(&track_id.to_be_bytes());
        for c in children {
            v.extend_from_slice(c);
        }
        v
    }

    /// A `trep` carrying just its `track_id` (no children) parses to an
    /// empty `children` list. Body is 4 preamble + 4 track_id = 8 bytes.
    #[test]
    fn parse_trep_track_id_only() {
        let body = build_trep(0x0102_0304, &[]);
        assert_eq!(body.len(), 8);
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.track_id, 0x0102_0304);
        assert!(r.children.is_empty());
    }

    /// A `trep` with two child boxes records each child's fourcc and
    /// payload length, in file order, without recursing into them.
    #[test]
    fn parse_trep_records_children_in_order() {
        let assp = build_child_box(b"assp", &[0xaa; 12]);
        let unkn = build_child_box(b"xyzw", &[]);
        let body = build_trep(7, &[assp, unkn]);
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.track_id, 7);
        assert_eq!(r.children.len(), 2);
        assert_eq!(&r.children[0].fourcc, b"assp");
        assert_eq!(r.children[0].payload_len, 12);
        assert_eq!(&r.children[1].fourcc, b"xyzw");
        assert_eq!(r.children[1].payload_len, 0);
    }

    /// A `trep` body shorter than the 4-byte FullBox preamble is
    /// rejected โ€” there's nothing to recover.
    #[test]
    fn parse_trep_too_short_preamble() {
        for n in 0..4 {
            let body = vec![0u8; n];
            assert!(super::parse_trep(&body).is_err(), "len {n} must err");
        }
    }

    /// A `trep` body with the preamble but a truncated `track_id` (fewer
    /// than 4 bytes after the preamble) is rejected.
    #[test]
    fn parse_trep_truncated_track_id() {
        for extra in 0..4 {
            let mut body = vec![0u8; 4]; // preamble
            body.extend_from_slice(&vec![0u8; extra]);
            assert!(
                super::parse_trep(&body).is_err(),
                "track_id with {extra} bytes must err",
            );
        }
    }

    /// A non-zero FullBox version is tolerated (the layout up to
    /// `track_id` is unambiguous), matching the `parse_leva` posture.
    #[test]
    fn parse_trep_tolerates_nonzero_version() {
        let mut body = build_trep(42, &[build_child_box(b"assp", &[1, 2, 3, 4])]);
        body[0] = 0x01; // flip the version byte
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.track_id, 42);
        assert_eq!(r.children.len(), 1);
        assert_eq!(r.children[0].payload_len, 4);
    }

    /// A child whose declared size overruns the remaining `trep` body is
    /// clamped to the bytes available, recorded with the clamped length,
    /// and ends the child walk (no sibling can follow an over-long box).
    #[test]
    fn parse_trep_clamps_overlong_child() {
        let mut body = build_trep(3, &[]);
        // Child header declaring size 0x40 (64) but only 4 payload
        // bytes actually present after the 8-byte header.
        body.extend_from_slice(&64u32.to_be_bytes());
        body.extend_from_slice(b"assp");
        body.extend_from_slice(&[0xff; 4]);
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.children.len(), 1);
        assert_eq!(&r.children[0].fourcc, b"assp");
        // Available after the header = 4 bytes; clamped payload_len = 4.
        assert_eq!(r.children[0].payload_len, 4);
    }

    /// A trailing child header that doesn't fit (fewer than 8 bytes left
    /// after the previous child) ends the walk cleanly rather than
    /// erroring โ€” the `track_id` and the well-formed children survive.
    #[test]
    fn parse_trep_trailing_partial_child_header_ignored() {
        let mut body = build_trep(9, &[build_child_box(b"assp", &[0; 4])]);
        // Append 5 stray bytes โ€” too few for an 8-byte box header.
        body.extend_from_slice(&[0x11; 5]);
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.track_id, 9);
        assert_eq!(r.children.len(), 1);
        assert_eq!(&r.children[0].fourcc, b"assp");
    }

    /// A child using the 64-bit `largesize` form (size32 == 1) is read
    /// via its 16-byte header and the largesize field.
    #[test]
    fn parse_trep_child_largesize_form() {
        let mut body = build_trep(5, &[]);
        // size32 = 1 signals a 64-bit largesize follows the fourcc.
        let payload = [0x55u8; 6];
        let total: u64 = (16 + payload.len()) as u64;
        body.extend_from_slice(&1u32.to_be_bytes());
        body.extend_from_slice(b"assp");
        body.extend_from_slice(&total.to_be_bytes());
        body.extend_from_slice(&payload);
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.children.len(), 1);
        assert_eq!(&r.children[0].fourcc, b"assp");
        assert_eq!(r.children[0].payload_len, 6);
    }

    /// `parse_trep_box` (the public wrapper) routes through the same
    /// internal parser as the `open()` walk.
    #[test]
    fn parse_trep_box_public_entry_matches_internal() {
        let body = build_trep(123, &[build_child_box(b"assp", &[7; 8])]);
        let r_public = super::parse_trep_box(&body).unwrap();
        let r_internal = super::parse_trep(&body).unwrap();
        assert_eq!(r_public.track_id, r_internal.track_id);
        assert_eq!(r_public.children, r_internal.children);
        assert_eq!(r_public.track_id, 123);
    }

    // ---- assp (AlternativeStartupSequencePropertiesBox, ยง8.8.16) -------

    /// A version-0 `assp` body decodes to a single implied entry carrying
    /// the signed `min_initial_alt_startup_offset` and no
    /// `grouping_type_parameter`.
    #[test]
    fn parse_assp_v0_single_offset() {
        let mut body = vec![0u8; 4]; // version 0 + flags 0
        body.extend_from_slice(&(-5i32).to_be_bytes());
        let r = super::parse_assp(&body).unwrap();
        assert_eq!(r.version, 0);
        assert_eq!(r.entries.len(), 1);
        assert_eq!(r.entries[0].grouping_type_parameter, None);
        assert_eq!(r.entries[0].min_initial_alt_startup_offset, -5);
    }

    /// A version-1 `assp` body decodes `num_entries` keyed
    /// `(grouping_type_parameter, offset)` pairs in order.
    #[test]
    fn parse_assp_v1_keyed_entries() {
        let mut body = vec![1u8, 0, 0, 0]; // version 1 + flags 0
        body.extend_from_slice(&2u32.to_be_bytes()); // num_entries
        body.extend_from_slice(&7u32.to_be_bytes());
        body.extend_from_slice(&(-3i32).to_be_bytes());
        body.extend_from_slice(&9u32.to_be_bytes());
        body.extend_from_slice(&100i32.to_be_bytes());
        let r = super::parse_assp(&body).unwrap();
        assert_eq!(r.version, 1);
        assert_eq!(r.entries.len(), 2);
        assert_eq!(r.entries[0].grouping_type_parameter, Some(7));
        assert_eq!(r.entries[0].min_initial_alt_startup_offset, -3);
        assert_eq!(r.entries[1].grouping_type_parameter, Some(9));
        assert_eq!(r.entries[1].min_initial_alt_startup_offset, 100);
    }

    /// A truncated v0 offset, a truncated v1 `num_entries`, a v1
    /// `num_entries` that overruns the body, and an unsupported version
    /// are all rejected.
    #[test]
    fn parse_assp_rejects_malformed() {
        // too short for the FullBox preamble
        assert!(super::parse_assp(&[0u8; 3]).is_err());
        // v0 with no offset
        assert!(super::parse_assp(&[0u8; 4]).is_err());
        // v1 with no num_entries
        assert!(super::parse_assp(&[1u8, 0, 0, 0]).is_err());
        // v1 declaring 4 entries but carrying bytes for one
        let mut overrun = vec![1u8, 0, 0, 0];
        overrun.extend_from_slice(&4u32.to_be_bytes());
        overrun.extend_from_slice(&[0u8; 8]);
        assert!(super::parse_assp(&overrun).is_err());
        // unsupported version 2
        assert!(super::parse_assp(&[2u8, 0, 0, 0, 0, 0, 0, 0]).is_err());
    }

    /// `build_assp_box` is the byte-exact inverse of `parse_assp_box` for
    /// both versions (modulo the 8-byte box header the builder prepends).
    #[test]
    fn assp_build_parse_round_trip() {
        for record in [
            super::AsspRecord {
                version: 0,
                entries: vec![super::AsspEntry {
                    grouping_type_parameter: None,
                    min_initial_alt_startup_offset: -42,
                }],
            },
            super::AsspRecord {
                version: 1,
                entries: vec![
                    super::AsspEntry {
                        grouping_type_parameter: Some(0),
                        min_initial_alt_startup_offset: 0,
                    },
                    super::AsspEntry {
                        grouping_type_parameter: Some(0xDEAD_BEEF),
                        min_initial_alt_startup_offset: i32::MIN,
                    },
                ],
            },
        ] {
            let bytes = super::build_assp_box(&record).unwrap();
            assert_eq!(&bytes[4..8], b"assp");
            assert_eq!(
                u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize,
                bytes.len()
            );
            let reparsed = super::parse_assp_box(&bytes[8..]).unwrap();
            assert_eq!(reparsed, record);
        }
    }

    /// `build_assp_box` rejects records that cannot round-trip: a v0
    /// record with a `grouping_type_parameter`, a v0 record with โ‰  1
    /// entry, or an unsupported version.
    #[test]
    fn assp_build_rejects_invalid_records() {
        // v0 entry carrying a grouping_type_parameter (no v0 wire slot)
        assert!(super::build_assp_box(&super::AsspRecord {
            version: 0,
            entries: vec![super::AsspEntry {
                grouping_type_parameter: Some(1),
                min_initial_alt_startup_offset: 0,
            }],
        })
        .is_err());
        // v0 with two entries
        assert!(super::build_assp_box(&super::AsspRecord {
            version: 0,
            entries: vec![
                super::AsspEntry {
                    grouping_type_parameter: None,
                    min_initial_alt_startup_offset: 0,
                };
                2
            ],
        })
        .is_err());
        // unsupported version
        assert!(super::build_assp_box(&super::AsspRecord {
            version: 9,
            entries: vec![],
        })
        .is_err());
    }

    /// When an `assp` child of a `trep` decodes cleanly, the `TrepChild`
    /// carries the typed `AsspRecord`; a malformed `assp` (or any other
    /// child type) leaves `assp = None`.
    #[test]
    fn parse_trep_decodes_assp_child() {
        // A clean v0 assp body: version+flags (4) + offset (4) = 8 bytes.
        let mut assp_body = vec![0u8; 4];
        assp_body.extend_from_slice(&(-7i32).to_be_bytes());
        let assp = build_child_box(b"assp", &assp_body);
        // A different child stays opaque.
        let other = build_child_box(b"xtra", &[0; 4]);
        let body = build_trep(11, &[assp, other]);
        let r = super::parse_trep(&body).unwrap();
        assert_eq!(r.children.len(), 2);
        let a = r.children[0].assp.as_ref().expect("assp should decode");
        assert_eq!(a.version, 0);
        assert_eq!(a.entries[0].min_initial_alt_startup_offset, -7);
        assert!(r.children[1].assp.is_none());
    }

    /// `build_trep_box` round-trips a `TrepRecord` carrying a typed `assp`
    /// child (and a bare empty-payload child) through `parse_trep_box`.
    #[test]
    fn build_trep_box_round_trips_assp_child() {
        let record = super::TrepRecord {
            track_id: 5,
            children: vec![
                super::TrepChild {
                    fourcc: *b"assp",
                    payload_len: 0,
                    assp: Some(super::AsspRecord {
                        version: 1,
                        entries: vec![super::AsspEntry {
                            grouping_type_parameter: Some(2),
                            min_initial_alt_startup_offset: -8,
                        }],
                    }),
                },
                super::TrepChild {
                    fourcc: *b"zzzz",
                    payload_len: 0,
                    assp: None,
                },
            ],
        };
        let bytes = super::build_trep_box(&record).unwrap();
        assert_eq!(&bytes[4..8], b"trep");
        let reparsed = super::parse_trep_box(&bytes[8..]).unwrap();
        assert_eq!(reparsed.track_id, 5);
        assert_eq!(reparsed.children.len(), 2);
        // The typed `assp` record round-trips verbatim (payload_len is a
        // derived on-wire length the builder recomputes, so we compare
        // the fourcc + typed record rather than the whole struct).
        assert_eq!(&reparsed.children[0].fourcc, b"assp");
        assert_eq!(reparsed.children[0].assp, record.children[0].assp);
        // The opaque empty-payload child round-trips fourcc + zero length.
        assert_eq!(&reparsed.children[1].fourcc, b"zzzz");
        assert_eq!(reparsed.children[1].payload_len, 0);
        assert!(reparsed.children[1].assp.is_none());
    }

    /// `build_trep_box` rejects a child whose `assp` record is set but
    /// whose fourcc isn't `assp`, and a non-`assp` child with a non-zero
    /// `payload_len` (the crate can't synthesise opaque child bytes).
    #[test]
    fn build_trep_box_rejects_inconsistent_children() {
        // assp record under a non-assp fourcc
        assert!(super::build_trep_box(&super::TrepRecord {
            track_id: 1,
            children: vec![super::TrepChild {
                fourcc: *b"abcd",
                payload_len: 0,
                assp: Some(super::AsspRecord {
                    version: 0,
                    entries: vec![super::AsspEntry {
                        grouping_type_parameter: None,
                        min_initial_alt_startup_offset: 0,
                    }],
                }),
            }],
        })
        .is_err());
        // opaque child with non-zero payload_len
        assert!(super::build_trep_box(&super::TrepRecord {
            track_id: 1,
            children: vec![super::TrepChild {
                fourcc: *b"abcd",
                payload_len: 4,
                assp: None,
            }],
        })
        .is_err());
    }

    /// `parse_ssix_box` (the public wrapper) routes through the same
    /// internal parser as the `open()` walk, and `build_ssix_box`
    /// round-trips a record through it (modulo the 8-byte box header
    /// the builder prepends).
    #[test]
    fn ssix_public_entries_round_trip() {
        let record = super::SsixRecord {
            subsegments: vec![
                super::SsixSubsegment {
                    ranges: vec![
                        super::SsixRange {
                            level: 0,
                            range_size: 1_024,
                        },
                        super::SsixRange {
                            level: 1,
                            range_size: 0xFF_FFFF,
                        },
                    ],
                },
                super::SsixSubsegment {
                    ranges: vec![
                        super::SsixRange {
                            level: 0,
                            range_size: 512,
                        },
                        super::SsixRange {
                            level: 2,
                            range_size: 7,
                        },
                    ],
                },
            ],
        };
        let boxed = super::build_ssix_box(&record).unwrap();
        assert_eq!(&boxed[4..8], b"ssix");
        assert_eq!(
            boxed.len(),
            u32::from_be_bytes(boxed[..4].try_into().unwrap()) as usize
        );
        let body = &boxed[8..];
        let r_public = super::parse_ssix_box(body).unwrap();
        let r_internal = super::parse_ssix(body).unwrap();
        assert_eq!(r_public, r_internal);
        assert_eq!(r_public, record);
    }

    /// `build_leva_box` emits a box whose body round-trips through
    /// `parse_leva_box` โ€” covering every assignment_type tail (0 carries
    /// grouping_type, 1 adds grouping_type_parameter, 2/3 are bare, 4
    /// carries sub_track_id) plus the padding_flag bit packing.
    #[test]
    fn leva_build_round_trip_all_assignment_types() {
        let record = super::LevaRecord {
            entries: vec![
                super::LevaEntry {
                    track_id: 1,
                    padding_flag: true,
                    assignment_type: 2,
                    grouping_type: 0,
                    grouping_type_parameter: 0,
                    sub_track_id: 0,
                },
                super::LevaEntry {
                    track_id: 2,
                    padding_flag: false,
                    assignment_type: 0,
                    grouping_type: u32::from_be_bytes(*b"rash"),
                    grouping_type_parameter: 0,
                    sub_track_id: 0,
                },
                super::LevaEntry {
                    track_id: 3,
                    padding_flag: true,
                    assignment_type: 1,
                    grouping_type: u32::from_be_bytes(*b"roll"),
                    grouping_type_parameter: 9,
                    sub_track_id: 0,
                },
                super::LevaEntry {
                    track_id: 4,
                    padding_flag: false,
                    assignment_type: 4,
                    grouping_type: 0,
                    grouping_type_parameter: 0,
                    sub_track_id: 77,
                },
            ],
        };
        let boxed = super::build_leva_box(&record).unwrap();
        assert_eq!(&boxed[4..8], b"leva");
        assert_eq!(
            boxed.len(),
            u32::from_be_bytes(boxed[..4].try_into().unwrap()) as usize
        );
        let parsed = super::parse_leva_box(&boxed[8..]).unwrap();
        assert_eq!(parsed.entries, record.entries);
    }

    /// `build_leva_box` rejects an `assignment_type` that does not fit the
    /// 7-bit field rather than corrupting it into the `padding_flag` bit.
    #[test]
    fn leva_build_rejects_oversized_assignment_type() {
        let record = super::LevaRecord {
            entries: vec![super::LevaEntry {
                track_id: 1,
                padding_flag: false,
                assignment_type: 200,
                grouping_type: 0,
                grouping_type_parameter: 0,
                sub_track_id: 0,
            }],
        };
        assert!(super::build_leva_box(&record).is_err());
    }

    /// `(subsample_size16, priority, discardable, csp)` โ€” one v0 sub-sample.
    type SubsV0Row = (u16, u8, u8, u32);
    /// `(subsample_size32, priority, discardable, csp)` โ€” one v1 sub-sample.
    type SubsV1Row = (u32, u8, u8, u32);

    /// Build a v0 `subs` body: FullBox preamble + entry_count + N entries.
    /// Each entry: `(sample_delta, [(size16, priority, discardable, csp), ...])`.
    fn build_subs_v0(flags: u32, entries: &[(u32, &[SubsV0Row])]) -> Vec<u8> {
        let mut body = Vec::new();
        body.push(0u8); // version
        body.extend_from_slice(&flags.to_be_bytes()[1..]); // 24-bit flags
        body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
        for (sample_delta, subs) in entries {
            body.extend_from_slice(&sample_delta.to_be_bytes());
            body.extend_from_slice(&(subs.len() as u16).to_be_bytes());
            for (size, prio, disc, csp) in subs.iter() {
                body.extend_from_slice(&size.to_be_bytes());
                body.push(*prio);
                body.push(*disc);
                body.extend_from_slice(&csp.to_be_bytes());
            }
        }
        body
    }

    /// Build a v1 `subs` body โ€” `subsample_size` widens to 32-bit.
    fn build_subs_v1(flags: u32, entries: &[(u32, &[SubsV1Row])]) -> Vec<u8> {
        let mut body = Vec::new();
        body.push(1u8);
        body.extend_from_slice(&flags.to_be_bytes()[1..]);
        body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
        for (sample_delta, subs) in entries {
            body.extend_from_slice(&sample_delta.to_be_bytes());
            body.extend_from_slice(&(subs.len() as u16).to_be_bytes());
            for (size, prio, disc, csp) in subs.iter() {
                body.extend_from_slice(&size.to_be_bytes());
                body.push(*prio);
                body.push(*disc);
                body.extend_from_slice(&csp.to_be_bytes());
            }
        }
        body
    }

    /// ยง8.7.7 โ€” v0 round-trip with two entries: one sample (delta=1) split
    /// into three sub-samples with varied priority/discardable/csp, plus
    /// a second sample (delta=2 โ†’ sample 3) with one sub-sample. Verifies
    /// field order, the 16-bit `subsample_size` width at v0, and the
    /// sparse `sample_delta` accumulation contract.
    #[test]
    fn parse_subs_v0_round_trip() {
        let body = build_subs_v0(
            0,
            &[
                (
                    1,
                    &[
                        (100, 5, 0, 0x0000_0001),
                        (50, 4, 1, 0x0000_0002),
                        (25, 3, 0, 0),
                    ],
                ),
                (2, &[(80, 6, 0, 0xdead_beef)]),
            ],
        );
        let s = super::parse_subs(&body).unwrap();
        assert_eq!(s.version, 0);
        assert_eq!(s.flags, 0);
        assert_eq!(s.entries.len(), 2);
        assert_eq!(s.entries[0].sample_delta, 1);
        assert_eq!(s.entries[0].subsamples.len(), 3);
        assert_eq!(s.entries[0].subsamples[0].subsample_size, 100);
        assert_eq!(s.entries[0].subsamples[0].subsample_priority, 5);
        assert_eq!(s.entries[0].subsamples[0].discardable, 0);
        assert_eq!(s.entries[0].subsamples[0].codec_specific_parameters, 1);
        assert_eq!(s.entries[0].subsamples[2].subsample_size, 25);
        assert_eq!(s.entries[1].sample_delta, 2);
        assert_eq!(s.entries[1].subsamples.len(), 1);
        assert_eq!(
            s.entries[1].subsamples[0].codec_specific_parameters,
            0xdead_beef
        );
    }

    /// ยง8.7.7 โ€” v1 widens `subsample_size` to 32-bit. Use a payload above
    /// the 16-bit ceiling (0x0001_0000) to prove the widening took effect
    /// and the parser didn't truncate to u16.
    #[test]
    fn parse_subs_v1_size_is_32bit() {
        let body = build_subs_v1(0, &[(1, &[(0x0001_2345, 0, 0, 0)])]);
        let s = super::parse_subs(&body).unwrap();
        assert_eq!(s.version, 1);
        assert_eq!(s.entries[0].subsamples[0].subsample_size, 0x0001_2345);
    }

    /// ยง8.7.7.1 โ€” a `subsample_count` of 0 is legal: the entry still
    /// consumes one row (advances the sparse delta cursor) but produces
    /// no per-sub-sample fields. Verifies the parser allows the
    /// degenerate shape rather than rejecting it.
    #[test]
    fn parse_subs_empty_subsample_count() {
        let body = build_subs_v0(0, &[(5, &[])]);
        let s = super::parse_subs(&body).unwrap();
        assert_eq!(s.entries.len(), 1);
        assert_eq!(s.entries[0].sample_delta, 5);
        assert!(s.entries[0].subsamples.is_empty());
    }

    /// `flags` is preserved verbatim (codec-specific per ยง8.7.7.1). Use a
    /// non-trivial 24-bit value to confirm the FullBox preamble parser
    /// didn't mask the field.
    #[test]
    fn parse_subs_preserves_flags() {
        let body = build_subs_v0(0x00_aa_55, &[(1, &[])]);
        let s = super::parse_subs(&body).unwrap();
        assert_eq!(s.flags, 0x00_aa_55);
    }

    /// A body too short to hold even the FullBox preamble + entry_count
    /// is rejected.
    #[test]
    fn parse_subs_too_short() {
        assert!(super::parse_subs(&[0u8; 7]).is_err());
    }

    /// A truncated sub-sample row (entry_count promises 1 entry, but the
    /// body runs out mid-sub-sample) is rejected rather than silently
    /// returning the partial table.
    #[test]
    fn parse_subs_truncated_subsample() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // FullBox preamble
        body.extend_from_slice(&1u32.to_be_bytes()); // entry_count = 1
        body.extend_from_slice(&1u32.to_be_bytes()); // sample_delta
        body.extend_from_slice(&1u16.to_be_bytes()); // subsample_count = 1
        body.extend_from_slice(&[0u8; 3]); // truncated subsample (need 8)
        assert!(super::parse_subs(&body).is_err());
    }

    /// `build_subs_box` is the byte-exact inverse of `parse_subs_box` for
    /// a multi-entry version-0 table (sparse deltas, multiple sub-samples,
    /// non-trivial codec_specific_parameters and flags).
    #[test]
    fn build_subs_box_v0_round_trips() {
        let record = super::SubsBox {
            version: 0,
            flags: 0x00_aa_55,
            entries: vec![
                super::SubsEntry {
                    sample_delta: 1,
                    subsamples: vec![
                        super::SubSampleEntry {
                            subsample_size: 100,
                            subsample_priority: 5,
                            discardable: 0,
                            codec_specific_parameters: 1,
                        },
                        super::SubSampleEntry {
                            subsample_size: 50,
                            subsample_priority: 4,
                            discardable: 1,
                            codec_specific_parameters: 2,
                        },
                    ],
                },
                super::SubsEntry {
                    sample_delta: 2,
                    subsamples: vec![super::SubSampleEntry {
                        subsample_size: 80,
                        subsample_priority: 6,
                        discardable: 0,
                        codec_specific_parameters: 0xdead_beef,
                    }],
                },
            ],
        };
        let boxed = super::build_subs_box(&record).unwrap();
        assert_eq!(&boxed[4..8], b"subs");
        let s = super::parse_subs_box(&boxed[8..]).unwrap();
        assert_eq!(s.version, 0);
        assert_eq!(s.flags, 0x00_aa_55);
        assert_eq!(s.entries.len(), 2);
        assert_eq!(s.entries[0].subsamples[1].subsample_size, 50);
        assert_eq!(s.entries[0].subsamples[1].discardable, 1);
        assert_eq!(
            s.entries[1].subsamples[0].codec_specific_parameters,
            0xdead_beef
        );
    }

    /// Version 1 widens `subsample_size` to 32-bit; a value above the
    /// 16-bit ceiling round-trips through the builder.
    #[test]
    fn build_subs_box_v1_wide_size() {
        let record = super::SubsBox {
            version: 1,
            flags: 0,
            entries: vec![super::SubsEntry {
                sample_delta: 1,
                subsamples: vec![super::SubSampleEntry {
                    subsample_size: 0x0001_2345,
                    subsample_priority: 0,
                    discardable: 0,
                    codec_specific_parameters: 0,
                }],
            }],
        };
        let boxed = super::build_subs_box(&record).unwrap();
        let s = super::parse_subs_box(&boxed[8..]).unwrap();
        assert_eq!(s.version, 1);
        assert_eq!(s.entries[0].subsamples[0].subsample_size, 0x0001_2345);
    }

    /// An empty entry list (a content-free `subs`) round-trips, and an
    /// entry with a zero `subsample_count` is preserved.
    #[test]
    fn build_subs_box_empty_and_degenerate() {
        let empty = super::build_subs_box(&super::SubsBox::default()).unwrap();
        assert!(super::parse_subs_box(&empty[8..])
            .unwrap()
            .entries
            .is_empty());
        let degenerate = super::SubsBox {
            version: 0,
            flags: 0,
            entries: vec![super::SubsEntry {
                sample_delta: 5,
                subsamples: vec![],
            }],
        };
        let boxed = super::build_subs_box(&degenerate).unwrap();
        let s = super::parse_subs_box(&boxed[8..]).unwrap();
        assert_eq!(s.entries[0].sample_delta, 5);
        assert!(s.entries[0].subsamples.is_empty());
    }

    /// A version-0 record whose `subsample_size` overflows the 16-bit v0
    /// field is rejected (the caller must use version 1); an undefined
    /// version is rejected.
    #[test]
    fn build_subs_box_rejects_inconsistent() {
        let overflow = super::SubsBox {
            version: 0,
            flags: 0,
            entries: vec![super::SubsEntry {
                sample_delta: 1,
                subsamples: vec![super::SubSampleEntry {
                    subsample_size: 0x0001_0000,
                    subsample_priority: 0,
                    discardable: 0,
                    codec_specific_parameters: 0,
                }],
            }],
        };
        assert!(super::build_subs_box(&overflow).is_none());
        let bad_version = super::SubsBox {
            version: 2,
            ..super::SubsBox::default()
        };
        assert!(super::build_subs_box(&bad_version).is_none());
    }

    /// `parse_stbl` lands the `subs` on the track alongside the other
    /// sample-table boxes (proves the dispatch arm is wired).
    #[test]
    fn parse_stbl_picks_up_subs() {
        let subs_body = build_subs_v0(0, &[(1, &[(42, 0, 0, 0)])]);
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"subs", &subs_body));
        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.subs.len(), 1);
        assert_eq!(t.subs[0].entries[0].subsamples[0].subsample_size, 42);
    }

    /// Multiple `subs` boxes (distinct `flags` per ยง8.7.7.1) accumulate
    /// in encounter order on the track โ€” we don't fail on, deduplicate,
    /// or otherwise touch the count: the spec explicitly permits several.
    #[test]
    fn parse_stbl_accumulates_multiple_subs() {
        let s1 = build_subs_v0(0, &[(1, &[(10, 0, 0, 0)])]);
        let s2 = build_subs_v0(1, &[(2, &[(20, 0, 0, 0)])]);
        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"subs", &s1));
        stbl.extend(wrap_box_full_size(b"subs", &s2));
        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.subs.len(), 2);
        assert_eq!(t.subs[0].flags, 0);
        assert_eq!(t.subs[1].flags, 1);
    }

    /// Surfacing: a parsed `subs` becomes one `subs_<n>` key on
    /// `params.options`. Verifies the `"v<version> flags=<f>"` prefix,
    /// the `delta=<d>:size,priority,discardable,csp` per-entry shape
    /// (with sub-samples joined by `;` and `csp` rendered as 8-digit
    /// hex), and the omission of the colon when an entry has zero
    /// sub-samples.
    #[test]
    fn build_stream_info_surfaces_subs_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        t.subs.push(super::SubsBox {
            version: 0,
            flags: 0x42,
            entries: vec![
                super::SubsEntry {
                    sample_delta: 1,
                    subsamples: vec![
                        super::SubSampleEntry {
                            subsample_size: 100,
                            subsample_priority: 5,
                            discardable: 0,
                            codec_specific_parameters: 0x0000_0001,
                        },
                        super::SubSampleEntry {
                            subsample_size: 50,
                            subsample_priority: 0,
                            discardable: 1,
                            codec_specific_parameters: 0x0000_0002,
                        },
                    ],
                },
                super::SubsEntry {
                    sample_delta: 3,
                    subsamples: Vec::new(),
                },
            ],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        let got = info.params.options.get("subs_0").unwrap();
        assert_eq!(
            got,
            "v0 flags=66 delta=1:100,5,0,00000001;50,0,1,00000002 delta=3"
        );
    }

    /// Absence: a track with no `subs` emits no `subs_<n>` keys.
    #[test]
    fn build_stream_info_no_subs_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("subs_0"), None);
    }

    // ISO/IEC 14496-12 ยง8.7.8 โ€” `saiz` parsing. Body layout (after the
    // 4-byte FullBox header):
    //
    //   if (flags & 1) { u32 aux_info_type; u32 aux_info_type_parameter }
    //   u8  default_sample_info_size
    //   u32 sample_count
    //   if (default_sample_info_size == 0) { u8 sample_info_size[sample_count] }

    /// ยง8.7.8.2 with `flags & 1 == 0` and a non-zero
    /// `default_sample_info_size`: the per-sample table is omitted on
    /// disk (every sample has the constant size) and the
    /// `aux_info_type` block is absent (the implied value is the
    /// sample-entry FourCC or the protection scheme type โ€” caller's
    /// job to apply that rule).
    #[test]
    fn parse_saiz_constant_size_no_aux_type_key() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version=0, flags=0
        body.push(16u8); // default_sample_info_size = 16
        body.extend_from_slice(&5u32.to_be_bytes()); // sample_count = 5
        let sz = super::parse_saiz(&body).expect("saiz parses");
        assert_eq!(sz.aux_info_type, None);
        assert_eq!(sz.aux_info_type_parameter, None);
        assert_eq!(sz.default_sample_info_size, 16);
        assert_eq!(sz.sample_count, 5);
        assert!(sz.per_sample.is_empty());
    }

    /// ยง8.7.8.2 with `flags & 1 == 1` (aux_info_type key present) and
    /// `default_sample_info_size == 0` (per-sample table populated).
    /// Matches the CENC case where each sample has a distinct IV +
    /// subsample-map record size.
    #[test]
    fn parse_saiz_variable_size_with_aux_type_key() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8, 0, 0, 1]); // version=0, flags=1
        body.extend_from_slice(b"cenc"); // aux_info_type
        body.extend_from_slice(&0u32.to_be_bytes()); // aux_info_type_parameter
        body.push(0u8); // default_sample_info_size = 0 โ†’ per-sample table
        body.extend_from_slice(&3u32.to_be_bytes()); // sample_count = 3
        body.extend_from_slice(&[12u8, 24u8, 36u8]); // sample_info_size[]
        let sz = super::parse_saiz(&body).expect("saiz parses");
        assert_eq!(sz.aux_info_type, Some(*b"cenc"));
        assert_eq!(sz.aux_info_type_parameter, Some(0));
        assert_eq!(sz.default_sample_info_size, 0);
        assert_eq!(sz.sample_count, 3);
        assert_eq!(sz.per_sample, vec![12, 24, 36]);
    }

    /// Truncation: a `sample_count` that names more bytes than the
    /// body actually carries must surface as `Error::invalid` (not a
    /// panic, not a partial vec). This is the same anti-DoS shape the
    /// fuzzer pinned for `subs`.
    #[test]
    fn parse_saiz_truncated_per_sample_returns_err() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version=0, flags=0
        body.push(0u8); // default_sample_info_size = 0 โ†’ per-sample table
        body.extend_from_slice(&100u32.to_be_bytes()); // claims 100 samples
        body.extend_from_slice(&[1u8, 2u8, 3u8]); // only 3 bytes follow
        let err = super::parse_saiz(&body).expect_err("truncation must err");
        assert!(format!("{err}").contains("MP4: saiz"));
    }

    // ISO/IEC 14496-12 ยง8.7.9 โ€” `saio` parsing. Body layout (after the
    // 4-byte FullBox header):
    //
    //   if (flags & 1) { u32 aux_info_type; u32 aux_info_type_parameter }
    //   u32 entry_count
    //   if (version == 0) { u32 offset[entry_count] }
    //   else              { u64 offset[entry_count] }

    /// ยง8.7.9.2 v0 with `flags & 1 == 0` and a single offset entry โ€”
    /// the common DASH/CMAF shape ("all aux-info for the segment is
    /// contiguous", per ยง8.7.9.3 + ยง8.8.14).
    #[test]
    fn parse_saio_v0_single_offset_no_aux_type() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // version=0, flags=0
        body.extend_from_slice(&1u32.to_be_bytes()); // entry_count = 1
        body.extend_from_slice(&0xdead_beefu32.to_be_bytes()); // offset
        let so = super::parse_saio(&body).expect("saio v0 parses");
        assert_eq!(so.version, 0);
        assert_eq!(so.aux_info_type, None);
        assert_eq!(so.aux_info_type_parameter, None);
        assert_eq!(so.offsets, vec![0xdead_beef]);
    }

    /// ยง8.7.9.2 v1 with the aux_info_type key + two 64-bit offsets.
    /// v1 is used when at least one offset exceeds 32 bits (typical
    /// for large mdat content).
    #[test]
    fn parse_saio_v1_two_64bit_offsets_with_aux_type() {
        let mut body = Vec::new();
        body.extend_from_slice(&[1u8, 0, 0, 1]); // version=1, flags=1
        body.extend_from_slice(b"cenc");
        body.extend_from_slice(&7u32.to_be_bytes());
        body.extend_from_slice(&2u32.to_be_bytes()); // entry_count = 2
        body.extend_from_slice(&0x0000_0001_0000_0000u64.to_be_bytes());
        body.extend_from_slice(&0xffff_ffff_ffff_0000u64.to_be_bytes());
        let so = super::parse_saio(&body).expect("saio v1 parses");
        assert_eq!(so.version, 1);
        assert_eq!(so.aux_info_type, Some(*b"cenc"));
        assert_eq!(so.aux_info_type_parameter, Some(7));
        assert_eq!(
            so.offsets,
            vec![0x0000_0001_0000_0000, 0xffff_ffff_ffff_0000]
        );
    }

    /// Truncation: a forged `entry_count` that exceeds the body size
    /// must err rather than panic / wrap. Confirms the anti-DoS budget
    /// cap (per_entry width ร— entry_count) holds.
    #[test]
    fn parse_saio_truncated_offsets_returns_err() {
        let mut body = Vec::new();
        body.extend_from_slice(&[0u8; 4]); // v0, flags=0
        body.extend_from_slice(&100u32.to_be_bytes()); // claims 100 entries
        body.extend_from_slice(&1u32.to_be_bytes()); // only 1 follows
        let err = super::parse_saio(&body).expect_err("truncation must err");
        assert!(format!("{err}").contains("MP4: saio"));
    }

    /// `build_saiz_box` is the byte-exact inverse of `parse_saiz_box`
    /// for a constant-size table without an aux-info-type key.
    #[test]
    fn build_saiz_box_constant_size_round_trips() {
        let record = super::SaizBox {
            aux_info_type: None,
            aux_info_type_parameter: None,
            default_sample_info_size: 8,
            sample_count: 4,
            per_sample: vec![],
        };
        let boxed = super::build_saiz_box(&record).unwrap();
        assert_eq!(&boxed[4..8], b"saiz");
        let s = super::parse_saiz_box(&boxed[8..]).unwrap();
        assert_eq!(s.default_sample_info_size, 8);
        assert_eq!(s.sample_count, 4);
        assert!(s.aux_info_type.is_none());
        assert!(s.per_sample.is_empty());
    }

    /// A variable-size `saiz` with a `(cenc, 7)` aux-info-type key round-
    /// trips, including the per-sample size table.
    #[test]
    fn build_saiz_box_variable_with_aux_type() {
        let record = super::SaizBox {
            aux_info_type: Some(*b"cenc"),
            aux_info_type_parameter: Some(7),
            default_sample_info_size: 0,
            sample_count: 3,
            per_sample: vec![10, 20, 30],
        };
        let boxed = super::build_saiz_box(&record).unwrap();
        let s = super::parse_saiz_box(&boxed[8..]).unwrap();
        assert_eq!(s.aux_info_type, Some(*b"cenc"));
        assert_eq!(s.aux_info_type_parameter, Some(7));
        assert_eq!(s.sample_count, 3);
        assert_eq!(s.per_sample, vec![10, 20, 30]);
    }

    /// Inconsistent `saiz` records are rejected: a constant size with a
    /// non-empty per-sample table, or a variable table whose declared
    /// `sample_count` disagrees with `per_sample.len()`.
    #[test]
    fn build_saiz_box_rejects_inconsistent() {
        let both = super::SaizBox {
            default_sample_info_size: 8,
            per_sample: vec![1],
            ..Default::default()
        };
        assert!(super::build_saiz_box(&both).is_none());
        let count_mismatch = super::SaizBox {
            default_sample_info_size: 0,
            sample_count: 5,
            per_sample: vec![1, 2],
            ..Default::default()
        };
        assert!(super::build_saiz_box(&count_mismatch).is_none());
    }

    /// `build_saio_box` is the byte-exact inverse of `parse_saio_box` for
    /// both v0 (32-bit offsets) and v1 (64-bit offsets, with aux key).
    #[test]
    fn build_saio_box_v0_and_v1_round_trip() {
        let v0 = super::SaioBox {
            version: 0,
            aux_info_type: None,
            aux_info_type_parameter: None,
            offsets: vec![0x1000, 0x2000],
        };
        let boxed = super::build_saio_box(&v0).unwrap();
        assert_eq!(&boxed[4..8], b"saio");
        let s = super::parse_saio_box(&boxed[8..]).unwrap();
        assert_eq!(s.version, 0);
        assert_eq!(s.offsets, vec![0x1000, 0x2000]);

        let v1 = super::SaioBox {
            version: 1,
            aux_info_type: Some(*b"cenc"),
            aux_info_type_parameter: Some(7),
            offsets: vec![0x1_0000_0000, 0xffff_ffff_ffff_0000],
        };
        let boxed = super::build_saio_box(&v1).unwrap();
        let s = super::parse_saio_box(&boxed[8..]).unwrap();
        assert_eq!(s.version, 1);
        assert_eq!(s.aux_info_type, Some(*b"cenc"));
        assert_eq!(s.aux_info_type_parameter, Some(7));
        assert_eq!(s.offsets, vec![0x1_0000_0000, 0xffff_ffff_ffff_0000]);
    }

    /// A v0 `saio` whose offset exceeds the 32-bit field is rejected (the
    /// caller must use version 1); an undefined version is rejected.
    #[test]
    fn build_saio_box_rejects_inconsistent() {
        let overflow = super::SaioBox {
            version: 0,
            aux_info_type: None,
            aux_info_type_parameter: None,
            offsets: vec![0x1_0000_0000],
        };
        assert!(super::build_saio_box(&overflow).is_none());
        let bad_version = super::SaioBox {
            version: 2,
            ..Default::default()
        };
        assert!(super::build_saio_box(&bad_version).is_none());
    }

    /// `parse_stbl` dispatch wires both boxes onto the Track. Build a
    /// minimal `stbl` carrying one `saiz` (constant-size) + one
    /// `saio` (single absolute offset) and verify the Track captures
    /// both with their fields intact.
    #[test]
    fn parse_stbl_collects_saiz_and_saio() {
        // saiz body: flags=0, default_sample_info_size=8, sample_count=4.
        let mut saiz_body = Vec::new();
        saiz_body.extend_from_slice(&[0u8; 4]);
        saiz_body.push(8u8);
        saiz_body.extend_from_slice(&4u32.to_be_bytes());

        // saio body: v0, flags=0, entry_count=1, offset=0x1000.
        let mut saio_body = Vec::new();
        saio_body.extend_from_slice(&[0u8; 4]);
        saio_body.extend_from_slice(&1u32.to_be_bytes());
        saio_body.extend_from_slice(&0x1000u32.to_be_bytes());

        let mut stbl = Vec::new();
        stbl.extend(wrap_box_full_size(b"saiz", &saiz_body));
        stbl.extend(wrap_box_full_size(b"saio", &saio_body));

        let mut t = fresh_track();
        super::parse_stbl(&stbl, &mut t, 1 << 30).unwrap();
        assert_eq!(t.saiz.len(), 1);
        assert_eq!(t.saiz[0].default_sample_info_size, 8);
        assert_eq!(t.saiz[0].sample_count, 4);
        assert_eq!(t.saio.len(), 1);
        assert_eq!(t.saio[0].version, 0);
        assert_eq!(t.saio[0].offsets, vec![0x1000]);
    }

    /// `build_stream_info` surfaces both boxes on `params.options`.
    /// Pair: a `saiz` carrying a `(cenc, 0)` key + variable per-sample
    /// table; a `saio` with the same key + two 64-bit offsets. The
    /// formatted strings follow the documented format.
    #[test]
    fn build_stream_info_surfaces_saiz_and_saio_on_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"encv";
        t.timescale = 1000;
        t.saiz.push(super::SaizBox {
            aux_info_type: Some(*b"cenc"),
            aux_info_type_parameter: Some(0),
            default_sample_info_size: 0,
            sample_count: 3,
            per_sample: vec![18, 18, 26],
        });
        t.saio.push(super::SaioBox {
            version: 1,
            aux_info_type: Some(*b"cenc"),
            aux_info_type_parameter: Some(0),
            offsets: vec![0x1_0000, 0x2_0000],
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("saiz_0").unwrap(),
            "type=cenc param=0 default_size=0 count=3 sizes=18,18,26"
        );
        assert_eq!(
            info.params.options.get("saio_0").unwrap(),
            "v1 type=cenc param=0 offsets=65536,131072"
        );
    }

    /// Absence: a track with no `saiz` / `saio` emits no `saiz_<n>` or
    /// `saio_<n>` keys (mirrors the `no_subs_no_options` shape).
    #[test]
    fn build_stream_info_no_saiz_saio_no_options() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Video;
        t.codec_id_fourcc = *b"avc1";
        t.timescale = 1000;
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(info.params.options.get("saiz_0"), None);
        assert_eq!(info.params.options.get("saio_0"), None);
    }

    /// `saiz` with no aux_info_type key + constant size: surfaced
    /// without the `type=` / `param=` prefix and without `sizes=`.
    #[test]
    fn build_stream_info_surfaces_saiz_constant_no_key() {
        let mut t = fresh_track();
        t.media_type = oxideav_core::MediaType::Audio;
        t.codec_id_fourcc = *b"mp4a";
        t.timescale = 48_000;
        t.saiz.push(super::SaizBox {
            aux_info_type: None,
            aux_info_type_parameter: None,
            default_sample_info_size: 22,
            sample_count: 100,
            per_sample: Vec::new(),
        });
        let info = super::build_stream_info(0, &t, &oxideav_core::NullCodecResolver);
        assert_eq!(
            info.params.options.get("saiz_0").unwrap(),
            "default_size=22 count=100"
        );
    }

    // ----- ยง8.8.2 mehd MovieExtendsHeaderBox parser ---------------------

    #[test]
    fn parse_mehd_v0_reads_32_bit_fragment_duration() {
        // FullBox(version=0, flags=0) + u32 fragment_duration
        let mut body = vec![0u8, 0, 0, 0];
        body.extend_from_slice(&0xDEAD_BEEFu32.to_be_bytes());
        let d = super::parse_mehd(&body).expect("v0 mehd parses");
        assert_eq!(d, 0xDEAD_BEEF);
    }

    #[test]
    fn parse_mehd_v1_reads_64_bit_fragment_duration() {
        // FullBox(version=1, flags=0) + u64 fragment_duration
        let mut body = vec![1u8, 0, 0, 0];
        let dur: u64 = 0x0123_4567_89AB_CDEF;
        body.extend_from_slice(&dur.to_be_bytes());
        let d = super::parse_mehd(&body).expect("v1 mehd parses");
        assert_eq!(d, dur);
    }

    #[test]
    fn parse_mehd_rejects_empty_body() {
        assert!(super::parse_mehd(&[]).is_err());
    }

    #[test]
    fn parse_mehd_rejects_truncated_v0() {
        // version=0, flags=0, only 2 of 4 duration bytes.
        let body = vec![0u8, 0, 0, 0, 0x12, 0x34];
        assert!(super::parse_mehd(&body).is_err());
    }

    #[test]
    fn parse_mehd_rejects_truncated_v1() {
        // version=1, flags=0, only 4 of 8 duration bytes.
        let body = vec![1u8, 0, 0, 0, 0, 0, 0, 0];
        assert!(super::parse_mehd(&body).is_err());
    }

    #[test]
    fn parse_mehd_rejects_unknown_version() {
        // The spec defines only versions 0 and 1; any other value is
        // a forged / corrupt box and must be refused (not best-effort
        // parsed โ€” we don't know what the field layout is).
        let mut body = vec![2u8, 0, 0, 0];
        body.extend_from_slice(&0u64.to_be_bytes());
        assert!(super::parse_mehd(&body).is_err());
    }

    // ----- ISO/IEC 23001-7 ยง8.1.1 โ€” moof-level pssh ---------------------

    /// Build a `moof` body containing one `mfhd` + N `pssh` children
    /// (no `traf` so we exercise just the pssh collection path).
    fn build_moof_body_with_pssh(seq: u32, psshes: &[Vec<u8>]) -> Vec<u8> {
        // mfhd: FullBox(version=0, flags=0) + u32 sequence_number.
        let mut mfhd_body = vec![0u8; 4];
        mfhd_body.extend_from_slice(&seq.to_be_bytes());
        let mfhd = wrap_box(b"mfhd", &mfhd_body);

        let mut body = Vec::new();
        body.extend_from_slice(&mfhd);
        for pssh_body in psshes {
            body.extend_from_slice(&wrap_box(b"pssh", pssh_body));
        }
        body
    }

    /// Wrap `body` with an 8-byte BoxHeader (size + fourcc).
    fn wrap_box(fourcc: &[u8; 4], body: &[u8]) -> Vec<u8> {
        let total = (8 + body.len()) as u32;
        let mut out = Vec::with_capacity(8 + body.len());
        out.extend_from_slice(&total.to_be_bytes());
        out.extend_from_slice(fourcc);
        out.extend_from_slice(body);
        out
    }

    /// Construct a v0 `pssh` body: FullBox + 16-byte SystemID +
    /// u32 DataSize + Data.
    fn pssh_v0_body(system_id: &[u8; 16], data: &[u8]) -> Vec<u8> {
        let mut body = vec![0u8; 4]; // version=0, flags=0
        body.extend_from_slice(system_id);
        body.extend_from_slice(&(data.len() as u32).to_be_bytes());
        body.extend_from_slice(data);
        body
    }

    /// Construct a v1 `pssh` body: FullBox + SystemID + KID_count + KIDs +
    /// DataSize + Data.
    fn pssh_v1_body(system_id: &[u8; 16], kids: &[[u8; 16]], data: &[u8]) -> Vec<u8> {
        let mut body = vec![1u8, 0, 0, 0]; // version=1, flags=0
        body.extend_from_slice(system_id);
        body.extend_from_slice(&(kids.len() as u32).to_be_bytes());
        for k in kids {
            body.extend_from_slice(k);
        }
        body.extend_from_slice(&(data.len() as u32).to_be_bytes());
        body.extend_from_slice(data);
        body
    }

    /// A moof containing one v0 pssh after the mfhd is captured into
    /// `moof_psshes` keyed by the mfhd sequence_number. Mirrors ยง8.1.1
    /// "pssh may be in moov or moof" and ยง8.1.1's reader rule that
    /// each fragment's pssh applies only to that fragment.
    #[test]
    fn parse_moof_collects_one_pssh_keyed_by_mfhd_sequence() {
        let sysid: [u8; 16] = [
            0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6, 0x4a, 0xce, 0xa3, 0xc8, 0x27, 0xdc, 0xd5, 0x1d,
            0x21, 0xed,
        ];
        let data = b"opaque-drm-blob".to_vec();
        let body = build_moof_body_with_pssh(7, &[pssh_v0_body(&sysid, &data)]);
        let moof = super::MoofRecord {
            moof_start: 0,
            body,
        };
        let mut samples: Vec<super::SampleRef> = Vec::new();
        let mut next_dts: Vec<i64> = Vec::new();
        let mut senc: Vec<super::SencRecord> = Vec::new();
        let mut sai: Vec<super::SaiRecord> = Vec::new();
        let mut moof_psshes: Vec<super::MoofPsshRecord> = Vec::new();
        super::parse_moof(
            &moof,
            &[],
            &mut samples,
            &mut next_dts,
            &mut senc,
            &mut sai,
            &mut moof_psshes,
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut (1 << 30),
        )
        .expect("moof walk succeeds");

        assert_eq!(moof_psshes.len(), 1);
        let r = &moof_psshes[0];
        assert_eq!(r.moof_sequence, 7);
        assert_eq!(r.pssh.version, 0);
        assert_eq!(r.pssh.system_id, sysid);
        assert!(r.pssh.kids.is_empty());
        assert_eq!(r.pssh.data, data);
    }

    /// A moof containing two pssh boxes (one v0, one v1 with two
    /// KIDs) โ€” both records share the same `moof_sequence` (= mfhd
    /// sequence_number) and preserve the on-wire walk order. Exercises
    /// the per-fragment "multiple SystemIDs" shape called out in ยง8.1.1
    /// ("A single file MAY be constructed to be playable by multiple
    /// key and digital rights management systems").
    #[test]
    fn parse_moof_collects_two_psshes_v0_and_v1_in_walk_order() {
        let sysid_a: [u8; 16] = [0x11; 16];
        let sysid_b: [u8; 16] = [0x22; 16];
        let kid_x: [u8; 16] = [0xAA; 16];
        let kid_y: [u8; 16] = [0xBB; 16];
        let data_a = b"sys-a-data".to_vec();
        let data_b = b"sys-b-data-longer".to_vec();
        let body = build_moof_body_with_pssh(
            42,
            &[
                pssh_v0_body(&sysid_a, &data_a),
                pssh_v1_body(&sysid_b, &[kid_x, kid_y], &data_b),
            ],
        );
        let moof = super::MoofRecord {
            moof_start: 0,
            body,
        };
        let mut samples: Vec<super::SampleRef> = Vec::new();
        let mut next_dts: Vec<i64> = Vec::new();
        let mut senc: Vec<super::SencRecord> = Vec::new();
        let mut sai: Vec<super::SaiRecord> = Vec::new();
        let mut moof_psshes: Vec<super::MoofPsshRecord> = Vec::new();
        super::parse_moof(
            &moof,
            &[],
            &mut samples,
            &mut next_dts,
            &mut senc,
            &mut sai,
            &mut moof_psshes,
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut (1 << 30),
        )
        .expect("moof walk succeeds");

        assert_eq!(moof_psshes.len(), 2);
        // Same fragment scope on both.
        assert_eq!(moof_psshes[0].moof_sequence, 42);
        assert_eq!(moof_psshes[1].moof_sequence, 42);
        // Walk order preserved.
        assert_eq!(moof_psshes[0].pssh.version, 0);
        assert_eq!(moof_psshes[0].pssh.system_id, sysid_a);
        assert!(moof_psshes[0].pssh.kids.is_empty());
        assert_eq!(moof_psshes[0].pssh.data, data_a);

        assert_eq!(moof_psshes[1].pssh.version, 1);
        assert_eq!(moof_psshes[1].pssh.system_id, sysid_b);
        assert_eq!(moof_psshes[1].pssh.kids, vec![kid_x, kid_y]);
        assert_eq!(moof_psshes[1].pssh.data, data_b);
    }

    /// A pssh that appears before the mfhd inside a moof still
    /// receives the correct `moof_sequence` once mfhd is encountered.
    /// ยง8.8 lists `mfhd` as the first child of `moof` but does not
    /// forbid other top-level boxes preceding it in practice; the
    /// buffered-finalize approach (collect pssh bodies, then key by
    /// the post-walk captured sequence_number) handles either order
    /// without losing fidelity.
    #[test]
    fn parse_moof_pssh_before_mfhd_still_binds_to_sequence() {
        let sysid: [u8; 16] = [0xCC; 16];
        let data = b"pre-mfhd-pssh".to_vec();

        // Build moof body with pssh FIRST, then mfhd.
        let mut mfhd_body = vec![0u8; 4];
        mfhd_body.extend_from_slice(&99u32.to_be_bytes());
        let mfhd = wrap_box(b"mfhd", &mfhd_body);
        let pssh = wrap_box(b"pssh", &pssh_v0_body(&sysid, &data));
        let mut body = Vec::new();
        body.extend_from_slice(&pssh);
        body.extend_from_slice(&mfhd);

        let moof = super::MoofRecord {
            moof_start: 0,
            body,
        };
        let mut samples: Vec<super::SampleRef> = Vec::new();
        let mut next_dts: Vec<i64> = Vec::new();
        let mut senc: Vec<super::SencRecord> = Vec::new();
        let mut sai: Vec<super::SaiRecord> = Vec::new();
        let mut moof_psshes: Vec<super::MoofPsshRecord> = Vec::new();
        super::parse_moof(
            &moof,
            &[],
            &mut samples,
            &mut next_dts,
            &mut senc,
            &mut sai,
            &mut moof_psshes,
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut (1 << 30),
        )
        .expect("moof walk succeeds");

        assert_eq!(moof_psshes.len(), 1);
        assert_eq!(moof_psshes[0].moof_sequence, 99);
        assert_eq!(moof_psshes[0].pssh.system_id, sysid);
        assert_eq!(moof_psshes[0].pssh.data, data);
    }

    /// A malformed pssh inside a moof (here a truncated body) is
    /// dropped without aborting the moof walk โ€” mirrors the moov-level
    /// recovery policy: a forged DRM box must not brick the demuxer
    /// for unrelated playback (or for any non-decrypting workflow).
    #[test]
    fn parse_moof_drops_malformed_pssh_silently() {
        // Truncated pssh body: just FullBox header, no SystemID/data.
        let bad = vec![0u8; 4];
        let body = build_moof_body_with_pssh(3, &[bad]);
        let moof = super::MoofRecord {
            moof_start: 0,
            body,
        };
        let mut samples: Vec<super::SampleRef> = Vec::new();
        let mut next_dts: Vec<i64> = Vec::new();
        let mut senc: Vec<super::SencRecord> = Vec::new();
        let mut sai: Vec<super::SaiRecord> = Vec::new();
        let mut moof_psshes: Vec<super::MoofPsshRecord> = Vec::new();
        super::parse_moof(
            &moof,
            &[],
            &mut samples,
            &mut next_dts,
            &mut senc,
            &mut sai,
            &mut moof_psshes,
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut Vec::new(),
            &mut (1 << 30),
        )
        .expect("walk succeeds despite bad pssh");
        assert!(moof_psshes.is_empty(), "malformed pssh dropped silently");
    }

    /// ยง8.9 โ€” a `traf` carrying a fragment-local `sgpd` + `sbgp` + `csgp`
    /// is collected into a `TrafSampleGroupRecord` keyed by
    /// `(track_idx, moof_sequence)`, with each box's values preserved
    /// verbatim. Exercises the structured-record side that the
    /// integration test (which only sees `Box<dyn Demuxer>`) cannot reach.
    #[test]
    fn parse_traf_collects_fragment_local_sample_groups() {
        // tfhd: FullBox(flags=0) + track_ID = 1. No optional fields.
        let mut tfhd_body = vec![0u8, 0, 0, 0];
        tfhd_body.extend_from_slice(&1u32.to_be_bytes());
        let tfhd = wrap_box(b"tfhd", &tfhd_body);

        // sgpd / sbgp / csgp built via the public sample_groups builders.
        let sgpd =
            crate::sample_groups::build_sgpd(&crate::sample_groups::SampleGroupDescription {
                grouping_type: *b"seig",
                default_sample_description_index: None,
                entries: vec![vec![0x00, 0x01]],
            });
        let sbgp = crate::sample_groups::build_sbgp(&crate::sample_groups::SampleToGroup {
            grouping_type: *b"roll",
            grouping_type_parameter: None,
            entries: vec![(2, 1)],
        });
        let csgp = crate::sample_groups::build_csgp(&crate::sample_groups::CompactSampleToGroup {
            grouping_type: *b"seig",
            grouping_type_parameter: None,
            index_msb_indicates_fragment_local_description: true,
            patterns: vec![crate::sample_groups::CompactSampleToGroupPattern {
                sample_count: 2,
                indices: vec![0x81],
            }],
        });

        let mut traf_body = Vec::new();
        traf_body.extend_from_slice(&tfhd);
        traf_body.extend_from_slice(&sgpd);
        traf_body.extend_from_slice(&sbgp);
        traf_body.extend_from_slice(&csgp);

        let mut track = fresh_track();
        track.track_id = 1;
        let tracks = [track];

        let mut samples: Vec<super::SampleRef> = Vec::new();
        let mut next_dts: Vec<i64> = vec![0];
        let mut senc: Vec<super::SencRecord> = Vec::new();
        let mut sai: Vec<super::SaiRecord> = Vec::new();
        let mut groups: Vec<super::TrafSampleGroupRecord> = Vec::new();

        super::parse_traf(
            &traf_body,
            0,
            &tracks,
            &mut samples,
            &mut next_dts,
            9,
            &mut senc,
            &mut sai,
            &mut groups,
            &mut Vec::new(),
            &mut Vec::new(),
            &mut (1 << 30),
        )
        .expect("traf walk succeeds");

        assert_eq!(groups.len(), 1);
        let r = &groups[0];
        assert_eq!(r.track_idx, 0);
        assert_eq!(r.moof_sequence, 9);
        assert_eq!(r.sgpd.len(), 1);
        assert_eq!(r.sgpd[0].grouping_type, *b"seig");
        assert_eq!(r.sgpd[0].entries, vec![vec![0x00, 0x01]]);
        assert_eq!(r.sbgp.len(), 1);
        assert_eq!(r.sbgp[0].grouping_type, *b"roll");
        assert_eq!(r.sbgp[0].entries, vec![(2, 1)]);
        assert_eq!(r.csgp.len(), 1);
        assert_eq!(r.csgp[0].grouping_type, *b"seig");
        assert!(r.csgp[0].index_msb_indicates_fragment_local_description);
        assert_eq!(r.csgp[0].patterns[0].sample_count, 2);
        assert_eq!(r.csgp[0].patterns[0].indices, vec![0x81]);
        // 0x81 at 8-bit width โ†’ fragment_local, value 1.
        let resolved = r.csgp[0].patterns[0]
            .resolve_index(0, true, r.csgp[0].index_field_bits)
            .unwrap();
        assert!(resolved.fragment_local);
        assert_eq!(resolved.value, 1);
    }

    /// A `traf` with no sample-group boxes contributes no
    /// `TrafSampleGroupRecord`.
    #[test]
    fn parse_traf_without_sample_groups_records_nothing() {
        let mut tfhd_body = vec![0u8, 0, 0, 0];
        tfhd_body.extend_from_slice(&1u32.to_be_bytes());
        let traf_body = wrap_box(b"tfhd", &tfhd_body);

        let mut track = fresh_track();
        track.track_id = 1;
        let tracks = [track];

        let mut samples: Vec<super::SampleRef> = Vec::new();
        let mut next_dts: Vec<i64> = vec![0];
        let mut senc: Vec<super::SencRecord> = Vec::new();
        let mut sai: Vec<super::SaiRecord> = Vec::new();
        let mut groups: Vec<super::TrafSampleGroupRecord> = Vec::new();

        super::parse_traf(
            &traf_body,
            0,
            &tracks,
            &mut samples,
            &mut next_dts,
            1,
            &mut senc,
            &mut sai,
            &mut groups,
            &mut Vec::new(),
            &mut Vec::new(),
            &mut (1 << 30),
        )
        .expect("traf walk succeeds");

        assert!(groups.is_empty());
    }

    // ----- ยง7.1 aux-info run parser (resolve_sai_aux_info) ------------------

    /// Two plain IV-only cells decode into IV entries with no
    /// subsample maps and a cleared UseSubSampleEncryption flag.
    #[test]
    fn parse_aux_info_run_plain_ivs() {
        let buf: Vec<u8> = (0..16).collect();
        let senc = super::parse_aux_info_run(&buf, &[8, 8], 8).expect("parses");
        assert_eq!(senc.flags, 0);
        assert_eq!(senc.samples.len(), 2);
        assert_eq!(
            senc.samples[0].initialization_vector,
            (0..8).collect::<Vec<u8>>()
        );
        assert_eq!(
            senc.samples[1].initialization_vector,
            (8..16).collect::<Vec<u8>>()
        );
        assert!(senc.samples[1].subsamples.is_empty());
    }

    /// A cell larger than the IV carries `u16 count` + 6-byte
    /// subsample entries and sets the flag.
    #[test]
    fn parse_aux_info_run_subsample_cell() {
        let mut buf = vec![0xAA; 8];
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&7u16.to_be_bytes());
        buf.extend_from_slice(&9u32.to_be_bytes());
        let senc = super::parse_aux_info_run(&buf, &[16], 8).expect("parses");
        assert_eq!(senc.flags, 0x0000_0002);
        assert_eq!(senc.samples[0].subsamples.len(), 1);
        assert_eq!(senc.samples[0].subsamples[0].bytes_of_clear_data, 7);
        assert_eq!(senc.samples[0].subsamples[0].bytes_of_protected_data, 9);
    }

    /// Hostile shapes: a cell whose declared size doesn't decompose
    /// into IV + count + 6ยทn, a cell shorter than the IV, and sizes
    /// overrunning the fetched buffer are all rejected whole (no
    /// half-parsed table).
    #[test]
    fn parse_aux_info_run_rejects_malformed_cells() {
        // 12 = IV(8) + count(2) + 2 stray bytes โ†’ not 6-per-entry.
        assert!(super::parse_aux_info_run(&[0u8; 12], &[12], 8).is_none());
        // Cell shorter than the declared IV width.
        assert!(super::parse_aux_info_run(&[0u8; 4], &[4], 8).is_none());
        // Sizes overrun the buffer.
        assert!(super::parse_aux_info_run(&[0u8; 8], &[8, 8], 8).is_none());
        // Declared subsample count overruns the cell.
        let mut buf = vec![0u8; 8];
        buf.extend_from_slice(&9u16.to_be_bytes()); // 9 entries, none present
        assert!(super::parse_aux_info_run(&buf, &[10], 8).is_none());
    }

    /// Constant-IV tracks (IV size 0) may carry zero-size cells โ€”
    /// they decode into empty entries rather than failing.
    #[test]
    fn parse_aux_info_run_zero_size_cells() {
        let senc = super::parse_aux_info_run(&[], &[0, 0], 0).expect("parses");
        assert_eq!(senc.samples.len(), 2);
        assert!(senc.samples[0].initialization_vector.is_empty());
        assert!(senc.samples[0].subsamples.is_empty());
        assert_eq!(senc.flags, 0);
    }

    // ----- ยง8.8.3.1 sample_flags typed accessor -----------------------------

    #[test]
    fn sample_flags_all_zero_decodes_to_sync_sample() {
        // ยง8.8.3.1: when the field is 0 every 2-bit/3-bit/16-bit
        // subfield is "unknown" / zero and the sync-sample bit is
        // clear โ†’ sample IS a sync sample.
        let f = super::SampleFlags::from_u32(0);
        assert_eq!(f.is_leading, 0);
        assert_eq!(f.sample_depends_on, 0);
        assert_eq!(f.sample_is_depended_on, 0);
        assert_eq!(f.sample_has_redundancy, 0);
        assert_eq!(f.sample_padding_value, 0);
        assert!(!f.sample_is_non_sync_sample);
        assert!(f.is_sync_sample());
        assert_eq!(f.sample_degradation_priority, 0);
    }

    #[test]
    fn sample_flags_non_sync_bit_only() {
        // The widely-used "non-sync sample" marker โ€” every other
        // subfield zero, just bit 16 set. Sentinel: 0x0001_0000.
        let f = super::SampleFlags::from_u32(0x0001_0000);
        assert!(f.sample_is_non_sync_sample);
        assert!(!f.is_sync_sample());
        assert_eq!(f.is_leading, 0);
        assert_eq!(f.sample_depends_on, 0);
        assert_eq!(f.sample_degradation_priority, 0);
    }

    #[test]
    fn sample_flags_i_picture_pattern() {
        // ยง8.6.4.3 / ยง8.8.3.1 convention for a typical I-picture
        // (used by every fMP4 producer for the SAP-1 frame of a
        // fragment): is_leading=2 (not leading),
        // sample_depends_on=2 (does not depend on others โ†’
        // I-picture), sample_is_depended_on=1 (others may depend),
        // sample_has_redundancy=0 (unknown), padding=0,
        // non_sync=0, priority=0.
        //
        // Bit packing (ยง8.8.3.1, per-field shifts):
        //   is_leading           << 26 = 2 << 26 = 0x0800_0000
        //   sample_depends_on    << 24 = 2 << 24 = 0x0200_0000
        //   sample_is_depended_on<< 22 = 1 << 22 = 0x0040_0000
        //   everything else                       = 0
        //   total                                 = 0x0A40_0000
        let raw: u32 = 0x0A40_0000;
        let f = super::SampleFlags::from_u32(raw);
        assert_eq!(f.is_leading, 2);
        assert_eq!(f.sample_depends_on, 2);
        assert_eq!(f.sample_is_depended_on, 1);
        assert_eq!(f.sample_has_redundancy, 0);
        assert!(!f.sample_is_non_sync_sample);
        assert!(f.is_sync_sample());
        assert_eq!(f.sample_padding_value, 0);
        assert_eq!(f.sample_degradation_priority, 0);
        // Round-trip โ€” reserved bits 31..28 stay zero per ยง8.8.3.1.
        assert_eq!(f.to_u32(), raw);
    }

    #[test]
    fn sample_flags_b_picture_pattern() {
        // Typical B-picture pattern in fMP4:
        // is_leading=0 (unknown), sample_depends_on=1 (depends on
        // others), sample_is_depended_on=2 (no one depends โ†’ safely
        // disposable), redundancy=0, padding=0, non_sync=1,
        // priority=0.
        //
        // Bit packing (ยง8.8.3.1, per-field shifts):
        //   sample_depends_on    << 24 = 1 << 24 = 0x0100_0000
        //   sample_is_depended_on<< 22 = 2 << 22 = 0x0080_0000
        //   sample_is_non_sync_sample  = bit 16   = 0x0001_0000
        //   total                                 = 0x0181_0000
        let raw: u32 = 0x0181_0000;
        let f = super::SampleFlags::from_u32(raw);
        assert_eq!(f.is_leading, 0);
        assert_eq!(f.sample_depends_on, 1);
        assert_eq!(f.sample_is_depended_on, 2);
        assert_eq!(f.sample_has_redundancy, 0);
        assert!(f.sample_is_non_sync_sample);
        assert!(!f.is_sync_sample());
        assert_eq!(f.sample_padding_value, 0);
        assert_eq!(f.sample_degradation_priority, 0);
        assert_eq!(f.to_u32(), raw);
    }

    #[test]
    fn sample_flags_degradation_priority_field_is_low_16_bits() {
        // Carry only the low 16 bits โ€” exercises the degradation
        // priority decode path independently. 0xBEEF is arbitrary
        // and chosen so the byte boundary is visible.
        let f = super::SampleFlags::from_u32(0x0000_BEEF);
        assert_eq!(f.sample_degradation_priority, 0xBEEF);
        assert_eq!(f.is_leading, 0);
        assert_eq!(f.sample_depends_on, 0);
        assert_eq!(f.sample_is_depended_on, 0);
        assert_eq!(f.sample_has_redundancy, 0);
        assert_eq!(f.sample_padding_value, 0);
        assert!(!f.sample_is_non_sync_sample);
    }

    #[test]
    fn sample_flags_padding_field_round_trips() {
        // sample_padding_value is 3 bits โ€” values 0..=7 are legal.
        // Exercise the full range to catch a shift / mask bug in
        // the bits 19..17 window.
        for pad in 0u8..=7 {
            let f = super::SampleFlags {
                sample_padding_value: pad,
                ..Default::default()
            };
            let round = super::SampleFlags::from_u32(f.to_u32());
            assert_eq!(round.sample_padding_value, pad);
            assert_eq!(round, f);
        }
    }

    #[test]
    fn sample_flags_reserved_bits_ignored_on_decode() {
        // ยง8.8.3.1 fixes bits 31..28 to zero, but we tolerate a
        // producer that sets them (silent-recovery posture matching
        // the rest of the demuxer). A decode then re-encode strips
        // the reserved bits back to zero.
        let raw = 0xF000_0000_u32 | 0x0001_0000_u32; // reserved + non-sync
        let f = super::SampleFlags::from_u32(raw);
        assert!(f.sample_is_non_sync_sample);
        // Re-encoding emits clean reserved=0.
        assert_eq!(f.to_u32(), 0x0001_0000);
    }

    #[test]
    fn sample_flags_all_field_widths_round_trip() {
        // Saturate every field at its maximum legal value to confirm
        // no field bleeds into a neighbour's window.
        let f = super::SampleFlags {
            is_leading: 3,
            sample_depends_on: 3,
            sample_is_depended_on: 3,
            sample_has_redundancy: 3,
            sample_padding_value: 7,
            sample_is_non_sync_sample: true,
            sample_degradation_priority: 0xFFFF,
        };
        let raw = f.to_u32();
        // reserved=0000 then five-pairs-saturated then padding=111
        // then non_sync=1 then priority=0xFFFF
        // = 0000 11 11 11 11 111 1 1111111111111111
        // = 0x0FFF_FFFF
        assert_eq!(raw, 0x0FFF_FFFF);
        assert_eq!(super::SampleFlags::from_u32(raw), f);
    }

    #[test]
    fn parse_sample_flags_public_helper_matches_struct() {
        // Confirms the free-function entry point routes through
        // SampleFlags::from_u32 unchanged.
        let raw = 0x0244_0000_u32;
        assert_eq!(
            super::parse_sample_flags(raw),
            super::SampleFlags::from_u32(raw)
        );
    }

    // ----------------------------------------------------------------
    // ยง8.11 meta item infrastructure (iloc / pitm / iinf / infe / iref)
    // ----------------------------------------------------------------

    /// Wrap `body` in a `[size][fourcc]` box header (32-bit size form).
    fn box_bytes(fourcc: &[u8; 4], body: &[u8]) -> Vec<u8> {
        let total = (8 + body.len()) as u32;
        let mut v = total.to_be_bytes().to_vec();
        v.extend_from_slice(fourcc);
        v.extend_from_slice(body);
        v
    }

    #[test]
    fn parse_iloc_v0_single_extent() {
        // version 0, offset_size=4 length_size=4 base_offset_size=0,
        // item_count=1, item_ID=1, dref=0, extent_count=1,
        // extent_offset=0x1000, extent_length=0x40.
        let mut b = vec![0u8, 0, 0, 0]; // version/flags
        b.push(0x44); // offset_size=4, length_size=4
        b.push(0x00); // base_offset_size=0, reserved=0
        b.extend_from_slice(&1u16.to_be_bytes()); // item_count
        b.extend_from_slice(&1u16.to_be_bytes()); // item_ID
        b.extend_from_slice(&0u16.to_be_bytes()); // data_reference_index
                                                  // base_offset omitted (size 0)
        b.extend_from_slice(&1u16.to_be_bytes()); // extent_count
        b.extend_from_slice(&0x1000u32.to_be_bytes()); // extent_offset
        b.extend_from_slice(&0x40u32.to_be_bytes()); // extent_length
        let iloc = super::parse_iloc_box(&b).expect("iloc parses");
        assert_eq!(iloc.version, 0);
        assert_eq!(iloc.offset_size, 4);
        assert_eq!(iloc.length_size, 4);
        assert_eq!(iloc.base_offset_size, 0);
        assert_eq!(iloc.items.len(), 1);
        let it = &iloc.items[0];
        assert_eq!(it.item_id, 1);
        assert_eq!(it.construction_method, 0);
        assert_eq!(it.base_offset, 0);
        assert_eq!(it.extents.len(), 1);
        assert_eq!(it.extents[0].extent_offset, 0x1000);
        assert_eq!(it.extents[0].extent_length, 0x40);
    }

    #[test]
    fn parse_iloc_v1_construction_method_and_index() {
        // version 1, offset_size=8 length_size=8 base_offset_size=4
        // index_size=4, item_count=1, item_ID=7, construction_method=1
        // (idat), dref=0, base_offset=0x10, extent_count=1,
        // extent_index=2, extent_offset=0x20, extent_length=0x30.
        let mut b = vec![1u8, 0, 0, 0];
        b.push(0x88); // offset_size=8, length_size=8
        b.push(0x44); // base_offset_size=4, index_size=4
        b.extend_from_slice(&1u16.to_be_bytes()); // item_count
        b.extend_from_slice(&7u16.to_be_bytes()); // item_ID
        b.extend_from_slice(&0x0001u16.to_be_bytes()); // reserved(12)+constr(4)=1
        b.extend_from_slice(&0u16.to_be_bytes()); // dref
        b.extend_from_slice(&0x10u32.to_be_bytes()); // base_offset (4)
        b.extend_from_slice(&1u16.to_be_bytes()); // extent_count
        b.extend_from_slice(&2u32.to_be_bytes()); // extent_index (4)
        b.extend_from_slice(&0x20u64.to_be_bytes()); // extent_offset (8)
        b.extend_from_slice(&0x30u64.to_be_bytes()); // extent_length (8)
        let iloc = super::parse_iloc_box(&b).expect("iloc v1 parses");
        assert_eq!(iloc.version, 1);
        assert_eq!(iloc.index_size, 4);
        let it = &iloc.items[0];
        assert_eq!(it.item_id, 7);
        assert_eq!(it.construction_method, 1);
        assert_eq!(it.base_offset, 0x10);
        assert_eq!(it.extents[0].extent_index, 2);
        assert_eq!(it.extents[0].extent_offset, 0x20);
        assert_eq!(it.extents[0].extent_length, 0x30);
    }

    #[test]
    fn parse_iloc_v2_32bit_item_id() {
        // version 2 widens item_count and item_ID to 32 bits.
        let mut b = vec![2u8, 0, 0, 0];
        b.push(0x44); // offset_size=4, length_size=4
        b.push(0x00); // base_offset_size=0, index_size=0
        b.extend_from_slice(&1u32.to_be_bytes()); // item_count (32-bit)
        b.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // item_ID (32-bit)
        b.extend_from_slice(&0x0000u16.to_be_bytes()); // reserved+constr=0
        b.extend_from_slice(&0u16.to_be_bytes()); // dref
        b.extend_from_slice(&1u16.to_be_bytes()); // extent_count
        b.extend_from_slice(&0x55u32.to_be_bytes()); // extent_offset
        b.extend_from_slice(&0x66u32.to_be_bytes()); // extent_length
        let iloc = super::parse_iloc_box(&b).expect("iloc v2 parses");
        assert_eq!(iloc.items[0].item_id, 0x0001_0000);
        assert_eq!(iloc.items[0].extents[0].extent_offset, 0x55);
    }

    #[test]
    fn parse_iloc_rejects_bad_field_width() {
        // offset_size=5 is not in {0,4,8} โ†’ reject.
        let mut b = vec![0u8, 0, 0, 0];
        b.push(0x54); // offset_size=5 (invalid), length_size=4
        b.push(0x00);
        b.extend_from_slice(&0u16.to_be_bytes());
        assert!(super::parse_iloc_box(&b).is_none());
    }

    #[test]
    fn parse_pitm_v0_and_v1() {
        let mut v0 = vec![0u8, 0, 0, 0];
        v0.extend_from_slice(&0x1234u16.to_be_bytes());
        assert_eq!(super::parse_pitm_box(&v0), Some(0x1234));
        let mut v1 = vec![1u8, 0, 0, 0];
        v1.extend_from_slice(&0x0001_2345u32.to_be_bytes());
        assert_eq!(super::parse_pitm_box(&v1), Some(0x0001_2345));
    }

    #[test]
    fn parse_iinf_v0_with_infe_v2() {
        // iinf v0: entry_count(16)=1 then one infe v2 box.
        // infe v2: item_ID(16)=1, prot_index(16)=0, item_type="hvc1",
        // item_name="image\0".
        let mut infe_body = vec![2u8, 0, 0, 0];
        infe_body.extend_from_slice(&1u16.to_be_bytes());
        infe_body.extend_from_slice(&0u16.to_be_bytes());
        infe_body.extend_from_slice(b"hvc1");
        infe_body.extend_from_slice(b"image\0");
        let infe = box_bytes(b"infe", &infe_body);

        let mut iinf_body = vec![0u8, 0, 0, 0];
        iinf_body.extend_from_slice(&1u16.to_be_bytes()); // entry_count
        iinf_body.extend_from_slice(&infe);

        let iinf = super::parse_iinf_box(&iinf_body).expect("iinf parses");
        assert_eq!(iinf.entries.len(), 1);
        let e = &iinf.entries[0];
        assert_eq!(e.item_id, 1);
        assert_eq!(&e.item_type, b"hvc1");
        assert_eq!(e.item_name, "image");
        assert_eq!(e.version, 2);
    }

    #[test]
    fn parse_infe_v0_name_and_content_type() {
        // v0/v1 shape: item_ID(16), prot_index(16), item_name\0,
        // content_type\0, content_encoding\0(optional).
        let mut body = vec![0u8, 0, 0, 0];
        body.extend_from_slice(&5u16.to_be_bytes());
        body.extend_from_slice(&0u16.to_be_bytes());
        body.extend_from_slice(b"thumb\0");
        body.extend_from_slice(b"image/jpeg\0");
        // wrap + reparse via iinf to exercise parse_infe through public path
        let infe = box_bytes(b"infe", &body);
        let mut iinf_body = vec![0u8, 0, 0, 0];
        iinf_body.extend_from_slice(&1u16.to_be_bytes());
        iinf_body.extend_from_slice(&infe);
        let iinf = super::parse_iinf_box(&iinf_body).unwrap();
        let e = &iinf.entries[0];
        assert_eq!(e.item_id, 5);
        assert_eq!(e.item_name, "thumb");
        assert_eq!(e.content_type, "image/jpeg");
        assert_eq!(e.version, 0);
        assert_eq!(&e.item_type, &[0u8; 4]);
    }

    #[test]
    fn parse_iref_v0_groups() {
        // iref v0: one dimg ref from item 1 to items {2,3}, one thmb
        // ref from item 4 to item 1.
        let mut dimg = 1u16.to_be_bytes().to_vec();
        dimg.extend_from_slice(&2u16.to_be_bytes()); // ref_count
        dimg.extend_from_slice(&2u16.to_be_bytes());
        dimg.extend_from_slice(&3u16.to_be_bytes());
        let dimg = box_bytes(b"dimg", &dimg);
        let mut thmb = 4u16.to_be_bytes().to_vec();
        thmb.extend_from_slice(&1u16.to_be_bytes());
        thmb.extend_from_slice(&1u16.to_be_bytes());
        let thmb = box_bytes(b"thmb", &thmb);
        let mut body = vec![0u8, 0, 0, 0]; // version 0
        body.extend_from_slice(&dimg);
        body.extend_from_slice(&thmb);
        let iref = super::parse_iref_box(&body).expect("iref parses");
        assert_eq!(iref.version, 0);
        assert_eq!(iref.references.len(), 2);
        assert_eq!(&iref.references[0].reference_type, b"dimg");
        assert_eq!(iref.references[0].from_item_id, 1);
        assert_eq!(iref.references[0].to_item_ids, vec![2, 3]);
        assert_eq!(&iref.references[1].reference_type, b"thmb");
        assert_eq!(iref.references[1].from_item_id, 4);
        assert_eq!(iref.references[1].to_item_ids, vec![1]);
    }

    #[test]
    fn parse_iref_v1_32bit_ids() {
        let mut g = 0x0001_0000u32.to_be_bytes().to_vec();
        g.extend_from_slice(&1u16.to_be_bytes()); // ref_count
        g.extend_from_slice(&0x0002_0000u32.to_be_bytes());
        let g = box_bytes(b"cdsc", &g);
        let mut body = vec![1u8, 0, 0, 0]; // version 1
        body.extend_from_slice(&g);
        let iref = super::parse_iref_box(&body).unwrap();
        assert_eq!(iref.version, 1);
        assert_eq!(iref.references[0].from_item_id, 0x0001_0000);
        assert_eq!(iref.references[0].to_item_ids, vec![0x0002_0000]);
    }

    #[test]
    fn parse_meta_items_full_heif_meta() {
        // Assemble a meta body with hdlr(pict) + pitm + iloc + iinf + iref.
        let mut hdlr = vec![0u8, 0, 0, 0]; // version/flags
        hdlr.extend_from_slice(&[0, 0, 0, 0]); // pre_defined
        hdlr.extend_from_slice(b"pict"); // handler_type
        hdlr.extend_from_slice(&[0u8; 12]); // reserved
        hdlr.push(0); // name terminator
        let hdlr = box_bytes(b"hdlr", &hdlr);

        let mut pitm = vec![0u8, 0, 0, 0];
        pitm.extend_from_slice(&1u16.to_be_bytes());
        let pitm = box_bytes(b"pitm", &pitm);

        let mut iloc_body = vec![0u8, 0, 0, 0];
        iloc_body.push(0x44);
        iloc_body.push(0x00);
        iloc_body.extend_from_slice(&1u16.to_be_bytes()); // item_count
        iloc_body.extend_from_slice(&1u16.to_be_bytes()); // item_ID
        iloc_body.extend_from_slice(&0u16.to_be_bytes()); // dref
        iloc_body.extend_from_slice(&1u16.to_be_bytes()); // extent_count
        iloc_body.extend_from_slice(&0x100u32.to_be_bytes());
        iloc_body.extend_from_slice(&0x10u32.to_be_bytes());
        let iloc = box_bytes(b"iloc", &iloc_body);

        let mut infe_body = vec![2u8, 0, 0, 0];
        infe_body.extend_from_slice(&1u16.to_be_bytes());
        infe_body.extend_from_slice(&0u16.to_be_bytes());
        infe_body.extend_from_slice(b"hvc1");
        infe_body.extend_from_slice(b"\0");
        let infe = box_bytes(b"infe", &infe_body);
        let mut iinf_body = vec![0u8, 0, 0, 0];
        iinf_body.extend_from_slice(&1u16.to_be_bytes());
        iinf_body.extend_from_slice(&infe);
        let iinf = box_bytes(b"iinf", &iinf_body);

        let mut dimg = 1u16.to_be_bytes().to_vec();
        dimg.extend_from_slice(&1u16.to_be_bytes());
        dimg.extend_from_slice(&2u16.to_be_bytes());
        let dimg = box_bytes(b"dimg", &dimg);
        let mut iref_body = vec![0u8, 0, 0, 0];
        iref_body.extend_from_slice(&dimg);
        let iref = box_bytes(b"iref", &iref_body);

        // meta body = version/flags(4) + children.
        let mut meta = vec![0u8, 0, 0, 0];
        meta.extend_from_slice(&hdlr);
        meta.extend_from_slice(&pitm);
        meta.extend_from_slice(&iloc);
        meta.extend_from_slice(&iinf);
        meta.extend_from_slice(&iref);

        let mi = super::parse_meta_items(&meta);
        assert_eq!(&mi.handler_type, b"pict");
        assert_eq!(mi.primary_item_id, Some(1));
        assert_eq!(mi.iloc.as_ref().unwrap().items.len(), 1);
        assert_eq!(mi.iinf.as_ref().unwrap().entries[0].item_name, "");
        assert_eq!(&mi.iinf.as_ref().unwrap().entries[0].item_type, b"hvc1");
        assert_eq!(mi.iref.as_ref().unwrap().references.len(), 1);
        assert!(!mi.is_empty());
    }

    #[test]
    fn meta_walk_surfaces_fiin_fd_item_info() {
        use crate::fd::{FiinBox, FparBox, PartitionEntry};

        // hdlr(`fdel`) + a fiin built via the fd builders.
        let mut hdlr = vec![0u8, 0, 0, 0];
        hdlr.extend_from_slice(&[0, 0, 0, 0]);
        hdlr.extend_from_slice(b"fdel");
        hdlr.extend_from_slice(&[0u8; 12]);
        hdlr.push(0);
        let hdlr = box_bytes(b"hdlr", &hdlr);

        let fiin = FiinBox {
            partition_entries: vec![PartitionEntry {
                fpar: Some(FparBox {
                    version: 0,
                    item_id: 1,
                    packet_payload_size: 1400,
                    fec_encoding_id: 0,
                    fec_instance_id: 0,
                    max_source_block_length: 16,
                    encoding_symbol_length: 1024,
                    max_number_of_encoding_symbols: 16,
                    scheme_specific_info: String::new(),
                    entries: vec![],
                }),
                fecr: None,
                fire: None,
            }],
            session_info: None,
            group_id_to_name: None,
        };
        let fiin_bytes = crate::fd::build_fiin_box(&fiin);

        let mut meta = vec![0u8, 0, 0, 0];
        meta.extend_from_slice(&hdlr);
        meta.extend_from_slice(&fiin_bytes);

        let mi = super::parse_meta_items(&meta);
        assert_eq!(&mi.handler_type, b"fdel");
        let parsed = mi.fiin.as_ref().expect("fiin parsed");
        assert_eq!(parsed.partition_entries.len(), 1);
        assert_eq!(parsed, &fiin);
        assert!(!mi.is_empty());

        // The flat metadata surface carries the partition count.
        let mut kv = Vec::new();
        super::surface_meta_items(&mi, &mut kv);
        assert!(kv
            .iter()
            .any(|(k, v)| k == "meta_fiin_partitions" && v == "1"));
    }

    #[test]
    fn mere_round_trips() {
        let r = super::MereRelation {
            first_metabox_handler_type: *b"mp7t",
            second_metabox_handler_type: *b"mdir",
            metabox_relation: 5,
        };
        let bytes = super::build_mere_box(&r);
        // [size][mere] header then 13-byte body.
        assert_eq!(&bytes[4..8], b"mere");
        let body = &bytes[8..];
        assert_eq!(body.len(), 13);
        assert_eq!(super::parse_mere_box(body).unwrap(), r);
    }

    #[test]
    fn mere_truncated_rejected() {
        // FullBox preamble + only one handler type โ€” short of 13 bytes.
        assert!(super::parse_mere_box(&[0, 0, 0, 0, b'a', b'b', b'c', b'd']).is_none());
    }

    #[test]
    fn meco_walk_collects_metas_and_relations() {
        // meco body = two additional meta boxes (distinct handler types)
        // + one mere relation between them.
        fn meta_with_handler(h: &[u8; 4]) -> Vec<u8> {
            let mut hdlr = vec![0u8, 0, 0, 0];
            hdlr.extend_from_slice(&[0, 0, 0, 0]);
            hdlr.extend_from_slice(h);
            hdlr.extend_from_slice(&[0u8; 12]);
            hdlr.push(0);
            let hdlr = box_bytes(b"hdlr", &hdlr);
            let mut meta = vec![0u8, 0, 0, 0];
            meta.extend_from_slice(&hdlr);
            box_bytes(b"meta", &meta)
        }
        let meta_a = meta_with_handler(b"mp7t");
        let meta_b = meta_with_handler(b"mdir");
        let mere = super::build_mere_box(&super::MereRelation {
            first_metabox_handler_type: *b"mp7t",
            second_metabox_handler_type: *b"mdir",
            metabox_relation: 3,
        });

        let mut meco_body = Vec::new();
        meco_body.extend_from_slice(&meta_a);
        meco_body.extend_from_slice(&meta_b);
        meco_body.extend_from_slice(&mere);

        let meco = super::parse_meco_box(&meco_body);
        assert!(!meco.is_empty());
        assert_eq!(meco.metas.len(), 2);
        assert_eq!(&meco.metas[0].handler_type, b"mp7t");
        assert_eq!(&meco.metas[1].handler_type, b"mdir");
        assert_eq!(meco.relations.len(), 1);
        assert_eq!(meco.relations[0].metabox_relation, 3);
        assert_eq!(&meco.relations[0].first_metabox_handler_type, b"mp7t");
    }

    #[test]
    fn meco_empty_body_is_empty() {
        assert!(super::parse_meco_box(&[]).is_empty());
    }

    #[test]
    fn meta_items_idat_resolution_and_lookups() {
        // meta with iloc (method 1 / idat) for item 1 (offset 4, len 6)
        // + idat box of 16 bytes + iinf naming item 1.
        let idat_payload: Vec<u8> = (0u8..16).collect();
        let idat = box_bytes(b"idat", &idat_payload);

        let mut iloc = vec![1u8, 0, 0, 0]; // version 1 (needs constr method)
        iloc.push(0x44); // offset_size=4, length_size=4
        iloc.push(0x00); // base_offset_size=0, index_size=0
        iloc.extend_from_slice(&1u16.to_be_bytes()); // item_count
        iloc.extend_from_slice(&1u16.to_be_bytes()); // item_ID
        iloc.extend_from_slice(&0x0001u16.to_be_bytes()); // reserved+constr=1
        iloc.extend_from_slice(&0u16.to_be_bytes()); // dref
        iloc.extend_from_slice(&1u16.to_be_bytes()); // extent_count
        iloc.extend_from_slice(&4u32.to_be_bytes()); // extent_offset
        iloc.extend_from_slice(&6u32.to_be_bytes()); // extent_length
        let iloc = box_bytes(b"iloc", &iloc);

        let mut infe = vec![2u8, 0, 0, 0];
        infe.extend_from_slice(&1u16.to_be_bytes());
        infe.extend_from_slice(&0u16.to_be_bytes());
        infe.extend_from_slice(b"Exif");
        infe.extend_from_slice(b"exif\0");
        let infe = box_bytes(b"infe", &infe);
        let mut iinf = vec![0u8, 0, 0, 0];
        iinf.extend_from_slice(&1u16.to_be_bytes());
        iinf.extend_from_slice(&infe);
        let iinf = box_bytes(b"iinf", &iinf);

        let mut meta = vec![0u8, 0, 0, 0];
        meta.extend_from_slice(&iloc);
        meta.extend_from_slice(&iinf);
        meta.extend_from_slice(&idat);
        let mi = super::parse_meta_items(&meta);

        assert_eq!(mi.idat.len(), 16);
        // item_data_from_idat concatenates the extent (offset 4, len 6).
        assert_eq!(mi.item_data_from_idat(1), Some(vec![4u8, 5, 6, 7, 8, 9]));
        // byte ranges reflect base_offset(0) + extent_offset(4).
        let ranges = mi.item_byte_ranges(1).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges[0].offset, 4);
        assert_eq!(ranges[0].length, 6);
        // lookups by ID.
        assert_eq!(mi.iloc_item(1).unwrap().construction_method, 1);
        assert_eq!(mi.item_info(1).unwrap().item_name, "exif");
        assert!(mi.iloc_item(99).is_none());
        // a file-method item would not resolve via idat.
        assert!(mi.item_data_from_idat(99).is_none());
    }

    #[test]
    fn meta_items_idat_overrun_rejected() {
        // extent runs past the 4-byte idat โ†’ resolution returns None.
        let idat = box_bytes(b"idat", &[1u8, 2, 3, 4]);
        let mut iloc = vec![1u8, 0, 0, 0];
        iloc.push(0x44);
        iloc.push(0x00);
        iloc.extend_from_slice(&1u16.to_be_bytes());
        iloc.extend_from_slice(&1u16.to_be_bytes());
        iloc.extend_from_slice(&0x0001u16.to_be_bytes()); // constr=1
        iloc.extend_from_slice(&0u16.to_be_bytes());
        iloc.extend_from_slice(&1u16.to_be_bytes());
        iloc.extend_from_slice(&2u32.to_be_bytes()); // offset 2
        iloc.extend_from_slice(&10u32.to_be_bytes()); // length 10 (overruns)
        let iloc = box_bytes(b"iloc", &iloc);
        let mut meta = vec![0u8, 0, 0, 0];
        meta.extend_from_slice(&iloc);
        meta.extend_from_slice(&idat);
        let mi = super::parse_meta_items(&meta);
        assert!(mi.item_data_from_idat(1).is_none());
    }

    // ---- builders: byte-exact round-trips ----

    /// Strip the 8-byte `[size][fourcc]` header from a built box,
    /// returning its body (what the `parse_*` entry points consume).
    fn box_body(built: &[u8]) -> &[u8] {
        &built[8..]
    }

    #[test]
    fn build_iloc_round_trips_v0_v1_v2() {
        let cases = [
            super::IlocBox {
                version: 0,
                offset_size: 4,
                length_size: 4,
                base_offset_size: 0,
                index_size: 0,
                items: vec![super::IlocItem {
                    item_id: 3,
                    construction_method: 0,
                    data_reference_index: 0,
                    base_offset: 0,
                    extents: vec![super::IlocExtent {
                        extent_index: 0,
                        extent_offset: 0x1234,
                        extent_length: 0x56,
                    }],
                }],
            },
            super::IlocBox {
                version: 1,
                offset_size: 8,
                length_size: 8,
                base_offset_size: 4,
                index_size: 4,
                items: vec![super::IlocItem {
                    item_id: 9,
                    construction_method: 1,
                    data_reference_index: 2,
                    base_offset: 0x40,
                    extents: vec![super::IlocExtent {
                        extent_index: 5,
                        extent_offset: 0x9999,
                        extent_length: 0x1000,
                    }],
                }],
            },
            super::IlocBox {
                version: 2,
                offset_size: 4,
                length_size: 4,
                base_offset_size: 0,
                index_size: 0,
                items: vec![super::IlocItem {
                    item_id: 0x0010_0000,
                    construction_method: 0,
                    data_reference_index: 0,
                    base_offset: 0,
                    extents: vec![super::IlocExtent {
                        extent_index: 0,
                        extent_offset: 7,
                        extent_length: 8,
                    }],
                }],
            },
        ];
        for c in cases {
            let built = super::build_iloc_box(&c).expect("build");
            let parsed = super::parse_iloc_box(box_body(&built)).expect("parse");
            assert_eq!(parsed, c, "iloc v{} round-trip", c.version);
        }
    }

    #[test]
    fn build_iloc_rejects_inconsistent_records() {
        // v0 with a non-zero construction_method cannot round-trip.
        let bad = super::IlocBox {
            version: 0,
            offset_size: 4,
            length_size: 4,
            base_offset_size: 0,
            index_size: 0,
            items: vec![super::IlocItem {
                item_id: 1,
                construction_method: 1, // illegal for v0
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![],
            }],
        };
        assert!(super::build_iloc_box(&bad).is_none());
        // v0 with index_size != 0 (reserved nibble) is rejected.
        let bad2 = super::IlocBox {
            version: 0,
            offset_size: 4,
            length_size: 4,
            base_offset_size: 0,
            index_size: 4,
            items: vec![],
        };
        assert!(super::build_iloc_box(&bad2).is_none());
    }

    #[test]
    fn build_pitm_round_trips() {
        let built = super::build_pitm_box(42);
        assert_eq!(super::parse_pitm_box(box_body(&built)), Some(42));
        let built = super::build_pitm_box(0x0010_0000);
        assert_eq!(super::parse_pitm_box(box_body(&built)), Some(0x0010_0000));
    }

    #[test]
    fn build_iinf_round_trips_mixed_versions() {
        let b = super::IinfBox {
            entries: vec![
                super::ItemInfoEntry {
                    item_id: 1,
                    protection_index: 0,
                    item_type: *b"hvc1",
                    item_name: "primary".to_string(),
                    content_type: String::new(),
                    content_encoding: String::new(),
                    version: 2,
                },
                super::ItemInfoEntry {
                    item_id: 2,
                    protection_index: 0,
                    item_type: *b"mime",
                    item_name: "meta".to_string(),
                    content_type: "application/rdf+xml".to_string(),
                    content_encoding: String::new(),
                    version: 2,
                },
                super::ItemInfoEntry {
                    item_id: 3,
                    protection_index: 0,
                    item_type: [0; 4],
                    item_name: "legacy".to_string(),
                    content_type: "image/jpeg".to_string(),
                    content_encoding: String::new(),
                    version: 0,
                },
            ],
        };
        let built = super::build_iinf_box(&b).expect("build");
        let parsed = super::parse_iinf_box(box_body(&built)).expect("parse");
        assert_eq!(parsed, b);
    }

    #[test]
    fn build_iref_round_trips_v0_v1() {
        let v0 = super::IrefBox {
            version: 0,
            references: vec![
                super::ItemReference {
                    reference_type: *b"dimg",
                    from_item_id: 1,
                    to_item_ids: vec![2, 3, 4],
                },
                super::ItemReference {
                    reference_type: *b"thmb",
                    from_item_id: 5,
                    to_item_ids: vec![1],
                },
            ],
        };
        let built = super::build_iref_box(&v0).unwrap();
        assert_eq!(super::parse_iref_box(box_body(&built)), Some(v0));

        let v1 = super::IrefBox {
            version: 1,
            references: vec![super::ItemReference {
                reference_type: *b"cdsc",
                from_item_id: 0x0001_0000,
                to_item_ids: vec![0x0002_0000],
            }],
        };
        let built = super::build_iref_box(&v1).unwrap();
        assert_eq!(super::parse_iref_box(box_body(&built)), Some(v1));
    }

    #[test]
    fn build_idat_round_trips_through_meta_walk() {
        // Assemble a meta with built iloc(method1) + built idat and
        // confirm item_data_from_idat reads back the original bytes.
        let payload: Vec<u8> = (10u8..30).collect();
        let idat = super::build_idat_box(&payload);
        let iloc = super::build_iloc_box(&super::IlocBox {
            version: 1,
            offset_size: 4,
            length_size: 4,
            base_offset_size: 0,
            index_size: 0,
            items: vec![super::IlocItem {
                item_id: 1,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![super::IlocExtent {
                    extent_index: 0,
                    extent_offset: 3,
                    extent_length: 5,
                }],
            }],
        })
        .unwrap();
        let mut meta = vec![0u8, 0, 0, 0];
        meta.extend_from_slice(&iloc);
        meta.extend_from_slice(&idat);
        let mi = super::parse_meta_items(&meta);
        assert_eq!(mi.item_data_from_idat(1), Some(payload[3..8].to_vec()));
    }

    #[test]
    fn parse_meta_items_plain_itunes_is_empty() {
        // A meta with just hdlr(mdir) + ilst carries no ยง8.11 items.
        let mut hdlr = vec![0u8, 0, 0, 0];
        hdlr.extend_from_slice(&[0, 0, 0, 0]);
        hdlr.extend_from_slice(b"mdir");
        hdlr.extend_from_slice(&[0u8; 12]);
        hdlr.push(0);
        let hdlr = box_bytes(b"hdlr", &hdlr);
        let ilst = box_bytes(b"ilst", &[]);
        let mut meta = vec![0u8, 0, 0, 0];
        meta.extend_from_slice(&hdlr);
        meta.extend_from_slice(&ilst);
        let mi = super::parse_meta_items(&meta);
        assert_eq!(&mi.handler_type, b"mdir");
        assert!(mi.is_empty());
    }
}