zenavif-parse 0.5.2

AVIF container parser with zero-copy AvifParser API, grid images, animation, and resource limits. Fork of avif-parse.
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
#![deny(unsafe_code)]
#![allow(clippy::missing_safety_doc)]
//! AVIF container parser (ISOBMFF/MIAF demuxer).
//!
//! Extracts AV1 payloads, alpha channels, grid tiles, animation frames,
//! and container metadata from AVIF files. Written in safe Rust with
//! fallible allocations throughout.
//!
//! The primary API is [`AvifParser`], which performs zero-copy parsing by
//! recording byte offsets and resolving data on demand.
//!
//! A legacy eager API ([`read_avif`]) is available behind the `eager` feature flag.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use arrayvec::ArrayVec;
use log::{debug, warn};

use bitreader::BitReader;
use byteorder::ReadBytesExt;
use fallible_collections::{TryClone, TryReserveError};
use std::borrow::Cow;
use std::convert::{TryFrom, TryInto as _};

use std::io::{Read, Take};
use std::num::NonZeroU32;
use std::ops::{Range, RangeFrom};

mod obu;

mod boxes;
use crate::boxes::{BoxType, FourCC};

/// This crate can be used from C.
#[cfg(feature = "c_api")]
pub mod c_api;

pub use enough::{Stop, StopReason, Unstoppable};

// Arbitrary buffer size limit used for raw read_bufs on a box.
// const BUF_SIZE_LIMIT: u64 = 10 * 1024 * 1024;

/// A trait to indicate a type can be infallibly converted to `u64`.
/// This should only be implemented for infallible conversions, so only unsigned types are valid.
trait ToU64 {
    fn to_u64(self) -> u64;
}

/// Infallible: usize always fits in u64.
impl ToU64 for usize {
    fn to_u64(self) -> u64 {
        const _: () = assert!(std::mem::size_of::<usize>() <= std::mem::size_of::<u64>());
        self as u64
    }
}

/// A trait to indicate a type can be infallibly converted to `usize`.
/// This should only be implemented for infallible conversions, so only unsigned types are valid.
pub(crate) trait ToUsize {
    fn to_usize(self) -> usize;
}

/// Infallible widening cast: `$from_type` always fits in `usize`.
macro_rules! impl_to_usize_from {
    ( $from_type:ty ) => {
        impl ToUsize for $from_type {
            fn to_usize(self) -> usize {
                const _: () = assert!(std::mem::size_of::<$from_type>() <= std::mem::size_of::<usize>());
                self as usize
            }
        }
    };
}

impl_to_usize_from!(u8);
impl_to_usize_from!(u16);
impl_to_usize_from!(u32);

/// Indicate the current offset (i.e., bytes already read) in a reader
trait Offset {
    fn offset(&self) -> u64;
}

/// Wraps a reader to track the current offset
struct OffsetReader<'a, T> {
    reader: &'a mut T,
    offset: u64,
}

impl<'a, T> OffsetReader<'a, T> {
    fn new(reader: &'a mut T) -> Self {
        Self { reader, offset: 0 }
    }
}

impl<T> Offset for OffsetReader<'_, T> {
    fn offset(&self) -> u64 {
        self.offset
    }
}

impl<T: Read> Read for OffsetReader<'_, T> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let bytes_read = self.reader.read(buf)?;
        self.offset = self
            .offset
            .checked_add(bytes_read.to_u64())
            .ok_or(Error::Unsupported("total bytes read too large for offset type"))?;
        Ok(bytes_read)
    }
}

pub(crate) type TryVec<T> = fallible_collections::TryVec<T>;
pub(crate) type TryString = fallible_collections::TryVec<u8>;

// To ensure we don't use stdlib allocating types by accident
#[allow(dead_code)]
struct Vec;
#[allow(dead_code)]
struct Box;
#[allow(dead_code)]
struct HashMap;
#[allow(dead_code)]
struct String;

/// Describes parser failures.
///
/// This enum wraps the standard `io::Error` type, unified with
/// our own parser error states and those of crates we use.
#[derive(Debug)]
pub enum Error {
    /// Parse error caused by corrupt or malformed data.
    InvalidData(&'static str),
    /// Parse error caused by limited parser support rather than invalid data.
    Unsupported(&'static str),
    /// Reflect `std::io::ErrorKind::UnexpectedEof` for short data.
    UnexpectedEOF,
    /// Propagate underlying errors from `std::io`.
    Io(std::io::Error),
    /// `read_mp4` terminated without detecting a moov box.
    NoMoov,
    /// Out of memory
    OutOfMemory,
    /// Resource limit exceeded during parsing
    ResourceLimitExceeded(&'static str),
    /// Operation was stopped/cancelled
    Stopped(enough::StopReason),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let msg = match self {
            Self::InvalidData(s) | Self::Unsupported(s) | Self::ResourceLimitExceeded(s) => s,
            Self::UnexpectedEOF => "EOF",
            Self::Io(err) => return err.fmt(f),
            Self::NoMoov => "Missing Moov box",
            Self::OutOfMemory => "OOM",
            Self::Stopped(reason) => return write!(f, "Stopped: {}", reason),
        };
        f.write_str(msg)
    }
}

impl std::error::Error for Error {}

impl From<bitreader::BitReaderError> for Error {
    #[cold]
    #[cfg_attr(debug_assertions, track_caller)]
    fn from(err: bitreader::BitReaderError) -> Self {
        log::warn!("bitreader: {err}");
        Self::InvalidData("truncated bits")
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        match err.kind() {
            std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEOF,
            _ => Self::Io(err),
        }
    }
}

impl From<std::string::FromUtf8Error> for Error {
    fn from(_: std::string::FromUtf8Error) -> Self {
        Self::InvalidData("invalid utf8")
    }
}

impl From<std::num::TryFromIntError> for Error {
    fn from(_: std::num::TryFromIntError) -> Self {
        Self::Unsupported("integer conversion failed")
    }
}

impl From<Error> for std::io::Error {
    fn from(err: Error) -> Self {
        let kind = match err {
            Error::InvalidData(_) => std::io::ErrorKind::InvalidData,
            Error::UnexpectedEOF => std::io::ErrorKind::UnexpectedEof,
            Error::Io(io_err) => return io_err,
            _ => std::io::ErrorKind::Other,
        };
        Self::new(kind, err)
    }
}

impl From<TryReserveError> for Error {
    fn from(_: TryReserveError) -> Self {
        Self::OutOfMemory
    }
}

impl From<enough::StopReason> for Error {
    fn from(reason: enough::StopReason) -> Self {
        Self::Stopped(reason)
    }
}

/// Result shorthand using our Error enum.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Basic ISO box structure.
///
/// mp4 files are a sequence of possibly-nested 'box' structures.  Each box
/// begins with a header describing the length of the box's data and a
/// four-byte box type which identifies the type of the box. Together these
/// are enough to interpret the contents of that section of the file.
///
/// See ISO 14496-12:2015 § 4.2
#[derive(Debug, Clone, Copy)]
struct BoxHeader {
    /// Box type.
    name: BoxType,
    /// Size of the box in bytes.
    size: u64,
    /// Offset to the start of the contained data (or header size).
    offset: u64,
    /// Uuid for extended type.
    #[allow(unused)]
    uuid: Option<[u8; 16]>,
}

impl BoxHeader {
    /// 4-byte size + 4-byte type
    const MIN_SIZE: u64 = 8;
    /// 4-byte size + 4-byte type + 16-byte size
    const MIN_LARGE_SIZE: u64 = 16;
}

/// File type box 'ftyp'.
#[derive(Debug)]
#[allow(unused)]
struct FileTypeBox {
    major_brand: FourCC,
    minor_version: u32,
    compatible_brands: TryVec<FourCC>,
}

// Handler reference box 'hdlr'
#[derive(Debug)]
#[allow(unused)]
struct HandlerBox {
    handler_type: FourCC,
}

/// AV1 codec configuration from the `av1C` property box.
///
/// Contains the AV1 codec parameters as signaled in the container.
/// See AV1-ISOBMFF § 2.3.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AV1Config {
    /// AV1 seq_profile (0=Main, 1=High, 2=Professional)
    pub profile: u8,
    /// AV1 seq_level_idx for operating point 0
    pub level: u8,
    /// AV1 seq_tier for operating point 0
    pub tier: u8,
    /// Bit depth (8, 10, or 12)
    pub bit_depth: u8,
    /// True if monochrome (no chroma planes)
    pub monochrome: bool,
    /// Chroma subsampling X (1 = horizontally subsampled)
    pub chroma_subsampling_x: u8,
    /// Chroma subsampling Y (1 = vertically subsampled)
    pub chroma_subsampling_y: u8,
    /// Chroma sample position (0=unknown, 1=vertical, 2=colocated)
    pub chroma_sample_position: u8,
}

/// Colour information from the `colr` property box.
///
/// Can be either CICP-based (`nclx`) or an ICC profile (`rICC`/`prof`).
/// See ISOBMFF § 12.1.5.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColorInformation {
    /// CICP-based color information (colour_type = 'nclx')
    Nclx {
        /// Colour primaries (ITU-T H.273 Table 2)
        color_primaries: u16,
        /// Transfer characteristics (ITU-T H.273 Table 3)
        transfer_characteristics: u16,
        /// Matrix coefficients (ITU-T H.273 Table 4)
        matrix_coefficients: u16,
        /// True if full range (0-255 for 8-bit), false if limited/studio range
        full_range: bool,
    },
    /// ICC profile (colour_type = 'rICC' or 'prof')
    IccProfile(std::vec::Vec<u8>),
}

/// Image rotation from the `irot` property box.
///
/// Specifies a counter-clockwise rotation to apply after decoding.
/// See ISOBMFF § 12.1.4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageRotation {
    /// Rotation angle in degrees counter-clockwise: 0, 90, 180, or 270.
    pub angle: u16,
}

/// Image mirror from the `imir` property box.
///
/// Specifies a mirror (flip) axis to apply after rotation.
/// See ISOBMFF § 12.1.4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageMirror {
    /// Mirror axis: 0 = top-to-bottom (vertical axis, left-right flip),
    /// 1 = left-to-right (horizontal axis, top-bottom flip).
    pub axis: u8,
}

/// Clean aperture from the `clap` property box.
///
/// Defines a crop rectangle as a centered region. All values are
/// stored as exact rationals (numerator/denominator).
/// See ISOBMFF § 12.1.4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CleanAperture {
    /// Width of the clean aperture (numerator)
    pub width_n: u32,
    /// Width of the clean aperture (denominator)
    pub width_d: u32,
    /// Height of the clean aperture (numerator)
    pub height_n: u32,
    /// Height of the clean aperture (denominator)
    pub height_d: u32,
    /// Horizontal offset of the clean aperture center (numerator, signed)
    pub horiz_off_n: i32,
    /// Horizontal offset of the clean aperture center (denominator)
    pub horiz_off_d: u32,
    /// Vertical offset of the clean aperture center (numerator, signed)
    pub vert_off_n: i32,
    /// Vertical offset of the clean aperture center (denominator)
    pub vert_off_d: u32,
}

/// Pixel aspect ratio from the `pasp` property box.
///
/// For AVIF, the spec requires this to be 1:1 if present.
/// See ISOBMFF § 12.1.4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PixelAspectRatio {
    /// Horizontal spacing
    pub h_spacing: u32,
    /// Vertical spacing
    pub v_spacing: u32,
}

/// Content light level info from the `clli` property box.
///
/// HDR metadata for display mapping.
/// See ISOBMFF § 12.1.5 / ITU-T H.274.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContentLightLevel {
    /// Maximum content light level (cd/m²)
    pub max_content_light_level: u16,
    /// Maximum picture average light level (cd/m²)
    pub max_pic_average_light_level: u16,
}

/// Mastering display colour volume from the `mdcv` property box.
///
/// HDR metadata describing the mastering display's color volume.
/// See ISOBMFF § 12.1.5 / SMPTE ST 2086.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MasteringDisplayColourVolume {
    /// Display primaries: [(x, y); 3] in 0.00002 units (CIE 1931)
    /// Order: green, blue, red (per SMPTE ST 2086)
    pub primaries: [(u16, u16); 3],
    /// White point (x, y) in 0.00002 units
    pub white_point: (u16, u16),
    /// Maximum display luminance in 0.0001 cd/m² units
    pub max_luminance: u32,
    /// Minimum display luminance in 0.0001 cd/m² units
    pub min_luminance: u32,
}

/// Content colour volume from the `cclv` property box.
///
/// Describes the colour volume of the content. Derived from H.265 D.2.40 /
/// ITU-T H.274. All fields are optional, controlled by presence flags.
/// See ISOBMFF § 12.1.5.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContentColourVolume {
    /// Content colour primaries (x, y) for 3 primaries, as signed i32.
    /// Present only if `ccv_primaries_present_flag` was set.
    pub primaries: Option<[(i32, i32); 3]>,
    /// Minimum luminance value. Present only if flag was set.
    pub min_luminance: Option<u32>,
    /// Maximum luminance value. Present only if flag was set.
    pub max_luminance: Option<u32>,
    /// Average luminance value. Present only if flag was set.
    pub avg_luminance: Option<u32>,
}

/// Ambient viewing environment from the `amve` property box.
///
/// Describes the ambient viewing conditions under which the content
/// was authored. See ISOBMFF § 12.1.5 / H.265 D.2.39.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AmbientViewingEnvironment {
    /// Ambient illuminance in units of 1/10000 cd/m²
    pub ambient_illuminance: u32,
    /// Ambient light x chromaticity (CIE 1931), units of 1/50000
    pub ambient_light_x: u16,
    /// Ambient light y chromaticity (CIE 1931), units of 1/50000
    pub ambient_light_y: u16,
}

/// Per-channel gain map parameters from ISO 21496-1.
///
/// Each field is a rational number (numerator/denominator pair) describing
/// how to apply the gain map for this channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GainMapChannel {
    /// Minimum gain map value (numerator).
    pub gain_map_min_n: i32,
    /// Minimum gain map value (denominator).
    pub gain_map_min_d: u32,
    /// Maximum gain map value (numerator).
    pub gain_map_max_n: i32,
    /// Maximum gain map value (denominator).
    pub gain_map_max_d: u32,
    /// Gamma curve parameter (numerator).
    pub gamma_n: u32,
    /// Gamma curve parameter (denominator).
    pub gamma_d: u32,
    /// Base image offset (numerator).
    pub base_offset_n: i32,
    /// Base image offset (denominator).
    pub base_offset_d: u32,
    /// Alternate image offset (numerator).
    pub alternate_offset_n: i32,
    /// Alternate image offset (denominator).
    pub alternate_offset_d: u32,
}

/// Gain map metadata from a ToneMapImage (`tmap`) derived image item.
///
/// Describes how to apply a gain map to convert between SDR and HDR
/// renditions. The gain map is a separate AV1-encoded image that, combined
/// with this metadata, allows reconstructing an HDR image from the SDR base.
///
/// See ISO 21496-1:2025 for the full specification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GainMapMetadata {
    /// If true, each RGB channel has independent gain map parameters.
    /// If false, `channels[0]` applies to all three channels.
    pub is_multichannel: bool,
    /// If true, the gain map is encoded in the base image's colour space.
    /// If false, it's in the alternate image's colour space.
    pub use_base_colour_space: bool,
    /// Base HDR headroom (numerator).
    pub base_hdr_headroom_n: u32,
    /// Base HDR headroom (denominator).
    pub base_hdr_headroom_d: u32,
    /// Alternate HDR headroom (numerator).
    pub alternate_hdr_headroom_n: u32,
    /// Alternate HDR headroom (denominator).
    pub alternate_hdr_headroom_d: u32,
    /// Per-channel parameters. For single-channel mode, only index 0 is
    /// meaningful (indices 1 and 2 are copies of index 0).
    pub channels: [GainMapChannel; 3],
}

/// Gain map information extracted from an AVIF container.
///
/// Bundles the ISO 21496-1 metadata, the raw AV1-encoded gain map image data,
/// and the alternate rendition's color information into a single type.
///
/// The `gain_map_data` field contains an AV1 bitstream that can be decoded
/// with any AV1 decoder (e.g., rav1d) to obtain the gain map pixel values.
///
/// # Example
///
/// ```no_run
/// let bytes = std::fs::read("hdr.avif").unwrap();
/// let parser = zenavif_parse::AvifParser::from_bytes(&bytes).unwrap();
/// if let Some(Ok(gm)) = parser.gain_map() {
///     println!("Gain map: {} bytes", gm.gain_map_data.len());
///     println!("Multichannel: {}", gm.metadata.is_multichannel);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AvifGainMap {
    /// ISO 21496-1 gain map metadata (parsed from the `tmap` item payload).
    pub metadata: GainMapMetadata,
    /// Raw AV1 bitstream of the gain map image. Decode with an AV1 decoder
    /// to obtain the gain map pixel values.
    pub gain_map_data: std::vec::Vec<u8>,
    /// Color information for the alternate (typically HDR) rendition,
    /// from the `tmap` item's `colr` property.
    pub alt_color_info: Option<ColorInformation>,
}

/// Depth auxiliary image extracted from an AVIF container.
///
/// AVIF supports auxiliary images via `auxl` item references with `auxC` type
/// properties, following the HEIF (ISO 23008-12) auxiliary image mechanism.
/// Depth maps use the auxiliary type URN
/// `urn:mpeg:mpegB:cicp:systems:auxiliary:depth` (MPEG-B Part 23) or the
/// legacy HEVC-style `urn:mpeg:hevc:2015:auxid:2`.
///
/// The `data` field contains a raw AV1 bitstream that can be decoded with
/// any AV1 decoder to obtain the depth image pixel values (typically
/// monochrome 8-bit or 10-bit).
///
/// # Example
///
/// ```no_run
/// let bytes = std::fs::read("portrait.avif").unwrap();
/// let parser = zenavif_parse::AvifParser::from_bytes(&bytes).unwrap();
/// if let Some(Ok(dm)) = parser.depth_map() {
///     println!("Depth map: {}x{}, {} bytes AV1 data", dm.width, dm.height, dm.data.len());
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AvifDepthMap {
    /// Raw AV1 bitstream of the depth auxiliary image. Decode with an AV1
    /// decoder to obtain grayscale depth pixel values.
    pub data: std::vec::Vec<u8>,
    /// Width of the depth image in pixels (from `ispe` property).
    pub width: u32,
    /// Height of the depth image in pixels (from `ispe` property).
    pub height: u32,
    /// AV1 codec configuration for the depth item (from `av1C` property).
    pub av1_config: Option<AV1Config>,
    /// Color information for the depth item (from `colr` property), if present.
    pub color_info: Option<ColorInformation>,
}

/// Operating point selector from the `a1op` property box.
///
/// Selects which AV1 operating point to decode for multi-operating-point images.
/// See AVIF § 4.3.4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperatingPointSelector {
    /// Operating point index (0..31)
    pub op_index: u8,
}

/// Layer selector from the `lsel` property box.
///
/// Selects which spatial layer to render for layered/progressive images.
/// See HEIF (ISO 23008-12).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LayerSelector {
    /// Layer ID to render (0-3), or 0xFFFF for all layers (progressive)
    pub layer_id: u16,
}

/// AV1 layered image indexing from the `a1lx` property box.
///
/// Provides byte sizes for the first 3 layers so decoders can seek
/// to a specific layer without parsing the full bitstream.
/// See AVIF § 4.3.6.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AV1LayeredImageIndexing {
    /// Byte sizes of layers 0, 1, 2. The last layer's size is implicit
    /// (total item size minus the sum of these three).
    pub layer_sizes: [u32; 3],
}

/// Options for parsing AVIF files
///
/// Prefer using [`DecodeConfig::lenient()`] with [`AvifParser`] instead.
#[derive(Debug, Clone, Copy)]
#[derive(Default)]
pub struct ParseOptions {
    /// Enable lenient parsing mode
    ///
    /// When true, non-critical validation errors (like non-zero flags in boxes
    /// that expect zero flags) will be ignored instead of returning errors.
    /// This allows parsing of slightly malformed but otherwise valid AVIF files.
    ///
    /// Default: false (strict validation)
    pub lenient: bool,
}

/// Configuration for parsing AVIF files with resource limits and validation options
///
/// Provides fine-grained control over resource consumption during AVIF parsing,
/// allowing defensive parsing against malicious or malformed files.
///
/// Resource limits are checked **before** allocations occur, preventing out-of-memory
/// conditions from malicious files that claim unrealistic dimensions or counts.
///
/// # Examples
///
/// ```rust
/// use zenavif_parse::DecodeConfig;
///
/// // Default limits (suitable for most apps)
/// let config = DecodeConfig::default();
///
/// // Strict limits for untrusted input
/// let config = DecodeConfig::default()
///     .with_peak_memory_limit(100_000_000)  // 100MB
///     .with_total_megapixels_limit(64)       // 64MP max
///     .with_max_animation_frames(100);       // 100 frames
///
/// // No limits (backwards compatible with read_avif)
/// let config = DecodeConfig::unlimited();
/// ```
#[derive(Debug, Clone)]
pub struct DecodeConfig {
    /// Maximum peak heap memory usage in bytes.
    /// Default: 1GB (1,000,000,000 bytes)
    pub peak_memory_limit: Option<u64>,

    /// Maximum total megapixels for grid images.
    /// Default: 512 megapixels
    pub total_megapixels_limit: Option<u32>,

    /// Maximum number of animation frames.
    /// Default: 10,000 frames
    pub max_animation_frames: Option<u32>,

    /// Maximum number of grid tiles.
    /// Default: 1,000 tiles
    pub max_grid_tiles: Option<u32>,

    /// Enable lenient parsing mode.
    /// Default: false (strict validation)
    pub lenient: bool,
}

impl Default for DecodeConfig {
    fn default() -> Self {
        Self {
            peak_memory_limit: Some(1_000_000_000),
            total_megapixels_limit: Some(512),
            max_animation_frames: Some(10_000),
            max_grid_tiles: Some(1_000),
            lenient: false,
        }
    }
}

impl DecodeConfig {
    /// Create a configuration with no resource limits.
    ///
    /// Equivalent to the behavior of `read_avif()` before resource limits were added.
    pub fn unlimited() -> Self {
        Self {
            peak_memory_limit: None,
            total_megapixels_limit: None,
            max_animation_frames: None,
            max_grid_tiles: None,
            lenient: false,
        }
    }

    /// Set the peak memory limit in bytes
    pub fn with_peak_memory_limit(mut self, bytes: u64) -> Self {
        self.peak_memory_limit = Some(bytes);
        self
    }

    /// Set the total megapixels limit for grid images
    pub fn with_total_megapixels_limit(mut self, megapixels: u32) -> Self {
        self.total_megapixels_limit = Some(megapixels);
        self
    }

