heic 0.1.3

Pure Rust HEIC/HEIF image decoder with SIMD acceleration
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
//! Internal decode pipeline: grid assembly, overlay compositing,
//! alpha plane extraction, metadata extraction, and gain map decoding.

use alloc::borrow::Cow;
use alloc::vec::Vec;

use enough::{Stop, Unstoppable};

use whereat::at;

use crate::error::check_stop;
use crate::heif::{self, CleanAperture, ColorInfo, FourCC, ItemType, Transform};
use crate::{
    DecodeOutput, DecoderConfig, HdrGainMap, HeicError, Limits, PixelLayout, Result, floor_f64,
    round_f64,
};

#[cfg(feature = "parallel")]
use rayon::prelude::*;

/// Decode a collection of tile data in parallel or sequentially depending on
/// `max_threads` and the `parallel` feature.
///
/// When `parallel` is enabled and `max_threads != Some(1)`, uses rayon
/// parallelism scoped to the requested thread count. Otherwise falls back
/// to sequential iteration.
#[cfg(feature = "parallel")]
fn decode_tiles_parallel(
    tile_data_list: &[Cow<'_, [u8]>],
    tile_config: &crate::heif::HevcDecoderConfig,
    max_threads: Option<usize>,
) -> Result<Vec<crate::hevc::DecodedFrame>> {
    match max_threads {
        Some(1) => {
            // Forced single-threaded
            tile_data_list
                .iter()
                .map(|tile_data| {
                    crate::hevc::decode_with_config(tile_config, tile_data).map_err(Into::into)
                })
                .collect::<Result<_>>()
        }
        Some(n) if n > 1 => {
            // Limited thread pool
            let pool = rayon::ThreadPoolBuilder::new()
                .num_threads(n)
                .build()
                .map_err(|_| at!(HeicError::InvalidData("failed to create thread pool")))?;
            pool.install(|| {
                tile_data_list
                    .par_iter()
                    .map(|tile_data| {
                        crate::hevc::decode_with_config(tile_config, tile_data).map_err(Into::into)
                    })
                    .collect::<Result<_>>()
            })
        }
        _ => {
            // Unlimited: use global rayon pool
            tile_data_list
                .par_iter()
                .map(|tile_data| {
                    crate::hevc::decode_with_config(tile_config, tile_data).map_err(Into::into)
                })
                .collect::<Result<_>>()
        }
    }
}

/// Sentinel for no limits
static NO_LIMITS: Limits = Limits {
    max_width: None,
    max_height: None,
    max_pixels: None,
    max_memory_bytes: None,
};

/// Core decode-to-frame implementation shared by all entry points.
pub(crate) fn decode_to_frame(
    data: &[u8],
    limits: Option<&Limits>,
    stop: &dyn Stop,
    max_threads: Option<usize>,
) -> Result<crate::hevc::DecodedFrame> {
    let limits = limits.unwrap_or(&NO_LIMITS);

    check_stop(stop)?;

    let container = heif::parse(data, stop)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    // Check limits on primary item dimensions if available from ispe
    if let Some((w, h)) = primary_item.dimensions {
        limits.check_dimensions(w, h)?;
        // Estimate memory before allocating frames
        let estimated = DecoderConfig::estimate_memory(w, h, PixelLayout::Rgba8);
        limits.check_memory(estimated)?;
    }

    check_stop(stop)?;

    let mut frame = decode_item(&container, &primary_item, 0, limits, stop, max_threads)?;

    check_stop(stop)?;

    // Try to decode alpha plane from auxiliary image.
    let alpha_id = container
        .find_auxiliary_items(primary_item.id, "urn:mpeg:hevc:2015:auxid:1")
        .first()
        .copied()
        .or_else(|| {
            container
                .find_auxiliary_items(
                    primary_item.id,
                    "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha",
                )
                .first()
                .copied()
        });
    if let Some(alpha_id) = alpha_id
        && let Some(alpha_plane) = decode_alpha_plane(&container, alpha_id, &frame, limits, stop)
    {
        frame.alpha_plane = Some(alpha_plane);
    }

    Ok(frame)
}

/// Decode an item, handling derived image types (iden, grid, iovl).
/// Applies the item's own transforms (clap, irot, imir) after decoding.
fn decode_item(
    container: &heif::HeifContainer<'_>,
    item: &heif::Item,
    depth: u32,
    limits: &Limits,
    stop: &dyn Stop,
    max_threads: Option<usize>,
) -> Result<crate::hevc::DecodedFrame> {
    if depth > 8 {
        return Err(at!(HeicError::InvalidData(
            "Derived image reference chain too deep"
        )));
    }

    check_stop(stop)?;

    let mut frame = match item.item_type {
        ItemType::Grid => decode_grid(container, item, depth, limits, stop, max_threads)?,
        ItemType::Iden => decode_iden(container, item, depth, limits, stop, max_threads)?,
        ItemType::Iovl => decode_iovl(container, item, depth, limits, stop, max_threads)?,
        ItemType::Hvc1 | ItemType::Unknown(_) => {
            // HEVC path — Unknown falls through to HEVC for backwards compat
            // Check limits before HEVC decode to avoid OOM from crafted SPS
            if let Some((w, h)) = item.dimensions {
                limits.check_dimensions(w, h)?;
            }
            let image_data = container.get_item_data(item.id)?;
            if let Some(ref config) = item.hevc_config {
                crate::hevc::decode_with_config(config, &image_data)?
            } else if item.item_type == ItemType::Hvc1 {
                crate::hevc::decode(&image_data)?
            } else {
                return Err(at!(HeicError::UnsupportedCodec(
                    "unknown item type with no decoder config"
                )));
            }
        }
        ItemType::Av01 => {
            #[cfg(feature = "av1")]
            {
                let image_data = container.get_item_data(item.id)?;
                decode_av1_item(item, &image_data, limits, stop)?
            }
            #[cfg(not(feature = "av1"))]
            {
                return Err(at!(HeicError::UnsupportedCodec(
                    "AV1 codec requires the 'av1' feature"
                )));
            }
        }
        ItemType::Unci => {
            #[cfg(feature = "unci")]
            {
                let image_data = container.get_item_data(item.id)?;
                decode_unci_item(item, &image_data, limits, stop)?
            }
            #[cfg(not(feature = "unci"))]
            {
                return Err(at!(HeicError::UnsupportedCodec(
                    "uncompressed HEIF requires the 'unci' feature"
                )));
            }
        }
        ItemType::Avc1 => {
            return Err(at!(HeicError::UnsupportedCodec(
                "H.264/AVC codec not supported"
            )));
        }
        ItemType::Jpeg => {
            return Err(at!(HeicError::UnsupportedCodec("JPEG codec not supported")));
        }
        ItemType::Exif | ItemType::Mime => {
            return Err(at!(HeicError::InvalidData(
                "metadata item type cannot be decoded as image"
            )));
        }
    };

    // Set color conversion parameters from colr nclx box if present.
    if let Some(ColorInfo::Nclx {
        full_range,
        matrix_coefficients,
        color_primaries,
        transfer_characteristics,
    }) = &item.color_info
    {
        frame.full_range = *full_range;
        frame.matrix_coeffs = *matrix_coefficients as u8;
        frame.color_primaries = *color_primaries as u8;
        frame.transfer_characteristics = *transfer_characteristics as u8;
    }

    // Apply transformative properties in ipma listing order (HEIF spec requirement)
    for transform in &item.transforms {
        match transform {
            Transform::CleanAperture(clap) => {
                apply_clean_aperture(&mut frame, clap);
            }
            Transform::Mirror(mirror) => {
                frame = match mirror.axis {
                    0 => frame.mirror_vertical()?,
                    1 => frame.mirror_horizontal()?,
                    _ => frame,
                };
            }
            Transform::Rotation(rotation) => {
                frame = match rotation.angle {
                    90 => frame.rotate_90_cw()?,
                    180 => frame.rotate_180()?,
                    270 => frame.rotate_270_cw()?,
                    _ => frame,
                };
            }
        }
    }

    Ok(frame)
}

/// Decode an identity-derived image by following dimg references.
fn decode_iden(
    container: &heif::HeifContainer<'_>,
    iden_item: &heif::Item,
    depth: u32,
    limits: &Limits,
    stop: &dyn Stop,
    max_threads: Option<usize>,
) -> Result<crate::hevc::DecodedFrame> {
    let source_ids = container.get_item_references(iden_item.id, FourCC::DIMG);
    let source_id = source_ids
        .first()
        .ok_or_else(|| at!(HeicError::InvalidData("iden item has no dimg reference")))?;

    let source_item = container
        .get_item(*source_id)
        .ok_or_else(|| at!(HeicError::InvalidData("iden dimg target item not found")))?;

    decode_item(
        container,
        &source_item,
        depth + 1,
        limits,
        stop,
        max_threads,
    )
}

/// Decode an image overlay (iovl) by compositing referenced tiles onto a canvas.
fn decode_iovl(
    container: &heif::HeifContainer<'_>,
    iovl_item: &heif::Item,
    depth: u32,
    limits: &Limits,
    stop: &dyn Stop,
    max_threads: Option<usize>,
) -> Result<crate::hevc::DecodedFrame> {
    let iovl_data = container.get_item_data(iovl_item.id)?;

    // Parse iovl descriptor:
    // - version (1 byte) + flags (3 bytes)
    // - canvas_fill_value: 2 bytes * num_channels (flags & 0x01 determines 32-bit offsets)
    if iovl_data.len() < 6 {
        return Err(at!(HeicError::InvalidData("Overlay descriptor too short")));
    }

    let flags = iovl_data[1];
    let large = (flags & 1) != 0;

    let tile_ids = container.get_item_references(iovl_item.id, FourCC::DIMG);
    if tile_ids.is_empty() {
        return Err(at!(HeicError::InvalidData(
            "Overlay has no tile references"
        )));
    }

    // Calculate expected layout
    let off_size = if large { 4usize } else { 2 };
    let per_tile = 2 * off_size;
    let fixed_end = 4 + 2 * off_size; // version/flags + width/height
    let tile_data_size = tile_ids.len() * per_tile;
    let fill_bytes = iovl_data
        .len()
        .checked_sub(fixed_end + tile_data_size)
        .ok_or_else(|| {
            at!(HeicError::InvalidData(
                "Overlay descriptor too short for tiles",
            ))
        })?;

    // Parse canvas fill values (16-bit per channel)
    let num_fill_channels = fill_bytes / 2;
    let mut fill_values = [0u16; 4];
    for i in 0..num_fill_channels.min(4) {
        fill_values[i] = u16::from_be_bytes([iovl_data[4 + i * 2], iovl_data[4 + i * 2 + 1]]);
    }

    let mut pos = 4 + fill_bytes;

    // Read canvas dimensions
    let (canvas_width, canvas_height) = if large {
        if pos + 8 > iovl_data.len() {
            return Err(at!(HeicError::InvalidData("Overlay descriptor truncated")));
        }
        let w = u32::from_be_bytes([
            iovl_data[pos],
            iovl_data[pos + 1],
            iovl_data[pos + 2],
            iovl_data[pos + 3],
        ]);
        let h = u32::from_be_bytes([
            iovl_data[pos + 4],
            iovl_data[pos + 5],
            iovl_data[pos + 6],
            iovl_data[pos + 7],
        ]);
        pos += 8;
        (w, h)
    } else {
        if pos + 4 > iovl_data.len() {
            return Err(at!(HeicError::InvalidData("Overlay descriptor truncated")));
        }
        let w = u16::from_be_bytes([iovl_data[pos], iovl_data[pos + 1]]) as u32;
        let h = u16::from_be_bytes([iovl_data[pos + 2], iovl_data[pos + 3]]) as u32;
        pos += 4;
        (w, h)
    };

    // Check canvas dimensions against limits
    limits.check_dimensions(canvas_width, canvas_height)?;

    // Read per-tile offsets
    let mut offsets = Vec::with_capacity(tile_ids.len());
    for _ in 0..tile_ids.len() {
        let (x, y) = if large {
            if pos + 8 > iovl_data.len() {
                return Err(at!(HeicError::InvalidData("Overlay offset data truncated")));
            }
            let x = i32::from_be_bytes([
                iovl_data[pos],
                iovl_data[pos + 1],
                iovl_data[pos + 2],
                iovl_data[pos + 3],
            ]);
            let y = i32::from_be_bytes([
                iovl_data[pos + 4],
                iovl_data[pos + 5],
                iovl_data[pos + 6],
                iovl_data[pos + 7],
            ]);
            pos += 8;
            (x, y)
        } else {
            if pos + 4 > iovl_data.len() {
                return Err(at!(HeicError::InvalidData("Overlay offset data truncated")));
            }
            let x = i16::from_be_bytes([iovl_data[pos], iovl_data[pos + 1]]) as i32;
            let y = i16::from_be_bytes([iovl_data[pos + 2], iovl_data[pos + 3]]) as i32;
            pos += 4;
            (x, y)
        };
        offsets.push((x, y));
    }

    // Decode first tile to get format info
    let first_tile_item = container
        .get_item(tile_ids[0])
        .ok_or_else(|| at!(HeicError::InvalidData("Missing overlay tile item")))?;

    let (bit_depth, chroma_format) = if let Some(ref config) = first_tile_item.hevc_config {
        (config.bit_depth_luma_minus8 + 8, config.chroma_format)
    } else if let Some(ref config) = first_tile_item.av1_config {
        (config.bit_depth(), config.chroma_format())
    } else {
        // Default to 8-bit 4:2:0 for unknown codecs
        (8u8, 1u8)
    };

    let mut output = crate::hevc::DecodedFrame::with_params(
        canvas_width,
        canvas_height,
        bit_depth,
        chroma_format,
    )?;

    // Apply canvas fill values (16-bit values scaled to bit depth)
    let fill_shift = 16u32.saturating_sub(bit_depth as u32);
    let y_fill = fill_values[0] >> fill_shift;
    let cb_fill = if num_fill_channels > 1 {
        fill_values[1] >> fill_shift
    } else {
        1u16 << (bit_depth - 1) // neutral chroma
    };
    let cr_fill = if num_fill_channels > 2 {
        fill_values[2] >> fill_shift
    } else {
        1u16 << (bit_depth - 1) // neutral chroma
    };
    output.y_plane.fill(y_fill);
    output.cb_plane.fill(cb_fill);
    output.cr_plane.fill(cr_fill);

    // Decode each tile and composite onto the canvas
    for (idx, &tile_id) in tile_ids.iter().enumerate() {
        check_stop(stop)?;

        let tile_item = container
            .get_item(tile_id)
            .ok_or_else(|| at!(HeicError::InvalidData("Missing overlay tile")))?;

        let tile_frame = decode_item(container, &tile_item, depth + 1, limits, stop, max_threads)?;

        // Propagate color conversion settings from first tile
        if idx == 0 {
            output.full_range = tile_frame.full_range;
            output.matrix_coeffs = tile_frame.matrix_coeffs;
        }

        let (off_x, off_y) = offsets[idx];
        let dst_x = off_x.max(0) as u32;
        let dst_y = off_y.max(0) as u32;
        let tile_w = tile_frame.cropped_width();
        let tile_h = tile_frame.cropped_height();

        // Copy luma
        let copy_w = tile_w.min(canvas_width.saturating_sub(dst_x));
        let copy_h = tile_h.min(canvas_height.saturating_sub(dst_y));

        for row in 0..copy_h {
            let src_row = (tile_frame.crop_top + row) as usize;
            let dst_row = (dst_y + row) as usize;
            for col in 0..copy_w {
                let src_col = (tile_frame.crop_left + col) as usize;
                let dst_col = (dst_x + col) as usize;
                let src_idx = src_row * tile_frame.y_stride() + src_col;
                let dst_idx = dst_row * output.y_stride() + dst_col;
                if src_idx < tile_frame.y_plane.len() && dst_idx < output.y_plane.len() {
                    output.y_plane[dst_idx] = tile_frame.y_plane[src_idx];
                }
            }
        }

        // Copy chroma
        if chroma_format > 0 {
            let (sub_x, sub_y) = match chroma_format {
                1 => (2u32, 2u32),
                2 => (2, 1),
                3 => (1, 1),
                _ => (2, 2),
            };
            let c_copy_w = copy_w.div_ceil(sub_x);
            let c_copy_h = copy_h.div_ceil(sub_y);
            let c_dst_x = dst_x / sub_x;
            let c_dst_y = dst_y / sub_y;
            let c_src_x = tile_frame.crop_left / sub_x;
            let c_src_y = tile_frame.crop_top / sub_y;

            let src_c_stride = tile_frame.c_stride();
            let dst_c_stride = output.c_stride();

            for row in 0..c_copy_h {
                let src_row = (c_src_y + row) as usize;
                let dst_row = (c_dst_y + row) as usize;
                for col in 0..c_copy_w {
                    let src_col = (c_src_x + col) as usize;
                    let dst_col = (c_dst_x + col) as usize;
                    let src_idx = src_row * src_c_stride + src_col;
                    let dst_idx = dst_row * dst_c_stride + dst_col;
                    if src_idx < tile_frame.cb_plane.len() && dst_idx < output.cb_plane.len() {
                        output.cb_plane[dst_idx] = tile_frame.cb_plane[src_idx];
                        output.cr_plane[dst_idx] = tile_frame.cr_plane[src_idx];
                    }
                }
            }
        }
    }

    Ok(output)
}

/// Decode an AV1-coded image item using rav1d-safe.
///
/// Prepends the av1C configOBUs to the image data, feeds the combined OBU
/// stream to the rav1d decoder, and converts the resulting frame to a
/// `DecodedFrame` with Y/Cb/Cr planes.
#[cfg(feature = "av1")]
fn decode_av1_item(
    item: &heif::Item,
    image_data: &[u8],
    limits: &Limits,
    stop: &dyn Stop,
) -> Result<crate::hevc::DecodedFrame> {
    use rav1d_safe::src::managed::{Decoder, Planes, Settings};

    let config = item
        .av1_config
        .as_ref()
        .ok_or_else(|| at!(HeicError::InvalidData("AV1 item has no av1C config")))?;

    // Build combined OBU data: config_obus + image_data
    let total_len = config
        .config_obus
        .len()
        .checked_add(image_data.len())
        .ok_or_else(|| at!(HeicError::LimitExceeded("AV1 OBU data size overflow")))?;
    if total_len > 256 * 1024 * 1024 {
        return Err(at!(HeicError::LimitExceeded(
            "AV1 OBU data exceeds 256 MiB"
        )));
    }

    let mut obu_data = Vec::new();
    obu_data
        .try_reserve(total_len)
        .map_err(|_| at!(HeicError::OutOfMemory))?;
    obu_data.extend_from_slice(&config.config_obus);
    obu_data.extend_from_slice(image_data);

    // Pre-decode limits check: use ispe dimensions if available, and feed
    // max_pixels to rav1d's frame_size_limit so it rejects oversized frames
    // during OBU parsing — before allocating the decoded frame.
    if let Some((w, h)) = item.dimensions {
        limits.check_dimensions(w, h)?;
        let estimated = DecoderConfig::estimate_memory(w, h, PixelLayout::Rgba8);
        limits.check_memory(estimated)?;
    }

    check_stop(stop)?;

    // Set rav1d frame_size_limit from user limits so the decoder rejects
    // oversized frames during OBU parsing, before allocating pixel buffers.
    // Set rav1d frame_size_limit from user limits
    let mut settings = Settings::default();
    if let Some(max_pixels) = limits.max_pixels {
        settings.frame_size_limit = max_pixels.min(u32::MAX as u64) as u32;
    }
    let mut decoder = Decoder::with_settings(settings).map_err(|e| {
        at!(HeicError::InvalidData(match e {
            rav1d_safe::src::managed::Error::OutOfMemory => "AV1 decoder init: out of memory",
            _ => "AV1 decoder initialization failed",
        }))
    })?;

    // Feed the OBU data
    let frame_opt = decoder
        .decode(&obu_data)
        .map_err(|_| at!(HeicError::InvalidData("AV1 decode failed")))?;

    // Get the frame — it may come from decode() or flush()
    let frame = if let Some(f) = frame_opt {
        f
    } else {
        // Try flushing to get buffered frames
        let flushed = decoder
            .flush()
            .map_err(|_| at!(HeicError::InvalidData("AV1 flush failed")))?;
        flushed
            .into_iter()
            .next()
            .ok_or_else(|| at!(HeicError::InvalidData("AV1 decoder produced no frames")))?
    };

    let width = frame.width();
    let height = frame.height();
    let bit_depth = frame.bit_depth();

    check_stop(stop)?;

    // Map rav1d PixelLayout to our chroma_format
    let chroma_format = match frame.pixel_layout() {
        rav1d_safe::src::managed::PixelLayout::I400 => 0u8,
        rav1d_safe::src::managed::PixelLayout::I420 => 1,
        rav1d_safe::src::managed::PixelLayout::I422 => 2,
        rav1d_safe::src::managed::PixelLayout::I444 => 3,
    };

    let mut output =
        crate::hevc::DecodedFrame::with_params(width, height, bit_depth, chroma_format)?;

    // Copy planes from rav1d frame to our DecodedFrame
    match frame.planes() {
        Planes::Depth8(planes) => {
            // Copy Y plane
            let y_view = planes.y();
            for y in 0..height as usize {
                let src_row = y_view.row(y);
                let dst_start = y * output.y_stride();
                for (i, &val) in src_row.iter().take(width as usize).enumerate() {
                    output.y_plane[dst_start + i] = val as u16;
                }
            }

            // Copy Cb/Cr planes if not monochrome
            if chroma_format > 0
                && let (Some(cb_view), Some(cr_view)) = (planes.u(), planes.v())
            {
                let c_height = cb_view.height();
                let c_width = cb_view.width();
                for y in 0..c_height {
                    let cb_row = cb_view.row(y);
                    let cr_row = cr_view.row(y);
                    let dst_start = y * output.c_stride();
                    for (i, (&cb, &cr)) in cb_row
                        .iter()
                        .take(c_width)
                        .zip(cr_row.iter().take(c_width))
                        .enumerate()
                    {
                        output.cb_plane[dst_start + i] = cb as u16;
                        output.cr_plane[dst_start + i] = cr as u16;
                    }
                }
            }
        }
        Planes::Depth16(planes) => {
            // Copy Y plane (16-bit)
            let y_view = planes.y();
            for y in 0..height as usize {
                let src_row = y_view.row(y);
                let dst_start = y * output.y_stride();
                for (i, &val) in src_row.iter().take(width as usize).enumerate() {
                    output.y_plane[dst_start + i] = val;
                }
            }

            // Copy Cb/Cr planes if not monochrome
            if chroma_format > 0
                && let (Some(cb_view), Some(cr_view)) = (planes.u(), planes.v())
            {
                let c_height = cb_view.height();
                let c_width = cb_view.width();
                for y in 0..c_height {
                    let cb_row = cb_view.row(y);
                    let cr_row = cr_view.row(y);
                    let dst_start = y * output.c_stride();
                    for (i, (&cb, &cr)) in cb_row
                        .iter()
                        .take(c_width)
                        .zip(cr_row.iter().take(c_width))
                        .enumerate()
                    {
                        output.cb_plane[dst_start + i] = cb;
                        output.cr_plane[dst_start + i] = cr;
                    }
                }
            }
        }
    }

    // Set color info from the AV1 frame
    let color_info = frame.color_info();
    output.full_range = color_info.color_range == rav1d_safe::src::managed::ColorRange::Full;
    output.matrix_coeffs = color_info.matrix_coefficients as u8;
    output.color_primaries = color_info.primaries as u8;
    output.transfer_characteristics = color_info.transfer_characteristics as u8;

    Ok(output)
}

/// Decode an uncompressed HEIF (unci) image item.
///
/// Handles both compressed (deflate/zlib via zenflate) and raw uncompressed
/// pixel data as defined in ISO 23001-17. Supports pixel-interleaved and
/// component-planar layouts for 8-bit unsigned integer components.
#[cfg(feature = "unci")]
fn decode_unci_item(
    item: &heif::Item,
    image_data: &[u8],
    limits: &Limits,
    stop: &dyn Stop,
) -> Result<crate::hevc::DecodedFrame> {
    let unc_config = item
        .uncompressed_config
        .as_ref()
        .ok_or_else(|| at!(HeicError::InvalidData("unci item has no uncC config")))?;

    let (width, height) = item
        .dimensions
        .ok_or_else(|| at!(HeicError::InvalidData("unci item has no dimensions")))?;

    if width == 0 || height == 0 {
        return Err(at!(HeicError::InvalidData("unci item has zero dimensions")));
    }

    // Check limits on unci dimensions before allocating
    limits.check_dimensions(width, height)?;
    let estimated = DecoderConfig::estimate_memory(width, height, PixelLayout::Rgba8);
    limits.check_memory(estimated)?;

    let num_components = unc_config.components.len();
    if num_components == 0 {
        return Err(at!(HeicError::InvalidData("unci item has no components")));
    }

    // Calculate expected decompressed size with overflow checks
    let bits_per_pixel: u32 = unc_config
        .components
        .iter()
        .try_fold(0u32, |acc, c| {
            acc.checked_add(c.component_bit_depth_minus_one as u32 + 1)
        })
        .ok_or_else(|| at!(HeicError::InvalidData("unci bit depth overflow")))?;

    // For now, only support 8-bit unsigned integer components
    let all_8bit = unc_config
        .components
        .iter()
        .all(|c| c.component_bit_depth_minus_one == 7 && c.component_format == 0);
    if !all_8bit {
        return Err(at!(HeicError::Unsupported(
            "unci: only 8-bit unsigned integer components supported"
        )));
    }

    let bytes_per_pixel = bits_per_pixel.div_ceil(8);
    let expected_size = (width as u64)
        .checked_mul(height as u64)
        .and_then(|n| n.checked_mul(bytes_per_pixel as u64))
        .ok_or_else(|| at!(HeicError::LimitExceeded("unci decompressed size overflow")))?;

    // Security: limit decompressed size to min(512 MiB, limits.max_memory_bytes)
    let decompress_cap = limits
        .max_memory_bytes
        .map_or(512 * 1024 * 1024, |m| m.min(512 * 1024 * 1024));
    if expected_size > decompress_cap {
        return Err(at!(HeicError::LimitExceeded(
            "unci decompressed size exceeds limit"
        )));
    }
    let expected_size = expected_size as usize;

    check_stop(stop)?;

    // Decompress if compression config is present
    let pixel_data: alloc::borrow::Cow<'_, [u8]> =
        if let Some(ref cmp_config) = item.compression_config {
            let mut decompressed = Vec::new();
            decompressed
                .try_reserve(expected_size)
                .map_err(|_| at!(HeicError::OutOfMemory))?;
            decompressed.resize(expected_size, 0);

            let mut decompressor = zenflate::Decompressor::new();
            let result = match &cmp_config.compression_type.0 {
                b"defl" => decompressor
                    .deflate_decompress(image_data, &mut decompressed, stop)
                    .map_err(|_| at!(HeicError::InvalidData("unci deflate decompression failed"))),
                b"zlib" => decompressor
                    .zlib_decompress(image_data, &mut decompressed, stop)
                    .map_err(|_| at!(HeicError::InvalidData("unci zlib decompression failed"))),
                _ => {
                    return Err(at!(HeicError::UnsupportedCodec(
                        "unci compression type not supported (only deflate and zlib)"
                    )));
                }
            }?;

            decompressed.truncate(result.output_written);
            alloc::borrow::Cow::Owned(decompressed)
        } else {
            // No compression — use raw data
            alloc::borrow::Cow::Borrowed(image_data)
        };

    if pixel_data.len() < expected_size {
        return Err(at!(HeicError::InvalidData(
            "unci decompressed data smaller than expected"
        )));
    }

    // Create output frame — use RGB (chroma_format=3 = 4:4:4) for unci
    let mut output = crate::hevc::DecodedFrame::with_params(width, height, 8, 3)?;

    // Set full-range since unci pixels are typically full-range
    output.full_range = true;

    // Determine component layout → map component indices to R, G, B channels
    // ISO 23001-17 component_index: 0=Y/R, 1=Cb/G, 2=Cr/B, 3=A, 4=R, 5=G, 6=B
    let interleave = unc_config.interleave_type;

    match interleave {
        0 => {
            // Component-planar: each component stored as a complete plane
            let plane_size = (width as usize) * (height as usize);
            for (comp_idx, comp) in unc_config.components.iter().enumerate() {
                check_stop(stop)?;
                let plane_offset = comp_idx * plane_size;
                if plane_offset + plane_size > pixel_data.len() {
                    return Err(at!(HeicError::InvalidData(
                        "unci component plane extends past data"
                    )));
                }
                let plane_data = &pixel_data[plane_offset..plane_offset + plane_size];

                // Map component_index to Y/Cb/Cr plane
                let target = match comp.component_index {
                    0 | 4 => Some(&mut output.y_plane),  // Y or R
                    1 | 5 => Some(&mut output.cb_plane), // Cb or G
                    2 | 6 => Some(&mut output.cr_plane), // Cr or B
                    _ => None,                           // alpha or unknown — skip
                };

                if let Some(target_plane) = target {
                    for (i, &val) in plane_data.iter().enumerate() {
                        if i < target_plane.len() {
                            target_plane[i] = val as u16;
                        }
                    }
                }
            }
        }
        1 => {
            // Pixel-interleaved: R,G,B,R,G,B,...
            let stride = num_components;
            let mut comp_to_plane: [Option<u8>; 8] = [None; 8];
            for (i, comp) in unc_config.components.iter().enumerate() {
                if i < 8 {
                    comp_to_plane[i] = match comp.component_index {
                        0 | 4 => Some(0), // Y/R
                        1 | 5 => Some(1), // Cb/G
                        2 | 6 => Some(2), // Cr/B
                        _ => None,
                    };
                }
            }

            for y in 0..height as usize {
                check_stop(stop)?;
                for x in 0..width as usize {
                    let pixel_offset = (y * width as usize + x) * stride;
                    if pixel_offset + stride > pixel_data.len() {
                        return Err(at!(HeicError::InvalidData("unci pixel data truncated")));
                    }
                    let dst_idx = y * output.y_stride() + x;
                    for (c, &mapping) in comp_to_plane.iter().enumerate().take(num_components) {
                        if let Some(plane_id) = mapping {
                            let val = pixel_data[pixel_offset + c] as u16;
                            match plane_id {
                                0 => {
                                    if dst_idx < output.y_plane.len() {
                                        output.y_plane[dst_idx] = val;
                                    }
                                }
                                1 => {
                                    if dst_idx < output.cb_plane.len() {
                                        output.cb_plane[dst_idx] = val;
                                    }
                                }
                                2 => {
                                    if dst_idx < output.cr_plane.len() {
                                        output.cr_plane[dst_idx] = val;
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }
        _ => {
            return Err(at!(HeicError::Unsupported(
                "unci interleave type not supported (only component-planar and pixel-interleaved)"
            )));
        }
    }

    // For unci RGB data, set identity matrix (no YCbCr conversion needed)
    // The output planes contain R, G, B directly when component indices are 4, 5, 6
    // or Y, Cb, Cr when indices are 0, 1, 2
    let has_rgb_indices = unc_config
        .components
        .iter()
        .any(|c| c.component_index >= 4 && c.component_index <= 6);

    if has_rgb_indices {
        // Direct RGB in Y/Cb/Cr planes — use identity matrix (0)
        output.matrix_coeffs = 0;
    }

    Ok(output)
}

/// Decode a grid-based HEIC image
fn decode_grid(
    container: &heif::HeifContainer<'_>,
    grid_item: &heif::Item,
    depth: u32,
    limits: &Limits,
    stop: &dyn Stop,
    max_threads: Option<usize>,
) -> Result<crate::hevc::DecodedFrame> {
    // Parse grid descriptor
    let grid_data = container.get_item_data(grid_item.id)?;

    if grid_data.len() < 8 {
        return Err(at!(HeicError::InvalidData("Grid descriptor too short")));
    }

    let flags = grid_data[1];
    let rows = grid_data[2] as u32 + 1;
    let cols = grid_data[3] as u32 + 1;
    let (output_width, output_height) = if (flags & 1) != 0 {
        if grid_data.len() < 12 {
            return Err(at!(HeicError::InvalidData(
                "Grid descriptor too short for 32-bit dims"
            )));
        }
        (
            u32::from_be_bytes([grid_data[4], grid_data[5], grid_data[6], grid_data[7]]),
            u32::from_be_bytes([grid_data[8], grid_data[9], grid_data[10], grid_data[11]]),
        )
    } else {
        (
            u16::from_be_bytes([grid_data[4], grid_data[5]]) as u32,
            u16::from_be_bytes([grid_data[6], grid_data[7]]) as u32,
        )
    };

    // Check grid output dimensions against limits
    limits.check_dimensions(output_width, output_height)?;

    // Get tile item IDs from iref
    let tile_ids = container.get_item_references(grid_item.id, FourCC::DIMG);
    let expected_tiles = (rows * cols) as usize;
    if tile_ids.len() != expected_tiles {
        return Err(at!(HeicError::InvalidData("Grid tile count mismatch")));
    }

    // Get config from the first tile item — supports HEVC, AV1, and unci tiles
    let first_tile = container
        .get_item(tile_ids[0])
        .ok_or_else(|| at!(HeicError::InvalidData("Missing tile item")))?;

    // Determine bit depth and chroma format from the tile's codec config
    let (bit_depth, chroma_format) = if let Some(ref config) = first_tile.hevc_config {
        (config.bit_depth_luma_minus8 + 8, config.chroma_format)
    } else if let Some(ref config) = first_tile.av1_config {
        (config.bit_depth(), config.chroma_format())
    } else if first_tile.uncompressed_config.is_some() {
        // unci tiles: assume 8-bit RGB (chroma_format 3 = 4:4:4)
        let bd = first_tile
            .uncompressed_config
            .as_ref()
            .and_then(|c| c.components.first())
            .map(|c| c.component_bit_depth_minus_one + 1)
            .unwrap_or(8);
        (bd, 3)
    } else {
        return Err(at!(HeicError::InvalidData(
            "Missing tile decoder config (no hvcC, av1C, or uncC)"
        )));
    };

    // Get tile dimensions from ispe
    let (tile_width, tile_height) = first_tile
        .dimensions
        .ok_or_else(|| at!(HeicError::InvalidData("Missing tile dimensions")))?;
    let mut output = crate::hevc::DecodedFrame::with_params(
        output_width,
        output_height,
        bit_depth,
        chroma_format,
    )?;

    // Streaming decode: decode tiles and blit immediately, dropping each tile
    // (or row of tiles) before decoding the next. This keeps peak memory at
    // output + 1 tile (sequential) or output + 1 row of tiles (parallel).
    check_stop(stop)?;
    let tile_data_list: Vec<Cow<'_, [u8]>> = tile_ids
        .iter()
        .map(|&tid| container.get_item_data(tid))
        .collect::<core::result::Result<_, _>>()?;

    // For HEVC grids, use the parallel decode path when available
    let hevc_tile_config = first_tile.hevc_config.as_ref();

    #[cfg(feature = "parallel")]
    {
        if let Some(tile_config) = hevc_tile_config {
            // Parallel HEVC: decode tiles concurrently (respecting max_threads), then blit.
            let all_tiles = decode_tiles_parallel(&tile_data_list, tile_config, max_threads)?;

            for (tile_idx, tile_frame) in all_tiles.iter().enumerate() {
                if tile_idx == 0 {
                    output.full_range = tile_frame.full_range;
                    output.matrix_coeffs = tile_frame.matrix_coeffs;
                }
                blit_tile_to_grid(
                    &mut output,
                    tile_frame,
                    tile_idx,
                    cols,
                    tile_width,
                    tile_height,
                    output_width,
                    output_height,
                    chroma_format,
                );
            }
        } else {
            // Non-HEVC tiles: sequential decode via decode_item per tile
            for (tile_idx, &tile_id) in tile_ids.iter().enumerate() {
                check_stop(stop)?;
                let tile_item = container
                    .get_item(tile_id)
                    .ok_or_else(|| at!(HeicError::InvalidData("Missing grid tile")))?;
                let tile_frame =
                    decode_item(container, &tile_item, depth + 1, limits, stop, max_threads)?;
                if tile_idx == 0 {
                    output.full_range = tile_frame.full_range;
                    output.matrix_coeffs = tile_frame.matrix_coeffs;
                }
                blit_tile_to_grid(
                    &mut output,
                    &tile_frame,
                    tile_idx,
                    cols,
                    tile_width,
                    tile_height,
                    output_width,
                    output_height,
                    chroma_format,
                );
            }
        }
    }

    #[cfg(not(feature = "parallel"))]
    {
        let _ = max_threads; // unused without parallel feature
        // Sequential: decode one tile, blit, drop — only 1 tile in memory at a time.
        for (tile_idx, tile_data) in tile_data_list.iter().enumerate() {
            check_stop(stop)?;
            let tile_frame = if let Some(tile_config) = hevc_tile_config {
                crate::hevc::decode_with_config(tile_config, tile_data)?
            } else {
                // Non-HEVC tiles: look up the tile item and dispatch
                let tile_id = tile_ids[tile_idx];
                let tile_item = container
                    .get_item(tile_id)
                    .ok_or_else(|| at!(HeicError::InvalidData("Missing grid tile")))?;
                decode_item(container, &tile_item, depth + 1, limits, stop, None)?
            };
            if tile_idx == 0 {
                output.full_range = tile_frame.full_range;
                output.matrix_coeffs = tile_frame.matrix_coeffs;
            }
            blit_tile_to_grid(
                &mut output,
                &tile_frame,
                tile_idx,
                cols,
                tile_width,
                tile_height,
                output_width,
                output_height,
                chroma_format,
            );
            // tile_frame dropped here
        }
    }

    Ok(output)
}

/// Copy a single decoded tile into the correct position in the output grid frame.
#[allow(clippy::too_many_arguments)]
fn blit_tile_to_grid(
    output: &mut crate::hevc::DecodedFrame,
    tile: &crate::hevc::DecodedFrame,
    tile_idx: usize,
    cols: u32,
    tile_width: u32,
    tile_height: u32,
    output_width: u32,
    output_height: u32,
    chroma_format: u8,
) {
    let tile_row = tile_idx as u32 / cols;
    let tile_col = tile_idx as u32 % cols;
    let dst_x = tile_col * tile_width;
    let dst_y = tile_row * tile_height;

    // Luma: copy visible portion (clamp to output dimensions)
    let copy_w = tile.cropped_width().min(output_width.saturating_sub(dst_x));
    let copy_h = tile
        .cropped_height()
        .min(output_height.saturating_sub(dst_y));

    let src_y_start = tile.crop_top;
    let src_x_start = tile.crop_left;

    for row in 0..copy_h {
        let src_row = (src_y_start + row) as usize;
        let dst_row = (dst_y + row) as usize;
        for col in 0..copy_w {
            let src_col = (src_x_start + col) as usize;
            let dst_col = (dst_x + col) as usize;

            let src_idx = src_row * tile.y_stride() + src_col;
            let dst_idx = dst_row * output.y_stride() + dst_col;
            output.y_plane[dst_idx] = tile.y_plane[src_idx];
        }
    }

    // Chroma: copy with subsampling
    if chroma_format > 0 {
        let (sub_x, sub_y) = match chroma_format {
            1 => (2u32, 2u32), // 4:2:0
            2 => (2, 1),       // 4:2:2
            3 => (1, 1),       // 4:4:4
            _ => (2, 2),
        };
        let c_copy_w = copy_w.div_ceil(sub_x);
        let c_copy_h = copy_h.div_ceil(sub_y);
        let c_dst_x = dst_x / sub_x;
        let c_dst_y = dst_y / sub_y;
        let c_src_x = src_x_start / sub_x;
        let c_src_y = src_y_start / sub_y;

        let src_c_stride = tile.c_stride();
        let dst_c_stride = output.c_stride();

        for row in 0..c_copy_h {
            let src_row = (c_src_y + row) as usize;
            let dst_row = (c_dst_y + row) as usize;
            for col in 0..c_copy_w {
                let src_col = (c_src_x + col) as usize;
                let dst_col = (c_dst_x + col) as usize;

                let src_idx = src_row * src_c_stride + src_col;
                let dst_idx = dst_row * dst_c_stride + dst_col;
                if src_idx < tile.cb_plane.len() && dst_idx < output.cb_plane.len() {
                    output.cb_plane[dst_idx] = tile.cb_plane[src_idx];
                    output.cr_plane[dst_idx] = tile.cr_plane[src_idx];
                }
            }
        }
    }
}

/// Try to decode a grid image directly into an RGB output buffer,
/// bypassing intermediate full-frame YCbCr assembly.
///
/// Returns `Ok(None)` if the image is not eligible for streaming
/// (not a grid, has transforms, has alpha). Returns `Ok(Some((w, h)))`
/// on success with the streaming path.
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_decode_grid_streaming(
    data: &[u8],
    limits: Option<&Limits>,
    stop: &dyn Stop,
    layout: PixelLayout,
    output: &mut [u8],
    max_threads: Option<usize>,
) -> Result<Option<(u32, u32)>> {
    let limits = limits.unwrap_or(&NO_LIMITS);

    check_stop(stop)?;

    let container = heif::parse(data, stop)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    // Eligibility: must be a grid with no transforms and no alpha
    if primary_item.item_type != ItemType::Grid {
        return Ok(None);
    }
    if !primary_item.transforms.is_empty() {
        return Ok(None);
    }

    // Check for alpha auxiliary image
    let has_alpha = !container
        .find_auxiliary_items(primary_item.id, "urn:mpeg:hevc:2015:auxid:1")
        .is_empty()
        || !container
            .find_auxiliary_items(
                primary_item.id,
                "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha",
            )
            .is_empty();
    if has_alpha {
        return Ok(None);
    }

    // Parse grid descriptor
    let grid_data = container.get_item_data(primary_item.id)?;

    if grid_data.len() < 8 {
        return Err(at!(HeicError::InvalidData("Grid descriptor too short")));
    }

    let flags = grid_data[1];
    let rows = grid_data[2] as u32 + 1;
    let cols = grid_data[3] as u32 + 1;
    let (output_width, output_height) = if (flags & 1) != 0 {
        if grid_data.len() < 12 {
            return Err(at!(HeicError::InvalidData(
                "Grid descriptor too short for 32-bit dims"
            )));
        }
        (
            u32::from_be_bytes([grid_data[4], grid_data[5], grid_data[6], grid_data[7]]),
            u32::from_be_bytes([grid_data[8], grid_data[9], grid_data[10], grid_data[11]]),
        )
    } else {
        (
            u16::from_be_bytes([grid_data[4], grid_data[5]]) as u32,
            u16::from_be_bytes([grid_data[6], grid_data[7]]) as u32,
        )
    };

    limits.check_dimensions(output_width, output_height)?;

    // Check output buffer size
    let bpp = layout.bytes_per_pixel();
    let required = (output_width as usize)
        .checked_mul(output_height as usize)
        .and_then(|n| n.checked_mul(bpp))
        .ok_or_else(|| {
            at!(HeicError::LimitExceeded(
                "output buffer size overflows usize",
            ))
        })?;
    if output.len() < required {
        return Err(at!(HeicError::BufferTooSmall {
            required,
            actual: output.len(),
        }));
    }

    // Get tile info
    let tile_ids = container.get_item_references(primary_item.id, FourCC::DIMG);
    let expected_tiles = (rows * cols) as usize;
    if tile_ids.len() != expected_tiles {
        return Err(at!(HeicError::InvalidData("Grid tile count mismatch")));
    }

    let first_tile = container
        .get_item(tile_ids[0])
        .ok_or_else(|| at!(HeicError::InvalidData("Missing tile item")))?;

    // Streaming grid path only supports HEVC tiles
    let tile_config = match first_tile.hevc_config.as_ref() {
        Some(config) => config,
        None => return Ok(None),
    };

    let (tile_width, tile_height) = first_tile
        .dimensions
        .ok_or_else(|| at!(HeicError::InvalidData("Missing tile dimensions")))?;

    // Determine color conversion overrides from grid item's colr nclx
    let color_override = match &primary_item.color_info {
        Some(ColorInfo::Nclx {
            full_range,
            matrix_coefficients,
            ..
        }) => Some((*full_range, *matrix_coefficients as u8)),
        _ => None,
    };

    // Collect tile data
    check_stop(stop)?;
    let tile_data_list: Vec<Cow<'_, [u8]>> = tile_ids
        .iter()
        .map(|&tid| container.get_item_data(tid))
        .collect::<core::result::Result<_, _>>()?;

    // Stream tiles: decode, color-convert directly to output, drop
    #[cfg(feature = "parallel")]
    {
        let cols_usize = cols as usize;
        for row in 0..rows {
            let row_start = row as usize * cols_usize;
            let row_end = row_start + cols_usize;
            let row_tiles = decode_tiles_parallel(
                &tile_data_list[row_start..row_end],
                tile_config,
                max_threads,
            )?;

            for (col, mut tile_frame) in row_tiles.into_iter().enumerate() {
                let tile_idx = row as usize * cols_usize + col;
                if let Some((fr, mc)) = color_override {
                    tile_frame.full_range = fr;
                    tile_frame.matrix_coeffs = mc;
                }
                let dst_x = col as u32 * tile_width;
                let dst_y = row * tile_height;
                let copy_w = tile_frame
                    .cropped_width()
                    .min(output_width.saturating_sub(dst_x));
                let copy_h = tile_frame
                    .cropped_height()
                    .min(output_height.saturating_sub(dst_y));
                convert_tile_to_output(
                    &tile_frame,
                    output,
                    layout,
                    dst_x,
                    dst_y,
                    copy_w,
                    copy_h,
                    output_width,
                );
                let _ = tile_idx; // suppress unused warning
            }
        }
    }

    #[cfg(not(feature = "parallel"))]
    {
        let _ = max_threads; // unused without parallel feature
        for (tile_idx, tile_data) in tile_data_list.iter().enumerate() {
            check_stop(stop)?;
            let mut tile_frame = crate::hevc::decode_with_config(tile_config, tile_data)?;
            if let Some((fr, mc)) = color_override {
                tile_frame.full_range = fr;
                tile_frame.matrix_coeffs = mc;
            }
            let tile_col = tile_idx as u32 % cols;
            let tile_row = tile_idx as u32 / cols;
            let dst_x = tile_col * tile_width;
            let dst_y = tile_row * tile_height;
            let copy_w = tile_frame
                .cropped_width()
                .min(output_width.saturating_sub(dst_x));
            let copy_h = tile_frame
                .cropped_height()
                .min(output_height.saturating_sub(dst_y));
            convert_tile_to_output(
                &tile_frame,
                output,
                layout,
                dst_x,
                dst_y,
                copy_w,
                copy_h,
                output_width,
            );
        }
    }

    Ok(Some((output_width, output_height)))
}

/// Try to decode a grid image with row-level streaming to a sink.
///
/// Calls [`RowSink::demand()`](crate::RowSink::demand) for each tile-row and
/// writes color-converted pixels directly. Returns `Ok(None)` if the image
/// is not eligible for streaming (not a grid, has transforms, has alpha).
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_decode_grid_to_sink(
    data: &[u8],
    limits: Option<&Limits>,
    stop: &dyn Stop,
    layout: PixelLayout,
    sink: &mut dyn crate::RowSink,
    max_threads: Option<usize>,
) -> Result<Option<(u32, u32)>> {
    let limits = limits.unwrap_or(&NO_LIMITS);

    check_stop(stop)?;

    let container = heif::parse(data, stop)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    // Eligibility: must be a grid with no transforms and no alpha
    if primary_item.item_type != ItemType::Grid {
        return Ok(None);
    }
    if !primary_item.transforms.is_empty() {
        return Ok(None);
    }

    // Check for alpha auxiliary image
    let has_alpha = !container
        .find_auxiliary_items(primary_item.id, "urn:mpeg:hevc:2015:auxid:1")
        .is_empty()
        || !container
            .find_auxiliary_items(
                primary_item.id,
                "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha",
            )
            .is_empty();
    if has_alpha {
        return Ok(None);
    }

    // Parse grid descriptor
    let grid_data = container.get_item_data(primary_item.id)?;

    if grid_data.len() < 8 {
        return Err(at!(HeicError::InvalidData("Grid descriptor too short")));
    }

    let flags = grid_data[1];
    let rows = grid_data[2] as u32 + 1;
    let cols = grid_data[3] as u32 + 1;
    let (output_width, output_height) = if (flags & 1) != 0 {
        if grid_data.len() < 12 {
            return Err(at!(HeicError::InvalidData(
                "Grid descriptor too short for 32-bit dims"
            )));
        }
        (
            u32::from_be_bytes([grid_data[4], grid_data[5], grid_data[6], grid_data[7]]),
            u32::from_be_bytes([grid_data[8], grid_data[9], grid_data[10], grid_data[11]]),
        )
    } else {
        (
            u16::from_be_bytes([grid_data[4], grid_data[5]]) as u32,
            u16::from_be_bytes([grid_data[6], grid_data[7]]) as u32,
        )
    };

    limits.check_dimensions(output_width, output_height)?;

    // Get tile info
    let tile_ids = container.get_item_references(primary_item.id, FourCC::DIMG);
    let expected_tiles = (rows * cols) as usize;
    if tile_ids.len() != expected_tiles {
        return Err(at!(HeicError::InvalidData("Grid tile count mismatch")));
    }

    let first_tile = container
        .get_item(tile_ids[0])
        .ok_or_else(|| at!(HeicError::InvalidData("Missing tile item")))?;

    // Streaming grid path only supports HEVC tiles
    let tile_config = match first_tile.hevc_config.as_ref() {
        Some(config) => config,
        None => return Ok(None),
    };

    let (tile_width, tile_height) = first_tile
        .dimensions
        .ok_or_else(|| at!(HeicError::InvalidData("Missing tile dimensions")))?;

    // Determine color conversion overrides from grid item's colr nclx
    let color_override = match &primary_item.color_info {
        Some(ColorInfo::Nclx {
            full_range,
            matrix_coefficients,
            ..
        }) => Some((*full_range, *matrix_coefficients as u8)),
        _ => None,
    };

    // Collect tile data
    check_stop(stop)?;
    let tile_data_list: Vec<Cow<'_, [u8]>> = tile_ids
        .iter()
        .map(|&tid| container.get_item_data(tid))
        .collect::<core::result::Result<_, _>>()?;

    let bpp = layout.bytes_per_pixel();

    // Stream tile-rows: decode one row at a time, write to sink, drop
    for row in 0..rows {
        check_stop(stop)?;

        let row_start = row as usize * cols as usize;
        let row_end = row_start + cols as usize;

        // Calculate strip height (last row may be clipped)
        let strip_h = tile_height.min(output_height.saturating_sub(row * tile_height));
        if strip_h == 0 {
            break;
        }

        let y_offset = row * tile_height;
        let min_bytes = output_width as usize * strip_h as usize * bpp;
        let strip_buf = sink.demand(y_offset, strip_h, min_bytes);

        // Decode tiles for this row
        #[cfg(feature = "parallel")]
        let row_tiles: Vec<crate::hevc::DecodedFrame> = decode_tiles_parallel(
            &tile_data_list[row_start..row_end],
            tile_config,
            max_threads,
        )?;

        #[cfg(not(feature = "parallel"))]
        let row_tiles: Vec<crate::hevc::DecodedFrame> = {
            let _ = max_threads; // unused without parallel feature
            tile_data_list[row_start..row_end]
                .iter()
                .map(|tile_data| {
                    crate::hevc::decode_with_config(tile_config, tile_data).map_err(Into::into)
                })
                .collect::<Result<_>>()?
        };

        // Color-convert each tile directly into the strip buffer
        for (col, mut tile_frame) in row_tiles.into_iter().enumerate() {
            if let Some((fr, mc)) = color_override {
                tile_frame.full_range = fr;
                tile_frame.matrix_coeffs = mc;
            }
            let dst_x = col as u32 * tile_width;
            let copy_w = tile_frame
                .cropped_width()
                .min(output_width.saturating_sub(dst_x));
            let copy_h = tile_frame.cropped_height().min(strip_h);

            // Write into the strip buffer (y=0 within the strip)
            convert_tile_to_output(
                &tile_frame,
                strip_buf,
                layout,
                dst_x,
                0, // relative to strip, not to full image
                copy_w,
                copy_h,
                output_width,
            );
        }
    }

    Ok(Some((output_width, output_height)))
}

/// Color-convert a single decoded tile directly into the correct region
/// of the output RGB/RGBA/BGR/BGRA buffer.
#[allow(clippy::too_many_arguments)]
pub(crate) fn convert_tile_to_output(
    tile: &crate::hevc::DecodedFrame,
    output: &mut [u8],
    layout: PixelLayout,
    dst_x: u32,
    dst_y: u32,
    copy_w: u32,
    copy_h: u32,
    output_width: u32,
) {
    let bpp = layout.bytes_per_pixel();
    let shift = tile.bit_depth - 8;
    let src_x_start = tile.crop_left;
    let src_y_start = tile.crop_top;

    // Fast path: 4:2:0 + Rgb8 uses SIMD-accelerated conversion
    if tile.chroma_format == 1 && layout == PixelLayout::Rgb8 {
        let y_stride = tile.y_stride();
        let c_stride = tile.c_stride();

        for r in 0..copy_h {
            let src_row = src_y_start + r;
            let out_offset = ((dst_y + r) as usize * output_width as usize + dst_x as usize) * 3;
            let row_bytes = copy_w as usize * 3;
            crate::hevc::color_convert::convert_420_to_rgb(
                &tile.y_plane,
                &tile.cb_plane,
                &tile.cr_plane,
                y_stride,
                c_stride,
                src_row,
                src_row + 1,
                src_x_start,
                src_x_start + copy_w,
                shift as u32,
                tile.full_range,
                tile.matrix_coeffs,
                &mut output[out_offset..out_offset + row_bytes],
            );
        }
        return;
    }

    // Scalar fallback for other layouts and chroma formats
    let (cr_r, cb_g, cr_g, cb_b, y_bias, y_scale, rnd, shr) = if tile.full_range {
        let (cr_r, cb_g, cr_g, cb_b) = match tile.matrix_coeffs {
            1 => (403i32, -48, -120, 475), // BT.709
            9 => (377, -42, -146, 482),    // BT.2020
            _ => (359i32, -88, -183, 454), // BT.601
        };
        (cr_r, cb_g, cr_g, cb_b, 0i32, 256i32, 128i32, 8i32)
    } else {
        let (cr_r, cb_g, cr_g, cb_b) = match tile.matrix_coeffs {
            1 => (14744i32, -1754, -4383, 17373), // BT.709
            9 => (13806, -1541, -5349, 17615),    // BT.2020
            _ => (13126i32, -3222, -6686, 16591), // BT.601
        };
        (cr_r, cb_g, cr_g, cb_b, 16i32, 9576i32, 4096i32, 13i32)
    };

    let y_stride = tile.y_stride();
    let c_stride = tile.c_stride();

    for r in 0..copy_h {
        let src_y = src_y_start + r;
        let out_row_start = ((dst_y + r) as usize * output_width as usize + dst_x as usize) * bpp;

        for c in 0..copy_w {
            let src_x = src_x_start + c;
            let y_idx = src_y as usize * y_stride + src_x as usize;
            let y_val = (tile.y_plane[y_idx] >> shift) as i32;

            // Get chroma values based on chroma format
            let (cb_val, cr_val) = match tile.chroma_format {
                0 => (128i32, 128i32),
                1 => {
                    let c_idx = (src_y / 2) as usize * c_stride + (src_x / 2) as usize;
                    (
                        (tile.cb_plane[c_idx] >> shift) as i32,
                        (tile.cr_plane[c_idx] >> shift) as i32,
                    )
                }
                2 => {
                    let c_idx = src_y as usize * c_stride + (src_x / 2) as usize;
                    (
                        (tile.cb_plane[c_idx] >> shift) as i32,
                        (tile.cr_plane[c_idx] >> shift) as i32,
                    )
                }
                3 => {
                    let c_idx = src_y as usize * c_stride + src_x as usize;
                    (
                        (tile.cb_plane[c_idx] >> shift) as i32,
                        (tile.cr_plane[c_idx] >> shift) as i32,
                    )
                }
                _ => (128, 128),
            };

            let cb = cb_val - 128;
            let cr = cr_val - 128;
            let yv = (y_val - y_bias) * y_scale;
            let red = ((yv + cr_r * cr + rnd) >> shr).clamp(0, 255) as u8;
            let green = ((yv + cb_g * cb + cr_g * cr + rnd) >> shr).clamp(0, 255) as u8;
            let blue = ((yv + cb_b * cb + rnd) >> shr).clamp(0, 255) as u8;

            let out_offset = out_row_start + c as usize * bpp;
            match layout {
                PixelLayout::Rgb8 => {
                    output[out_offset] = red;
                    output[out_offset + 1] = green;
                    output[out_offset + 2] = blue;
                }
                PixelLayout::Rgba8 => {
                    output[out_offset] = red;
                    output[out_offset + 1] = green;
                    output[out_offset + 2] = blue;
                    output[out_offset + 3] = 255;
                }
                PixelLayout::Bgr8 => {
                    output[out_offset] = blue;
                    output[out_offset + 1] = green;
                    output[out_offset + 2] = red;
                }
                PixelLayout::Bgra8 => {
                    output[out_offset] = blue;
                    output[out_offset + 1] = green;
                    output[out_offset + 2] = red;
                    output[out_offset + 3] = 255;
                }
            }
        }
    }
}

/// Decode an auxiliary alpha plane and return it sized to match the primary frame.
///
/// Returns the alpha plane as a Vec<u16> with one value per cropped pixel,
/// or None if decoding fails.
fn decode_alpha_plane(
    container: &heif::HeifContainer<'_>,
    alpha_id: u32,
    primary_frame: &crate::hevc::DecodedFrame,
    limits: &Limits,
    stop: &dyn Stop,
) -> Option<Vec<u16>> {
    let alpha_item = container.get_item(alpha_id)?;
    let alpha_data = container.get_item_data(alpha_id).ok()?;

    // Check limits on alpha image dimensions before decoding
    if let Some((w, h)) = alpha_item.dimensions {
        limits.check_dimensions(w, h).ok()?;
        let estimated = DecoderConfig::estimate_memory(w, h, PixelLayout::Rgba8);
        limits.check_memory(estimated).ok()?;
    }

    check_stop(stop).ok()?;

    // Multi-codec dispatch: try HEVC first, then AV1
    let alpha_frame = if let Some(ref config) = alpha_item.hevc_config {
        crate::hevc::decode_with_config(config, &alpha_data).ok()?
    } else {
        #[cfg(feature = "av1")]
        {
            if alpha_item.av1_config.is_some() {
                decode_av1_item(&alpha_item, &alpha_data, limits, stop).ok()?
            } else {
                return None;
            }
        }
        #[cfg(not(feature = "av1"))]
        {
            return None;
        }
    };

    let primary_w = primary_frame.cropped_width();
    let primary_h = primary_frame.cropped_height();
    let alpha_w = alpha_frame.cropped_width();
    let alpha_h = alpha_frame.cropped_height();

    // Use u64 arithmetic to avoid u32 overflow
    let total_pixels = usize::try_from((primary_w as u64).checked_mul(primary_h as u64)?).ok()?;
    let mut alpha_plane = Vec::with_capacity(total_pixels);

    if alpha_w == primary_w && alpha_h == primary_h {
        // Same dimensions — direct copy of Y plane from cropped region
        let y_start = alpha_frame.crop_top;
        let x_start = alpha_frame.crop_left;
        for y in 0..primary_h {
            for x in 0..primary_w {
                let src_idx = ((y_start + y) * alpha_frame.width + (x_start + x)) as usize;
                alpha_plane.push(alpha_frame.y_plane[src_idx]);
            }
        }
    } else {
        // Different dimensions — bilinear resize
        for dy in 0..primary_h {
            for dx in 0..primary_w {
                let sx = (dx as f64) * (alpha_w as f64 - 1.0) / (primary_w as f64 - 1.0).max(1.0);
                let sy = (dy as f64) * (alpha_h as f64 - 1.0) / (primary_h as f64 - 1.0).max(1.0);

                let x0 = floor_f64(sx) as u32;
                let y0 = floor_f64(sy) as u32;
                let x1 = (x0 + 1).min(alpha_w - 1);
                let y1 = (y0 + 1).min(alpha_h - 1);
                let fx = sx - x0 as f64;
                let fy = sy - y0 as f64;

                let stride = alpha_frame.width;
                let off_y = alpha_frame.crop_top;
                let off_x = alpha_frame.crop_left;

                let get = |px: u32, py: u32| -> f64 {
                    let idx = ((off_y + py) * stride + (off_x + px)) as usize;
                    alpha_frame.y_plane.get(idx).copied().unwrap_or(0) as f64
                };

                let v00 = get(x0, y0);
                let v10 = get(x1, y0);
                let v01 = get(x0, y1);
                let v11 = get(x1, y1);

                let val = v00 * (1.0 - fx) * (1.0 - fy)
                    + v10 * fx * (1.0 - fy)
                    + v01 * (1.0 - fx) * fy
                    + v11 * fx * fy;

                alpha_plane.push(round_f64(val) as u16);
            }
        }
    }

    Some(alpha_plane)
}

/// Decode gain map from Apple HDR HEIC.
///
/// Returns the grayscale gain map pixels scaled to 8-bit, along with
/// the source bit depth and any XMP metadata associated with the gain map item.
pub(crate) fn decode_gain_map(data: &[u8]) -> Result<HdrGainMap> {
    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let gainmap_ids =
        container.find_auxiliary_items(primary_item.id, "urn:com:apple:photo:2020:aux:hdrgainmap");

    let &gainmap_id = gainmap_ids
        .first()
        .ok_or_else(|| at!(HeicError::InvalidData("No HDR gain map found")))?;

    let gainmap_item = container
        .get_item(gainmap_id)
        .ok_or_else(|| at!(HeicError::InvalidData("Missing gain map item")))?;

    // Use decode_item to handle grids, iden, and plain HEVC gain maps
    let frame = decode_item(
        &container,
        &gainmap_item,
        0,
        &Limits::default(),
        &Unstoppable,
        None,
    )?;

    let width = frame.cropped_width();
    let height = frame.cropped_height();
    let bit_depth = frame.bit_depth;

    // Extract Y plane as grayscale, scale to 8-bit if needed
    let total_pixels = (width as usize)
        .checked_mul(height as usize)
        .ok_or_else(|| at!(HeicError::LimitExceeded("gain map dimensions overflow")))?;

    let max_val = ((1u32 << bit_depth) - 1) as u32;
    let y_start = frame.crop_top;
    let x_start = frame.crop_left;

    let mut grayscale = Vec::new();
    grayscale
        .try_reserve(total_pixels)
        .map_err(|_| at!(HeicError::OutOfMemory))?;

    for y in 0..height {
        for x in 0..width {
            let src_idx = ((y_start + y) * frame.width + (x_start + x)) as usize;
            let raw = frame.y_plane[src_idx] as u32;
            let val = if bit_depth == 8 {
                raw as u8
            } else {
                ((raw * 255 + max_val / 2) / max_val) as u8
            };
            grayscale.push(val);
        }
    }

    // Extract XMP metadata associated with the gain map item (if any)
    let xmp = container
        .find_xmp_for_item(gainmap_id)
        .map(|cow| cow.into_owned());

    Ok(HdrGainMap {
        data: grayscale,
        width,
        height,
        bit_depth,
        xmp,
    })
}

/// Check if the primary image has an HDR gain map auxiliary image.
pub(crate) fn has_gain_map(data: &[u8]) -> Result<bool> {
    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let gainmap_ids =
        container.find_auxiliary_items(primary_item.id, "urn:com:apple:photo:2020:aux:hdrgainmap");
    Ok(!gainmap_ids.is_empty())
}

/// Apply clean aperture (clap box) crop to a decoded frame
fn apply_clean_aperture(frame: &mut crate::hevc::DecodedFrame, clap: &CleanAperture) {
    let conf_width = frame.cropped_width();
    let conf_height = frame.cropped_height();

    let clean_width = clap.width_n.checked_div(clap.width_d).unwrap_or(conf_width);
    let clean_height = clap
        .height_n
        .checked_div(clap.height_d)
        .unwrap_or(conf_height);

    if clean_width >= conf_width && clean_height >= conf_height {
        return;
    }

    let horiz_off_pixels = if clap.horiz_off_d > 0 {
        (clap.horiz_off_n as f64) / (clap.horiz_off_d as f64)
    } else {
        0.0
    };
    let vert_off_pixels = if clap.vert_off_d > 0 {
        (clap.vert_off_n as f64) / (clap.vert_off_d as f64)
    } else {
        0.0
    };

    let extra_left =
        round_f64((conf_width as f64 - clean_width as f64) / 2.0 + horiz_off_pixels) as u32;
    let extra_top =
        round_f64((conf_height as f64 - clean_height as f64) / 2.0 + vert_off_pixels) as u32;
    let extra_right = conf_width
        .saturating_sub(clean_width)
        .saturating_sub(extra_left);
    let extra_bottom = conf_height
        .saturating_sub(clean_height)
        .saturating_sub(extra_top);

    frame.crop_left += extra_left;
    frame.crop_right += extra_right;
    frame.crop_top += extra_top;
    frame.crop_bottom += extra_bottom;
}

/// Extract EXIF TIFF data from HEIC container
pub(crate) fn extract_exif<'a>(data: &'a [u8]) -> Result<Option<Cow<'a, [u8]>>> {
    let container = heif::parse(data, &Unstoppable)?;

    // Find Exif item(s)
    for info in &container.item_infos {
        if info.item_type != FourCC(*b"Exif") {
            continue;
        }
        let Ok(exif_data) = container.get_item_data(info.item_id) else {
            continue;
        };
        // HEIF EXIF format: 4 bytes big-endian offset to TIFF header, then data.
        // The offset is from byte 4 (after the 4-byte offset field itself).
        // Typically 0, meaning TIFF data starts at byte 4.
        if exif_data.len() < 4 {
            continue;
        }
        let tiff_offset =
            u32::from_be_bytes([exif_data[0], exif_data[1], exif_data[2], exif_data[3]]) as usize;
        let tiff_start = 4 + tiff_offset;
        if tiff_start < exif_data.len() {
            return Ok(Some(match exif_data {
                Cow::Borrowed(b) => Cow::Borrowed(&b[tiff_start..]),
                Cow::Owned(v) => Cow::Owned(v[tiff_start..].to_vec()),
            }));
        }
    }

    Ok(None)
}

/// Decode thumbnail image from HEIC container
pub(crate) fn decode_thumbnail(data: &[u8], layout: PixelLayout) -> Result<Option<DecodeOutput>> {
    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let thumb_ids = container.find_thumbnails(primary_item.id);
    let Some(&thumb_id) = thumb_ids.first() else {
        return Ok(None);
    };

    let thumb_item = container
        .get_item(thumb_id)
        .ok_or_else(|| at!(HeicError::InvalidData("Thumbnail item not found")))?;

    let stop: &dyn Stop = &Unstoppable;
    let frame = decode_item(&container, &thumb_item, 0, &NO_LIMITS, stop, None)?;

    let width = frame.cropped_width();
    let height = frame.cropped_height();

    let pixels = match layout {
        PixelLayout::Rgb8 => frame.to_rgb()?,
        PixelLayout::Rgba8 => frame.to_rgba()?,
        PixelLayout::Bgr8 => frame.to_bgr()?,
        PixelLayout::Bgra8 => frame.to_bgra()?,
    };

    Ok(Some(DecodeOutput {
        data: pixels,
        width,
        height,
        layout,
    }))
}

/// Extract XMP XML data from HEIC container
pub(crate) fn extract_xmp<'a>(data: &'a [u8]) -> Result<Option<Cow<'a, [u8]>>> {
    let container = heif::parse(data, &Unstoppable)?;

    // Find mime items with XMP content type
    for info in &container.item_infos {
        if info.item_type == FourCC(*b"mime")
            && (info.content_type.contains("xmp")
                || info.content_type.contains("rdf+xml")
                || info.content_type == "application/rdf+xml")
            && let Ok(xmp_data) = container.get_item_data(info.item_id)
        {
            return Ok(Some(xmp_data));
        }
    }

    Ok(None)
}

/// List all auxiliary images linked to the primary item.
pub(crate) fn list_auxiliary_images(data: &[u8]) -> Result<Vec<crate::AuxiliaryImageDescriptor>> {
    use crate::auxiliary::AuxiliaryImageType;

    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let aux_items = container.find_all_auxiliary_items(primary_item.id);

    let mut result = Vec::new();
    for (item_id, urn) in aux_items {
        let aux_type = AuxiliaryImageType::from_urn(&urn);
        let item = container.get_item(item_id);
        let dimensions = item.and_then(|it| it.dimensions);
        result.push(crate::AuxiliaryImageDescriptor {
            aux_type,
            item_id,
            dimensions,
        });
    }

    Ok(result)
}

/// Check if the primary image has a depth auxiliary image.
pub(crate) fn has_depth(data: &[u8]) -> Result<bool> {
    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let depth_ids = container.find_auxiliary_items(primary_item.id, "urn:mpeg:hevc:2015:auxid:2");
    if !depth_ids.is_empty() {
        return Ok(true);
    }
    let depth_ids = container.find_auxiliary_items(
        primary_item.id,
        "urn:mpeg:mpegB:cicp:systems:auxiliary:depth",
    );
    Ok(!depth_ids.is_empty())
}

/// Decode the depth map auxiliary image.
pub(crate) fn decode_depth(data: &[u8]) -> Result<crate::DepthMap> {
    use crate::auxiliary::{AuxiliaryImageType, parse_depth_representation_info};

    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    // Find depth auxiliary item (try MPEG URN first, then CICP URN)
    let depth_id = container
        .find_auxiliary_items(primary_item.id, "urn:mpeg:hevc:2015:auxid:2")
        .first()
        .copied()
        .or_else(|| {
            container
                .find_auxiliary_items(
                    primary_item.id,
                    "urn:mpeg:mpegB:cicp:systems:auxiliary:depth",
                )
                .first()
                .copied()
        })
        .ok_or_else(|| at!(HeicError::InvalidData("no depth auxiliary image found")))?;

    let depth_item = container
        .get_item(depth_id)
        .ok_or_else(|| at!(HeicError::InvalidData("depth item not found")))?;

    // Parse depth representation info from auxC subtype data
    let depth_info = depth_item
        .auxiliary_type_property
        .as_ref()
        .map(|atp| {
            let _ = AuxiliaryImageType::from_urn(&atp.aux_type); // validates it's depth
            parse_depth_representation_info(&atp.subtype_data)
        })
        .unwrap_or_default();

    // Decode the depth image using the same item decode pipeline
    let frame = decode_item(
        &container,
        &depth_item,
        0,
        &Limits::default(),
        &Unstoppable,
        None,
    )?;

    let width = frame.cropped_width();
    let height = frame.cropped_height();
    let bit_depth = frame.bit_depth;

    // Extract the Y (luma) plane as the grayscale depth data
    let total_pixels = (width as usize)
        .checked_mul(height as usize)
        .ok_or_else(|| at!(HeicError::LimitExceeded("depth map dimensions overflow")))?;

    let mut depth_data = Vec::new();
    depth_data
        .try_reserve(total_pixels)
        .map_err(|_| at!(HeicError::OutOfMemory))?;

    let y_start = frame.crop_top;
    let x_start = frame.crop_left;
    for y in 0..height {
        for x in 0..width {
            let src_idx = ((y_start + y) * frame.width + (x_start + x)) as usize;
            depth_data.push(frame.y_plane[src_idx]);
        }
    }

    Ok(crate::DepthMap {
        data: depth_data,
        width,
        height,
        bit_depth,
        depth_info,
    })
}

/// Decode a specific auxiliary image by item ID to grayscale u16 pixels.
///
/// This is a general-purpose decoder for any auxiliary image item,
/// returning the luma plane as u16 samples.
pub(crate) fn decode_auxiliary_item(
    data: &[u8],
    item_id: u32,
    layout: PixelLayout,
) -> Result<DecodeOutput> {
    let container = heif::parse(data, &Unstoppable)?;
    let item = container
        .get_item(item_id)
        .ok_or_else(|| at!(HeicError::InvalidData("auxiliary item not found")))?;

    let frame = decode_item(&container, &item, 0, &Limits::default(), &Unstoppable, None)?;

    let width = frame.cropped_width();
    let height = frame.cropped_height();

    let pixels = match layout {
        PixelLayout::Rgb8 => frame.to_rgb()?,
        PixelLayout::Rgba8 => frame.to_rgba()?,
        PixelLayout::Bgr8 => frame.to_bgr()?,
        PixelLayout::Bgra8 => frame.to_bgra()?,
    };

    Ok(DecodeOutput {
        data: pixels,
        width,
        height,
        layout,
    })
}

/// Decode a single auxiliary item to grayscale 8-bit pixels.
///
/// The Y plane of the decoded HEVC frame is extracted and scaled
/// to 8-bit if the source bit depth is greater than 8.
fn decode_aux_to_grayscale(
    container: &heif::HeifContainer<'_>,
    item_id: u32,
) -> Result<(Vec<u8>, u32, u32)> {
    let item = container
        .get_item(item_id)
        .ok_or_else(|| at!(HeicError::InvalidData("auxiliary item not found")))?;

    let frame = decode_item(container, &item, 0, &Limits::default(), &Unstoppable, None)?;

    let width = frame.cropped_width();
    let height = frame.cropped_height();
    let max_val = ((1u32 << frame.bit_depth) - 1) as u32;
    let y_start = frame.crop_top;
    let x_start = frame.crop_left;

    let mut grayscale = Vec::with_capacity((width * height) as usize);
    for y in 0..height {
        for x in 0..width {
            let src_idx = ((y_start + y) * frame.width + (x_start + x)) as usize;
            let raw = frame.y_plane[src_idx] as u32;
            // Scale to 8-bit
            let val = if frame.bit_depth == 8 {
                raw as u8
            } else {
                ((raw * 255 + max_val / 2) / max_val) as u8
            };
            grayscale.push(val);
        }
    }

    Ok((grayscale, width, height))
}

/// Decode all segmentation mattes from a HEIC file.
///
/// Looks for all known matte auxiliary types (portrait, skin, hair, teeth,
/// glasses) and decodes each to an 8-bit grayscale matte.
pub(crate) fn decode_mattes(data: &[u8]) -> Result<Vec<crate::SegmentationMatte>> {
    use crate::auxiliary::AuxiliaryImageType;

    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let matte_urns: &[(AuxiliaryImageType, &str)] = &[
        (
            AuxiliaryImageType::PortraitMatte,
            AuxiliaryImageType::PortraitMatte.urn(),
        ),
        (
            AuxiliaryImageType::SkinMatte,
            AuxiliaryImageType::SkinMatte.urn(),
        ),
        (
            AuxiliaryImageType::HairMatte,
            AuxiliaryImageType::HairMatte.urn(),
        ),
        (
            AuxiliaryImageType::TeethMatte,
            AuxiliaryImageType::TeethMatte.urn(),
        ),
        (
            AuxiliaryImageType::GlassesMatte,
            AuxiliaryImageType::GlassesMatte.urn(),
        ),
    ];

    let mut mattes = Vec::new();

    for (aux_type, urn) in matte_urns {
        let aux_ids = container.find_auxiliary_items(primary_item.id, urn);
        if let Some(&aux_id) = aux_ids.first() {
            let (pixels, width, height) = decode_aux_to_grayscale(&container, aux_id)?;
            mattes.push(crate::SegmentationMatte {
                data: pixels,
                width,
                height,
                matte_type: aux_type.clone(),
            });
        }
    }

    Ok(mattes)
}

/// Decode a specific segmentation matte type from a HEIC file.
///
/// Returns `None` if the requested matte type is not present.
pub(crate) fn decode_matte(
    data: &[u8],
    matte_type: &crate::auxiliary::AuxiliaryImageType,
) -> Result<Option<crate::SegmentationMatte>> {
    let container = heif::parse(data, &Unstoppable)?;
    let primary_item = container
        .primary_item()
        .ok_or_else(|| at!(HeicError::NoPrimaryImage))?;

    let aux_ids = container.find_auxiliary_items(primary_item.id, matte_type.urn());
    let Some(&aux_id) = aux_ids.first() else {
        return Ok(None);
    };

    let (pixels, width, height) = decode_aux_to_grayscale(&container, aux_id)?;
    Ok(Some(crate::SegmentationMatte {
        data: pixels,
        width,
        height,
        matte_type: matte_type.clone(),
    }))
}