oxideav-avif 0.0.15

Pure-Rust AVIF (AV1 Image File Format) decoder — HEIF meta-box walk + primary-item / av1C extraction, handed to oxideav-av1 for end-to-end pixel decode; grid + alpha + irot/imir/clap composition
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
//! Derived-image descriptors and entity grouping — HEIF §6.6.2 + §9.4,
//! plus AV1-AVIF v1.2.0 §4.2.3 sample-transform derivations.
//!
//! AVIF restricts derived-image carriage to the `grid` form (av1-avif
//! §4.2), but a reader that walks AVIF / HEIF files in the wild will
//! encounter HEIF features layered on top of an AVIF brand:
//!
//! * **`iovl` image-overlay derivations** (HEIF §6.6.2.2): one or more
//!   source images placed at signed `(x, y)` offsets on a fixed canvas
//!   with an RGBA fill colour.
//! * **`iden` identity derivations** (HEIF §6.6.2.1): the source image
//!   passed through unchanged, useful when transformative properties
//!   on the derivation differ from those on the source.
//! * **`sato` sample-transform derivations** (av1-avif v1.2.0 §4.2.3):
//!   a postfix-notation expression of integer operators and operands
//!   evaluated per sample to combine pixels from one or more input
//!   image items. See [`SampleTransform`].
//! * **Entity grouping** (HEIF §9.4): `grpl` containing one or more
//!   `EntityToGroupBox` per grouping type. The common groupings are
//!   `altr` (alternates), `ster` (stereo pair), `eqiv` (timeline
//!   equivalence to a track sample).
//!
//! All parsers here operate on raw box payload bytes — they're
//! independent of the [`crate::parser`] file walker and the
//! [`crate::meta`] item-property pipeline, so a caller can apply them
//! to any byte range that follows the documented layout. The
//! [`crate::parser::AvifHeader`] walker now exposes a `grpl` slice
//! through [`crate::meta::Meta::groups`] for callers that need to
//! enumerate AVIF/HEIF alternates without rebuilding the container
//! traversal.

use crate::box_parser::{b, iter_boxes, parse_full_box, read_u16, read_u32, type_str, BoxType};
use crate::error::{AvifError as Error, Result};

/// One placed image inside an `iovl` overlay descriptor (HEIF §6.6.2.2).
/// `horizontal_offset` + `vertical_offset` are signed pixel offsets from
/// the top-left corner of the canvas; per spec, source pixels with a
/// negative coordinate (or coordinates `>= output_width / output_height`)
/// are clipped out of the reconstructed image.
///
/// The actual source image item id isn't stored here — `iovl` payload
/// only carries the offsets; the source ids come from the parallel
/// `dimg` iref's `to_ids` list (in the same order).
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OverlayEntry {
    pub horizontal_offset: i32,
    pub vertical_offset: i32,
}

impl OverlayEntry {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(horizontal_offset: i32, vertical_offset: i32) -> Self {
        Self {
            horizontal_offset,
            vertical_offset,
        }
    }
    /// Setter: replace `horizontal_offset`.
    pub fn with_horizontal_offset(mut self, horizontal_offset: i32) -> Self {
        self.horizontal_offset = horizontal_offset;
        self
    }
    /// Setter: replace `vertical_offset`.
    pub fn with_vertical_offset(mut self, vertical_offset: i32) -> Self {
        self.vertical_offset = vertical_offset;
        self
    }
}

/// Parsed `iovl` ImageOverlay descriptor (HEIF §6.6.2.2). Bottom-most
/// input image is `entries[0]`; the top-most is `entries[entries.len()-1]`.
///
/// `canvas_fill_value` is RGBA in sRGB (R, G, B, A) per spec; the A
/// channel runs 0 (transparent) to 65535 (opaque) linearly. RGB values
/// are also 16-bit, padded with zeros if the writer thought in 8-bit.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageOverlay {
    pub canvas_fill_value: [u16; 4],
    pub output_width: u32,
    pub output_height: u32,
    pub entries: Vec<OverlayEntry>,
}

impl ImageOverlay {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        canvas_fill_value: [u16; 4],
        output_width: u32,
        output_height: u32,
        entries: Vec<OverlayEntry>,
    ) -> Self {
        Self {
            canvas_fill_value,
            output_width,
            output_height,
            entries,
        }
    }
    /// Setter: replace `canvas_fill_value`.
    pub fn with_canvas_fill_value(mut self, canvas_fill_value: [u16; 4]) -> Self {
        self.canvas_fill_value = canvas_fill_value;
        self
    }
    /// Setter: replace `output_width`.
    pub fn with_output_width(mut self, output_width: u32) -> Self {
        self.output_width = output_width;
        self
    }
    /// Setter: replace `output_height`.
    pub fn with_output_height(mut self, output_height: u32) -> Self {
        self.output_height = output_height;
        self
    }
    /// Setter: replace `entries`.
    pub fn with_entries(mut self, entries: Vec<OverlayEntry>) -> Self {
        self.entries = entries;
        self
    }
}

impl ImageOverlay {
    /// Parse an `iovl` item body; `reference_count` is the number of
    /// `dimg` inputs the item declares (HEIF §6.6.2.2.2).
    pub fn parse(payload: &[u8], reference_count: usize) -> Result<Self> {
        match payload.first() {
            None => return Err(Error::invalid("avif: iovl header too short")),
            Some(0) => {}
            Some(v) => return Err(Error::invalid(format!("avif: iovl version {v} != 0"))),
        }
        let desc = oxideav_heif::derived::OverlayDescriptor::parse(payload, reference_count)?;
        Ok(ImageOverlay {
            canvas_fill_value: desc.canvas_fill,
            output_width: desc.output_width,
            output_height: desc.output_height,
            entries: desc
                .offsets
                .iter()
                .map(|&(h, v)| OverlayEntry {
                    horizontal_offset: h,
                    vertical_offset: v,
                })
                .collect(),
        })
    }

    /// The container crate's view of the same descriptor.
    pub(crate) fn descriptor(&self) -> oxideav_heif::derived::OverlayDescriptor {
        oxideav_heif::derived::OverlayDescriptor::new(
            self.canvas_fill_value,
            self.output_width,
            self.output_height,
            self.entries
                .iter()
                .map(|e| (e.horizontal_offset, e.vertical_offset))
                .collect(),
        )
    }
}

/// One `EntityToGroupBox` entry (HEIF / ISOBMFF §8.15.3 / 23008-12 §9.4.3).
/// `grouping_type` is a four-CC declaring the relationship between the
/// listed entity ids: `altr` (alternates), `ster` (stereo pair), `eqiv`
/// (equivalence to a track sample), and others.
///
/// `entity_ids` are conventionally `item_ID` values from the same `meta`
/// (file-level `grpl` references file-level items; per §9.4.1). When a
/// grouping mixes items and tracks, the resolver chooses based on which
/// id matches — that's a caller-side concern.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntityGroup {
    pub grouping_type: BoxType,
    pub group_id: u32,
    pub entity_ids: Vec<u32>,
    /// The 24-bit `flags` field of the `EntityToGroupBox` FullBox header
    /// (ISO/IEC 14496-12 §8.15.3.2). Most grouping types leave it `0`,
    /// but some carry semantics here — e.g. the `'iaug'` audio-to-image
    /// group (HEIF §6.8.4) uses the least-significant flag bit to signal
    /// that the audio track should repeat for the whole viewing
    /// duration.
    pub flags: u32,
}

impl EntityGroup {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(grouping_type: BoxType, group_id: u32, entity_ids: Vec<u32>, flags: u32) -> Self {
        Self {
            grouping_type,
            group_id,
            entity_ids,
            flags,
        }
    }
}

impl EntityGroup {
    /// True when the grouping type signals stereo pair (HEIF §9.4.3.1).
    /// Reader convention: `entity_ids[0]` is the left view,
    /// `entity_ids[1]` is the right view.
    pub fn is_stereo_pair(&self) -> bool {
        &self.grouping_type == b"ster"
    }

    /// True when the grouping type signals an alternate set
    /// (HEIF §9.4.3.1) — the reader picks one of `entity_ids` and
    /// discards the others.
    pub fn is_alternates(&self) -> bool {
        &self.grouping_type == b"altr"
    }

    /// True when the grouping type signals timeline equivalence to a
    /// track sample (HEIF §6.8.1).
    pub fn is_equivalence(&self) -> bool {
        &self.grouping_type == b"eqiv"
    }

    /// True when the grouping type signals a set of images captured in
    /// order to create a panorama (HEIF §6.8.8.1), listed in
    /// increasing panorama order. The §6.5.27 `pano` item property
    /// describing the panorama direction `should` only be associated
    /// with an entity group of this type (§6.5.27.1).
    pub fn is_panorama(&self) -> bool {
        &self.grouping_type == b"pano"
    }

    /// True when the grouping type signals a progressive rendering set
    /// (`'prgr'`, HEIF §6.8.10): the listed image items are similar images
    /// at different quality levels, stored — and listed in the group — in
    /// **increasing picture quality order**, so a renderer can show a
    /// first low-quality image quickly and refine it. A `'prgr'` group
    /// contains only image items, never tracks (§6.8.10).
    pub fn is_progressive(&self) -> bool {
        &self.grouping_type == b"prgr"
    }

    /// True when the grouping type signals a burst image set (`'brst'`,
    /// HEIF §6.8.9): a series of rapid-succession images whose `entity_id`
    /// values are listed in temporally increasing order.
    pub fn is_burst(&self) -> bool {
        &self.grouping_type == b"brst"
    }

    /// True when the grouping type signals a multi-source grouping
    /// (`'msrc'`, HEIF §9.4): tracks/items that originate from the same
    /// source (e.g. the visual tracks for the same captured content,
    /// alongside their associated audio).
    pub fn is_multi_source(&self) -> bool {
        &self.grouping_type == b"msrc"
    }

    /// Check the §6.8 cardinality `shall`s that can be verified from the
    /// group alone (without resolving whether each `entity_id` is an
    /// image item, a track, or another group). Returns `true` when the
    /// group's `entity_ids` count satisfies its grouping-type constraint,
    /// and `true` (vacuously) for grouping types with no fixed-count
    /// `shall`:
    ///
    /// * `'ster'` (§6.8.5) — exactly two image items.
    /// * `'iaug'` (§6.8.4) — exactly two entities (one image item/group,
    ///   one audio track).
    ///
    /// This is a necessary — not sufficient — compliance check: the
    /// per-entity type constraints (image vs audio) require track/item
    /// resolution the caller must perform separately.
    pub fn cardinality_ok(&self) -> bool {
        match &self.grouping_type {
            b"ster" | b"iaug" => self.entity_ids.len() == 2,
            _ => true,
        }
    }

    /// True when the grouping type signals a time-synchronized capture
    /// set (`'tsyn'`, HEIF §6.8.3): the listed entities were
    /// synchronously captured spanning the same time. A single `'tsyn'`
    /// group `shall` list `entity_id` values that all resolve to image
    /// items or all to image-sequence tracks — never a mixture — and
    /// any tracks in the group `shall` have the same duration.
    pub fn is_time_synchronized(&self) -> bool {
        &self.grouping_type == b"tsyn"
    }

    /// True when the grouping type signals an audio-to-image association
    /// (`'iaug'`, HEIF §6.8.4): exactly two entities, one an image item
    /// (or an entity group) and the other an audio track, so a reader
    /// can play the audio while the image is displayed.
    pub fn is_audio_to_image(&self) -> bool {
        &self.grouping_type == b"iaug"
    }

    /// For an `'iaug'` audio-to-image group (HEIF §6.8.4): `true` when
    /// the least-significant `flags` bit is set, requesting that the
    /// audio track repeat for the whole viewing duration when the audio
    /// is shorter than the display and its edit list does not already
    /// set the repeat flag. Meaningless (always `false`-checked by the
    /// caller) for other grouping types.
    pub fn audio_repeats(&self) -> bool {
        self.is_audio_to_image() && (self.flags & 0x1) != 0
    }

    /// True when the grouping type signals a slideshow set (`'slid'`,
    /// HEIF §6.8.9): the listed image items form a slideshow, listed in
    /// increasing display order, with per-item transition-effect
    /// properties and optional `stpe`/`ssld` timing.
    pub fn is_slideshow(&self) -> bool {
        &self.grouping_type == b"slid"
    }

    /// True when the grouping type signals an album collection
    /// (`'albc'`, HEIF §6.8.7.1): the listed entities form an album; an
    /// optional `udes` user-description property may describe it.
    pub fn is_album_collection(&self) -> bool {
        &self.grouping_type == b"albc"
    }

    /// True when the grouping type signals a favorites collection
    /// (`'favc'`, HEIF §6.8.7.2): the listed entities form a collection
    /// of favorite images; an optional `udes` property may describe it.
    pub fn is_favorites_collection(&self) -> bool {
        &self.grouping_type == b"favc"
    }

    /// True when the grouping type is one of the HEIF §6.8.7
    /// user-defined image collections (`'albc'` album / `'favc'`
    /// favorites).
    pub fn is_user_collection(&self) -> bool {
        self.is_album_collection() || self.is_favorites_collection()
    }

    /// True when the grouping type is one of the HEIF §6.8.6 bracketed
    /// capture-time sets (`'aebr'` auto-exposure, `'wbbr'` white-balance,
    /// `'fobr'` focus, `'afbr'` flash-exposure, `'dobr'` depth-of-field).
    /// The listed image items were captured with a single varying
    /// parameter; the per-item value is carried by the item property of
    /// the same four-CC (§6.8.6.1).
    pub fn is_bracketed_set(&self) -> bool {
        self.bracketing_kind().is_some()
    }

    /// Classify a §6.8.6 bracketed-set grouping type, or `None` for any
    /// other grouping type.
    pub fn bracketing_kind(&self) -> Option<BracketingKind> {
        BracketingKind::from_four_cc(&self.grouping_type)
    }
}

/// The five HEIF §6.8.6 bracketed-set capture-time grouping types. Each
/// FourCC serves simultaneously as an `EntityToGroupBox` `grouping_type`
/// (grouping the image items of a bracket) and as the box type of the
/// per-item item property that carries the item-specific parameter, and
/// — for image sequences — as a sample-group `grouping_type` whose
/// `VisualSampleGroupEntry` subclass carries the per-sample parameter
/// (see [`BracketingEntry`]).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BracketingKind {
    /// `'aebr'` — auto-exposure bracketing (§6.8.6.2).
    AutoExposure,
    /// `'wbbr'` — white-balance bracketing (§6.8.6.3).
    WhiteBalance,
    /// `'fobr'` — focus bracketing (§6.8.6.4).
    Focus,
    /// `'afbr'` — flash-exposure bracketing (§6.8.6.5).
    FlashExposure,
    /// `'dobr'` — depth-of-field bracketing (§6.8.6.6).
    DepthOfField,
}

impl BracketingKind {
    /// Classify a four-CC as a §6.8.6 bracketed-set kind, or `None`.
    pub fn from_four_cc(fourcc: &[u8; 4]) -> Option<BracketingKind> {
        match fourcc {
            b"aebr" => Some(BracketingKind::AutoExposure),
            b"wbbr" => Some(BracketingKind::WhiteBalance),
            b"fobr" => Some(BracketingKind::Focus),
            b"afbr" => Some(BracketingKind::FlashExposure),
            b"dobr" => Some(BracketingKind::DepthOfField),
            _ => None,
        }
    }

    /// The four-CC that identifies this bracketing kind.
    pub fn four_cc(&self) -> &'static [u8; 4] {
        match self {
            BracketingKind::AutoExposure => b"aebr",
            BracketingKind::WhiteBalance => b"wbbr",
            BracketingKind::Focus => b"fobr",
            BracketingKind::FlashExposure => b"afbr",
            BracketingKind::DepthOfField => b"dobr",
        }
    }
}

/// Parse a `GroupsListBox` (`grpl`) payload into its set of entity
/// groups. Spec: ISO/IEC 23008-12 §9.4.2 (file-level grouping).
///
/// `grpl` itself is a plain Box containing one or more `EntityToGroupBox`
/// children, each a FullBox keyed by `grouping_type` four-CC.
pub fn parse_grpl(payload: &[u8]) -> Result<Vec<EntityGroup>> {
    let mut out = Vec::new();
    for hdr in iter_boxes(payload) {
        let hdr = hdr?;
        let child = &payload[hdr.payload_start..hdr.end()];
        let (_version, flags, body) = parse_full_box(child)?;
        if body.len() < 8 {
            return Err(Error::invalid(format!(
                "avif: EntityToGroupBox '{}' body too short ({} < 8)",
                type_str(&hdr.box_type),
                body.len()
            )));
        }
        let group_id = read_u32(body, 0)?;
        let num_entities = read_u32(body, 4)? as usize;
        let need = 8 + num_entities * 4;
        if body.len() < need {
            return Err(Error::invalid(format!(
                "avif: EntityToGroupBox '{}' truncated entity list ({} < {need})",
                type_str(&hdr.box_type),
                body.len()
            )));
        }
        let mut entity_ids = Vec::with_capacity(num_entities);
        for i in 0..num_entities {
            entity_ids.push(read_u32(body, 8 + i * 4)?);
        }
        out.push(EntityGroup {
            grouping_type: hdr.box_type,
            group_id,
            entity_ids,
            flags,
        });
    }
    Ok(out)
}

/// Result of a `mif1` brand compliance audit (HEIF §10.2.1.1).
///
/// A `mif1` file must contain a top-level `ftyp` + `meta` and its `meta`
/// must contain `hdlr`, `pitm`, `iinf` + `infe` entries, `iloc`, and
/// `iprp`. The audit is informational: AVIF files in the wild ship
/// `mif1` as a compatible brand without strict compliance (e.g. ones
/// emitted by ImageMagick), and our reader still accepts them. The
/// validator exists so callers that want to enforce strict-mif1 mode
/// can.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Mif1Compliance {
    pub has_hdlr: bool,
    pub has_pitm: bool,
    pub has_iinf: bool,
    pub has_iloc: bool,
    pub has_iprp: bool,
    /// Number of `infe` entries inside `iinf`. mif1 requires at least
    /// one image item (the primary).
    pub infe_count: usize,
    /// Brand carries `mif1` in major_brand or compatible_brands.
    pub claims_mif1: bool,
}

impl Mif1Compliance {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        has_hdlr: bool,
        has_pitm: bool,
        has_iinf: bool,
        has_iloc: bool,
        has_iprp: bool,
        infe_count: usize,
        claims_mif1: bool,
    ) -> Self {
        Self {
            has_hdlr,
            has_pitm,
            has_iinf,
            has_iloc,
            has_iprp,
            infe_count,
            claims_mif1,
        }
    }
}

impl Mif1Compliance {
    /// True when every mandatory mif1 reader-side box is present.
    /// Strict spec interpretation per §10.2.1.1 table — does not include
    /// the optional `iref` / `idat` / `iprp` of §10.2.1.2 entries that
    /// are reader-side suggestions only.
    pub fn is_compliant(&self) -> bool {
        self.has_hdlr
            && self.has_pitm
            && self.has_iinf
            && self.has_iloc
            && self.has_iprp
            && self.infe_count > 0
    }

    /// A human-friendly list of missing required boxes, useful for
    /// diagnostics. Returns an empty list when [`Self::is_compliant`].
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if !self.has_hdlr {
            out.push("hdlr");
        }
        if !self.has_pitm {
            out.push("pitm");
        }
        if !self.has_iinf {
            out.push("iinf");
        }
        if self.infe_count == 0 {
            out.push("infe");
        }
        if !self.has_iloc {
            out.push("iloc");
        }
        if !self.has_iprp {
            out.push("iprp");
        }
        out
    }
}

// ---------------------------------------------------------------------------
// AV1-AVIF v1.2.0 §4.2.3 — Sample Transform Derived Image Item (`sato`)
// ---------------------------------------------------------------------------

/// A single token in a [`SampleTransform`] expression. The encoding is
/// the raw 8-bit token value from the bitstream (av1-avif §4.2.3.2,
/// Table 2). The variant carries any decoded payload (`Constant` holds
/// the signed literal extracted from the stream; every other variant is
/// a no-payload tag).
///
/// Token-value ranges (spec Table 2):
///
/// * `0` — `Constant(value)`. The constant is a signed integer of
///   `2^(bit_depth+3)` bits read from the stream (so 8, 16, 32 or
///   64 bits keyed by [`SampleTransform::bit_depth`]). The decoded value
///   is sign-extended to `i64` for in-memory storage; it is pushed to
///   the stack at the [`SampleTransform::num_bits`] intermediate
///   precision when evaluated.
/// * `1..=32` — `Sample(token)`. A 1-based index into the parallel
///   `dimg` iref's `to_ids` list. The actual sample value comes from
///   the named input image item at the same spatial coordinates and
///   channel as the output sample being evaluated.
/// * `33..=63` — reserved. Readers shall reject (av1-avif §4.2.3.3:
///   "Readers shall ignore a Sample Transform Derived Image Item with
///   a reserved token value"). Surfaced as [`Token::Reserved`] from
///   [`SampleTransform::parse_relaxed`] for diagnostics; the strict
///   [`SampleTransform::parse`] errors out instead.
/// * `64..=67` — `Unary(op)`. One stack pop, one stack push.
///   * `64` — negation (`-L`)
///   * `65` — absolute value (`|L|`)
///   * `66` — bitwise not (`¬L`)
///   * `67` — `bsr` (0-based index of the MSB of `L` when `L > 0`,
///     else `0`)
/// * `68..=127` — reserved.
/// * `128..=137` — `Binary(op)`. Two stack pops (right first, then
///   left), one push.
///   * `128` — sum (`L + R`)
///   * `129` — difference (`L - R`)
///   * `130` — product (`L * R`)
///   * `131` — quotient (`L / R` truncated toward zero; `L` if
///     `R == 0`)
///   * `132` — bitwise and (`L ∧ R`)
///   * `133` — bitwise or (`L ∨ R`)
///   * `134` — bitwise xor (`L ⊕ R`)
///   * `135` — pow (`L^R` truncated; `0` if `L == 0`)
///   * `136` — min
///   * `137` — max
/// * `138..=255` — reserved.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Token {
    /// A literal signed constant pushed to the stack.
    Constant(i64),
    /// Push the sample from the `n`th input image item (1-based, so
    /// `1..=32`).
    Sample(u8),
    /// Unary operator (token value `64..=67`). Carries the raw token
    /// byte for round-trip and error reporting.
    Unary(u8),
    /// Binary operator (token value `128..=137`). Carries the raw token
    /// byte.
    Binary(u8),
    /// Reserved token value (`33..=63`, `68..=127`, `138..=255`).
    /// Returned only by [`SampleTransform::parse_relaxed`]; the strict
    /// parser refuses these per av1-avif §4.2.3.3.
    Reserved(u8),
}

impl Token {
    /// True for [`Self::Constant`] and [`Self::Sample`] — tokens that
    /// produce an operand without consuming any.
    pub fn is_operand(&self) -> bool {
        matches!(self, Token::Constant(_) | Token::Sample(_))
    }

    /// True for [`Self::Unary`] — one input pop, one push.
    pub fn is_unary(&self) -> bool {
        matches!(self, Token::Unary(_))
    }

    /// True for [`Self::Binary`] — two input pops, one push.
    pub fn is_binary(&self) -> bool {
        matches!(self, Token::Binary(_))
    }
}

/// Parsed `sato` Sample Transform Derived Image Item descriptor
/// (av1-avif v1.2.0 §4.2.3). The wire format is one header byte
/// (`version:2 | reserved:4 | bit_depth:2`), then `token_count: u8`,
/// then `token_count` tokens (each one byte plus an optional
/// constant-value payload).
///
/// The reconstructed image's samples come from evaluating this
/// expression once per channel per `(x, y)` coordinate, drawing input
/// samples from the input image items named in the parallel `dimg`
/// iref's `to_ids` list (`reference_count` items in declaration order).
/// The result is the single value left on the stack after the last
/// token; it is clamped to fit the reconstructed item's
/// `PixelInformationProperty` bit depth.
///
/// Use [`Self::parse`] to decode the descriptor with strict
/// spec-conformance — reserved token values, version mismatches, and
/// stack-discipline violations all error. The descriptor stores the
/// fully decoded token list so callers can either evaluate the
/// expression themselves (via [`Self::evaluate`] on a per-sample input
/// vector) or hand the parsed structure to a future composition layer
/// when an AV1 decoder is available to produce the input items.
///
/// Caveat: composition is not implemented in oxideav yet — the
/// `oxideav-av1` decoder is the bottleneck (see crate README). This
/// parser unblocks structural inspection, validation, and any future
/// composition work that lands on top.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SampleTransform {
    /// `version` field. Spec mandates `0`; readers shall ignore items
    /// with an unrecognised version. [`Self::parse`] errors on any
    /// non-zero version (callers that prefer "ignore" semantics can
    /// match on the error and skip the item).
    pub version: u8,
    /// `bit_depth` field — selector for the intermediate precision.
    /// `0..=3` map to 8 / 16 / 32 / 64 bits via [`Self::num_bits`].
    /// [`Self::parse`] errors on any value outside that range (the
    /// wire format reserves only 2 bits so a strict reader can never
    /// observe an out-of-range value, but a relaxed parser fed garbled
    /// bytes might).
    pub bit_depth: u8,
    /// Decoded token list. The first token's evaluation happens first.
    pub tokens: Vec<Token>,
}

impl SampleTransform {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(version: u8, bit_depth: u8, tokens: Vec<Token>) -> Self {
        Self {
            version,
            bit_depth,
            tokens,
        }
    }
}

impl SampleTransform {
    /// Intermediate bit depth keyed by [`Self::bit_depth`] (av1-avif
    /// Table 1). `0 → 8`, `1 → 16`, `2 → 32`, `3 → 64`.
    pub fn num_bits(&self) -> u32 {
        bit_depth_to_num_bits(self.bit_depth)
    }

    /// Minimum value representable at [`Self::num_bits`] precision
    /// (`-2^(num_bits-1)`). Computed underflows clamp to this value
    /// per spec.
    pub fn min_value(&self) -> i64 {
        let n = self.num_bits();
        if n >= 64 {
            i64::MIN
        } else {
            -(1i64 << (n - 1))
        }
    }

    /// Maximum value representable at [`Self::num_bits`] precision
    /// (`2^(num_bits-1) - 1`). Computed overflows clamp to this value
    /// per spec.
    pub fn max_value(&self) -> i64 {
        let n = self.num_bits();
        if n >= 64 {
            i64::MAX
        } else {
            (1i64 << (n - 1)) - 1
        }
    }

    /// Parse a `sato` payload strictly per av1-avif v1.2.0 §4.2.3.2 /
    /// §4.2.3.4:
    ///
    /// * `version` must be `0`.
    /// * `token_count` must be `>= 1`.
    /// * Each sample-operand token (`1..=token_count_max`) must be
    ///   `<= reference_count` per §4.2.3.4. Pass the `dimg` iref's
    ///   reference count for the item.
    /// * Reserved token values cause an error.
    /// * The expression must evaluate without stack underflow and leave
    ///   exactly one element on the stack.
    pub fn parse(payload: &[u8], reference_count: u32) -> Result<Self> {
        let st = Self::parse_relaxed(payload)?;
        if st.version != 0 {
            return Err(Error::invalid(format!(
                "avif: sato version {} != 0",
                st.version
            )));
        }
        // bit_depth is 2 bits on the wire so always 0..=3, but
        // parse_relaxed accepts whatever it was decoded to. Re-check.
        if st.bit_depth > 3 {
            return Err(Error::invalid(format!(
                "avif: sato bit_depth {} out of 0..=3",
                st.bit_depth
            )));
        }
        // Reject reserved tokens.
        for (i, t) in st.tokens.iter().enumerate() {
            if let Token::Reserved(raw) = *t {
                return Err(Error::invalid(format!(
                    "avif: sato token[{i}] = {raw} is reserved"
                )));
            }
        }
        // Validate every sample reference fits inside reference_count.
        // Spec §4.2.3.4: `token shall be at most reference_count` when
        // 1 <= token <= 32.
        for (i, t) in st.tokens.iter().enumerate() {
            if let Token::Sample(n) = *t {
                if u32::from(n) > reference_count {
                    return Err(Error::invalid(format!(
                        "avif: sato token[{i}] sample index {n} > reference_count {reference_count}"
                    )));
                }
            }
        }
        // Validate stack discipline without evaluating actual values.
        let mut depth: i64 = 0;
        for (i, t) in st.tokens.iter().enumerate() {
            match t {
                Token::Constant(_) | Token::Sample(_) => depth += 1,
                Token::Unary(_) => {
                    if depth < 1 {
                        return Err(Error::invalid(format!(
                            "avif: sato token[{i}] unary op underflows stack"
                        )));
                    }
                    // Pop one, push one: net 0.
                }
                Token::Binary(_) => {
                    if depth < 2 {
                        return Err(Error::invalid(format!(
                            "avif: sato token[{i}] binary op underflows stack"
                        )));
                    }
                    depth -= 1; // Two pops, one push: net -1.
                }
                Token::Reserved(_) => unreachable!(),
            }
        }
        if depth != 1 {
            return Err(Error::invalid(format!(
                "avif: sato expression leaves {depth} elements on stack, expected 1"
            )));
        }
        Ok(st)
    }

    /// Parse a `sato` payload structurally without rejecting reserved
    /// tokens or unrecognised versions. Useful for diagnostic dumps of
    /// experimental files. Stack discipline is still enforced (a
    /// malformed expression can't be round-tripped).
    pub fn parse_relaxed(payload: &[u8]) -> Result<Self> {
        if payload.len() < 2 {
            return Err(Error::invalid("avif: sato header too short"));
        }
        let header = payload[0];
        let version = (header >> 6) & 0x03;
        // bits 5..=2 are reserved (spec says ignored)
        let bit_depth = header & 0x03;
        let token_count = payload[1] as usize;
        if token_count == 0 {
            return Err(Error::invalid("avif: sato token_count = 0"));
        }
        let num_bits = bit_depth_to_num_bits(bit_depth);
        let const_bytes = (num_bits / 8) as usize; // 1, 2, 4, or 8
        let mut tokens = Vec::with_capacity(token_count);
        let mut cursor = 2usize;
        for i in 0..token_count {
            if cursor >= payload.len() {
                return Err(Error::invalid(format!(
                    "avif: sato truncated before token {i} (cursor {cursor} >= {})",
                    payload.len()
                )));
            }
            let raw = payload[cursor];
            cursor += 1;
            let token = if raw == 0 {
                let end = cursor
                    .checked_add(const_bytes)
                    .ok_or_else(|| Error::invalid("avif: sato constant offset overflow"))?;
                if end > payload.len() {
                    return Err(Error::invalid(format!(
                        "avif: sato truncated constant payload for token {i} (need {const_bytes} bytes at {cursor})"
                    )));
                }
                let value = read_sint_be(&payload[cursor..end])?;
                cursor = end;
                Token::Constant(value)
            } else if raw <= 32 {
                Token::Sample(raw)
            } else if (64..=67).contains(&raw) {
                Token::Unary(raw)
            } else if (128..=137).contains(&raw) {
                Token::Binary(raw)
            } else {
                Token::Reserved(raw)
            };
            tokens.push(token);
        }
        Ok(SampleTransform {
            version,
            bit_depth,
            tokens,
        })
    }

    /// Evaluate this expression for one output sample, given the input
    /// sample values from the parallel `dimg` iref's `to_ids` list (in
    /// the same order). Returns the single value left on the stack,
    /// already clamped to the intermediate precision via the
    /// underflow / overflow rules of av1-avif §4.2.3.3.
    ///
    /// `inputs[i]` is the sample from input image item `i + 1` (the
    /// spec's `token` values for sample operands are 1-based; this
    /// helper translates them to 0-based vector indices).
    ///
    /// The caller is responsible for the final clamp into the
    /// reconstructed item's `PixelInformationProperty` bit depth, since
    /// that depth lives outside the `sato` descriptor itself.
    ///
    /// Returns an error if the expression dereferences an out-of-range
    /// sample or trips a stack underflow that wasn't caught by
    /// [`Self::parse`]'s validation (the only path is a caller passing
    /// `inputs.len() < max_sample_index_used` or a `parse_relaxed`
    /// expression that bypassed validation).
    pub fn evaluate(&self, inputs: &[i64]) -> Result<i64> {
        let min = self.min_value();
        let max = self.max_value();
        let clamp = |v: i64| v.clamp(min, max);
        let mut stack: Vec<i64> = Vec::with_capacity(self.tokens.len());
        for (i, t) in self.tokens.iter().enumerate() {
            match t {
                Token::Constant(value) => stack.push(clamp(*value)),
                Token::Sample(n) => {
                    let idx = usize::from(*n).saturating_sub(1);
                    let v = *inputs.get(idx).ok_or_else(|| {
                        Error::invalid(format!(
                            "avif: sato token[{i}] sample {n} out of range (inputs.len()={})",
                            inputs.len()
                        ))
                    })?;
                    stack.push(clamp(v));
                }
                Token::Unary(raw) => {
                    let l = stack
                        .pop()
                        .ok_or_else(|| Error::invalid("avif: sato unary stack underflow"))?;
                    let r = match *raw {
                        64 => l.checked_neg().unwrap_or(i64::MAX), // negation
                        65 => l.checked_abs().unwrap_or(i64::MAX), // abs
                        66 => !l,                                  // bitwise not
                        67 => {
                            // bsr: 0-based index of MSB if l > 0, else 0.
                            if l > 0 {
                                (63 - (l as u64).leading_zeros()) as i64
                            } else {
                                0
                            }
                        }
                        _ => {
                            return Err(Error::invalid(format!(
                                "avif: sato unary token {raw} not implemented",
                            )));
                        }
                    };
                    stack.push(clamp(r));
                }
                Token::Binary(raw) => {
                    let r = stack
                        .pop()
                        .ok_or_else(|| Error::invalid("avif: sato binary right underflow"))?;
                    let l = stack
                        .pop()
                        .ok_or_else(|| Error::invalid("avif: sato binary left underflow"))?;
                    let out = match *raw {
                        // Spec §4.2.3.3: results that underflow / overflow
                        // the intermediate bit depth are replaced by
                        // -2^(num_bits-1) / 2^(num_bits-1)-1. We compute
                        // at i64 saturation and rely on the final
                        // `clamp` call below to narrow into num_bits.
                        128 => l.saturating_add(r),
                        129 => l.saturating_sub(r),
                        130 => l.saturating_mul(r),
                        131 => {
                            if r == 0 {
                                l
                            } else {
                                // Truncate toward zero, which is Rust's
                                // default for `/` on signed integers.
                                // `i64::MIN / -1` overflows; saturate.
                                l.checked_div(r).unwrap_or(i64::MAX)
                            }
                        }
                        132 => l & r,
                        133 => l | r,
                        134 => l ^ r,
                        135 => {
                            if l == 0 {
                                0
                            } else {
                                pow_truncated(l, r)
                            }
                        }
                        136 => l.min(r),
                        137 => l.max(r),
                        _ => {
                            return Err(Error::invalid(format!(
                                "avif: sato binary token {raw} not implemented",
                            )));
                        }
                    };
                    stack.push(clamp(out));
                }
                Token::Reserved(raw) => {
                    return Err(Error::invalid(format!(
                        "avif: sato token[{i}] = {raw} reserved (cannot evaluate)",
                    )));
                }
            }
        }
        if stack.len() != 1 {
            return Err(Error::invalid(format!(
                "avif: sato expression leaves {} elements on stack, expected 1",
                stack.len()
            )));
        }
        Ok(stack[0])
    }
}

// `sato` four-CC lives in [`crate::meta::ITEM_TYPE_SATO`] (alongside
// `iovl`, `iden`, `tmap`, etc.) to keep all item-type constants on the
// `Meta` surface.

/// Map the 2-bit `bit_depth` selector to its intermediate bit depth
/// (av1-avif Table 1).
fn bit_depth_to_num_bits(bit_depth: u8) -> u32 {
    match bit_depth & 0x03 {
        0 => 8,
        1 => 16,
        2 => 32,
        3 => 64,
        _ => unreachable!(),
    }
}

/// Read a signed big-endian integer of `bytes.len()` bytes (must be
/// 1, 2, 4 or 8) and sign-extend to `i64`.
fn read_sint_be(bytes: &[u8]) -> Result<i64> {
    Ok(match bytes.len() {
        1 => bytes[0] as i8 as i64,
        2 => i16::from_be_bytes([bytes[0], bytes[1]]) as i64,
        4 => i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as i64,
        8 => i64::from_be_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ]),
        n => {
            return Err(Error::invalid(format!(
                "avif: sato constant width {n} not in {{1,2,4,8}}"
            )))
        }
    })
}

/// Truncated integer exponentiation per av1-avif Table 2 row 135.
/// `L^R` with the result truncated; the spec defines `0` for the
/// `L == 0` case via the row's own piecewise rule (handled by the
/// caller). Negative `R` truncates to `0` for `|L| > 1` (1/L^|R| < 1)
/// and to `L` itself for `L == ±1` (since `1^anything = 1` and
/// `(-1)^anything = ±1`). The result is saturated to `i64`'s range
/// when intermediate computations would overflow.
fn pow_truncated(base: i64, exp: i64) -> i64 {
    if exp < 0 {
        return match base.abs() {
            1 => {
                // 1^anything = 1; (-1)^anything alternates so just
                // compute by parity.
                if base == 1 || exp % 2 == 0 {
                    1
                } else {
                    -1
                }
            }
            _ => 0,
        };
    }
    if exp == 0 {
        return 1;
    }
    let mut result: i64 = 1;
    let mut base_acc = base;
    let mut e = exp as u64;
    while e > 0 {
        if e & 1 == 1 {
            result = match result.checked_mul(base_acc) {
                Some(v) => v,
                None => {
                    return if (result >= 0) == (base_acc >= 0) {
                        i64::MAX
                    } else {
                        i64::MIN
                    };
                }
            };
        }
        e >>= 1;
        if e > 0 {
            base_acc = match base_acc.checked_mul(base_acc) {
                Some(v) => v,
                None => {
                    return if base_acc >= 0 || (exp & 1 == 0) {
                        i64::MAX
                    } else {
                        i64::MIN
                    };
                }
            };
        }
    }
    result
}

// ---------------------------------------------------------------------------
// AV1-AVIF v1.2.0 §4.2.2 — Tone Map Derived Image Item (`tmap`) compliance
// ---------------------------------------------------------------------------

/// Result of an av1-avif §4.2.2 audit on a single `'tmap'` Tone Map
/// Derived Image Item carried by the file.
///
/// The `tmap` item type itself is registered by the HEIF / MIAF family;
/// the descriptor *body* the item points at via its `iloc` is the ISO
/// 21496-1 gain map metadata payload, parsed by
/// [`GainMapMetadata::parse`]. This audit covers the two file-shape
/// `should` constraints av1-avif §4.2.2 imposes *independently* of that
/// body:
///
/// 1. **`altr` grouping.** The base image item (i.e. the input the
///    tmap item references via `'dimg'`) and the `tmap` item should be
///    grouped together by an `'altr'` entity group, so legacy readers
///    that don't understand `tmap` still pick a valid alternate.
/// 2. **Hidden gain map.** When the tmap derivation references a "gain
///    map" input image item (the additional image input layered onto
///    the base via tone mapping), that input should be a HEIF
///    [hidden image item](crate::meta::ItemInfo::is_hidden) so a
///    legacy reader never surfaces it as a primary picture.
///
/// Both are `should`, not `shall`, so a fail does not invalidate the
/// file — it is purely informational for callers that want strict
/// av1-avif §4.2.2 mode. [`Self::is_compliant`] reports the AND of
/// both signals; [`Self::missing`] lists which checks failed.
///
/// `tmap` items carry their inputs in `'dimg'` iref entries whose
/// `from_item_ID` is the `tmap` item id (per av1-avif §4.2.3.1
/// SingleItemTypeReferenceBox conventions, the same shape `'sato'`
/// uses). Convention in HEIF gain-map layouts is `to_ids[0]` =
/// base image item, `to_ids[1..]` = gain map(s); we treat
/// `to_ids[0]` as the base and every subsequent entry as a gain map.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ToneMapCompliance {
    /// The `'tmap'` item id this audit describes.
    pub tmap_item_id: u32,
    /// The base image item id (input `0` of the tmap's `dimg`), or
    /// `None` when the tmap has no `dimg` iref / no inputs at all.
    pub base_item_id: Option<u32>,
    /// Every additional input image item id (`to_ids[1..]`) — these
    /// are the gain map inputs the spec wants hidden. Empty when the
    /// tmap has exactly one input (base only).
    pub gain_map_item_ids: Vec<u32>,
    /// True when *some* `'altr'` entity group pairs `tmap_item_id`
    /// with `base_item_id` (av1-avif §4.2.2 first `should`).
    /// False when no `grpl` is present, when no `altr` group lists
    /// both ids, or when `base_item_id` is `None`.
    pub paired_in_altr: bool,
    /// True when every id in `gain_map_item_ids` is marked hidden
    /// (`infe` flags low bit set; HEIF §6.4.2). Trivially true when
    /// `gain_map_item_ids` is empty.
    pub gain_maps_hidden: bool,
}

impl ToneMapCompliance {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        tmap_item_id: u32,
        base_item_id: Option<u32>,
        gain_map_item_ids: Vec<u32>,
        paired_in_altr: bool,
        gain_maps_hidden: bool,
    ) -> Self {
        Self {
            tmap_item_id,
            base_item_id,
            gain_map_item_ids,
            paired_in_altr,
            gain_maps_hidden,
        }
    }
}

impl ToneMapCompliance {
    /// True when both `should`s pass — there exists an `altr` group
    /// pairing the tmap with its base item, and every gain-map input
    /// is hidden.
    pub fn is_compliant(&self) -> bool {
        self.paired_in_altr && self.gain_maps_hidden
    }

    /// Human-readable list of failed checks. Returns an empty vector
    /// when [`Self::is_compliant`].
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if !self.paired_in_altr {
            out.push("altr-pairs-base-and-tmap");
        }
        if !self.gain_maps_hidden {
            out.push("gain-map-hidden");
        }
        out
    }
}

/// Audit every `'tmap'` item carried in `meta` against the two av1-avif
/// §4.2.2 `should` constraints. Returns one [`ToneMapCompliance`]
/// record per tmap item, in `iinf` declaration order. The returned
/// vector is empty when the file ships no tmap items.
///
/// Spec: av1-avif v1.2.0 §4.2.2 (Tone Map Derived Image Item) — the
/// av1-avif file-shape clauses only. The `tmap` descriptor body itself
/// (the ISO 21496-1 gain map metadata payload pointed at by the item's
/// `iloc`) is parsed separately by [`GainMapMetadata::parse`].
pub fn audit_tone_map(meta: &crate::meta::Meta) -> Vec<ToneMapCompliance> {
    let tmap_type = crate::meta::ITEM_TYPE_TMAP;
    let dimg = b(b"dimg");
    let groups = meta.groups().unwrap_or_default();
    meta.item_ids_of_type(&tmap_type)
        .into_iter()
        .map(|tmap_id| audit_one_tone_map(meta, &groups, &dimg, tmap_id))
        .collect()
}

fn audit_one_tone_map(
    meta: &crate::meta::Meta,
    groups: &[EntityGroup],
    dimg: &BoxType,
    tmap_id: u32,
) -> ToneMapCompliance {
    let inputs = meta.iref_targets(dimg, tmap_id);
    let base_item_id = inputs.first().copied();
    let gain_map_item_ids: Vec<u32> = inputs.iter().skip(1).copied().collect();

    // §4.2.2 first `should`: an `altr` group contains both the tmap and
    // its base image item.
    let paired_in_altr = match base_item_id {
        Some(base) => groups.iter().any(|g| {
            g.is_alternates() && g.entity_ids.contains(&tmap_id) && g.entity_ids.contains(&base)
        }),
        None => false,
    };

    // §4.2.2 second `should`: every gain-map input image item is
    // hidden. Items missing from `iinf` (malformed iref) count as
    // not-hidden — they fail the audit rather than silently passing.
    let gain_maps_hidden = gain_map_item_ids
        .iter()
        .all(|id| meta.item_by_id(*id).is_some_and(|info| info.is_hidden()));

    ToneMapCompliance {
        tmap_item_id: tmap_id,
        base_item_id,
        gain_map_item_ids,
        paired_in_altr,
        gain_maps_hidden,
    }
}

// ---------------------------------------------------------------------------
// ISO 21496-1:2025 Annex C.2 — Gain map metadata binary payload
// ---------------------------------------------------------------------------

/// A signed rational (`numerator / denominator`) read from the gain map
/// metadata payload. The numerator is stored as a signed 32-bit integer
/// and the denominator as an unsigned 32-bit integer per ISO 21496-1
/// Annex C.2.2; the denominator of every rational field "shall not be 0".
///
/// Stored as raw integer components rather than a pre-divided float so
/// the parse stays lossless — callers that want the value compute
/// `numerator as f64 / denominator as f64` themselves.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct GainMapRational {
    /// Signed numerator (the `int(32)` component).
    pub numerator: i32,
    /// Unsigned denominator (the `unsigned int(32)` component). The spec
    /// forbids `0`; [`GainMapMetadata::parse`] rejects any payload that
    /// carries a zero denominator.
    pub denominator: u32,
}

impl GainMapRational {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(numerator: i32, denominator: u32) -> Self {
        Self {
            numerator,
            denominator,
        }
    }
}

impl GainMapRational {
    /// The rational evaluated as an `f64`. The denominator is guaranteed
    /// non-zero by [`GainMapMetadata::parse`], so this never divides by
    /// zero on a value obtained through the parser.
    pub fn as_f64(&self) -> f64 {
        self.numerator as f64 / self.denominator as f64
    }
}

/// One per-channel gain map metadata record (ISO 21496-1 `GainMapChannel`,
/// Annex C.2.2). Each field is a signed/unsigned rational pair; the
/// per-component values are computed as `numerator / denominator`.
///
/// `gamma_numerator` and every `*_denominator` "shall not be 0" per Annex
/// C.2.3; [`GainMapMetadata::parse`] enforces those constraints.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct GainMapChannel {
    /// Per-component gain map min value (signed rational; 5.2.5.2).
    pub gain_map_min: GainMapRational,
    /// Per-component gain map max value (signed rational; 5.2.5.3).
    pub gain_map_max: GainMapRational,
    /// Per-component gamma value (unsigned rational; 5.2.5.6). The
    /// numerator is constrained non-zero in addition to the denominator.
    pub gamma: GainMapRational,
    /// Per-component baseline offset constant (signed rational; 5.2.5.4).
    pub base_offset: GainMapRational,
    /// Per-component alternate offset constant (signed rational; 5.2.5.5).
    pub alternate_offset: GainMapRational,
}

impl GainMapChannel {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        gain_map_min: GainMapRational,
        gain_map_max: GainMapRational,
        gamma: GainMapRational,
        base_offset: GainMapRational,
        alternate_offset: GainMapRational,
    ) -> Self {
        Self {
            gain_map_min,
            gain_map_max,
            gamma,
            base_offset,
            alternate_offset,
        }
    }
}

impl GainMapChannel {
    /// Unnormalize a stored gain-map sample for this component into the
    /// log2 gain value `G`, applying ISO 21496-1 §6.2.1 Formula (1):
    ///
    /// ```text
    /// G = [max(G) − min(G)] × (Gnormalized ^ (1/γ)) + min(G)
    /// ```
    ///
    /// `normalized` is the stored, gamma-encoded sample in `[0, 1]`
    /// (`Gnormalized_γ` in the spec's notation — the value as carried in
    /// the gain-map image after the §A.3.4 gamma pre-compression). The
    /// `(·)^(1/γ)` term inverts that gamma, then the `[min, max]` range
    /// scaling inverts the §A.3.3 normalization, yielding `G` in log2
    /// (stops) space ready for [`GainMapMetadata::apply_component`].
    ///
    /// `min(G)`, `max(G)` and `γ` are this channel's [`Self::gain_map_min`],
    /// [`Self::gain_map_max`] and [`Self::gamma`]. The parser guarantees
    /// `γ > 0` (non-zero numerator and denominator) so `1/γ` is finite,
    /// and `max(G) ≥ min(G)` so the span is non-negative.
    ///
    /// The stored sample is clamped into `[0, 1]` before the gamma inverse
    /// because `x^(1/γ)` is not real for negative `x` when `1/γ` is
    /// non-integral; §A.3.3 defines `Gnormalized` on `[0, 1]` so an
    /// out-of-range input is a writer error and is saturated rather than
    /// allowed to produce a NaN.
    pub fn unnormalize_log2_gain(&self, normalized: f64) -> f64 {
        let min = self.gain_map_min.as_f64();
        let max = self.gain_map_max.as_f64();
        let gamma = self.gamma.as_f64();
        let g_norm = normalized.clamp(0.0, 1.0);
        // Invert the §A.3.4 gamma: Gnormalized = (Gnormalized_γ)^(1/γ).
        let degammad = g_norm.powf(1.0 / gamma);
        (max - min) * degammad + min
    }
}

/// Parsed ISO 21496-1:2025 gain map metadata payload (Annex C.2) — the
/// binary descriptor body carried by the AVIF / HEIF `'tmap'` (tone map)
/// derived image item.
///
/// av1-avif §4.2.2 (and HEIF) register the `'tmap'` item type and the
/// `altr`/hidden file-shape constraints audited by [`audit_tone_map`];
/// the *body* the item points at via its `iloc` is this structure,
/// specified by ISO 21496-1. Resolve the item bytes with
/// [`crate::inspect::item_payload_bytes`] (or
/// [`crate::parser::item_bytes_owned`]) and hand them to
/// [`GainMapMetadata::parse`].
///
/// The byte order is big-endian regardless of the container, and the
/// 1-bit `is_multichannel` / `use_base_colour_space` flags are read from
/// the most-significant bits of a single byte (Annex C.2.1). Per Annex
/// C.2.1 the structure may carry trailing padding or future optional
/// metadata after the recognised fields; the parser stops after the last
/// recognised field and ignores the remainder, so a longer payload is
/// not an error.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct GainMapMetadata {
    /// `minimum_version` — the minimum version a parser must understand to
    /// apply the gain map. Annex C.2.3: this "shall be 0 in this version
    /// of the specification". A reader encountering an unrecognised value
    /// must ignore the payload and display the base image.
    pub minimum_version: u16,
    /// `writer_version` — the version the writer used; "shall be greater
    /// than or equal to `minimum_version`".
    pub writer_version: u16,
    /// `is_multichannel` — when true the per-channel record count is 3
    /// (channels in R, G, B order); when false it is 1.
    pub is_multichannel: bool,
    /// `use_base_colour_space` — true selects the baseline image colour
    /// primaries for the gain map application space; false selects the
    /// alternate image primaries (5.3.4).
    pub use_base_colour_space: bool,
    /// Baseline HDR headroom (unsigned rational; 5.2.6). Stored with its
    /// `int(32)` numerator widened to `i32` for a uniform rational type —
    /// the value is logically unsigned and the denominator is non-zero.
    pub base_hdr_headroom: GainMapRational,
    /// Alternate HDR headroom (unsigned rational; 5.2.7).
    pub alternate_hdr_headroom: GainMapRational,
    /// Per-channel metadata. Length is 3 when [`Self::is_multichannel`],
    /// else 1.
    pub channels: Vec<GainMapChannel>,
}

impl GainMapMetadata {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        minimum_version: u16,
        writer_version: u16,
        is_multichannel: bool,
        use_base_colour_space: bool,
        base_hdr_headroom: GainMapRational,
        alternate_hdr_headroom: GainMapRational,
        channels: Vec<GainMapChannel>,
    ) -> Self {
        Self {
            minimum_version,
            writer_version,
            is_multichannel,
            use_base_colour_space,
            base_hdr_headroom,
            alternate_hdr_headroom,
            channels,
        }
    }
}

impl GainMapMetadata {
    /// Parse the body of a `'tmap'` item — the `ToneMapImage` of
    /// HEIF Amd 1:2025 §6.6.2.4.2: one `version` byte that shall be 0
    /// followed by the ISO 21496-1 C.2 `GainMapMetadata` to the end
    /// of the item. Any other version is `Unsupported` (§6.6.2.4.3:
    /// readers shall not process it; the base image is what to show).
    pub fn parse_tone_map_image(body: &[u8]) -> Result<Self> {
        match body.split_first() {
            Some((0, metadata)) => Self::parse(metadata),
            Some((version, _)) => Err(Error::unsupported(format!(
                "avif: ToneMapImage version {version} — readers shall not process a version other \
                 than 0 (HEIF Amd 1:2025 §6.6.2.4.3); display the base image"
            ))),
            None => Err(Error::invalid("avif: empty tmap item body")),
        }
    }

    /// Parse a bare ISO 21496-1 Annex C.2.2 `GainMapMetadata` payload
    /// (the bytes after a `tmap` body's `ToneMapImage` version byte —
    /// see [`Self::parse_tone_map_image`]).
    ///
    /// Behaviour:
    ///
    /// * Returns [`AvifError::Unsupported`](crate::error::AvifError::Unsupported)
    ///   when `minimum_version != 0` — Annex C.2.3 requires such a reader
    ///   to ignore the payload, so the caller should fall back to the
    ///   base image rather than treat the bytes as malformed.
    /// * Returns [`AvifError::InvalidData`](crate::error::AvifError::InvalidData)
    ///   when the payload is truncated, when `writer_version <
    ///   minimum_version`, when any rational denominator (or the gamma
    ///   numerator) is `0`, when any channel's `gain_map_max <
    ///   gain_map_min` (§5.2.5.3 "shall be greater than or equal to"),
    ///   or when `alternate_hdr_headroom == base_hdr_headroom` (§5.2.7
    ///   "shall not be equal to") — all `shall`-level constraints from
    ///   §5.2 / Annex C.2.3.
    /// * Trailing bytes after the last recognised field are ignored
    ///   (Annex C.2.1 padding / future-optional-metadata rule).
    pub fn parse(payload: &[u8]) -> Result<Self> {
        // GainMapVersion: minimum_version(16) + writer_version(16).
        let minimum_version = read_u16(payload, 0)?;
        let writer_version = read_u16(payload, 2)?;

        if minimum_version != 0 {
            return Err(Error::unsupported(format!(
                "avif: gain map metadata minimum_version {minimum_version} not understood \
                 (ISO 21496-1 C.2.3 requires 0); caller should display the base image"
            )));
        }
        // C.2.3: writer_version shall be >= minimum_version.
        if writer_version < minimum_version {
            return Err(Error::invalid(format!(
                "avif: gain map metadata writer_version {writer_version} < minimum_version \
                 {minimum_version} (ISO 21496-1 C.2.3)"
            )));
        }

        // One flags byte: is_multichannel(1) | use_base_colour_space(1) |
        // reserved(6), MSB-first (C.2.1).
        let flags = *payload
            .get(4)
            .ok_or_else(|| Error::invalid("avif: gain map metadata truncated at flags byte"))?;
        let is_multichannel = flags & 0x80 != 0;
        let use_base_colour_space = flags & 0x40 != 0;
        let channel_count = if is_multichannel { 3 } else { 1 };

        // base/alternate HDR headroom: 4 × u32 starting at offset 5.
        let base_hdr_headroom = read_unsigned_rational(payload, 5)?;
        let alternate_hdr_headroom = read_unsigned_rational(payload, 13)?;
        // §5.2.7: "H_alternate shall not be equal to H_baseline". The
        // headroom values are unsigned rationals; compare via the
        // cross-multiplied i64 product so a different
        // (numerator, denominator) pair that reduces to the same value
        // is still flagged (e.g. 1/1 == 2/2). Denominators have already
        // been rejected when zero by `read_unsigned_rational`.
        if !rationals_differ(&base_hdr_headroom, &alternate_hdr_headroom) {
            return Err(Error::invalid(
                "avif: gain map metadata alternate_hdr_headroom equals base_hdr_headroom \
                 (ISO 21496-1 §5.2.7)",
            ));
        }

        // GainMapChannel[channel_count] follow, each 10 × 32-bit fields
        // (40 bytes): min, max, gamma, base_offset, alternate_offset.
        let mut channels = Vec::with_capacity(channel_count);
        let mut at = 21usize;
        for _ in 0..channel_count {
            let gain_map_min = read_signed_rational(payload, at)?;
            let gain_map_max = read_signed_rational(payload, at + 8)?;
            // §5.2.5.3: "For each component, max(G) shall be greater
            // than or equal to the min(G) value". Compare via the
            // cross-multiplied i64 product so the predicate is exact
            // for any (numerator, denominator) pair; denominators are
            // already non-zero (and positive, being unsigned), so the
            // product's sign is the sign of the difference.
            if !rational_ge(&gain_map_max, &gain_map_min) {
                return Err(Error::invalid(
                    "avif: gain map metadata gain_map_max < gain_map_min \
                     (ISO 21496-1 §5.2.5.3)",
                ));
            }
            let gamma = read_unsigned_rational(payload, at + 16)?;
            // C.2.3: gamma_numerator shall not be 0.
            if gamma.numerator == 0 {
                return Err(Error::invalid(
                    "avif: gain map metadata gamma_numerator is 0 (ISO 21496-1 C.2.3)",
                ));
            }
            let base_offset = read_signed_rational(payload, at + 24)?;
            let alternate_offset = read_signed_rational(payload, at + 32)?;
            channels.push(GainMapChannel {
                gain_map_min,
                gain_map_max,
                gamma,
                base_offset,
                alternate_offset,
            });
            at += 40;
        }

        Ok(GainMapMetadata {
            minimum_version,
            writer_version,
            is_multichannel,
            use_base_colour_space,
            base_hdr_headroom,
            alternate_hdr_headroom,
            channels,
        })
    }

    /// The per-channel record count implied by [`Self::is_multichannel`]
    /// (3 when multichannel, else 1). Always equal to `channels.len()`
    /// for a value obtained from [`Self::parse`].
    pub fn channel_count(&self) -> usize {
        self.channels.len()
    }

    /// The weighting factor `W` for a target HDR headroom, per ISO 21496-1
    /// §6.3 Formula (3):
    ///
    /// ```text
    /// W = sign(H_alternate − H_baseline) × clamp((H_target − H_baseline) /
    ///                                            (H_alternate − H_baseline), 0, 1)
    /// ```
    ///
    /// `W` scales how much of the gain map is applied (§6.3 NOTE 4): at
    /// `H_target == H_baseline` the gain map is not applied (`W == 0`),
    /// and at `H_target == H_alternate` it is fully applied (`W == ±1`,
    /// the sign following `sign(H_alternate − H_baseline)`). Targets
    /// outside `[H_baseline, H_alternate]` are clamped so `W` stays in
    /// `[−1, 1]`.
    ///
    /// `H_baseline` and `H_alternate` are [`Self::base_hdr_headroom`] and
    /// [`Self::alternate_hdr_headroom`]; the parser guarantees they are
    /// not equal (§5.2.7), so the denominator is non-zero.
    pub fn weight_factor(&self, target_headroom: f64) -> f64 {
        let h_base = self.base_hdr_headroom.as_f64();
        let h_alt = self.alternate_hdr_headroom.as_f64();
        let span = h_alt - h_base;
        // span != 0 is guaranteed by the §5.2.7 parse check.
        let frac = ((target_headroom - h_base) / span).clamp(0.0, 1.0);
        span.signum() * frac
    }

    /// The per-component metadata record that applies to RGB component
    /// `component` (`0 = R`, `1 = G`, `2 = B`), honouring the §5.2.5.1
    /// broadcast rule: a single-channel metadata record applies to all
    /// three colour components, while a three-channel record uses one
    /// value per component. Returns `None` only when `channels` is empty
    /// (never the case for a value from [`Self::parse`]) or `component`
    /// exceeds 2.
    fn channel_for(&self, component: usize) -> Option<&GainMapChannel> {
        if component > 2 {
            return None;
        }
        match self.channels.len() {
            // Achromatic / single per-component metadata: broadcast.
            1 => self.channels.first(),
            // Per-component metadata: index directly.
            _ => self.channels.get(component),
        }
    }

    /// Apply the gain map to one linear baseline colour component and
    /// recover the corresponding linear alternate component, per
    /// ISO 21496-1 §6.3 Formula (2):
    ///
    /// ```text
    /// Alternate = (Baseline + k_baseline) × 2^(W × G) − k_alternate
    /// ```
    ///
    /// where `G` is the unnormalized log2 gain for this component
    /// ([`GainMapChannel::unnormalize_log2_gain`] applied to the stored
    /// `normalized` sample) and `W` is the weighting factor for
    /// `target_headroom` ([`Self::weight_factor`]). `k_baseline` and
    /// `k_alternate` are the channel's [`GainMapChannel::base_offset`] and
    /// [`GainMapChannel::alternate_offset`].
    ///
    /// `component` is the RGB component index (`0 = R`, `1 = G`,
    /// `2 = B`); the metadata channel is selected via the §5.2.5.1
    /// broadcast rule (single-channel metadata applies to all three).
    /// `baseline` is the linear baseline sample (scaled so HDR reference
    /// white is `1.0`, per §A.2 / Annex B.2) and `normalized` is the
    /// stored gain-map sample in `[0, 1]` for the gain-map component that
    /// applies to this colour component — for an achromatic gain map
    /// (§6.3 NOTE 2) the same sample is supplied for all three colour
    /// components.
    ///
    /// Returns `None` when `component > 2` or `channels` is empty.
    pub fn apply_component(
        &self,
        baseline: f64,
        normalized: f64,
        target_headroom: f64,
        component: usize,
    ) -> Option<f64> {
        let ch = self.channel_for(component)?;
        let g = ch.unnormalize_log2_gain(normalized);
        let w = self.weight_factor(target_headroom);
        let k_base = ch.base_offset.as_f64();
        let k_alt = ch.alternate_offset.as_f64();
        Some((baseline + k_base) * (w * g).exp2() - k_alt)
    }

    /// Apply the gain map to a linear baseline RGB pixel and recover the
    /// linear alternate RGB pixel, per ISO 21496-1 §6.3 Formula (2)
    /// applied to each of the three colour components.
    ///
    /// `baseline` is the linear baseline `[R, G, B]` (HDR reference white
    /// `= 1.0`). `gain` is the stored gain-map sample(s): a 3-element
    /// array carries one sample per colour component, while broadcasting
    /// is the caller's job for an achromatic (single-component) gain-map
    /// image — pass the one decoded gain-map sample in all three slots
    /// (§6.3 NOTE 2). The per-component *metadata* broadcast (§5.2.5.1) is
    /// handled internally, so a single-channel-metadata file still applies
    /// correctly to all three colour components.
    ///
    /// Returns `None` when `channels` is empty (never the case for a value
    /// from [`Self::parse`]).
    pub fn apply_rgb(
        &self,
        baseline: [f64; 3],
        gain: [f64; 3],
        target_headroom: f64,
    ) -> Option<[f64; 3]> {
        Some([
            self.apply_component(baseline[0], gain[0], target_headroom, 0)?,
            self.apply_component(baseline[1], gain[1], target_headroom, 1)?,
            self.apply_component(baseline[2], gain[2], target_headroom, 2)?,
        ])
    }

    /// Apply the gain map across a whole linear baseline RGB image plane,
    /// recovering the linear alternate RGB plane (ISO 21496-1 §6.3
    /// applied pixel-by-pixel).
    ///
    /// `baseline` is `width × height × 3` linear samples, interleaved as
    /// `[R, G, B, R, G, B, …]` in row-major order (HDR reference white
    /// `= 1.0`). `gain` is the decoded gain-map plane: either `width ×
    /// height` samples (a single-component / achromatic gain map — the
    /// same sample is applied to each colour component per §6.3 NOTE 2),
    /// or `width × height × 3` interleaved samples (an RGB gain map).
    /// Gain samples are the stored, normalized `[0, 1]` values
    /// (`Gnormalized_γ`); the §6.2.1 unnormalization is performed
    /// internally.
    ///
    /// The output is a freshly allocated `width × height × 3` interleaved
    /// linear alternate RGB plane.
    ///
    /// Returns [`AvifError::InvalidData`](crate::error::AvifError::InvalidData)
    /// when:
    ///
    /// * `width × height` overflows `usize`, or `baseline.len()` is not
    ///   exactly `width × height × 3`;
    /// * `gain.len()` is neither `width × height` (achromatic) nor
    ///   `width × height × 3` (RGB);
    /// * `channels` is empty (never the case for a [`Self::parse`] value).
    ///
    /// The §6.2.2 resampling step is the **caller's** responsibility: this
    /// method requires the gain plane to already match the baseline
    /// dimensions (§6.2.2 NOTE 3 — the alternate dimensions equal the
    /// baseline dimensions). A gain map stored at a different resolution
    /// must be resampled to `width × height` before being passed here.
    pub fn apply_plane_rgb(
        &self,
        baseline: &[f64],
        gain: &[f64],
        width: u32,
        height: u32,
        target_headroom: f64,
    ) -> Result<Vec<f64>> {
        if self.channels.is_empty() {
            return Err(Error::invalid(
                "avif: gain map metadata has no channel records to apply",
            ));
        }
        let px = (width as usize)
            .checked_mul(height as usize)
            .ok_or_else(|| Error::invalid("avif: gain map plane dimensions overflow usize"))?;
        let rgb_len = px
            .checked_mul(3)
            .ok_or_else(|| Error::invalid("avif: gain map plane dimensions overflow usize"))?;
        if baseline.len() != rgb_len {
            return Err(Error::invalid(format!(
                "avif: baseline plane length {} != width*height*3 = {rgb_len}",
                baseline.len()
            )));
        }
        // Achromatic (one sample/pixel, broadcast to RGB) or interleaved
        // RGB gain plane (§6.3 NOTE 2 vs an RGB gain map).
        let achromatic = match gain.len() {
            n if n == px => true,
            n if n == rgb_len => false,
            other => {
                return Err(Error::invalid(format!(
                    "avif: gain plane length {other} is neither width*height = {px} \
                     (achromatic) nor width*height*3 = {rgb_len} (RGB)"
                )));
            }
        };

        // The weight factor depends only on the target headroom, so it is
        // constant across the whole plane — compute it once (§6.3
        // Formula 3).
        let w = self.weight_factor(target_headroom);

        let mut out = vec![0.0f64; rgb_len];
        for i in 0..px {
            for c in 0..3 {
                let base = baseline[i * 3 + c];
                let g_sample = if achromatic { gain[i] } else { gain[i * 3 + c] };
                // channel_for is Some for c in 0..3 with a non-empty
                // channels vec (guaranteed above).
                let ch = self
                    .channel_for(c)
                    .expect("channel_for is Some for c<3 with non-empty channels");
                let g = ch.unnormalize_log2_gain(g_sample);
                let k_base = ch.base_offset.as_f64();
                let k_alt = ch.alternate_offset.as_f64();
                out[i * 3 + c] = (base + k_base) * (w * g).exp2() - k_alt;
            }
        }
        Ok(out)
    }

    /// [`Self::apply_plane_rgb`] over a gain-map plane still in its
    /// **coded integer** form at `gain_bit_depth` bits — the shape the
    /// AV1 decode of a 8/10/12-bit `'tmap'` gain-map input item emits
    /// (av1-avif §4.2.2 codes the gain map as an ordinary AV1 image
    /// item). Each coded sample is first mapped to the normalized
    /// `[0, 1]` domain [`Self::apply_plane_rgb`] consumes via
    /// [`normalize_full_range_plane`] (full-range scaling at the coded
    /// depth), then the §6.3 application runs unchanged. `gain_coded`
    /// follows the same layout contract as `gain` there: `width ×
    /// height` samples for an achromatic gain map, `width × height × 3`
    /// interleaved for an RGB one.
    pub fn apply_plane_rgb_coded(
        &self,
        baseline: &[f64],
        gain_coded: &[u16],
        gain_bit_depth: u8,
        width: u32,
        height: u32,
        target_headroom: f64,
    ) -> Result<Vec<f64>> {
        let gain = normalize_full_range_plane(gain_coded, gain_bit_depth)?;
        self.apply_plane_rgb(baseline, &gain, width, height, target_headroom)
    }
}

/// Map a plane of full-range coded samples at `bit_depth` bits into the
/// normalized `[0, 1]` domain: `x / (2^bit_depth − 1)`.
///
/// This is the AV1 full-range sample convention (§5.5.2
/// `color_range = 1`: code values span the whole `[0, 2^depth − 1]`
/// interval) applied in reverse — the shape a decoded 8/10/12-bit
/// gain-map or alpha plane arrives in before any normalized-domain
/// math. Accepts `bit_depth` ∈ {8, 10, 12, 16} and rejects samples
/// that exceed the declared depth's code range.
pub fn normalize_full_range_plane(samples: &[u16], bit_depth: u8) -> Result<Vec<f64>> {
    if !matches!(bit_depth, 8 | 10 | 12 | 16) {
        return Err(Error::invalid(format!(
            "avif: bit depth {bit_depth} is not one of 8/10/12/16"
        )));
    }
    let max = ((1u32 << bit_depth) - 1) as f64;
    let ceil = 1u32 << bit_depth;
    let mut out = Vec::with_capacity(samples.len());
    for (i, &s) in samples.iter().enumerate() {
        if (s as u32) >= ceil && bit_depth < 16 {
            return Err(Error::invalid(format!(
                "avif: sample {i} = {s} exceeds the {bit_depth}-bit code range"
            )));
        }
        out.push(s as f64 / max);
    }
    Ok(out)
}

/// Read a `numerator(int32) / denominator(uint32)` rational and reject a
/// zero denominator (every denominator field "shall not be 0", C.2.3).
fn read_signed_rational(buf: &[u8], at: usize) -> Result<GainMapRational> {
    let numerator = read_u32(buf, at)? as i32;
    let denominator = read_u32(buf, at + 4)?;
    if denominator == 0 {
        return Err(Error::invalid(
            "avif: gain map metadata rational denominator is 0 (ISO 21496-1 C.2.3)",
        ));
    }
    Ok(GainMapRational {
        numerator,
        denominator,
    })
}

/// Read a `numerator(uint32) / denominator(uint32)` rational. The HDR
/// headroom numerators are logically unsigned but stored in the same
/// `GainMapRational` (`i32` numerator) for a uniform type; values up to
/// `i32::MAX` round-trip exactly and the denominator is still rejected
/// when zero.
fn read_unsigned_rational(buf: &[u8], at: usize) -> Result<GainMapRational> {
    read_signed_rational(buf, at)
}

/// True when the rational value of `a` is greater than or equal to
/// the rational value of `b`. Computes the comparison via the
/// cross-multiplied `i64` product so the predicate is exact across
/// any (numerator, denominator) pair without floating-point rounding.
///
/// Both denominators are required to be non-zero (and positive — the
/// underlying field is `unsigned int(32)` per Annex C.2.2 and the
/// reader rejects zero in `read_signed_rational`). With positive
/// denominators, `a/da >= b/db` iff `a*db >= b*da`. Numerators are
/// `i32` and denominators fit in `u32`, so the products always fit in
/// `i64` (max magnitude ~2^31 × 2^32 = 2^63, the i64 limit).
fn rational_ge(a: &GainMapRational, b: &GainMapRational) -> bool {
    let lhs = (a.numerator as i64) * (b.denominator as i64);
    let rhs = (b.numerator as i64) * (a.denominator as i64);
    lhs >= rhs
}

/// True when the rational values of `a` and `b` are not equal. Uses
/// the same exact i64 cross-multiplication as [`rational_ge`] so
/// `1/1` and `2/2` correctly compare as equal (and therefore are not
/// reported as differing).
fn rationals_differ(a: &GainMapRational, b: &GainMapRational) -> bool {
    let lhs = (a.numerator as i64) * (b.denominator as i64);
    let rhs = (b.numerator as i64) * (a.denominator as i64);
    lhs != rhs
}

/// Per-grid `shall`-level compliance against av1-avif §7's
/// transformative-property constraint:
///
/// > Transformative properties shall not be associated with items in a
/// > derivation chain (as defined in [MIAF]) that serves as an input to
/// > a grid derived image item. For example, if a file contains a grid
/// > item and its referenced coded image items, cropping, mirroring or
/// > rotation transformations are only permitted on the grid item itself.
///
/// This is a *file-shape* constraint: the spec lets the grid item itself
/// carry any of `clap` / `irot` / `imir`, but forbids any of its `dimg`
/// input tiles from doing so. A reader that processes a non-compliant
/// file would either silently get the wrong pixels (if it ignored the
/// per-tile transform) or render a torn canvas (if it honoured the
/// per-tile transform before compositing).
///
/// One [`GridDerivationAudit`] record is emitted per `'grid'` item in
/// `iinf` declaration order via [`audit_grid_derivations`]. Each record
/// lists the offending `(tile_item_id, transformative_kind)` pairs found
/// on any `dimg` input. An empty `offenders` vector is the compliant
/// case; [`Self::is_compliant`] is a one-call gate.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct GridDerivationAudit {
    /// The `'grid'` item id this audit describes.
    pub grid_item_id: u32,
    /// Tile items referenced by the grid's `dimg` iref, in declaration
    /// order. Empty when the grid has no `dimg` iref (already a malformed
    /// grid; the audit still emits the record).
    pub tile_item_ids: Vec<u32>,
    /// `(tile_item_id, property_kind)` pairs where a tile carries a
    /// transformative property (`'clap'` / `'irot'` / `'imir'` /
    /// `'iscl'`). One entry per (tile, kind) — a tile that carries
    /// all four lands as four entries. Empty when the grid is
    /// compliant.
    pub offenders: Vec<(u32, BoxType)>,
}

impl GridDerivationAudit {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(grid_item_id: u32, tile_item_ids: Vec<u32>, offenders: Vec<(u32, BoxType)>) -> Self {
        Self {
            grid_item_id,
            tile_item_ids,
            offenders,
        }
    }
}

impl GridDerivationAudit {
    /// True when no tile in the derivation chain carries any
    /// transformative property — the spec-compliant shape.
    pub fn is_compliant(&self) -> bool {
        self.offenders.is_empty()
    }

    /// Convenience: list the unique offending tile item ids (a tile that
    /// carries multiple transformative properties only appears once).
    pub fn offending_tile_ids(&self) -> Vec<u32> {
        let mut out: Vec<u32> = self.offenders.iter().map(|(id, _)| *id).collect();
        out.sort_unstable();
        out.dedup();
        out
    }
}

/// Audit every `'grid'` item carried in `meta` against the av1-avif §7
/// transformative-property `shall`. Returns one [`GridDerivationAudit`]
/// record per grid item, in `iinf` declaration order. The returned
/// vector is empty when the file ships no grid items.
///
/// Spec: av1-avif v1.2.0 §7 General constraints — "Transformative
/// properties shall not be associated with items in a derivation chain
/// that serves as an input to a grid derived image item." The
/// transformative properties this crate recognises are `'clap'`
/// (cropping, HEIF §6.5.5), `'irot'` (rotation, HEIF §6.5.10),
/// `'imir'` (mirroring, HEIF §6.5.11), and `'iscl'` (image scaling,
/// HEIF §6.5.13). `'rref'` is descriptive (not transformative) and
/// is therefore not flagged; an explicit `Property::Other`
/// association on a tile is surfaced by the existing
/// [`crate::meta::Meta::unsupported_essential_properties`] path.
pub fn audit_grid_derivations(meta: &crate::meta::Meta) -> Vec<GridDerivationAudit> {
    let grid_type = crate::parser::ITEM_TYPE_GRID;
    let dimg = b(b"dimg");
    let irot = b(b"irot");
    let imir = b(b"imir");
    let clap = b(b"clap");
    let iscl = b(b"iscl");
    meta.item_ids_of_type(&grid_type)
        .into_iter()
        .map(|grid_id| {
            let tile_item_ids = meta.iref_targets(&dimg, grid_id);
            let mut offenders = Vec::new();
            for tile_id in &tile_item_ids {
                // For each tile we check the four transformative property
                // kinds explicitly so the output preserves a stable
                // (clap, irot, imir, iscl) ordering per offending tile —
                // easier for callers (and tests) to diff than association
                // order, which depends on `ipma` writer choice.
                for kind in [clap, irot, imir, iscl] {
                    if meta.property_for(*tile_id, &kind).is_some() {
                        offenders.push((*tile_id, kind));
                    }
                }
            }
            GridDerivationAudit {
                grid_item_id: grid_id,
                tile_item_ids,
                offenders,
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// HEIF §6.6.2.1 — Identity Derived Image Item (`iden`) `shall`-level compliance
// ---------------------------------------------------------------------------

/// Per-iden `shall`-level compliance against ISO/IEC 23008-12 (HEIF) §6.6.2.1
/// (Identity derivation):
///
/// > A derived image item of the `item_type` value `'iden'` (identity
/// > transformation) may be used when it is desired to use transformative
/// > properties to derive an image item. The derived image item **shall**
/// > have no item body (i.e. no extents), and `reference_count` for the
/// > `'dimg'` item reference of a `'iden'` derived image item **shall** be
/// > equal to 1.
///
/// In addition to those two clause-local `shall`s, HEIF §6.6.1 imposes a
/// crosscutting `shall` that applies to every derived image item (`iden`
/// included):
///
/// > The number of `SingleItemTypeReferenceBoxes` with the box type `'dimg'`
/// > and with the same value of `from_item_ID` **shall** not be greater
/// > than 1.
///
/// Together, the constraints check whether a file's `'iden'` items obey
/// the standalone identity-derivation `shall`s without depending on any
/// pixel-side decode (the AV1 OBU pipeline is irrelevant here — `iden`
/// items have no body to decode in the first place).
///
/// One [`IdenCompliance`] record is emitted per `'iden'` item in `iinf`
/// declaration order via [`audit_iden_derivations`]. Each record reports:
///
/// * `dimg_reference_count` — number of `'dimg'` `to_ids` listed for the
///   iden's `from_item_ID`. Compliant value is exactly `1`.
/// * `dimg_iref_count` — how many separate `'dimg'` iref entries share the
///   iden's `from_item_ID`. Compliant value is at most `1` (HEIF §6.6.1).
/// * `has_item_body` — whether the iden's `'iloc'` entry lists any
///   non-empty extent. Compliant value is `false` (no body).
/// * `source_item_id` — the single contributing source item id, when
///   `dimg_reference_count == 1`. Useful for callers that want to resolve
///   which coded image item the iden derives from without re-walking the
///   iref.
///
/// All three checks are `shall`-level, so a fail means the file is
/// non-conformant per HEIF §6.6.2.1 / §6.6.1. [`Self::is_compliant`]
/// reports the AND of every signal; [`Self::missing`] enumerates the
/// failing checks for diagnostics.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct IdenCompliance {
    /// The `'iden'` item id this audit describes.
    pub iden_item_id: u32,
    /// Number of `'dimg'` `to_ids` listed for the iden's `from_item_ID`,
    /// across the single matching iref entry (HEIF §6.6.1 forbids more
    /// than one such entry; when multiple are present this counts the
    /// first only, and `dimg_iref_count` flags the violation separately).
    /// Compliant value: exactly `1`.
    pub dimg_reference_count: usize,
    /// Number of distinct `'dimg'` `SingleItemTypeReferenceBox` entries
    /// whose `from_item_ID` equals the iden item id. Compliant value: at
    /// most `1` (HEIF §6.6.1).
    pub dimg_iref_count: usize,
    /// `true` when the iden item's `'iloc'` entry carries any extent —
    /// HEIF §6.6.2.1 mandates the iden item have no body. Compliant
    /// value: `false`. An iden with no `'iloc'` entry at all is also
    /// compliant (empty extent list).
    pub has_item_body: bool,
    /// The single source image item id contributing to the iden, when
    /// `dimg_reference_count == 1`. `None` when the iden has zero
    /// inputs or when the input count is non-conformant (in which case
    /// the audit doesn't pick "the" source — the file is malformed and
    /// the caller should inspect `dimg_reference_count` to disambiguate).
    pub source_item_id: Option<u32>,
}

impl IdenCompliance {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        iden_item_id: u32,
        dimg_reference_count: usize,
        dimg_iref_count: usize,
        has_item_body: bool,
        source_item_id: Option<u32>,
    ) -> Self {
        Self {
            iden_item_id,
            dimg_reference_count,
            dimg_iref_count,
            has_item_body,
            source_item_id,
        }
    }
}

impl IdenCompliance {
    /// True when every HEIF §6.6.2.1 + §6.6.1 `shall` passes for this
    /// iden item:
    ///
    /// * exactly one `'dimg'` input (`dimg_reference_count == 1`),
    /// * exactly one `'dimg'` iref entry for the iden's `from_item_ID`
    ///   (`dimg_iref_count <= 1`; zero is a degenerate but still
    ///   non-conformant case),
    /// * no item body (`!has_item_body`).
    pub fn is_compliant(&self) -> bool {
        self.dimg_reference_count == 1 && self.dimg_iref_count == 1 && !self.has_item_body
    }

    /// Human-readable list of failed `shall`s. Returns an empty vector
    /// when [`Self::is_compliant`].
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.dimg_reference_count != 1 {
            out.push("dimg-reference-count-eq-1");
        }
        if self.dimg_iref_count != 1 {
            out.push("dimg-iref-count-eq-1");
        }
        if self.has_item_body {
            out.push("no-item-body");
        }
        out
    }
}

/// Audit every `'iden'` item carried in `meta` against the HEIF §6.6.2.1
/// (Identity derivation) and §6.6.1 (derived-image cross-clause)
/// `shall`-level constraints. Returns one [`IdenCompliance`] record per
/// iden item, in `iinf` declaration order. The returned vector is empty
/// when the file ships no iden items.
///
/// Spec: ISO/IEC 23008-12 (HEIF) §6.6.2.1 — "The derived image item shall
/// have no item body (i.e. no extents), and `reference_count` for the
/// `'dimg'` item reference of a `'iden'` derived image item shall be equal
/// to 1." + §6.6.1 — "The number of `SingleItemTypeReferenceBoxes` with
/// the box type `'dimg'` and with the same value of `from_item_ID` shall
/// not be greater than 1."
pub fn audit_iden_derivations(meta: &crate::meta::Meta) -> Vec<IdenCompliance> {
    let iden_type = crate::meta::ITEM_TYPE_IDEN;
    let dimg = b(b"dimg");
    meta.item_ids_of_type(&iden_type)
        .into_iter()
        .map(|iden_id| audit_one_iden(meta, &dimg, iden_id))
        .collect()
}

fn audit_one_iden(meta: &crate::meta::Meta, dimg: &BoxType, iden_id: u32) -> IdenCompliance {
    // Count how many distinct `'dimg'` iref entries share this iden as
    // their `from_item_ID` (HEIF §6.6.1: shall not be greater than 1).
    let dimg_iref_count = meta
        .irefs
        .iter()
        .filter(|e| &e.reference_type == dimg && e.from_id == iden_id)
        .count();

    // `iref_targets` returns the to_ids of the first matching entry, so
    // when `dimg_iref_count > 1` the reference count reported here is from
    // entry 0 only — that's fine: the `dimg_iref_count` field is what
    // flags the §6.6.1 violation, while `dimg_reference_count` checks the
    // §6.6.2.1 single-input shall against the (possibly first-of-many)
    // observed input list.
    let inputs = meta.iref_targets(dimg, iden_id);
    let dimg_reference_count = inputs.len();
    let source_item_id = if dimg_reference_count == 1 {
        Some(inputs[0])
    } else {
        None
    };

    // HEIF §6.6.2.1 mandates the iden item carry no item body. An item
    // with no `'iloc'` entry at all trivially has no body; an entry with
    // an empty extent list (or every extent length zero) is equivalent.
    // Any non-zero-length extent flags a violation.
    let has_item_body = meta
        .location_by_id(iden_id)
        .map(|loc| loc.extents.iter().any(|x| x.length > 0))
        .unwrap_or(false);

    IdenCompliance {
        iden_item_id: iden_id,
        dimg_reference_count,
        dimg_iref_count,
        has_item_body,
        source_item_id,
    }
}

// ---------------------------------------------------------------------------
// 'pred' brand file-constraint audit (HEIF §10.2.4)
// ---------------------------------------------------------------------------

/// Result of a `'pred'` brand file-constraint audit (HEIF §10.2.4.2).
///
/// The `'pred'` brand declares a file may contain *predictively coded
/// image items* (image items with a decoding dependency on other coded
/// image items, expressed through `'pred'` item references, §6.4.9). When
/// the brand is claimed the file shall satisfy two `shall`s (§10.2.4.2):
///
/// 1. **Dependency closure** — for every predictively coded image item,
///    the file shall also contain every item that item depends on (each
///    `'pred'` target shall be an item present in `iinf`).
/// 2. **mif1 primary independence** — if `'mif1'` is *also* among the
///    compatible brands, the primary item shall be independently coded
///    (it shall itself have no `'pred'` reference).
///
/// All flags are reported even when the file makes no `'pred'` claim, so a
/// caller can distinguish "claims pred and fails" from "no pred claim".
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PredBrandCompliance {
    /// `'pred'` is among the file's major/compatible brands.
    pub claims_pred: bool,
    /// `'mif1'` is among the compatible brands (gates the §10.2.4.2
    /// primary-independence `shall`).
    pub claims_mif1: bool,
    /// Number of predictively coded image items found (items with at
    /// least one outgoing `'pred'` reference).
    pub predictive_item_count: usize,
    /// `'pred'` targets that name an item id absent from `iinf` — each is
    /// a §10.2.4.2 dependency-closure violation. Empty when closure holds.
    pub missing_dependency_ids: Vec<u32>,
    /// `true` when `'mif1'` is claimed yet the primary item carries a
    /// `'pred'` reference (i.e. it is not independently coded) — a
    /// §10.2.4.2 violation. `false` when not applicable or satisfied.
    pub primary_not_independent: bool,
}

impl PredBrandCompliance {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        claims_pred: bool,
        claims_mif1: bool,
        predictive_item_count: usize,
        missing_dependency_ids: Vec<u32>,
        primary_not_independent: bool,
    ) -> Self {
        Self {
            claims_pred,
            claims_mif1,
            predictive_item_count,
            missing_dependency_ids,
            primary_not_independent,
        }
    }
}

impl PredBrandCompliance {
    /// `true` when every applicable §10.2.4.2 `shall` passes. Trivially
    /// `true` when the file makes no `'pred'` claim.
    pub fn is_compliant(&self) -> bool {
        if !self.claims_pred {
            return true;
        }
        self.missing_dependency_ids.is_empty() && !self.primary_not_independent
    }

    /// Human-readable list of failed `shall`s; empty when
    /// [`Self::is_compliant`].
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if !self.claims_pred {
            return out;
        }
        if !self.missing_dependency_ids.is_empty() {
            out.push("pred-dependency-closure");
        }
        if self.primary_not_independent {
            out.push("mif1-primary-independent");
        }
        out
    }
}

/// Audit a file's `'pred'` brand file-level constraints (HEIF §10.2.4.2)
/// against `meta` and the file's `compatible_brands` (plus `major_brand`).
///
/// `brands` is the brand set to test against — pass the file's
/// `major_brand` followed by its `compatible_brands` (the audit treats the
/// whole set uniformly; §10.2.4.1 places `'pred'` in `compatible_brands`).
/// The audit walks every image item, collects those with an outgoing
/// `'pred'` reference, verifies each `'pred'` target is an item present in
/// `iinf` (dependency closure), and — when `'mif1'` is also claimed —
/// checks the primary item carries no `'pred'` reference.
pub fn audit_pred_brand(meta: &crate::meta::Meta, brands: &[BoxType]) -> PredBrandCompliance {
    let pred = b(b"pred");
    let mif1 = b(b"mif1");
    let pred_brand = b(b"pred");

    let mut out = PredBrandCompliance {
        claims_pred: brands.contains(&pred_brand),
        claims_mif1: brands.contains(&mif1),
        ..PredBrandCompliance::default()
    };

    // Set of item ids present in iinf — the dependency-closure check.
    let present: std::collections::BTreeSet<u32> = meta.items.iter().map(|i| i.id).collect();

    let mut missing: Vec<u32> = Vec::new();
    for item in &meta.items {
        let deps = meta.iref_targets_of(&pred, item.id);
        if deps.is_empty() {
            continue;
        }
        out.predictive_item_count += 1;
        for dep in deps {
            if !present.contains(&dep) && !missing.contains(&dep) {
                missing.push(dep);
            }
        }
    }
    out.missing_dependency_ids = missing;

    if out.claims_mif1 {
        if let Some(primary) = meta.primary_item_id {
            out.primary_not_independent = !meta.iref_targets_of(&pred, primary).is_empty();
        }
    }

    out
}

// ---------------------------------------------------------------------------
// AV1 Alpha Image Item bit-depth match audit (av1-avif v1.2.0 §4.1)
// ---------------------------------------------------------------------------

/// Decode bit-depth from the first three bytes of an `av1C` (AV1
/// CodecConfigurationRecord) payload. Returns `None` when the slice is
/// too short to carry the `high_bitdepth` / `twelve_bit` flag byte.
///
/// Layout per av1-avif §2.2.1 (which references AV1 Bitstream &
/// Decoding Process §6.4): `av1C[2]` packs
/// `high_bitdepth (1) | twelve_bit (1) | monochrome (1) |
///  chroma_subsampling_x (1) | chroma_subsampling_y (1) |
///  chroma_sample_position (2) | reserved (1)`. Bit depth is `8`
/// (neither flag), `10` (high only), or `12` (both).
fn decode_av1c_bit_depth(av1c: &[u8]) -> Option<u8> {
    if av1c.len() < 3 {
        return None;
    }
    let b2 = av1c[2];
    let high_bitdepth = ((b2 >> 6) & 1) != 0;
    let twelve_bit = ((b2 >> 5) & 1) != 0;
    Some(if twelve_bit {
        12
    } else if high_bitdepth {
        10
    } else {
        8
    })
}

/// Per-(alpha, master) `shall`-level compliance against av1-avif v1.2.0
/// §4.1 (Auxiliary Image Items and Sequences):
///
/// > An AV1 Alpha Image Item (respectively an AV1 Alpha Image Sequence)
/// > shall be encoded with the same bit depth as the associated master
/// > AV1 Image Item (respectively AV1 Image Sequence).
///
/// One [`AlphaBitDepthAudit`] record is emitted per `(alpha_item_id,
/// master_item_id)` pair an `auxl` iref's `to_ids` declares, in iref
/// declaration order. The audit is independent of any AV1 OBU decode —
/// the check operates entirely on the `av1C` configuration record
/// surfaced by the box walker.
///
/// Fields:
///
/// * `alpha_bit_depth` / `master_bit_depth` — bit depths extracted from
///   each item's `av1C` property (`8`, `10`, or `12`). `None` when the
///   corresponding item carries no `av1C` (malformed) or when the
///   `av1C` payload is too short to carry the flag byte.
/// * `master_missing_av1c` — `true` when the master item id appearing
///   in the `auxl` iref does not resolve to an item with an `av1C`
///   property. This is also a §2.1 violation (every AV1 Image Item
///   shall carry `av1C`) and surfaces alongside the bit-depth check
///   here for a single point of inspection.
/// * `alpha_missing_av1c` — same for the alpha item.
///
/// The check passes ([`AlphaBitDepthAudit::is_compliant`]) when both
/// items carry an `av1C` and both decoded bit depths agree. Either
/// item missing `av1C`, or any mismatch, fails the audit.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct AlphaBitDepthAudit {
    /// The AV1 Alpha Image Item id (the `auxl` iref's `from_id`).
    pub alpha_item_id: u32,
    /// The associated master AV1 Image Item id (one of the `auxl`
    /// iref's `to_ids`).
    pub master_item_id: u32,
    /// Bit depth decoded from the alpha item's `av1C` (`8`, `10`, or
    /// `12`), or `None` when `av1C` is absent or truncated.
    pub alpha_bit_depth: Option<u8>,
    /// Bit depth decoded from the master item's `av1C`, or `None` when
    /// `av1C` is absent or truncated.
    pub master_bit_depth: Option<u8>,
    /// `true` when the alpha item carries no `av1C` association at all.
    /// Distinct from a present-but-truncated `av1C` (which surfaces as
    /// `alpha_bit_depth = None` without setting this flag).
    pub alpha_missing_av1c: bool,
    /// `true` when the master item carries no `av1C` association at
    /// all.
    pub master_missing_av1c: bool,
}

impl AlphaBitDepthAudit {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        alpha_item_id: u32,
        master_item_id: u32,
        alpha_bit_depth: Option<u8>,
        master_bit_depth: Option<u8>,
        alpha_missing_av1c: bool,
        master_missing_av1c: bool,
    ) -> Self {
        Self {
            alpha_item_id,
            master_item_id,
            alpha_bit_depth,
            master_bit_depth,
            alpha_missing_av1c,
            master_missing_av1c,
        }
    }
}

impl AlphaBitDepthAudit {
    /// True when both items carry an `av1C` whose decoded bit depth
    /// agrees — the spec-compliant shape per av1-avif §4.1.
    pub fn is_compliant(&self) -> bool {
        match (self.alpha_bit_depth, self.master_bit_depth) {
            (Some(a), Some(m)) => a == m,
            _ => false,
        }
    }

    /// Human-readable list of failed `shall`s. Returns an empty vector
    /// when [`Self::is_compliant`].
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.alpha_missing_av1c {
            out.push("alpha-item-missing-av1C");
        } else if self.alpha_bit_depth.is_none() {
            out.push("alpha-item-av1C-truncated");
        }
        if self.master_missing_av1c {
            out.push("master-item-missing-av1C");
        } else if self.master_bit_depth.is_none() {
            out.push("master-item-av1C-truncated");
        }
        if let (Some(a), Some(m)) = (self.alpha_bit_depth, self.master_bit_depth) {
            if a != m {
                out.push("alpha-master-bit-depth-mismatch");
            }
        }
        out
    }
}

/// Audit every `(AV1 Alpha Image Item, associated master AV1 Image
/// Item)` pairing carried in `meta` against the av1-avif §4.1 `shall`
/// that they share bit depth. Returns one [`AlphaBitDepthAudit`] record
/// per `(alpha, master)` pair declared by an `auxl` iref. The returned
/// vector is empty when the file ships no AV1 Alpha Image Items.
///
/// An item qualifies as an "AV1 Alpha Image Item" when:
///
/// 1. It is the `from_id` of an `auxl` iref entry, and
/// 2. It carries an `auxC` property whose URN starts with the alpha
///    prefix (`urn:mpeg:mpegB:cicp:systems:auxiliary:alpha`), matching
///    [`crate::alpha::ALPHA_URN_PREFIX`].
///
/// Each `to_id` in the same iref entry is audited as a master. A single
/// alpha item declared against multiple masters (a `to_ids` list of
/// length > 1) emits one record per master, in `to_ids` order — the
/// `shall` applies per pairing. Iref entries are processed in the order
/// they appear inside the source `iref` box.
///
/// Spec: av1-avif v1.2.0 §4.1 — "An AV1 Alpha Image Item (respectively
/// an AV1 Alpha Image Sequence) shall be encoded with the same bit
/// depth as the associated master AV1 Image Item (respectively AV1
/// Image Sequence)."
///
/// Either side may be a **derived** item (HEIF §6.4.1: an auxiliary
/// image may be a `grid` of coded tiles, and a grid primary's alpha is
/// such a grid): its `av1C` is then resolved through the first `dimg`
/// input of the derivation chain — the coded leaf whose configuration
/// record governs the whole derived image (all tiles share one
/// depth, av1-avif §7 / HEIF §6.6.2.3).
pub fn audit_alpha_bit_depth(meta: &crate::meta::Meta) -> Vec<AlphaBitDepthAudit> {
    let auxl = b(b"auxl");
    let auxc = b(b"auxC");
    let mut out = Vec::new();
    for entry in &meta.irefs {
        if entry.reference_type != auxl {
            continue;
        }
        let alpha_id = entry.from_id;
        // Classify the candidate as an alpha auxiliary by URN prefix
        // match against the `auxC` property. Non-alpha auxiliaries
        // (depth maps, HDR gain maps) are bound by separate `shall`s
        // beyond §4.1's bit-depth constraint and don't surface here.
        let is_alpha = match meta.property_for(alpha_id, &auxc) {
            Some(crate::meta::Property::AuxC(aux)) => {
                aux.aux_type.starts_with(crate::alpha::ALPHA_URN_PREFIX)
            }
            _ => false,
        };
        if !is_alpha {
            continue;
        }
        let (alpha_bit_depth, alpha_missing_av1c) = match effective_av1c(meta, alpha_id, 0) {
            Some(bytes) => (decode_av1c_bit_depth(bytes), false),
            None => (None, true),
        };
        for &master_id in &entry.to_ids {
            let (master_bit_depth, master_missing_av1c) = match effective_av1c(meta, master_id, 0) {
                Some(bytes) => (decode_av1c_bit_depth(bytes), false),
                None => (None, true),
            };
            out.push(AlphaBitDepthAudit {
                alpha_item_id: alpha_id,
                master_item_id: master_id,
                alpha_bit_depth,
                master_bit_depth,
                alpha_missing_av1c,
                master_missing_av1c,
            });
        }
    }
    out
}

/// The `av1C` governing `item_id`: its own property, or — for a derived
/// item without one — the record of its first `dimg` input, recursively
/// (depth-guarded by [`MAX_DERIVATION_DEPTH`]).
fn effective_av1c(meta: &crate::meta::Meta, item_id: u32, depth: u32) -> Option<&[u8]> {
    if depth > MAX_DERIVATION_DEPTH {
        return None;
    }
    if let Some(crate::meta::Property::Av1C(bytes)) = meta.property_for(item_id, &b(b"av1C")) {
        return Some(bytes);
    }
    let inputs = meta.iref_targets(&b(b"dimg"), item_id);
    let &first = inputs.first()?;
    if first == item_id {
        return None;
    }
    effective_av1c(meta, first, depth + 1)
}

/// Outcome of walking a single AV1 Image Item's OBU stream to count
/// Sequence Header OBUs, per av1-avif v1.2.0 §2.1 — "The AV1 Image
/// Item Data shall have exactly one Sequence Header OBU."
///
/// One record per AV1 Image Item (`item_type == 'av01'`) in declaration
/// order. The audit is purely structural: it walks the framing defined
/// in AV1 §5.3.1 (header byte plus leb128 `obu_size`) and reads the
/// `obu_type` field from each OBU header (AV1 §5.3.2), incrementing
/// [`Self::sequence_header_count`] each time the type equals
/// `OBU_SEQUENCE_HEADER` (value `1`, per AV1 §6.2.1's `obu_type`
/// enumeration). The OBU payload bodies themselves are not decoded — the
/// walker only needs the framing.
///
/// Three structural failure modes are surfaced distinctly from a plain
/// `sequence_header_count != 1` mismatch:
///
/// * [`Self::missing_iloc`] — the `iinf` lists the item but no `iloc`
///   resolves its bytes. The OBU walk is not attempted.
/// * [`Self::truncated_obu`] — the OBU framing walker hit the end of
///   the stream mid-OBU (truncated leb128, or a declared `obu_size`
///   that runs past the item payload). Any OBUs successfully walked
///   before truncation are still counted; the flag tells the caller
///   the count may be an undercount of the well-formed file the
///   writer intended.
/// * [`Self::has_size_field_zero`] — at least one OBU in the stream
///   has `obu_has_size_field == 0`. AV1 §5.3.1 requires that OBUs
///   carried inside a container that does not separately frame each
///   OBU (which is the case for AVIF image items, see §2.1's
///   "identical to the content of an AV1 Sample marked as 'sync'"
///   constraint and [AV1-ISOBMFF] §2.3.2's requirement that the
///   has_size flag be set when chaining OBUs inside one sample) must
///   carry `obu_size`. We surface this as a separate signal because
///   the walker cannot frame an OBU without an explicit size when
///   chained — it stops at the first such OBU and the count from
///   that point on is undefined.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct SequenceHeaderObuAudit {
    /// AV1 Image Item id whose payload was walked.
    pub item_id: u32,
    /// Number of OBUs whose header byte decoded to
    /// `obu_type == OBU_SEQUENCE_HEADER` (value `1`).
    pub sequence_header_count: u32,
    /// Total number of OBUs walked (successfully framed) in the
    /// stream. Diagnostic; not a `shall` check on its own.
    pub total_obu_count: u32,
    /// `true` when no `iloc` entry resolved the item's bytes. The OBU
    /// walk was skipped; [`Self::sequence_header_count`] and
    /// [`Self::total_obu_count`] are both `0`.
    pub missing_iloc: bool,
    /// `true` when the framing walker hit end-of-stream mid-OBU
    /// (truncated leb128 byte sequence, or a declared `obu_size` that
    /// runs past the end of the item payload).
    pub truncated_obu: bool,
    /// `true` when the walker encountered an OBU whose header byte has
    /// `obu_has_size_field == 0`. The walker stops at that OBU because
    /// it has no in-band length to advance past it. Per AV1 §5.3.1 +
    /// av1-avif §2.1, AV1 Image Item Data chains OBUs into one item
    /// payload and the `has_size` bit is required.
    pub has_size_field_zero: bool,
}

impl SequenceHeaderObuAudit {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        item_id: u32,
        sequence_header_count: u32,
        total_obu_count: u32,
        missing_iloc: bool,
        truncated_obu: bool,
        has_size_field_zero: bool,
    ) -> Self {
        Self {
            item_id,
            sequence_header_count,
            total_obu_count,
            missing_iloc,
            truncated_obu,
            has_size_field_zero,
        }
    }
}

impl SequenceHeaderObuAudit {
    /// True when the walk succeeded structurally (`!missing_iloc &&
    /// !truncated_obu && !has_size_field_zero`) AND the OBU stream
    /// contains exactly one Sequence Header OBU.
    ///
    /// Spec: av1-avif v1.2.0 §2.1.
    pub fn is_compliant(&self) -> bool {
        !self.missing_iloc
            && !self.truncated_obu
            && !self.has_size_field_zero
            && self.sequence_header_count == 1
    }

    /// Human-readable list of `shall`-level failures. Empty when
    /// [`Self::is_compliant`].
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.missing_iloc {
            out.push("av01-item-missing-iloc");
        }
        if self.has_size_field_zero {
            out.push("av01-item-obu-has-size-field-zero");
        }
        if self.truncated_obu {
            out.push("av01-item-obu-stream-truncated");
        }
        if !self.missing_iloc && !self.has_size_field_zero && !self.truncated_obu {
            match self.sequence_header_count {
                0 => out.push("av01-item-missing-sequence-header-obu"),
                1 => {} // compliant
                _ => out.push("av01-item-multiple-sequence-header-obus"),
            }
        }
        out
    }
}

/// `obu_type` value for `OBU_SEQUENCE_HEADER` per AV1 §6.2.1.
const AV1_OBU_TYPE_SEQUENCE_HEADER: u8 = 1;

/// Decode an AV1 leb128 `obu_size` value (AV1 §4.10.5) from `bytes`.
///
/// Returns the decoded value and the number of bytes consumed
/// (`Leb128Bytes`, 1..=8). Returns `Err` when the bitstream ends in
/// the middle of a leb128 byte sequence (continuation bit set on the
/// last available byte) or when the leb128 sequence exceeds 8 bytes
/// without terminating.
fn read_leb128(bytes: &[u8]) -> core::result::Result<(u32, usize), ()> {
    let mut value: u64 = 0;
    for i in 0..8 {
        if i >= bytes.len() {
            return Err(());
        }
        let byte = bytes[i];
        value |= u64::from(byte & 0x7f) << (i * 7);
        if byte & 0x80 == 0 {
            // §4.10.5 also requires value <= (1 << 32) - 1 for
            // bitstream conformance; we surface a u32 so any wider
            // claim trips the conversion.
            if value > u64::from(u32::MAX) {
                return Err(());
            }
            return Ok((value as u32, i + 1));
        }
    }
    Err(())
}

/// Walk the OBU framing of one AV1 Image Item's payload and count
/// Sequence Header OBUs. `payload` is the raw item bytes resolved via
/// the iloc.
///
/// Per AV1 §5.3.1 / §5.3.2:
///
/// * OBU header byte: `obu_forbidden_bit(1) | obu_type(4) |
///   obu_extension_flag(1) | obu_has_size_field(1) | obu_reserved_1bit(1)`.
/// * If `obu_extension_flag == 1`, one extension header byte follows
///   (§5.3.3 — temporal_id + spatial_id + reserved, total 8 bits).
/// * If `obu_has_size_field == 1`, a `leb128()` `obu_size` follows;
///   that many bytes are the OBU payload.
/// * If `obu_has_size_field == 0` we cannot frame the next OBU — the
///   walker stops and reports [`SequenceHeaderObuAudit::has_size_field_zero`].
fn walk_obu_stream(item_id: u32, payload: &[u8]) -> SequenceHeaderObuAudit {
    let mut out = SequenceHeaderObuAudit {
        item_id,
        ..SequenceHeaderObuAudit::default()
    };
    let mut cursor = 0usize;
    while cursor < payload.len() {
        // 1. OBU header byte.
        let header = payload[cursor];
        cursor += 1;
        let obu_type = (header >> 3) & 0x0f;
        let obu_extension_flag = (header >> 2) & 0x01;
        let obu_has_size_field = (header >> 1) & 0x01;
        // 2. Optional extension header.
        if obu_extension_flag == 1 {
            if cursor >= payload.len() {
                out.truncated_obu = true;
                return out;
            }
            cursor += 1;
        }
        // 3. Size field. AV1 §5.3.1 — when chained in a container that
        // doesn't externally frame each OBU (which is exactly the
        // AVIF Image Item Data case per av1-avif §2.1), this MUST be
        // set or we cannot find the next OBU.
        if obu_has_size_field == 0 {
            out.has_size_field_zero = true;
            // Still count this OBU's type — the header byte was
            // successfully read.
            if obu_type == AV1_OBU_TYPE_SEQUENCE_HEADER {
                out.sequence_header_count = out.sequence_header_count.saturating_add(1);
            }
            out.total_obu_count = out.total_obu_count.saturating_add(1);
            return out;
        }
        let (obu_size, leb_len) = match read_leb128(&payload[cursor..]) {
            Ok(v) => v,
            Err(()) => {
                out.truncated_obu = true;
                return out;
            }
        };
        cursor += leb_len;
        let obu_size = obu_size as usize;
        if cursor
            .checked_add(obu_size)
            .map(|end| end > payload.len())
            .unwrap_or(true)
        {
            out.truncated_obu = true;
            // The header byte itself was readable, count it before
            // bailing — this lets a caller see whether the truncation
            // dropped a Sequence Header.
            if obu_type == AV1_OBU_TYPE_SEQUENCE_HEADER {
                out.sequence_header_count = out.sequence_header_count.saturating_add(1);
            }
            out.total_obu_count = out.total_obu_count.saturating_add(1);
            return out;
        }
        cursor += obu_size;
        if obu_type == AV1_OBU_TYPE_SEQUENCE_HEADER {
            out.sequence_header_count = out.sequence_header_count.saturating_add(1);
        }
        out.total_obu_count = out.total_obu_count.saturating_add(1);
    }
    out
}

/// Audit every AV1 Image Item (`item_type == 'av01'`) in `meta`
/// against the av1-avif v1.2.0 §2.1 `shall` "The AV1 Image Item Data
/// shall have exactly one Sequence Header OBU."
///
/// The function walks each item's payload bytes (resolved via the
/// item's `iloc` entry against `file`) and counts OBUs whose header
/// byte decodes to `obu_type == OBU_SEQUENCE_HEADER` (value `1`, per
/// AV1 §6.2.1). Items are reported in the same order as
/// `Meta::item_ids_of_type(b"av01")`.
///
/// The returned vector is empty when the file ships no AV1 Image
/// Items (a degenerate case, since an AVIF primary is required to
/// have at least one).
///
/// Spec sources:
/// * av1-avif v1.2.0 §2.1 — the `shall` audited.
/// * AV1 (Bitstream & Decoding Process Specification v1.0.0-errata1)
///   §5.3.1 (general OBU framing), §5.3.2 (OBU header byte layout),
///   §4.10.5 (`leb128()` decoder), §6.2.1 (`obu_type` enumeration).
pub fn audit_sequence_header_obu(
    meta: &crate::meta::Meta,
    file: &[u8],
) -> Vec<SequenceHeaderObuAudit> {
    let av01 = b(b"av01");
    let mut out = Vec::new();
    for item_id in meta.item_ids_of_type(&av01) {
        let Some(loc) = meta.location_by_id(item_id) else {
            out.push(SequenceHeaderObuAudit {
                item_id,
                missing_iloc: true,
                ..SequenceHeaderObuAudit::default()
            });
            continue;
        };
        // Reuse the standard iloc resolver. A failure here (e.g.
        // construction_method we don't support, or extent offsets
        // outside `file`) is surfaced the same way as missing iloc —
        // the audit can't reach the bytes either way.
        let Ok(payload) = crate::parser::item_bytes(file, loc) else {
            out.push(SequenceHeaderObuAudit {
                item_id,
                missing_iloc: true,
                ..SequenceHeaderObuAudit::default()
            });
            continue;
        };
        out.push(walk_obu_stream(item_id, payload));
    }
    out
}

// ===========================================================================
// AVIF Profile compliance — av1-avif v1.2.0 §8.2 / §8.3 (MA1B / MA1A)
// ===========================================================================

/// AV1 `seq_level_idx_0` decoded from `av1C[1]` low 5 bits, or `None`
/// when `av1c` is too short to carry byte 1. av1-isobmff §2.3 packs
/// `seq_profile (3) | seq_level_idx_0 (5)` into byte 1.
///
/// Crate-visible so the AVIS audit ([`crate::avis::audit_avis_profile_compliance`])
/// can decode the per-track av1C surfaced via `stsd → av01 → av1C`.
pub(crate) fn decode_av1c_seq_level_idx_0(av1c: &[u8]) -> Option<u8> {
    if av1c.len() < 2 {
        return None;
    }
    Some(av1c[1] & 0x1F)
}

/// AV1 `seq_profile` decoded from `av1C[1]` high 3 bits, or `None`
/// when `av1c` is too short. Per AV1 Annex A.2: `0` = Main,
/// `1` = High, `2` = Professional.
///
/// Crate-visible so the AVIS audit ([`crate::avis::audit_avis_profile_compliance`])
/// can decode the per-track av1C surfaced via `stsd → av01 → av1C`.
pub(crate) fn decode_av1c_seq_profile(av1c: &[u8]) -> Option<u8> {
    if av1c.len() < 2 {
        return None;
    }
    Some((av1c[1] >> 5) & 0x7)
}

/// Which AVIF profile brand a record was audited against — see
/// [`AvifProfileCompliance::profile`].
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AvifProfile {
    /// `MA1B` — AVIF Baseline Profile (av1-avif v1.2.0 §8.2). Requires
    /// AV1 Main Profile (`seq_profile == 0`) at level 5.1 or lower
    /// (`seq_level_idx_0 <= 13`).
    Baseline,
    /// `MA1A` — AVIF Advanced Profile (av1-avif v1.2.0 §8.3). For AV1
    /// Image Items requires AV1 High Profile (`seq_profile <= 1`) at
    /// level 6.0 or lower (`seq_level_idx_0 <= 16`).
    Advanced,
}

/// Per-AV1-Image-Item compliance against the av1-avif v1.2.0 §8.2 /
/// §8.3 profile `shall`-level constraints when the file's `ftyp`
/// declares the corresponding brand.
///
/// One record is emitted by [`audit_avif_profile_compliance`] per
/// `(AV1 Image Item, declared profile)` pairing — when a file
/// declares both `MA1B` and `MA1A` brands (unusual but legal per §8.1
/// since both are independent profile claims), each AV1 Image Item
/// emits one record per declared brand.
///
/// The fields:
///
/// * [`Self::profile`] — which AVIF profile this record is checking.
/// * [`Self::item_id`] — the AV1 Image Item's id.
/// * [`Self::seq_profile`] — the AV1 `seq_profile` value decoded from
///   the item's `av1C[1]` high 3 bits (`0` = Main, `1` = High,
///   `2` = Professional). `None` when `av1C` is absent or truncated.
/// * [`Self::seq_level_idx_0`] — the AV1 `seq_level_idx_0` value
///   decoded from `av1C[1]` low 5 bits (`13` = level 5.1,
///   `16` = level 6.0, `31` = unconstrained per AV1 §A.3). `None` when
///   `av1C` is absent or truncated.
/// * [`Self::missing_av1c`] — `true` when the item carries no `av1C`
///   association at all (also a §2.1 violation; surfaced here so a
///   single point of inspection covers both).
///
/// The check passes ([`Self::is_compliant`]) when the `av1C` is
/// present and the (seq_profile, seq_level_idx_0) pair satisfies the
/// declared profile's constraints. The seq_level_idx_0 = 31 "Maximum
/// parameters" value is treated as not-compliant for either profile:
/// the spec's profile clauses both bound the level (5.1 / 6.0), and
/// the level-31 carve-out signals unconstrained sizing, which is
/// outside either profile's reach.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AvifProfileCompliance {
    /// The AVIF profile this record is checking the item against.
    pub profile: AvifProfile,
    /// The AV1 Image Item id whose `av1C` was inspected.
    pub item_id: u32,
    /// `seq_profile` decoded from `av1C[1]` high 3 bits, or `None`
    /// when `av1C` is absent or truncated.
    pub seq_profile: Option<u8>,
    /// `seq_level_idx_0` decoded from `av1C[1]` low 5 bits, or `None`
    /// when `av1C` is absent or truncated.
    pub seq_level_idx_0: Option<u8>,
    /// `true` when the item has no `av1C` property association at all
    /// (distinct from a present-but-truncated `av1C`, which surfaces
    /// as both fields `None` without setting this flag).
    pub missing_av1c: bool,
}

impl AvifProfileCompliance {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        profile: AvifProfile,
        item_id: u32,
        seq_profile: Option<u8>,
        seq_level_idx_0: Option<u8>,
        missing_av1c: bool,
    ) -> Self {
        Self {
            profile,
            item_id,
            seq_profile,
            seq_level_idx_0,
            missing_av1c,
        }
    }
}

impl AvifProfileCompliance {
    /// True when the AV1 Image Item satisfies the declared AVIF
    /// profile's `shall`-level constraints on AV1 profile + level.
    ///
    /// Baseline (`MA1B`, §8.2): `seq_profile == 0` (AV1 Main) AND
    /// `seq_level_idx_0 <= 13` (level ≤ 5.1).
    ///
    /// Advanced (`MA1A`, §8.3): `seq_profile <= 1` (AV1 Main or
    /// High) AND `seq_level_idx_0 <= 16` (level ≤ 6.0). The §8.3
    /// `shall` is "The AV1 profile shall be the High Profile" — the
    /// AV1 Annex A.2 definition of "High Profile decoders" includes
    /// streams with `seq_profile == 0` (Main is a subset of High),
    /// so a Main-Profile stream is also accepted under `MA1A`.
    ///
    /// Returns `false` when `av1C` is missing or truncated.
    pub fn is_compliant(&self) -> bool {
        match (self.seq_profile, self.seq_level_idx_0) {
            (Some(p), Some(l)) => match self.profile {
                AvifProfile::Baseline => p == 0 && l <= 13,
                AvifProfile::Advanced => p <= 1 && l <= 16,
            },
            _ => false,
        }
    }

    /// Human-readable list of failed `shall`s. Returns an empty vector
    /// when [`Self::is_compliant`]. Tokens:
    /// `item-missing-av1C`, `item-av1C-truncated`,
    /// `seq-profile-out-of-range`, `seq-level-idx-out-of-range`.
    pub fn missing(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if self.missing_av1c {
            out.push("item-missing-av1C");
            return out;
        }
        if self.seq_profile.is_none() || self.seq_level_idx_0.is_none() {
            out.push("item-av1C-truncated");
            return out;
        }
        let p = self.seq_profile.unwrap();
        let l = self.seq_level_idx_0.unwrap();
        let (max_p, max_l) = match self.profile {
            AvifProfile::Baseline => (0u8, 13u8),
            AvifProfile::Advanced => (1u8, 16u8),
        };
        if p > max_p {
            out.push("seq-profile-out-of-range");
        }
        if l > max_l {
            out.push("seq-level-idx-out-of-range");
        }
        out
    }
}

/// Audit every AV1 Image Item in `meta` against the av1-avif v1.2.0
/// §8.2 / §8.3 profile `shall`-level constraints, but only when the
/// file's `ftyp` declares the corresponding brand. Items are reported
/// in `iinf` declaration order; for files declaring both `MA1B` and
/// `MA1A`, each item emits one record per declared brand (Baseline
/// before Advanced).
///
/// The audit is independent of any AV1 OBU decode — it operates
/// entirely on `av1C[1]` (which packs `seq_profile (3) |
/// seq_level_idx_0 (5)` per av1-isobmff §2.3). For grid primaries the
/// constraint is on the tile items, not the grid item itself — `'grid'`
/// items carry no `av1C` and are skipped here (the per-tile records
/// give the same coverage, since av1-avif §4.2 keeps the AV1 profile +
/// level uniform across grid tiles).
///
/// The returned vector is empty when (a) the file ships no AV1 Image
/// Items, or (b) the file declares neither `MA1B` nor `MA1A` in its
/// `ftyp` compatible-brands list. The second case is a deliberate
/// no-op: a file that doesn't claim a profile has nothing to fail.
///
/// Spec sources:
/// * av1-avif v1.2.0 §8.2 — `MA1B` Baseline Profile constraints.
/// * av1-avif v1.2.0 §8.3 — `MA1A` Advanced Profile constraints.
/// * AV1 §A.2 — Profiles (Main / High / Professional).
/// * AV1 §A.3 — Levels (seq_level_idx_0 ↔ X.Y mapping; 13 = 5.1,
///   16 = 6.0, 31 = unconstrained).
/// * av1-isobmff §2.3 — `av1C` byte layout.
pub fn audit_avif_profile_compliance(
    meta: &crate::meta::Meta,
    brands: &crate::parser::BrandClass,
) -> Vec<AvifProfileCompliance> {
    let av01 = b(b"av01");
    let av1c_kind = b(b"av1C");
    let mut out = Vec::new();
    if !brands.is_baseline_profile && !brands.is_advanced_profile {
        return out;
    }
    for item_id in meta.item_ids_of_type(&av01) {
        let (seq_profile, seq_level_idx_0, missing_av1c) =
            match meta.property_for(item_id, &av1c_kind) {
                Some(crate::meta::Property::Av1C(bytes)) => (
                    decode_av1c_seq_profile(bytes),
                    decode_av1c_seq_level_idx_0(bytes),
                    false,
                ),
                _ => (None, None, true),
            };
        if brands.is_baseline_profile {
            out.push(AvifProfileCompliance {
                profile: AvifProfile::Baseline,
                item_id,
                seq_profile,
                seq_level_idx_0,
                missing_av1c,
            });
        }
        if brands.is_advanced_profile {
            out.push(AvifProfileCompliance {
                profile: AvifProfile::Advanced,
                item_id,
                seq_profile,
                seq_level_idx_0,
                missing_av1c,
            });
        }
    }
    out
}

// ===========================================================================
// Derived-image geometry resolution (HEIF §6.3 / §6.6.2)
// ===========================================================================
//
// §6.3 defines the *output image* of any image item as the result of
// applying its transformative item properties — in ItemPropertyAssociation
// order — to the item's *reconstructed image*. For a coded item the
// reconstructed image is the decoded picture (`ispe` dimensions); for a
// derived item it is the result of the derivation operation (the
// descriptor's `output_width`/`output_height` for `grid` / `iovl`, or the
// single input's output image for `iden`).
//
// The helpers below resolve this geometry **without decoding any AV1
// bitstream** — they walk only the box-level item-property graph. They are
// the dimension half of derived-image evaluation: a caller that later wires
// in a real AV1 decoder uses them to size the output canvas, place overlay
// inputs, and crop/rotate identity derivations, and to validate that the
// declared geometry is self-consistent before any pixels exist.

/// A transformative item property that changes (or preserves) the pixel
/// dimensions of the image it is applied to, in the order it appears in the
/// item's `ipma` association. Descriptive properties (`ispe`, `colr`,
/// `pixi`, …) do not appear here — only the four transformative properties
/// HEIF defines that affect output geometry.
///
/// Spec: ISO/IEC 23008-12 §6.5.10 (`irot`), §6.5.12 (`imir`), §6.5.8 /
/// §6.5.9 (`clap`), §6.5.13 (`iscl`).
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DimTransform {
    /// Counter-clockwise rotation, `angle` × 90°. 90°/270° swap width and
    /// height; 0°/180° preserve them.
    Rotate { angle: u8 },
    /// Mirror about an axis. Does not change dimensions.
    Mirror { axis: u8 },
    /// Clean-aperture crop. The output dimensions are the clean-aperture
    /// width/height rounded to nearest integer (`§6.5.9` rationals), or the
    /// input unchanged when the crop falls outside the input rectangle.
    Crop {
        width_n: i32,
        width_d: i32,
        height_n: i32,
        height_d: i32,
    },
    /// Rational scale per §6.5.13: `ceil(input * num / den)` independently
    /// on each axis.
    Scale {
        target_width_numerator: u16,
        target_width_denominator: u16,
        target_height_numerator: u16,
        target_height_denominator: u16,
    },
}

impl DimTransform {
    /// Apply this transform's effect on dimensions to `(w, h)`. Returns the
    /// post-transform `(width, height)`. Defensive: a degenerate crop or a
    /// zero-denominator scale leaves the dimensions unchanged (mirroring the
    /// no-op fall-throughs in [`crate::transform`]).
    pub fn apply_dims(&self, w: u32, h: u32) -> (u32, u32) {
        match *self {
            DimTransform::Rotate { angle } => {
                if angle % 2 == 1 {
                    (h, w)
                } else {
                    (w, h)
                }
            }
            DimTransform::Mirror { .. } => (w, h),
            DimTransform::Crop {
                width_n,
                width_d,
                height_n,
                height_d,
            } => {
                if width_d == 0 || height_d == 0 {
                    return (w, h);
                }
                // §6.5.9: clean-aperture width/height are signed rationals;
                // round to nearest integer (same rounding as
                // `transform::apply_clap`).
                let cw = (width_n as i64 + width_d as i64 / 2) / width_d as i64;
                let ch = (height_n as i64 + height_d as i64 / 2) / height_d as i64;
                if cw <= 0 || ch <= 0 || cw > w as i64 || ch > h as i64 {
                    return (w, h);
                }
                (cw as u32, ch as u32)
            }
            DimTransform::Scale {
                target_width_numerator,
                target_width_denominator,
                target_height_numerator,
                target_height_denominator,
            } => {
                let iscl = crate::meta::Iscl {
                    target_width_numerator,
                    target_width_denominator,
                    target_height_numerator,
                    target_height_denominator,
                };
                iscl.scaled_dims(w, h).unwrap_or((w, h))
            }
        }
    }
}

/// The ordered list of dimension-affecting transformative item properties
/// associated with `item_id`, in `ipma` association order. Non-transformative
/// properties are skipped. An item with no transformative properties yields
/// an empty vector (its output image equals its reconstructed image — §6.3).
///
/// Per §6.5.11, a `lsel` (layer selector) — when present — precedes every
/// transformative property in the association order; it carries no geometry
/// effect and so does not appear in the returned list, but the relative
/// order of the transformative properties that follow it is preserved.
pub fn transform_chain(meta: &crate::meta::Meta, item_id: u32) -> Vec<DimTransform> {
    use crate::meta::Property;
    let Some(assoc) = meta.assoc_by_id(item_id) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for pa in &assoc.entries {
        let Some(prop) = meta.properties.get(pa.index as usize) else {
            continue;
        };
        match prop {
            Property::Irot(r) => out.push(DimTransform::Rotate { angle: r.angle }),
            Property::Imir(m) => out.push(DimTransform::Mirror { axis: m.axis }),
            Property::Clap(c) => out.push(DimTransform::Crop {
                width_n: c.clean_aperture_width_n,
                width_d: c.clean_aperture_width_d,
                height_n: c.clean_aperture_height_n,
                height_d: c.clean_aperture_height_d,
            }),
            Property::Iscl(s) => out.push(DimTransform::Scale {
                target_width_numerator: s.target_width_numerator,
                target_width_denominator: s.target_width_denominator,
                target_height_numerator: s.target_height_numerator,
                target_height_denominator: s.target_height_denominator,
            }),
            _ => {}
        }
    }
    out
}

/// Apply an item's transform chain to a reconstructed `(width, height)`,
/// returning the **output-image** dimensions per HEIF §6.3. Equivalent to
/// folding [`DimTransform::apply_dims`] over [`transform_chain`].
pub fn output_dims_from_reconstructed(
    meta: &crate::meta::Meta,
    item_id: u32,
    reconstructed_w: u32,
    reconstructed_h: u32,
) -> (u32, u32) {
    let mut dims = (reconstructed_w, reconstructed_h);
    for t in transform_chain(meta, item_id) {
        dims = t.apply_dims(dims.0, dims.1);
    }
    dims
}

/// Resolve the **reconstructed-image** dimensions of an item from the
/// box-level graph alone (no AV1 decode):
///
/// * a `grid` item → its descriptor `output_width`/`output_height`;
/// * an `iovl` item → its descriptor `output_width`/`output_height`;
/// * an `iden` item → the output dimensions of its single `dimg` input
///   (recursively resolved);
/// * any other item (coded `av01`, etc.) → its `ispe` dimensions.
///
/// Returns `None` when the dimensions cannot be determined: a coded item
/// without an `ispe`, a `grid`/`iovl` whose descriptor payload can't be
/// resolved or parsed, an `iden` without exactly one input, or a derivation
/// chain that exceeds [`MAX_DERIVATION_DEPTH`] (cycle guard). `idat`/`mdat`
/// resolution of the `grid`/`iovl` descriptor bytes uses `file_bytes` and
/// the optional `idat` slice via the standard `iloc` resolver.
pub fn reconstructed_dims(
    meta: &crate::meta::Meta,
    item_id: u32,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> Option<(u32, u32)> {
    reconstructed_dims_inner(meta, item_id, file_bytes, idat, 0)
}

/// Resolve a derived-item descriptor's payload bytes (`grid` / `iovl` body)
/// from its `iloc` entry, handling all three `construction_method`s:
/// `0` (file-offset, the bytes live in `mdat`/elsewhere in `file_bytes`),
/// `1` (idat-offset, the bytes live in the `meta` box's `idat` and are
/// passed in via `idat`), and `2` (item-offset, the bytes are a range of
/// another item's data named via the `'iloc'` item reference — resolved
/// through [`crate::parser::item_bytes_owned_full`], which follows the iref
/// and recurses through cm=0/cm=1 origin items). Returns `None` when the
/// item has no `iloc`, when an idat extent is referenced without an `idat`
/// slice, when a cm=2 chain is malformed/cyclic, or when any extent runs
/// past the backing buffer.
///
/// Spec: ISO/IEC 14496-12 §8.11.3 (`iloc` construction methods); HEIF
/// §6.6.2 derived-item payloads conventionally use `idat` (cm=1).
fn resolve_descriptor_bytes(
    meta: &crate::meta::Meta,
    item_id: u32,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> Option<Vec<u8>> {
    let loc = meta.location_by_id(item_id)?;
    let backing: &[u8] = match loc.construction_method {
        0 => file_bytes,
        1 => idat?,
        // construction_method 2 (item-offset): the descriptor bytes are a
        // range of another item's data, named via the `'iloc'` item
        // reference (ISO/IEC 14496-12 §8.11.3.3). Delegate to the cm=2-aware
        // resolver, which consults the whole `Meta` to follow the iref and
        // recurse through cm=0/cm=1 origin items. A grid / iovl descriptor
        // stored this way (uncommon but spec-legal) now resolves.
        2 => return crate::parser::item_bytes_owned_full(file_bytes, meta, item_id).ok(),
        _ => return None,
    };
    if loc.extents.is_empty() {
        return None;
    }
    let mut out = Vec::new();
    for e in &loc.extents {
        let start = loc.base_offset.checked_add(e.offset)?;
        let end = start.checked_add(e.length)?;
        let (start, end) = (usize::try_from(start).ok()?, usize::try_from(end).ok()?);
        if end > backing.len() || start > end {
            return None;
        }
        out.extend_from_slice(&backing[start..end]);
    }
    Some(out)
}

/// Maximum derivation-chain recursion depth before [`reconstructed_dims`]
/// gives up. A well-formed file nests at most a handful of derivations; a
/// deeper chain is almost certainly a `dimg` cycle, which this bound breaks
/// without unbounded recursion.
pub const MAX_DERIVATION_DEPTH: u32 = 16;

fn reconstructed_dims_inner(
    meta: &crate::meta::Meta,
    item_id: u32,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
    depth: u32,
) -> Option<(u32, u32)> {
    if depth > MAX_DERIVATION_DEPTH {
        return None;
    }
    let item = meta.item_by_id(item_id)?;
    let grid = b(b"grid");
    let dimg = b(b"dimg");
    if item.item_type == grid {
        let bytes = resolve_descriptor_bytes(meta, item_id, file_bytes, idat)?;
        let g = crate::grid::ImageGrid::parse(&bytes).ok()?;
        return Some((g.output_width, g.output_height));
    }
    if item.item_type == crate::meta::ITEM_TYPE_IOVL {
        let bytes = resolve_descriptor_bytes(meta, item_id, file_bytes, idat)?;
        let refs = meta.iref_targets(&dimg, item_id).len();
        let o = ImageOverlay::parse(&bytes, refs).ok()?;
        return Some((o.output_width, o.output_height));
    }
    if item.item_type == crate::meta::ITEM_TYPE_IDEN {
        let inputs = meta.iref_targets(&dimg, item_id);
        if inputs.len() != 1 {
            return None;
        }
        // §6.6.2.1 + §6.3: the iden's reconstructed image is the *output
        // image* of its single input.
        let (iw, ih) = reconstructed_dims_inner(meta, inputs[0], file_bytes, idat, depth + 1)?;
        return Some(output_dims_from_reconstructed(meta, inputs[0], iw, ih));
    }
    if item.item_type == crate::meta::ITEM_TYPE_TMAP {
        // av1-avif §4.2.2 (tone-map derived image item): the rendered image
        // has the spatial extents of the *base* image input. The base image
        // is input `0` of the tmap's `dimg` iref; the remaining inputs are
        // gain map(s) which may be coded at a lower resolution and are
        // up-sampled to the base extents during tone mapping. The tmap's
        // reconstructed image therefore takes the base input's output
        // dimensions.
        let inputs = meta.iref_targets(&dimg, item_id);
        let base = *inputs.first()?;
        let (iw, ih) = reconstructed_dims_inner(meta, base, file_bytes, idat, depth + 1)?;
        return Some(output_dims_from_reconstructed(meta, base, iw, ih));
    }
    if item.item_type == crate::meta::ITEM_TYPE_SATO {
        // av1-avif §4.2.3.1: the Sample Transform Derived Image Item and all
        // of its inputs "shall be associated with … an 'ispe' property" and
        // "have the same dimensions as defined by the 'ispe' property". So a
        // well-formed sato carries its own `ispe` (handled by the coded-item
        // fall-through below). When it does not, fall back to its first
        // input's reconstructed dimensions — every input shares the sato's
        // extents, so input 0 is representative.
        if let Some(crate::meta::Property::Ispe(ispe)) = meta.property_for(item_id, &b(b"ispe")) {
            return Some((ispe.width, ispe.height));
        }
        let inputs = meta.iref_targets(&dimg, item_id);
        let base = *inputs.first()?;
        let (iw, ih) = reconstructed_dims_inner(meta, base, file_bytes, idat, depth + 1)?;
        return Some(output_dims_from_reconstructed(meta, base, iw, ih));
    }
    // Coded item: reconstructed dimensions are the `ispe` extents.
    match meta.property_for(item_id, &b(b"ispe")) {
        Some(crate::meta::Property::Ispe(ispe)) => Some((ispe.width, ispe.height)),
        _ => None,
    }
}

/// Where one input image of an `iovl` overlay lands on the canvas, and what
/// portion of it is visible after clipping. All coordinates are canvas-space
/// pixels with the origin at the top-left corner (§6.6.2.2.3).
///
/// The input image occupies `[offset_x, offset_x + input_width)` ×
/// `[offset_y, offset_y + input_height)`. Per §6.6.2.2.3 a pixel is included
/// in the reconstructed image only when its canvas coordinate is in
/// `[0, output_width)` × `[0, output_height)`; the [`visible`](Self::visible)
/// rectangle is that intersection, expressed back in canvas coordinates.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OverlayPlacement {
    /// The source image item id (from the parallel `dimg` iref `to_ids`).
    pub source_item_id: u32,
    /// Declared horizontal offset of the input's left column on the canvas.
    pub offset_x: i64,
    /// Declared vertical offset of the input's top row on the canvas.
    pub offset_y: i64,
    /// Input image output-image width (post its own transforms).
    pub input_width: u32,
    /// Input image output-image height.
    pub input_height: u32,
}

impl OverlayPlacement {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        source_item_id: u32,
        offset_x: i64,
        offset_y: i64,
        input_width: u32,
        input_height: u32,
    ) -> Self {
        Self {
            source_item_id,
            offset_x,
            offset_y,
            input_width,
            input_height,
        }
    }
}

impl OverlayPlacement {
    /// The visible canvas rectangle as `(x, y, width, height)` after
    /// clipping the input against `[0, canvas_w) × [0, canvas_h)`. Returns
    /// `None` when the input lands entirely off-canvas (no visible pixels).
    pub fn visible(&self, canvas_w: u32, canvas_h: u32) -> Option<(u32, u32, u32, u32)> {
        let left = self.offset_x.max(0);
        let top = self.offset_y.max(0);
        let right = (self.offset_x + i64::from(self.input_width)).min(i64::from(canvas_w));
        let bottom = (self.offset_y + i64::from(self.input_height)).min(i64::from(canvas_h));
        if right <= left || bottom <= top {
            return None;
        }
        Some((
            left as u32,
            top as u32,
            (right - left) as u32,
            (bottom - top) as u32,
        ))
    }

    /// True when the input image is wholly inside the canvas (no clipping
    /// occurs).
    pub fn fully_visible(&self, canvas_w: u32, canvas_h: u32) -> bool {
        self.offset_x >= 0
            && self.offset_y >= 0
            && self.offset_x + i64::from(self.input_width) <= i64::from(canvas_w)
            && self.offset_y + i64::from(self.input_height) <= i64::from(canvas_h)
    }

    /// True when no pixel of the input lands on the canvas.
    pub fn off_canvas(&self, canvas_w: u32, canvas_h: u32) -> bool {
        self.visible(canvas_w, canvas_h).is_none()
    }
}

/// A fully resolved `iovl` overlay derivation: the parsed descriptor plus
/// each input's resolved placement against the canvas (§6.6.2.2).
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OverlayResolution {
    /// The `iovl` derived item id.
    pub iovl_item_id: u32,
    /// The parsed descriptor (canvas fill, output dimensions, offsets).
    pub descriptor: ImageOverlay,
    /// One placement per input, bottom-most first (layering order matches
    /// the `dimg` iref `to_ids` order, §6.6.2.2.1).
    pub placements: Vec<OverlayPlacement>,
}

impl OverlayResolution {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        iovl_item_id: u32,
        descriptor: ImageOverlay,
        placements: Vec<OverlayPlacement>,
    ) -> Self {
        Self {
            iovl_item_id,
            descriptor,
            placements,
        }
    }
}

impl OverlayResolution {
    /// Canvas dimensions `(output_width, output_height)`.
    pub fn canvas(&self) -> (u32, u32) {
        (self.descriptor.output_width, self.descriptor.output_height)
    }

    /// True when at least one canvas pixel is left to the fill colour — i.e.
    /// the union of every input's visible rectangle does not cover the whole
    /// canvas. Computed conservatively from a coverage scan bounded by the
    /// canvas area; for very large canvases (> 4M pixels) it returns `true`
    /// without scanning, since a partial fill is the common case and the
    /// exact answer isn't worth a multi-megabyte allocation.
    pub fn canvas_partially_filled(&self) -> bool {
        let (cw, ch) = self.canvas();
        let area = u64::from(cw) * u64::from(ch);
        if area == 0 {
            return false;
        }
        if area > 4_000_000 {
            return true;
        }
        let mut covered = vec![false; area as usize];
        for p in &self.placements {
            if let Some((x, y, w, h)) = p.visible(cw, ch) {
                for row in y..y + h {
                    let base = (u64::from(row) * u64::from(cw)) as usize;
                    for col in x..x + w {
                        covered[base + col as usize] = true;
                    }
                }
            }
        }
        covered.iter().any(|&c| !c)
    }
}

/// Resolve every `iovl` overlay item in `meta` end-to-end: parse the
/// descriptor, pair each placement with its `dimg` source item, and resolve
/// each source's output dimensions from the box graph. Returns one
/// [`OverlayResolution`] per `iovl` item, in `iinf` declaration order;
/// `iovl` items whose descriptor can't be resolved/parsed are skipped.
///
/// Spec: ISO/IEC 23008-12 §6.6.2.2. `file_bytes` + the optional `idat`
/// slice resolve the descriptor payload via the standard `iloc` resolver;
/// each input's dimensions come from [`reconstructed_dims`] +
/// [`output_dims_from_reconstructed`] so inputs that are themselves grids,
/// overlays, or transformed coded items resolve correctly.
pub fn resolve_overlays(
    meta: &crate::meta::Meta,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> Vec<OverlayResolution> {
    let dimg = b(b"dimg");
    let mut out = Vec::new();
    for iovl_id in meta.item_ids_of_type(&crate::meta::ITEM_TYPE_IOVL) {
        let Some(bytes) = resolve_descriptor_bytes(meta, iovl_id, file_bytes, idat) else {
            continue;
        };
        let sources = meta.iref_targets(&dimg, iovl_id);
        let Ok(descriptor) = ImageOverlay::parse(&bytes, sources.len()) else {
            continue;
        };
        let mut placements = Vec::with_capacity(descriptor.entries.len());
        for (entry, &src) in descriptor.entries.iter().zip(sources.iter()) {
            let (iw, ih) = reconstructed_dims(meta, src, file_bytes, idat)
                .map(|(w, h)| output_dims_from_reconstructed(meta, src, w, h))
                .unwrap_or((0, 0));
            placements.push(OverlayPlacement {
                source_item_id: src,
                offset_x: i64::from(entry.horizontal_offset),
                offset_y: i64::from(entry.vertical_offset),
                input_width: iw,
                input_height: ih,
            });
        }
        out.push(OverlayResolution {
            iovl_item_id: iovl_id,
            descriptor,
            placements,
        });
    }
    out
}

/// A fully resolved `iden` identity derivation: the single source item, its
/// reconstructed dimensions, the transform chain applied by the iden item
/// itself, and the resulting output dimensions (§6.6.2.1 + §6.3).
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdenResolution {
    /// The `iden` derived item id.
    pub iden_item_id: u32,
    /// The single `dimg` source item id (the image the identity derivation
    /// re-presents), or `None` when the iden does not have exactly one input.
    pub source_item_id: Option<u32>,
    /// The source's reconstructed dimensions, or `None` when unresolvable.
    pub source_dims: Option<(u32, u32)>,
    /// The dimension-affecting transformative properties on the **iden item
    /// itself**, in `ipma` order. These are the whole point of an identity
    /// derivation (§6.6.2.1 NOTE 2: e.g. a `clap` crop of the original).
    pub transforms: Vec<DimTransform>,
    /// The iden item's output dimensions after applying `transforms` to
    /// `source_dims`, or `None` when `source_dims` is `None`.
    pub output_dims: Option<(u32, u32)>,
}

impl IdenResolution {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        iden_item_id: u32,
        source_item_id: Option<u32>,
        source_dims: Option<(u32, u32)>,
        transforms: Vec<DimTransform>,
        output_dims: Option<(u32, u32)>,
    ) -> Self {
        Self {
            iden_item_id,
            source_item_id,
            source_dims,
            transforms,
            output_dims,
        }
    }
}

/// Resolve every `iden` identity-derivation item in `meta` end-to-end:
/// find the single `dimg` source, resolve its reconstructed dimensions from
/// the box graph, collect the transformative properties on the iden item,
/// and compute the resulting output dimensions. Returns one
/// [`IdenResolution`] per `iden` item, in `iinf` declaration order.
///
/// Spec: ISO/IEC 23008-12 §6.6.2.1. The reconstructed image of an `iden`
/// item is the *output image* of its single input (§6.3); the iden's own
/// output image then applies the iden item's transformative properties.
/// Because the source's output dimensions already fold in *its* transforms,
/// `source_dims` here is the source's output image, and `output_dims` folds
/// the iden's transforms on top.
pub fn resolve_iden_derivations(
    meta: &crate::meta::Meta,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> Vec<IdenResolution> {
    let dimg = b(b"dimg");
    let mut out = Vec::new();
    for iden_id in meta.item_ids_of_type(&crate::meta::ITEM_TYPE_IDEN) {
        let inputs = meta.iref_targets(&dimg, iden_id);
        let source_item_id = if inputs.len() == 1 {
            Some(inputs[0])
        } else {
            None
        };
        let source_dims = source_item_id.and_then(|src| {
            reconstructed_dims(meta, src, file_bytes, idat)
                .map(|(w, h)| output_dims_from_reconstructed(meta, src, w, h))
        });
        let transforms = transform_chain(meta, iden_id);
        let output_dims = source_dims.map(|(w, h)| {
            let mut d = (w, h);
            for t in &transforms {
                d = t.apply_dims(d.0, d.1);
            }
            d
        });
        out.push(IdenResolution {
            iden_item_id: iden_id,
            source_item_id,
            source_dims,
            transforms,
            output_dims,
        });
    }
    out
}

/// A fully resolved `tmap` tone-map derivation: the base image input, the
/// gain-map input(s), and the rendered (reconstructed) dimensions.
///
/// av1-avif §4.2.2 — a tone-map derived image item layers an additional
/// "gain map" image onto a base image so that a single file serves both an
/// SDR (the base) and an HDR (`base · 2^(W·gain)`) rendition. The rendered
/// image has the spatial extents of the **base** image; gain maps may be
/// coded at a lower resolution and are up-sampled. The structured byte-level
/// reconstruction lives in [`GainMapMetadata`] + its §6 application surface;
/// this record describes the derivation *geometry* — which item is the base,
/// which are gain maps, and the resulting output dimensions — without an AV1
/// decode, mirroring [`OverlayResolution`] / [`IdenResolution`].
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToneMapResolution {
    /// The `tmap` derived item id.
    pub tmap_item_id: u32,
    /// The base image item id (`dimg` input `0`), or `None` when the tmap
    /// has no `dimg` inputs at all.
    pub base_item_id: Option<u32>,
    /// Every gain-map image item id (`dimg` inputs `1..`). Empty when the
    /// tmap declares only a base input.
    pub gain_map_item_ids: Vec<u32>,
    /// The base image's reconstructed dimensions (its `ispe`, folding in any
    /// of its own derivations), or `None` when unresolvable. These are the
    /// rendered dimensions of the tone-mapped output.
    pub rendered_dims: Option<(u32, u32)>,
    /// Each gain map's reconstructed dimensions, paired with the gain-map
    /// item id, in `dimg` order: `(gain_map_item_id, dims)`. A gain map
    /// coded smaller than [`Self::rendered_dims`] is up-sampled during tone
    /// mapping; surfacing the coded extents lets callers report the
    /// up-sampling ratio. `dims` is `None` when the gain map's dimensions
    /// are unresolvable (missing `ispe`, malformed derivation, …).
    pub gain_map_dims: Vec<(u32, Option<(u32, u32)>)>,
}

impl ToneMapResolution {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        tmap_item_id: u32,
        base_item_id: Option<u32>,
        gain_map_item_ids: Vec<u32>,
        rendered_dims: Option<(u32, u32)>,
        gain_map_dims: Vec<(u32, Option<(u32, u32)>)>,
    ) -> Self {
        Self {
            tmap_item_id,
            base_item_id,
            gain_map_item_ids,
            rendered_dims,
            gain_map_dims,
        }
    }
}

impl ToneMapResolution {
    /// True when at least one gain map is coded at a strictly smaller
    /// resolution than the rendered (base) dimensions — i.e. the tone-map
    /// reconstruction must up-sample that gain map. `false` when the base
    /// dims are unknown, when there are no gain maps, or when every gain
    /// map already matches the rendered extents.
    pub fn upsamples_gain_map(&self) -> bool {
        let Some((bw, bh)) = self.rendered_dims else {
            return false;
        };
        self.gain_map_dims.iter().any(|&(_, dims)| match dims {
            Some((gw, gh)) => gw < bw || gh < bh,
            None => false,
        })
    }
}

/// Resolve every `tmap` tone-map derivation item in `meta` end-to-end: read
/// its `dimg` inputs (base = input 0, gain maps = the rest) and resolve each
/// input's reconstructed dimensions from the box graph. Returns one
/// [`ToneMapResolution`] per `tmap` item, in `iinf` declaration order.
///
/// Spec: av1-avif §4.2.2. The rendered output takes the base image's
/// extents; gain maps may be coded smaller. No AV1 decode is performed — the
/// gain-map byte reconstruction is a separate concern handled by
/// [`GainMapMetadata`]. This resolver only describes the derivation geometry,
/// mirroring [`resolve_overlays`] / [`resolve_iden_derivations`].
pub fn resolve_tone_maps(
    meta: &crate::meta::Meta,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> Vec<ToneMapResolution> {
    let dimg = b(b"dimg");
    let mut out = Vec::new();
    for tmap_id in meta.item_ids_of_type(&crate::meta::ITEM_TYPE_TMAP) {
        let inputs = meta.iref_targets(&dimg, tmap_id);
        let base_item_id = inputs.first().copied();
        let gain_map_item_ids: Vec<u32> = inputs.iter().skip(1).copied().collect();
        // Base image output dimensions are the rendered tone-map extents.
        let rendered_dims = base_item_id.and_then(|base| {
            reconstructed_dims(meta, base, file_bytes, idat)
                .map(|(w, h)| output_dims_from_reconstructed(meta, base, w, h))
        });
        let gain_map_dims = gain_map_item_ids
            .iter()
            .map(|&gid| {
                let dims = reconstructed_dims(meta, gid, file_bytes, idat)
                    .map(|(w, h)| output_dims_from_reconstructed(meta, gid, w, h));
                (gid, dims)
            })
            .collect::<Vec<_>>();
        out.push(ToneMapResolution {
            tmap_item_id: tmap_id,
            base_item_id,
            gain_map_item_ids,
            rendered_dims,
            gain_map_dims,
        });
    }
    out
}

/// Where one tile of a `'grid'` derived image lands on the reconstructed
/// canvas, and what portion of it survives the right/bottom trim
/// (ISO/IEC 23008-12 §6.6.2.3.1). Tiles are placed row-major, top row first,
/// left to right, at `(col · tile_width, row · tile_height)` without gap or
/// overlap; pixels at or beyond `output_width` / `output_height` are
/// trimmed.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GridTilePlacement {
    /// The tile's source image item id (the `dimg` `to_id` at this index).
    pub source_item_id: u32,
    /// Zero-based grid row (`tile_index / columns`).
    pub row: u16,
    /// Zero-based grid column (`tile_index % columns`).
    pub col: u16,
    /// Canvas x of the tile's left column (`col · tile_width`).
    pub origin_x: u32,
    /// Canvas y of the tile's top row (`row · tile_height`).
    pub origin_y: u32,
}

impl GridTilePlacement {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(source_item_id: u32, row: u16, col: u16, origin_x: u32, origin_y: u32) -> Self {
        Self {
            source_item_id,
            row,
            col,
            origin_x,
            origin_y,
        }
    }
}

impl GridTilePlacement {
    /// The visible canvas rectangle `(x, y, width, height)` after trimming
    /// the tile against `[0, output_width) × [0, output_height)`
    /// (§6.6.2.3.1 right/bottom trim). Returns `None` when the tile lands
    /// entirely outside the canvas — which a spec-conformant grid never
    /// does (the tiles must cover the canvas), but a malformed descriptor
    /// might. `tile_w` / `tile_h` are the common tile dimensions.
    pub fn visible(
        &self,
        tile_w: u32,
        tile_h: u32,
        output_width: u32,
        output_height: u32,
    ) -> Option<(u32, u32, u32, u32)> {
        let right = (u64::from(self.origin_x) + u64::from(tile_w)).min(u64::from(output_width));
        let bottom = (u64::from(self.origin_y) + u64::from(tile_h)).min(u64::from(output_height));
        if right <= u64::from(self.origin_x) || bottom <= u64::from(self.origin_y) {
            return None;
        }
        Some((
            self.origin_x,
            self.origin_y,
            (right - u64::from(self.origin_x)) as u32,
            (bottom - u64::from(self.origin_y)) as u32,
        ))
    }

    /// True when the tile is trimmed on the right or bottom edge — i.e. it
    /// extends past `output_width` / `output_height`. The right column and
    /// bottom row of a grid whose `output` dims aren't a whole multiple of
    /// the tile size are trimmed this way.
    pub fn is_trimmed(
        &self,
        tile_w: u32,
        tile_h: u32,
        output_width: u32,
        output_height: u32,
    ) -> bool {
        u64::from(self.origin_x) + u64::from(tile_w) > u64::from(output_width)
            || u64::from(self.origin_y) + u64::from(tile_h) > u64::from(output_height)
    }
}

/// A fully resolved `'grid'` derivation: the parsed descriptor, the common
/// tile dimensions, and each tile's canvas placement (§6.6.2.3).
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GridResolution {
    /// The `'grid'` derived item id.
    pub grid_item_id: u32,
    /// The parsed descriptor (row/column counts + output dimensions).
    pub descriptor: crate::grid::ImageGrid,
    /// The common tile dimensions `(tile_width, tile_height)` — every input
    /// tile shares these (§6.6.2.3.1, "All input images shall have exactly
    /// the same width and height"). Taken from the first tile's
    /// reconstructed dimensions; `None` when that tile is unresolvable.
    pub tile_dims: Option<(u32, u32)>,
    /// One placement per tile, row-major (top row first, left to right),
    /// in `dimg` `to_ids` order (§6.6.2.3.1).
    pub placements: Vec<GridTilePlacement>,
}

impl GridResolution {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        grid_item_id: u32,
        descriptor: crate::grid::ImageGrid,
        tile_dims: Option<(u32, u32)>,
        placements: Vec<GridTilePlacement>,
    ) -> Self {
        Self {
            grid_item_id,
            descriptor,
            tile_dims,
            placements,
        }
    }
}

impl GridResolution {
    /// Canvas dimensions `(output_width, output_height)`.
    pub fn canvas(&self) -> (u32, u32) {
        (self.descriptor.output_width, self.descriptor.output_height)
    }

    /// True when the tiles "cover" the canvas as §6.6.2.3.1 requires:
    /// `tile_width · columns ≥ output_width` and
    /// `tile_height · rows ≥ output_height`. `false` when [`Self::tile_dims`]
    /// is unknown (cannot verify coverage).
    pub fn covers_canvas(&self) -> bool {
        let Some((tw, th)) = self.tile_dims else {
            return false;
        };
        u64::from(tw) * u64::from(self.descriptor.columns)
            >= u64::from(self.descriptor.output_width)
            && u64::from(th) * u64::from(self.descriptor.rows)
                >= u64::from(self.descriptor.output_height)
    }

    /// The number of tiles trimmed on the right or bottom edge (§6.6.2.3.1).
    /// Zero when the output dimensions are a whole multiple of the tile size.
    /// Always zero when [`Self::tile_dims`] is unknown.
    pub fn trimmed_tile_count(&self) -> usize {
        let Some((tw, th)) = self.tile_dims else {
            return 0;
        };
        let (ow, oh) = self.canvas();
        self.placements
            .iter()
            .filter(|p| p.is_trimmed(tw, th, ow, oh))
            .count()
    }
}

/// Resolve every `'grid'` derived item in `meta` end-to-end: parse the
/// descriptor, pair each `dimg` input with its row-major canvas placement,
/// and resolve the common tile dimensions from the first tile's box-graph
/// reconstructed dimensions. Returns one [`GridResolution`] per `'grid'`
/// item, in `iinf` declaration order; grids whose descriptor can't be
/// resolved/parsed are skipped.
///
/// Spec: ISO/IEC 23008-12 §6.6.2.3. Tiles are placed at
/// `(col · tile_width, row · tile_height)` and the canvas is trimmed on the
/// right/bottom to `output_width × output_height`. No AV1 decode — the
/// geometry comes from the box graph alone, mirroring [`resolve_overlays`].
pub fn resolve_grids(
    meta: &crate::meta::Meta,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> Vec<GridResolution> {
    let grid_type = crate::parser::ITEM_TYPE_GRID;
    let dimg = b(b"dimg");
    let mut out = Vec::new();
    for grid_id in meta.item_ids_of_type(&grid_type) {
        let Some(bytes) = resolve_descriptor_bytes(meta, grid_id, file_bytes, idat) else {
            continue;
        };
        let Ok(descriptor) = crate::grid::ImageGrid::parse(&bytes) else {
            continue;
        };
        let tiles = meta.iref_targets(&dimg, grid_id);
        // Common tile dimensions = first tile's reconstructed output image.
        let tile_dims = tiles.first().and_then(|&first| {
            reconstructed_dims(meta, first, file_bytes, idat)
                .map(|(w, h)| output_dims_from_reconstructed(meta, first, w, h))
        });
        let cols = descriptor.columns;
        let (tw, th) = tile_dims.unwrap_or((0, 0));
        let mut placements = Vec::with_capacity(tiles.len());
        for (idx, &tile_id) in tiles.iter().enumerate() {
            let row = (idx as u32 / cols.max(1) as u32) as u16;
            let col = (idx as u32 % cols.max(1) as u32) as u16;
            placements.push(GridTilePlacement {
                source_item_id: tile_id,
                row,
                col,
                origin_x: u32::from(col) * tw,
                origin_y: u32::from(row) * th,
            });
        }
        out.push(GridResolution {
            grid_item_id: grid_id,
            descriptor,
            tile_dims,
            placements,
        });
    }
    out
}

/// The kind of a node in a [`DerivationGraph`] — i.e. how its reconstructed
/// image is obtained (HEIF §6.6.1). A coded leaf is decoded directly from an
/// AV1 bitstream; every other variant is a derived image item whose
/// reconstructed image is computed from its `'dimg'` inputs.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DerivationKind {
    /// A coded image item (`'av01'`): the leaf a renderer actually decodes.
    /// Its reconstructed image is the decoded AV1 frame, with extents from
    /// the item's `'ispe'` property.
    Coded,
    /// A `'grid'` tile-mosaic derivation (§6.6.2.3).
    Grid,
    /// An `'iovl'` overlay derivation (§6.6.2.2).
    Overlay,
    /// An `'iden'` identity derivation (§6.6.2.1) — its reconstructed image
    /// is its single input's output image; the geometry comes entirely from
    /// the input plus this item's own transformative properties.
    Identity,
    /// A `'tmap'` tone-map / gain-map derivation (av1-avif §4.2.2). Its
    /// rendered extents are the base (input 0) image's.
    ToneMap,
    /// A `'sato'` Sample-Transform derivation (av1-avif §4.2.3).
    SampleTransform,
    /// A derived item whose `item_type` this crate does not model
    /// structurally; its inputs are still walked so a renderer sees the
    /// dependency edges, but its geometry is taken from its first input.
    Unknown,
}

impl DerivationKind {
    /// Classify an item by its `item_type`.
    fn classify(item_type: &BoxType, is_derived: bool) -> Self {
        if item_type == &crate::parser::ITEM_TYPE_AV01 {
            DerivationKind::Coded
        } else if item_type == &crate::parser::ITEM_TYPE_GRID {
            DerivationKind::Grid
        } else if item_type == &crate::meta::ITEM_TYPE_IOVL {
            DerivationKind::Overlay
        } else if item_type == &crate::meta::ITEM_TYPE_IDEN {
            DerivationKind::Identity
        } else if item_type == &crate::meta::ITEM_TYPE_TMAP {
            DerivationKind::ToneMap
        } else if item_type == &crate::meta::ITEM_TYPE_SATO {
            DerivationKind::SampleTransform
        } else if is_derived {
            DerivationKind::Unknown
        } else {
            // A non-`av01` item with no `'dimg'` inputs: treat as a coded
            // leaf (it is the bottom of the chain and a renderer hands its
            // bytes to whatever decoder matches the item type).
            DerivationKind::Coded
        }
    }

    /// True for the coded-leaf kind — the only nodes a renderer decodes
    /// directly.
    pub fn is_coded(self) -> bool {
        matches!(self, DerivationKind::Coded)
    }
}

/// One node in a [`DerivationGraph`]: an image item reachable from the root
/// primary by walking `'dimg'` edges, together with its resolved geometry.
///
/// Geometry is the box-graph-only resolution (no AV1 decode):
/// `reconstructed_dims` is the node's reconstructed image size (§6.3) and
/// `output_dims` folds the node's own transformative item properties on top
/// (§6.6.1). For a coded leaf the two differ only when the leaf carries a
/// `'clap'`/`'irot'`/`'imir'`/`'iscl'` of its own.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DerivationNode {
    /// The image item id.
    pub item_id: u32,
    /// How this node's reconstructed image is obtained.
    pub kind: DerivationKind,
    /// The `'dimg'` input item ids, in reference order (empty for a coded
    /// leaf). For `'grid'` this is the row-major tile list; for `'iovl'` the
    /// bottom-to-top layer list; for `'iden'`/`'tmap'` the single/base input
    /// first.
    pub inputs: Vec<u32>,
    /// The reconstructed-image dimensions, or `None` when unresolvable from
    /// the box graph (e.g. a coded leaf with no `'ispe'`, or a derivation
    /// whose descriptor cannot be parsed).
    pub reconstructed_dims: Option<(u32, u32)>,
    /// The output-image dimensions: [`Self::reconstructed_dims`] with this
    /// node's own transform chain folded in (§6.3 / §6.6.1).
    pub output_dims: Option<(u32, u32)>,
    /// Recursion depth from the root primary (the root is depth 0).
    pub depth: u32,
}

impl DerivationNode {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        item_id: u32,
        kind: DerivationKind,
        inputs: Vec<u32>,
        reconstructed_dims: Option<(u32, u32)>,
        output_dims: Option<(u32, u32)>,
        depth: u32,
    ) -> Self {
        Self {
            item_id,
            kind,
            inputs,
            reconstructed_dims,
            output_dims,
            depth,
        }
    }
}

impl DerivationNode {
    /// The node's own dimension-affecting transform chain (`'clap'` →
    /// `'irot'` → `'imir'` → `'iscl'`, in `ipma` order). Convenience wrapper
    /// over [`transform_chain`].
    pub fn transform_chain(&self, meta: &crate::meta::Meta) -> Vec<DimTransform> {
        transform_chain(meta, self.item_id)
    }
}

/// A fully-walked derivation graph rooted at one image item (typically the
/// primary), enumerating every image item reachable through `'dimg'` edges
/// and the distinct coded leaves a renderer must decode (HEIF §6.6).
///
/// This is the decode-free dependency planner: given a derived primary, it
/// reports (a) the output canvas size, (b) every node's resolved geometry,
/// and (c) the set of coded `'av01'` items — with no duplicates and in
/// first-visit order — that have to be decoded before the derivation can be
/// reconstructed. It ties together the per-derivation resolvers
/// ([`resolve_grids`] / [`resolve_overlays`] / [`resolve_iden_derivations`] /
/// [`resolve_tone_maps`]) into a single traversal that also handles
/// **nested** derivations (e.g. an `'iden'` crop of a `'grid'`, or a
/// `'tmap'` whose base is itself a `'grid'`).
///
/// The traversal is depth-bounded by [`MAX_DERIVATION_DEPTH`] so a `'dimg'`
/// cycle terminates; a node already visited is recorded once (its first
/// visit) and not re-expanded, so a diamond-shaped graph (two derivations
/// sharing an input) lists the shared leaf once.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DerivationGraph {
    /// The root item id the graph was built from.
    pub root_item_id: u32,
    /// Every reachable node, in first-visit (pre-order) order. The root is
    /// always `nodes[0]`.
    pub nodes: Vec<DerivationNode>,
    /// The distinct coded leaf item ids, in first-visit order — the decode
    /// set. A renderer decodes each of these once and composes them per the
    /// derivation tree.
    pub coded_leaf_ids: Vec<u32>,
    /// True when the walk hit [`MAX_DERIVATION_DEPTH`] before fully
    /// expanding the graph (a probable `'dimg'` cycle or pathological
    /// nesting). The partial graph collected up to the bound is still
    /// returned.
    pub truncated: bool,
}

impl DerivationGraph {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        root_item_id: u32,
        nodes: Vec<DerivationNode>,
        coded_leaf_ids: Vec<u32>,
        truncated: bool,
    ) -> Self {
        Self {
            root_item_id,
            nodes,
            coded_leaf_ids,
            truncated,
        }
    }
}

impl DerivationGraph {
    /// The root primary's output-image dimensions (the final canvas a
    /// renderer paints). `None` when the root geometry is unresolvable.
    pub fn output_dims(&self) -> Option<(u32, u32)> {
        self.nodes.first().and_then(|n| n.output_dims)
    }

    /// True when the root is a coded image item (not a derivation) — i.e.
    /// the file's primary is a plain coded picture and the graph has exactly
    /// one node.
    pub fn root_is_coded(&self) -> bool {
        self.nodes
            .first()
            .is_some_and(|n| n.kind == DerivationKind::Coded)
    }

    /// Look up a node by item id (linear scan; graphs are small).
    pub fn node(&self, item_id: u32) -> Option<&DerivationNode> {
        self.nodes.iter().find(|n| n.item_id == item_id)
    }

    /// The number of derived (non-coded) nodes in the graph.
    pub fn derived_node_count(&self) -> usize {
        self.nodes.iter().filter(|n| !n.kind.is_coded()).count()
    }

    /// The decode set paired with each leaf's reconstructed dimensions — the
    /// `(item_id, Option<(width, height)>)` a renderer needs to size each
    /// AV1 output buffer before composing the derivation. The dims are the
    /// leaf's `'ispe'` extents (its own `'clap'`/`'irot'` are applied during
    /// composition, not to the decode buffer), or `None` when the leaf
    /// carries no `'ispe'`. In first-visit (decode) order, de-duplicated.
    pub fn coded_leaf_dims(&self) -> Vec<(u32, Option<(u32, u32)>)> {
        self.coded_leaf_ids
            .iter()
            .map(|&id| (id, self.node(id).and_then(|n| n.reconstructed_dims)))
            .collect()
    }

    /// All node item ids at a given derivation `depth` (root = depth 0), in
    /// first-visit order. Depth 0 is always just the root.
    pub fn nodes_at_depth(&self, depth: u32) -> Vec<u32> {
        self.nodes
            .iter()
            .filter(|n| n.depth == depth)
            .map(|n| n.item_id)
            .collect()
    }
}

/// Walk the `'dimg'` derivation graph rooted at `root_item_id`, resolving
/// every node's box-graph geometry and collecting the distinct coded leaves
/// (HEIF §6.6). See [`DerivationGraph`].
///
/// No AV1 decode: all geometry comes from the box graph
/// ([`reconstructed_dims`] + [`transform_chain`]). The walk is depth-bounded
/// by [`MAX_DERIVATION_DEPTH`] (cycle guard) and visits each item id once.
pub fn build_derivation_graph(
    meta: &crate::meta::Meta,
    root_item_id: u32,
    file_bytes: &[u8],
    idat: Option<&[u8]>,
) -> DerivationGraph {
    let dimg = b(b"dimg");
    let mut nodes: Vec<DerivationNode> = Vec::new();
    let mut visited: Vec<u32> = Vec::new();
    let mut truncated = false;

    // Iterative pre-order walk over a small explicit stack of (item, depth)
    // so deep/adversarial nesting cannot blow the native stack. Children are
    // pushed in reverse so they pop in `dimg` reference order.
    let mut stack: Vec<(u32, u32)> = vec![(root_item_id, 0)];
    while let Some((item_id, depth)) = stack.pop() {
        if visited.contains(&item_id) {
            continue;
        }
        if depth > MAX_DERIVATION_DEPTH {
            truncated = true;
            continue;
        }
        visited.push(item_id);

        let Some(item) = meta.item_by_id(item_id) else {
            // A `dimg` target that names no known item: record nothing but
            // don't fail the whole walk.
            continue;
        };
        let inputs = meta.iref_targets(&dimg, item_id);
        let is_derived = !inputs.is_empty();
        let kind = DerivationKind::classify(&item.item_type, is_derived);

        let reconstructed = reconstructed_dims_inner(meta, item_id, file_bytes, idat, 0);
        let output =
            reconstructed.map(|(w, h)| output_dims_from_reconstructed(meta, item_id, w, h));

        if !kind.is_coded() {
            // Push children in reverse for pre-order `dimg` ordering.
            for &child in inputs.iter().rev() {
                stack.push((child, depth + 1));
            }
        }

        nodes.push(DerivationNode {
            item_id,
            kind,
            inputs,
            reconstructed_dims: reconstructed,
            output_dims: output,
            depth,
        });
    }

    // `nodes` is currently in stack-pop order; re-sort into ascending depth
    // then first-visit (visited) order so callers get a stable pre-order
    // view with the root first.
    let visit_rank = |id: u32| visited.iter().position(|&v| v == id).unwrap_or(usize::MAX);
    nodes.sort_by_key(|n| (n.depth, visit_rank(n.item_id)));

    // Coded leaves in stable pre-order (the sorted node order), deduplicated
    // — a diamond graph lists a shared leaf once.
    let coded_leaf_ids: Vec<u32> = nodes
        .iter()
        .filter(|n| n.kind.is_coded())
        .map(|n| n.item_id)
        .collect();

    DerivationGraph {
        root_item_id,
        nodes,
        coded_leaf_ids,
        truncated,
    }
}

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

    /// 16-bit `iovl` with two source images stacked at `(10, 20)` and
    /// `(30, 40)` on a 256×256 canvas filled white-opaque.
    #[test]
    fn iovl_parses_two_entries_16bit_fields() {
        let mut buf = Vec::new();
        buf.push(0); // version
        buf.push(0); // flags = 0 → 16-bit fields
        for v in [65535u16, 65535, 65535, 65535] {
            buf.extend_from_slice(&v.to_be_bytes());
        }
        buf.extend_from_slice(&256u16.to_be_bytes()); // output_width
        buf.extend_from_slice(&256u16.to_be_bytes()); // output_height
        buf.extend_from_slice(&10i16.to_be_bytes()); // h
        buf.extend_from_slice(&20i16.to_be_bytes()); // v
        buf.extend_from_slice(&30i16.to_be_bytes()); // h
        buf.extend_from_slice(&40i16.to_be_bytes()); // v
        let o = ImageOverlay::parse(&buf, 2).unwrap();
        assert_eq!(o.canvas_fill_value, [65535, 65535, 65535, 65535]);
        assert_eq!(o.output_width, 256);
        assert_eq!(o.output_height, 256);
        assert_eq!(
            o.entries,
            vec![
                OverlayEntry {
                    horizontal_offset: 10,
                    vertical_offset: 20
                },
                OverlayEntry {
                    horizontal_offset: 30,
                    vertical_offset: 40
                }
            ]
        );
    }

    /// 32-bit field variant (`flags & 1 == 1`) — needed for canvases
    /// larger than 65535 pixels.
    #[test]
    fn iovl_parses_32bit_fields() {
        let mut buf = Vec::new();
        buf.push(0); // version
        buf.push(1); // flags = 1 → 32-bit fields
        for v in [0u16, 0, 0, 0] {
            buf.extend_from_slice(&v.to_be_bytes());
        }
        // 100 000 × 8 000 (8·10⁸ pixels): 32-bit fields, inside the
        // container's 2³⁰-pixel descriptor bound.
        buf.extend_from_slice(&100_000u32.to_be_bytes()); // output_width
        buf.extend_from_slice(&8_000u32.to_be_bytes()); // output_height
        buf.extend_from_slice(&(-5i32).to_be_bytes()); // h (negative clips)
        buf.extend_from_slice(&10_000i32.to_be_bytes()); // v
        let o = ImageOverlay::parse(&buf, 1).unwrap();
        assert_eq!(o.output_width, 100_000);
        assert_eq!(o.output_height, 8_000);
        assert_eq!(o.entries[0].horizontal_offset, -5);
        assert_eq!(o.entries[0].vertical_offset, 10_000);
    }

    /// Negative `horizontal_offset` (signed) decoded correctly in
    /// 16-bit mode — a placement intentionally clipped at the left
    /// edge.
    #[test]
    fn iovl_negative_offset_signed_round_trip() {
        let mut buf = Vec::new();
        buf.push(0);
        buf.push(0);
        for _ in 0..4 {
            buf.extend_from_slice(&0u16.to_be_bytes());
        }
        buf.extend_from_slice(&64u16.to_be_bytes());
        buf.extend_from_slice(&64u16.to_be_bytes());
        buf.extend_from_slice(&(-3i16).to_be_bytes());
        buf.extend_from_slice(&(-4i16).to_be_bytes());
        let o = ImageOverlay::parse(&buf, 1).unwrap();
        assert_eq!(o.entries[0].horizontal_offset, -3);
        assert_eq!(o.entries[0].vertical_offset, -4);
    }

    /// `iovl` with `reference_count` larger than payload is rejected
    /// before allocating.
    #[test]
    fn iovl_rejects_oversized_reference_count() {
        let mut buf = Vec::new();
        buf.push(0);
        buf.push(0);
        for _ in 0..4 {
            buf.extend_from_slice(&0u16.to_be_bytes());
        }
        buf.extend_from_slice(&16u16.to_be_bytes());
        buf.extend_from_slice(&16u16.to_be_bytes());
        // Payload only has room for 0 entries; claim 100.
        assert!(ImageOverlay::parse(&buf, 100).is_err());
    }

    /// `iovl` rejects unrecognised versions.
    #[test]
    fn iovl_rejects_nonzero_version() {
        let buf = vec![1u8, 0]; // version=1
        assert!(ImageOverlay::parse(&buf, 0).is_err());
    }

    /// Build a minimal `grpl` containing one `altr` group with three
    /// alternate item ids.
    fn build_grpl_altr() -> Vec<u8> {
        let mut buf = Vec::new();
        // EntityToGroupBox: size(4) + 'altr' + FullBox(v=0,f=0) + group_id(4) + count(4) + ids
        let mut child = vec![0u8; 4]; // FullBox
        child.extend_from_slice(&42u32.to_be_bytes()); // group_id
        child.extend_from_slice(&3u32.to_be_bytes()); // num_entities
        child.extend_from_slice(&1u32.to_be_bytes());
        child.extend_from_slice(&2u32.to_be_bytes());
        child.extend_from_slice(&3u32.to_be_bytes());
        let size = (8 + child.len()) as u32;
        buf.extend_from_slice(&size.to_be_bytes());
        buf.extend_from_slice(b"altr");
        buf.extend_from_slice(&child);
        buf
    }

    /// `parse_grpl` extracts an `altr` group and surfaces its entity
    /// list in declaration order.
    #[test]
    fn grpl_parses_altr_group() {
        let grpl = build_grpl_altr();
        let groups = parse_grpl(&grpl).unwrap();
        assert_eq!(groups.len(), 1);
        let g = &groups[0];
        assert_eq!(&g.grouping_type, b"altr");
        assert!(g.is_alternates());
        assert!(!g.is_stereo_pair());
        assert!(!g.is_equivalence());
        assert!(!g.is_panorama());
        assert_eq!(g.group_id, 42);
        assert_eq!(g.entity_ids, vec![1, 2, 3]);
    }

    /// `pano` group (HEIF §6.8.8.1): entities listed in increasing
    /// panorama order; the helper classifies the grouping type.
    #[test]
    fn grpl_parses_pano_group() {
        let mut buf = Vec::new();
        let mut child = vec![0u8; 4]; // FullBox
        child.extend_from_slice(&5u32.to_be_bytes()); // group_id
        child.extend_from_slice(&3u32.to_be_bytes()); // num_entities
        child.extend_from_slice(&21u32.to_be_bytes()); // first in panorama order
        child.extend_from_slice(&22u32.to_be_bytes());
        child.extend_from_slice(&23u32.to_be_bytes());
        let size = (8 + child.len()) as u32;
        buf.extend_from_slice(&size.to_be_bytes());
        buf.extend_from_slice(b"pano");
        buf.extend_from_slice(&child);
        let groups = parse_grpl(&buf).unwrap();
        assert_eq!(groups.len(), 1);
        let g = &groups[0];
        assert!(g.is_panorama());
        assert!(!g.is_alternates());
        assert!(!g.is_stereo_pair());
        assert!(!g.is_equivalence());
        assert_eq!(g.entity_ids, vec![21, 22, 23]);
    }

    /// `prgr` / `brst` / `msrc` groups classify via their respective
    /// projections and are mutually exclusive with the others.
    #[test]
    fn grpl_classifies_prgr_brst_msrc_groups() {
        let build = |fourcc: &[u8; 4], ids: &[u32]| {
            let mut child = vec![0u8; 4]; // FullBox
            child.extend_from_slice(&7u32.to_be_bytes()); // group_id
            child.extend_from_slice(&(ids.len() as u32).to_be_bytes());
            for &id in ids {
                child.extend_from_slice(&id.to_be_bytes());
            }
            let mut buf = Vec::new();
            let size = (8 + child.len()) as u32;
            buf.extend_from_slice(&size.to_be_bytes());
            buf.extend_from_slice(fourcc);
            buf.extend_from_slice(&child);
            buf
        };

        let prgr = &parse_grpl(&build(b"prgr", &[1, 2, 3])).unwrap()[0];
        assert!(prgr.is_progressive());
        assert!(!prgr.is_burst() && !prgr.is_multi_source() && !prgr.is_alternates());
        assert_eq!(prgr.entity_ids, vec![1, 2, 3]);

        let brst = &parse_grpl(&build(b"brst", &[10, 11])).unwrap()[0];
        assert!(brst.is_burst());
        assert!(!brst.is_progressive() && !brst.is_multi_source());

        let msrc = &parse_grpl(&build(b"msrc", &[5, 6])).unwrap()[0];
        assert!(msrc.is_multi_source());
        assert!(!msrc.is_progressive() && !msrc.is_burst());
    }

    /// `tsyn` time-synchronized group + `iaug` audio-to-image group
    /// classify via their projections; the `iaug` flags LSB drives the
    /// audio-repeat semantic (HEIF §6.8.3 / §6.8.4).
    #[test]
    fn grpl_classifies_tsyn_and_iaug_groups() {
        // grouping child with an explicit 24-bit flags value.
        let build = |fourcc: &[u8; 4], flags: u32, ids: &[u32]| {
            let mut child = Vec::new();
            child.push(0u8); // version
            child.extend_from_slice(&flags.to_be_bytes()[1..]); // 24-bit flags
            child.extend_from_slice(&9u32.to_be_bytes()); // group_id
            child.extend_from_slice(&(ids.len() as u32).to_be_bytes());
            for &id in ids {
                child.extend_from_slice(&id.to_be_bytes());
            }
            let mut buf = Vec::new();
            let size = (8 + child.len()) as u32;
            buf.extend_from_slice(&size.to_be_bytes());
            buf.extend_from_slice(fourcc);
            buf.extend_from_slice(&child);
            buf
        };

        let tsyn = &parse_grpl(&build(b"tsyn", 0, &[1, 2, 3])).unwrap()[0];
        assert!(tsyn.is_time_synchronized());
        assert!(!tsyn.is_audio_to_image() && !tsyn.is_burst());
        assert_eq!(tsyn.entity_ids, vec![1, 2, 3]);
        assert_eq!(tsyn.flags, 0);

        // iaug with the repeat flag clear.
        let iaug = &parse_grpl(&build(b"iaug", 0, &[20, 21])).unwrap()[0];
        assert!(iaug.is_audio_to_image());
        assert!(!iaug.audio_repeats());
        assert_eq!(iaug.entity_ids, vec![20, 21]);

        // iaug with the repeat flag set.
        let iaug_rep = &parse_grpl(&build(b"iaug", 0x1, &[20, 21])).unwrap()[0];
        assert!(iaug_rep.is_audio_to_image());
        assert!(iaug_rep.audio_repeats());
        assert_eq!(iaug_rep.flags, 0x1);

        // audio_repeats is only meaningful for iaug — a set flag on a
        // different grouping type does not report a repeat.
        let ster = &parse_grpl(&build(b"ster", 0x1, &[20, 21])).unwrap()[0];
        assert!(!ster.audio_repeats());
    }

    /// `ster` / `iaug` carry an exactly-two `shall`; `cardinality_ok`
    /// flags a violation and passes any other grouping type (§6.8.5 /
    /// §6.8.4).
    #[test]
    fn grpl_cardinality_shall() {
        let build = |fourcc: &[u8; 4], ids: &[u32]| {
            let mut child = vec![0u8; 4];
            child.extend_from_slice(&1u32.to_be_bytes());
            child.extend_from_slice(&(ids.len() as u32).to_be_bytes());
            for &id in ids {
                child.extend_from_slice(&id.to_be_bytes());
            }
            let mut buf = Vec::new();
            let size = (8 + child.len()) as u32;
            buf.extend_from_slice(&size.to_be_bytes());
            buf.extend_from_slice(fourcc);
            buf.extend_from_slice(&child);
            buf
        };

        assert!(parse_grpl(&build(b"ster", &[1, 2])).unwrap()[0].cardinality_ok());
        assert!(!parse_grpl(&build(b"ster", &[1])).unwrap()[0].cardinality_ok());
        assert!(!parse_grpl(&build(b"ster", &[1, 2, 3])).unwrap()[0].cardinality_ok());
        assert!(parse_grpl(&build(b"iaug", &[1, 2])).unwrap()[0].cardinality_ok());
        assert!(!parse_grpl(&build(b"iaug", &[1])).unwrap()[0].cardinality_ok());
        // A grouping type with no fixed-count shall passes for any count.
        assert!(parse_grpl(&build(b"altr", &[1, 2, 3, 4])).unwrap()[0].cardinality_ok());
    }

    /// The five §6.8.6 bracketed-set grouping types classify through
    /// `bracketing_kind` / `is_bracketed_set`; non-bracket types return
    /// `None`.
    #[test]
    fn grpl_classifies_bracketed_set_groups() {
        let build = |fourcc: &[u8; 4], ids: &[u32]| {
            let mut child = vec![0u8; 4]; // FullBox
            child.extend_from_slice(&3u32.to_be_bytes()); // group_id
            child.extend_from_slice(&(ids.len() as u32).to_be_bytes());
            for &id in ids {
                child.extend_from_slice(&id.to_be_bytes());
            }
            let mut buf = Vec::new();
            let size = (8 + child.len()) as u32;
            buf.extend_from_slice(&size.to_be_bytes());
            buf.extend_from_slice(fourcc);
            buf.extend_from_slice(&child);
            buf
        };

        let cases = [
            (&b"aebr"[..], BracketingKind::AutoExposure),
            (&b"wbbr"[..], BracketingKind::WhiteBalance),
            (&b"fobr"[..], BracketingKind::Focus),
            (&b"afbr"[..], BracketingKind::FlashExposure),
            (&b"dobr"[..], BracketingKind::DepthOfField),
        ];
        for (fourcc, kind) in cases {
            let mut fc = [0u8; 4];
            fc.copy_from_slice(fourcc);
            let g = &parse_grpl(&build(&fc, &[1, 2])).unwrap()[0];
            assert!(g.is_bracketed_set());
            assert_eq!(g.bracketing_kind(), Some(kind));
            assert_eq!(kind.four_cc(), &fc);
        }

        // altr is not a bracketed set.
        let altr = &parse_grpl(&build(b"altr", &[1, 2])).unwrap()[0];
        assert!(!altr.is_bracketed_set());
        assert_eq!(altr.bracketing_kind(), None);
    }

    /// `slid` slideshow + `albc`/`favc` user-collection groups classify
    /// through their projections (HEIF §6.8.9 / §6.8.7).
    #[test]
    fn grpl_classifies_slid_and_user_collections() {
        let build = |fourcc: &[u8; 4], ids: &[u32]| {
            let mut child = vec![0u8; 4]; // FullBox
            child.extend_from_slice(&4u32.to_be_bytes()); // group_id
            child.extend_from_slice(&(ids.len() as u32).to_be_bytes());
            for &id in ids {
                child.extend_from_slice(&id.to_be_bytes());
            }
            let mut buf = Vec::new();
            let size = (8 + child.len()) as u32;
            buf.extend_from_slice(&size.to_be_bytes());
            buf.extend_from_slice(fourcc);
            buf.extend_from_slice(&child);
            buf
        };

        let slid = &parse_grpl(&build(b"slid", &[1, 2, 3])).unwrap()[0];
        assert!(slid.is_slideshow());
        assert!(!slid.is_user_collection() && !slid.is_bracketed_set());

        let albc = &parse_grpl(&build(b"albc", &[4, 5])).unwrap()[0];
        assert!(albc.is_album_collection() && albc.is_user_collection());
        assert!(!albc.is_favorites_collection() && !albc.is_slideshow());

        let favc = &parse_grpl(&build(b"favc", &[6])).unwrap()[0];
        assert!(favc.is_favorites_collection() && favc.is_user_collection());
        assert!(!favc.is_album_collection());
    }

    /// `ster` group convention: two entities, first is left view.
    #[test]
    fn grpl_parses_ster_pair() {
        let mut buf = Vec::new();
        let mut child = vec![0u8; 4]; // FullBox
        child.extend_from_slice(&7u32.to_be_bytes()); // group_id
        child.extend_from_slice(&2u32.to_be_bytes()); // num_entities
        child.extend_from_slice(&10u32.to_be_bytes()); // left view
        child.extend_from_slice(&11u32.to_be_bytes()); // right view
        let size = (8 + child.len()) as u32;
        buf.extend_from_slice(&size.to_be_bytes());
        buf.extend_from_slice(b"ster");
        buf.extend_from_slice(&child);
        let groups = parse_grpl(&buf).unwrap();
        assert_eq!(groups.len(), 1);
        assert!(groups[0].is_stereo_pair());
        assert_eq!(groups[0].entity_ids, vec![10, 11]);
    }

    /// Multiple groups in one `grpl` come out in declaration order.
    #[test]
    fn grpl_parses_multiple_groups() {
        let mut buf = Vec::new();
        // altr group
        let mut a = vec![0u8; 4];
        a.extend_from_slice(&1u32.to_be_bytes());
        a.extend_from_slice(&1u32.to_be_bytes());
        a.extend_from_slice(&100u32.to_be_bytes());
        let asz = (8 + a.len()) as u32;
        buf.extend_from_slice(&asz.to_be_bytes());
        buf.extend_from_slice(b"altr");
        buf.extend_from_slice(&a);
        // eqiv group
        let mut e = vec![0u8; 4];
        e.extend_from_slice(&2u32.to_be_bytes());
        e.extend_from_slice(&0u32.to_be_bytes()); // empty group
        let esz = (8 + e.len()) as u32;
        buf.extend_from_slice(&esz.to_be_bytes());
        buf.extend_from_slice(b"eqiv");
        buf.extend_from_slice(&e);
        let groups = parse_grpl(&buf).unwrap();
        assert_eq!(groups.len(), 2);
        assert!(groups[0].is_alternates());
        assert!(groups[1].is_equivalence());
        assert!(groups[1].entity_ids.is_empty());
    }

    /// Truncated entity list is rejected before allocation overflow.
    #[test]
    fn grpl_rejects_truncated_entity_list() {
        let mut buf = Vec::new();
        let mut child = vec![0u8; 4];
        child.extend_from_slice(&1u32.to_be_bytes()); // group_id
        child.extend_from_slice(&5u32.to_be_bytes()); // claims 5 entities…
        child.extend_from_slice(&100u32.to_be_bytes()); // …but ships only 1
        let size = (8 + child.len()) as u32;
        buf.extend_from_slice(&size.to_be_bytes());
        buf.extend_from_slice(b"altr");
        buf.extend_from_slice(&child);
        assert!(parse_grpl(&buf).is_err());
    }

    /// Mif1Compliance flags every missing required box.
    #[test]
    fn mif1_compliance_missing_list() {
        let bare = Mif1Compliance::default();
        assert!(!bare.is_compliant());
        let m = bare.missing();
        // Order is fixed; every required box should appear.
        assert!(m.contains(&"hdlr"));
        assert!(m.contains(&"pitm"));
        assert!(m.contains(&"iinf"));
        assert!(m.contains(&"infe"));
        assert!(m.contains(&"iloc"));
        assert!(m.contains(&"iprp"));
    }

    /// Mif1Compliance with every required flag set reports compliant.
    #[test]
    fn mif1_compliance_full() {
        let m = Mif1Compliance {
            has_hdlr: true,
            has_pitm: true,
            has_iinf: true,
            has_iloc: true,
            has_iprp: true,
            infe_count: 1,
            claims_mif1: true,
        };
        assert!(m.is_compliant());
        assert!(m.missing().is_empty());
    }

    // ---- sato (Sample Transform Derived Image Item) -----------------

    /// Build a `sato` payload (header byte + token_count + token bytes).
    /// `bit_depth` is the 2-bit selector; `tokens` is the raw byte
    /// stream (caller is responsible for appending constant payloads).
    fn build_sato_raw(bit_depth: u8, tokens: &[u8]) -> Vec<u8> {
        let mut buf = Vec::with_capacity(2 + tokens.len());
        // version = 0 in the high 2 bits, bit_depth in the low 2.
        buf.push(bit_depth & 0x03);
        assert!(tokens.iter().filter(|&&t| t != 0).count() <= 255);
        // token_count = number of *tokens* (not bytes); the caller has
        // already serialised constant payloads inline. We need the
        // count of token bytes (each token is one byte plus optional
        // constant payload), which is hard to recover from bytes
        // alone, so the helpers below count it themselves.
        // Inserted by callers via build_sato_tokens.
        buf.push(0);
        buf.extend_from_slice(tokens);
        buf
    }

    /// Build a well-formed `sato` payload with the given header
    /// `bit_depth` and an iterable of `Token`s. Constants serialise to
    /// the bit-depth-keyed byte width per spec Table 1.
    fn build_sato(bit_depth: u8, tokens: &[Token]) -> Vec<u8> {
        let const_bytes = match bit_depth & 0x03 {
            0 => 1,
            1 => 2,
            2 => 4,
            3 => 8,
            _ => unreachable!(),
        };
        let mut body = Vec::new();
        for t in tokens {
            match t {
                Token::Constant(v) => {
                    body.push(0);
                    match const_bytes {
                        1 => body.push(*v as i8 as u8),
                        2 => body.extend_from_slice(&(*v as i16).to_be_bytes()),
                        4 => body.extend_from_slice(&(*v as i32).to_be_bytes()),
                        8 => body.extend_from_slice(&v.to_be_bytes()),
                        _ => unreachable!(),
                    }
                }
                Token::Sample(n) => body.push(*n),
                Token::Unary(raw) | Token::Binary(raw) | Token::Reserved(raw) => body.push(*raw),
            }
        }
        let mut buf = build_sato_raw(bit_depth, &body);
        buf[1] = tokens.len() as u8;
        buf
    }

    /// Round-trip a minimal constant-only expression at every supported
    /// bit_depth (8 / 16 / 32 / 64 bits intermediate).
    #[test]
    fn sato_parses_constant_only_each_bit_depth() {
        for (bd, expected_bits) in [(0, 8u32), (1, 16), (2, 32), (3, 64)] {
            let payload = build_sato(bd, &[Token::Constant(-1)]);
            let st = SampleTransform::parse(&payload, 0).unwrap();
            assert_eq!(st.version, 0);
            assert_eq!(st.bit_depth, bd);
            assert_eq!(st.num_bits(), expected_bits);
            assert_eq!(st.tokens, vec![Token::Constant(-1)]);
            // Evaluating with no inputs yields the constant.
            assert_eq!(st.evaluate(&[]).unwrap(), -1);
        }
    }

    /// A two-sample postfix sum expression — Sample(1), Sample(2),
    /// Binary(128) — evaluates to L + R.
    #[test]
    fn sato_evaluates_sum_of_two_samples() {
        let payload = build_sato(0, &[Token::Sample(1), Token::Sample(2), Token::Binary(128)]);
        let st = SampleTransform::parse(&payload, 2).unwrap();
        assert_eq!(st.tokens.len(), 3);
        assert_eq!(st.evaluate(&[40, 25]).unwrap(), 65);
        // Overflow clamps to max_value for 8-bit intermediate.
        assert_eq!(st.evaluate(&[120, 120]).unwrap(), 127);
    }

    /// Difference is right-popped first — av1-avif Table 2 row 129.
    /// `Sample(1) Sample(2) Binary(129)` is `L - R = inputs[0] -
    /// inputs[1]`.
    #[test]
    fn sato_evaluates_difference_with_right_pop_first() {
        let payload = build_sato(
            1, // 16-bit intermediate avoids 8-bit clamps
            &[Token::Sample(1), Token::Sample(2), Token::Binary(129)],
        );
        let st = SampleTransform::parse(&payload, 2).unwrap();
        assert_eq!(st.evaluate(&[100, 30]).unwrap(), 70);
        assert_eq!(st.evaluate(&[30, 100]).unwrap(), -70);
    }

    /// Worked example from av1-avif Appendix A — combine an 8-bit MSB
    /// item and an 8-bit residual to produce a 16-bit result via
    /// `(msb << 8) | residual` ≡ Sample(1) Constant(256) * Sample(2) +.
    /// Verified via the `or` operator (bitwise) — spec accepts either.
    #[test]
    fn sato_evaluates_msb_residual_recombine() {
        // Tokens: Sample(1), Constant(8), Binary(135 pow → 2^8=256),
        //         Binary(130 product), Sample(2), Binary(128 sum)
        let payload = build_sato(
            1, // 16-bit intermediate
            &[
                Token::Sample(1),
                Token::Constant(2),
                Token::Constant(8),
                Token::Binary(135), // 2^8 = 256
                Token::Binary(130), // sample(1) * 256
                Token::Sample(2),
                Token::Binary(128), // + sample(2)
            ],
        );
        let st = SampleTransform::parse(&payload, 2).unwrap();
        // msb=0x12, lsb=0x34 → 0x1234 = 4660
        assert_eq!(st.evaluate(&[0x12, 0x34]).unwrap(), 0x1234);
    }

    /// Unary `negation` (token 64) flips the sign of the top of stack.
    #[test]
    fn sato_evaluates_unary_negation() {
        let payload = build_sato(1, &[Token::Sample(1), Token::Unary(64)]);
        let st = SampleTransform::parse(&payload, 1).unwrap();
        assert_eq!(st.evaluate(&[42]).unwrap(), -42);
    }

    /// Unary `bsr` (token 67) returns the MSB index for L > 0, else 0.
    #[test]
    fn sato_evaluates_unary_bsr() {
        let payload = build_sato(1, &[Token::Sample(1), Token::Unary(67)]);
        let st = SampleTransform::parse(&payload, 1).unwrap();
        assert_eq!(st.evaluate(&[1]).unwrap(), 0); // log2(1) = 0
        assert_eq!(st.evaluate(&[2]).unwrap(), 1);
        assert_eq!(st.evaluate(&[255]).unwrap(), 7);
        assert_eq!(st.evaluate(&[0]).unwrap(), 0); // spec: 0 for L <= 0
        assert_eq!(st.evaluate(&[-5]).unwrap(), 0);
    }

    /// Quotient (token 131) returns L for R == 0, else L/R truncated
    /// toward zero.
    #[test]
    fn sato_evaluates_quotient_with_zero_divisor_returns_left() {
        let payload = build_sato(1, &[Token::Sample(1), Token::Sample(2), Token::Binary(131)]);
        let st = SampleTransform::parse(&payload, 2).unwrap();
        assert_eq!(st.evaluate(&[10, 3]).unwrap(), 3); // 10/3 → 3
        assert_eq!(st.evaluate(&[-10, 3]).unwrap(), -3); // truncate toward zero
        assert_eq!(st.evaluate(&[10, 0]).unwrap(), 10); // R == 0 → L
    }

    /// Pow (token 135) returns 0 for L == 0, otherwise L^R truncated.
    #[test]
    fn sato_evaluates_pow_zero_base() {
        let payload = build_sato(1, &[Token::Sample(1), Token::Sample(2), Token::Binary(135)]);
        let st = SampleTransform::parse(&payload, 2).unwrap();
        assert_eq!(st.evaluate(&[0, 5]).unwrap(), 0);
        assert_eq!(st.evaluate(&[2, 3]).unwrap(), 8);
        assert_eq!(st.evaluate(&[3, 0]).unwrap(), 1);
    }

    /// Min / max (tokens 136 / 137) pick the appropriate operand.
    #[test]
    fn sato_evaluates_min_max() {
        let min_p = build_sato(1, &[Token::Sample(1), Token::Sample(2), Token::Binary(136)]);
        let max_p = build_sato(1, &[Token::Sample(1), Token::Sample(2), Token::Binary(137)]);
        let min_st = SampleTransform::parse(&min_p, 2).unwrap();
        let max_st = SampleTransform::parse(&max_p, 2).unwrap();
        assert_eq!(min_st.evaluate(&[10, 3]).unwrap(), 3);
        assert_eq!(max_st.evaluate(&[10, 3]).unwrap(), 10);
        assert_eq!(min_st.evaluate(&[-5, -2]).unwrap(), -5);
        assert_eq!(max_st.evaluate(&[-5, -2]).unwrap(), -2);
    }

    /// `token_count = 0` is rejected per av1-avif §4.2.3.3 assert
    /// `66976029`.
    #[test]
    fn sato_rejects_zero_token_count() {
        let buf = vec![0u8, 0]; // header, token_count=0
        let err = SampleTransform::parse(&buf, 0).unwrap_err();
        assert!(format!("{err:?}").contains("token_count"));
    }

    /// version != 0 is rejected by the strict parser (spec: "Readers
    /// shall ignore" — we map that to an error so the caller decides).
    #[test]
    fn sato_rejects_nonzero_version() {
        let mut buf = build_sato(0, &[Token::Constant(0)]);
        buf[0] = 1u8 << 6; // version=1
        assert!(SampleTransform::parse(&buf, 0).is_err());
        // parse_relaxed still surfaces it.
        let relaxed = SampleTransform::parse_relaxed(&buf).unwrap();
        assert_eq!(relaxed.version, 1);
    }

    /// A sample-operand token whose value exceeds reference_count is
    /// rejected per av1-avif §4.2.3.4 assert `1f569fa5`.
    #[test]
    fn sato_rejects_sample_index_over_reference_count() {
        let payload = build_sato(0, &[Token::Sample(5)]);
        assert!(SampleTransform::parse(&payload, 3).is_err());
        assert!(SampleTransform::parse(&payload, 5).is_ok());
    }

    /// Reserved token values (33..=63, 68..=127, 138..=255) are
    /// rejected by `parse` per av1-avif §4.2.3.3.
    #[test]
    fn sato_rejects_reserved_token_values() {
        for raw in [33u8, 50, 63, 68, 100, 127, 138, 200, 255] {
            let payload = build_sato_raw(0, &[raw]);
            // Fix token_count to 1.
            let mut p = payload;
            p[1] = 1;
            assert!(
                SampleTransform::parse(&p, 32).is_err(),
                "expected error for reserved token {raw}"
            );
            // parse_relaxed surfaces it as a Reserved variant.
            let relaxed = SampleTransform::parse_relaxed(&p).unwrap();
            assert_eq!(relaxed.tokens, vec![Token::Reserved(raw)]);
        }
    }

    /// A binary operator on a single-operand stack is caught by the
    /// stack-discipline check.
    #[test]
    fn sato_rejects_binary_op_without_enough_operands() {
        let payload = build_sato(0, &[Token::Sample(1), Token::Binary(128)]);
        assert!(SampleTransform::parse(&payload, 32).is_err());
    }

    /// An expression that leaves more than one element on the stack
    /// is rejected (av1-avif §4.2.3.4 assert `bac41e3a`).
    #[test]
    fn sato_rejects_expression_with_leftover_stack() {
        let payload = build_sato(0, &[Token::Sample(1), Token::Sample(2)]);
        let err = SampleTransform::parse(&payload, 32).unwrap_err();
        assert!(format!("{err:?}").contains("leaves 2"));
    }

    /// Truncated payload (claims `token_count = 3` but only ships 1
    /// token byte) is rejected.
    #[test]
    fn sato_rejects_truncated_token_stream() {
        let payload = vec![0u8, 3, 1]; // header, token_count=3, only one token
        assert!(SampleTransform::parse(&payload, 32).is_err());
        assert!(SampleTransform::parse_relaxed(&payload).is_err());
    }

    /// Constant payload that runs off the end of the buffer is
    /// rejected (8-byte constant at `bit_depth=3` but only 4 bytes
    /// remaining).
    #[test]
    fn sato_rejects_truncated_constant_payload() {
        // bit_depth=3 → 8-byte constants
        let mut buf = vec![3u8, 1, 0]; // bit_depth=3, token_count=1, token=Constant
        buf.extend_from_slice(&[0u8, 0, 0, 0]); // only 4 bytes of the needed 8
        assert!(SampleTransform::parse(&buf, 0).is_err());
    }

    /// Number-of-bits mapping matches av1-avif Table 1 verbatim.
    #[test]
    fn sato_num_bits_table_1() {
        let mk = |bd: u8| SampleTransform {
            version: 0,
            bit_depth: bd,
            tokens: vec![Token::Constant(0)],
        };
        assert_eq!(mk(0).num_bits(), 8);
        assert_eq!(mk(1).num_bits(), 16);
        assert_eq!(mk(2).num_bits(), 32);
        assert_eq!(mk(3).num_bits(), 64);
    }

    /// min_value / max_value cover every supported bit depth.
    #[test]
    fn sato_min_max_value_per_bit_depth() {
        let mk = |bd: u8| SampleTransform {
            version: 0,
            bit_depth: bd,
            tokens: vec![Token::Constant(0)],
        };
        assert_eq!(mk(0).min_value(), -128);
        assert_eq!(mk(0).max_value(), 127);
        assert_eq!(mk(1).min_value(), -32_768);
        assert_eq!(mk(1).max_value(), 32_767);
        assert_eq!(mk(2).min_value(), i32::MIN as i64);
        assert_eq!(mk(2).max_value(), i32::MAX as i64);
        assert_eq!(mk(3).min_value(), i64::MIN);
        assert_eq!(mk(3).max_value(), i64::MAX);
    }

    /// `Token::is_operand` / `is_unary` / `is_binary` classification
    /// matches the variant the parser yields.
    #[test]
    fn sato_token_classification_helpers() {
        assert!(Token::Constant(0).is_operand());
        assert!(Token::Sample(1).is_operand());
        assert!(!Token::Unary(64).is_operand());
        assert!(!Token::Binary(128).is_operand());
        assert!(Token::Unary(64).is_unary());
        assert!(!Token::Binary(128).is_unary());
        assert!(Token::Binary(128).is_binary());
        assert!(!Token::Unary(64).is_binary());
    }

    /// `evaluate` errors when given fewer inputs than the expression
    /// requires (defence in depth — parse() also enforces the
    /// reference_count constraint).
    #[test]
    fn sato_evaluate_errors_when_inputs_short() {
        let payload = build_sato(0, &[Token::Sample(3)]);
        let st = SampleTransform::parse(&payload, 3).unwrap();
        let err = st.evaluate(&[1, 2]).unwrap_err();
        assert!(format!("{err:?}").contains("out of range"));
    }

    // -------------------------------------------------------------------
    // Tone Map compliance audit (av1-avif v1.2.0 §4.2.2)
    // -------------------------------------------------------------------

    use crate::meta::{IrefEntry, ItemInfo, Meta};

    fn make_infe(id: u32, item_type: &[u8; 4], flags: u32) -> ItemInfo {
        ItemInfo {
            id,
            item_type: *item_type,
            name: String::new(),
            content_type: None,
            content_encoding: None,
            item_uri_type: None,
            flags,
        }
    }

    /// Build a `grpl` payload containing one `altr` EntityToGroupBox
    /// over the given ids.
    fn build_altr_grpl(group_id: u32, ids: &[u32]) -> Vec<u8> {
        let mut child = vec![0u8; 4]; // FullBox(version=0, flags=0)
        child.extend_from_slice(&group_id.to_be_bytes());
        child.extend_from_slice(&(ids.len() as u32).to_be_bytes());
        for id in ids {
            child.extend_from_slice(&id.to_be_bytes());
        }
        let size = (8 + child.len()) as u32;
        let mut buf = Vec::new();
        buf.extend_from_slice(&size.to_be_bytes());
        buf.extend_from_slice(b"altr");
        buf.extend_from_slice(&child);
        buf
    }

    /// Happy path: one tmap item with one base (no gain map), grouped
    /// with the base by an `altr` entity group. Compliant.
    #[test]
    fn audit_tone_map_altr_pairing_compliant() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0), // base, visible
                make_infe(2, b"tmap", 0), // tmap derived item
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 2,
                to_ids: vec![1],
            }],
            grpl: Some(build_altr_grpl(7, &[1, 2])),
            ..Meta::default()
        };
        let results = audit_tone_map(&meta);
        assert_eq!(results.len(), 1);
        let r = &results[0];
        assert_eq!(r.tmap_item_id, 2);
        assert_eq!(r.base_item_id, Some(1));
        assert!(r.gain_map_item_ids.is_empty());
        assert!(r.paired_in_altr);
        assert!(r.gain_maps_hidden);
        assert!(r.is_compliant());
        assert!(r.missing().is_empty());
    }

    /// tmap + base + gain map, where the gain map is hidden as the
    /// spec recommends. Should pass when there's also an `altr` group.
    #[test]
    fn audit_tone_map_hidden_gain_map_compliant() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),    // base, visible
                make_infe(2, b"av01", 0x01), // gain map, hidden
                make_infe(3, b"tmap", 0),    // tmap derived item
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 3,
                to_ids: vec![1, 2],
            }],
            grpl: Some(build_altr_grpl(9, &[1, 3])),
            ..Meta::default()
        };
        let r = &audit_tone_map(&meta)[0];
        assert_eq!(r.base_item_id, Some(1));
        assert_eq!(r.gain_map_item_ids, vec![2]);
        assert!(r.paired_in_altr);
        assert!(r.gain_maps_hidden);
        assert!(r.is_compliant());
    }

    /// No `grpl` at all → `altr` pairing fails; visible gain map →
    /// gain-map hidden check fails. Both `missing` entries surface.
    #[test]
    fn audit_tone_map_flags_both_failures() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0), // base, visible
                make_infe(2, b"av01", 0), // gain map NOT hidden
                make_infe(3, b"tmap", 0),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 3,
                to_ids: vec![1, 2],
            }],
            grpl: None,
            ..Meta::default()
        };
        let r = &audit_tone_map(&meta)[0];
        assert!(!r.paired_in_altr);
        assert!(!r.gain_maps_hidden);
        assert!(!r.is_compliant());
        let m = r.missing();
        assert!(m.contains(&"altr-pairs-base-and-tmap"));
        assert!(m.contains(&"gain-map-hidden"));
    }

    /// `grpl` present but the `altr` group lists only the base — the
    /// pairing check should still fail when the tmap id is absent.
    #[test]
    fn audit_tone_map_altr_without_tmap_id_fails_pairing() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"tmap", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 2,
                to_ids: vec![1],
            }],
            grpl: Some(build_altr_grpl(11, &[1, 99])), // tmap not in altr
            ..Meta::default()
        };
        let r = &audit_tone_map(&meta)[0];
        assert!(!r.paired_in_altr);
        // No gain map → hidden check trivially true.
        assert!(r.gain_maps_hidden);
        assert!(!r.is_compliant());
    }

    /// A tmap with no `dimg` iref at all surfaces `base_item_id =
    /// None` and fails the altr-pairing check (nothing to pair with).
    #[test]
    fn audit_tone_map_no_dimg_iref() {
        let meta = Meta {
            items: vec![make_infe(2, b"tmap", 0)],
            irefs: vec![],
            grpl: None,
            ..Meta::default()
        };
        let r = &audit_tone_map(&meta)[0];
        assert_eq!(r.base_item_id, None);
        assert!(r.gain_map_item_ids.is_empty());
        assert!(!r.paired_in_altr);
        // No gain map → hidden check trivially true.
        assert!(r.gain_maps_hidden);
    }

    /// File with no `tmap` items returns an empty audit list.
    #[test]
    fn audit_tone_map_empty_when_no_tmap_items() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            ..Meta::default()
        };
        assert!(audit_tone_map(&meta).is_empty());
    }

    /// Multiple `tmap` items audited in `iinf` declaration order.
    #[test]
    fn audit_tone_map_reports_each_tmap_item() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"tmap", 0),
                make_infe(3, b"av01", 0x01), // hidden
                make_infe(4, b"tmap", 0),
            ],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![1],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 4,
                    to_ids: vec![1, 3],
                },
            ],
            grpl: Some(build_altr_grpl(1, &[1, 2, 4])),
            ..Meta::default()
        };
        let r = audit_tone_map(&meta);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].tmap_item_id, 2);
        assert_eq!(r[1].tmap_item_id, 4);
        assert!(r[0].is_compliant());
        assert!(r[1].is_compliant());
    }

    /// `ItemInfo::is_hidden` honours `flags & 0x01` and ignores higher
    /// bits.
    #[test]
    fn item_info_is_hidden_reads_low_bit_only() {
        assert!(!make_infe(1, b"av01", 0).is_hidden());
        assert!(make_infe(1, b"av01", 0x01).is_hidden());
        // High bits set but bit 0 clear → not hidden.
        assert!(!make_infe(1, b"av01", 0xfffe).is_hidden());
        // Mixed: bit 0 set + other bits set → hidden.
        assert!(make_infe(1, b"av01", 0xff03).is_hidden());
    }

    // -------------------------------------------------------------------
    // Grid derivation chain — transformative-property audit (av1-avif §7)
    // -------------------------------------------------------------------

    use crate::meta::{Clap, Imir, Irot, ItemPropertyAssociation, Property, PropertyAssociation};

    /// Sample Clap value — arbitrary, the audit only cares about presence.
    fn sample_clap() -> Clap {
        Clap {
            clean_aperture_width_n: 1,
            clean_aperture_width_d: 1,
            clean_aperture_height_n: 1,
            clean_aperture_height_d: 1,
            horiz_off_n: 0,
            horiz_off_d: 1,
            vert_off_n: 0,
            vert_off_d: 1,
        }
    }

    fn assoc(item_id: u32, indices: &[u16]) -> ItemPropertyAssociation {
        ItemPropertyAssociation {
            item_id,
            entries: indices
                .iter()
                .map(|i| PropertyAssociation {
                    index: *i,
                    essential: false,
                })
                .collect(),
        }
    }

    /// Compliant grid: no tile carries a transformative property — the
    /// grid item may itself carry `irot` / `imir` / `clap` (we put `irot`
    /// on the grid here to prove the audit ignores grid-level transforms).
    #[test]
    fn audit_grid_derivations_clean_chain_compliant() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"grid", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"av01", 0),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            // Index 0: irot on the grid item (permitted by §7).
            properties: vec![Property::Irot(Irot { angle: 1 })],
            associations: vec![assoc(1, &[0])],
            ..Meta::default()
        };
        let r = audit_grid_derivations(&meta);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].grid_item_id, 1);
        assert_eq!(r[0].tile_item_ids, vec![2, 3]);
        assert!(
            r[0].offenders.is_empty(),
            "grid-level transforms must not flag the chain"
        );
        assert!(r[0].is_compliant());
        assert!(r[0].offending_tile_ids().is_empty());
    }

    /// Non-compliant grid: a tile carries `irot`. The audit reports the
    /// offending tile + `irot` kind, and `is_compliant` flips to false.
    #[test]
    fn audit_grid_derivations_tile_irot_flagged() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"grid", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"av01", 0),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            properties: vec![Property::Irot(Irot { angle: 2 })],
            // Tile 3 carries the property — chain violation.
            associations: vec![assoc(3, &[0])],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert!(!r.is_compliant());
        assert_eq!(r.offenders, vec![(3, *b"irot")]);
        assert_eq!(r.offending_tile_ids(), vec![3]);
    }

    /// A single tile carrying all three transformative kinds surfaces
    /// three offender entries in the stable `(clap, irot, imir)` order
    /// the audit produces.
    #[test]
    fn audit_grid_derivations_tile_with_all_four_kinds() {
        let meta = Meta {
            items: vec![make_infe(1, b"grid", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2],
            }],
            properties: vec![
                Property::Clap(sample_clap()),
                Property::Irot(Irot { angle: 1 }),
                Property::Imir(Imir { axis: 0 }),
                Property::Iscl(crate::meta::Iscl {
                    target_width_numerator: 1,
                    target_width_denominator: 2,
                    target_height_numerator: 1,
                    target_height_denominator: 2,
                }),
            ],
            associations: vec![assoc(2, &[0, 1, 2, 3])],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert_eq!(
            r.offenders,
            vec![(2, *b"clap"), (2, *b"irot"), (2, *b"imir"), (2, *b"iscl"),]
        );
        // Tile id is unique even though it offends four times.
        assert_eq!(r.offending_tile_ids(), vec![2]);
    }

    /// HEIF §6.5.13 `'iscl'` is a transformative item property; av1-avif
    /// §7 forbids any transformative property on a `'dimg'` input tile.
    /// A solo `'iscl'` on a tile must surface as an offender.
    #[test]
    fn audit_grid_derivations_tile_iscl_flagged() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"grid", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"av01", 0),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            properties: vec![Property::Iscl(crate::meta::Iscl {
                target_width_numerator: 1,
                target_width_denominator: 2,
                target_height_numerator: 1,
                target_height_denominator: 2,
            })],
            // Only tile 2 carries the iscl; tile 3 is clean.
            associations: vec![assoc(2, &[0])],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert!(!r.is_compliant());
        assert_eq!(r.offenders, vec![(2, *b"iscl")]);
        assert_eq!(r.offending_tile_ids(), vec![2]);
    }

    /// HEIF §6.5.17 `'rref'` is descriptive (not transformative). A
    /// tile carrying `'rref'` must NOT be reported by the §7 audit —
    /// the §7 `shall` is scoped to transformative properties only.
    #[test]
    fn audit_grid_derivations_tile_rref_not_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"grid", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2],
            }],
            properties: vec![Property::Rref(crate::meta::Rref {
                reference_types: vec![*b"dimg"],
            })],
            associations: vec![assoc(2, &[0])],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert!(r.is_compliant());
        assert!(r.offenders.is_empty());
    }

    /// An `'iscl'` on the grid item itself is explicitly permitted by
    /// §7 ("transformations are only permitted on the grid item
    /// itself"), so it must not surface as an offender.
    #[test]
    fn audit_grid_derivations_grid_level_iscl_permitted() {
        let meta = Meta {
            items: vec![make_infe(1, b"grid", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2],
            }],
            properties: vec![Property::Iscl(crate::meta::Iscl {
                target_width_numerator: 1,
                target_width_denominator: 2,
                target_height_numerator: 1,
                target_height_denominator: 2,
            })],
            // Iscl associated with the grid (id 1), tile 2 clean.
            associations: vec![assoc(1, &[0])],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert!(r.is_compliant());
        assert!(r.offenders.is_empty());
    }

    /// Two tiles offending in different ways. Both surface; the unique
    /// tile-id list collapses duplicates.
    #[test]
    fn audit_grid_derivations_multiple_offending_tiles() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"grid", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"av01", 0),
                make_infe(4, b"av01", 0),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3, 4],
            }],
            properties: vec![
                Property::Imir(Imir { axis: 1 }),
                Property::Clap(sample_clap()),
            ],
            associations: vec![
                // Tile 3 carries imir; tile 4 carries clap; tile 2 clean.
                assoc(3, &[0]),
                assoc(4, &[1]),
            ],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert!(!r.is_compliant());
        // clap-on-4 sorts before imir-on-3 in the per-tile loop:
        // we walk tiles in dimg order (2, 3, 4) and emit (clap, irot, imir)
        // per tile, so the result is [(3, imir), (4, clap)].
        assert_eq!(r.offenders, vec![(3, *b"imir"), (4, *b"clap")]);
        assert_eq!(r.offending_tile_ids(), vec![3, 4]);
    }

    /// File with no `grid` items returns an empty audit list — the
    /// constraint is vacuous and the strict-compliant predicate folds
    /// to true.
    #[test]
    fn audit_grid_derivations_empty_when_no_grid_items() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            ..Meta::default()
        };
        assert!(audit_grid_derivations(&meta).is_empty());
    }

    /// Multiple grid items each get their own audit record, in `iinf`
    /// declaration order.
    #[test]
    fn audit_grid_derivations_reports_each_grid_item() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"grid", 0), // first grid
                make_infe(2, b"av01", 0),
                make_infe(3, b"av01", 0),
                make_infe(4, b"grid", 0), // second grid
                make_infe(5, b"av01", 0),
            ],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2, 3],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 4,
                    to_ids: vec![5],
                },
            ],
            properties: vec![Property::Irot(Irot { angle: 3 })],
            // Tile 5 (second grid's tile) carries an irot.
            associations: vec![assoc(5, &[0])],
            ..Meta::default()
        };
        let r = audit_grid_derivations(&meta);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].grid_item_id, 1);
        assert!(r[0].is_compliant());
        assert_eq!(r[1].grid_item_id, 4);
        assert!(!r[1].is_compliant());
        assert_eq!(r[1].offenders, vec![(5, *b"irot")]);
    }

    /// A grid item with no `dimg` iref still emits an audit record with
    /// empty tile + offender vectors. The constraint is trivially
    /// satisfied (no chain → no offending tiles); a malformed grid is
    /// caught elsewhere.
    #[test]
    fn audit_grid_derivations_grid_without_dimg_is_compliant() {
        let meta = Meta {
            items: vec![make_infe(1, b"grid", 0)],
            ..Meta::default()
        };
        let r = &audit_grid_derivations(&meta)[0];
        assert_eq!(r.grid_item_id, 1);
        assert!(r.tile_item_ids.is_empty());
        assert!(r.is_compliant());
    }

    // -------------------------------------------------------------------
    // Identity (`iden`) compliance audit (HEIF §6.6.2.1 + §6.6.1)
    // -------------------------------------------------------------------

    use crate::meta::{IlocExtent, ItemLocation};

    /// Build a placeholder [`ItemLocation`] with a single non-empty
    /// extent — useful for the `has_item_body == true` (non-conformant)
    /// shape.
    fn make_iloc_with_body(id: u32) -> ItemLocation {
        ItemLocation {
            id,
            construction_method: 0,
            data_reference_index: 0,
            base_offset: 0,
            extents: vec![IlocExtent {
                offset: 1000,
                length: 16,
                extent_index: 0,
            }],
        }
    }

    /// `ItemLocation` with one extent whose `length == 0`. HEIF §6.6.2.1
    /// requires the iden to have no body; a zero-length extent is
    /// equivalent (no actual bytes) and the audit treats it as compliant.
    fn make_iloc_zero_length(id: u32) -> ItemLocation {
        ItemLocation {
            id,
            construction_method: 0,
            data_reference_index: 0,
            base_offset: 0,
            extents: vec![IlocExtent {
                offset: 0,
                length: 0,
                extent_index: 0,
            }],
        }
    }

    /// Happy path: one `'iden'` item with exactly one `'dimg'` input,
    /// exactly one `'dimg'` iref entry for the iden's `from_item_ID`,
    /// and no `'iloc'` entry at all (so trivially no body).
    #[test]
    fn audit_iden_compliant_no_iloc_entry() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0), // source
                make_infe(2, b"iden", 0), // identity derivation
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 2,
                to_ids: vec![1],
            }],
            ..Meta::default()
        };
        let r = audit_iden_derivations(&meta);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].iden_item_id, 2);
        assert_eq!(r[0].dimg_reference_count, 1);
        assert_eq!(r[0].dimg_iref_count, 1);
        assert!(!r[0].has_item_body);
        assert_eq!(r[0].source_item_id, Some(1));
        assert!(r[0].is_compliant());
        assert!(r[0].missing().is_empty());
    }

    /// An `'iden'` with an `'iloc'` entry that carries a zero-length
    /// extent passes the "no item body" check — the spec defines "body"
    /// in terms of actual byte content, not the presence of an iloc
    /// entry. Compliant.
    #[test]
    fn audit_iden_compliant_iloc_with_zero_length_extent() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"iden", 0)],
            locations: vec![make_iloc_zero_length(2)],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 2,
                to_ids: vec![1],
            }],
            ..Meta::default()
        };
        let r = &audit_iden_derivations(&meta)[0];
        assert!(!r.has_item_body);
        assert!(r.is_compliant());
    }

    /// HEIF §6.6.2.1: an `'iden'` item with a non-empty extent has a
    /// body, which is forbidden. The audit flags it.
    #[test]
    fn audit_iden_flags_non_empty_item_body() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"iden", 0)],
            locations: vec![make_iloc_with_body(2)],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 2,
                to_ids: vec![1],
            }],
            ..Meta::default()
        };
        let r = &audit_iden_derivations(&meta)[0];
        assert!(r.has_item_body);
        assert!(!r.is_compliant());
        assert!(r.missing().contains(&"no-item-body"));
    }

    /// HEIF §6.6.2.1: `reference_count` of an `'iden'`'s `'dimg'` iref
    /// shall be exactly 1. A zero-input iden fails.
    #[test]
    fn audit_iden_flags_zero_dimg_inputs() {
        let meta = Meta {
            items: vec![make_infe(2, b"iden", 0)],
            irefs: vec![],
            ..Meta::default()
        };
        let r = &audit_iden_derivations(&meta)[0];
        assert_eq!(r.dimg_reference_count, 0);
        assert_eq!(r.dimg_iref_count, 0);
        assert_eq!(r.source_item_id, None);
        assert!(!r.is_compliant());
        let m = r.missing();
        assert!(m.contains(&"dimg-reference-count-eq-1"));
        assert!(m.contains(&"dimg-iref-count-eq-1"));
    }

    /// HEIF §6.6.2.1: `reference_count` of an `'iden'`'s `'dimg'` iref
    /// shall be exactly 1. Two inputs fail. (HEIF §6.6.1 separately
    /// forbids multiple iref entries with the same `from_item_ID`; this
    /// case is one entry with reference_count = 2, so §6.6.1 is OK but
    /// §6.6.2.1 is not.)
    #[test]
    fn audit_iden_flags_two_dimg_inputs_in_single_iref() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"iden", 0),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 3,
                to_ids: vec![1, 2],
            }],
            ..Meta::default()
        };
        let r = &audit_iden_derivations(&meta)[0];
        assert_eq!(r.dimg_reference_count, 2);
        // Single iref entry → §6.6.1 still satisfied even though it
        // carries two to_ids.
        assert_eq!(r.dimg_iref_count, 1);
        assert_eq!(r.source_item_id, None);
        assert!(!r.is_compliant());
        assert!(r.missing().contains(&"dimg-reference-count-eq-1"));
        assert!(!r.missing().contains(&"dimg-iref-count-eq-1"));
    }

    /// HEIF §6.6.1: number of `'dimg'` SingleItemTypeReferenceBoxes with
    /// the same `from_item_ID` shall be at most 1. Two separate iref
    /// entries fail.
    #[test]
    fn audit_iden_flags_multiple_dimg_iref_entries() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"iden", 0),
            ],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 3,
                    to_ids: vec![1],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 3,
                    to_ids: vec![2],
                },
            ],
            ..Meta::default()
        };
        let r = &audit_iden_derivations(&meta)[0];
        assert_eq!(r.dimg_iref_count, 2);
        // `iref_targets` returns the first matching entry only, so the
        // observed reference_count is 1 (from entry 0). §6.6.1 violation
        // is reported via `dimg_iref_count`.
        assert_eq!(r.dimg_reference_count, 1);
        assert!(!r.is_compliant());
        assert!(r.missing().contains(&"dimg-iref-count-eq-1"));
    }

    /// File with no `'iden'` items returns an empty audit list. Other
    /// derived items (`grid`, `tmap`, `sato`, `iovl`) are not picked up.
    #[test]
    fn audit_iden_empty_when_no_iden_items() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"grid", 0),
                make_infe(3, b"tmap", 0),
                make_infe(4, b"sato", 0),
                make_infe(5, b"iovl", 0),
            ],
            ..Meta::default()
        };
        assert!(audit_iden_derivations(&meta).is_empty());
    }

    /// Multiple `'iden'` items are audited in `iinf` declaration order.
    /// One compliant + one with a forbidden item body — the two records
    /// surface independently with the right ids.
    #[test]
    fn audit_iden_reports_each_iden_item_in_iinf_order() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"iden", 0), // compliant
                make_infe(3, b"av01", 0),
                make_infe(4, b"iden", 0), // has body → non-compliant
            ],
            locations: vec![make_iloc_with_body(4)],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![1],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 4,
                    to_ids: vec![3],
                },
            ],
            ..Meta::default()
        };
        let r = audit_iden_derivations(&meta);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].iden_item_id, 2);
        assert!(r[0].is_compliant());
        assert_eq!(r[1].iden_item_id, 4);
        assert!(!r[1].is_compliant());
        assert!(r[1].has_item_body);
    }

    /// A non-`'dimg'` iref of the same shape (e.g. `'cdsc'`) must not
    /// be counted by the audit — only `'dimg'` references contribute to
    /// HEIF §6.6.2.1 / §6.6.1 input enumeration.
    #[test]
    fn audit_iden_ignores_non_dimg_irefs() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"iden", 0),
                make_infe(9, b"Exif", 0),
            ],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![1],
                },
                // `cdsc` from a metadata item — irrelevant to iden input.
                IrefEntry {
                    reference_type: *b"cdsc",
                    from_id: 9,
                    to_ids: vec![2],
                },
            ],
            ..Meta::default()
        };
        let r = &audit_iden_derivations(&meta)[0];
        assert_eq!(r.dimg_iref_count, 1);
        assert_eq!(r.dimg_reference_count, 1);
        assert!(r.is_compliant());
    }

    // -------------------------------------------------------------------
    // AV1 Alpha bit-depth match audit (av1-avif v1.2.0 §4.1)
    // -------------------------------------------------------------------

    use crate::meta::{AuxC, ItemPropertyAssociation as Ipa, PropertyAssociation as Pa};

    /// Build an `av1C` payload whose first three bytes carry the
    /// `(high_bitdepth, twelve_bit)` flag pair for the given bit depth.
    /// Bit 7 is the `marker` (always 1), bits 6..0 of byte 0 are
    /// `version` (always 1) — but the audit only consults byte 2, so
    /// we just zero the first two bytes here.
    fn av1c_with_bit_depth(bit_depth: u8) -> Vec<u8> {
        let (high, twelve) = match bit_depth {
            8 => (0u8, 0u8),
            10 => (1, 0),
            12 => (1, 1),
            _ => panic!("test helper supports 8/10/12 only"),
        };
        // byte 0: marker(1) + version(7) — recreated nominally as 0x81.
        // byte 1: profile/seq_level — irrelevant to bit depth.
        // byte 2: high_bitdepth(1)<<6 | twelve_bit(1)<<5 | rest.
        let b2 = (high << 6) | (twelve << 5);
        vec![0x81, 0x00, b2]
    }

    fn ipa(item_id: u32, indices: &[u16]) -> Ipa {
        Ipa {
            item_id,
            entries: indices
                .iter()
                .map(|i| Pa {
                    index: *i,
                    essential: false,
                })
                .collect(),
        }
    }

    fn make_alpha_auxc() -> AuxC {
        AuxC {
            aux_type: crate::alpha::ALPHA_URN_PREFIX.to_string(),
            aux_subtype: Vec::new(),
        }
    }

    fn make_depth_auxc() -> AuxC {
        AuxC {
            aux_type: crate::meta::AUX_URN_DEPTH_MPEG.to_string(),
            aux_subtype: Vec::new(),
        }
    }

    /// `decode_av1c_bit_depth` covers the three legal AV1 depths.
    #[test]
    fn decode_av1c_bit_depth_recognises_8_10_12() {
        assert_eq!(decode_av1c_bit_depth(&av1c_with_bit_depth(8)), Some(8));
        assert_eq!(decode_av1c_bit_depth(&av1c_with_bit_depth(10)), Some(10));
        assert_eq!(decode_av1c_bit_depth(&av1c_with_bit_depth(12)), Some(12));
    }

    /// Truncated `av1C` (< 3 bytes) is rejected without panicking.
    #[test]
    fn decode_av1c_bit_depth_handles_truncation() {
        assert_eq!(decode_av1c_bit_depth(&[]), None);
        assert_eq!(decode_av1c_bit_depth(&[0x81]), None);
        assert_eq!(decode_av1c_bit_depth(&[0x81, 0x00]), None);
    }

    /// Happy path: 8-bit master + 8-bit alpha → compliant.
    #[test]
    fn audit_alpha_bit_depth_match_compliant() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0), // master
                make_infe(2, b"av01", 0), // alpha
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(8)), // index 0 — master av1C
                Property::Av1C(av1c_with_bit_depth(8)), // index 1 — alpha av1C
                Property::AuxC(make_alpha_auxc()),      // index 2
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1, 2])],
            ..Meta::default()
        };
        let r = audit_alpha_bit_depth(&meta);
        assert_eq!(r.len(), 1);
        let rec = &r[0];
        assert_eq!(rec.alpha_item_id, 2);
        assert_eq!(rec.master_item_id, 1);
        assert_eq!(rec.alpha_bit_depth, Some(8));
        assert_eq!(rec.master_bit_depth, Some(8));
        assert!(!rec.alpha_missing_av1c);
        assert!(!rec.master_missing_av1c);
        assert!(rec.is_compliant());
        assert!(rec.missing().is_empty());
    }

    /// 10-bit master + 8-bit alpha → §4.1 mismatch flagged.
    #[test]
    fn audit_alpha_bit_depth_mismatch_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(10)), // master 10-bit
                Property::Av1C(av1c_with_bit_depth(8)),  // alpha 8-bit
                Property::AuxC(make_alpha_auxc()),
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1, 2])],
            ..Meta::default()
        };
        let rec = &audit_alpha_bit_depth(&meta)[0];
        assert_eq!(rec.alpha_bit_depth, Some(8));
        assert_eq!(rec.master_bit_depth, Some(10));
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["alpha-master-bit-depth-mismatch"]);
    }

    /// 12-bit on both sides also matches.
    #[test]
    fn audit_alpha_bit_depth_12_bit_compliant() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(12)),
                Property::Av1C(av1c_with_bit_depth(12)),
                Property::AuxC(make_alpha_auxc()),
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1, 2])],
            ..Meta::default()
        };
        let rec = &audit_alpha_bit_depth(&meta)[0];
        assert!(rec.is_compliant());
    }

    /// Alpha item missing `av1C` surfaces both the missing-av1c flag
    /// and the corresponding `missing()` entry. The §2.1 violation
    /// (every AV1 Image Item shall carry `av1C`) is reported alongside
    /// the §4.1 check.
    #[test]
    fn audit_alpha_bit_depth_alpha_missing_av1c() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(10)),
                Property::AuxC(make_alpha_auxc()),
            ],
            // Alpha item 2 has only the auxC, no av1C.
            associations: vec![ipa(1, &[0]), ipa(2, &[1])],
            ..Meta::default()
        };
        let rec = &audit_alpha_bit_depth(&meta)[0];
        assert!(rec.alpha_missing_av1c);
        assert_eq!(rec.alpha_bit_depth, None);
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["alpha-item-missing-av1C"]);
    }

    /// Master item missing `av1C` surfaces the corresponding flag +
    /// `missing()` entry.
    #[test]
    fn audit_alpha_bit_depth_master_missing_av1c() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(10)),
                Property::AuxC(make_alpha_auxc()),
            ],
            // Master item 1 has no av1C; alpha carries both.
            associations: vec![ipa(2, &[0, 1])],
            ..Meta::default()
        };
        let rec = &audit_alpha_bit_depth(&meta)[0];
        assert!(rec.master_missing_av1c);
        assert_eq!(rec.master_bit_depth, None);
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["master-item-missing-av1C"]);
    }

    /// Truncated `av1C` payload on the alpha side surfaces as
    /// `alpha-item-av1C-truncated` (distinct from the missing case).
    #[test]
    fn audit_alpha_bit_depth_truncated_av1c() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(10)),
                // Alpha av1C is truncated to 2 bytes — present-but-unusable.
                Property::Av1C(vec![0x81, 0x00]),
                Property::AuxC(make_alpha_auxc()),
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1, 2])],
            ..Meta::default()
        };
        let rec = &audit_alpha_bit_depth(&meta)[0];
        assert!(!rec.alpha_missing_av1c);
        assert_eq!(rec.alpha_bit_depth, None);
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["alpha-item-av1C-truncated"]);
    }

    /// Non-alpha auxiliaries (depth maps, gain maps) are out of §4.1's
    /// scope and must not surface in the audit. A depth-map auxC is the
    /// canonical confound — the same `auxl` iref + a non-alpha URN
    /// means the audit walks past.
    #[test]
    fn audit_alpha_bit_depth_skips_depth_map_auxiliary() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 2,
                to_ids: vec![1],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(10)),
                Property::Av1C(av1c_with_bit_depth(8)),
                Property::AuxC(make_depth_auxc()), // depth, not alpha
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1, 2])],
            ..Meta::default()
        };
        assert!(audit_alpha_bit_depth(&meta).is_empty());
    }

    /// A single alpha item declared against multiple masters in one
    /// `auxl` `to_ids` list emits one record per master pairing, in
    /// `to_ids` order. The §4.1 `shall` applies per pairing.
    #[test]
    fn audit_alpha_bit_depth_one_record_per_master() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0), // master A, 8-bit
                make_infe(2, b"av01", 0), // master B, 10-bit
                make_infe(3, b"av01", 0), // alpha, 10-bit
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"auxl",
                from_id: 3,
                to_ids: vec![1, 2],
            }],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(8)),  // master A
                Property::Av1C(av1c_with_bit_depth(10)), // master B
                Property::Av1C(av1c_with_bit_depth(10)), // alpha
                Property::AuxC(make_alpha_auxc()),
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1]), ipa(3, &[2, 3])],
            ..Meta::default()
        };
        let r = audit_alpha_bit_depth(&meta);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].master_item_id, 1);
        assert!(!r[0].is_compliant()); // 10 vs 8 → mismatch
        assert_eq!(r[1].master_item_id, 2);
        assert!(r[1].is_compliant()); // 10 vs 10 → ok
    }

    /// Files with no alpha auxiliaries emit no records.
    #[test]
    fn audit_alpha_bit_depth_empty_when_no_alpha() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            irefs: Vec::new(),
            properties: vec![Property::Av1C(av1c_with_bit_depth(10))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        assert!(audit_alpha_bit_depth(&meta).is_empty());
    }

    /// Multiple alpha auxiliaries (one per master in a multi-image
    /// collection) emit one record per `(alpha, master)` pair in iref
    /// declaration order.
    #[test]
    fn audit_alpha_bit_depth_multiple_alpha_items() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"av01", 0),
                make_infe(2, b"av01", 0),
                make_infe(3, b"av01", 0),
                make_infe(4, b"av01", 0),
            ],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"auxl",
                    from_id: 3,
                    to_ids: vec![1],
                },
                IrefEntry {
                    reference_type: *b"auxl",
                    from_id: 4,
                    to_ids: vec![2],
                },
            ],
            properties: vec![
                Property::Av1C(av1c_with_bit_depth(8)),
                Property::Av1C(av1c_with_bit_depth(10)),
                Property::Av1C(av1c_with_bit_depth(8)),
                Property::Av1C(av1c_with_bit_depth(10)),
                Property::AuxC(make_alpha_auxc()),
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1]), ipa(3, &[2, 4]), ipa(4, &[3, 4])],
            ..Meta::default()
        };
        let r = audit_alpha_bit_depth(&meta);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].alpha_item_id, 3);
        assert_eq!(r[0].master_item_id, 1);
        assert!(r[0].is_compliant());
        assert_eq!(r[1].alpha_item_id, 4);
        assert_eq!(r[1].master_item_id, 2);
        assert!(r[1].is_compliant());
    }

    // -------------------------------------------------------------------
    // §2.1 Sequence Header OBU count audit
    // -------------------------------------------------------------------

    /// Build one OBU framed per AV1 §5.3.1/§5.3.2 with `obu_has_size_field
    /// == 1` and no extension header. `obu_type` goes in bits 6..3.
    /// `payload` is the OBU body bytes (their content doesn't matter for
    /// the audit — only the type and the framing are inspected).
    fn obu_with_size(obu_type: u8, payload: &[u8]) -> Vec<u8> {
        // header byte: 0|type(4)|ext(0)|has_size(1)|reserved(0)
        let hdr = ((obu_type & 0x0f) << 3) | 0b10;
        let mut out = vec![hdr];
        // leb128 encode payload length.
        let mut v = payload.len() as u32;
        loop {
            let mut b = (v & 0x7f) as u8;
            v >>= 7;
            if v != 0 {
                b |= 0x80;
                out.push(b);
            } else {
                out.push(b);
                break;
            }
        }
        out.extend_from_slice(payload);
        out
    }

    /// Build a one-byte OBU with `obu_has_size_field == 0` — illegal in
    /// AVIF Image Item Data per av1-avif §2.1 + AV1 §5.3.1's container
    /// chaining requirement.
    fn obu_no_size(obu_type: u8) -> Vec<u8> {
        // header byte: 0|type(4)|ext(0)|has_size(0)|reserved(0)
        vec![(obu_type & 0x0f) << 3]
    }

    /// Build a synthetic file whose iloc resolves item `1`'s payload to
    /// the given byte slice. Returns `(file_bytes, meta)`. The file
    /// bytes are just a flat buffer with the payload at offset 0 (so
    /// `iloc.base_offset = 0`, `extent.offset = 0`, `extent.length =
    /// payload.len()`).
    fn synth_av01_item(payload: &[u8]) -> (Vec<u8>, Meta) {
        use crate::meta::{IlocExtent, ItemLocation};
        let file = payload.to_vec();
        let length = file.len() as u64;
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            locations: vec![ItemLocation {
                id: 1,
                construction_method: 0,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length,
                    extent_index: 0,
                }],
            }],
            ..Meta::default()
        };
        (file, meta)
    }

    /// leb128 round-trip on small + large values (within 32-bit range).
    #[test]
    fn read_leb128_decodes_single_and_multi_byte_values() {
        // single-byte: 0x05 → 5 in 1 byte
        assert_eq!(read_leb128(&[0x05, 0xff]), Ok((5, 1)));
        // two-byte: 0x80 0x01 → 128 in 2 bytes
        assert_eq!(read_leb128(&[0x80, 0x01, 0xff]), Ok((128, 2)));
        // five-byte: largest u32: 0xff ff ff ff 0f
        assert_eq!(
            read_leb128(&[0xff, 0xff, 0xff, 0xff, 0x0f]),
            Ok((0xffff_ffff, 5))
        );
    }

    /// Truncation (continuation bit set on last byte) errors out.
    #[test]
    fn read_leb128_rejects_truncated_continuation() {
        assert!(read_leb128(&[0x80]).is_err());
        assert!(read_leb128(&[0x80, 0x80, 0x80]).is_err());
    }

    /// A leb128 sequence longer than 8 bytes errors out (the §4.10.5
    /// loop bound).
    #[test]
    fn read_leb128_rejects_overlong_sequence() {
        assert!(read_leb128(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]).is_err());
    }

    /// Happy path: one Sequence Header + one Temporal Delimiter + one
    /// Frame OBU → `sequence_header_count == 1`, compliant.
    #[test]
    fn audit_sequence_header_obu_single_count_compliant() {
        let mut stream = Vec::new();
        stream.extend(obu_with_size(2, &[])); // OBU_TEMPORAL_DELIMITER
        stream.extend(obu_with_size(1, &[0x00, 0x01, 0x02])); // OBU_SEQUENCE_HEADER
        stream.extend(obu_with_size(6, &[0xab; 7])); // OBU_FRAME
        let (file, meta) = synth_av01_item(&stream);
        let r = audit_sequence_header_obu(&meta, &file);
        assert_eq!(r.len(), 1);
        let rec = &r[0];
        assert_eq!(rec.item_id, 1);
        assert_eq!(rec.sequence_header_count, 1);
        assert_eq!(rec.total_obu_count, 3);
        assert!(rec.is_compliant());
        assert!(rec.missing().is_empty());
    }

    /// Two Sequence Headers in one item → §2.1 violation, flagged as
    /// `av01-item-multiple-sequence-header-obus`.
    #[test]
    fn audit_sequence_header_obu_two_count_flagged() {
        let mut stream = Vec::new();
        stream.extend(obu_with_size(1, &[0x00, 0x01])); // SH #1
        stream.extend(obu_with_size(1, &[0x00, 0x01])); // SH #2
        let (file, meta) = synth_av01_item(&stream);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert_eq!(rec.sequence_header_count, 2);
        assert!(!rec.is_compliant());
        assert_eq!(
            rec.missing(),
            vec!["av01-item-multiple-sequence-header-obus"]
        );
    }

    /// Zero Sequence Headers → §2.1 violation, flagged as
    /// `av01-item-missing-sequence-header-obu`.
    #[test]
    fn audit_sequence_header_obu_zero_count_flagged() {
        let mut stream = Vec::new();
        stream.extend(obu_with_size(2, &[])); // TD only
        stream.extend(obu_with_size(6, &[0xab; 4])); // FRAME
        let (file, meta) = synth_av01_item(&stream);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert_eq!(rec.sequence_header_count, 0);
        assert_eq!(rec.total_obu_count, 2);
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["av01-item-missing-sequence-header-obu"]);
    }

    /// `obu_has_size_field == 0` in a chained stream → walker stops and
    /// reports `has_size_field_zero`. Per AV1 §5.3.1, an OBU without a
    /// size field cannot be chained with subsequent OBUs.
    #[test]
    fn audit_sequence_header_obu_size_field_zero_flagged() {
        let mut stream = Vec::new();
        stream.extend(obu_no_size(1)); // SH with no size
                                       // Following bytes can't be framed — anything after.
        stream.extend([0xff, 0xff, 0xff]);
        let (file, meta) = synth_av01_item(&stream);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert!(rec.has_size_field_zero);
        assert!(!rec.is_compliant());
        // The SH header byte itself was decoded before we noticed the
        // missing size — count surfaces but compliance still false.
        assert_eq!(rec.sequence_header_count, 1);
        assert!(rec.missing().contains(&"av01-item-obu-has-size-field-zero"));
    }

    /// A declared `obu_size` that runs past the item payload → walker
    /// reports `truncated_obu`.
    #[test]
    fn audit_sequence_header_obu_truncated_payload_flagged() {
        // Header for SH, claim 100-byte payload, but only give it 3.
        let mut stream = vec![(1u8 << 3) | 0b10]; // SH + has_size
        stream.push(100); // leb128(100), single byte
        stream.extend([0xde, 0xad, 0xbe]); // only 3 bytes of payload
        let (file, meta) = synth_av01_item(&stream);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert!(rec.truncated_obu);
        assert!(!rec.is_compliant());
        assert!(rec.missing().contains(&"av01-item-obu-stream-truncated"));
    }

    /// Truncated leb128 mid-OBU (continuation bit set on last byte) →
    /// `truncated_obu` flagged; no OBUs walked past the bad leb.
    #[test]
    fn audit_sequence_header_obu_truncated_leb128_flagged() {
        // Header byte SH + has_size, then a single byte 0x80 (continuation
        // bit set, no follow-on) — leb128 walker errors → truncated.
        let stream = vec![(1u8 << 3) | 0b10, 0x80];
        let (file, meta) = synth_av01_item(&stream);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert!(rec.truncated_obu);
        assert!(!rec.is_compliant());
        // Header byte was readable, but the leb128 framing failure
        // bailed before the type-credit step — SH counter does not
        // fire because we cannot confirm we successfully framed an OBU.
        assert_eq!(rec.sequence_header_count, 0);
        assert_eq!(rec.total_obu_count, 0);
    }

    /// `iinf` lists an av01 item but no `iloc` resolves it → missing_iloc.
    #[test]
    fn audit_sequence_header_obu_missing_iloc_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            // no locations
            ..Meta::default()
        };
        let r = audit_sequence_header_obu(&meta, &[]);
        assert_eq!(r.len(), 1);
        let rec = &r[0];
        assert!(rec.missing_iloc);
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["av01-item-missing-iloc"]);
    }

    /// Non-av01 items (e.g. `Exif`, `iden`, `grid`) are ignored.
    #[test]
    fn audit_sequence_header_obu_ignores_non_av01_items() {
        let meta = Meta {
            items: vec![
                make_infe(1, b"Exif", 0),
                make_infe(2, b"iden", 0),
                make_infe(3, b"grid", 0),
            ],
            ..Meta::default()
        };
        assert!(audit_sequence_header_obu(&meta, &[]).is_empty());
    }

    /// An `obu_extension_flag == 1` OBU correctly skips the extension
    /// header byte before reading `obu_size`.
    #[test]
    fn audit_sequence_header_obu_handles_extension_header() {
        // header byte: SH(1)|ext(1)|has_size(1)|reserved(0)
        let hdr = (1u8 << 3) | 0b110;
        let mut stream = vec![hdr];
        stream.push(0x00); // extension header byte (temporal_id=0, spatial_id=0)
        stream.push(2); // leb128(2)
        stream.extend([0x11, 0x22]); // payload
        let (file, meta) = synth_av01_item(&stream);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert_eq!(rec.sequence_header_count, 1);
        assert_eq!(rec.total_obu_count, 1);
        assert!(rec.is_compliant());
    }

    /// Empty `av01` payload: 0 OBUs walked, 0 SH OBUs → flagged as
    /// missing SH.
    #[test]
    fn audit_sequence_header_obu_empty_payload_flagged_missing() {
        let (file, meta) = synth_av01_item(&[]);
        let rec = &audit_sequence_header_obu(&meta, &file)[0];
        assert_eq!(rec.sequence_header_count, 0);
        assert_eq!(rec.total_obu_count, 0);
        assert!(!rec.missing_iloc);
        assert!(!rec.truncated_obu);
        assert!(!rec.is_compliant());
        assert_eq!(rec.missing(), vec!["av01-item-missing-sequence-header-obu"]);
    }

    /// Multiple AV1 Image Items in the same file each get their own
    /// audit record, in `item_ids_of_type` (declaration) order.
    #[test]
    fn audit_sequence_header_obu_one_record_per_av01_item() {
        use crate::meta::{IlocExtent, ItemLocation};
        // Build two items back-to-back in the file: item 1 compliant
        // (one SH), item 2 non-compliant (zero SH).
        let mut s1 = Vec::new();
        s1.extend(obu_with_size(2, &[])); // TD
        s1.extend(obu_with_size(1, &[0x00; 3])); // SH
        let mut s2 = Vec::new();
        s2.extend(obu_with_size(2, &[])); // TD only — no SH
        let mut file = Vec::new();
        let off1 = file.len() as u64;
        file.extend(&s1);
        let off2 = file.len() as u64;
        file.extend(&s2);
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            locations: vec![
                ItemLocation {
                    id: 1,
                    construction_method: 0,
                    data_reference_index: 0,
                    base_offset: 0,
                    extents: vec![IlocExtent {
                        offset: off1,
                        length: s1.len() as u64,
                        extent_index: 0,
                    }],
                },
                ItemLocation {
                    id: 2,
                    construction_method: 0,
                    data_reference_index: 0,
                    base_offset: 0,
                    extents: vec![IlocExtent {
                        offset: off2,
                        length: s2.len() as u64,
                        extent_index: 0,
                    }],
                },
            ],
            ..Meta::default()
        };
        let r = audit_sequence_header_obu(&meta, &file);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].item_id, 1);
        assert!(r[0].is_compliant());
        assert_eq!(r[1].item_id, 2);
        assert!(!r[1].is_compliant());
        assert_eq!(r[1].sequence_header_count, 0);
    }

    // -- ISO 21496-1 Annex C.2 gain map metadata --------------------------

    /// Push a `numerator(int32) / denominator(uint32)` rational pair onto
    /// a big-endian payload buffer.
    fn push_rational(buf: &mut Vec<u8>, num: i32, den: u32) {
        buf.extend_from_slice(&(num as u32).to_be_bytes());
        buf.extend_from_slice(&den.to_be_bytes());
    }

    /// Build a single-channel (`is_multichannel == 0`) gain map metadata
    /// payload with deterministic, distinguishable rational values.
    fn build_singlechannel_gain_map() -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&0u16.to_be_bytes()); // minimum_version
        buf.extend_from_slice(&0u16.to_be_bytes()); // writer_version
        buf.push(0x40); // is_multichannel=0, use_base_colour_space=1
        push_rational(&mut buf, 5, 2); // base_hdr_headroom
        push_rational(&mut buf, 8, 1); // alternate_hdr_headroom
                                       // one GainMapChannel
        push_rational(&mut buf, -1, 4); // gain_map_min
        push_rational(&mut buf, 3, 4); // gain_map_max
        push_rational(&mut buf, 1, 1); // gamma
        push_rational(&mut buf, -2, 16); // base_offset
        push_rational(&mut buf, 7, 16); // alternate_offset
        buf
    }

    /// Single-channel payload parses with the right flags, headroom, and
    /// one channel record; the rationals round-trip exactly.
    #[test]
    fn gain_map_metadata_parses_single_channel() {
        let buf = build_singlechannel_gain_map();
        let m = GainMapMetadata::parse(&buf).unwrap();
        assert_eq!(m.minimum_version, 0);
        assert_eq!(m.writer_version, 0);
        assert!(!m.is_multichannel);
        assert!(m.use_base_colour_space);
        assert_eq!(m.channel_count(), 1);
        assert_eq!(
            m.base_hdr_headroom,
            GainMapRational {
                numerator: 5,
                denominator: 2
            }
        );
        assert_eq!(
            m.alternate_hdr_headroom,
            GainMapRational {
                numerator: 8,
                denominator: 1
            }
        );
        let c = m.channels[0];
        assert_eq!(
            c.gain_map_min,
            GainMapRational {
                numerator: -1,
                denominator: 4
            }
        );
        assert_eq!(c.gain_map_max.as_f64(), 0.75);
        assert_eq!(
            c.gamma,
            GainMapRational {
                numerator: 1,
                denominator: 1
            }
        );
        assert_eq!(c.base_offset.as_f64(), -0.125);
        assert_eq!(c.alternate_offset.numerator, 7);
    }

    /// `is_multichannel == 1` yields three channel records (R, G, B
    /// order) read from 3 × 40 trailing bytes.
    #[test]
    fn gain_map_metadata_parses_three_channels_when_multichannel() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&0u16.to_be_bytes()); // minimum_version
        buf.extend_from_slice(&1u16.to_be_bytes()); // writer_version
        buf.push(0x80); // is_multichannel=1, use_base_colour_space=0
        push_rational(&mut buf, 1, 1); // base_hdr_headroom
                                       // alternate_hdr_headroom must differ from base_hdr_headroom
                                       // (§5.2.7); 4/1 ≠ 1/1.
        push_rational(&mut buf, 4, 1); // alternate_hdr_headroom
        for ch in 0..3i32 {
            push_rational(&mut buf, ch, 1); // gain_map_min (R=0,G=1,B=2)
            push_rational(&mut buf, 10, 1); // gain_map_max
            push_rational(&mut buf, 2, 1); // gamma
            push_rational(&mut buf, 0, 1); // base_offset
            push_rational(&mut buf, 0, 1); // alternate_offset
        }
        let m = GainMapMetadata::parse(&buf).unwrap();
        assert!(m.is_multichannel);
        assert!(!m.use_base_colour_space);
        assert_eq!(m.channel_count(), 3);
        assert_eq!(m.channels[0].gain_map_min.numerator, 0);
        assert_eq!(m.channels[1].gain_map_min.numerator, 1);
        assert_eq!(m.channels[2].gain_map_min.numerator, 2);
    }

    /// Annex C.2.1: trailing padding / future-optional metadata after the
    /// recognised fields is ignored, not an error.
    #[test]
    fn gain_map_metadata_ignores_trailing_bytes() {
        let mut buf = build_singlechannel_gain_map();
        buf.extend_from_slice(&[0xAA; 32]); // padding + hypothetical v2 fields
        let m = GainMapMetadata::parse(&buf).unwrap();
        assert_eq!(m.channel_count(), 1);
    }

    /// Annex C.2.3: a `minimum_version` the reader doesn't understand is
    /// an `Unsupported` (display the base image), not malformed data.
    #[test]
    fn gain_map_metadata_unknown_min_version_is_unsupported() {
        let mut buf = build_singlechannel_gain_map();
        buf[0] = 0;
        buf[1] = 1; // minimum_version = 1
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::Unsupported(_)));
    }

    /// A zero rational denominator is rejected (C.2.3 "shall not be 0").
    #[test]
    fn gain_map_metadata_rejects_zero_denominator() {
        let mut buf = build_singlechannel_gain_map();
        // base_hdr_headroom denominator sits at offset 5+4 = 9.
        buf[9] = 0;
        buf[10] = 0;
        buf[11] = 0;
        buf[12] = 0;
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    /// `gamma_numerator == 0` is rejected (C.2.3 "gamma_numerator shall
    /// not be 0"), distinct from the denominator constraint.
    #[test]
    fn gain_map_metadata_rejects_zero_gamma_numerator() {
        let mut buf = build_singlechannel_gain_map();
        // Channel record starts at offset 21; gamma is field 3 →
        // 21 + 16 = 37, the gamma numerator (4 bytes).
        for b in buf.iter_mut().skip(37).take(4) {
            *b = 0;
        }
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    /// A payload truncated before all channel bytes arrive is rejected.
    #[test]
    fn gain_map_metadata_rejects_truncated_channel() {
        let mut buf = build_singlechannel_gain_map();
        buf.truncate(buf.len() - 1); // drop last byte of the channel
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    /// §5.2.5.3: per-component `max(G)` "shall be greater than or
    /// equal to the `min(G)` value". The default fixture has min=-1/4
    /// (-0.25) and max=3/4 (0.75), so swapping the two numerators
    /// flips the predicate and the parse must reject the payload.
    #[test]
    fn gain_map_metadata_rejects_max_below_min() {
        let mut buf = build_singlechannel_gain_map();
        // Channel record starts at offset 21; the gain_map_min and
        // gain_map_max sint32 numerators sit at +0 and +8 within it.
        // Swap them so max < min.
        let orig_min = i32::from_be_bytes(buf[21..25].try_into().unwrap());
        let orig_max = i32::from_be_bytes(buf[29..33].try_into().unwrap());
        buf[21..25].copy_from_slice(&orig_max.to_be_bytes());
        buf[29..33].copy_from_slice(&orig_min.to_be_bytes());
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    /// §5.2.5.3 boundary: `max(G) == min(G)` is permitted ("greater
    /// than or equal to"). Build a channel where both equal 0/1 and
    /// confirm the parse succeeds.
    #[test]
    fn gain_map_metadata_accepts_max_equal_to_min() {
        let mut buf = build_singlechannel_gain_map();
        // Force gain_map_min and gain_map_max to the same rational
        // (0/1, the simplest legal value).
        buf[21..25].copy_from_slice(&0i32.to_be_bytes()); // min numerator
        buf[25..29].copy_from_slice(&1u32.to_be_bytes()); // min denominator
        buf[29..33].copy_from_slice(&0i32.to_be_bytes()); // max numerator
        buf[33..37].copy_from_slice(&1u32.to_be_bytes()); // max denominator
        let m = GainMapMetadata::parse(&buf).expect("max==min is permitted");
        assert_eq!(m.channels[0].gain_map_min.numerator, 0);
        assert_eq!(m.channels[0].gain_map_max.numerator, 0);
    }

    /// §5.2.7: `alternate_hdr_headroom` "shall not be equal to" the
    /// `base_hdr_headroom`. Overwrite the alternate headroom with the
    /// base headroom's exact bytes and confirm the parse rejects it.
    #[test]
    fn gain_map_metadata_rejects_equal_hdr_headrooms() {
        let mut buf = build_singlechannel_gain_map();
        // base_hdr_headroom sits at offset 5..13; alternate at 13..21.
        let base = buf[5..13].to_vec();
        buf[13..21].copy_from_slice(&base);
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    /// §5.2.7 uses rational *value* equality, not byte equality:
    /// 1/1 and 2/2 are the same value and so must trip the check
    /// even though the encoded bytes differ.
    #[test]
    fn gain_map_metadata_rejects_value_equal_hdr_headrooms() {
        let mut buf = build_singlechannel_gain_map();
        // base = 1/1, alternate = 2/2 → both = 1.0, must reject.
        buf[5..9].copy_from_slice(&1u32.to_be_bytes()); // base numerator
        buf[9..13].copy_from_slice(&1u32.to_be_bytes()); // base denominator
        buf[13..17].copy_from_slice(&2u32.to_be_bytes()); // alt numerator
        buf[17..21].copy_from_slice(&2u32.to_be_bytes()); // alt denominator
        let err = GainMapMetadata::parse(&buf).unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    // -- ISO 21496-1 §6 gain map application ------------------------------

    /// Helper to compare two floats within a tight absolute tolerance.
    fn approx(a: f64, b: f64) {
        assert!((a - b).abs() < 1e-12, "expected {b}, got {a}");
    }

    /// §6.3 Formula (3): `W == 0` at the baseline headroom, `W == 1` at
    /// the alternate headroom (positive span), and a linear interpolation
    /// in between. The single-channel fixture has H_baseline = 2.5 and
    /// H_alternate = 8.0 (span 5.5).
    #[test]
    fn weight_factor_spans_baseline_to_alternate() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        approx(m.weight_factor(2.5), 0.0); // at H_baseline → not applied
        approx(m.weight_factor(8.0), 1.0); // at H_alternate → fully applied
        approx(m.weight_factor(5.25), 0.5); // midpoint → half
                                            // Targets outside [H_baseline, H_alternate] clamp into [0, 1].
        approx(m.weight_factor(-100.0), 0.0);
        approx(m.weight_factor(100.0), 1.0);
    }

    /// §6.3 Formula (3) with a negative span (H_alternate < H_baseline):
    /// `sign(H_alternate − H_baseline)` flips W negative, and full
    /// application yields `W == -1` (§6.3 NOTE 4).
    #[test]
    fn weight_factor_is_negative_when_alternate_below_baseline() {
        // base_hdr = 5/1 = 5.0, alternate_hdr = 1/1 = 1.0 → span = -4.
        let mut buf = build_singlechannel_gain_map();
        buf[5..9].copy_from_slice(&5u32.to_be_bytes()); // base num
        buf[9..13].copy_from_slice(&1u32.to_be_bytes()); // base den
        buf[13..17].copy_from_slice(&1u32.to_be_bytes()); // alt num
        buf[17..21].copy_from_slice(&1u32.to_be_bytes()); // alt den
        let m = GainMapMetadata::parse(&buf).unwrap();
        approx(m.weight_factor(5.0), 0.0); // at H_baseline
        approx(m.weight_factor(1.0), -1.0); // at H_alternate → W = -1
        approx(m.weight_factor(3.0), -0.5); // midpoint
    }

    /// §6.2.1 Formula (1) inverse-normalization with γ = 1: a normalized
    /// sample of 1.0 maps to max(G), 0.0 to min(G), 0.5 to the midpoint.
    /// The fixture channel has min(G) = −0.25, max(G) = 0.75.
    #[test]
    fn unnormalize_log2_gain_inverts_normalization() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        let ch = m.channels[0];
        approx(ch.unnormalize_log2_gain(1.0), 0.75); // → max(G)
        approx(ch.unnormalize_log2_gain(0.0), -0.25); // → min(G)
        approx(ch.unnormalize_log2_gain(0.5), 0.25); // span 1.0 × 0.5 − 0.25
                                                     // Out-of-range stored sample saturates rather than producing NaN.
        approx(ch.unnormalize_log2_gain(2.0), 0.75);
        approx(ch.unnormalize_log2_gain(-1.0), -0.25);
    }

    /// §6.2.1 Formula (1) with γ ≠ 1: the gamma inverse `x^(1/γ)` is
    /// applied before the [min, max] range scaling. With γ = 2 and a
    /// normalized sample of 0.25, `0.25^(1/2) = 0.5`, so the result is
    /// the same midpoint as a γ = 1 sample of 0.5.
    #[test]
    fn unnormalize_log2_gain_applies_gamma_inverse() {
        let mut buf = build_singlechannel_gain_map();
        // channel gamma lives at offset 21 + 16 = 37 (num) / 41 (den).
        buf[37..41].copy_from_slice(&2u32.to_be_bytes()); // gamma num = 2
        buf[41..45].copy_from_slice(&1u32.to_be_bytes()); // gamma den = 1
        let m = GainMapMetadata::parse(&buf).unwrap();
        let ch = m.channels[0];
        approx(ch.unnormalize_log2_gain(0.25), 0.25);
        approx(ch.unnormalize_log2_gain(1.0), 0.75); // 1^anything = 1 → max
        approx(ch.unnormalize_log2_gain(0.0), -0.25); // 0 → min
    }

    /// §6.3 Formula (2) end to end: at the baseline headroom W = 0 so
    /// `2^(W·G) = 1` and the alternate reduces to
    /// `(Baseline + k_baseline) − k_alternate`. Fixture offsets are
    /// k_baseline = −0.125, k_alternate = 0.4375.
    #[test]
    fn apply_component_at_baseline_headroom_is_offset_only() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        // Baseline 1.0, target == H_baseline (2.5) → W = 0.
        let out = m.apply_component(1.0, 1.0, 2.5, 0).unwrap();
        approx(out, 1.0 + (-0.125) - 0.4375);
    }

    /// §6.3 Formula (2) at full application (target == H_alternate, W = 1)
    /// with a maximal gain sample (G = max(G) = 0.75): the multiplicative
    /// term is `2^0.75`.
    #[test]
    fn apply_component_at_full_application() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        // baseline 1.0, normalized 1.0 → G = 0.75, target 8.0 → W = 1.
        let out = m.apply_component(1.0, 1.0, 8.0, 0).unwrap();
        let expected = (1.0 + (-0.125)) * 0.75f64.exp2() - 0.4375;
        approx(out, expected);
    }

    /// §5.2.5.1 broadcast: a single-channel metadata record applies to
    /// all three RGB colour components, so each component uses the same
    /// channel values, and `apply_rgb` matches `apply_component` per slot.
    #[test]
    fn apply_rgb_broadcasts_single_channel_metadata() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        let baseline = [0.5, 1.0, 0.25];
        let gain = [0.0, 0.5, 1.0];
        let rgb = m.apply_rgb(baseline, gain, 8.0).unwrap();
        for c in 0..3 {
            let want = m.apply_component(baseline[c], gain[c], 8.0, c).unwrap();
            approx(rgb[c], want);
        }
    }

    /// §5.2.5.1 per-component metadata: a three-channel record uses a
    /// distinct value per colour component. The R/G/B channels carry
    /// different min(G) values, so `channel_for` must index them rather
    /// than broadcast channel 0.
    #[test]
    fn apply_component_indexes_per_component_metadata() {
        // Three-channel payload: R/G/B min(G) = 0/0.5/1 (×1 den), max = 2,
        // gamma = 1, offsets 0; base_hdr = 1, alt_hdr = 2.
        let mut buf = Vec::new();
        buf.extend_from_slice(&0u16.to_be_bytes()); // minimum_version
        buf.extend_from_slice(&0u16.to_be_bytes()); // writer_version
        buf.push(0x80); // is_multichannel = 1
        push_rational(&mut buf, 1, 1); // base_hdr_headroom = 1.0
        push_rational(&mut buf, 2, 1); // alternate_hdr_headroom = 2.0
        let mins = [(0i32, 1u32), (1, 2), (1, 1)]; // 0.0, 0.5, 1.0
        for (mn, md) in mins {
            push_rational(&mut buf, mn, md); // gain_map_min
            push_rational(&mut buf, 2, 1); // gain_map_max = 2.0
            push_rational(&mut buf, 1, 1); // gamma = 1
            push_rational(&mut buf, 0, 1); // base_offset = 0
            push_rational(&mut buf, 0, 1); // alternate_offset = 0
        }
        let m = GainMapMetadata::parse(&buf).unwrap();
        assert_eq!(m.channel_count(), 3);
        // normalized = 0 selects each component's min(G); with W = 1 at
        // target 2.0 the result is baseline · 2^min(G).
        let baseline = 1.0;
        approx(
            m.apply_component(baseline, 0.0, 2.0, 0).unwrap(),
            baseline * 0.0f64.exp2(),
        );
        approx(
            m.apply_component(baseline, 0.0, 2.0, 1).unwrap(),
            baseline * 0.5f64.exp2(),
        );
        approx(
            m.apply_component(baseline, 0.0, 2.0, 2).unwrap(),
            baseline * 1.0f64.exp2(),
        );
    }

    /// `apply_component` rejects an out-of-range colour-component index.
    #[test]
    fn apply_component_rejects_component_index_above_two() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        assert!(m.apply_component(1.0, 1.0, 8.0, 3).is_none());
    }

    /// §6.2 NOTE 3 / §6.3 round trip: a gain map computed from a known
    /// baseline/alternate pair (Annex A.2 Formula (A.1)) reconstructs the
    /// alternate when applied with W = 1. With zero offsets and γ = 1, the
    /// log2-ratio stored as the gain and re-applied returns the alternate.
    #[test]
    fn apply_component_round_trips_a2_gain() {
        // Construct metadata whose single channel spans the exact gain
        // G = log2(alternate / baseline) for baseline = 2, alternate = 8
        // → G = log2(4) = 2.0. Store min = max = 2.0 so any normalized
        // sample unnormalizes to 2.0; offsets 0, gamma 1.
        let mut buf = Vec::new();
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.push(0x00); // single channel
        push_rational(&mut buf, 1, 1); // base_hdr = 1.0
        push_rational(&mut buf, 2, 1); // alt_hdr  = 2.0 (W = 1 at target 2)
        push_rational(&mut buf, 2, 1); // gain_map_min = 2.0
        push_rational(&mut buf, 2, 1); // gain_map_max = 2.0
        push_rational(&mut buf, 1, 1); // gamma
        push_rational(&mut buf, 0, 1); // base_offset
        push_rational(&mut buf, 0, 1); // alternate_offset
        let m = GainMapMetadata::parse(&buf).unwrap();
        // Alternate = (2 + 0) · 2^(1 · 2) − 0 = 2 · 4 = 8.
        approx(m.apply_component(2.0, 0.5, 2.0, 0).unwrap(), 8.0);
    }

    /// `apply_plane_rgb` over an achromatic gain plane (one sample per
    /// pixel) matches per-pixel `apply_rgb` with the sample broadcast to
    /// all three colour components (§6.3 NOTE 2).
    #[test]
    fn apply_plane_rgb_achromatic_matches_per_pixel() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        // 2×1 image, interleaved RGB baseline.
        let baseline = [0.25, 0.5, 0.75, 1.0, 0.125, 0.6];
        let gain = [0.3, 0.9]; // one sample per pixel
        let out = m.apply_plane_rgb(&baseline, &gain, 2, 1, 6.0).unwrap();
        assert_eq!(out.len(), 6);
        for p in 0..2 {
            let base = [baseline[p * 3], baseline[p * 3 + 1], baseline[p * 3 + 2]];
            let want = m.apply_rgb(base, [gain[p]; 3], 6.0).unwrap();
            for c in 0..3 {
                approx(out[p * 3 + c], want[c]);
            }
        }
    }

    /// `apply_plane_rgb` over an interleaved RGB gain plane consumes one
    /// gain sample per colour component.
    #[test]
    fn apply_plane_rgb_interleaved_uses_per_component_gain() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        let baseline = [0.25, 0.5, 0.75]; // 1×1
        let gain = [0.0, 0.5, 1.0]; // RGB gain plane, 1×1×3
        let out = m.apply_plane_rgb(&baseline, &gain, 1, 1, 8.0).unwrap();
        for c in 0..3 {
            let want = m.apply_component(baseline[c], gain[c], 8.0, c).unwrap();
            approx(out[c], want);
        }
    }

    /// `apply_plane_rgb` rejects a baseline length that does not match
    /// `width × height × 3` and a gain length that is neither the
    /// achromatic nor the RGB size.
    #[test]
    fn apply_plane_rgb_rejects_mismatched_lengths() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        // baseline too short for 2×1×3 = 6.
        let err = m
            .apply_plane_rgb(&[0.0, 0.0, 0.0], &[0.0, 0.0], 2, 1, 6.0)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
        // gain length 5 is neither 2 (achromatic) nor 6 (RGB).
        let baseline = [0.0; 6];
        let err = m
            .apply_plane_rgb(&baseline, &[0.0; 5], 2, 1, 6.0)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidData(_)));
    }

    /// `apply_plane_rgb` on a zero-area plane is a valid empty result.
    #[test]
    fn apply_plane_rgb_zero_area_is_empty() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        let out = m.apply_plane_rgb(&[], &[], 0, 4, 8.0).unwrap();
        assert!(out.is_empty());
    }

    /// `normalize_full_range_plane` maps the code-range endpoints of
    /// each supported depth to exactly 0.0 / 1.0 and mid values
    /// proportionally; out-of-range samples and unknown depths reject.
    #[test]
    fn normalize_full_range_plane_endpoints_and_guards() {
        for depth in [8u8, 10, 12, 16] {
            let max = ((1u32 << depth) - 1) as u16;
            let out = normalize_full_range_plane(&[0, max, max / 2], depth).unwrap();
            approx(out[0], 0.0);
            approx(out[1], 1.0);
            approx(out[2], (max / 2) as f64 / max as f64);
        }
        // 1024 exceeds the 10-bit code range.
        assert!(matches!(
            normalize_full_range_plane(&[1024], 10).unwrap_err(),
            Error::InvalidData(_)
        ));
        assert!(matches!(
            normalize_full_range_plane(&[0], 9).unwrap_err(),
            Error::InvalidData(_)
        ));
    }

    /// `apply_plane_rgb_coded` over a 10-bit coded achromatic gain
    /// plane equals `apply_plane_rgb` fed the same samples normalized
    /// by hand — the coded path is exactly the full-range scaling plus
    /// the §6.3 application.
    #[test]
    fn apply_plane_rgb_coded_matches_manual_normalization() {
        let m = GainMapMetadata::parse(&build_singlechannel_gain_map()).unwrap();
        let baseline = [0.25, 0.5, 0.75, 1.0, 0.125, 0.6]; // 2×1×3
        let coded: [u16; 2] = [307, 921]; // 10-bit samples
        let manual: Vec<f64> = coded.iter().map(|&s| s as f64 / 1023.0).collect();
        let want = m.apply_plane_rgb(&baseline, &manual, 2, 1, 6.0).unwrap();
        let got = m
            .apply_plane_rgb_coded(&baseline, &coded, 10, 2, 1, 6.0)
            .unwrap();
        assert_eq!(got.len(), want.len());
        for (g, w) in got.iter().zip(&want) {
            approx(*g, *w);
        }
    }

    // -------------------------------------------------------------------
    // AVIF Profile compliance audit (av1-avif v1.2.0 §8.2 / §8.3)
    // -------------------------------------------------------------------

    /// Build an `av1C` payload whose byte 1 packs
    /// `seq_profile (3) | seq_level_idx_0 (5)` per av1-isobmff §2.3.
    /// Other bytes are filled with conventional values (marker=1,
    /// version=1, chroma 4:2:0 mono-cleared).
    fn av1c_with_profile_level(seq_profile: u8, seq_level_idx_0: u8) -> Vec<u8> {
        assert!(seq_profile <= 7);
        assert!(seq_level_idx_0 <= 31);
        let b1 = (seq_profile << 5) | (seq_level_idx_0 & 0x1F);
        vec![0x81, b1, 0x00, 0x00]
    }

    fn brands_with(baseline: bool, advanced: bool) -> crate::parser::BrandClass {
        crate::parser::BrandClass {
            is_image: true,
            is_miaf: true,
            is_baseline_profile: baseline,
            is_advanced_profile: advanced,
            ..crate::parser::BrandClass::default()
        }
    }

    /// Decoded `seq_profile` / `seq_level_idx_0` round-trip through
    /// the byte-1 helpers across the boundary values that the spec's
    /// §8.2 / §8.3 audit branches on.
    #[test]
    fn decode_av1c_byte1_round_trips_profile_and_level() {
        // (seq_profile, seq_level_idx_0) coverage: 0/13 (Baseline edge),
        // 0/14 (over Baseline level), 1/16 (Advanced edge), 1/17 (over
        // Advanced level), 2/0 (Professional disallowed), 7/31 (max bits).
        let cases = [(0, 13), (0, 14), (1, 16), (1, 17), (2, 0), (7, 31)];
        for (p, l) in cases {
            let bytes = av1c_with_profile_level(p, l);
            assert_eq!(decode_av1c_seq_profile(&bytes), Some(p), "p={p} l={l}");
            assert_eq!(decode_av1c_seq_level_idx_0(&bytes), Some(l), "p={p} l={l}");
        }
    }

    /// Both helpers tolerate truncation without panicking.
    #[test]
    fn decode_av1c_byte1_handles_truncation() {
        assert_eq!(decode_av1c_seq_profile(&[]), None);
        assert_eq!(decode_av1c_seq_profile(&[0x81]), None);
        assert_eq!(decode_av1c_seq_level_idx_0(&[]), None);
        assert_eq!(decode_av1c_seq_level_idx_0(&[0x81]), None);
    }

    /// MA1B + Main Profile + level 5.1 (`seq_profile=0, idx=13`) is the
    /// spec-canonical Baseline shape. Compliant.
    #[test]
    fn audit_profile_baseline_main_level_5_1_compliant() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(0, 13))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].profile, AvifProfile::Baseline);
        assert_eq!(r[0].seq_profile, Some(0));
        assert_eq!(r[0].seq_level_idx_0, Some(13));
        assert!(r[0].is_compliant());
        assert!(r[0].missing().is_empty());
    }

    /// MA1B + Main + level 5.2 (`idx=14`) tips the level over the
    /// §8.2 bound. Flagged with `seq-level-idx-out-of-range`.
    #[test]
    fn audit_profile_baseline_level_above_5_1_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(0, 14))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert_eq!(r.len(), 1);
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["seq-level-idx-out-of-range"]);
    }

    /// MA1B + High Profile (`seq_profile=1`) violates §8.2's "Main
    /// Profile" requirement. Flagged with `seq-profile-out-of-range`.
    #[test]
    fn audit_profile_baseline_high_profile_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(1, 13))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert_eq!(r.len(), 1);
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["seq-profile-out-of-range"]);
    }

    /// MA1A + High Profile + level 6.0 (`idx=16`) is the spec-canonical
    /// Advanced shape. Compliant.
    #[test]
    fn audit_profile_advanced_high_level_6_0_compliant() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(1, 16))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(false, true));
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].profile, AvifProfile::Advanced);
        assert!(r[0].is_compliant());
    }

    /// MA1A + Main Profile (`seq_profile=0`) is also compliant — Main
    /// is a subset of High per AV1 §A.2.
    #[test]
    fn audit_profile_advanced_main_profile_compliant() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(0, 13))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(false, true));
        assert!(r[0].is_compliant());
    }

    /// MA1A + Professional (`seq_profile=2`) breaches §8.3's "≤ High"
    /// requirement. Flagged.
    #[test]
    fn audit_profile_advanced_professional_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(2, 16))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(false, true));
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["seq-profile-out-of-range"]);
    }

    /// MA1A + level 6.1 (`idx=17`) breaches §8.3's "≤ 6.0".
    #[test]
    fn audit_profile_advanced_level_above_6_0_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(1, 17))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(false, true));
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["seq-level-idx-out-of-range"]);
    }

    /// AV1 §A.3's `seq_level_idx_0 == 31` "Maximum parameters" carve-out
    /// signals unconstrained sizing, which is outside either profile's
    /// reach — even though Main Profile (`seq_profile=0`) is compliant
    /// with §8.2's profile clause, the level clause is unmet.
    #[test]
    fn audit_profile_level_31_max_parameters_flagged_for_baseline() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(0, 31))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["seq-level-idx-out-of-range"]);
    }

    /// Missing `av1C` surfaces the missing-av1c flag distinctly from
    /// a truncated `av1C`.
    #[test]
    fn audit_profile_missing_av1c_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![],
            associations: vec![],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert_eq!(r.len(), 1);
        assert!(r[0].missing_av1c);
        assert_eq!(r[0].seq_profile, None);
        assert_eq!(r[0].seq_level_idx_0, None);
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["item-missing-av1C"]);
    }

    /// Truncated `av1C` (`< 2` bytes) surfaces as item-av1C-truncated,
    /// distinct from missing-av1c.
    #[test]
    fn audit_profile_truncated_av1c_flagged() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(vec![0x81])], // only 1 byte
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert_eq!(r.len(), 1);
        assert!(!r[0].missing_av1c);
        assert_eq!(r[0].seq_profile, None);
        assert_eq!(r[0].seq_level_idx_0, None);
        assert!(!r[0].is_compliant());
        assert_eq!(r[0].missing(), vec!["item-av1C-truncated"]);
    }

    /// File declaring both `MA1B` and `MA1A` emits one record per
    /// brand, Baseline before Advanced.
    #[test]
    fn audit_profile_both_brands_emit_two_records_per_item() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            // Main profile + level 5.1 — compliant with both brands.
            properties: vec![Property::Av1C(av1c_with_profile_level(0, 13))],
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, true));
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].profile, AvifProfile::Baseline);
        assert_eq!(r[1].profile, AvifProfile::Advanced);
        assert!(r[0].is_compliant());
        assert!(r[1].is_compliant());
    }

    /// File declaring neither `MA1B` nor `MA1A` skips the audit
    /// entirely. The §8 constraints only apply to files claiming the
    /// brand; an unbranded AVIF has nothing to fail.
    #[test]
    fn audit_profile_no_brand_claim_returns_empty() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            properties: vec![Property::Av1C(av1c_with_profile_level(2, 31))], // would fail both
            associations: vec![ipa(1, &[0])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(false, false));
        assert!(r.is_empty());
    }

    /// File with no AV1 Image Items returns an empty audit even when
    /// the brand is declared (degenerate case — `meta.item_ids_of_type`
    /// returns nothing).
    #[test]
    fn audit_profile_no_av01_items_returns_empty() {
        let meta = Meta {
            items: vec![make_infe(1, b"mime", 0)],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, false));
        assert!(r.is_empty());
    }

    /// Two AV1 Image Items in a file declaring both brands → 4
    /// records, paired (Baseline, Advanced) per item in iinf order.
    #[test]
    fn audit_profile_two_items_two_brands_four_records() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            properties: vec![
                Property::Av1C(av1c_with_profile_level(0, 13)), // item 1: compliant both
                Property::Av1C(av1c_with_profile_level(2, 16)), // item 2: Advanced-fails profile
            ],
            associations: vec![ipa(1, &[0]), ipa(2, &[1])],
            ..Meta::default()
        };
        let r = audit_avif_profile_compliance(&meta, &brands_with(true, true));
        assert_eq!(r.len(), 4);
        // Item 1 first (iinf order), then item 2.
        assert_eq!(r[0].item_id, 1);
        assert_eq!(r[0].profile, AvifProfile::Baseline);
        assert!(r[0].is_compliant());
        assert_eq!(r[1].item_id, 1);
        assert_eq!(r[1].profile, AvifProfile::Advanced);
        assert!(r[1].is_compliant());
        assert_eq!(r[2].item_id, 2);
        assert_eq!(r[2].profile, AvifProfile::Baseline);
        assert!(!r[2].is_compliant()); // seq_profile=2 fails Baseline
        assert_eq!(r[3].item_id, 2);
        assert_eq!(r[3].profile, AvifProfile::Advanced);
        assert!(!r[3].is_compliant()); // seq_profile=2 fails Advanced too
    }

    // -----------------------------------------------------------------------
    // Derived-image geometry resolution (HEIF §6.3 / §6.6.2)
    // -----------------------------------------------------------------------

    use crate::meta::{
        Clap as MClap, Imir as MImir, Irot as MIrot, Iscl as MIscl, ItemInfo as MII,
        ItemPropertyAssociation as MIpa, Meta as MMeta, Property as MProp,
        PropertyAssociation as MPa,
    };

    fn geo_ii(id: u32, item_type: &[u8; 4]) -> MII {
        MII {
            id,
            item_type: *item_type,
            name: String::new(),
            content_type: None,
            content_encoding: None,
            item_uri_type: None,
            flags: 0,
        }
    }

    fn geo_assoc(item_id: u32, indices: &[u16]) -> MIpa {
        MIpa {
            item_id,
            entries: indices
                .iter()
                .map(|&index| MPa {
                    index,
                    essential: true,
                })
                .collect(),
        }
    }

    fn ispe_prop(w: u32, h: u32) -> MProp {
        MProp::Ispe(crate::meta::Ispe {
            width: w,
            height: h,
        })
    }

    /// `DimTransform::apply_dims` — rotation by 90°/270° swaps W/H; 0°/180°
    /// preserve.
    #[test]
    fn dim_transform_rotate_swaps_at_odd_quarter_turns() {
        assert_eq!(
            DimTransform::Rotate { angle: 0 }.apply_dims(40, 30),
            (40, 30)
        );
        assert_eq!(
            DimTransform::Rotate { angle: 1 }.apply_dims(40, 30),
            (30, 40)
        );
        assert_eq!(
            DimTransform::Rotate { angle: 2 }.apply_dims(40, 30),
            (40, 30)
        );
        assert_eq!(
            DimTransform::Rotate { angle: 3 }.apply_dims(40, 30),
            (30, 40)
        );
    }

    /// Mirror never changes dimensions (§6.5.12).
    #[test]
    fn dim_transform_mirror_preserves_dims() {
        assert_eq!(
            DimTransform::Mirror { axis: 0 }.apply_dims(40, 30),
            (40, 30)
        );
        assert_eq!(
            DimTransform::Mirror { axis: 1 }.apply_dims(40, 30),
            (40, 30)
        );
    }

    /// Crop reduces dimensions to the clean-aperture width/height; a crop
    /// larger than the input is a no-op (defensive, matches `apply_clap`).
    #[test]
    fn dim_transform_crop_to_clean_aperture() {
        let c = DimTransform::Crop {
            width_n: 20,
            width_d: 1,
            height_n: 10,
            height_d: 1,
        };
        assert_eq!(c.apply_dims(40, 30), (20, 10));
        // Crop wider than input → unchanged.
        let big = DimTransform::Crop {
            width_n: 100,
            width_d: 1,
            height_n: 10,
            height_d: 1,
        };
        assert_eq!(big.apply_dims(40, 30), (40, 30));
        // Zero denominator → unchanged.
        let zero = DimTransform::Crop {
            width_n: 20,
            width_d: 0,
            height_n: 10,
            height_d: 1,
        };
        assert_eq!(zero.apply_dims(40, 30), (40, 30));
    }

    /// Scale applies `ceil(input * num / den)` per §6.5.13.
    #[test]
    fn dim_transform_scale_ceil() {
        let s = DimTransform::Scale {
            target_width_numerator: 3,
            target_width_denominator: 2,
            target_height_numerator: 1,
            target_height_denominator: 2,
        };
        // 40 * 3 / 2 = 60; 30 * 1 / 2 = 15.
        assert_eq!(s.apply_dims(40, 30), (60, 15));
        // Ceiling: 41 * 1 / 2 = 20.5 → 21.
        assert_eq!(
            DimTransform::Scale {
                target_width_numerator: 1,
                target_width_denominator: 2,
                target_height_numerator: 1,
                target_height_denominator: 1,
            }
            .apply_dims(41, 9),
            (21, 9)
        );
    }

    /// `transform_chain` collects only the dimension-affecting transformative
    /// properties, in `ipma` order, skipping descriptive properties.
    #[test]
    fn transform_chain_preserves_ipma_order_skips_descriptive() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"av01")],
            properties: vec![
                ispe_prop(100, 50),              // 0: descriptive, skipped
                MProp::Irot(MIrot { angle: 1 }), // 1: rotate
                MProp::Clap(MClap {
                    // 2: crop
                    clean_aperture_width_n: 40,
                    clean_aperture_width_d: 1,
                    clean_aperture_height_n: 30,
                    clean_aperture_height_d: 1,
                    horiz_off_n: 0,
                    horiz_off_d: 1,
                    vert_off_n: 0,
                    vert_off_d: 1,
                }),
                MProp::Imir(MImir { axis: 1 }), // 3: mirror
            ],
            // ipma order: ispe, irot, clap, imir.
            associations: vec![geo_assoc(1, &[0, 1, 2, 3])],
            ..MMeta::default()
        };
        let chain = transform_chain(&meta, 1);
        assert_eq!(chain.len(), 3);
        assert_eq!(chain[0], DimTransform::Rotate { angle: 1 });
        assert!(matches!(chain[1], DimTransform::Crop { .. }));
        assert_eq!(chain[2], DimTransform::Mirror { axis: 1 });
    }

    /// `output_dims_from_reconstructed` folds the chain in order: a coded
    /// 100×50 image rotated 90° → 50×100, then clap-cropped to 40×30.
    #[test]
    fn output_dims_folds_chain_in_order() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"av01")],
            properties: vec![
                MProp::Irot(MIrot { angle: 1 }),
                MProp::Clap(MClap {
                    clean_aperture_width_n: 40,
                    clean_aperture_width_d: 1,
                    clean_aperture_height_n: 30,
                    clean_aperture_height_d: 1,
                    horiz_off_n: 0,
                    horiz_off_d: 1,
                    vert_off_n: 0,
                    vert_off_d: 1,
                }),
            ],
            associations: vec![geo_assoc(1, &[0, 1])],
            ..MMeta::default()
        };
        // Reconstructed 100×50, rotate → 50×100, crop → 40×30.
        assert_eq!(output_dims_from_reconstructed(&meta, 1, 100, 50), (40, 30));
        // Empty chain → identity.
        let bare = MMeta {
            items: vec![geo_ii(9, b"av01")],
            ..MMeta::default()
        };
        assert_eq!(output_dims_from_reconstructed(&bare, 9, 100, 50), (100, 50));
    }

    /// `reconstructed_dims` for a coded item reads `ispe`.
    #[test]
    fn reconstructed_dims_coded_uses_ispe() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"av01")],
            properties: vec![ispe_prop(640, 480)],
            associations: vec![geo_assoc(1, &[0])],
            ..MMeta::default()
        };
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), Some((640, 480)));
        // No ispe → None.
        let bare = MMeta {
            items: vec![geo_ii(2, b"av01")],
            ..MMeta::default()
        };
        assert_eq!(reconstructed_dims(&bare, 2, &[], None), None);
    }

    /// Build a 16-bit `iovl` descriptor with the given canvas + offsets.
    fn iovl_desc(out_w: u16, out_h: u16, offsets: &[(i16, i16)]) -> Vec<u8> {
        let mut buf = vec![0u8, 0u8]; // version 0, flags 0 (16-bit fields)
        for _ in 0..4 {
            buf.extend_from_slice(&0u16.to_be_bytes()); // canvas fill
        }
        buf.extend_from_slice(&out_w.to_be_bytes());
        buf.extend_from_slice(&out_h.to_be_bytes());
        for &(x, y) in offsets {
            buf.extend_from_slice(&x.to_be_bytes());
            buf.extend_from_slice(&y.to_be_bytes());
        }
        buf
    }

    /// End-to-end `iovl` resolution against an `idat`-backed descriptor:
    /// two inputs placed on a 200×200 canvas, the second partially clipped
    /// at the right/bottom edge.
    #[test]
    fn resolve_overlays_idat_with_clipping() {
        // idat holds the iovl descriptor at offset 0.
        let desc = iovl_desc(200, 200, &[(10, 20), (160, 170)]);
        let idat = desc.clone();
        let meta = MMeta {
            items: vec![geo_ii(1, b"iovl"), geo_ii(2, b"av01"), geo_ii(3, b"av01")],
            properties: vec![ispe_prop(80, 60), ispe_prop(80, 60)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[1])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            locations: vec![ItemLocation {
                id: 1,
                construction_method: 1, // idat
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: desc.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        let res = resolve_overlays(&meta, &[], Some(&idat));
        assert_eq!(res.len(), 1);
        let r = &res[0];
        assert_eq!(r.iovl_item_id, 1);
        assert_eq!(r.canvas(), (200, 200));
        assert_eq!(r.placements.len(), 2);

        // First input: fully visible at (10, 20), 80×60.
        let p0 = &r.placements[0];
        assert_eq!(p0.source_item_id, 2);
        assert_eq!((p0.input_width, p0.input_height), (80, 60));
        assert!(p0.fully_visible(200, 200));
        assert_eq!(p0.visible(200, 200), Some((10, 20, 80, 60)));

        // Second input: at (160, 170), 80×60 → clipped to (160,170,40,30).
        let p1 = &r.placements[1];
        assert_eq!(p1.source_item_id, 3);
        assert!(!p1.fully_visible(200, 200));
        assert_eq!(p1.visible(200, 200), Some((160, 170, 40, 30)));
        // Not fully covered → fill colour shows through.
        assert!(r.canvas_partially_filled());
    }

    /// An overlay input placed entirely off-canvas (negative beyond its own
    /// extent) is reported as off-canvas with no visible rectangle.
    #[test]
    fn overlay_placement_off_canvas() {
        let p = OverlayPlacement {
            source_item_id: 5,
            offset_x: -100,
            offset_y: 0,
            input_width: 50,
            input_height: 50,
        };
        assert!(p.off_canvas(200, 200));
        assert_eq!(p.visible(200, 200), None);
        // A negative offset that still overlaps → partial visible rect.
        let q = OverlayPlacement { offset_x: -10, ..p };
        assert_eq!(q.visible(200, 200), Some((0, 0, 40, 50)));
    }

    /// End-to-end `iden` resolution: an identity derivation that crops its
    /// 100×80 source via a `clap` carried on the iden item itself
    /// (§6.6.2.1 NOTE 2).
    #[test]
    fn resolve_iden_applies_iden_transforms() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"iden"), geo_ii(2, b"av01")],
            properties: vec![
                ispe_prop(100, 80), // 0: source ispe
                MProp::Clap(MClap {
                    // 1: clap on the iden item
                    clean_aperture_width_n: 50,
                    clean_aperture_width_d: 1,
                    clean_aperture_height_n: 40,
                    clean_aperture_height_d: 1,
                    horiz_off_n: 0,
                    horiz_off_d: 1,
                    vert_off_n: 0,
                    vert_off_d: 1,
                }),
            ],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(1, &[1])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2],
            }],
            ..MMeta::default()
        };
        let res = resolve_iden_derivations(&meta, &[], None);
        assert_eq!(res.len(), 1);
        let r = &res[0];
        assert_eq!(r.iden_item_id, 1);
        assert_eq!(r.source_item_id, Some(2));
        assert_eq!(r.source_dims, Some((100, 80)));
        assert_eq!(r.transforms.len(), 1);
        assert_eq!(r.output_dims, Some((50, 40)));
    }

    /// An `iden` whose source is itself a grid resolves transitively: the
    /// grid's `output_width/height` become the iden's source dims, then the
    /// iden's `irot` swaps them.
    #[test]
    fn reconstructed_dims_iden_over_grid_with_rotation() {
        // grid descriptor: version 0, flags 0, rows=1, cols=1, 256×128.
        let mut grid = vec![0u8, 0u8, 0u8, 0u8];
        grid.extend_from_slice(&256u16.to_be_bytes());
        grid.extend_from_slice(&128u16.to_be_bytes());
        let idat = grid.clone();
        let meta = MMeta {
            items: vec![geo_ii(1, b"iden"), geo_ii(2, b"grid"), geo_ii(3, b"av01")],
            properties: vec![
                ispe_prop(256, 128),             // 0: tile ispe (unused for grid dims)
                MProp::Irot(MIrot { angle: 1 }), // 1: rotate on the iden
            ],
            associations: vec![geo_assoc(3, &[0]), geo_assoc(1, &[1])],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![3],
                },
            ],
            locations: vec![ItemLocation {
                id: 2,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: grid.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        // iden reconstructed dims = output image of its grid source = 256×128
        // (grid has no transforms), then the iden's irot swaps → 128×256.
        let res = resolve_iden_derivations(&meta, &[], Some(&idat));
        assert_eq!(res.len(), 1);
        assert_eq!(res[0].source_dims, Some((256, 128)));
        assert_eq!(res[0].output_dims, Some((128, 256)));
    }

    /// A `dimg` cycle (iden → iden → …) is broken by the depth guard rather
    /// than recursing forever.
    #[test]
    fn reconstructed_dims_cycle_guard() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"iden"), geo_ii(2, b"iden")],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![1],
                },
            ],
            ..MMeta::default()
        };
        // Must terminate and return None rather than overflow the stack.
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), None);
    }

    /// `iscl` participates in the chain — verify a coded item scaled 2×.
    #[test]
    fn output_dims_with_iscl() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"av01")],
            properties: vec![MProp::Iscl(MIscl {
                target_width_numerator: 2,
                target_width_denominator: 1,
                target_height_numerator: 2,
                target_height_denominator: 1,
            })],
            associations: vec![geo_assoc(1, &[0])],
            ..MMeta::default()
        };
        assert_eq!(output_dims_from_reconstructed(&meta, 1, 64, 48), (128, 96));
    }

    /// av1-avif §4.2.2: a `tmap` derived item's reconstructed dimensions are
    /// the *base* image input's (input 0) output dimensions, not the gain
    /// map's. Base = 200×150 coded, gain map = 100×75 coded; the tmap
    /// resolves to 200×150.
    #[test]
    fn reconstructed_dims_tmap_takes_base_extents() {
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"tmap"),
                geo_ii(2, b"av01"), // base
                geo_ii(3, b"av01"), // gain map
            ],
            properties: vec![ispe_prop(200, 150), ispe_prop(100, 75)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[1])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            ..MMeta::default()
        };
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), Some((200, 150)));
    }

    /// A `tmap` whose base input is itself a transformed coded item folds the
    /// base's transforms into the rendered extents. Base coded 200×150 +
    /// `irot` 90° → base output 150×200 → tmap reconstructs 150×200.
    #[test]
    fn reconstructed_dims_tmap_folds_base_transforms() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"tmap"), geo_ii(2, b"av01"), geo_ii(3, b"av01")],
            properties: vec![
                ispe_prop(200, 150),             // 0: base ispe
                MProp::Irot(MIrot { angle: 1 }), // 1: base irot (swaps dims)
                ispe_prop(100, 75),              // 2: gain map ispe
            ],
            associations: vec![geo_assoc(2, &[0, 1]), geo_assoc(3, &[2])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            ..MMeta::default()
        };
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), Some((150, 200)));
    }

    /// `resolve_tone_maps` surfaces the base id, gain-map ids, rendered
    /// extents, and per-gain-map coded dims, and detects gain-map
    /// up-sampling.
    #[test]
    fn resolve_tone_maps_reports_geometry_and_upsampling() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"tmap"), geo_ii(2, b"av01"), geo_ii(3, b"av01")],
            properties: vec![ispe_prop(200, 150), ispe_prop(100, 75)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[1])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            ..MMeta::default()
        };
        let res = resolve_tone_maps(&meta, &[], None);
        assert_eq!(res.len(), 1);
        let r = &res[0];
        assert_eq!(r.tmap_item_id, 1);
        assert_eq!(r.base_item_id, Some(2));
        assert_eq!(r.gain_map_item_ids, vec![3]);
        assert_eq!(r.rendered_dims, Some((200, 150)));
        assert_eq!(r.gain_map_dims, vec![(3, Some((100, 75)))]);
        // 100×75 gain map under a 200×150 render → up-sampled.
        assert!(r.upsamples_gain_map());
    }

    /// A gain map coded at the same extents as the base is not up-sampled.
    #[test]
    fn resolve_tone_maps_no_upsampling_when_gain_map_matches_base() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"tmap"), geo_ii(2, b"av01"), geo_ii(3, b"av01")],
            properties: vec![ispe_prop(200, 150)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[0])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            ..MMeta::default()
        };
        let r = &resolve_tone_maps(&meta, &[], None)[0];
        assert_eq!(r.rendered_dims, Some((200, 150)));
        assert_eq!(r.gain_map_dims, vec![(3, Some((200, 150)))]);
        assert!(!r.upsamples_gain_map());
    }

    /// av1-avif §4.2.3.1: a `sato` Sample-Transform derived item carries its
    /// own `ispe` (its inputs share those extents). `reconstructed_dims`
    /// reads that `ispe` directly.
    #[test]
    fn reconstructed_dims_sato_reads_own_ispe() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"sato"), geo_ii(2, b"av01"), geo_ii(3, b"av01")],
            properties: vec![ispe_prop(320, 240)],
            associations: vec![geo_assoc(1, &[0])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            ..MMeta::default()
        };
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), Some((320, 240)));
    }

    /// When a `sato` lacks its own `ispe` (malformed per §4.2.3.1), the
    /// resolver falls back to its first input's reconstructed dimensions —
    /// every input shares the sato's extents, so input 0 is representative.
    #[test]
    fn reconstructed_dims_sato_falls_back_to_input_extents() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"sato"), geo_ii(2, b"av01"), geo_ii(3, b"av01")],
            // No ispe on the sato item itself; only on the inputs.
            properties: vec![ispe_prop(320, 240)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[0])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3],
            }],
            ..MMeta::default()
        };
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), Some((320, 240)));
    }

    /// Build a 16-bit `ImageGrid` descriptor payload (version 0, flags 0).
    fn build_grid_desc(rows: u8, cols: u8, out_w: u16, out_h: u16) -> Vec<u8> {
        let mut b = vec![0u8, 0u8, rows.saturating_sub(1), cols.saturating_sub(1)];
        b.extend_from_slice(&out_w.to_be_bytes());
        b.extend_from_slice(&out_h.to_be_bytes());
        b
    }

    /// `resolve_grids` resolves a 2×2 grid of 100×100 tiles into a 180×180
    /// canvas: tiles placed row-major at (0,0)/(100,0)/(0,100)/(100,100),
    /// with the right column + bottom row trimmed to the 180 px output.
    #[test]
    fn resolve_grids_places_tiles_and_trims_edges() {
        let desc = build_grid_desc(2, 2, 180, 180);
        let idat = desc.clone();
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"grid"),
                geo_ii(2, b"av01"),
                geo_ii(3, b"av01"),
                geo_ii(4, b"av01"),
                geo_ii(5, b"av01"),
            ],
            properties: vec![ispe_prop(100, 100)],
            // every tile shares the same 100×100 ispe (property index 0)
            associations: vec![
                geo_assoc(2, &[0]),
                geo_assoc(3, &[0]),
                geo_assoc(4, &[0]),
                geo_assoc(5, &[0]),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3, 4, 5],
            }],
            locations: vec![ItemLocation {
                id: 1,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: desc.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        let res = resolve_grids(&meta, &[], Some(&idat));
        assert_eq!(res.len(), 1);
        let r = &res[0];
        assert_eq!(r.grid_item_id, 1);
        assert_eq!(r.canvas(), (180, 180));
        assert_eq!(r.tile_dims, Some((100, 100)));
        assert!(r.covers_canvas());
        assert_eq!(r.placements.len(), 4);
        // Row-major placement.
        assert_eq!(
            r.placements[0],
            GridTilePlacement {
                source_item_id: 2,
                row: 0,
                col: 0,
                origin_x: 0,
                origin_y: 0
            }
        );
        assert_eq!(
            r.placements[3],
            GridTilePlacement {
                source_item_id: 5,
                row: 1,
                col: 1,
                origin_x: 100,
                origin_y: 100
            }
        );
        // Top-left tile fully inside; bottom-right tile trimmed to 80×80.
        assert_eq!(
            r.placements[0].visible(100, 100, 180, 180),
            Some((0, 0, 100, 100))
        );
        assert_eq!(
            r.placements[3].visible(100, 100, 180, 180),
            Some((100, 100, 80, 80))
        );
        assert!(!r.placements[0].is_trimmed(100, 100, 180, 180));
        assert!(r.placements[3].is_trimmed(100, 100, 180, 180));
        // The right column (1) + bottom row (2) + corner = 3 trimmed tiles.
        assert_eq!(r.trimmed_tile_count(), 3);
    }

    /// A grid whose output is a whole multiple of the tile size trims no
    /// tiles and covers the canvas exactly.
    #[test]
    fn resolve_grids_no_trim_on_exact_multiple() {
        let desc = build_grid_desc(1, 3, 192, 64);
        let idat = desc.clone();
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"grid"),
                geo_ii(2, b"av01"),
                geo_ii(3, b"av01"),
                geo_ii(4, b"av01"),
            ],
            properties: vec![ispe_prop(64, 64)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[0]), geo_assoc(4, &[0])],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3, 4],
            }],
            locations: vec![ItemLocation {
                id: 1,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: desc.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        let r = &resolve_grids(&meta, &[], Some(&idat))[0];
        assert_eq!(r.tile_dims, Some((64, 64)));
        assert!(r.covers_canvas());
        assert_eq!(r.trimmed_tile_count(), 0);
        assert_eq!(r.placements[2].origin_x, 128);
    }

    /// A `grid` descriptor stored via `construction_method == 2` (item-offset)
    /// — its bytes are a range of another item's data, named through the
    /// `'iloc'` item reference (ISO/IEC 14496-12 §8.11.3.3). `resolve_grids`
    /// (through `resolve_descriptor_bytes`) now follows the iref instead of
    /// silently skipping the grid.
    #[test]
    fn resolve_grids_resolves_cm2_item_offset_descriptor() {
        // Item 10 holds the raw grid descriptor bytes at file offset (cm=0);
        // the grid item 1 is cm=2 and points at item 10 via an `'iloc'` iref,
        // taking the whole referenced item (extent_length 0).
        let desc = build_grid_desc(1, 2, 128, 64);
        // Lay the descriptor bytes into a synthetic file at offset 8.
        let mut file = vec![0u8; 8];
        file.extend_from_slice(&desc);
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"grid"),
                geo_ii(2, b"av01"),
                geo_ii(3, b"av01"),
                geo_ii(10, b"av01"), // data-origin item (treated as bytes)
            ],
            properties: vec![ispe_prop(64, 64)],
            associations: vec![geo_assoc(2, &[0]), geo_assoc(3, &[0])],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2, 3],
                },
                // The cm=2 data-origin reference: grid item 1 ← item 10.
                IrefEntry {
                    reference_type: *b"iloc",
                    from_id: 1,
                    to_ids: vec![10],
                },
            ],
            locations: vec![
                // grid item: cm=2, whole referenced item (length 0).
                ItemLocation {
                    id: 1,
                    construction_method: 2,
                    data_reference_index: 0,
                    base_offset: 0,
                    extents: vec![IlocExtent {
                        offset: 0,
                        length: 0,
                        extent_index: 1,
                    }],
                },
                // data-origin item 10: cm=0, points at the descriptor bytes
                // in the synthetic file.
                ItemLocation {
                    id: 10,
                    construction_method: 0,
                    data_reference_index: 0,
                    base_offset: 0,
                    extents: vec![IlocExtent {
                        offset: 8,
                        length: desc.len() as u64,
                        extent_index: 0,
                    }],
                },
            ],
            ..MMeta::default()
        };
        let res = resolve_grids(&meta, &file, None);
        assert_eq!(res.len(), 1, "cm=2 grid descriptor must resolve");
        let r = &res[0];
        assert_eq!(r.canvas(), (128, 64));
        assert_eq!(r.placements.len(), 2);
        // The same descriptor is reachable through reconstructed_dims.
        assert_eq!(reconstructed_dims(&meta, 1, &file, None), Some((128, 64)));
    }

    // -----------------------------------------------------------------------
    // Unified derivation-graph walk (HEIF §6.6)
    // -----------------------------------------------------------------------

    /// A plain coded primary is a single-node graph whose root is `Coded`
    /// and whose decode set is just that item.
    #[test]
    fn derivation_graph_coded_root_single_node() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"av01")],
            properties: vec![ispe_prop(640, 480)],
            associations: vec![geo_assoc(1, &[0])],
            ..MMeta::default()
        };
        let g = build_derivation_graph(&meta, 1, &[], None);
        assert_eq!(g.root_item_id, 1);
        assert_eq!(g.nodes.len(), 1);
        assert!(g.root_is_coded());
        assert_eq!(g.nodes[0].kind, DerivationKind::Coded);
        assert_eq!(g.nodes[0].reconstructed_dims, Some((640, 480)));
        assert_eq!(g.nodes[0].output_dims, Some((640, 480)));
        assert_eq!(g.output_dims(), Some((640, 480)));
        assert_eq!(g.coded_leaf_ids, vec![1]);
        assert_eq!(g.derived_node_count(), 0);
        assert!(!g.truncated);
    }

    /// A 2×2 grid primary: one `Grid` root + four `Coded` tiles. The decode
    /// set is the four tiles in row-major order; the canvas is the grid
    /// descriptor's output size.
    #[test]
    fn derivation_graph_grid_root_lists_tiles() {
        let desc = build_grid_desc(2, 2, 200, 200);
        let idat = desc.clone();
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"grid"),
                geo_ii(2, b"av01"),
                geo_ii(3, b"av01"),
                geo_ii(4, b"av01"),
                geo_ii(5, b"av01"),
            ],
            properties: vec![ispe_prop(100, 100)],
            associations: vec![
                geo_assoc(2, &[0]),
                geo_assoc(3, &[0]),
                geo_assoc(4, &[0]),
                geo_assoc(5, &[0]),
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"dimg",
                from_id: 1,
                to_ids: vec![2, 3, 4, 5],
            }],
            locations: vec![ItemLocation {
                id: 1,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: desc.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        let g = build_derivation_graph(&meta, 1, &[], Some(&idat));
        assert!(!g.root_is_coded());
        assert_eq!(g.nodes[0].kind, DerivationKind::Grid);
        assert_eq!(g.nodes[0].inputs, vec![2, 3, 4, 5]);
        assert_eq!(g.output_dims(), Some((200, 200)));
        assert_eq!(g.coded_leaf_ids, vec![2, 3, 4, 5]);
        assert_eq!(g.nodes.len(), 5);
        assert_eq!(g.derived_node_count(), 1);
        // The tiles sit at depth 1, the grid at depth 0.
        assert_eq!(g.node(1).unwrap().depth, 0);
        assert_eq!(g.node(2).unwrap().depth, 1);
    }

    /// Nested derivation: an `iden` crop (via `clap`) of a 2×2 grid. The
    /// walk descends iden → grid → tiles, the root output folds the iden's
    /// own `clap`, and the decode set is still the four grid tiles.
    #[test]
    fn derivation_graph_iden_over_grid_nests() {
        let desc = build_grid_desc(2, 2, 200, 200);
        let idat = desc.clone();
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"iden"),
                geo_ii(2, b"grid"),
                geo_ii(3, b"av01"),
                geo_ii(4, b"av01"),
                geo_ii(5, b"av01"),
                geo_ii(6, b"av01"),
            ],
            // property 0 = tile ispe; property 1 = iden's clap crop to 150×120.
            properties: vec![
                ispe_prop(100, 100),
                MProp::Clap(MClap {
                    clean_aperture_width_n: 150,
                    clean_aperture_width_d: 1,
                    clean_aperture_height_n: 120,
                    clean_aperture_height_d: 1,
                    horiz_off_n: 0,
                    horiz_off_d: 1,
                    vert_off_n: 0,
                    vert_off_d: 1,
                }),
            ],
            associations: vec![
                geo_assoc(1, &[1]), // iden carries the clap
                geo_assoc(3, &[0]),
                geo_assoc(4, &[0]),
                geo_assoc(5, &[0]),
                geo_assoc(6, &[0]),
            ],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![3, 4, 5, 6],
                },
            ],
            locations: vec![ItemLocation {
                id: 2,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: desc.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        let g = build_derivation_graph(&meta, 1, &[], Some(&idat));
        assert_eq!(g.nodes[0].kind, DerivationKind::Identity);
        // iden reconstructed = grid output (200×200); iden output = clap crop.
        assert_eq!(g.nodes[0].reconstructed_dims, Some((200, 200)));
        assert_eq!(g.nodes[0].output_dims, Some((150, 120)));
        assert_eq!(g.output_dims(), Some((150, 120)));
        // Decode set is the four tiles, in row-major order.
        assert_eq!(g.coded_leaf_ids, vec![3, 4, 5, 6]);
        // Depth ordering: iden(0) → grid(1) → tiles(2).
        assert_eq!(g.node(1).unwrap().depth, 0);
        assert_eq!(g.node(2).unwrap().depth, 1);
        assert_eq!(g.node(3).unwrap().depth, 2);
        assert_eq!(g.derived_node_count(), 2);
    }

    /// A diamond graph — two `iden` derivations sharing one coded leaf via
    /// an `iovl` — lists the shared leaf exactly once in the decode set.
    #[test]
    fn derivation_graph_diamond_dedups_shared_leaf() {
        // overlay(1) → iden(2), iden(3); both iden → coded(4).
        let ovl = {
            let mut b = vec![0u8, 0u8]; // version, flags (16-bit)
            b.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); // canvas fill RGBA
            b.extend_from_slice(&100u16.to_be_bytes()); // output_width
            b.extend_from_slice(&100u16.to_be_bytes()); // output_height
            b.extend_from_slice(&0i16.to_be_bytes()); // h offset 0
            b.extend_from_slice(&0i16.to_be_bytes()); // v offset 0
            b.extend_from_slice(&0i16.to_be_bytes()); // h offset 1
            b.extend_from_slice(&0i16.to_be_bytes()); // v offset 1
            b
        };
        let idat = ovl.clone();
        let meta = MMeta {
            items: vec![
                geo_ii(1, b"iovl"),
                geo_ii(2, b"iden"),
                geo_ii(3, b"iden"),
                geo_ii(4, b"av01"),
            ],
            properties: vec![ispe_prop(50, 50)],
            associations: vec![geo_assoc(4, &[0])],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2, 3],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![4],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 3,
                    to_ids: vec![4],
                },
            ],
            locations: vec![ItemLocation {
                id: 1,
                construction_method: 1,
                data_reference_index: 0,
                base_offset: 0,
                extents: vec![IlocExtent {
                    offset: 0,
                    length: ovl.len() as u64,
                    extent_index: 0,
                }],
            }],
            ..MMeta::default()
        };
        let g = build_derivation_graph(&meta, 1, &[], Some(&idat));
        assert_eq!(g.nodes[0].kind, DerivationKind::Overlay);
        // Both idens reachable, shared leaf listed once.
        assert_eq!(g.coded_leaf_ids, vec![4]);
        // 4 distinct nodes (iovl, iden×2, coded) — the leaf is not duplicated.
        assert_eq!(g.nodes.len(), 4);
        assert_eq!(g.derived_node_count(), 3);
        assert!(!g.truncated);
        // Decode-buffer sizing: the single shared leaf is 50×50.
        assert_eq!(g.coded_leaf_dims(), vec![(4, Some((50, 50)))]);
        // Depth layers: overlay at 0, both idens at 1, leaf at 2.
        assert_eq!(g.nodes_at_depth(0), vec![1]);
        assert_eq!(g.nodes_at_depth(1), vec![2, 3]);
        assert_eq!(g.nodes_at_depth(2), vec![4]);
    }

    /// A `dimg` cycle terminates the walk at the depth bound and sets the
    /// `truncated` flag rather than recursing forever.
    #[test]
    fn derivation_graph_cycle_terminates_and_flags_truncation() {
        // iden(1) → iden(2) → iden(1) — a 2-cycle.
        let meta = MMeta {
            items: vec![geo_ii(1, b"iden"), geo_ii(2, b"iden")],
            irefs: vec![
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 1,
                    to_ids: vec![2],
                },
                IrefEntry {
                    reference_type: *b"dimg",
                    from_id: 2,
                    to_ids: vec![1],
                },
            ],
            ..MMeta::default()
        };
        let g = build_derivation_graph(&meta, 1, &[], None);
        // Each item visited once; the back-edge to an already-visited node
        // is dropped, so only two nodes and no coded leaves.
        assert_eq!(g.nodes.len(), 2);
        assert!(g.coded_leaf_ids.is_empty());
        // Geometry is unresolvable (no coded leaf) but the walk still
        // terminated cleanly.
        assert_eq!(g.output_dims(), None);
    }

    /// A `tmap` with no `dimg` inputs at all resolves to no dimensions and
    /// an empty geometry record (defensive — malformed file).
    #[test]
    fn resolve_tone_maps_handles_inputless_tmap() {
        let meta = MMeta {
            items: vec![geo_ii(1, b"tmap")],
            ..MMeta::default()
        };
        let r = &resolve_tone_maps(&meta, &[], None)[0];
        assert_eq!(r.base_item_id, None);
        assert!(r.gain_map_item_ids.is_empty());
        assert_eq!(r.rendered_dims, None);
        assert!(!r.upsamples_gain_map());
        assert_eq!(reconstructed_dims(&meta, 1, &[], None), None);
    }

    // -----------------------------------------------------------------------
    // Property / fuzz tests for the box-parsing surface
    // -----------------------------------------------------------------------
    //
    // These hammer the descriptor parsers and the geometry resolver with
    // pseudo-random and adversarially-shaped byte inputs. The contract under
    // test is **total**: a parser must return `Ok(_)` or `Err(_)` and never
    // panic (no slice-index OOB, no integer overflow in debug, no
    // unbounded recursion) for *any* input. The PRNG is a deterministic
    // splitmix64 so a failure reproduces from the printed seed.

    /// Deterministic splitmix64 — no external crate, reproducible from seed.
    struct SplitMix64(u64);

    impl SplitMix64 {
        fn next(&mut self) -> u64 {
            self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = self.0;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^ (z >> 31)
        }

        /// A pseudo-random byte vector of length `0..=max_len`.
        fn bytes(&mut self, max_len: usize) -> Vec<u8> {
            let len = (self.next() as usize) % (max_len + 1);
            (0..len).map(|_| (self.next() & 0xff) as u8).collect()
        }
    }

    /// `ImageOverlay::parse` is total over arbitrary bytes × arbitrary
    /// reference counts — it never panics, only returns `Ok`/`Err`.
    #[test]
    fn fuzz_image_overlay_parse_is_total() {
        let mut rng = SplitMix64(0x0AF1_2026_0341_0001);
        for _ in 0..20_000 {
            let buf = rng.bytes(48);
            let refs = (rng.next() as usize) % 8;
            // Must not panic regardless of input.
            let _ = ImageOverlay::parse(&buf, refs);
        }
    }

    /// `GainMapMetadata::parse` (ISO 21496-1 Annex C.2) is total — random
    /// payloads must not panic on the flag byte, version bounds, or the
    /// per-channel rational reads.
    #[test]
    fn fuzz_gain_map_metadata_parse_is_total() {
        let mut rng = SplitMix64(0x0AF1_2026_0341_0002);
        for _ in 0..20_000 {
            let buf = rng.bytes(160);
            let _ = GainMapMetadata::parse(&buf);
        }
    }

    /// `SampleTransform::parse` (av1-avif §4.2.3) is total over random
    /// descriptor bytes × reference counts — the postfix token stream
    /// validation must reject malformed input without panicking.
    #[test]
    fn fuzz_sample_transform_parse_is_total() {
        let mut rng = SplitMix64(0x0AF1_2026_0341_0003);
        for _ in 0..20_000 {
            let buf = rng.bytes(64);
            let refs = (rng.next() % 8) as u32;
            let _ = SampleTransform::parse(&buf, refs);
        }
    }

    /// `parse_grpl` (HEIF §9.4 EntityToGroupBox container) is total over
    /// random `grpl` payloads.
    #[test]
    fn fuzz_parse_grpl_is_total() {
        let mut rng = SplitMix64(0x0AF1_2026_0341_0004);
        for _ in 0..20_000 {
            let buf = rng.bytes(80);
            let _ = parse_grpl(&buf);
        }
    }

    /// The geometry resolver is total over a randomly-shaped item graph:
    /// `resolve_overlays`, `resolve_iden_derivations`, and
    /// `reconstructed_dims` must terminate (cycle guard) and never panic
    /// for any meta layout × backing buffer.
    #[test]
    fn fuzz_geometry_resolver_is_total() {
        let mut rng = SplitMix64(0x0AF1_2026_0341_0005);
        let types: [&[u8; 4]; 5] = [b"av01", b"grid", b"iovl", b"iden", b"sato"];
        for _ in 0..5_000 {
            let item_count = 1 + (rng.next() as usize % 6);
            let mut items = Vec::new();
            let mut properties = Vec::new();
            let mut associations = Vec::new();
            let mut irefs = Vec::new();
            let mut locations = Vec::new();
            for i in 0..item_count {
                let id = (i + 1) as u32;
                let t = types[(rng.next() as usize) % types.len()];
                items.push(geo_ii(id, t));
                // Random ispe property + association.
                let w = (rng.next() % 600) as u32;
                let h = (rng.next() % 600) as u32;
                properties.push(ispe_prop(w, h));
                associations.push(geo_assoc(id, &[(properties.len() - 1) as u16]));
                // A random dimg edge to another (possibly self → cycle).
                if rng.next() & 1 == 0 {
                    let to = 1 + (rng.next() as u32 % item_count as u32);
                    irefs.push(IrefEntry {
                        reference_type: *b"dimg",
                        from_id: id,
                        to_ids: vec![to],
                    });
                }
                // A random idat-backed location.
                if rng.next() & 1 == 0 {
                    locations.push(ItemLocation {
                        id,
                        construction_method: (rng.next() % 3) as u8,
                        data_reference_index: 0,
                        base_offset: rng.next() % 64,
                        extents: vec![IlocExtent {
                            offset: rng.next() % 64,
                            length: rng.next() % 64,
                            extent_index: 0,
                        }],
                    });
                }
            }
            let meta = MMeta {
                items,
                properties,
                associations,
                irefs,
                locations,
                ..MMeta::default()
            };
            let file = rng.bytes(128);
            let idat = rng.bytes(128);
            // None of these may panic or fail to terminate.
            let _ = resolve_overlays(&meta, &file, Some(&idat));
            let _ = resolve_iden_derivations(&meta, &file, Some(&idat));
            let _ = resolve_grids(&meta, &file, Some(&idat));
            let _ = resolve_tone_maps(&meta, &file, Some(&idat));
            for id in 1..=item_count as u32 {
                let _ = reconstructed_dims(&meta, id, &file, Some(&idat));
                // The unified graph walk must also be total: it terminates on
                // any cyclic / adversarial dimg shape, visits each item once
                // (no duplicate nodes), and never lists a coded leaf twice.
                let g = build_derivation_graph(&meta, id, &file, Some(&idat));
                let mut seen = std::collections::BTreeSet::new();
                for n in &g.nodes {
                    assert!(seen.insert(n.item_id), "duplicate node {}", n.item_id);
                    assert!(n.depth <= MAX_DERIVATION_DEPTH);
                }
                let mut leaves = std::collections::BTreeSet::new();
                for &leaf in &g.coded_leaf_ids {
                    assert!(leaves.insert(leaf), "duplicate coded leaf {leaf}");
                }
            }
        }
    }

    // -----------------------------------------------------------------
    // 'pred' brand file-constraint audit (HEIF §10.2.4)
    // -----------------------------------------------------------------

    /// No `'pred'` claim ⇒ trivially compliant regardless of content.
    #[test]
    fn pred_audit_no_claim_is_compliant() {
        let meta = Meta {
            items: vec![make_infe(1, b"av01", 0)],
            ..Meta::default()
        };
        let c = audit_pred_brand(&meta, &[b(b"avif"), b(b"mif1")]);
        assert!(!c.claims_pred);
        assert!(c.is_compliant());
        assert!(c.missing().is_empty());
    }

    /// A predictively coded item whose `'pred'` dependencies are all
    /// present passes the §10.2.4.2 closure `shall`.
    #[test]
    fn pred_audit_closure_satisfied() {
        let meta = Meta {
            primary_item_id: Some(1),
            items: vec![
                make_infe(1, b"av01", 0), // primary, independently coded
                make_infe(2, b"av01", 0), // P-frame item
                make_infe(3, b"av01", 0), // its dependency
            ],
            irefs: vec![IrefEntry {
                reference_type: *b"pred",
                from_id: 2,
                to_ids: vec![1, 3],
            }],
            ..Meta::default()
        };
        let c = audit_pred_brand(&meta, &[b(b"avif"), b(b"pred")]);
        assert!(c.claims_pred);
        assert_eq!(c.predictive_item_count, 1);
        assert!(c.missing_dependency_ids.is_empty());
        assert!(c.is_compliant());
    }

    /// A `'pred'` dependency naming an item absent from `iinf` is a
    /// closure violation.
    #[test]
    fn pred_audit_missing_dependency_flagged() {
        let meta = Meta {
            primary_item_id: Some(1),
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"pred",
                from_id: 2,
                to_ids: vec![1, 99], // 99 not present
            }],
            ..Meta::default()
        };
        let c = audit_pred_brand(&meta, &[b(b"pred")]);
        assert_eq!(c.missing_dependency_ids, vec![99]);
        assert!(!c.is_compliant());
        assert!(c.missing().contains(&"pred-dependency-closure"));
    }

    /// When `'mif1'` is also claimed, a primary item carrying a `'pred'`
    /// reference (not independently coded) violates §10.2.4.2.
    #[test]
    fn pred_audit_mif1_primary_must_be_independent() {
        let meta = Meta {
            primary_item_id: Some(1),
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"pred",
                from_id: 1, // primary is itself predictively coded
                to_ids: vec![2],
            }],
            ..Meta::default()
        };
        let c = audit_pred_brand(&meta, &[b(b"mif1"), b(b"pred")]);
        assert!(c.claims_mif1 && c.claims_pred);
        assert!(c.primary_not_independent);
        assert!(!c.is_compliant());
        assert!(c.missing().contains(&"mif1-primary-independent"));
    }

    /// Without the `'mif1'` claim a predictively coded primary is allowed
    /// (§10.2.4.2 NOTE), so only the closure `shall` applies.
    #[test]
    fn pred_audit_no_mif1_allows_predictive_primary() {
        let meta = Meta {
            primary_item_id: Some(1),
            items: vec![make_infe(1, b"av01", 0), make_infe(2, b"av01", 0)],
            irefs: vec![IrefEntry {
                reference_type: *b"pred",
                from_id: 1,
                to_ids: vec![2],
            }],
            ..Meta::default()
        };
        let c = audit_pred_brand(&meta, &[b(b"pred")]);
        assert!(!c.claims_mif1);
        assert!(!c.primary_not_independent);
        assert!(c.is_compliant());
    }
}