    /// Set the maximum animation frame count
    pub fn with_max_animation_frames(mut self, frames: u32) -> Self {
        self.max_animation_frames = Some(frames);
        self
    }

    /// Set the maximum grid tile count
    pub fn with_max_grid_tiles(mut self, tiles: u32) -> Self {
        self.max_grid_tiles = Some(tiles);
        self
    }

    /// Enable lenient parsing mode
    pub fn lenient(mut self, lenient: bool) -> Self {
        self.lenient = lenient;
        self
    }
}

/// Grid configuration for tiled/grid-based AVIF images
#[derive(Debug, Clone, PartialEq)]
/// Grid image configuration
///
/// For tiled/grid AVIF images, this describes the grid layout.
/// Grid images are composed of multiple AV1 image items (tiles) arranged in a rectangular grid.
///
/// ## Grid Layout Determination
///
/// Grid layout can be specified in two ways:
/// 1. **Explicit ImageGrid property box** - contains rows, columns, and output dimensions
/// 2. **Calculated from ispe properties** - when no ImageGrid box exists, dimensions are
///    calculated by dividing the grid item's dimensions by a tile's dimensions
///
/// ## Output Dimensions
///
/// - `output_width` and `output_height` may be 0, indicating the decoder should calculate
///   them from the tile dimensions
/// - When non-zero, they specify the exact output dimensions of the composed image
pub struct GridConfig {
    /// Number of tile rows (1-256)
    pub rows: u8,
    /// Number of tile columns (1-256)
    pub columns: u8,
    /// Output width in pixels (0 = calculate from tiles)
    pub output_width: u32,
    /// Output height in pixels (0 = calculate from tiles)
    pub output_height: u32,
}

/// Frame information for animated AVIF
#[cfg(feature = "eager")]
#[deprecated(since = "1.5.0", note = "Use `AvifParser::frame()` which returns `FrameRef` instead")]
#[derive(Debug)]
pub struct AnimationFrame {
    /// AV1 bitstream data for this frame
    pub data: TryVec<u8>,
    /// Duration in milliseconds (0 if unknown)
    pub duration_ms: u32,
}

/// Animation configuration for animated AVIF (avis brand)
#[cfg(feature = "eager")]
#[deprecated(since = "1.5.0", note = "Use `AvifParser::animation_info()` and `AvifParser::frames()` instead")]
#[derive(Debug)]
#[allow(deprecated)]
pub struct AnimationConfig {
    /// Number of times to loop (0 = infinite)
    pub loop_count: u32,
    /// All frames in the animation
    pub frames: TryVec<AnimationFrame>,
}

// Internal structures for animation parsing

#[derive(Debug)]
struct MovieHeader {
    _timescale: u32,
    _duration: u64,
}

#[derive(Debug)]
struct MediaHeader {
    timescale: u32,
    _duration: u64,
}

#[derive(Debug)]
struct TimeToSampleEntry {
    sample_count: u32,
    sample_delta: u32,
}

#[derive(Debug)]
struct SampleToChunkEntry {
    first_chunk: u32,
    samples_per_chunk: u32,
    _sample_description_index: u32,
}

#[derive(Debug)]
struct SampleTable {
    time_to_sample: TryVec<TimeToSampleEntry>,
    sample_sizes: TryVec<u32>,
    /// Precomputed byte offset for each sample, derived from
    /// sample_to_chunk + chunk_offsets + sample_sizes during parsing.
    sample_offsets: TryVec<u64>,
}

/// A track reference entry (e.g., auxl, cdsc) parsed from a `tref` sub-box.
#[derive(Debug)]
struct TrackReference {
    reference_type: FourCC,
    track_ids: TryVec<u32>,
}

/// Codec properties extracted from a `stsd` VisualSampleEntry.
#[derive(Debug, Clone, Default)]
struct TrackCodecConfig {
    av1_config: Option<AV1Config>,
    color_info: Option<ColorInformation>,
}

/// Parsed data from a single track box (`trak`).
#[derive(Debug)]
struct ParsedTrack {
    track_id: u32,
    handler_type: FourCC,
    media_timescale: u32,
    sample_table: SampleTable,
    references: TryVec<TrackReference>,
    loop_count: u32,
    codec_config: TrackCodecConfig,
}

/// Paired color + optional alpha animation data after track association.
struct ParsedAnimationData {
    color_timescale: u32,
    color_sample_table: SampleTable,
    alpha_timescale: Option<u32>,
    alpha_sample_table: Option<SampleTable>,
    loop_count: u32,
    color_codec_config: TrackCodecConfig,
}

#[cfg(feature = "eager")]
#[deprecated(since = "1.5.0", note = "Use `AvifParser` for zero-copy parsing instead")]
#[derive(Debug, Default)]
#[allow(deprecated)]
pub struct AvifData {
    /// AV1 data for the color channels.
    ///
    /// The collected data indicated by the `pitm` box, See ISO 14496-12:2015 § 8.11.4
    pub primary_item: TryVec<u8>,
    /// AV1 data for alpha channel.
    ///
    /// Associated alpha channel for the primary item, if any
    pub alpha_item: Option<TryVec<u8>>,
    /// If true, divide RGB values by the alpha value.
    ///
    /// See `prem` in MIAF § 7.3.5.2
    pub premultiplied_alpha: bool,

    /// Grid configuration for tiled images.
    ///
    /// If present, the image is a grid and `grid_tiles` contains the tile data.
    /// Grid layout is determined either from an explicit ImageGrid property box or
    /// calculated from ispe (Image Spatial Extents) properties.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// #[allow(deprecated)]
    /// use std::fs::File;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #[allow(deprecated)]
    /// let data = zenavif_parse::read_avif(&mut File::open("image.avif")?)?;
    ///
    /// if let Some(grid) = data.grid_config {
    ///     println!("Grid: {}×{} tiles", grid.rows, grid.columns);
    ///     println!("Output: {}×{}", grid.output_width, grid.output_height);
    ///     println!("Tile count: {}", data.grid_tiles.len());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub grid_config: Option<GridConfig>,

    /// AV1 payloads for grid image tiles.
    ///
    /// Empty for non-grid images. For grid images, contains one entry per tile.
    ///
    /// **Tile ordering:** Tiles are guaranteed to be in the correct order for grid assembly,
    /// sorted by their dimgIdx (reference index). This is row-major order: tiles in the first
    /// row from left to right, then the second row, etc.
    pub grid_tiles: TryVec<TryVec<u8>>,

    /// Animation configuration (for animated AVIF with avis brand)
    ///
    /// When present, primary_item contains the first frame
    pub animation: Option<AnimationConfig>,

    /// AV1 codec configuration from the container's `av1C` property.
    pub av1_config: Option<AV1Config>,

    /// Colour information from the container's `colr` property.
    pub color_info: Option<ColorInformation>,

    /// Image rotation from the container's `irot` property.
    pub rotation: Option<ImageRotation>,

    /// Image mirror from the container's `imir` property.
    pub mirror: Option<ImageMirror>,

    /// Clean aperture (crop) from the container's `clap` property.
    pub clean_aperture: Option<CleanAperture>,

    /// Pixel aspect ratio from the container's `pasp` property.
    pub pixel_aspect_ratio: Option<PixelAspectRatio>,

    /// Content light level from the container's `clli` property.
    pub content_light_level: Option<ContentLightLevel>,

    /// Mastering display colour volume from the container's `mdcv` property.
    pub mastering_display: Option<MasteringDisplayColourVolume>,

    /// Content colour volume from the container's `cclv` property.
    pub content_colour_volume: Option<ContentColourVolume>,

    /// Ambient viewing environment from the container's `amve` property.
    pub ambient_viewing: Option<AmbientViewingEnvironment>,

    /// Operating point selector from the container's `a1op` property.
    pub operating_point: Option<OperatingPointSelector>,

    /// Layer selector from the container's `lsel` property.
    pub layer_selector: Option<LayerSelector>,

    /// AV1 layered image indexing from the container's `a1lx` property.
    pub layered_image_indexing: Option<AV1LayeredImageIndexing>,

    /// EXIF metadata from a `cdsc`-linked `Exif` item.
    ///
    /// Raw EXIF data (TIFF header onwards), with the 4-byte AVIF offset prefix stripped.
    pub exif: Option<TryVec<u8>>,

    /// XMP metadata from a `cdsc`-linked `mime` item.
    ///
    /// Raw XMP/XML data as UTF-8.
    pub xmp: Option<TryVec<u8>>,

    /// Gain map metadata from a `tmap` derived image item.
    pub gain_map_metadata: Option<GainMapMetadata>,

    /// AV1-encoded gain map image data.
    pub gain_map_item: Option<TryVec<u8>>,

    /// Color information for the alternate (HDR) rendition from the `tmap` item.
    pub gain_map_color_info: Option<ColorInformation>,

    /// Depth auxiliary image data, if present.
    pub depth_item: Option<TryVec<u8>>,

    /// Width of the depth auxiliary image (from `ispe`).
    pub depth_width: u32,

    /// Height of the depth auxiliary image (from `ispe`).
    pub depth_height: u32,

    /// AV1 codec configuration for the depth auxiliary item.
    pub depth_av1_config: Option<AV1Config>,

    /// Color information for the depth auxiliary item.
    pub depth_color_info: Option<ColorInformation>,

    /// Major brand from the `ftyp` box (e.g., `*b"avif"` or `*b"avis"`).
    pub major_brand: [u8; 4],

    /// Compatible brands from the `ftyp` box.
    pub compatible_brands: std::vec::Vec<[u8; 4]>,
}

#[cfg(feature = "eager")]
#[allow(deprecated)]
impl AvifData {
    /// Get the full gain map bundle, if present.
    ///
    /// Consumes the gain map metadata and data from this `AvifData` and returns
    /// an [`AvifGainMap`]. Returns `None` if no gain map metadata or data is present.
    pub fn gain_map(&self) -> Option<AvifGainMap> {
        let metadata = self.gain_map_metadata.as_ref()?.clone();
        let gain_map_data = self.gain_map_item.as_ref()?.to_vec();
        Some(AvifGainMap {
            metadata,
            gain_map_data,
            alt_color_info: self.gain_map_color_info.clone(),
        })
    }

    /// Get the depth auxiliary image bundle, if present.
    ///
    /// Returns [`AvifDepthMap`] with the raw AV1 depth data, dimensions,
    /// and codec/color info. Returns `None` if no depth auxiliary is present.
    pub fn depth_map(&self) -> Option<AvifDepthMap> {
        let data = self.depth_item.as_ref()?.to_vec();
        Some(AvifDepthMap {
            data,
            width: self.depth_width,
            height: self.depth_height,
            av1_config: self.depth_av1_config.clone(),
            color_info: self.depth_color_info.clone(),
        })
    }
}

// # Memory Usage
//
// This implementation loads all image data into owned vectors (`TryVec<u8>`), which has
// memory implications depending on the file type:
//
// - **Static images**: Single copy of compressed data (~5-50KB typical)
//   - `primary_item`: compressed AV1 data
//   - `alpha_item`: compressed alpha data (if present)
//
// - **Grid images**: All tiles loaded (~100KB-2MB for large grids)
//   - `grid_tiles`: one compressed tile per grid cell
//
// - **Animated images**: All frames loaded eagerly (⚠️ HIGH MEMORY)
//   - Internal mdat boxes: ~500KB for 95-frame video
//   - Extracted frames: ~500KB duplicated in `animation.frames[].data`
//   - **Total: ~2× file size in memory**
//
// For large animated files, consider using a streaming approach or processing frames
// individually rather than loading the entire `AvifData` structure.

#[cfg(feature = "eager")]
#[allow(deprecated)]
impl AvifData {
    #[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader()` instead")]
    pub fn from_reader<R: Read>(reader: &mut R) -> Result<Self> {
        read_avif(reader)
    }

    /// Parses AV1 data to get basic properties of the opaque channel
    pub fn primary_item_metadata(&self) -> Result<AV1Metadata> {
        AV1Metadata::parse_av1_bitstream(&self.primary_item)
    }

    /// Parses AV1 data to get basic properties about the alpha channel, if any
    pub fn alpha_item_metadata(&self) -> Result<Option<AV1Metadata>> {
        self.alpha_item.as_deref().map(AV1Metadata::parse_av1_bitstream).transpose()
    }
}

/// Chroma subsampling configuration for AV1/AVIF.
///
/// `(false, false)` = 4:4:4 (no subsampling).
/// `(true, true)` = 4:2:0 (both axes subsampled).
/// `(true, false)` = 4:2:2 (horizontal only).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChromaSubsampling {
    /// Whether the horizontal (X) axis is subsampled.
    pub horizontal: bool,
    /// Whether the vertical (Y) axis is subsampled.
    pub vertical: bool,
}

impl ChromaSubsampling {
    /// 4:4:4 — no chroma subsampling.
    pub const NONE: Self = Self { horizontal: false, vertical: false };
    /// 4:2:0 — both axes subsampled.
    pub const YUV420: Self = Self { horizontal: true, vertical: true };
    /// 4:2:2 — horizontal subsampling only.
    pub const YUV422: Self = Self { horizontal: true, vertical: false };
}

impl From<(bool, bool)> for ChromaSubsampling {
    fn from((h, v): (bool, bool)) -> Self {
        Self { horizontal: h, vertical: v }
    }
}

impl From<ChromaSubsampling> for (bool, bool) {
    fn from(cs: ChromaSubsampling) -> Self {
        (cs.horizontal, cs.vertical)
    }
}

/// AV1 sequence header metadata parsed from an OBU bitstream.
///
/// See [`AvifParser::primary_metadata()`] and [`AV1Metadata::parse_av1_bitstream()`].
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct AV1Metadata {
    /// Should be true for non-animated AVIF
    pub still_picture: bool,
    pub max_frame_width: NonZeroU32,
    pub max_frame_height: NonZeroU32,
    /// 8, 10, or 12
    pub bit_depth: u8,
    /// 0, 1 or 2 for the level of complexity
    pub seq_profile: u8,
    /// Chroma subsampling. Use named fields (`horizontal`, `vertical`) or
    /// constants like [`ChromaSubsampling::YUV420`].
    pub chroma_subsampling: ChromaSubsampling,
    pub monochrome: bool,
    /// AV1 base quantizer index (0-255) from the first frame header.
    /// `None` if the frame header could not be parsed.
    /// 0 = lossless candidate, 255 = worst quality.
    pub base_q_idx: Option<u8>,
    /// Whether the encoding is lossless (all quantization parameters are zero
    /// and chroma is not subsampled).
    /// `None` if the frame header could not be parsed.
    pub lossless: Option<bool>,
}

impl AV1Metadata {
    /// Parses raw AV1 bitstream (sequence header + optional frame header).
    ///
    /// Extracts sequence-level metadata and attempts to parse the first frame
    /// header for quantization/lossless detection.
    ///
    /// This is for the bare image payload from an encoder, not an AVIF/HEIF file.
    /// To parse AVIF files, see [`AvifParser::from_reader()`].
    #[inline(never)]
    pub fn parse_av1_bitstream(obu_bitstream: &[u8]) -> Result<Self> {
        let (h, frame_quant) = obu::parse_obu_with_frame_info(obu_bitstream)?;
        let no_chroma_subsampling = !h.color.chroma_subsampling.horizontal
            && !h.color.chroma_subsampling.vertical;
        Ok(Self {
            still_picture: h.still_picture,
            max_frame_width: h.max_frame_width,
            max_frame_height: h.max_frame_height,
            bit_depth: h.color.bit_depth,
            seq_profile: h.seq_profile,
            chroma_subsampling: h.color.chroma_subsampling,
            monochrome: h.color.monochrome,
            base_q_idx: frame_quant.map(|fq| fq.base_q_idx),
            lossless: frame_quant.map(|fq| fq.coded_lossless && no_chroma_subsampling),
        })
    }
}

/// A single frame from an animated AVIF, with zero-copy when possible.
///
/// The `data` field is `Cow::Borrowed` when the frame lives in a single
/// contiguous mdat extent, and `Cow::Owned` when extents must be concatenated.
pub struct FrameRef<'a> {
    pub data: Cow<'a, [u8]>,
    /// Alpha channel data for this frame, if the animation has a separate alpha track.
    pub alpha_data: Option<Cow<'a, [u8]>>,
    pub duration_ms: u32,
}

/// Byte range of a media data box within the file.
struct MdatBounds {
    offset: u64,
    length: u64,
}

/// Where an item's data lives: construction method + extent ranges.
struct ItemExtents {
    construction_method: ConstructionMethod,
    extents: TryVec<ExtentRange>,
}

/// Zero-copy AVIF parser backed by a borrowed or owned byte buffer.
///
/// `AvifParser` records byte offsets during parsing but does **not** copy
/// mdat payload data. Data access methods return `Cow<[u8]>` — borrowed
/// when the item is a single contiguous extent, owned when extents must
/// be concatenated.
///
/// # Constructors
///
/// | Method | Lifetime | Zero-copy? |
/// |--------|----------|------------|
/// | [`from_bytes`](Self::from_bytes) | `'data` | Yes — borrows the slice |
/// | [`from_owned`](Self::from_owned) | `'static` | Within the owned buffer |
/// | [`from_reader`](Self::from_reader) | `'static` | Reads all, then owned |
///
/// # Example
///
/// ```no_run
/// use zenavif_parse::AvifParser;
///
/// let bytes = std::fs::read("image.avif")?;
/// let parser = AvifParser::from_bytes(&bytes)?;
/// let primary = parser.primary_data()?; // Cow::Borrowed for single-extent
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct AvifParser<'data> {
    raw: Cow<'data, [u8]>,
    mdat_bounds: TryVec<MdatBounds>,
    idat: Option<TryVec<u8>>,
    primary: ItemExtents,
    alpha: Option<ItemExtents>,
    grid_config: Option<GridConfig>,
    tiles: TryVec<ItemExtents>,
    animation_data: Option<AnimationParserData>,
    premultiplied_alpha: bool,
    av1_config: Option<AV1Config>,
    color_info: Option<ColorInformation>,
    rotation: Option<ImageRotation>,
    mirror: Option<ImageMirror>,
    clean_aperture: Option<CleanAperture>,
    pixel_aspect_ratio: Option<PixelAspectRatio>,
    content_light_level: Option<ContentLightLevel>,
    mastering_display: Option<MasteringDisplayColourVolume>,
    content_colour_volume: Option<ContentColourVolume>,
    ambient_viewing: Option<AmbientViewingEnvironment>,
    operating_point: Option<OperatingPointSelector>,
    layer_selector: Option<LayerSelector>,
    layered_image_indexing: Option<AV1LayeredImageIndexing>,
    exif_item: Option<ItemExtents>,
    xmp_item: Option<ItemExtents>,
    gain_map_metadata: Option<GainMapMetadata>,
    gain_map: Option<ItemExtents>,
    gain_map_color_info: Option<ColorInformation>,
    depth_item: Option<ItemExtents>,
    depth_width: u32,
    depth_height: u32,
    depth_av1_config: Option<AV1Config>,
    depth_color_info: Option<ColorInformation>,
    major_brand: [u8; 4],
    compatible_brands: std::vec::Vec<[u8; 4]>,
}

struct AnimationParserData {
    media_timescale: u32,
    sample_table: SampleTable,
    alpha_media_timescale: Option<u32>,
    alpha_sample_table: Option<SampleTable>,
    loop_count: u32,
    codec_config: TrackCodecConfig,
}

/// Animation metadata from [`AvifParser`]
#[derive(Debug, Clone, Copy)]
pub struct AnimationInfo {
    pub frame_count: usize,
    pub loop_count: u32,
    /// Whether animation has a separate alpha track.
    pub has_alpha: bool,
    /// Media timescale (ticks per second) for the color track.
    pub timescale: u32,
}

/// Parsed structure from the box-level parse pass (no mdat data).
struct ParsedStructure {
    /// `None` for pure AVIF sequences (`avis` brand) that have only `moov`+`mdat`.
    meta: Option<AvifInternalMeta>,
    mdat_bounds: TryVec<MdatBounds>,
    animation_data: Option<ParsedAnimationData>,
    major_brand: [u8; 4],
    compatible_brands: std::vec::Vec<[u8; 4]>,
}

impl<'data> AvifParser<'data> {
    // ========================================
    // Constructors
    // ========================================

    /// Parse AVIF from a borrowed byte slice (true zero-copy).
    ///
    /// The returned parser borrows `data` — single-extent items will be
    /// returned as `Cow::Borrowed` slices into this buffer.
    pub fn from_bytes(data: &'data [u8]) -> Result<Self> {
        Self::from_bytes_with_config(data, &DecodeConfig::default(), &Unstoppable)
    }

    /// Parse AVIF from a borrowed byte slice with resource limits.
    pub fn from_bytes_with_config(
        data: &'data [u8],
        config: &DecodeConfig,
        stop: &dyn Stop,
    ) -> Result<Self> {
        let parsed = Self::parse_raw(data, config, stop)?;
        Self::build(Cow::Borrowed(data), parsed, config)
    }

    /// Parse AVIF from an owned buffer.
    ///
    /// The returned parser owns the data — single-extent items will still
    /// be returned as `Cow::Borrowed` slices (borrowing from the internal buffer).
    pub fn from_owned(data: std::vec::Vec<u8>) -> Result<AvifParser<'static>> {
        AvifParser::from_owned_with_config(data, &DecodeConfig::default(), &Unstoppable)
    }

    /// Parse AVIF from an owned buffer with resource limits.
    pub fn from_owned_with_config(
        data: std::vec::Vec<u8>,
        config: &DecodeConfig,
        stop: &dyn Stop,
    ) -> Result<AvifParser<'static>> {
        let parsed = AvifParser::parse_raw(&data, config, stop)?;
        AvifParser::build(Cow::Owned(data), parsed, config)
    }

    /// Parse AVIF from a reader (reads all bytes, then parses).
    pub fn from_reader<R: Read>(reader: &mut R) -> Result<AvifParser<'static>> {
        AvifParser::from_reader_with_config(reader, &DecodeConfig::default(), &Unstoppable)
    }

    /// Parse AVIF from a reader with resource limits.
    ///
    /// If `config.peak_memory_limit` is set, reading is capped at that many
    /// bytes to prevent unbounded allocation from an untrusted reader.
    pub fn from_reader_with_config<R: Read>(
        reader: &mut R,
        config: &DecodeConfig,
        stop: &dyn Stop,
    ) -> Result<AvifParser<'static>> {
        let buf = if let Some(limit) = config.peak_memory_limit {
            let mut limited = reader.take(limit.saturating_add(1));
            let mut buf = std::vec::Vec::new();
            limited.read_to_end(&mut buf)?;
            if buf.len() as u64 > limit {
                return Err(Error::ResourceLimitExceeded(
                    "input exceeds peak_memory_limit",
                ));
            }
            buf
        } else {
            let mut buf = std::vec::Vec::new();
            reader.read_to_end(&mut buf)?;
            buf
        };
        AvifParser::from_owned_with_config(buf, config, stop)
    }

    // ========================================
    // Internal: parse pass (records offsets, no mdat copy)
    // ========================================

    /// Parse the AVIF box structure from raw bytes, recording mdat offsets
    /// without copying mdat content.
    fn parse_raw(data: &[u8], config: &DecodeConfig, stop: &dyn Stop) -> Result<ParsedStructure> {
        let parse_opts = ParseOptions { lenient: config.lenient };
        let mut cursor = std::io::Cursor::new(data);
        let mut f = OffsetReader::new(&mut cursor);
        let mut iter = BoxIter::with_max_remaining(&mut f, data.len() as u64);

        // 'ftyp' box must occur first; see ISO 14496-12:2015 § 4.3.1
        let (major_brand, compatible_brands) = if let Some(mut b) = iter.next_box()? {
            if b.head.name == BoxType::FileTypeBox {
                let ftyp = read_ftyp(&mut b)?;
                if ftyp.major_brand != b"avif" && ftyp.major_brand != b"avis" {
                    return Err(Error::InvalidData("ftyp must be 'avif' or 'avis'"));
                }
                let major = ftyp.major_brand.value;
                let compat = ftyp.compatible_brands.iter().map(|b| b.value).collect();
                (major, compat)
            } else {
                return Err(Error::InvalidData("'ftyp' box must occur first"));
            }
        } else {
            return Err(Error::InvalidData("'ftyp' box must occur first"));
        };

        let mut meta = None;
        let mut mdat_bounds = TryVec::new();
        let mut animation_data: Option<ParsedAnimationData> = None;

        while let Some(mut b) = iter.next_box()? {
            stop.check()?;

            match b.head.name {
                BoxType::MetadataBox => {
                    if meta.is_some() {
                        return Err(Error::InvalidData(
                            "There should be zero or one meta boxes per ISO 14496-12:2015 § 8.11.1.1",
                        ));
                    }
                    meta = Some(read_avif_meta(&mut b, &parse_opts)?);
                }
                BoxType::MovieBox => {
                    let tracks = read_moov(&mut b)?;
                    if !tracks.is_empty() {
                        animation_data = Some(associate_tracks(tracks)?);
                    }
                }
                BoxType::MediaDataBox => {
                    if b.bytes_left() > 0 {
                        let offset = b.offset();
                        let length = b.bytes_left();
                        mdat_bounds.push(MdatBounds { offset, length })?;
                    }
                    // Skip the content — we'll slice into raw later
                    skip_box_content(&mut b)?;
                }
                _ => skip_box_content(&mut b)?,
            }

            check_parser_state(&b.head, &b.content)?;
        }

        // meta is required for still images, but pure AVIF sequences (avis brand)
        // can have only moov+mdat with no meta box.
        if meta.is_none() && animation_data.is_none() {
            return Err(Error::InvalidData("missing meta"));
        }

        Ok(ParsedStructure { meta, mdat_bounds, animation_data, major_brand, compatible_brands })
    }

    /// Build an AvifParser from raw bytes + parsed structure.
    fn build(raw: Cow<'data, [u8]>, parsed: ParsedStructure, config: &DecodeConfig) -> Result<Self> {
        let tracker = ResourceTracker::new(config);

        // Store animation metadata if present
        let animation_data = if let Some(anim) = parsed.animation_data {
            tracker.validate_animation_frames(anim.color_sample_table.sample_sizes.len() as u32)?;
            Some(AnimationParserData {
                media_timescale: anim.color_timescale,
                sample_table: anim.color_sample_table,
                alpha_media_timescale: anim.alpha_timescale,
                alpha_sample_table: anim.alpha_sample_table,
                loop_count: anim.loop_count,
                codec_config: anim.color_codec_config,
            })
        } else {
            None
        };

        // Pure sequence (no meta box): only animation methods will work.
        // Use codec config from the color track's stsd if available.
        let Some(meta) = parsed.meta else {
            let track_config = animation_data.as_ref()
                .map(|a| a.codec_config.clone())
                .unwrap_or_default();
            return Ok(Self {
                raw,
                mdat_bounds: parsed.mdat_bounds,
                idat: None,
                primary: ItemExtents { construction_method: ConstructionMethod::File, extents: TryVec::new() },
                alpha: None,
                grid_config: None,
                tiles: TryVec::new(),
                animation_data,
                premultiplied_alpha: false,
                av1_config: track_config.av1_config,
                color_info: track_config.color_info,
                rotation: None,
                mirror: None,
                clean_aperture: None,
                pixel_aspect_ratio: None,
                content_light_level: None,
                mastering_display: None,
                content_colour_volume: None,
                ambient_viewing: None,
                operating_point: None,
                layer_selector: None,
                layered_image_indexing: None,
                exif_item: None,
                xmp_item: None,
                gain_map_metadata: None,
                gain_map: None,
                gain_map_color_info: None,
                depth_item: None,
                depth_width: 0,
                depth_height: 0,
                depth_av1_config: None,
                depth_color_info: None,
                major_brand: parsed.major_brand,
                compatible_brands: parsed.compatible_brands,
            });
        };

        // Get primary item extents
        let primary = Self::get_item_extents(&meta, meta.primary_item_id)?;

        // Find alpha item and get its extents
        let alpha_item_id = meta
            .item_references
            .iter()
            .filter(|iref| {
                iref.to_item_id == meta.primary_item_id
                    && iref.from_item_id != meta.primary_item_id
                    && iref.item_type == b"auxl"
            })
            .map(|iref| iref.from_item_id)
            .find(|&item_id| {
                meta.properties.iter().any(|prop| {
                    prop.item_id == item_id
                        && match &prop.property {
                            ItemProperty::AuxiliaryType(urn) => {
                                urn.type_subtype().0 == b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha"
                            }
                            _ => false,
                        }
                })
            });

        let alpha = alpha_item_id
            .map(|id| Self::get_item_extents(&meta, id))
            .transpose()?;

        // Check for premultiplied alpha
        let premultiplied_alpha = alpha_item_id.is_some_and(|alpha_id| {
            meta.item_references.iter().any(|iref| {
                iref.from_item_id == meta.primary_item_id
                    && iref.to_item_id == alpha_id
                    && iref.item_type == b"prem"
            })
        });

        // Find depth auxiliary item (auxl reference with depth auxC type)
        let depth_item_id = meta
            .item_references
            .iter()
            .filter(|iref| {
                iref.to_item_id == meta.primary_item_id
                    && iref.from_item_id != meta.primary_item_id
                    && iref.item_type == b"auxl"
            })
            .map(|iref| iref.from_item_id)
            .find(|&item_id| {
                // Skip the alpha item if we already found one
                if alpha_item_id == Some(item_id) {
                    return false;
                }
                meta.properties.iter().any(|prop| {
                    prop.item_id == item_id
                        && match &prop.property {
                            ItemProperty::AuxiliaryType(urn) => {
                                is_depth_auxiliary_urn(urn.type_subtype().0)
                            }
                            _ => false,
                        }
                })
            });

        let (depth_item, depth_width, depth_height, depth_av1_config, depth_color_info) =
            if let Some(depth_id) = depth_item_id {
                let extents = Self::get_item_extents(&meta, depth_id)?;
                // Get dimensions from ispe property
                let dims = meta.properties.iter().find_map(|p| {
                    if p.item_id == depth_id {
                        match &p.property {
                            ItemProperty::ImageSpatialExtents(e) => Some((e.width, e.height)),
                            _ => None,
                        }
                    } else {
                        None
                    }
                });
                let (w, h) = dims.unwrap_or((0, 0));
                // Get av1C property
                let av1c = meta.properties.iter().find_map(|p| {
                    if p.item_id == depth_id {
                        match &p.property {
                            ItemProperty::AV1Config(c) => Some(c.clone()),
                            _ => None,
                        }
                    } else {
                        None
                    }
                });
                // Get colr property
                let colr = meta.properties.iter().find_map(|p| {
                    if p.item_id == depth_id {
                        match &p.property {
                            ItemProperty::ColorInformation(c) => Some(c.clone()),
                            _ => None,
                        }
                    } else {
                        None
                    }
                });
                (Some(extents), w, h, av1c, colr)
            } else {
                (None, 0, 0, None, None)
            };

        // Find EXIF/XMP items linked via cdsc references to the primary item
        let mut exif_item = None;
        let mut xmp_item = None;
        for iref in meta.item_references.iter() {
            if iref.to_item_id != meta.primary_item_id || iref.item_type != b"cdsc" {
                continue;
            }
            let desc_item_id = iref.from_item_id;
            let Some(info) = meta.item_infos.iter().find(|i| i.item_id == desc_item_id) else {
                continue;
            };
            if info.item_type == b"Exif" && exif_item.is_none() {
                exif_item = Some(Self::get_item_extents(&meta, desc_item_id)?);
            } else if info.item_type == b"mime" && xmp_item.is_none() {
                xmp_item = Some(Self::get_item_extents(&meta, desc_item_id)?);
            }
        }

        // Check if primary item is a grid (tiled image)
        let is_grid = meta
            .item_infos
            .iter()
            .find(|x| x.item_id == meta.primary_item_id)
            .is_some_and(|info| info.item_type == b"grid");

        // Extract grid configuration and tile extents if this is a grid
        let (grid_config, tiles) = if is_grid {
            let mut tiles_with_index: TryVec<(u32, u16)> = TryVec::new();
            for iref in meta.item_references.iter() {
                if iref.from_item_id == meta.primary_item_id && iref.item_type == b"dimg" {
                    tiles_with_index.push((iref.to_item_id, iref.reference_index))?;
                }
            }

            tracker.validate_grid_tiles(tiles_with_index.len() as u32)?;
            tiles_with_index.sort_by_key(|&(_, idx)| idx);

            let mut tile_extents = TryVec::new();
            for (tile_id, _) in tiles_with_index.iter() {
                tile_extents.push(Self::get_item_extents(&meta, *tile_id)?)?;
            }

            let mut tile_ids = TryVec::new();
            for (tile_id, _) in tiles_with_index.iter() {
                tile_ids.push(*tile_id)?;
            }

            let grid_config = Self::calculate_grid_config(&meta, &tile_ids)?;

            // AVIF 1.2: transformative properties SHALL NOT be on grid tile items
            for (tile_id, _) in tiles_with_index.iter() {
                for prop in meta.properties.iter() {
                    if prop.item_id == *tile_id {
                        match &prop.property {
                            ItemProperty::Rotation(_)
                            | ItemProperty::Mirror(_)
                            | ItemProperty::CleanAperture(_) => {
                                warn!("grid tile {} has a transformative property (irot/imir/clap), violating AVIF spec", tile_id);
                            }
                            _ => {}
                        }
                    }
                }
            }

            (Some(grid_config), tile_extents)
        } else {
            (None, TryVec::new())
        };

        // Detect gain map (tmap derived image item)
        let (gain_map_metadata, gain_map, gain_map_color_info) = {
            let tmap_item = meta.item_infos.iter()
                .find(|info| info.item_type == b"tmap");

            if let Some(tmap_info) = tmap_item {
                let tmap_id = tmap_info.item_id;

                // Find dimg references FROM tmap TO its inputs
                let mut inputs: TryVec<(u32, u16)> = TryVec::new();
                for iref in meta.item_references.iter() {
                    if iref.from_item_id == tmap_id && iref.item_type == b"dimg" {
                        inputs.push((iref.to_item_id, iref.reference_index))?;
                    }
                }
                inputs.sort_by_key(|&(_, idx)| idx);

                if inputs.len() >= 2 {
                    let base_item_id = inputs[0].0;
                    let gmap_item_id = inputs[1].0;

                    if base_item_id == meta.primary_item_id {
                        // Read tmap item's data payload (ToneMapImage)
                        let tmap_extents = Self::get_item_extents(&meta, tmap_id)?;
                        let tmap_data = Self::resolve_extents_from_raw(
                            raw.as_ref(), &parsed.mdat_bounds, &tmap_extents,
                        )?;
                        let metadata = parse_tone_map_image(&tmap_data)?;

                        // Get gain map image extents
                        let gmap_extents = Self::get_item_extents(&meta, gmap_item_id)?;

                        // Get alternate color info from tmap item's properties
                        let alt_color = meta.properties.iter().find_map(|p| {
                            if p.item_id == tmap_id {
                                match &p.property {
                                    ItemProperty::ColorInformation(c) => Some(c.clone()),
                                    _ => None,
                                }
                            } else {
                                None
                            }
                        });

                        (Some(metadata), Some(gmap_extents), alt_color)
                    } else {
                        (None, None, None)
                    }
                } else {
                    (None, None, None)
                }
            } else {
                (None, None, None)
            }
        };

        // Extract properties for the primary item
        macro_rules! find_prop {
            ($variant:ident) => {
                meta.properties.iter().find_map(|p| {
                    if p.item_id == meta.primary_item_id {
                        match &p.property {
                            ItemProperty::$variant(c) => Some(c.clone()),
                            _ => None,
                        }
                    } else {
                        None
                    }
                })
            };
        }

        let track_config = animation_data.as_ref().map(|a| &a.codec_config);
        let av1_config = find_prop!(AV1Config)
            .or_else(|| track_config.and_then(|c| c.av1_config.clone()));
        let color_info = find_prop!(ColorInformation)
            .or_else(|| track_config.and_then(|c| c.color_info.clone()));
        let rotation = find_prop!(Rotation);
        let mirror = find_prop!(Mirror);
        let clean_aperture = find_prop!(CleanAperture);
        let pixel_aspect_ratio = find_prop!(PixelAspectRatio);
        let content_light_level = find_prop!(ContentLightLevel);
        let mastering_display = find_prop!(MasteringDisplayColourVolume);
        let content_colour_volume = find_prop!(ContentColourVolume);
        let ambient_viewing = find_prop!(AmbientViewingEnvironment);
        let operating_point = find_prop!(OperatingPointSelector);
        let layer_selector = find_prop!(LayerSelector);
        let layered_image_indexing = find_prop!(AV1LayeredImageIndexing);

        // Clone idat
        let idat = if let Some(ref idat_data) = meta.idat {
            let mut cloned = TryVec::new();
            cloned.extend_from_slice(idat_data)?;
            Some(cloned)
        } else {
            None
        };

        Ok(Self {
            raw,
            mdat_bounds: parsed.mdat_bounds,
            idat,
            primary,
            alpha,
            grid_config,
            tiles,
            animation_data,
            premultiplied_alpha,
            av1_config,
            color_info,
            rotation,
            mirror,
            clean_aperture,
            pixel_aspect_ratio,
            content_light_level,
            mastering_display,
            content_colour_volume,
            ambient_viewing,
            operating_point,
            layer_selector,
            layered_image_indexing,
            exif_item,
            xmp_item,
            gain_map_metadata,
            gain_map,
            gain_map_color_info,
            depth_item,
            depth_width,
            depth_height,
            depth_av1_config,
            depth_color_info,
            major_brand: parsed.major_brand,
            compatible_brands: parsed.compatible_brands,
        })
    }

    // ========================================
    // Internal helpers
    // ========================================

    /// Get item extents (construction method + ranges) from metadata.
    fn get_item_extents(meta: &AvifInternalMeta, item_id: u32) -> Result<ItemExtents> {
        let item = meta
            .iloc_items
            .iter()
            .find(|item| item.item_id == item_id)
            .ok_or(Error::InvalidData("item not found in iloc"))?;

        let mut extents = TryVec::new();
        for extent in &item.extents {
            extents.push(extent.extent_range.clone())?;
        }
        Ok(ItemExtents {
            construction_method: item.construction_method,
            extents,
        })
    }

    /// Resolve file-based item extents from a raw buffer during `build()`,
    /// before `self` exists. Returns owned data (small payloads like tmap).
    fn resolve_extents_from_raw(
        raw: &[u8],
        mdat_bounds: &[MdatBounds],
        item: &ItemExtents,
    ) -> Result<std::vec::Vec<u8>> {
        if item.construction_method != ConstructionMethod::File {
            return Err(Error::Unsupported("tmap item must use file construction method"));
        }
        let mut data = std::vec::Vec::new();
        for extent in &item.extents {
            let file_offset = extent.start();
            let start = usize::try_from(file_offset)?;
            let end = match extent {
                ExtentRange::WithLength(range) => {
                    let len = range.end.checked_sub(range.start)
                        .ok_or(Error::InvalidData("extent range start > end"))?;
                    start.checked_add(usize::try_from(len)?)
                        .ok_or(Error::InvalidData("extent end overflow"))?
                }
                ExtentRange::ToEnd(_) => {
                    // Find the mdat that contains this offset
                    let mut found_end = raw.len();
                    for mdat in mdat_bounds {
                        if file_offset >= mdat.offset && file_offset < mdat.offset + mdat.length {
                            found_end = usize::try_from(mdat.offset + mdat.length)?;
                            break;
                        }
                    }
                    found_end
                }
            };
            let slice = raw.get(start..end)
                .ok_or(Error::InvalidData("tmap extent out of bounds"))?;
            data.extend_from_slice(slice);
        }
        Ok(data)
    }

    /// Resolve an item's data from the raw buffer, returning `Cow::Borrowed`
    /// for single-extent file items and `Cow::Owned` for multi-extent or idat.
    fn resolve_item(&self, item: &ItemExtents) -> Result<Cow<'_, [u8]>> {
        match item.construction_method {
            ConstructionMethod::Idat => self.resolve_idat_extents(&item.extents),
            ConstructionMethod::File => self.resolve_file_extents(&item.extents),
            ConstructionMethod::Item => Err(Error::Unsupported("construction_method 'item' not supported")),
        }
    }

    /// Resolve file-based extents from the raw buffer.
    fn resolve_file_extents(&self, extents: &[ExtentRange]) -> Result<Cow<'_, [u8]>> {
        let raw = self.raw.as_ref();

        // Fast path: single extent → borrow directly from raw
        if extents.len() == 1 {
            let extent = &extents[0];
            let (start, end) = self.extent_byte_range(extent)?;
            let slice = raw.get(start..end).ok_or(Error::InvalidData("extent out of bounds in raw buffer"))?;
            return Ok(Cow::Borrowed(slice));
        }

        // Multi-extent: concatenate into owned buffer
        let mut data = TryVec::new();
        for extent in extents {
            let (start, end) = self.extent_byte_range(extent)?;
            let slice = raw.get(start..end).ok_or(Error::InvalidData("extent out of bounds in raw buffer"))?;
            data.extend_from_slice(slice)?;
        }
        Ok(Cow::Owned(data.into_iter().collect()))
    }

    /// Convert an ExtentRange to a (start, end) byte range within the raw buffer.
    fn extent_byte_range(&self, extent: &ExtentRange) -> Result<(usize, usize)> {
        let file_offset = extent.start();
        let start = usize::try_from(file_offset)?;

        match extent {
            ExtentRange::WithLength(range) => {
                let len = range.end.checked_sub(range.start)
                    .ok_or(Error::InvalidData("extent range start > end"))?;
                let end = start.checked_add(usize::try_from(len)?)
                    .ok_or(Error::InvalidData("extent end overflow"))?;
                Ok((start, end))
            }
            ExtentRange::ToEnd(_) => {
                // Find the mdat that contains this offset and use its bounds
                for mdat in &self.mdat_bounds {
                    if file_offset >= mdat.offset && file_offset < mdat.offset + mdat.length {
                        let end = usize::try_from(mdat.offset + mdat.length)?;
                        return Ok((start, end));
                    }
                }
                // Fall back to end of raw buffer
                Ok((start, self.raw.len()))
            }
        }
    }

    /// Resolve idat-based extents.
    fn resolve_idat_extents(&self, extents: &[ExtentRange]) -> Result<Cow<'_, [u8]>> {
        let idat_data = self.idat.as_ref()
            .ok_or(Error::InvalidData("idat box missing but construction_method is Idat"))?;

        if extents.len() == 1 {
            let extent = &extents[0];
            let start = usize::try_from(extent.start())?;
            let slice = match extent {
                ExtentRange::WithLength(range) => {
                    let len = usize::try_from(range.end - range.start)?;
                    idat_data.get(start..start + len)
                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
                }
                ExtentRange::ToEnd(_) => {
                    idat_data.get(start..)
                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
                }
            };
            return Ok(Cow::Borrowed(slice));
        }

        // Multi-extent idat: concatenate
        let mut data = TryVec::new();
        for extent in extents {
            let start = usize::try_from(extent.start())?;
            let slice = match extent {
                ExtentRange::WithLength(range) => {
                    let len = usize::try_from(range.end - range.start)?;
                    idat_data.get(start..start + len)
                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
                }
                ExtentRange::ToEnd(_) => {
                    idat_data.get(start..)
                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
                }
            };
            data.extend_from_slice(slice)?;
        }
        Ok(Cow::Owned(data.into_iter().collect()))
    }

    /// Resolve a single animation frame from the raw buffer.
    fn resolve_frame(&self, index: usize) -> Result<FrameRef<'_>> {
        let anim = self.animation_data.as_ref()
            .ok_or(Error::InvalidData("not an animated AVIF"))?;

        if index >= anim.sample_table.sample_sizes.len() {
            return Err(Error::InvalidData("frame index out of bounds"));
        }

        let duration_ms = self.calculate_frame_duration(&anim.sample_table, anim.media_timescale, index)?;
        let (offset, size) = self.calculate_sample_location(&anim.sample_table, index)?;

        let start = usize::try_from(offset)?;
        let end = start.checked_add(size as usize)
            .ok_or(Error::InvalidData("frame end overflow"))?;

        let raw = self.raw.as_ref();
        let slice = raw.get(start..end)
            .ok_or(Error::InvalidData("frame not found in raw buffer"))?;

        // Resolve alpha frame if alpha track exists and has this index
        let alpha_data = if let Some(ref alpha_st) = anim.alpha_sample_table {
            let alpha_timescale = anim.alpha_media_timescale.unwrap_or(anim.media_timescale);
            if index < alpha_st.sample_sizes.len() {
                let (a_offset, a_size) = self.calculate_sample_location(alpha_st, index)?;
                let a_start = usize::try_from(a_offset)?;
                let a_end = a_start.checked_add(a_size as usize)
                    .ok_or(Error::InvalidData("alpha frame end overflow"))?;
                let a_slice = raw.get(a_start..a_end)
                    .ok_or(Error::InvalidData("alpha frame not found in raw buffer"))?;
                let _ = alpha_timescale; // timescale used for duration, which comes from color track
                Some(Cow::Borrowed(a_slice))
            } else {
                warn!("alpha track has fewer frames than color track (index {})", index);
                None
            }
        } else {
            None
        };

        Ok(FrameRef {
            data: Cow::Borrowed(slice),
            alpha_data,
            duration_ms,
        })
    }

    /// Calculate grid configuration from metadata.
    fn calculate_grid_config(meta: &AvifInternalMeta, tile_ids: &[u32]) -> Result<GridConfig> {
        // Try explicit grid property first
        for prop in &meta.properties {
            if prop.item_id == meta.primary_item_id
                && let ItemProperty::ImageGrid(grid) = &prop.property {
                    return Ok(grid.clone());
                }
        }

        // Fall back to ispe calculation
        let grid_dims = meta
            .properties
            .iter()
            .find(|p| p.item_id == meta.primary_item_id)
            .and_then(|p| match &p.property {
                ItemProperty::ImageSpatialExtents(e) => Some(e),
                _ => None,
            });

        let tile_dims = tile_ids.first().and_then(|&tile_id| {
            meta.properties
                .iter()
                .find(|p| p.item_id == tile_id)
                .and_then(|p| match &p.property {
                    ItemProperty::ImageSpatialExtents(e) => Some(e),
                    _ => None,
                })
        });

        if let (Some(grid), Some(tile)) = (grid_dims, tile_dims)
            && tile.width != 0
                && tile.height != 0
                && grid.width % tile.width == 0
                && grid.height % tile.height == 0
            {
                let columns = grid.width / tile.width;
                let rows = grid.height / tile.height;

                if columns <= 255 && rows <= 255 {
                    return Ok(GridConfig {
                        rows: rows as u8,
                        columns: columns as u8,
                        output_width: grid.width,
                        output_height: grid.height,
                    });
                }
            }

        let tile_count = tile_ids.len();
        Ok(GridConfig {
            rows: tile_count.min(255) as u8,
            columns: 1,
            output_width: 0,
            output_height: 0,
        })
    }

    /// Calculate frame duration from sample table.
    fn calculate_frame_duration(
        &self,
        st: &SampleTable,
        timescale: u32,
        index: usize,
    ) -> Result<u32> {
        let mut current_sample = 0;
        for entry in &st.time_to_sample {
            if current_sample + entry.sample_count as usize > index {
                let duration_ms = if timescale > 0 {
                    ((entry.sample_delta as u64) * 1000) / (timescale as u64)
                } else {
                    0
                };
                return Ok(u32::try_from(duration_ms).unwrap_or(u32::MAX));
            }
            current_sample += entry.sample_count as usize;
        }
        Ok(0)
    }

    /// Look up precomputed sample location (offset and size) from sample table.
    fn calculate_sample_location(&self, st: &SampleTable, index: usize) -> Result<(u64, u32)> {
        let offset = *st
            .sample_offsets
            .get(index)
            .ok_or(Error::InvalidData("sample index out of bounds"))?;
        let size = *st
            .sample_sizes
            .get(index)
            .ok_or(Error::InvalidData("sample index out of bounds"))?;
        Ok((offset, size))
    }

    // ========================================
    // Public data access API (one way each)
    // ========================================

    /// Get primary item data.
    ///
    /// Returns `Cow::Borrowed` for single-extent items, `Cow::Owned` for multi-extent.
    pub fn primary_data(&self) -> Result<Cow<'_, [u8]>> {
        self.resolve_item(&self.primary)
    }

    /// Get alpha item data, if present.
    pub fn alpha_data(&self) -> Option<Result<Cow<'_, [u8]>>> {
        self.alpha.as_ref().map(|item| self.resolve_item(item))
    }

    /// Get grid tile data by index.
    pub fn tile_data(&self, index: usize) -> Result<Cow<'_, [u8]>> {
        let item = self.tiles.get(index)
            .ok_or(Error::InvalidData("tile index out of bounds"))?;
        self.resolve_item(item)
    }

    /// Get a single animation frame by index.
    pub fn frame(&self, index: usize) -> Result<FrameRef<'_>> {
        self.resolve_frame(index)
    }

    /// Iterate over all animation frames.
    pub fn frames(&self) -> FrameIterator<'_> {
        let count = self
            .animation_info()
            .map(|info| info.frame_count)
            .unwrap_or(0);
        FrameIterator { parser: self, index: 0, count }
    }

    // ========================================
    // Metadata (no data access)
    // ========================================

    /// Get animation metadata (if animated).
    pub fn animation_info(&self) -> Option<AnimationInfo> {
        self.animation_data.as_ref().map(|data| AnimationInfo {
            frame_count: data.sample_table.sample_sizes.len(),
            loop_count: data.loop_count,
            has_alpha: data.alpha_sample_table.is_some(),
            timescale: data.media_timescale,
        })
    }

    /// Get grid configuration (if grid image).
    pub fn grid_config(&self) -> Option<&GridConfig> {
        self.grid_config.as_ref()
    }

    /// Get number of grid tiles.
    pub fn grid_tile_count(&self) -> usize {
        self.tiles.len()
    }

    /// Check if alpha channel uses premultiplied alpha.
    pub fn premultiplied_alpha(&self) -> bool {
        self.premultiplied_alpha
    }

    /// Get the AV1 codec configuration for the primary item, if present.
    ///
    /// This is parsed from the `av1C` property box in the container.
    pub fn av1_config(&self) -> Option<&AV1Config> {
        self.av1_config.as_ref()
    }

    /// Get colour information for the primary item, if present.
    ///
    /// This is parsed from the `colr` property box in the container.
    /// For CICP/nclx values, this is the authoritative source and may
    /// differ from values in the AV1 bitstream sequence header.
    pub fn color_info(&self) -> Option<&ColorInformation> {
        self.color_info.as_ref()
    }

    /// Get rotation for the primary item, if present.
    pub fn rotation(&self) -> Option<&ImageRotation> {
        self.rotation.as_ref()
    }

    /// Get mirror for the primary item, if present.
    pub fn mirror(&self) -> Option<&ImageMirror> {
        self.mirror.as_ref()
    }

    /// Get clean aperture (crop) for the primary item, if present.
    pub fn clean_aperture(&self) -> Option<&CleanAperture> {
        self.clean_aperture.as_ref()
    }

    /// Get pixel aspect ratio for the primary item, if present.
    pub fn pixel_aspect_ratio(&self) -> Option<&PixelAspectRatio> {
        self.pixel_aspect_ratio.as_ref()
    }

    /// Get content light level info for the primary item, if present.
    pub fn content_light_level(&self) -> Option<&ContentLightLevel> {
        self.content_light_level.as_ref()
    }

    /// Get mastering display colour volume for the primary item, if present.
    pub fn mastering_display(&self) -> Option<&MasteringDisplayColourVolume> {
        self.mastering_display.as_ref()
    }

    /// Get content colour volume for the primary item, if present.
    pub fn content_colour_volume(&self) -> Option<&ContentColourVolume> {
        self.content_colour_volume.as_ref()
    }

    /// Get ambient viewing environment for the primary item, if present.
    pub fn ambient_viewing(&self) -> Option<&AmbientViewingEnvironment> {
        self.ambient_viewing.as_ref()
    }

    /// Get operating point selector for the primary item, if present.
    pub fn operating_point(&self) -> Option<&OperatingPointSelector> {
        self.operating_point.as_ref()
    }

    /// Get layer selector for the primary item, if present.
    pub fn layer_selector(&self) -> Option<&LayerSelector> {
        self.layer_selector.as_ref()
    }

    /// Get AV1 layered image indexing for the primary item, if present.
    pub fn layered_image_indexing(&self) -> Option<&AV1LayeredImageIndexing> {
        self.layered_image_indexing.as_ref()
    }

    /// Get EXIF metadata for the primary item, if present.
    ///
    /// Returns raw EXIF data (TIFF header onwards), with the 4-byte AVIF offset prefix stripped.
    pub fn exif(&self) -> Option<Result<Cow<'_, [u8]>>> {
        self.exif_item.as_ref().map(|item| {
            let raw = self.resolve_item(item)?;
            // AVIF EXIF items start with a 4-byte big-endian offset to the TIFF header
            if raw.len() <= 4 {
                return Err(Error::InvalidData("EXIF item too short"));
            }
            let offset = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
            let start = 4 + offset;
            if start >= raw.len() {
                return Err(Error::InvalidData("EXIF offset exceeds item size"));
            }
            match raw {
                Cow::Borrowed(slice) => Ok(Cow::Borrowed(&slice[start..])),
                Cow::Owned(vec) => Ok(Cow::Owned(vec[start..].to_vec())),
            }
        })
    }

    /// Get XMP metadata for the primary item, if present.
    ///
    /// Returns raw XMP/XML data.
    pub fn xmp(&self) -> Option<Result<Cow<'_, [u8]>>> {
        self.xmp_item.as_ref().map(|item| self.resolve_item(item))
    }

    /// Gain map metadata, if a `tmap` derived image item is present.
    ///
    /// Describes how to apply a gain map to reconstruct an HDR rendition
    /// from the SDR base image. See ISO 21496-1.
    pub fn gain_map_metadata(&self) -> Option<&GainMapMetadata> {
        self.gain_map_metadata.as_ref()
    }

    /// Gain map image data (AV1-encoded), if present.
    pub fn gain_map_data(&self) -> Option<Result<Cow<'_, [u8]>>> {
        self.gain_map.as_ref().map(|item| self.resolve_item(item))
    }

    /// Color information for the alternate (typically HDR) rendition.
    ///
    /// This comes from the `tmap` item's `colr` property and describes
    /// the colour space of the tone-mapped output.
    pub fn gain_map_color_info(&self) -> Option<&ColorInformation> {
        self.gain_map_color_info.as_ref()
    }

    /// Get the full gain map bundle, if a `tmap` derived image item is present.
    ///
    /// Returns [`AvifGainMap`] containing metadata, raw AV1 gain map data,
    /// and alternate rendition color info. Returns `None` if no gain map
    /// is present, or `Some(Err(..))` if the gain map data cannot be resolved.
    pub fn gain_map(&self) -> Option<Result<AvifGainMap>> {
        let metadata = self.gain_map_metadata.as_ref()?.clone();
        let data_extents = self.gain_map.as_ref()?;
        let alt_color_info = self.gain_map_color_info.clone();

        Some(self.resolve_item(data_extents).map(|data| AvifGainMap {
            metadata,
            gain_map_data: data.into_owned(),
            alt_color_info,
        }))
    }

    /// Check if a depth auxiliary image is present.
    ///
    /// Returns `true` if the AVIF container has an `auxl`-linked item with
    /// a depth auxiliary type URN.
    pub fn has_depth_map(&self) -> bool {
        self.depth_item.is_some()
    }

    /// Get the raw AV1 bitstream of the depth auxiliary image, if present.
    pub fn depth_map_data(&self) -> Option<Result<Cow<'_, [u8]>>> {
        self.depth_item.as_ref().map(|item| self.resolve_item(item))
    }

    /// Get the full depth map bundle, if a depth auxiliary image is present.
    ///
    /// Returns [`AvifDepthMap`] containing the raw AV1 depth image data,
    /// dimensions, codec config, and color info. Returns `None` if no depth
    /// auxiliary is present, or `Some(Err(..))` if the data cannot be resolved.
    ///
    /// # Example
    ///
    /// ```no_run
    /// let bytes = std::fs::read("portrait.avif").unwrap();
    /// let parser = zenavif_parse::AvifParser::from_bytes(&bytes).unwrap();
    /// if let Some(Ok(dm)) = parser.depth_map() {
    ///     println!("Depth: {}x{}, {} bytes", dm.width, dm.height, dm.data.len());
    /// }
    /// ```
    pub fn depth_map(&self) -> Option<Result<AvifDepthMap>> {
        let data_extents = self.depth_item.as_ref()?;
        let av1_config = self.depth_av1_config.clone();
        let color_info = self.depth_color_info.clone();
        let width = self.depth_width;
        let height = self.depth_height;

        Some(self.resolve_item(data_extents).map(|data| AvifDepthMap {
            data: data.into_owned(),
            width,
            height,
            av1_config,
            color_info,
        }))
    }

    /// Get the major brand from the `ftyp` box (e.g., `*b"avif"` or `*b"avis"`).
    pub fn major_brand(&self) -> &[u8; 4] {
        &self.major_brand
    }

    /// Get the compatible brands from the `ftyp` box.
    pub fn compatible_brands(&self) -> &[[u8; 4]] {
        &self.compatible_brands
    }

    /// Parse AV1 metadata from the primary item.
    pub fn primary_metadata(&self) -> Result<AV1Metadata> {
        let data = self.primary_data()?;
        AV1Metadata::parse_av1_bitstream(&data)
    }

    /// Parse AV1 metadata from the alpha item, if present.
    pub fn alpha_metadata(&self) -> Option<Result<AV1Metadata>> {
        self.alpha.as_ref().map(|item| {
            let data = self.resolve_item(item)?;
            AV1Metadata::parse_av1_bitstream(&data)
        })
    }

    // ========================================
    // Conversion
    // ========================================

    /// Convert to [`AvifData`] (eagerly loads all frames and tiles).
    ///
    /// Provided for migration from the eager API. Prefer using `AvifParser`
    /// methods directly.
    #[cfg(feature = "eager")]
    #[deprecated(since = "1.5.0", note = "Use AvifParser methods directly instead of converting to AvifData")]
    #[allow(deprecated)]
    pub fn to_avif_data(&self) -> Result<AvifData> {
        let primary_data = self.primary_data()?;
        let mut primary_item = TryVec::new();
        primary_item.extend_from_slice(&primary_data)?;

        let alpha_item = match self.alpha_data() {
            Some(Ok(data)) => {
                let mut v = TryVec::new();
                v.extend_from_slice(&data)?;
                Some(v)
            }
            Some(Err(e)) => return Err(e),
            None => None,
        };

        let mut grid_tiles = TryVec::new();
        for i in 0..self.grid_tile_count() {
            let data = self.tile_data(i)?;
            let mut v = TryVec::new();
            v.extend_from_slice(&data)?;
            grid_tiles.push(v)?;
        }

        let animation = if let Some(info) = self.animation_info() {
            let mut frames = TryVec::new();
            for i in 0..info.frame_count {
                let frame_ref = self.frame(i)?;
                let mut data = TryVec::new();
                data.extend_from_slice(&frame_ref.data)?;
                frames.push(AnimationFrame { data, duration_ms: frame_ref.duration_ms })?;
            }
            Some(AnimationConfig {
                loop_count: info.loop_count,
                frames,
            })
        } else {
            None
        };

        Ok(AvifData {
            primary_item,
            alpha_item,
            premultiplied_alpha: self.premultiplied_alpha,
            grid_config: self.grid_config.clone(),
            grid_tiles,
            animation,
            av1_config: self.av1_config.clone(),
            color_info: self.color_info.clone(),
            rotation: self.rotation,
            mirror: self.mirror,
            clean_aperture: self.clean_aperture,
            pixel_aspect_ratio: self.pixel_aspect_ratio,
            content_light_level: self.content_light_level,
            mastering_display: self.mastering_display,
            content_colour_volume: self.content_colour_volume,
            ambient_viewing: self.ambient_viewing,
            operating_point: self.operating_point,
            layer_selector: self.layer_selector,
            layered_image_indexing: self.layered_image_indexing,
            exif: self.exif().and_then(|r| r.ok()).map(|c| {
                let mut v = TryVec::new();
                let _ = v.extend_from_slice(&c);
                v
            }),
            xmp: self.xmp().and_then(|r| r.ok()).map(|c| {
                let mut v = TryVec::new();
                let _ = v.extend_from_slice(&c);
                v
            }),
            gain_map_metadata: self.gain_map_metadata.clone(),
            gain_map_item: self.gain_map_data().and_then(|r| r.ok()).map(|c| {
                let mut v = TryVec::new();
                let _ = v.extend_from_slice(&c);
                v
            }),
            gain_map_color_info: self.gain_map_color_info.clone(),
            depth_item: self.depth_map_data().and_then(|r| r.ok()).map(|c| {
                let mut v = TryVec::new();
                let _ = v.extend_from_slice(&c);
                v
            }),
            depth_width: self.depth_width,
            depth_height: self.depth_height,
            depth_av1_config: self.depth_av1_config.clone(),
            depth_color_info: self.depth_color_info.clone(),
            major_brand: self.major_brand,
            compatible_brands: self.compatible_brands.clone(),
        })
    }
}

/// Iterator over animation frames.
///
/// Created by [`AvifParser::frames()`]. Yields [`FrameRef`] on demand.
pub struct FrameIterator<'a> {
    parser: &'a AvifParser<'a>,
    index: usize,
    count: usize,
}

impl<'a> Iterator for FrameIterator<'a> {
    type Item = Result<FrameRef<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.count {
            return None;
        }
        let result = self.parser.frame(self.index);
        self.index += 1;
        Some(result)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.count.saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for FrameIterator<'_> {
    fn len(&self) -> usize {
        self.count.saturating_sub(self.index)
    }
}

struct AvifInternalMeta {
    item_references: TryVec<SingleItemTypeReferenceBox>,
    properties: TryVec<AssociatedProperty>,
    primary_item_id: u32,
    iloc_items: TryVec<ItemLocationBoxItem>,
    item_infos: TryVec<ItemInfoEntry>,
    idat: Option<TryVec<u8>>,
    #[allow(dead_code)] // Parsed for future altr group support
    entity_groups: TryVec<EntityGroup>,
}

/// A Media Data Box
/// See ISO 14496-12:2015 § 8.1.1
#[cfg(feature = "eager")]
struct MediaDataBox {
    /// Offset of `data` from the beginning of the file. See `ConstructionMethod::File`
    offset: u64,
    data: TryVec<u8>,
}

#[cfg(feature = "eager")]
impl MediaDataBox {
    /// Check whether the beginning of `extent` is within the bounds of the `MediaDataBox`.
    /// We assume extents to not cross box boundaries. If so, this will cause an error
    /// in `read_extent`.
    fn contains_extent(&self, extent: &ExtentRange) -> bool {
        if self.offset <= extent.start() {
            let start_offset = extent.start() - self.offset;
            start_offset < self.data.len().to_u64()
        } else {
            false
        }
    }

    /// Check whether `extent` covers the `MediaDataBox` exactly.
    fn matches_extent(&self, extent: &ExtentRange) -> bool {
        if self.offset == extent.start() {
            match extent {
                ExtentRange::WithLength(range) => {
                    if let Some(end) = self.offset.checked_add(self.data.len().to_u64()) {
                        end == range.end
                    } else {
                        false
                    }
                },
                ExtentRange::ToEnd(_) => true,
            }
        } else {
            false
        }
    }

    /// Copy the range specified by `extent` to the end of `buf` or return an error if the range
    /// is not fully contained within `MediaDataBox`.
    fn read_extent(&self, extent: &ExtentRange, buf: &mut TryVec<u8>) -> Result<()> {
        let start_offset = extent
            .start()
            .checked_sub(self.offset)
            .ok_or(Error::InvalidData("mdat does not contain extent"))?;
        let slice = match extent {
            ExtentRange::WithLength(range) => {
                let range_len = range
                    .end
                    .checked_sub(range.start)
                    .ok_or(Error::InvalidData("range start > end"))?;
                let end = start_offset
                    .checked_add(range_len)
                    .ok_or(Error::InvalidData("extent end overflow"))?;
                self.data.get(start_offset.try_into()?..end.try_into()?)
            },
            ExtentRange::ToEnd(_) => self.data.get(start_offset.try_into()?..),
        };
        let slice = slice.ok_or(Error::InvalidData("extent crosses box boundary"))?;
        buf.extend_from_slice(slice)?;
        Ok(())
    }

}

/// Used for 'infe' boxes within 'iinf' boxes
/// See ISO 14496-12:2015 § 8.11.6
/// Only versions {2, 3} are supported
#[derive(Debug)]
struct ItemInfoEntry {
    item_id: u32,
    item_type: FourCC,
}

/// See ISO 14496-12:2015 § 8.11.12
#[derive(Debug)]
struct SingleItemTypeReferenceBox {
    item_type: FourCC,
    from_item_id: u32,
    to_item_id: u32,
    /// Index of this reference within the list of references of the same type from the same item
    /// (0-based). This is the dimgIdx for grid tiles.
    reference_index: u16,
}

/// Potential sizes (in bytes) of variable-sized fields of the 'iloc' box
/// See ISO 14496-12:2015 § 8.11.3
#[derive(Debug)]
enum IlocFieldSize {
    Zero,
    Four,
    Eight,
}

impl IlocFieldSize {
    const fn to_bits(&self) -> u8 {
        match self {
            Self::Zero => 0,
            Self::Four => 32,
            Self::Eight => 64,
        }
    }
}

impl TryFrom<u8> for IlocFieldSize {
    type Error = Error;

    fn try_from(value: u8) -> Result<Self> {
        match value {
            0 => Ok(Self::Zero),
            4 => Ok(Self::Four),
            8 => Ok(Self::Eight),
            _ => Err(Error::InvalidData("value must be in the set {0, 4, 8}")),
        }
    }
}

#[derive(PartialEq)]
enum IlocVersion {
    Zero,
    One,
    Two,
}

impl TryFrom<u8> for IlocVersion {
    type Error = Error;

    fn try_from(value: u8) -> Result<Self> {
        match value {
            0 => Ok(Self::Zero),
            1 => Ok(Self::One),
            2 => Ok(Self::Two),
            _ => Err(Error::Unsupported("unsupported version in 'iloc' box")),
        }
    }
}

/// Used for 'iloc' boxes
/// See ISO 14496-12:2015 § 8.11.3
/// `base_offset` is omitted since it is integrated into the ranges in `extents`
/// `data_reference_index` is omitted, since only 0 (i.e., this file) is supported
#[derive(Debug)]
struct ItemLocationBoxItem {
    item_id: u32,
    construction_method: ConstructionMethod,
    /// Unused for `ConstructionMethod::Idat`
    extents: TryVec<ItemLocationBoxExtent>,
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum ConstructionMethod {
    File,
    Idat,
    #[allow(dead_code)] // TODO: see https://github.com/mozilla/mp4parse-rust/issues/196
    Item,
}

/// `extent_index` is omitted since it's only used for `ConstructionMethod::Item` which
/// is currently not implemented.
#[derive(Clone, Debug)]
struct ItemLocationBoxExtent {
    extent_range: ExtentRange,
}

#[derive(Clone, Debug)]
enum ExtentRange {
    WithLength(Range<u64>),
    ToEnd(RangeFrom<u64>),
}

impl ExtentRange {
    const fn start(&self) -> u64 {
        match self {
            Self::WithLength(r) => r.start,
            Self::ToEnd(r) => r.start,
        }
    }
}

/// See ISO 14496-12:2015 § 4.2
struct BMFFBox<'a, T> {
    head: BoxHeader,
    content: Take<&'a mut T>,
}

impl<T: Read> BMFFBox<'_, T> {
    fn read_into_try_vec(&mut self) -> std::io::Result<TryVec<u8>> {
        let limit = self.content.limit();
        // For size=0 boxes, size is set to u64::MAX, but after subtracting offset
        // (8 or 16 bytes), the limit will be slightly less. Check for values very
        // close to u64::MAX to detect these cases.
        // Cap pre-allocation to 256 MB — the actual read_to_end will
        // grow as needed if the box really is larger, and return early
        // if the underlying reader has less data than claimed.
        const MAX_PREALLOC: u64 = 256 * 1024 * 1024;
        let mut vec = if limit >= u64::MAX - BoxHeader::MIN_LARGE_SIZE {
            // Unknown size (size=0 box), read without pre-allocation
            std::vec::Vec::new()
        } else {
            let mut v = std::vec::Vec::new();
            v.try_reserve_exact(limit.min(MAX_PREALLOC) as usize)
                .map_err(|_| std::io::ErrorKind::OutOfMemory)?;
            v
        };
        self.content.read_to_end(&mut vec)?; // The default impl
        Ok(vec.into())
    }
}

#[test]
fn box_read_to_end() {
    let tmp = &mut b"1234567890".as_slice();
    let mut src = BMFFBox {
        head: BoxHeader { name: BoxType::FileTypeBox, size: 5, offset: 0, uuid: None },
        content: <_ as Read>::take(tmp, 5),
    };
    let buf = src.read_into_try_vec().unwrap();
    assert_eq!(buf.len(), 5);
    assert_eq!(buf, b"12345".as_ref());
}

#[test]
fn box_read_to_end_large_claim() {
    // A box claiming huge size but backed by only 10 bytes should still succeed —
    // read_to_end returns what's actually available, pre-allocation is capped.
    let tmp = &mut b"1234567890".as_slice();
    let mut src = BMFFBox {
        head: BoxHeader { name: BoxType::FileTypeBox, size: 5, offset: 0, uuid: None },
        content: <_ as Read>::take(tmp, u64::MAX / 2),
    };
    let buf = src.read_into_try_vec().unwrap();
    assert_eq!(buf.len(), 10);
}

struct BoxIter<'a, T> {
    src: &'a mut T,
    /// Upper bound on bytes remaining in the source.
    ///
    /// Used to clamp claimed box sizes so that a malformed header
    /// (e.g. claiming 4 GB when only 26 bytes remain) does not cause
    /// multi-gigabyte allocations based on [`BMFFBox::bytes_left`].
    max_remaining: u64,
}

impl<T: Read> BoxIter<'_, T> {
    /// Create a BoxIter without a known data bound (used by streaming readers).
    #[cfg(feature = "eager")]
    fn new(src: &mut T) -> BoxIter<'_, T> {
        BoxIter { src, max_remaining: u64::MAX }
    }

    fn with_max_remaining(src: &mut T, max_remaining: u64) -> BoxIter<'_, T> {
        BoxIter { src, max_remaining }
    }

    fn next_box(&mut self) -> Result<Option<BMFFBox<'_, T>>> {
        let r = read_box_header(self.src);
        match r {
            Ok(h) => {
                let claimed = h.size - h.offset;
                // Clamp the Take limit so that allocations based on
                // bytes_left() cannot exceed the actual data available.
                let clamped = claimed.min(self.max_remaining);
                // Decrease our remaining budget by the clamped content
                // size plus the header bytes already consumed.
                self.max_remaining = self.max_remaining.saturating_sub(clamped.saturating_add(h.offset));
                Ok(Some(BMFFBox {
                    head: h,
                    content: self.src.take(clamped),
                }))
            }
            Err(Error::UnexpectedEOF) => Ok(None),
            Err(e) => Err(e),
        }
    }
}

impl<T: Read> Read for BMFFBox<'_, T> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.content.read(buf)
    }
}

impl<T: Offset> Offset for BMFFBox<'_, T> {
    fn offset(&self) -> u64 {
        self.content.get_ref().offset()
    }
}

impl<T: Read> BMFFBox<'_, T> {
    fn bytes_left(&self) -> u64 {
        self.content.limit()
    }

    const fn get_header(&self) -> &BoxHeader {
        &self.head
    }

    fn box_iter(&mut self) -> BoxIter<'_, Self> {
        BoxIter::with_max_remaining(self, self.bytes_left())
    }
}

impl<T> Drop for BMFFBox<'_, T> {
    fn drop(&mut self) {
        if self.content.limit() > 0 {
            let name: FourCC = From::from(self.head.name);
            debug!("Dropping {} bytes in '{}'", self.content.limit(), name);
        }
    }
}

/// Read and parse a box header.
///
/// Call this first to determine the type of a particular mp4 box
/// and its length. Used internally for dispatching to specific
/// parsers for the internal content, or to get the length to
/// skip unknown or uninteresting boxes.
///
/// See ISO 14496-12:2015 § 4.2
fn read_box_header<T: ReadBytesExt>(src: &mut T) -> Result<BoxHeader> {
    let size32 = be_u32(src)?;
    let name = BoxType::from(be_u32(src)?);
    let size = match size32 {
        // valid only for top-level box and indicates it's the last box in the file.  usually mdat.
        0 => {
            // Size=0 means box extends to EOF (ISOBMFF spec allows this for last box)
            u64::MAX
        },
        1 => {
            let size64 = be_u64(src)?;
            if size64 < BoxHeader::MIN_LARGE_SIZE {
                return Err(Error::InvalidData("malformed wide size"));
            }
            size64
        },
        _ => {
            if u64::from(size32) < BoxHeader::MIN_SIZE {
                return Err(Error::InvalidData("malformed size"));
            }
            u64::from(size32)
        },
    };
    let mut offset = match size32 {
        1 => BoxHeader::MIN_LARGE_SIZE,
        _ => BoxHeader::MIN_SIZE,
    };
    let uuid = if name == BoxType::UuidBox {
        if size >= offset + 16 {
            let mut buffer = [0u8; 16];
            let count = src.read(&mut buffer)?;
            offset += count.to_u64();
            if count == 16 {
                Some(buffer)
            } else {
                debug!("malformed uuid (short read), skipping");
                None
            }
        } else {
            debug!("malformed uuid, skipping");
            None
        }
    } else {
        None
    };
    if offset > size {
        return Err(Error::InvalidData("box header offset exceeds size"));
    }
    Ok(BoxHeader { name, size, offset, uuid })
}

/// Parse the extra header fields for a full box.
fn read_fullbox_extra<T: ReadBytesExt>(src: &mut T) -> Result<(u8, u32)> {
    let version = src.read_u8()?;
    let flags_a = src.read_u8()?;
    let flags_b = src.read_u8()?;
    let flags_c = src.read_u8()?;
    Ok((
        version,
        u32::from(flags_a) << 16 | u32::from(flags_b) << 8 | u32::from(flags_c),
    ))
}

// Parse the extra fields for a full box whose flag fields must be zero.
fn read_fullbox_version_no_flags<T: ReadBytesExt>(src: &mut T, options: &ParseOptions) -> Result<u8> {
    let (version, flags) = read_fullbox_extra(src)?;

    if flags != 0 && !options.lenient {
        return Err(Error::Unsupported("expected flags to be 0"));
    }

    Ok(version)
}

/// Skip over the entire contents of a box.
fn skip_box_content<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<()> {
    // Skip the contents of unknown chunks.
    let to_skip = {
        let header = src.get_header();
        debug!("{header:?} (skipped)");
        header
            .size
            .checked_sub(header.offset)
            .ok_or(Error::InvalidData("header offset > size"))?
    };
    if to_skip != src.bytes_left() {
        return Err(Error::InvalidData("box content size mismatch"));
    }
    skip(src, to_skip)
}

/// Skip over the remain data of a box.
fn skip_box_remain<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<()> {
    let remain = {
        let header = src.get_header();
        let len = src.bytes_left();
        debug!("remain {len} (skipped) in {header:?}");
        len
    };
    skip(src, remain)
}

struct ResourceTracker<'a> {
    config: &'a DecodeConfig,
    #[cfg(feature = "eager")]
    current_memory: u64,
    #[cfg(feature = "eager")]
    peak_memory: u64,
}

impl<'a> ResourceTracker<'a> {
    fn new(config: &'a DecodeConfig) -> Self {
        Self {
            config,
            #[cfg(feature = "eager")]
            current_memory: 0,
            #[cfg(feature = "eager")]
            peak_memory: 0,
        }
    }

    #[cfg(feature = "eager")]
    fn reserve(&mut self, bytes: u64) -> Result<()> {
        self.current_memory = self.current_memory.saturating_add(bytes);
        self.peak_memory = self.peak_memory.max(self.current_memory);

        if let Some(limit) = self.config.peak_memory_limit
            && self.peak_memory > limit {
                return Err(Error::ResourceLimitExceeded("peak memory limit exceeded"));
            }

        Ok(())
    }

    #[cfg(feature = "eager")]
    fn release(&mut self, bytes: u64) {
        self.current_memory = self.current_memory.saturating_sub(bytes);
    }

    #[cfg(feature = "eager")]
    fn validate_total_megapixels(&self, width: u32, height: u32) -> Result<()> {
        if let Some(limit) = self.config.total_megapixels_limit {
            let megapixels = (width as u64)
                .checked_mul(height as u64)
                .ok_or(Error::InvalidData("dimension overflow"))?
                / 1_000_000;

            if megapixels > limit as u64 {
                return Err(Error::ResourceLimitExceeded("total megapixels limit exceeded"));
            }
        }

        Ok(())
    }

    fn validate_animation_frames(&self, count: u32) -> Result<()> {
        if let Some(limit) = self.config.max_animation_frames
            && count > limit {
                return Err(Error::ResourceLimitExceeded("animation frame count limit exceeded"));
            }

        Ok(())
    }

    fn validate_grid_tiles(&self, count: u32) -> Result<()> {
        if let Some(limit) = self.config.max_grid_tiles
            && count > limit {
                return Err(Error::ResourceLimitExceeded("grid tile count limit exceeded"));
            }

        Ok(())
    }
}

/// Read the contents of an AVIF file with resource limits and cancellation support
///
/// This is the primary parsing function with full control over resource limits
/// and cooperative cancellation via the [`Stop`] trait.
///
/// # Arguments
///
/// * `f` - Reader for the AVIF file
/// * `config` - Resource limits and parsing options
/// * `stop` - Cancellation token (use [`Unstoppable`] if not needed)
#[cfg(feature = "eager")]
#[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader_with_config()` instead")]
#[allow(deprecated)]
pub fn read_avif_with_config<T: Read>(
    f: &mut T,
    config: &DecodeConfig,
    stop: &dyn Stop,
) -> Result<AvifData> {
    let mut tracker = ResourceTracker::new(config);
    let mut f = OffsetReader::new(f);

    let mut iter = BoxIter::new(&mut f);

    // 'ftyp' box must occur first; see ISO 14496-12:2015 § 4.3.1
    let (major_brand, compatible_brands) = if let Some(mut b) = iter.next_box()? {
        if b.head.name == BoxType::FileTypeBox {
            let ftyp = read_ftyp(&mut b)?;
            // Accept both 'avif' (single-frame) and 'avis' (animated) brands
            if ftyp.major_brand != b"avif" && ftyp.major_brand != b"avis" {
                warn!("major_brand: {}", ftyp.major_brand);
                return Err(Error::InvalidData("ftyp must be 'avif' or 'avis'"));
            }
            let major = ftyp.major_brand.value;
            let compat = ftyp.compatible_brands.iter().map(|b| b.value).collect();
            (major, compat)
        } else {
            return Err(Error::InvalidData("'ftyp' box must occur first"));
        }
    } else {
        return Err(Error::InvalidData("'ftyp' box must occur first"));
    };

    let mut meta = None;
    let mut mdats = TryVec::new();
    let mut animation_data: Option<ParsedAnimationData> = None;

    let parse_opts = ParseOptions { lenient: config.lenient };

    while let Some(mut b) = iter.next_box()? {
        stop.check()?;

        match b.head.name {
            BoxType::MetadataBox => {
                if meta.is_some() {
                    return Err(Error::InvalidData("There should be zero or one meta boxes per ISO 14496-12:2015 § 8.11.1.1"));
                }
                meta = Some(read_avif_meta(&mut b, &parse_opts)?);
            },
            BoxType::MovieBox => {
                let tracks = read_moov(&mut b)?;
                if !tracks.is_empty() {
                    animation_data = Some(associate_tracks(tracks)?);
                }
            },
            BoxType::MediaDataBox => {
                if b.bytes_left() > 0 {
                    let offset = b.offset();
                    let size = b.bytes_left();
                    tracker.reserve(size)?;
                    let data = b.read_into_try_vec()?;
                    tracker.release(size);
                    mdats.push(MediaDataBox { offset, data })?;
                }
            },
            _ => skip_box_content(&mut b)?,
        }

        check_parser_state(&b.head, &b.content)?;
    }

    // meta is required for still images; pure sequences can have only moov+mdat
    if meta.is_none() && animation_data.is_none() {
        return Err(Error::InvalidData("missing meta"));
    }
    let Some(meta) = meta else {
        // Pure sequence: return minimal AvifData with no items
        return Ok(AvifData {
            ..Default::default()
        });
    };

    // Check if primary item is a grid (tiled image)
    let is_grid = meta
        .item_infos
        .iter()
        .find(|x| x.item_id == meta.primary_item_id)
        .is_some_and(|info| {
            let is_g = info.item_type == b"grid";
            if is_g {
                log::debug!("Grid image detected: primary_item_id={}", meta.primary_item_id);
            }
            is_g
        });

    // Extract grid configuration if this is a grid image
    let mut grid_config = if is_grid {
        meta.properties
            .iter()
            .find(|prop| {
                prop.item_id == meta.primary_item_id
                    && matches!(prop.property, ItemProperty::ImageGrid(_))
            })
            .and_then(|prop| match &prop.property {
                ItemProperty::ImageGrid(config) => {
                    log::debug!("Grid: found explicit ImageGrid property: {:?}", config);
                    Some(config.clone())
                },
                _ => None,
            })
    } else {
        None
    };

    // Find tile item IDs if this is a grid
    let tile_item_ids: TryVec<u32> = if is_grid {
        // Collect tiles with their reference index
        let mut tiles_with_index: TryVec<(u32, u16)> = TryVec::new();
        for iref in meta.item_references.iter() {
            // Grid items reference tiles via "dimg" (derived image) type
            if iref.from_item_id == meta.primary_item_id && iref.item_type == b"dimg" {
                tiles_with_index.push((iref.to_item_id, iref.reference_index))?;
            }
        }

        // Validate tile count
        tracker.validate_grid_tiles(tiles_with_index.len() as u32)?;

        // Sort tiles by reference_index to get correct grid order
        tiles_with_index.sort_by_key(|&(_, idx)| idx);

        // Extract just the IDs in sorted order
        let mut ids = TryVec::new();
        for (tile_id, _) in tiles_with_index.iter() {
            ids.push(*tile_id)?;
        }

        // No logging here - too verbose for production

        // If no ImageGrid property found, calculate grid layout from ispe dimensions
        if grid_config.is_none() && !ids.is_empty() {
            // Try to calculate grid dimensions from ispe properties
            let grid_dims = meta.properties.iter()
                .find(|p| p.item_id == meta.primary_item_id)
                .and_then(|p| match &p.property {
                    ItemProperty::ImageSpatialExtents(e) => Some(e),
                    _ => None,
                });

            let tile_dims = ids.first().and_then(|&tile_id| {
                meta.properties.iter()
                    .find(|p| p.item_id == tile_id)
                    .and_then(|p| match &p.property {
                        ItemProperty::ImageSpatialExtents(e) => Some(e),
                        _ => None,
                    })
            });

            if let (Some(grid), Some(tile)) = (grid_dims, tile_dims) {
                // Validate grid output dimensions
                tracker.validate_total_megapixels(grid.width, grid.height)?;

                // Validate tile dimensions are non-zero (already validated in read_ispe, but defensive)
                if tile.width == 0 || tile.height == 0 {
                    log::warn!("Grid: tile has zero dimensions, using fallback");
                } else if grid.width % tile.width == 0 && grid.height % tile.height == 0 {
                    // Calculate grid layout: grid_dims ÷ tile_dims
                    let columns = grid.width / tile.width;
                    let rows = grid.height / tile.height;

                    // Validate grid dimensions fit in u8 (max 255×255 grid)
                    if columns > 255 || rows > 255 {
                        log::warn!("Grid: calculated dimensions {}×{} exceed 255, using fallback", rows, columns);
                    } else {
                        log::debug!("Grid: calculated {}×{} layout from ispe dimensions", rows, columns);
                        grid_config = Some(GridConfig {
                            rows: rows as u8,
                            columns: columns as u8,
                            output_width: grid.width,
                            output_height: grid.height,
                        });
                    }
                } else {
                    log::warn!("Grid: dimension mismatch - grid {}×{} not evenly divisible by tile {}×{}, using fallback",
                              grid.width, grid.height, tile.width, tile.height);
                }
            }

            // Fallback: if calculation failed or ispe not available, use N×1 inference
            if grid_config.is_none() {
                log::debug!("Grid: using fallback {}×1 layout inference", ids.len());
                grid_config = Some(GridConfig {
                    rows: ids.len() as u8,  // Changed: vertical stack
                    columns: 1,              // Changed: single column
                    output_width: 0,  // Will be calculated from tiles
                    output_height: 0, // Will be calculated from tiles
                });
            }
        }

        ids
    } else {
        TryVec::new()
    };

    let alpha_item_id = meta
        .item_references
        .iter()
        // Auxiliary image for the primary image
        .filter(|iref| {
            iref.to_item_id == meta.primary_item_id
                && iref.from_item_id != meta.primary_item_id
                && iref.item_type == b"auxl"
        })
        .map(|iref| iref.from_item_id)
        // which has the alpha property
        .find(|&item_id| {
            meta.properties.iter().any(|prop| {
                prop.item_id == item_id
                    && match &prop.property {
                        ItemProperty::AuxiliaryType(urn) => {
                            urn.type_subtype().0 == b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha"
                        }
                        _ => false,
                    }
            })
        });

    // Extract properties for the primary item
    macro_rules! find_prop {
        ($variant:ident) => {
            meta.properties.iter().find_map(|p| {
                if p.item_id == meta.primary_item_id {
                    match &p.property {
                        ItemProperty::$variant(c) => Some(c.clone()),
                        _ => None,
                    }
                } else {
                    None
                }
            })
        };
    }

    let av1_config = find_prop!(AV1Config);
    let color_info = find_prop!(ColorInformation);
    let rotation = find_prop!(Rotation);
    let mirror = find_prop!(Mirror);
    let clean_aperture = find_prop!(CleanAperture);
    let pixel_aspect_ratio = find_prop!(PixelAspectRatio);
    let content_light_level = find_prop!(ContentLightLevel);
    let mastering_display = find_prop!(MasteringDisplayColourVolume);
    let content_colour_volume = find_prop!(ContentColourVolume);
    let ambient_viewing = find_prop!(AmbientViewingEnvironment);
    let operating_point = find_prop!(OperatingPointSelector);
    let layer_selector = find_prop!(LayerSelector);
    let layered_image_indexing = find_prop!(AV1LayeredImageIndexing);

    let mut context = AvifData {
        premultiplied_alpha: alpha_item_id.is_some_and(|alpha_item_id| {
            meta.item_references.iter().any(|iref| {
                iref.from_item_id == meta.primary_item_id
                    && iref.to_item_id == alpha_item_id
                    && iref.item_type == b"prem"
            })
        }),
        av1_config,
        color_info,
        rotation,
        mirror,
        clean_aperture,
        pixel_aspect_ratio,
        content_light_level,
        mastering_display,
        content_colour_volume,
        ambient_viewing,
        operating_point,
        layer_selector,
        layered_image_indexing,
        major_brand,
        compatible_brands,
        ..Default::default()
    };

    // Helper to extract item data from either mdat or idat
    let mut extract_item_data = |loc: &ItemLocationBoxItem, buf: &mut TryVec<u8>| -> Result<()> {
        match loc.construction_method {
            ConstructionMethod::File => {
                for extent in loc.extents.iter() {
                    let mut found = false;
                    for mdat in mdats.iter_mut() {
                        if mdat.matches_extent(&extent.extent_range) {
                            buf.append(&mut mdat.data)?;
                            found = true;
                            break;
                        } else if mdat.contains_extent(&extent.extent_range) {
                            mdat.read_extent(&extent.extent_range, buf)?;
                            found = true;
                            break;
                        }
                    }
                    if !found {
                        return Err(Error::InvalidData("iloc contains an extent that is not in mdat"));
                    }
                }
                Ok(())
            },
            ConstructionMethod::Idat => {
                let idat_data = meta.idat.as_ref().ok_or(Error::InvalidData("idat box missing but construction_method is Idat"))?;
                for extent in loc.extents.iter() {
                    match &extent.extent_range {
                        ExtentRange::WithLength(range) => {
                            let start = usize::try_from(range.start).map_err(|_| Error::InvalidData("extent start too large"))?;
                            let end = usize::try_from(range.end).map_err(|_| Error::InvalidData("extent end too large"))?;
                            if end > idat_data.len() {
                                return Err(Error::InvalidData("extent exceeds idat size"));
                            }
                            buf.extend_from_slice(&idat_data[start..end]).map_err(|_| Error::OutOfMemory)?;
                        },
                        ExtentRange::ToEnd(range) => {
                            let start = usize::try_from(range.start).map_err(|_| Error::InvalidData("extent start too large"))?;
                            if start >= idat_data.len() {
                                return Err(Error::InvalidData("extent start exceeds idat size"));
                            }
                            buf.extend_from_slice(&idat_data[start..]).map_err(|_| Error::OutOfMemory)?;
                        },
                    }
                }
                Ok(())
            },
            ConstructionMethod::Item => {
                Err(Error::Unsupported("construction_method 'item' not supported"))
            },
        }
    };

    // load data of relevant items
    // For grid images, we need to load tiles in the order specified by iref
    if is_grid {
        // Extract each tile in order
        for (idx, &tile_id) in tile_item_ids.iter().enumerate() {
            if idx % 16 == 0 {
                stop.check()?;
            }

            let mut tile_data = TryVec::new();

            if let Some(loc) = meta.iloc_items.iter().find(|loc| loc.item_id == tile_id) {
                extract_item_data(loc, &mut tile_data)?;
            } else {
                return Err(Error::InvalidData("grid tile not found in iloc"));
            }

            context.grid_tiles.push(tile_data)?;
        }

        // Set grid_config in context
        context.grid_config = grid_config;
    } else {
        // Standard single-frame AVIF: load primary_item and optional alpha_item
        for loc in meta.iloc_items.iter() {
            let item_data = if loc.item_id == meta.primary_item_id {
                &mut context.primary_item
            } else if Some(loc.item_id) == alpha_item_id {
                context.alpha_item.get_or_insert_with(TryVec::new)
            } else {
                continue;
            };

            extract_item_data(loc, item_data)?;
        }
    }

    // Extract EXIF and XMP items linked via cdsc references to the primary item
    for iref in meta.item_references.iter() {
        if iref.to_item_id != meta.primary_item_id || iref.item_type != b"cdsc" {
            continue;
        }
        let desc_item_id = iref.from_item_id;
        let Some(info) = meta.item_infos.iter().find(|i| i.item_id == desc_item_id) else {
            continue;
        };
        if info.item_type == b"Exif" {
            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == desc_item_id) {
                let mut raw = TryVec::new();
                extract_item_data(loc, &mut raw)?;
                // AVIF EXIF items start with a 4-byte big-endian offset to the TIFF header
                if raw.len() > 4 {
                    let offset = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
                    let start = 4 + offset;
                    if start < raw.len() {
                        let mut exif = TryVec::new();
                        exif.extend_from_slice(&raw[start..])?;
                        context.exif = Some(exif);
                    }
                }
            }
        } else if info.item_type == b"mime"
            && let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == desc_item_id)
        {
            let mut xmp = TryVec::new();
            extract_item_data(loc, &mut xmp)?;
            context.xmp = Some(xmp);
        }
    }

    // Extract gain map (tmap derived image item)
    if let Some(tmap_info) = meta.item_infos.iter().find(|info| info.item_type == b"tmap") {
        let tmap_id = tmap_info.item_id;

        let mut inputs: TryVec<(u32, u16)> = TryVec::new();
        for iref in meta.item_references.iter() {
            if iref.from_item_id == tmap_id && iref.item_type == b"dimg" {
                inputs.push((iref.to_item_id, iref.reference_index))?;
            }
        }
        inputs.sort_by_key(|&(_, idx)| idx);

        if inputs.len() >= 2 && inputs[0].0 == meta.primary_item_id {
            let gmap_item_id = inputs[1].0;

            // Read tmap item payload
            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == tmap_id) {
                let mut tmap_data = TryVec::new();
                extract_item_data(loc, &mut tmap_data)?;
                if let Ok(metadata) = parse_tone_map_image(&tmap_data) {
                    context.gain_map_metadata = Some(metadata);
                }
            }

            // Read gain map image data
            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == gmap_item_id) {
                let mut gmap_data = TryVec::new();
                extract_item_data(loc, &mut gmap_data)?;
                context.gain_map_item = Some(gmap_data);
            }

            // Get alternate color info from tmap item's properties
            context.gain_map_color_info = meta.properties.iter().find_map(|p| {
                if p.item_id == tmap_id {
                    match &p.property {
                        ItemProperty::ColorInformation(c) => Some(c.clone()),
                        _ => None,
                    }
                } else {
                    None
                }
            });
        }
    }

    // Extract depth auxiliary image
    {
        let depth_item_id = meta
            .item_references
            .iter()
            .filter(|iref| {
                iref.to_item_id == meta.primary_item_id
                    && iref.from_item_id != meta.primary_item_id
                    && iref.item_type == b"auxl"
            })
            .map(|iref| iref.from_item_id)
            .find(|&item_id| {
                if alpha_item_id == Some(item_id) {
                    return false;
                }
                meta.properties.iter().any(|prop| {
                    prop.item_id == item_id
                        && match &prop.property {
                            ItemProperty::AuxiliaryType(urn) => {
                                is_depth_auxiliary_urn(urn.type_subtype().0)
                            }
                            _ => false,
                        }
                })
            });

        if let Some(depth_id) = depth_item_id {
            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == depth_id) {
                let mut depth_data = TryVec::new();
                extract_item_data(loc, &mut depth_data)?;
                context.depth_item = Some(depth_data);
            }
            // Get dimensions from ispe
            if let Some((w, h)) = meta.properties.iter().find_map(|p| {
                if p.item_id == depth_id {
                    match &p.property {
                        ItemProperty::ImageSpatialExtents(e) => Some((e.width, e.height)),
                        _ => None,
                    }
                } else {
                    None
                }
            }) {
                context.depth_width = w;
                context.depth_height = h;
            }
            // Get av1C
            context.depth_av1_config = meta.properties.iter().find_map(|p| {
                if p.item_id == depth_id {
                    match &p.property {
                        ItemProperty::AV1Config(c) => Some(c.clone()),
                        _ => None,
                    }
                } else {
                    None
                }
            });
            // Get colr
            context.depth_color_info = meta.properties.iter().find_map(|p| {
                if p.item_id == depth_id {
                    match &p.property {
                        ItemProperty::ColorInformation(c) => Some(c.clone()),
                        _ => None,
                    }
                } else {
                    None
                }
            });
        }
    }

    // Extract animation frames if this is an animated AVIF
    if let Some(anim) = animation_data {
        let frame_count = anim.color_sample_table.sample_sizes.len() as u32;
        tracker.validate_animation_frames(frame_count)?;

        log::debug!("Animation: extracting frames (media_timescale={})", anim.color_timescale);
        match extract_animation_frames(&anim.color_sample_table, anim.color_timescale, &mut mdats) {
            Ok(frames) => {
                if !frames.is_empty() {
                    log::debug!("Animation: extracted {} frames", frames.len());
                    context.animation = Some(AnimationConfig {
                        loop_count: anim.loop_count,
                        frames,
                    });
                }
            }
            Err(e) => {
                log::warn!("Animation: failed to extract frames: {}", e);
            }
        }
    }

    Ok(context)
}

/// Read the contents of an AVIF file with custom parsing options
///
/// Uses unlimited resource limits for backwards compatibility.
///
/// # Arguments
///
/// * `f` - Reader for the AVIF file
/// * `options` - Parsing options (e.g., lenient mode)
#[cfg(feature = "eager")]
#[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader_with_config()` with `DecodeConfig::lenient()` instead")]
#[allow(deprecated)]
pub fn read_avif_with_options<T: Read>(f: &mut T, options: &ParseOptions) -> Result<AvifData> {
    let config = DecodeConfig::unlimited().lenient(options.lenient);
    read_avif_with_config(f, &config, &Unstoppable)
}

/// Read the contents of an AVIF file
///
/// Metadata is accumulated and returned in [`AvifData`] struct.
/// Uses strict validation and unlimited resource limits by default.
///
/// For resource limits, use [`read_avif_with_config`].
/// For lenient parsing, use [`read_avif_with_options`].
#[cfg(feature = "eager")]
#[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader()` instead")]
#[allow(deprecated)]
pub fn read_avif<T: Read>(f: &mut T) -> Result<AvifData> {
    read_avif_with_options(f, &ParseOptions::default())
}

/// An entity group from a GroupsListBox (`grpl`).
///
/// See ISO 14496-12:2024 § 8.15.3.
#[allow(dead_code)] // Parsed for future altr group support
struct EntityGroup {
    group_type: FourCC,
    group_id: u32,
    entity_ids: TryVec<u32>,
}

/// Parse a GroupsListBox (`grpl`).
///
/// Each child box is an EntityToGroupBox with a grouping type given by its box type.
/// See ISO 14496-12:2024 § 8.15.3.
fn read_grpl<T: Read + Offset>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<EntityGroup>> {
    let mut groups = TryVec::new();
    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        let group_type = FourCC::from(u32::from(b.head.name));
        // Read version and flags (not validated per spec flexibility)
        let _version = b.read_u8()?;
        let mut flags_buf = [0u8; 3];
        b.read_exact(&mut flags_buf)?;

        let group_id = be_u32(&mut b)?;
        let num_entities = be_u32(&mut b)?;
        // Each entity_id is 4 bytes
        if (num_entities as u64) * 4 > b.bytes_left() {
            return Err(Error::InvalidData(
                "grpl num_entities exceeds remaining box bytes",
            ));
        }

        let mut entity_ids = TryVec::new();
        for _ in 0..num_entities {
            entity_ids.push(be_u32(&mut b)?)?;
        }

        groups.push(EntityGroup {
            group_type,
            group_id,
            entity_ids,
        })?;

        skip_box_remain(&mut b)?;
        check_parser_state(&b.head, &b.content)?;
    }
    Ok(groups)
}

/// Parse a ToneMapImage (`tmap`) item payload into gain map metadata.
///
/// See ISO 21496-1:2025 for the payload format.
fn parse_tone_map_image(data: &[u8]) -> Result<GainMapMetadata> {
    let mut cursor = std::io::Cursor::new(data);

    // version (u8) — must be 0
    let version = cursor.read_u8()?;
    if version != 0 {
        return Err(Error::Unsupported("tmap version"));
    }

    // minimum_version (u16 BE) — must be 0
    let minimum_version = be_u16(&mut cursor)?;
    if minimum_version > 0 {
        return Err(Error::Unsupported("tmap minimum version"));
    }

    // writer_version (u16 BE) — informational, must be >= minimum_version
    let writer_version = be_u16(&mut cursor)?;
    if writer_version < minimum_version {
        return Err(Error::InvalidData("tmap writer_version < minimum_version"));
    }

    // Flags byte: is_multichannel (bit 7), use_base_colour_space (bit 6), reserved (bits 0-5)
    let flags = cursor.read_u8()?;
    let is_multichannel = (flags & 0x80) != 0;
    let use_base_colour_space = (flags & 0x40) != 0;

    // base_hdr_headroom and alternate_hdr_headroom
    let base_hdr_headroom_n = be_u32(&mut cursor)?;
    let base_hdr_headroom_d = be_u32(&mut cursor)?;
    let alternate_hdr_headroom_n = be_u32(&mut cursor)?;
    let alternate_hdr_headroom_d = be_u32(&mut cursor)?;

    let channel_count = if is_multichannel { 3 } else { 1 };
    let mut channels = [GainMapChannel {
        gain_map_min_n: 0, gain_map_min_d: 0,
        gain_map_max_n: 0, gain_map_max_d: 0,
        gamma_n: 0, gamma_d: 0,
        base_offset_n: 0, base_offset_d: 0,
        alternate_offset_n: 0, alternate_offset_d: 0,
    }; 3];

    for ch in channels.iter_mut().take(channel_count) {
        ch.gain_map_min_n = be_i32(&mut cursor)?;
        ch.gain_map_min_d = be_u32(&mut cursor)?;
        ch.gain_map_max_n = be_i32(&mut cursor)?;
        ch.gain_map_max_d = be_u32(&mut cursor)?;
        ch.gamma_n = be_u32(&mut cursor)?;
        ch.gamma_d = be_u32(&mut cursor)?;
        ch.base_offset_n = be_i32(&mut cursor)?;
        ch.base_offset_d = be_u32(&mut cursor)?;
        ch.alternate_offset_n = be_i32(&mut cursor)?;
        ch.alternate_offset_d = be_u32(&mut cursor)?;
    }

    // Copy channel 0 to channels 1 and 2 if single-channel
    if !is_multichannel {
        channels[1] = channels[0];
        channels[2] = channels[0];
    }

    Ok(GainMapMetadata {
        is_multichannel,
        use_base_colour_space,
        base_hdr_headroom_n,
        base_hdr_headroom_d,
        alternate_hdr_headroom_n,
        alternate_hdr_headroom_d,
        channels,
    })
}

/// Parse a metadata box in the context of an AVIF
/// Currently requires the primary item to be an av01 item type and generates
/// an error otherwise.
/// See ISO 14496-12:2015 § 8.11.1
fn read_avif_meta<T: Read + Offset>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<AvifInternalMeta> {
    let version = read_fullbox_version_no_flags(src, options)?;

    if version != 0 {
        return Err(Error::Unsupported("unsupported meta version"));
    }

    let mut primary_item_id = None;
    let mut item_infos = None;
    let mut iloc_items = None;
    let mut item_references = TryVec::new();
    let mut properties = TryVec::new();
    let mut idat = None;
    let mut entity_groups = TryVec::new();

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        match b.head.name {
            BoxType::ItemInfoBox => {
                if item_infos.is_some() {
                    return Err(Error::InvalidData("There should be zero or one iinf boxes per ISO 14496-12:2015 § 8.11.6.1"));
                }
                item_infos = Some(read_iinf(&mut b, options)?);
            },
            BoxType::ItemLocationBox => {
                if iloc_items.is_some() {
                    return Err(Error::InvalidData("There should be zero or one iloc boxes per ISO 14496-12:2015 § 8.11.3.1"));
                }
                iloc_items = Some(read_iloc(&mut b, options)?);
            },
            BoxType::PrimaryItemBox => {
                if primary_item_id.is_some() {
                    return Err(Error::InvalidData("There should be zero or one iloc boxes per ISO 14496-12:2015 § 8.11.4.1"));
                }
                primary_item_id = Some(read_pitm(&mut b, options)?);
            },
            BoxType::ImageReferenceBox => {
                item_references.append(&mut read_iref(&mut b, options)?)?;
            },
            BoxType::ImagePropertiesBox => {
                properties = read_iprp(&mut b, options)?;
            },
            BoxType::ItemDataBox => {
                if idat.is_some() {
                    return Err(Error::InvalidData("There should be zero or one idat boxes"));
                }
                idat = Some(b.read_into_try_vec()?);
            },
            BoxType::GroupsListBox => {
                entity_groups.append(&mut read_grpl(&mut b)?)?;
            },
            BoxType::HandlerBox => {
                let hdlr = read_hdlr(&mut b)?;
                if hdlr.handler_type != b"pict" {
                    warn!("hdlr handler_type: {}", hdlr.handler_type);
                    return Err(Error::InvalidData("meta handler_type must be 'pict' for AVIF"));
                }
            },
            _ => skip_box_content(&mut b)?,
        }

        check_parser_state(&b.head, &b.content)?;
    }

    let primary_item_id = primary_item_id.ok_or(Error::InvalidData("Required pitm box not present in meta box"))?;

    let item_infos = item_infos.ok_or(Error::InvalidData("iinf missing"))?;

    if let Some(item_info) = item_infos.iter().find(|x| x.item_id == primary_item_id) {
        // Allow both "av01" (standard single-frame) and "grid" (tiled) types
        if item_info.item_type != b"av01" && item_info.item_type != b"grid" {
            warn!("primary_item_id type: {}", item_info.item_type);
            return Err(Error::InvalidData("primary_item_id type is not av01 or grid"));
        }
    } else {
        return Err(Error::InvalidData("primary_item_id not present in iinf box"));
    }

    Ok(AvifInternalMeta {
        properties,
        item_references,
        primary_item_id,
        iloc_items: iloc_items.ok_or(Error::InvalidData("iloc missing"))?,
        item_infos,
        idat,
        entity_groups,
    })
}

/// Parse a Handler Reference Box
/// See ISO 14496-12:2015 § 8.4.3
fn read_hdlr<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<HandlerBox> {
    let (_version, _flags) = read_fullbox_extra(src)?;
    // pre_defined (4 bytes)
    skip(src, 4)?;
    // handler_type (4 bytes)
    let handler_type = be_u32(src)?;
    // reserved (3 × 4 bytes) + name (variable) — skip the rest
    skip_box_remain(src)?;
    Ok(HandlerBox {
        handler_type: FourCC::from(handler_type),
    })
}

/// Parse a Primary Item Box
/// See ISO 14496-12:2015 § 8.11.4
fn read_pitm<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<u32> {
    let version = read_fullbox_version_no_flags(src, options)?;

    let item_id = match version {
        0 => be_u16(src)?.into(),
        1 => be_u32(src)?,
        _ => return Err(Error::Unsupported("unsupported pitm version")),
    };

    Ok(item_id)
}

/// Parse an Item Information Box
/// See ISO 14496-12:2015 § 8.11.6
fn read_iinf<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<ItemInfoEntry>> {
    let version = read_fullbox_version_no_flags(src, options)?;

    match version {
        0 | 1 => (),
        _ => return Err(Error::Unsupported("unsupported iinf version")),
    }

    let entry_count = if version == 0 {
        be_u16(src)?.to_usize()
    } else {
        be_u32(src)?.to_usize()
    };
    // Cap pre-allocation: entry_count is untrusted, actual items come from box_iter
    let mut item_infos = TryVec::with_capacity(entry_count.min(4096))?;

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        if b.head.name != BoxType::ItemInfoEntry {
            return Err(Error::InvalidData("iinf box should contain only infe boxes"));
        }

        item_infos.push(read_infe(&mut b)?)?;

        check_parser_state(&b.head, &b.content)?;
    }

    Ok(item_infos)
}

/// Parse an Item Info Entry
/// See ISO 14496-12:2015 § 8.11.6.2
fn read_infe<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ItemInfoEntry> {
    // According to the standard, it seems the flags field should be 0, but
    // at least one sample AVIF image has a nonzero value.
    let (version, _) = read_fullbox_extra(src)?;

    // mif1 brand (see ISO 23008-12:2017 § 10.2.1) only requires v2 and 3
    let item_id = match version {
        2 => be_u16(src)?.into(),
        3 => be_u32(src)?,
        _ => return Err(Error::Unsupported("unsupported version in 'infe' box")),
    };

    let item_protection_index = be_u16(src)?;

    if item_protection_index != 0 {
        return Err(Error::Unsupported("protected items (infe.item_protection_index != 0) are not supported"));
    }

    let item_type = FourCC::from(be_u32(src)?);
    debug!("infe item_id {item_id} item_type: {item_type}");

    // There are some additional fields here, but they're not of interest to us
    skip_box_remain(src)?;

    Ok(ItemInfoEntry { item_id, item_type })
}

fn read_iref<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<SingleItemTypeReferenceBox>> {
    let mut item_references = TryVec::new();
    let version = read_fullbox_version_no_flags(src, options)?;
    if version > 1 {
        return Err(Error::Unsupported("iref version"));
    }

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        let from_item_id = if version == 0 {
            be_u16(&mut b)?.into()
        } else {
            be_u32(&mut b)?
        };
        let reference_count = be_u16(&mut b)?;
        // Each to_item_id is 2 bytes (version 0) or 4 bytes (version 1)
        let bytes_per_ref: u64 = if version == 0 { 2 } else { 4 };
        if (reference_count as u64) * bytes_per_ref > b.bytes_left() {
            return Err(Error::InvalidData(
                "iref reference_count exceeds remaining box bytes",
            ));
        }
        for reference_index in 0..reference_count {
            let to_item_id = if version == 0 {
                be_u16(&mut b)?.into()
            } else {
                be_u32(&mut b)?
            };
            if from_item_id == to_item_id {
                return Err(Error::InvalidData("from_item_id and to_item_id must be different"));
            }
            item_references.push(SingleItemTypeReferenceBox {
                item_type: b.head.name.into(),
                from_item_id,
                to_item_id,
                reference_index,
            })?;
        }
        check_parser_state(&b.head, &b.content)?;
    }
    Ok(item_references)
}

/// Properties that MUST be marked essential when associated with an item.
/// See AVIF § 2.3.2.1.1 (a1op), HEIF § 6.5.11.1 (lsel), MIAF § 7.3.9 (clap, irot, imir).
const MUST_BE_ESSENTIAL: &[&[u8; 4]] = &[b"a1op", b"lsel", b"clap", b"irot", b"imir"];

/// Properties that MUST NOT be marked essential when associated with an item.
/// See AVIF § 2.3.2.3.2 (a1lx).
const MUST_NOT_BE_ESSENTIAL: &[&[u8; 4]] = &[b"a1lx"];

fn read_iprp<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<AssociatedProperty>> {
    let mut iter = src.box_iter();
    let mut properties = TryVec::new();
    let mut associations = TryVec::new();

    while let Some(mut b) = iter.next_box()? {
        match b.head.name {
            BoxType::ItemPropertyContainerBox => {
                properties = read_ipco(&mut b, options)?;
            },
            BoxType::ItemPropertyAssociationBox => {
                associations = read_ipma(&mut b)?;
            },
            _ => return Err(Error::InvalidData("unexpected ipco child")),
        }
    }

    let mut associated = TryVec::new();
    for a in associations {
        let index = match a.property_index {
            0 => {
                // property_index 0 means no association; essential must also be 0
                if a.essential {
                    return Err(Error::InvalidData(
                        "ipma property_index 0 must not be marked essential",
                    ));
                }
                continue;
            }
            x => x as usize - 1,
        };

        let Some(entry) = properties.get(index) else {
            continue;
        };

        let is_supported = entry.property != ItemProperty::Unsupported;
        let fourcc_bytes = &entry.fourcc.value;

        if is_supported {
            // Validate essential flag for known property types
            if a.essential && MUST_NOT_BE_ESSENTIAL.contains(&fourcc_bytes) {
                warn!("item {} has {} marked essential (spec forbids it)", a.item_id, entry.fourcc);
                if !options.lenient {
                    return Err(Error::InvalidData(
                        "property must not be marked essential",
                    ));
                }
            }
            if !a.essential && MUST_BE_ESSENTIAL.contains(&fourcc_bytes) {
                warn!("item {} has {} not marked essential (spec requires it)", a.item_id, entry.fourcc);
                if !options.lenient {
                    return Err(Error::InvalidData(
                        "property must be marked essential",
                    ));
                }
            }

            associated.push(AssociatedProperty {
                item_id: a.item_id,
                property: entry.property.try_clone()?,
            })?;
        } else if a.essential {
            // Unknown property marked essential — this item cannot be correctly processed
            warn!(
                "item {} has unsupported property {} marked essential; item will be unusable",
                a.item_id, entry.fourcc
            );
            if !options.lenient {
                return Err(Error::Unsupported(
                    "unsupported property marked as essential",
                ));
            }
        }
        // Unknown non-essential properties are silently skipped (they're optional)
    }
    Ok(associated)
}

/// Image spatial extents (dimensions)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ImageSpatialExtents {
    pub(crate) width: u32,
    pub(crate) height: u32,
}

#[derive(Debug, PartialEq)]
pub(crate) enum ItemProperty {
    Channels(ArrayVec<u8, 16>),
    AuxiliaryType(AuxiliaryTypeProperty),
    ImageSpatialExtents(ImageSpatialExtents),
    ImageGrid(GridConfig),
    AV1Config(AV1Config),
    ColorInformation(ColorInformation),
    Rotation(ImageRotation),
    Mirror(ImageMirror),
    CleanAperture(CleanAperture),
    PixelAspectRatio(PixelAspectRatio),
    ContentLightLevel(ContentLightLevel),
    MasteringDisplayColourVolume(MasteringDisplayColourVolume),
    ContentColourVolume(ContentColourVolume),
    AmbientViewingEnvironment(AmbientViewingEnvironment),
    OperatingPointSelector(OperatingPointSelector),
    LayerSelector(LayerSelector),
    AV1LayeredImageIndexing(AV1LayeredImageIndexing),
    Unsupported,
}

impl TryClone for ItemProperty {
    fn try_clone(&self) -> Result<Self, TryReserveError> {
        Ok(match self {
            Self::Channels(val) => Self::Channels(val.clone()),
            Self::AuxiliaryType(val) => Self::AuxiliaryType(val.try_clone()?),
            Self::ImageSpatialExtents(val) => Self::ImageSpatialExtents(*val),
            Self::ImageGrid(val) => Self::ImageGrid(val.clone()),
            Self::AV1Config(val) => Self::AV1Config(val.clone()),
            Self::ColorInformation(val) => Self::ColorInformation(val.clone()),
            Self::Rotation(val) => Self::Rotation(*val),
            Self::Mirror(val) => Self::Mirror(*val),
            Self::CleanAperture(val) => Self::CleanAperture(*val),
            Self::PixelAspectRatio(val) => Self::PixelAspectRatio(*val),
            Self::ContentLightLevel(val) => Self::ContentLightLevel(*val),
            Self::MasteringDisplayColourVolume(val) => Self::MasteringDisplayColourVolume(*val),
            Self::ContentColourVolume(val) => Self::ContentColourVolume(*val),
            Self::AmbientViewingEnvironment(val) => Self::AmbientViewingEnvironment(*val),
            Self::OperatingPointSelector(val) => Self::OperatingPointSelector(*val),
            Self::LayerSelector(val) => Self::LayerSelector(*val),
            Self::AV1LayeredImageIndexing(val) => Self::AV1LayeredImageIndexing(*val),
            Self::Unsupported => Self::Unsupported,
        })
    }
}

struct Association {
    item_id: u32,
    essential: bool,
    property_index: u16,
}

pub(crate) struct AssociatedProperty {
    pub item_id: u32,
    pub property: ItemProperty,
}

fn read_ipma<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<Association>> {
    let (version, flags) = read_fullbox_extra(src)?;

    let mut associations = TryVec::new();

    let entry_count = be_u32(src)?;
    // Each entry has at minimum: item_id (2 or 4 bytes) + association_count (1 byte)
    let min_bytes_per_entry: u64 = if version == 0 { 3 } else { 5 };
    if (entry_count as u64) * min_bytes_per_entry > src.bytes_left() {
        return Err(Error::InvalidData(
            "ipma entry_count exceeds remaining box bytes",
        ));
    }
    for _ in 0..entry_count {
        let item_id = if version == 0 {
            be_u16(src)?.into()
        } else {
            be_u32(src)?
        };
        let association_count = src.read_u8()?;
        for _ in 0..association_count {
            let num_association_bytes = if flags & 1 == 1 { 2 } else { 1 };
            let association = &mut [0; 2][..num_association_bytes];
            src.read_exact(association)?;
            let mut association = BitReader::new(association);
            let essential = association.read_bool()?;
            let property_index = association.read_u16(association.remaining().try_into()?)?;
            associations.push(Association {
                item_id,
                essential,
                property_index,
            })?;
        }
    }
    Ok(associations)
}

/// A parsed property with its box FourCC, for essential flag validation.
struct IndexedProperty {
    fourcc: FourCC,
    property: ItemProperty,
}

fn read_ipco<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<IndexedProperty>> {
    let mut properties = TryVec::new();

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        let fourcc: FourCC = b.head.name.into();
        // Must push for every property to have correct index for them
        let prop = match b.head.name {
            BoxType::PixelInformationBox => ItemProperty::Channels(read_pixi(&mut b, options)?),
            BoxType::AuxiliaryTypeProperty => ItemProperty::AuxiliaryType(read_auxc(&mut b, options)?),
            BoxType::ImageSpatialExtentsBox => ItemProperty::ImageSpatialExtents(read_ispe(&mut b, options)?),
            BoxType::ImageGridBox => ItemProperty::ImageGrid(read_grid(&mut b, options)?),
            BoxType::AV1CodecConfigurationBox => ItemProperty::AV1Config(read_av1c(&mut b)?),
            BoxType::ColorInformationBox => {
                match read_colr(&mut b) {
                    Ok(colr) => ItemProperty::ColorInformation(colr),
                    Err(_) => ItemProperty::Unsupported,
                }
            },
            BoxType::ImageRotationBox => ItemProperty::Rotation(read_irot(&mut b)?),
            BoxType::ImageMirrorBox => ItemProperty::Mirror(read_imir(&mut b)?),
            BoxType::CleanApertureBox => ItemProperty::CleanAperture(read_clap(&mut b)?),
            BoxType::PixelAspectRatioBox => ItemProperty::PixelAspectRatio(read_pasp(&mut b)?),
            BoxType::ContentLightLevelBox => ItemProperty::ContentLightLevel(read_clli(&mut b)?),
            BoxType::MasteringDisplayColourVolumeBox => ItemProperty::MasteringDisplayColourVolume(read_mdcv(&mut b)?),
            BoxType::ContentColourVolumeBox => ItemProperty::ContentColourVolume(read_cclv(&mut b)?),
            BoxType::AmbientViewingEnvironmentBox => ItemProperty::AmbientViewingEnvironment(read_amve(&mut b)?),
            BoxType::OperatingPointSelectorBox => ItemProperty::OperatingPointSelector(read_a1op(&mut b)?),
            BoxType::LayerSelectorBox => ItemProperty::LayerSelector(read_lsel(&mut b)?),
            BoxType::AV1LayeredImageIndexingBox => ItemProperty::AV1LayeredImageIndexing(read_a1lx(&mut b)?),
            _ => {
                skip_box_remain(&mut b)?;
                ItemProperty::Unsupported
            },
        };
        properties.push(IndexedProperty { fourcc, property: prop })?;
    }
    Ok(properties)
}

fn read_pixi<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<ArrayVec<u8, 16>> {
    let version = read_fullbox_version_no_flags(src, options)?;
    if version != 0 {
        return Err(Error::Unsupported("pixi version"));
    }

    let num_channels = usize::from(src.read_u8()?);
    let mut channels = ArrayVec::new();
    let clamped = num_channels.min(channels.capacity());
    channels.extend((0..clamped).map(|_| 0));
    src.read_exact(&mut channels).map_err(|_| Error::InvalidData("invalid num_channels"))?;

    // In lenient mode, skip any extra bytes (e.g., extended_pixi.avif has 6 extra bytes)
    if options.lenient && src.bytes_left() > 0 {
        skip(src, src.bytes_left())?;
    }

    check_parser_state(&src.head, &src.content)?;
    Ok(channels)
}

#[derive(Debug, PartialEq)]
struct AuxiliaryTypeProperty {
    aux_data: TryString,
}

impl AuxiliaryTypeProperty {
    #[must_use]
    fn type_subtype(&self) -> (&[u8], &[u8]) {
        let split = self.aux_data.iter().position(|&b| b == b'\0')
            .map(|pos| self.aux_data.split_at(pos));
        if let Some((aux_type, rest)) = split {
            (aux_type, &rest[1..])
        } else {
            (&self.aux_data, &[])
        }
    }
}

impl TryClone for AuxiliaryTypeProperty {
    fn try_clone(&self) -> Result<Self, TryReserveError> {
        Ok(Self {
            aux_data: self.aux_data.try_clone()?,
        })
    }
}

fn read_auxc<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<AuxiliaryTypeProperty> {
    let version = read_fullbox_version_no_flags(src, options)?;
    if version != 0 {
        return Err(Error::Unsupported("auxC version"));
    }

    let aux_data = src.read_into_try_vec()?;

    Ok(AuxiliaryTypeProperty { aux_data })
}

/// Check if an auxiliary type URN identifies a depth auxiliary image.
///
/// Recognizes two standard URNs:
/// - `urn:mpeg:mpegB:cicp:systems:auxiliary:depth` (MPEG-B Part 23 / ISO 23091-2)
/// - `urn:mpeg:hevc:2015:auxid:2` (HEVC-style, auxid 2 = depth)
fn is_depth_auxiliary_urn(urn: &[u8]) -> bool {
    urn == b"urn:mpeg:mpegB:cicp:systems:auxiliary:depth"
        || urn == b"urn:mpeg:hevc:2015:auxid:2"
}

/// Parse an AV1 Codec Configuration property box
/// See AV1-ISOBMFF § 2.3
fn read_av1c<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<AV1Config> {
    // av1C is NOT a FullBox — it has no version/flags
    let byte0 = src.read_u8()?;
    let marker = byte0 >> 7;
    let version = byte0 & 0x7F;

    if marker != 1 {
        return Err(Error::InvalidData("av1C marker must be 1"));
    }
    if version != 1 {
        return Err(Error::Unsupported("av1C version must be 1"));
    }

    let byte1 = src.read_u8()?;
    let profile = byte1 >> 5;
    let level = byte1 & 0x1F;

    let byte2 = src.read_u8()?;
    let tier = byte2 >> 7;
    let high_bitdepth = (byte2 >> 6) & 1;
    let twelve_bit = (byte2 >> 5) & 1;
    let monochrome = (byte2 >> 4) & 1 != 0;
    let chroma_subsampling_x = (byte2 >> 3) & 1;
    let chroma_subsampling_y = (byte2 >> 2) & 1;
    let chroma_sample_position = byte2 & 0x03;

    let byte3 = src.read_u8()?;
    // byte3: 3 bits reserved, 1 bit initial_presentation_delay_present, 4 bits delay/reserved
    // Not needed for image decoding.
    let _ = byte3;

    let bit_depth = if high_bitdepth != 0 {
        if twelve_bit != 0 { 12 } else { 10 }
    } else {
        8
    };

    // Skip any configOBUs (remainder of box)
    skip_box_remain(src)?;

    Ok(AV1Config {
        profile,
        level,
        tier,
        bit_depth,
        monochrome,
        chroma_subsampling_x,
        chroma_subsampling_y,
        chroma_sample_position,
    })
}

/// Parse a Colour Information property box
/// See ISOBMFF § 12.1.5
fn read_colr<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ColorInformation> {
    // colr is NOT a FullBox — no version/flags
    let colour_type = be_u32(src)?;

    match &colour_type.to_be_bytes() {
        b"nclx" => {
            let color_primaries = be_u16(src)?;
            let transfer_characteristics = be_u16(src)?;
            let matrix_coefficients = be_u16(src)?;
            let full_range_byte = src.read_u8()?;
            let full_range = (full_range_byte >> 7) != 0;
            // Skip any remaining bytes
            skip_box_remain(src)?;
            Ok(ColorInformation::Nclx {
                color_primaries,
                transfer_characteristics,
                matrix_coefficients,
                full_range,
            })
        }
        b"rICC" | b"prof" => {
            let icc_data = src.read_into_try_vec()?;
            Ok(ColorInformation::IccProfile(icc_data.to_vec()))
        }
        _ => {
            skip_box_remain(src)?;
            Err(Error::Unsupported("unsupported colr colour_type"))
        }
    }
}

/// Parse an Image Rotation property box.
/// See ISOBMFF § 12.1.4. NOT a FullBox.
fn read_irot<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ImageRotation> {
    let byte = src.read_u8()?;
    let angle_code = byte & 0x03;
    let angle = match angle_code {
        0 => 0,
        1 => 90,
        2 => 180,
        _ => 270, // angle_code & 0x03 can only be 0..=3
    };
    skip_box_remain(src)?;
    Ok(ImageRotation { angle })
}

/// Parse an Image Mirror property box.
/// See ISOBMFF § 12.1.4. NOT a FullBox.
fn read_imir<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ImageMirror> {
    let byte = src.read_u8()?;
    let axis = byte & 0x01;
    skip_box_remain(src)?;
    Ok(ImageMirror { axis })
}

/// Parse a Clean Aperture property box.
/// See ISOBMFF § 12.1.4. NOT a FullBox.
fn read_clap<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<CleanAperture> {
    let width_n = be_u32(src)?;
    let width_d = be_u32(src)?;
    let height_n = be_u32(src)?;
    let height_d = be_u32(src)?;
    let horiz_off_n = be_i32(src)?;
    let horiz_off_d = be_u32(src)?;
    let vert_off_n = be_i32(src)?;
    let vert_off_d = be_u32(src)?;
    // Validate denominators are non-zero
    if width_d == 0 || height_d == 0 || horiz_off_d == 0 || vert_off_d == 0 {
        return Err(Error::InvalidData("clap denominator cannot be zero"));
    }
    skip_box_remain(src)?;
    Ok(CleanAperture {
        width_n, width_d,
        height_n, height_d,
        horiz_off_n, horiz_off_d,
        vert_off_n, vert_off_d,
    })
}

/// Parse a Pixel Aspect Ratio property box.
/// See ISOBMFF § 12.1.4. NOT a FullBox.
fn read_pasp<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<PixelAspectRatio> {
    let h_spacing = be_u32(src)?;
    let v_spacing = be_u32(src)?;
    skip_box_remain(src)?;
    Ok(PixelAspectRatio { h_spacing, v_spacing })
}

/// Parse a Content Light Level Info property box.
/// See ISOBMFF § 12.1.5 / ITU-T H.274. NOT a FullBox.
fn read_clli<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ContentLightLevel> {
    let max_content_light_level = be_u16(src)?;
    let max_pic_average_light_level = be_u16(src)?;
    skip_box_remain(src)?;
    Ok(ContentLightLevel {
        max_content_light_level,
        max_pic_average_light_level,
    })
}

/// Parse a Mastering Display Colour Volume property box.
/// See ISOBMFF § 12.1.5 / SMPTE ST 2086. NOT a FullBox.
fn read_mdcv<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<MasteringDisplayColourVolume> {
    // 3 primaries, each (x, y) as u16
    let primaries = [
        (be_u16(src)?, be_u16(src)?),
        (be_u16(src)?, be_u16(src)?),
        (be_u16(src)?, be_u16(src)?),
    ];
    let white_point = (be_u16(src)?, be_u16(src)?);
    let max_luminance = be_u32(src)?;
    let min_luminance = be_u32(src)?;
    skip_box_remain(src)?;
    Ok(MasteringDisplayColourVolume {
        primaries,
        white_point,
        max_luminance,
        min_luminance,
    })
}

/// Parse a Content Colour Volume property box.
/// See ISOBMFF § 12.1.5 / H.265 D.2.40. NOT a FullBox.
fn read_cclv<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ContentColourVolume> {
    let flags = src.read_u8()?;
    let primaries_present = flags & 0x20 != 0;
    let min_lum_present = flags & 0x10 != 0;
    let max_lum_present = flags & 0x08 != 0;
    let avg_lum_present = flags & 0x04 != 0;

    let primaries = if primaries_present {
        Some([
            (be_i32(src)?, be_i32(src)?),
            (be_i32(src)?, be_i32(src)?),
            (be_i32(src)?, be_i32(src)?),
        ])
    } else {
        None
    };

    let min_luminance = if min_lum_present { Some(be_u32(src)?) } else { None };
    let max_luminance = if max_lum_present { Some(be_u32(src)?) } else { None };
    let avg_luminance = if avg_lum_present { Some(be_u32(src)?) } else { None };

    skip_box_remain(src)?;
    Ok(ContentColourVolume {
        primaries,
        min_luminance,
        max_luminance,
        avg_luminance,
    })
}

/// Parse an Ambient Viewing Environment property box.
/// See ISOBMFF § 12.1.5 / H.265 D.2.39. NOT a FullBox.
fn read_amve<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<AmbientViewingEnvironment> {
    let ambient_illuminance = be_u32(src)?;
    let ambient_light_x = be_u16(src)?;
    let ambient_light_y = be_u16(src)?;
    skip_box_remain(src)?;
    Ok(AmbientViewingEnvironment {
        ambient_illuminance,
        ambient_light_x,
        ambient_light_y,
    })
}

/// Parse an Operating Point Selector property box.
/// See AVIF § 4.3.4. NOT a FullBox.
fn read_a1op<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<OperatingPointSelector> {
    let op_index = src.read_u8()?;
    if op_index > 31 {
        return Err(Error::InvalidData("a1op op_index must be 0..31"));
    }
    skip_box_remain(src)?;
    Ok(OperatingPointSelector { op_index })
}

/// Parse a Layer Selector property box.
/// See HEIF (ISO 23008-12). NOT a FullBox.
fn read_lsel<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<LayerSelector> {
    let layer_id = be_u16(src)?;
    skip_box_remain(src)?;
    Ok(LayerSelector { layer_id })
}

/// Parse an AV1 Layered Image Indexing property box.
/// See AVIF § 4.3.6. NOT a FullBox.
fn read_a1lx<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<AV1LayeredImageIndexing> {
    let flags = src.read_u8()?;
    let large_size = flags & 0x01 != 0;
    let layer_sizes = if large_size {
        [be_u32(src)?, be_u32(src)?, be_u32(src)?]
    } else {
        [u32::from(be_u16(src)?), u32::from(be_u16(src)?), u32::from(be_u16(src)?)]
    };
    skip_box_remain(src)?;
    Ok(AV1LayeredImageIndexing { layer_sizes })
}

/// Parse an Image Spatial Extents property box
/// See ISO/IEC 23008-12:2017 § 6.5.3
fn read_ispe<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<ImageSpatialExtents> {
    let _version = read_fullbox_version_no_flags(src, options)?;
    // Version is always 0 for ispe

    let width = be_u32(src)?;
    let height = be_u32(src)?;

    // Validate dimensions are non-zero (0×0 images are invalid)
    if width == 0 || height == 0 {
        return Err(Error::InvalidData("ispe dimensions cannot be zero"));
    }

    Ok(ImageSpatialExtents { width, height })
}

/// Parse a Movie Header box (mvhd)
/// See ISO/IEC 14496-12:2015 § 8.2.2
fn read_mvhd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<MovieHeader> {
    let version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];

    let (timescale, duration) = if version == 1 {
        let _creation_time = be_u64(src)?;
        let _modification_time = be_u64(src)?;
        let timescale = be_u32(src)?;
        let duration = be_u64(src)?;
        (timescale, duration)
    } else {
        let _creation_time = be_u32(src)?;
        let _modification_time = be_u32(src)?;
        let timescale = be_u32(src)?;
        let duration = be_u32(src)?;
        (timescale, duration as u64)
    };

    // Skip rest of mvhd (rate, volume, matrix, etc.)
    skip_box_remain(src)?;

    Ok(MovieHeader { _timescale: timescale, _duration: duration })
}

/// Parse a Media Header box (mdhd)
/// See ISO/IEC 14496-12:2015 § 8.4.2
fn read_mdhd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<MediaHeader> {
    let version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];

    let (timescale, duration) = if version == 1 {
        let _creation_time = be_u64(src)?;
        let _modification_time = be_u64(src)?;
        let timescale = be_u32(src)?;
        let duration = be_u64(src)?;
        (timescale, duration)
    } else {
        let _creation_time = be_u32(src)?;
        let _modification_time = be_u32(src)?;
        let timescale = be_u32(src)?;
        let duration = be_u32(src)?;
        (timescale, duration as u64)
    };

    // Skip language and pre_defined
    skip_box_remain(src)?;

    Ok(MediaHeader { timescale, _duration: duration })
}

/// Parse Time To Sample box (stts)
/// See ISO/IEC 14496-12:2015 § 8.6.1.2
fn read_stts<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<TimeToSampleEntry>> {
    let _version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
    let entry_count = be_u32(src)?;
    // Each entry: sample_count (4) + sample_delta (4) = 8 bytes
    if (entry_count as u64) * 8 > src.bytes_left() {
        return Err(Error::InvalidData(
            "stts entry_count exceeds remaining box bytes",
        ));
    }

    let mut entries = TryVec::new();
    for _ in 0..entry_count {
        entries.push(TimeToSampleEntry {
            sample_count: be_u32(src)?,
            sample_delta: be_u32(src)?,
        })?;
    }

    Ok(entries)
}

/// Parse Sample To Chunk box (stsc)
/// See ISO/IEC 14496-12:2015 § 8.7.4
fn read_stsc<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<SampleToChunkEntry>> {
    let _version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
    let entry_count = be_u32(src)?;
    // Each entry: first_chunk (4) + samples_per_chunk (4) + sample_desc_index (4) = 12 bytes
    if (entry_count as u64) * 12 > src.bytes_left() {
        return Err(Error::InvalidData(
            "stsc entry_count exceeds remaining box bytes",
        ));
    }

    let mut entries = TryVec::new();
    for _ in 0..entry_count {
        entries.push(SampleToChunkEntry {
            first_chunk: be_u32(src)?,
            samples_per_chunk: be_u32(src)?,
            _sample_description_index: be_u32(src)?,
        })?;
    }

    Ok(entries)
}

/// Parse Sample Size box (stsz)
/// See ISO/IEC 14496-12:2015 § 8.7.3
fn read_stsz<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<u32>> {
    let _version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
    let sample_size = be_u32(src)?;
    let sample_count = be_u32(src)?;

    // Cap sample_count to avoid multi-GB allocations from malformed data.
    // 64M entries * 4 bytes = 256 MB, a generous upper bound for real AVIF files.
    const MAX_SAMPLE_COUNT: u32 = 64 * 1024 * 1024;
    if sample_count > MAX_SAMPLE_COUNT {
        return Err(Error::InvalidData("stsz sample_count exceeds maximum"));
    }

    let mut sizes = TryVec::new();
    if sample_size == 0 {
        // Variable sizes: each entry is 4 bytes
        if (sample_count as u64) * 4 > src.bytes_left() {
            return Err(Error::InvalidData(
                "stsz sample_count exceeds remaining box bytes",
            ));
        }
        // Variable sizes - read each one
        for _ in 0..sample_count {
            sizes.push(be_u32(src)?)?;
        }
    } else {
        // Constant size for all samples
        for _ in 0..sample_count {
            sizes.push(sample_size)?;
        }
    }

    Ok(sizes)
}

/// Parse Chunk Offset box (stco or co64)
/// See ISO/IEC 14496-12:2015 § 8.7.5
fn read_chunk_offsets<T: Read>(src: &mut BMFFBox<'_, T>, is_64bit: bool) -> Result<TryVec<u64>> {
    let _version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
    let entry_count = be_u32(src)?;
    let bytes_per_entry: u64 = if is_64bit { 8 } else { 4 };
    if (entry_count as u64) * bytes_per_entry > src.bytes_left() {
        return Err(Error::InvalidData(
            "chunk offset entry_count exceeds remaining box bytes",
        ));
    }

    let mut offsets = TryVec::new();
    for _ in 0..entry_count {
        let offset = if is_64bit {
            be_u64(src)?
        } else {
            be_u32(src)? as u64
        };
        offsets.push(offset)?;
    }

    Ok(offsets)
}

/// Parse Sample Description box (stsd) to extract codec config from VisualSampleEntry.
/// See ISO/IEC 14496-12:2015 § 8.5.2
///
/// For AVIF sequences, the VisualSampleEntry is `av01` which contains sub-boxes
/// like `av1C` (codec config) and `colr` (color info), similar to ipco properties.
fn read_stsd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TrackCodecConfig> {
    let _version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
    let entry_count = be_u32(src)?;

    let mut config = TrackCodecConfig::default();

    // Parse first entry only (AVIF tracks have one sample description)
    let mut iter = src.box_iter();
    for _ in 0..entry_count {
        let Some(mut entry_box) = iter.next_box()? else {
            break;
        };

        // Check if this is an av01 VisualSampleEntry
        if entry_box.head.name != BoxType::AV1SampleEntry {
            skip_box_remain(&mut entry_box)?;
            continue;
        }

        // Skip VisualSampleEntry fixed fields (78 bytes total):
        //   reserved[6] + data_ref_index[2] + pre_defined[2] + reserved[2] +
        //   pre_defined[12] + width[2] + height[2] + horiz_res[4] + vert_res[4] +
        //   reserved[4] + frame_count[2] + compressorname[32] + depth[2] + pre_defined[2]
        const VISUAL_SAMPLE_ENTRY_SIZE: u64 = 78;
        if entry_box.bytes_left() < VISUAL_SAMPLE_ENTRY_SIZE {
            skip_box_remain(&mut entry_box)?;
            continue;
        }
        skip(&mut entry_box, VISUAL_SAMPLE_ENTRY_SIZE)?;

        // Parse sub-boxes within the VisualSampleEntry for av1C and colr
        let mut sub_iter = entry_box.box_iter();
        while let Some(mut sub_box) = sub_iter.next_box()? {
            match sub_box.head.name {
                BoxType::AV1CodecConfigurationBox => {
                    config.av1_config = Some(read_av1c(&mut sub_box)?);
                }
                BoxType::ColorInformationBox => {
                    if let Ok(colr) = read_colr(&mut sub_box) {
                        config.color_info = Some(colr);
                    } else {
                        skip_box_remain(&mut sub_box)?;
                    }
                }
                _ => {
                    skip_box_remain(&mut sub_box)?;
                }
            }
        }

        // Only need the first av01 entry
        if config.av1_config.is_some() {
            break;
        }
    }

    Ok(config)
}

/// Parse Sample Table box (stbl)
/// See ISO/IEC 14496-12:2015 § 8.5
fn read_stbl<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<(SampleTable, TrackCodecConfig)> {
    let mut time_to_sample = TryVec::new();
    let mut sample_to_chunk = TryVec::new();
    let mut sample_sizes = TryVec::new();
    let mut chunk_offsets = TryVec::new();
    let mut codec_config = TrackCodecConfig::default();

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        match b.head.name {
            BoxType::SampleDescriptionBox => {
                codec_config = read_stsd(&mut b)?;
            }
            BoxType::TimeToSampleBox => {
                time_to_sample = read_stts(&mut b)?;
            }
            BoxType::SampleToChunkBox => {
                sample_to_chunk = read_stsc(&mut b)?;
            }
            BoxType::SampleSizeBox => {
                sample_sizes = read_stsz(&mut b)?;
            }
            BoxType::ChunkOffsetBox => {
                chunk_offsets = read_chunk_offsets(&mut b, false)?;
            }
            BoxType::ChunkLargeOffsetBox => {
                chunk_offsets = read_chunk_offsets(&mut b, true)?;
            }
            _ => {
                skip_box_remain(&mut b)?;
            }
        }
    }

    // Precompute per-sample byte offsets from sample_to_chunk + chunk_offsets + sample_sizes.
    // This flattens the ISOBMFF indirection into a simple array for O(1) frame lookup.
    let mut sample_offsets = TryVec::new();
    let mut sample_idx = 0usize;
    for (i, entry) in sample_to_chunk.iter().enumerate() {
        let next_first_chunk = sample_to_chunk
            .get(i + 1)
            .map(|e| e.first_chunk)
            .unwrap_or(u32::MAX);

        for chunk_no in entry.first_chunk..next_first_chunk {
            if chunk_no == 0 {
                break;
            }
            let co_idx = (chunk_no - 1) as usize;
            let chunk_offset = match chunk_offsets.get(co_idx) {
                Some(&o) => o,
                None => break,
            };

            let mut offset = chunk_offset;
            for _ in 0..entry.samples_per_chunk {
                if sample_idx >= sample_sizes.len() {
                    break;
                }
                sample_offsets.push(offset)?;
                offset += *sample_sizes.get(sample_idx)
                    .ok_or(Error::InvalidData("sample index mismatch"))? as u64;
                sample_idx += 1;
            }
        }
    }

    Ok((SampleTable {
        time_to_sample,
        sample_sizes,
        sample_offsets,
    }, codec_config))
}

/// Parse Track Header box (tkhd)
/// See ISO/IEC 14496-12:2015 § 8.3.2
fn read_tkhd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<u32> {
    let version = src.read_u8()?;
    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];

    let track_id = if version == 1 {
        let _creation_time = be_u64(src)?;
        let _modification_time = be_u64(src)?;
        let track_id = be_u32(src)?;
        let _reserved = be_u32(src)?;
        let _duration = be_u64(src)?;
        track_id
    } else {
        let _creation_time = be_u32(src)?;
        let _modification_time = be_u32(src)?;
        let track_id = be_u32(src)?;
        let _reserved = be_u32(src)?;
        let _duration = be_u32(src)?;
        track_id
    };

    // Skip rest (reserved, layer, alternate_group, volume, matrix, width, height)
    skip_box_remain(src)?;
    Ok(track_id)
}

/// Parse Track Reference box (tref)
/// See ISO/IEC 14496-12:2015 § 8.3.3
///
/// Contains sub-boxes typed by FourCC (e.g., `auxl`, `cdsc`), each with a list of track IDs.
fn read_tref<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<TrackReference>> {
    let mut refs = TryVec::new();
    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        let reference_type = FourCC::from(u32::from(b.head.name));
        let bytes_left = b.bytes_left();
        if bytes_left < 4 || bytes_left % 4 != 0 {
            skip_box_remain(&mut b)?;
            continue;
        }
        let count = bytes_left / 4;
        let mut track_ids = TryVec::new();
        for _ in 0..count {
            track_ids.push(be_u32(&mut b)?)?;
        }
        refs.push(TrackReference { reference_type, track_ids })?;
    }
    Ok(refs)
}

/// Parse Edit List box (elst) to extract loop count from flags.
/// See ISO/IEC 14496-12:2015 § 8.6.6
///
/// Returns the loop count: flags bit 0 set = infinite looping (0), otherwise 1.
fn read_elst<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<u32> {
    let (version, flags) = read_fullbox_extra(src)?;

    let entry_count = be_u32(src)?;
    // Skip all entries
    let entry_size: u64 = if version == 1 { 20 } else { 12 };
    skip(src, (entry_count as u64).checked_mul(entry_size)
        .ok_or(Error::InvalidData("edit list entry count overflow"))?)?;
    skip_box_remain(src)?;

    // Bit 0 of flags: repeat (1 = infinite loop → loop_count=0, 0 = play once → loop_count=1)
    if flags & 1 != 0 {
        Ok(0) // infinite
    } else {
        Ok(1) // play once
    }
}

/// Parse animation from moov box.
/// Returns all parsed tracks.
fn read_moov<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<ParsedTrack>> {
    let mut tracks = TryVec::new();

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        match b.head.name {
            BoxType::MovieHeaderBox => {
                let _mvhd = read_mvhd(&mut b)?;
            }
            BoxType::TrackBox => {
                if let Some(track) = read_trak(&mut b)? {
                    tracks.push(track)?;
                }
            }
            _ => {
                skip_box_remain(&mut b)?;
            }
        }
    }

    Ok(tracks)
}

/// Parse track box (trak).
/// Returns a ParsedTrack if this track has a valid sample table.
fn read_trak<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<Option<ParsedTrack>> {
    let mut track_id = 0u32;
    let mut references = TryVec::new();
    let mut loop_count = 1u32; // default: play once
    let mut mdia_result: Option<(FourCC, u32, SampleTable, TrackCodecConfig)> = None;

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        match b.head.name {
            BoxType::TrackHeaderBox => {
                track_id = read_tkhd(&mut b)?;
            }
            BoxType::TrackReferenceBox => {
                references = read_tref(&mut b)?;
            }
            BoxType::EditBox => {
                // Parse edts to find elst
                let mut edts_iter = b.box_iter();
                while let Some(mut eb) = edts_iter.next_box()? {
                    if eb.head.name == BoxType::EditListBox {
                        loop_count = read_elst(&mut eb)?;
                    } else {
                        skip_box_remain(&mut eb)?;
                    }
                }
            }
            BoxType::MediaBox => {
                mdia_result = read_mdia(&mut b)?;
            }
            _ => {
                skip_box_remain(&mut b)?;
            }
        }
    }

    if let Some((handler_type, media_timescale, sample_table, codec_config)) = mdia_result {
        Ok(Some(ParsedTrack {
            track_id,
            handler_type,
            media_timescale,
            sample_table,
            references,
            loop_count,
            codec_config,
        }))
    } else {
        Ok(None)
    }
}

/// Parse media box (mdia).
/// Returns (handler_type, media_timescale, sample_table, codec_config) if valid.
fn read_mdia<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<Option<(FourCC, u32, SampleTable, TrackCodecConfig)>> {
    let mut media_timescale = 1000; // default
    let mut handler_type = FourCC::default();
    let mut stbl_result: Option<(SampleTable, TrackCodecConfig)> = None;

    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        match b.head.name {
            BoxType::MediaHeaderBox => {
                let mdhd = read_mdhd(&mut b)?;
                media_timescale = mdhd.timescale;
            }
            BoxType::HandlerBox => {
                let hdlr = read_hdlr(&mut b)?;
                handler_type = hdlr.handler_type;
            }
            BoxType::MediaInformationBox => {
                stbl_result = read_minf(&mut b)?;
            }
            _ => {
                skip_box_remain(&mut b)?;
            }
        }
    }

    if let Some((stbl, codec_config)) = stbl_result {
        Ok(Some((handler_type, media_timescale, stbl, codec_config)))
    } else {
        Ok(None)
    }
}

/// Associate parsed tracks into color + optional alpha animation data.
///
/// - Color track: first with handler `pict` (fallback: first track with a sample table)
/// - Alpha track: handler `auxv` with `tref/auxl` referencing color's track_id
/// - Audio tracks (handler `soun`) are skipped
fn associate_tracks(tracks: TryVec<ParsedTrack>) -> Result<ParsedAnimationData> {
    // Find color track: first with handler_type == "pict"
    let color_idx = tracks
        .iter()
        .position(|t| t.handler_type == b"pict")
        .or_else(|| {
            // Fallback: first track that isn't audio
            tracks.iter().position(|t| t.handler_type != b"soun")
        })
        .ok_or(Error::InvalidData("no color track found in moov"))?;

    let color_track = tracks.get(color_idx)
        .ok_or(Error::InvalidData("color track index out of bounds"))?;
    let color_track_id = color_track.track_id;

    // Find alpha track: handler_type == "auxv" with tref/auxl referencing color track
    let alpha_idx = tracks.iter().position(|t| {
        t.handler_type == b"auxv"
            && t.references.iter().any(|r| {
                r.reference_type == b"auxl"
                    && r.track_ids.iter().any(|&id| id == color_track_id)
            })
    });

    if let Some(ai) = alpha_idx {
        let alpha_track = tracks.get(ai)
            .ok_or(Error::InvalidData("alpha track index out of bounds"))?;
        let color_track = tracks.get(color_idx)
            .ok_or(Error::InvalidData("color track index out of bounds"))?;
        let alpha_frames = alpha_track.sample_table.sample_sizes.len();
        let color_frames = color_track.sample_table.sample_sizes.len();
        if alpha_frames != color_frames {
            warn!(
                "alpha track has {} frames but color track has {} frames",
                alpha_frames, color_frames
            );
        }
    }

    // Destructure — we need to consume the vec
    // Convert to a std vec so we can remove by index
    let mut tracks_vec: std::vec::Vec<ParsedTrack> = tracks.into_iter().collect();

    // Remove alpha first if it has a higher index to avoid shifting
    let (color_track, alpha_track) = if let Some(ai) = alpha_idx {
        if ai > color_idx {
            let alpha = tracks_vec.remove(ai);
            let color = tracks_vec.remove(color_idx);
            (color, Some(alpha))
        } else {
            let color = tracks_vec.remove(color_idx);
            let alpha = tracks_vec.remove(ai);
            (color, Some(alpha))
        }
    } else {
        let color = tracks_vec.remove(color_idx);
        (color, None)
    };

    let (alpha_timescale, alpha_sample_table) = match alpha_track {
        Some(t) => (Some(t.media_timescale), Some(t.sample_table)),
        None => (None, None),
    };

    Ok(ParsedAnimationData {
        color_timescale: color_track.media_timescale,
        color_codec_config: color_track.codec_config,
        color_sample_table: color_track.sample_table,
        alpha_timescale,
        alpha_sample_table,
        loop_count: color_track.loop_count,
    })
}

/// Parse media information box (minf)
fn read_minf<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<Option<(SampleTable, TrackCodecConfig)>> {
    let mut iter = src.box_iter();
    while let Some(mut b) = iter.next_box()? {
        if b.head.name == BoxType::SampleTableBox {
            return Ok(Some(read_stbl(&mut b)?));
        } else {
            skip_box_remain(&mut b)?;
        }
    }
    Ok(None)
}

/// Extract animation frames using sample table
#[cfg(feature = "eager")]
#[allow(deprecated)]
fn extract_animation_frames(
    sample_table: &SampleTable,
    media_timescale: u32,
    mdats: &mut [MediaDataBox],
) -> Result<TryVec<AnimationFrame>> {
    let mut frames = TryVec::new();

    // Calculate frame durations from time-to-sample
    let mut frame_durations = TryVec::new();
    for entry in &sample_table.time_to_sample {
        for _ in 0..entry.sample_count {
            let duration_ms = if media_timescale > 0 {
                ((entry.sample_delta as u64) * 1000) / (media_timescale as u64)
            } else {
                0
            };
            frame_durations.push(u32::try_from(duration_ms).unwrap_or(u32::MAX))?;
        }
    }

    // Extract each frame using precomputed sample offsets
    for i in 0..sample_table.sample_sizes.len() {
        let sample_offset = *sample_table.sample_offsets.get(i)
            .ok_or(Error::InvalidData("sample offset index out of bounds"))?;
        let sample_size = *sample_table.sample_sizes.get(i)
            .ok_or(Error::InvalidData("sample size index out of bounds"))?;
        let duration_ms = frame_durations.get(i).copied().unwrap_or(0);

        let mut frame_data = TryVec::new();
        let mut found = false;

        for mdat in mdats.iter_mut() {
            let range = ExtentRange::WithLength(Range {
                start: sample_offset,
                end: sample_offset + sample_size as u64,
            });

            if mdat.contains_extent(&range) {
                mdat.read_extent(&range, &mut frame_data)?;
                found = true;
                break;
            }
        }

        if !found {
            log::warn!("Animation frame {} not found in mdat", i);
        }

        frames.push(AnimationFrame {
            data: frame_data,
            duration_ms,
        })?;
    }

    Ok(frames)
}

/// Parse an ImageGrid property box
/// See ISO/IEC 23008-12:2017 § 6.6.2.3
fn read_grid<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<GridConfig> {
    let version = read_fullbox_version_no_flags(src, options)?;
    if version > 0 {
        return Err(Error::Unsupported("grid version > 0"));
    }

    let flags_byte = src.read_u8()?;
    let rows = src.read_u8()?;
    let columns = src.read_u8()?;

    // flags & 1 determines field size: 0 = 16-bit, 1 = 32-bit
    let (output_width, output_height) = if flags_byte & 1 == 0 {
        // 16-bit fields
        (u32::from(be_u16(src)?), u32::from(be_u16(src)?))
    } else {
        // 32-bit fields
        (be_u32(src)?, be_u32(src)?)
    };

    Ok(GridConfig {
        rows,
        columns,
        output_width,
        output_height,
    })
}

/// Parse an item location box inside a meta box
/// See ISO 14496-12:2015 § 8.11.3
fn read_iloc<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<ItemLocationBoxItem>> {
    let version: IlocVersion = read_fullbox_version_no_flags(src, options)?.try_into()?;

    let iloc = src.read_into_try_vec()?;
    let mut iloc = BitReader::new(&iloc);

    let offset_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
    let length_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
    let base_offset_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;

    let index_size: Option<IlocFieldSize> = match version {
        IlocVersion::One | IlocVersion::Two => Some(iloc.read_u8(4)?.try_into()?),
        IlocVersion::Zero => {
            let _reserved = iloc.read_u8(4)?;
            None
        },
    };

    let item_count = match version {
        IlocVersion::Zero | IlocVersion::One => iloc.read_u32(16)?,
        IlocVersion::Two => iloc.read_u32(32)?,
    };

    // Cap pre-allocation: item_count is untrusted, actual data is bounded by bitstream
    let mut items = TryVec::with_capacity(item_count.to_usize().min(4096))?;

    for _ in 0..item_count {
        let item_id = match version {
            IlocVersion::Zero | IlocVersion::One => iloc.read_u32(16)?,
            IlocVersion::Two => iloc.read_u32(32)?,
        };

        // The spec isn't entirely clear how an `iloc` should be interpreted for version 0,
        // which has no `construction_method` field. It does say:
        // "For maximum compatibility, version 0 of this box should be used in preference to
        //  version 1 with `construction_method==0`, or version 2 when possible."
        // We take this to imply version 0 can be interpreted as using file offsets.
        let construction_method = match version {
            IlocVersion::Zero => ConstructionMethod::File,
            IlocVersion::One | IlocVersion::Two => {
                let _reserved = iloc.read_u16(12)?;
                match iloc.read_u16(4)? {
                    0 => ConstructionMethod::File,
                    1 => ConstructionMethod::Idat,
                    2 => return Err(Error::Unsupported("construction_method 'item_offset' is not supported")),
                    _ => return Err(Error::InvalidData("construction_method is taken from the set 0, 1 or 2 per ISO 14496-12:2015 § 8.11.3.3")),
                }
            },
        };

        let data_reference_index = iloc.read_u16(16)?;

        if data_reference_index != 0 {
            return Err(Error::Unsupported("external file references (iloc.data_reference_index != 0) are not supported"));
        }

        let base_offset = iloc.read_u64(base_offset_size.to_bits())?;
        let extent_count = iloc.read_u16(16)?;

        if extent_count < 1 {
            return Err(Error::InvalidData("extent_count must have a value 1 or greater per ISO 14496-12:2015 § 8.11.3.3"));
        }

        let mut extents = TryVec::with_capacity(extent_count.to_usize())?;

        for _ in 0..extent_count {
            // Parsed but currently ignored, see `ItemLocationBoxExtent`
            let _extent_index = match &index_size {
                None | Some(IlocFieldSize::Zero) => None,
                Some(index_size) => {
                    debug_assert!(version == IlocVersion::One || version == IlocVersion::Two);
                    Some(iloc.read_u64(index_size.to_bits())?)
                },
            };

            // Per ISO 14496-12:2015 § 8.11.3.1:
            // "If the offset is not identified (the field has a length of zero), then the
            //  beginning of the source (offset 0) is implied"
            // This behavior will follow from BitReader::read_u64(0) -> 0.
            let extent_offset = iloc.read_u64(offset_size.to_bits())?;
            let extent_length = iloc.read_u64(length_size.to_bits())?;

            // "If the length is not specified, or specified as zero, then the entire length of
            //  the source is implied" (ibid)
            let start = base_offset
                .checked_add(extent_offset)
                .ok_or(Error::InvalidData("offset calculation overflow"))?;
            let extent_range = if extent_length == 0 {
                ExtentRange::ToEnd(RangeFrom { start })
            } else {
                let end = start
                    .checked_add(extent_length)
                    .ok_or(Error::InvalidData("end calculation overflow"))?;
                ExtentRange::WithLength(Range { start, end })
            };

            extents.push(ItemLocationBoxExtent { extent_range })?;
        }

        items.push(ItemLocationBoxItem { item_id, construction_method, extents })?;
    }

    if iloc.remaining() == 0 {
        Ok(items)
    } else {
        Err(Error::InvalidData("invalid iloc size"))
    }
}

/// Parse an ftyp box.
/// See ISO 14496-12:2015 § 4.3
fn read_ftyp<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<FileTypeBox> {
    let major = be_u32(src)?;
    let minor = be_u32(src)?;
    let bytes_left = src.bytes_left();
    if !bytes_left.is_multiple_of(4) {
        return Err(Error::InvalidData("invalid ftyp size"));
    }
    // Is a brand_count of zero valid?
    let brand_count = bytes_left / 4;
    let mut brands = TryVec::with_capacity(brand_count.try_into()?)?;
    for _ in 0..brand_count {
        brands.push(be_u32(src)?.into())?;
    }
    Ok(FileTypeBox {
        major_brand: From::from(major),
        minor_version: minor,
        compatible_brands: brands,
    })
}

#[cfg_attr(debug_assertions, track_caller)]
fn check_parser_state<T>(header: &BoxHeader, left: &Take<T>) -> Result<(), Error> {
    let limit = left.limit();
    // Allow fully consumed boxes, or size=0 boxes (where original size was u64::MAX)
    if limit == 0 || header.size == u64::MAX {
        Ok(())
    } else {
        Err(Error::InvalidData("unread box content or bad parser sync"))
    }
}

/// Skip a number of bytes that we don't care to parse.
fn skip<T: Read>(src: &mut T, bytes: u64) -> Result<()> {
    std::io::copy(&mut src.take(bytes), &mut std::io::sink())?;
    Ok(())
}

fn be_u16<T: ReadBytesExt>(src: &mut T) -> Result<u16> {
    src.read_u16::<byteorder::BigEndian>().map_err(From::from)
}

fn be_u32<T: ReadBytesExt>(src: &mut T) -> Result<u32> {
    src.read_u32::<byteorder::BigEndian>().map_err(From::from)
}

fn be_i32<T: ReadBytesExt>(src: &mut T) -> Result<i32> {
    src.read_i32::<byteorder::BigEndian>().map_err(From::from)
}

fn be_u64<T: ReadBytesExt>(src: &mut T) -> Result<u64> {
    src.read_u64::<byteorder::BigEndian>().map_err(From::from)
}