hpvca 0.1.11

HEVC/HEIC tiny image encoder
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
/*
 * // Copyright (c) Radzivon Bartoshyk 6/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#![allow(clippy::excessive_precision)]
#![deny(unreachable_pub)]
use std::mem::size_of;
mod aq;
mod cabac;
mod color;
mod cost;
mod dct;
mod deblock;
mod error;
mod fmt;
mod hevc;
mod hevc_transform;
mod intra;
mod isobmff;
mod math;
mod metadata;
mod pool;
mod sao;
mod ycgco;
mod yuv;

#[cfg(all(target_arch = "x86_64", feature = "avx"))]
mod avx;
#[cfg(all(target_arch = "aarch64", feature = "neon"))]
mod neon;

pub use color::{Cicp, ColorMetadata, MatrixCoefficients, Primaries, TransferFunction};
pub use error::EncodeError;
pub use fmt::{BitDepth, ChromaFormat};
pub use metadata::{ContentLightLevel, Metadata, Orientation};
pub use yuv::Yuv;

const MIN_DIM: u32 = 1;
const MAX_DIM: u32 = 16_384;

/// Images wider or taller than this are encoded as a HEIF grid of 512×512
/// tiles. The value matches Apple's tile size for compatibility.
const TILE_SIZE: u32 = 512;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum ParallelismStrategy {
    /// One HEVC image, no parallel coding tools (sequential).
    Single,
    /// One HEVC image coded with Wavefront Parallel Processing
    /// (`entropy_coding_sync`): CTU rows are independent CABAC substreams.
    Wpp,
    /// One HEVC image combining HEVC tiles + WPP for maximum core saturation.
    TilesWpp,
    /// A HEIF grid of independent HEVC images (large pictures), each coded
    /// sequentially. Broadly compatible;
    Grid,
    /// A HEIF grid of independent HEVC images, each internally WPP'd — every cell is
    /// a plain WPP image, so it stays broadly compatible while each cell also
    /// carries its own wavefront substreams.
    #[default]
    GridWpp,
}

/// Variance-boost controls for low-contrast detail preservation.
#[derive(Clone, Copy, Debug)]
pub struct VarianceBoost {
    /// Ranked 8x8 variance octile selected inside each 64x64 CTU (1..=8).
    pub octile: u8,
    /// Boost curve strength (0 disables variance boost; 1..=4 are typical).
    pub strength: f32,
    /// Apply only negative QP boosts instead of combining them with activity AQ.
    pub boost_only: bool,
}

impl Default for VarianceBoost {
    fn default() -> Self {
        Self {
            octile: 6,
            strength: 1.0,
            boost_only: false,
        }
    }
}

impl ParallelismStrategy {
    /// Whether a picture large enough to tile is coded as a HEIF grid.
    fn uses_grid(self) -> bool {
        matches!(self, Self::Grid | Self::GridWpp)
    }
    /// Whether grid cells are individually WPP'd (only when [`uses_grid`]).
    fn grid_cell_wpp(self) -> bool {
        matches!(self, Self::GridWpp)
    }
    /// Whether the single-image path enables WPP. `GridWpp`/`TilesWpp` fall back to
    /// plain WPP here when the picture is too small to grid/tile.
    fn single_wpp(self) -> bool {
        matches!(self, Self::Wpp | Self::TilesWpp | Self::GridWpp)
    }
    /// Whether the single-image path also enables HEVC tiles (combined with WPP).
    fn single_tiles(self) -> bool {
        matches!(self, Self::TilesWpp)
    }
}

/// Encoder configuration shared by all entry points.
///
/// Build with [`EncodeConfig::new`] and the `with_*` builder methods.
///
/// ```ignore
/// let cfg = EncodeConfig::new()
///     .with_quality(90)
///     .with_chroma(ChromaFormat::Yuv444)
///     .with_color(ColorMetadata::cicp(ColorEncoding::bt2020_pq()));
/// ```
#[derive(Clone, Debug)]
pub struct EncodeConfig {
    /// Visual quality 1..=100 (higher = better, larger file). Maps to HEVC QP.
    /// Ignored when [`lossless`](Self::lossless) is set.
    pub quality: u8,
    /// Mathematically lossless encoding.
    pub lossless: bool,
    /// Chroma subsampling format. Ignored by the `gray*` entry points, which
    /// always use [`ChromaFormat::Monochrome`].
    pub chroma: ChromaFormat,
    /// Color metadata written to the `colr` box / VUI.
    pub color: ColorMetadata,
    /// Optional image metadata (orientation, HDR light level, EXIF).
    pub metadata: Metadata,
    /// Preferred total encoder parallelism. Grid cells are encoded concurrently;
    /// with [`ParallelismStrategy::GridWpp`], spare capacity is divided between
    /// their WPP row encoders without exceeding this total. The output is
    /// identical regardless of this value. `0` means "auto": use the number of
    /// hardware threads reported by the platform (falling back to 1).
    pub threads: usize,
    /// How the picture is parallelized and packaged. See [`ParallelismStrategy`];
    /// defaults to [`ParallelismStrategy::Auto`].
    pub parallelism: ParallelismStrategy,
    /// Enable luma Sample Adaptive Offset filtering. SAO currently requires an
    /// analysis encode before the final encode, so disabling it nearly halves
    /// the transform/RDO work at a small compression-efficiency cost.
    pub sao: bool,
    /// Low-contrast variance-boost settings.
    pub variance_boost: VarianceBoost,
}

impl Default for EncodeConfig {
    fn default() -> Self {
        EncodeConfig {
            quality: 90,
            lossless: false,
            chroma: ChromaFormat::Yuv420,
            color: ColorMetadata::default(), // sRGB ICC profile
            metadata: Metadata::default(),
            threads: 0, // auto-detect
            parallelism: ParallelismStrategy::GridWpp,
            sao: true,
            variance_boost: VarianceBoost::default(),
        }
    }
}

impl EncodeConfig {
    /// Default settings: q = 90, 4:2:0, sRGB ICC.
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_quality(mut self, quality: u8) -> Self {
        self.quality = quality;
        self
    }

    /// Select the [`ParallelismStrategy`].
    pub fn with_parallelism(mut self, parallelism: ParallelismStrategy) -> Self {
        self.parallelism = parallelism;
        self
    }

    /// Enable mathematically lossless encoding (see [`lossless`](Self::lossless)).
    /// In this mode [`quality`](Self::quality) is ignored.
    pub fn with_lossless(mut self, lossless: bool) -> Self {
        self.lossless = lossless;
        self
    }

    /// Enable or disable luma Sample Adaptive Offset filtering.
    pub fn with_sao(mut self, sao: bool) -> Self {
        self.sao = sao;
        self
    }

    /// Configure low-contrast variance boost. `octile` is 1..=8, typical
    /// `strength` values are 1..=4 (0 disables it), and `boost_only` disables
    /// the ordinary activity-masking redistribution.
    pub fn with_variance_boost(mut self, octile: u8, strength: f32, boost_only: bool) -> Self {
        self.variance_boost = VarianceBoost {
            octile,
            strength,
            boost_only,
        };
        self
    }

    pub fn with_chroma(mut self, chroma: ChromaFormat) -> Self {
        self.chroma = chroma;
        self
    }

    pub fn with_color(mut self, color: ColorMetadata) -> Self {
        self.color = color;
        self
    }

    /// Attach an ICC profile (`prof` colr box), preserving any CICP encoding already
    /// set. Chain with [`Self::with_cicp`] to signal both at once.
    pub fn with_icc_profile(mut self, icc: Vec<u8>) -> Self {
        self.color.icc = Some(icc);
        self
    }

    /// Set the CICP encoding (`nclx` colr box), preserving any ICC profile already
    /// set. Chain with [`Self::with_icc_profile`] to signal both at once.
    pub fn with_cicp(mut self, enc: Cicp) -> Self {
        self.color.cicp = Some(enc);
        self
    }

    pub fn with_metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = metadata;
        self
    }

    pub fn with_orientation(mut self, o: Orientation) -> Self {
        self.metadata.orientation = o;
        self
    }

    pub fn with_content_light_level(mut self, cll: ContentLightLevel) -> Self {
        self.metadata.content_light_level = Some(cll);
        self
    }

    pub fn with_exif(mut self, exif: Vec<u8>) -> Self {
        self.metadata.exif = Some(exif);
        self
    }

    /// Set the preferred worker-thread count for tiled (large-image) encoding.
    /// `0` selects the platform's hardware-thread count automatically. Has no
    /// effect on images small enough to encode as a single tile, and never
    /// changes the encoded output.
    pub fn with_threads(mut self, threads: usize) -> Self {
        self.threads = threads;
        self
    }

    fn validate(&self) -> Result<(), EncodeError> {
        validate_quality(self.quality)?;
        if !(1..=8).contains(&self.variance_boost.octile)
            || !self.variance_boost.strength.is_finite()
            || !(0.0..=4.0).contains(&self.variance_boost.strength)
        {
            return Err(EncodeError::InvalidInput);
        }
        Ok(())
    }
}

/// Encode a packed 8-bit RGB image to HEIC.
///
/// `rgb` must hold exactly `width * height * 3` bytes in R, G, B order.
pub fn encode_rgb(
    rgb: &[u8],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u8(rgb, width, height, 3)?;
    let wide: Vec<u16> = rgb.iter().map(|&b| b as u16).collect();
    encode_rgb_wide(&wide, width, height, BitDepth::Eight, cfg)
}

/// Encode a packed 8-bit RGBA image to HEIC. Alpha is **discarded**.
/// Use [`encode_rgba_with_alpha`] to preserve it.
///
/// `rgba` must hold exactly `width * height * 4` bytes in R, G, B, A order.
pub fn encode_rgba(
    rgba: &[u8],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u8(rgba, width, height, 4)?;
    let wide: Vec<u16> = rgba
        .as_chunks::<4>()
        .0
        .iter()
        .flat_map(|px| [px[0] as u16, px[1] as u16, px[2] as u16])
        .collect();
    encode_rgb_wide(&wide, width, height, BitDepth::Eight, cfg)
}

/// Encode a packed 8-bit RGBA image to HEIC, writing alpha as a separate
/// monochrome auxiliary image per ISO/IEC 23008-12.
///
/// `rgba` must hold exactly `width * height * 4` bytes in R, G, B, A order.
///
/// # Large images
/// Images larger than 512×512 are not tiled when alpha is present. If you need
/// tiled output with alpha, pre-tile and call this function per tile, or use
/// [`encode_yuv`] on pre-converted YCbCr data.
pub fn encode_rgba_with_alpha(
    rgba: &[u8],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u8(rgba, width, height, 4)?;
    let wide: Vec<u16> = rgba.iter().map(|&b| b as u16).collect();
    encode_rgba_with_alpha_wide(&wide, width, height, BitDepth::Eight, cfg)
}

/// Encode a 10-bit RGB image to HEIC.
///
/// `rgb` must hold exactly `width * height * 3` samples, each in `0..=1023`,
/// packed as `u16`.
pub fn encode_rgb10(
    rgb: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(rgb, width, height, 3)?;
    encode_rgb_wide(rgb, width, height, BitDepth::Ten, cfg)
}

/// Encode a 10-bit RGBA image to HEIC. Alpha is **discarded**.
///
/// `rgba` must hold exactly `width * height * 4` samples in R, G, B, A order,
/// each in `0..=1023`, packed as `u16`.
pub fn encode_rgba10(
    rgba: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(rgba, width, height, 4)?;
    let rgb: Vec<u16> = rgba
        .as_chunks::<4>()
        .0
        .iter()
        .flat_map(|px| [px[0], px[1], px[2]])
        .collect();
    encode_rgb_wide(&rgb, width, height, BitDepth::Ten, cfg)
}

/// Encode a 10-bit RGBA image to HEIC with a separate alpha auxiliary image.
///
/// `rgba` must hold exactly `width * height * 4` samples in R, G, B, A order,
/// each in `0..=1023`, packed as `u16`.
pub fn encode_rgba10_with_alpha(
    rgba: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(rgba, width, height, 4)?;
    encode_rgba_with_alpha_wide(rgba, width, height, BitDepth::Ten, cfg)
}

/// Encode a 12-bit RGB image to HEIC.
///
/// `rgb` must hold exactly `width * height * 3` samples, each in `0..=4095`,
/// packed as `u16`.
pub fn encode_rgb12(
    rgb: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(rgb, width, height, 3)?;
    encode_rgb_wide(rgb, width, height, BitDepth::Twelve, cfg)
}

/// Encode a 12-bit RGBA image to HEIC. Alpha is **discarded**.
///
/// `rgba` must hold exactly `width * height * 4` samples in R, G, B, A order,
/// each in `0..=4095`, packed as `u16`.
pub fn encode_rgba12(
    rgba: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(rgba, width, height, 4)?;
    let rgb: Vec<u16> = rgba
        .as_chunks::<4>()
        .0
        .iter()
        .flat_map(|px| [px[0], px[1], px[2]])
        .collect();
    encode_rgb_wide(&rgb, width, height, BitDepth::Twelve, cfg)
}

/// Encode a 12-bit RGBA image to HEIC with a separate alpha auxiliary image.
///
/// `rgba` must hold exactly `width * height * 4` samples in R, G, B, A order,
/// each in `0..=4095`, packed as `u16`.
pub fn encode_rgba12_with_alpha(
    rgba: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(rgba, width, height, 4)?;
    encode_rgba_with_alpha_wide(rgba, width, height, BitDepth::Twelve, cfg)
}

/// Encode a packed 8-bit grayscale image to HEIC (monochrome, no chroma).
///
/// `gray` must hold exactly `width * height` bytes.
pub fn encode_gray(
    gray: &[u8],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u8(gray, width, height, 1)?;
    let wide: Vec<u16> = gray.iter().map(|&b| b as u16).collect();
    encode_gray_wide(&wide, width, height, BitDepth::Eight, cfg)
}

/// Encode a packed 8-bit grayscale + alpha image to HEIC. Alpha is **discarded**.
/// Use [`encode_gray_alpha_with_alpha`] to preserve it.
///
/// `ya` must hold exactly `width * height * 2` bytes in Y, A order.
pub fn encode_gray_alpha(
    ya: &[u8],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u8(ya, width, height, 2)?;
    let wide: Vec<u16> = ya
        .as_chunks::<2>()
        .0
        .iter()
        .map(|px| px[0] as u16)
        .collect();
    encode_gray_wide(&wide, width, height, BitDepth::Eight, cfg)
}

/// Encode a packed 8-bit grayscale + alpha image to HEIC with a separate
/// alpha auxiliary image per ISO/IEC 23008-12.
///
/// `ya` must hold exactly `width * height * 2` bytes in Y, A order.
pub fn encode_gray_alpha_with_alpha(
    ya: &[u8],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u8(ya, width, height, 2)?;
    let wide: Vec<u16> = ya.iter().map(|&b| b as u16).collect();
    encode_gray_alpha_wide(&wide, width, height, BitDepth::Eight, cfg)
}

/// Encode a 10-bit grayscale image to HEIC.
///
/// `gray` must hold exactly `width * height` samples in `0..=1023`, packed as `u16`.
pub fn encode_gray10(
    gray: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(gray, width, height, 1)?;
    encode_gray_wide(gray, width, height, BitDepth::Ten, cfg)
}

/// Encode a 10-bit grayscale + alpha image to HEIC. Alpha is **discarded**.
///
/// `ya` must hold exactly `width * height * 2` samples in Y, A order,
/// each in `0..=1023`, packed as `u16`.
pub fn encode_gray_alpha10(
    ya: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(ya, width, height, 2)?;
    let luma: Vec<u16> = ya.as_chunks::<2>().0.iter().map(|px| px[0]).collect();
    encode_gray_wide(&luma, width, height, BitDepth::Ten, cfg)
}

/// Encode a 10-bit grayscale + alpha image to HEIC with a separate alpha
/// auxiliary image.
///
/// `ya` must hold exactly `width * height * 2` samples in Y, A order,
/// each in `0..=1023`, packed as `u16`.
pub fn encode_gray_alpha10_with_alpha(
    ya: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(ya, width, height, 2)?;
    encode_gray_alpha_wide(ya, width, height, BitDepth::Ten, cfg)
}

/// Encode a 12-bit grayscale image to HEIC.
///
/// `gray` must hold exactly `width * height` samples in `0..=4095`, packed as `u16`.
pub fn encode_gray12(
    gray: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(gray, width, height, 1)?;
    encode_gray_wide(gray, width, height, BitDepth::Twelve, cfg)
}

/// Encode a 12-bit grayscale + alpha image to HEIC. Alpha is **discarded**.
///
/// `ya` must hold exactly `width * height * 2` samples in Y, A order,
/// each in `0..=4095`, packed as `u16`.
pub fn encode_gray_alpha12(
    ya: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(ya, width, height, 2)?;
    let luma: Vec<u16> = ya.as_chunks::<2>().0.iter().map(|px| px[0]).collect();
    encode_gray_wide(&luma, width, height, BitDepth::Twelve, cfg)
}

/// Encode a 12-bit grayscale + alpha image to HEIC with a separate alpha
/// auxiliary image.
///
/// `ya` must hold exactly `width * height * 2` samples in Y, A order,
/// each in `0..=4095`, packed as `u16`.
pub fn encode_gray_alpha12_with_alpha(
    ya: &[u16],
    width: u32,
    height: u32,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    cfg.validate()?;
    validate_buf_u16(ya, width, height, 2)?;
    encode_gray_alpha_wide(ya, width, height, BitDepth::Twelve, cfg)
}

/// Encode pre-converted planar YCbCr directly, skipping the RGB→YCbCr step.
///
/// The [`Yuv`] carries its own chroma format and bit depth; `cfg.chroma` is
/// **ignored** in favour of what is stored in the planes. This entry point is
/// for callers that already hold YCbCr data (camera pipeline, decoder output,
/// etc.). The visible `width`/`height` are read from the [`Yuv`] itself.
///
/// Images wider or taller than 512 px are encoded as a HEIF grid of 512×512
/// tiles automatically.
///
/// Plane dimensions must satisfy the chroma subsampling grid. Use
/// [`Yuv::from_planes`] or [`yuv::rgb_to_yuv`] to produce a conformant
/// [`Yuv`]; those functions validate plane sizes on construction.
pub fn encode_yuv(yuv: &Yuv, cfg: &EncodeConfig) -> Result<Vec<u8>, EncodeError> {
    yuv.validate()?;
    cfg.validate()?;
    // A grid packages the picture as multiple items; the single-image strategies
    // (Wpp / TilesWpp / Single) code it as one item instead.
    if needs_tiling(yuv.display_w, yuv.display_h) && cfg.parallelism.uses_grid() {
        return encode_yuv_tiled(yuv, cfg);
    }
    encode_yuv_raw(yuv, cfg)
}

/// Returns true if the image is large enough to need grid tiling.
fn needs_tiling(width: u32, height: u32) -> bool {
    width > TILE_SIZE || height > TILE_SIZE
}

/// Core RGB path: dispatches to tiled grid for large images, single `hvc1`
/// item otherwise. `rgb` is always 3-channel u16 at this point.
fn encode_rgb_wide(
    rgb: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let mut local_cfg = cfg.clone();
    if local_cfg.lossless {
        // Lossless RGB round-trips exactly only as 4:4:4 GBR under the Identity
        // matrix: chroma subsampling and the YCgCo transform both discard
        // information (and common decoders can't even invert YCgCo). Force both.
        local_cfg.chroma = ChromaFormat::Yuv444;
        force_identity_matrix(&mut local_cfg.color);
    }
    let cfg = &local_cfg;
    // A grid packages the picture as multiple HEVC items; the single-image
    // strategies code it as one item instead (handled below).
    if needs_tiling(width, height) && cfg.parallelism.uses_grid() {
        return encode_rgb_tiled(rgb, width, height, bit_depth, cfg);
    }
    let (enc_w, enc_h) = encoded_dims(width, height, cfg.chroma);
    let mut yuv = if enc_w != width || enc_h != height {
        let padded = pad_buf::<3>(rgb, width, height, enc_w, enc_h);
        if cfg.lossless {
            ycgco::rgb_to_gbr(&padded, enc_w, enc_h, cfg.chroma, bit_depth)
        } else {
            yuv::rgb_to_yuv(&padded, enc_w, enc_h, cfg.chroma, bit_depth)
        }
    } else if cfg.lossless {
        ycgco::rgb_to_gbr(rgb, width, height, cfg.chroma, bit_depth)
    } else {
        yuv::rgb_to_yuv(rgb, width, height, cfg.chroma, bit_depth)
    };
    yuv = yuv.with_display(width, height);
    encode_yuv_raw(&yuv, cfg)
}

fn force_identity_matrix(color: &mut ColorMetadata) {
    let base = color.cicp.unwrap_or_else(Cicp::srgb);
    color.cicp = Some(Cicp {
        primaries: base.primaries,
        transfer: base.transfer,
        matrix: MatrixCoefficients::Identity,
        full_range: true,
    });
}

/// Core RGBA-with-alpha path. Dispatches to a paired color+alpha grid for
/// images larger than [`TILE_SIZE`]; otherwise a single `hvc1`+auxl pair.
fn encode_rgba_with_alpha_wide(
    rgba: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    if needs_tiling(width, height) {
        return encode_rgba_alpha_tiled(rgba, width, height, bit_depth, cfg);
    }
    let (enc_w, enc_h) = encoded_dims(width, height, cfg.chroma);
    let (w, h) = (width as usize, height as usize);
    let (nw, nh) = (enc_w as usize, enc_h as usize);

    let mut color_buf = vec![0u16; nw * nh * 3];
    let mut alpha_plane = vec![0u16; nw * nh];

    for (dst_row_idx, (col_row, alp_row)) in color_buf
        .chunks_exact_mut(nw * 3)
        .zip(alpha_plane.chunks_exact_mut(nw))
        .enumerate()
    {
        let sr = dst_row_idx.min(h - 1);
        let src_row = &rgba[sr * w * 4..(sr * w + w) * 4];
        for (dst_col_idx, (col_px, alp_px)) in col_row
            .as_chunks_mut::<3>()
            .0
            .iter_mut()
            .zip(alp_row.iter_mut())
            .enumerate()
        {
            let sc = dst_col_idx.min(w - 1);
            let src = &src_row[sc * 4..sc * 4 + 4];
            col_px.copy_from_slice(&src[..3]);
            *alp_px = src[3];
        }
    }

    let color_yuv = yuv::rgb_to_yuv(&color_buf, enc_w, enc_h, cfg.chroma, bit_depth);
    let color_stream = hevc::encode_intra(
        &color_yuv,
        enc_w,
        enc_h,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.sao,
        cfg.variance_boost,
    )?;

    let alpha_yuv = build_mono_yuv(alpha_plane, enc_w, enc_h, width, height, bit_depth);
    let alpha_stream = hevc::encode_intra(
        &alpha_yuv,
        enc_w,
        enc_h,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.sao,
        cfg.variance_boost,
    )?;

    isobmff::wrap_hevc_image_with_alpha(
        &color_stream,
        &alpha_stream,
        width,
        height,
        isobmff::ImageMeta {
            bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Core grayscale path: dispatches to tiled grid for large images.
/// Always encodes as Monochrome regardless of `cfg.chroma`.
fn encode_gray_wide(
    gray: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    validate_buf_u16(gray, width, height, 1)?;
    if needs_tiling(width, height) {
        return encode_gray_tiled(gray, width, height, bit_depth, cfg);
    }
    // Grayscale is always Monochrome regardless of cfg.chroma.
    let (enc_w, enc_h) = encoded_dims(width, height, ChromaFormat::Monochrome);
    let luma = if enc_w != width || enc_h != height {
        pad_buf::<1>(gray, width, height, enc_w, enc_h)
    } else {
        gray.to_vec()
    };
    let yuv = build_mono_yuv(luma, enc_w, enc_h, width, height, bit_depth);
    encode_yuv_raw(&yuv, cfg)
}

/// Core grayscale-with-alpha path. Dispatches to a paired luma+alpha grid
/// for images larger than [`TILE_SIZE`]; otherwise a single item+auxl pair.
fn encode_gray_alpha_wide(
    ya: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    validate_buf_u16(ya, width, height, 2)?;
    if needs_tiling(width, height) {
        return encode_gray_alpha_tiled(ya, width, height, bit_depth, cfg);
    }
    let (enc_w, enc_h) = encoded_dims(width, height, ChromaFormat::Monochrome);
    let (w, h) = (width as usize, height as usize);
    let (nw, nh) = (enc_w as usize, enc_h as usize);

    let mut luma_plane = vec![0u16; nw * nh];
    let mut alpha_plane = vec![0u16; nw * nh];

    for (dst_row_idx, (luma_row, alp_row)) in luma_plane
        .chunks_exact_mut(nw)
        .zip(alpha_plane.chunks_exact_mut(nw))
        .enumerate()
    {
        let sr = dst_row_idx.min(h - 1);
        let src_row = &ya[sr * w * 2..(sr * w + w) * 2];
        for (dst_col_idx, (luma_px, alp_px)) in
            luma_row.iter_mut().zip(alp_row.iter_mut()).enumerate()
        {
            let sc = dst_col_idx.min(w - 1);
            *luma_px = src_row[sc * 2];
            *alp_px = src_row[sc * 2 + 1];
        }
    }

    let color_yuv = build_mono_yuv(luma_plane, enc_w, enc_h, width, height, bit_depth);
    let color_stream = hevc::encode_intra(
        &color_yuv,
        enc_w,
        enc_h,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.sao,
        cfg.variance_boost,
    )?;

    let alpha_yuv = build_mono_yuv(alpha_plane, enc_w, enc_h, width, height, bit_depth);
    let alpha_stream = hevc::encode_intra(
        &alpha_yuv,
        enc_w,
        enc_h,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.sao,
        cfg.variance_boost,
    )?;

    isobmff::wrap_hevc_image_with_alpha(
        &color_stream,
        &alpha_stream,
        width,
        height,
        isobmff::ImageMeta {
            bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

pub fn encode_yuv_with_alpha(
    yuv: &Yuv,
    alpha: &[u16],
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    yuv.validate()?;
    cfg.validate()?;
    if alpha.len() != yuv.y.len() {
        return Err(EncodeError::InvalidInput);
    }
    if needs_tiling(yuv.display_w, yuv.display_h) {
        return encode_yuv_alpha_tiled(yuv, alpha, cfg);
    }

    // Color image — identical to encode_yuv's single-item path.
    let color_stream = hevc::encode_intra(
        yuv,
        yuv.width,
        yuv.height,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.sao,
        cfg.variance_boost,
    )?;

    // Alpha auxiliary image — monochrome, coded at the color image's dimensions.
    let alpha_yuv = build_mono_yuv(
        alpha.to_vec(),
        yuv.width,
        yuv.height,
        yuv.display_w,
        yuv.display_h,
        yuv.bit_depth,
    );
    let alpha_stream = hevc::encode_intra(
        &alpha_yuv,
        yuv.width,
        yuv.height,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.sao,
        cfg.variance_boost,
    )?;

    isobmff::wrap_hevc_image_with_alpha(
        &color_stream,
        &alpha_stream,
        yuv.display_w,
        yuv.display_h,
        isobmff::ImageMeta {
            bit_depth: yuv.bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Wrap an already-built [`Yuv`] into a HEIC bitstream (no re-validation).
fn encode_yuv_raw(yuv: &Yuv, cfg: &EncodeConfig) -> Result<Vec<u8>, EncodeError> {
    let nalu_stream = hevc::encode_intra_opts(
        yuv,
        yuv.width,
        yuv.height,
        cfg.quality,
        cfg.lossless,
        cfg.color.cicp,
        cfg.parallelism.single_wpp(),
        cfg.parallelism.single_tiles(),
        resolve_threads(cfg.threads),
        cfg.sao,
        cfg.variance_boost,
    )?;
    isobmff::wrap_hevc_image(
        &nalu_stream,
        yuv.display_w,
        yuv.display_h,
        isobmff::ImageMeta {
            bit_depth: yuv.bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Construct a monochrome [`Yuv`] from a pre-built luma plane.
fn build_mono_yuv(
    y: Vec<u16>,
    coded_w: u32,
    coded_h: u32,
    display_w: u32,
    display_h: u32,
    bit_depth: BitDepth,
) -> Yuv {
    Yuv {
        y,
        cb: Vec::new(),
        cr: Vec::new(),
        width: coded_w,
        height: coded_h,
        display_w,
        display_h,
        chroma: ChromaFormat::Monochrome,
        bit_depth,
    }
}

/// Resolve a configured thread preference to a concrete worker count. `0` means
/// "auto": the number of hardware threads the platform reports, or 1 if it
/// can't report one.
fn resolve_threads(preferred: usize) -> usize {
    if preferred != 0 {
        preferred
    } else {
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1)
    }
}

fn parallel_try_map<T, E, F>(n: usize, threads: usize, f: F) -> Result<Vec<T>, E>
where
    T: Send,
    E: Send,
    F: Fn(usize, usize) -> Result<T, E> + Sync,
{
    if n == 0 {
        return Ok(Vec::new());
    }
    let total_threads = resolve_threads(threads);
    let nthreads = total_threads.clamp(1, n);
    if nthreads == 1 {
        // Sequential fast path: no scheduling, no allocation of slots.
        return (0..n).map(|index| f(index, total_threads)).collect();
    }

    // Grid cells are the outer scheduling units. When there are fewer cells
    // than available threads, divide the unused capacity between their WPP row
    // encoders. The sum of all simultaneously active cell budgets is at most
    // `total_threads`, so nested pools do not oversubscribe the machine.
    let threads_per_item = total_threads / nthreads;
    let extra_threads = total_threads % nthreads;

    // One task per item on a context-local pool; `slots.iter_mut()` hands each task
    // a disjoint slot, and the pool load-balances items of uneven cost across cores.
    // The pool's threads are joined when it is dropped at the end of this call.
    let mut slots: Vec<Option<Result<T, E>>> = (0..n).map(|_| None).collect();
    let f = &f;
    let pool = pool::ThreadPool::new(nthreads.saturating_sub(1));
    pool.scoped(|scope| {
        for (i, slot) in slots.iter_mut().enumerate() {
            let item_threads = threads_per_item + usize::from(i < extra_threads);
            scope.spawn(move || {
                *slot = Some(f(i, item_threads));
            });
        }
    });

    let mut out = Vec::with_capacity(n);
    for slot in slots {
        // Every slot is written exactly once by its owning task.
        out.push(slot.expect("scoped tasks fill every slot")?);
    }
    Ok(out)
}

#[allow(clippy::too_many_arguments)]
fn encode_cell(
    yuv: &Yuv,
    w: u32,
    h: u32,
    quality: u8,
    lossless: bool,
    cicp: Option<Cicp>,
    cell_wpp: bool,
    threads: usize,
    sao: bool,
    variance_boost: VarianceBoost,
) -> Result<hevc::NaluStream, EncodeError> {
    if cell_wpp {
        // A WPP picture cannot run more CTU rows concurrently than it has.
        // Capping here avoids creating idle nested workers on high-core-count
        // systems encoding the fixed 512-pixel grid cells.
        let wpp_threads = threads.min(h.div_ceil(64) as usize).max(1);
        hevc::encode_intra_opts(
            yuv,
            w,
            h,
            quality,
            lossless,
            cicp,
            true,
            false,
            wpp_threads,
            sao,
            variance_boost,
        )
    } else {
        hevc::encode_intra(yuv, w, h, quality, lossless, cicp, sao, variance_boost)
    }
}

/// Encode a large RGB image as a HEIF grid of [`TILE_SIZE`]×[`TILE_SIZE`] tiles.
fn encode_rgb_tiled(
    rgb: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    encode_cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let mut cfg = encode_cfg.clone();
    let cell_wpp = cfg.parallelism.grid_cell_wpp();
    let cols = width.div_ceil(TILE_SIZE);
    let rows = height.div_ceil(TILE_SIZE);
    // TILE_SIZE=512 is always chroma-even for sub_w/sub_h ∈ {1,2}, so
    // encoded_dims returns (512,512) for every subsampling format.
    let (enc_tw, enc_th) = encoded_dims(TILE_SIZE, TILE_SIZE, cfg.chroma);

    if cfg.lossless {
        // The caller (encode_rgb_wide) has already forced 4:4:4 + Identity; keep
        // this idempotent guard so a direct call stays lossless too.
        cfg.chroma = ChromaFormat::Yuv444;
        force_identity_matrix(&mut cfg.color);
    }

    let n = (cols * rows) as usize;
    let tile_streams = parallel_try_map(n, cfg.threads, |idx, cell_threads| {
        let row = idx as u32 / cols;
        let col = idx as u32 % cols;
        let tile = extract_rgb_tile(rgb, width, height, col, row, TILE_SIZE, 3);
        let yuv = if cfg.lossless {
            ycgco::rgb_to_gbr(&tile, enc_tw, enc_th, cfg.chroma, bit_depth)
        } else {
            yuv::rgb_to_yuv(&tile, enc_tw, enc_th, cfg.chroma, bit_depth)
        };
        encode_cell(
            &yuv,
            enc_tw,
            enc_th,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )
    })?;
    isobmff::wrap_hevc_grid(
        &tile_streams,
        isobmff::GridDims {
            cols,
            rows,
            tile_w: enc_tw,
            tile_h: enc_th,
            full_w: width,
            full_h: height,
        },
        isobmff::ImageMeta {
            bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Encode a large grayscale image as a HEIF grid of monochrome tiles.
fn encode_gray_tiled(
    gray: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    validate_buf_u16(gray, width, height, 1)?;
    let cols = width.div_ceil(TILE_SIZE);
    let rows = height.div_ceil(TILE_SIZE);
    let cell_wpp = cfg.parallelism.grid_cell_wpp();

    let n = (cols * rows) as usize;
    let tile_streams = parallel_try_map(n, cfg.threads, |idx, cell_threads| {
        let row = idx as u32 / cols;
        let col = idx as u32 % cols;
        let luma = extract_plane_tile(
            gray,
            width as usize,
            height as usize,
            (col * TILE_SIZE) as usize,
            (row * TILE_SIZE) as usize,
            TILE_SIZE as usize,
            TILE_SIZE as usize,
        );
        let yuv = build_mono_yuv(luma, TILE_SIZE, TILE_SIZE, TILE_SIZE, TILE_SIZE, bit_depth);
        encode_cell(
            &yuv,
            TILE_SIZE,
            TILE_SIZE,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )
    })?;
    isobmff::wrap_hevc_grid(
        &tile_streams,
        isobmff::GridDims {
            cols,
            rows,
            tile_w: TILE_SIZE,
            tile_h: TILE_SIZE,
            full_w: width,
            full_h: height,
        },
        isobmff::ImageMeta {
            bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

fn encode_yuv_alpha_tiled(
    yuv: &Yuv,
    alpha: &[u16],
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let cell_wpp = cfg.parallelism.grid_cell_wpp();
    let cols = yuv.display_w.div_ceil(TILE_SIZE);
    let rows = yuv.display_h.div_ceil(TILE_SIZE);
    let (enc_tw, enc_th) = encoded_dims(TILE_SIZE, TILE_SIZE, yuv.chroma);

    let sw = yuv.chroma.sub_w() as u32;
    let sh = yuv.chroma.sub_h() as u32;
    // Chroma tile dimensions after subsampling.
    let c_tw = (enc_tw / sw) as usize;
    let c_th = (enc_th / sh) as usize;
    // Full chroma plane dimensions (yuv.width is already chroma-even padded).
    let c_src_w = (yuv.width / sw) as usize;
    let c_src_h = (yuv.height / sh) as usize;

    let n = (cols * rows) as usize;
    let pairs = parallel_try_map(n, cfg.threads, |idx, cell_threads| {
        let row = idx as u32 / cols;
        let col = idx as u32 % cols;
        let x0 = (col * TILE_SIZE) as usize;
        let y0 = (row * TILE_SIZE) as usize;

        let y_tile = extract_plane_tile(
            &yuv.y,
            yuv.width as usize,
            yuv.height as usize,
            x0,
            y0,
            enc_tw as usize,
            enc_th as usize,
        );
        let (cb_tile, cr_tile) = if yuv.chroma.is_monochrome() {
            (Vec::new(), Vec::new())
        } else {
            let cx0 = x0 / sw as usize;
            let cy0 = y0 / sh as usize;
            (
                extract_plane_tile(&yuv.cb, c_src_w, c_src_h, cx0, cy0, c_tw, c_th),
                extract_plane_tile(&yuv.cr, c_src_w, c_src_h, cx0, cy0, c_tw, c_th),
            )
        };

        let tile_yuv = Yuv {
            y: y_tile,
            cb: cb_tile,
            cr: cr_tile,
            width: enc_tw,
            height: enc_th,
            display_w: enc_tw,
            display_h: enc_th,
            chroma: yuv.chroma,
            bit_depth: yuv.bit_depth,
        };
        let color = encode_cell(
            &tile_yuv,
            enc_tw,
            enc_th,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )?;

        let alpha_tile = extract_plane_tile(
            alpha,
            yuv.width as usize,
            yuv.height as usize,
            x0,
            y0,
            enc_tw as usize,
            enc_th as usize,
        );
        let alpha_yuv = build_mono_yuv(alpha_tile, enc_tw, enc_th, enc_tw, enc_th, yuv.bit_depth);
        let alpha = encode_cell(
            &alpha_yuv,
            enc_tw,
            enc_th,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )?;
        Ok::<_, EncodeError>((color, alpha))
    })?;
    let mut color_streams = Vec::with_capacity(n);
    let mut alpha_streams = Vec::with_capacity(n);
    for (color, alpha) in pairs {
        color_streams.push(color);
        alpha_streams.push(alpha);
    }

    isobmff::wrap_hevc_grid_with_alpha(
        &color_streams,
        &alpha_streams,
        isobmff::GridDims {
            cols,
            rows,
            tile_w: enc_tw,
            tile_h: enc_th,
            full_w: yuv.display_w,
            full_h: yuv.display_h,
        },
        isobmff::ImageMeta {
            bit_depth: yuv.bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Encode a large pre-converted [`Yuv`] image as a HEIF grid. Splits all
/// planes (Y, Cb, Cr) into tiles respecting the chroma subsampling ratio.
fn encode_yuv_tiled(yuv: &Yuv, cfg: &EncodeConfig) -> Result<Vec<u8>, EncodeError> {
    let cell_wpp = cfg.parallelism.grid_cell_wpp();
    let cols = yuv.display_w.div_ceil(TILE_SIZE);
    let rows = yuv.display_h.div_ceil(TILE_SIZE);
    let (enc_tw, enc_th) = encoded_dims(TILE_SIZE, TILE_SIZE, yuv.chroma);

    let sw = yuv.chroma.sub_w() as u32;
    let sh = yuv.chroma.sub_h() as u32;
    // Chroma tile dimensions after subsampling.
    let c_tw = (enc_tw / sw) as usize;
    let c_th = (enc_th / sh) as usize;
    // Full chroma plane dimensions (yuv.width is already chroma-even padded).
    let c_src_w = (yuv.width / sw) as usize;
    let c_src_h = (yuv.height / sh) as usize;

    let n = (cols * rows) as usize;
    let tile_streams = parallel_try_map(n, cfg.threads, |idx, cell_threads| {
        let row = idx as u32 / cols;
        let col = idx as u32 % cols;
        let x0 = (col * TILE_SIZE) as usize;
        let y0 = (row * TILE_SIZE) as usize;

        let y_tile = extract_plane_tile(
            &yuv.y,
            yuv.width as usize,
            yuv.height as usize,
            x0,
            y0,
            enc_tw as usize,
            enc_th as usize,
        );
        let (cb_tile, cr_tile) = if yuv.chroma.is_monochrome() {
            (Vec::new(), Vec::new())
        } else {
            let cx0 = x0 / sw as usize;
            let cy0 = y0 / sh as usize;
            (
                extract_plane_tile(&yuv.cb, c_src_w, c_src_h, cx0, cy0, c_tw, c_th),
                extract_plane_tile(&yuv.cr, c_src_w, c_src_h, cx0, cy0, c_tw, c_th),
            )
        };

        let tile_yuv = Yuv {
            y: y_tile,
            cb: cb_tile,
            cr: cr_tile,
            width: enc_tw,
            height: enc_th,
            display_w: enc_tw,
            display_h: enc_th,
            chroma: yuv.chroma,
            bit_depth: yuv.bit_depth,
        };
        encode_cell(
            &tile_yuv,
            enc_tw,
            enc_th,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )
    })?;
    isobmff::wrap_hevc_grid(
        &tile_streams,
        isobmff::GridDims {
            cols,
            rows,
            tile_w: enc_tw,
            tile_h: enc_th,
            full_w: yuv.display_w,
            full_h: yuv.display_h,
        },
        isobmff::ImageMeta {
            bit_depth: yuv.bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Encode a large RGBA image as a paired HEIF grid: a color grid + an alpha
/// auxiliary grid, both with [`TILE_SIZE`]×[`TILE_SIZE`] tiles.
fn encode_rgba_alpha_tiled(
    rgba: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let cell_wpp = cfg.parallelism.grid_cell_wpp();
    let cols = width.div_ceil(TILE_SIZE);
    let rows = height.div_ceil(TILE_SIZE);
    let (enc_tw, enc_th) = encoded_dims(TILE_SIZE, TILE_SIZE, cfg.chroma);
    let ts2 = (TILE_SIZE * TILE_SIZE) as usize;

    let n = (cols * rows) as usize;
    let pairs = parallel_try_map(n, cfg.threads, |idx, cell_threads| {
        let row = idx as u32 / cols;
        let col = idx as u32 % cols;
        // Extract a TILE_SIZE×TILE_SIZE RGBA tile (4 ch) with edge replication.
        let tile = extract_rgb_tile(rgba, width, height, col, row, TILE_SIZE, 4);

        // Deinterleave RGBA → color (3 ch) + alpha (1 ch).
        let mut color_buf = vec![0u16; ts2 * 3];
        let mut alpha_plane = vec![0u16; ts2];
        for ((px, colors), alpha) in tile
            .as_chunks::<4>()
            .0
            .iter()
            .zip(color_buf.as_chunks_mut::<3>().0.iter_mut())
            .zip(alpha_plane.iter_mut())
        {
            colors[0] = px[0];
            colors[1] = px[1];
            colors[2] = px[2];
            *alpha = px[3];
        }

        let color_yuv = yuv::rgb_to_yuv(&color_buf, enc_tw, enc_th, cfg.chroma, bit_depth);
        let color = encode_cell(
            &color_yuv,
            enc_tw,
            enc_th,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )?;

        // Alpha is always monochrome; TILE_SIZE is already dimension-aligned.
        let alpha_yuv = build_mono_yuv(
            alpha_plane,
            TILE_SIZE,
            TILE_SIZE,
            TILE_SIZE,
            TILE_SIZE,
            bit_depth,
        );
        let alpha = encode_cell(
            &alpha_yuv,
            TILE_SIZE,
            TILE_SIZE,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )?;
        Ok::<_, EncodeError>((color, alpha))
    })?;
    let mut color_streams = Vec::with_capacity(n);
    let mut alpha_streams = Vec::with_capacity(n);
    for (color, alpha) in pairs {
        color_streams.push(color);
        alpha_streams.push(alpha);
    }

    isobmff::wrap_hevc_grid_with_alpha(
        &color_streams,
        &alpha_streams,
        isobmff::GridDims {
            cols,
            rows,
            tile_w: enc_tw,
            tile_h: enc_th,
            full_w: width,
            full_h: height,
        },
        isobmff::ImageMeta {
            bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Encode a large grayscale+alpha image as a paired HEIF grid: a luma grid +
/// an alpha auxiliary grid, both monochrome, with [`TILE_SIZE`]×[`TILE_SIZE`] tiles.
fn encode_gray_alpha_tiled(
    ya: &[u16],
    width: u32,
    height: u32,
    bit_depth: BitDepth,
    cfg: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    validate_dims(width, height)?;
    validate_buf_u16(ya, width, height, 2)?;
    let cols = width.div_ceil(TILE_SIZE);
    let rows = height.div_ceil(TILE_SIZE);
    let cell_wpp = cfg.parallelism.grid_cell_wpp();
    let ts2 = (TILE_SIZE * TILE_SIZE) as usize;

    let n = (cols * rows) as usize;
    let pairs = parallel_try_map(n, cfg.threads, |idx, cell_threads| {
        let row = idx as u32 / cols;
        let col = idx as u32 % cols;
        // Extract a TILE_SIZE×TILE_SIZE YA tile (2 ch) with edge replication.
        let tile = extract_rgb_tile(ya, width, height, col, row, TILE_SIZE, 2);

        // Deinterleave YA → luma (1 ch) + alpha (1 ch).
        let mut luma_plane = vec![0u16; ts2];
        let mut alpha_plane = vec![0u16; ts2];
        for ((px, luma), alpha) in tile
            .as_chunks::<2>()
            .0
            .iter()
            .zip(luma_plane.iter_mut())
            .zip(alpha_plane.iter_mut())
        {
            *luma = px[0];
            *alpha = px[1];
        }

        let luma_yuv = build_mono_yuv(
            luma_plane, TILE_SIZE, TILE_SIZE, TILE_SIZE, TILE_SIZE, bit_depth,
        );
        let luma = encode_cell(
            &luma_yuv,
            TILE_SIZE,
            TILE_SIZE,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )?;

        let alpha_yuv = build_mono_yuv(
            alpha_plane,
            TILE_SIZE,
            TILE_SIZE,
            TILE_SIZE,
            TILE_SIZE,
            bit_depth,
        );
        let alpha = encode_cell(
            &alpha_yuv,
            TILE_SIZE,
            TILE_SIZE,
            cfg.quality,
            cfg.lossless,
            cfg.color.cicp,
            cell_wpp,
            cell_threads,
            cfg.sao,
            cfg.variance_boost,
        )?;
        Ok::<_, EncodeError>((luma, alpha))
    })?;
    let mut luma_streams = Vec::with_capacity(n);
    let mut alpha_streams = Vec::with_capacity(n);
    for (luma, alpha) in pairs {
        luma_streams.push(luma);
        alpha_streams.push(alpha);
    }

    isobmff::wrap_hevc_grid_with_alpha(
        &luma_streams,
        &alpha_streams,
        isobmff::GridDims {
            cols,
            rows,
            tile_w: TILE_SIZE,
            tile_h: TILE_SIZE,
            full_w: width,
            full_h: height,
        },
        isobmff::ImageMeta {
            bit_depth,
            color_meta: &cfg.color,
            metadata: &cfg.metadata,
        },
    )
}

/// Extract a [`TILE_SIZE`]×[`TILE_SIZE`] interleaved-channel tile from a wide
/// pixel buffer, replication-padding at the right and bottom edges.
fn extract_rgb_tile(
    src: &[u16],
    src_w: u32,
    src_h: u32,
    col: u32,
    row: u32,
    tile_size: u32,
    channels: usize,
) -> Vec<u16> {
    let (sw, sh) = (src_w as usize, src_h as usize);
    let ts = tile_size as usize;
    let x0 = (col * tile_size) as usize;
    let y0 = (row * tile_size) as usize;
    let mut tile = vec![0u16; ts * ts * channels];
    for ty in 0..ts {
        let sy = (y0 + ty).min(sh - 1);
        let src_row = &src[sy * sw * channels..(sy * sw + sw) * channels];
        let dst_row = &mut tile[ty * ts * channels..(ty * ts + ts) * channels];
        for tx in 0..ts {
            let sx = (x0 + tx).min(sw - 1);
            dst_row[tx * channels..(tx + 1) * channels]
                .copy_from_slice(&src_row[sx * channels..(sx + 1) * channels]);
        }
    }
    tile
}

/// Extract a single-channel plane tile, replication-padding at edges.
fn extract_plane_tile(
    plane: &[u16],
    src_w: usize,
    src_h: usize,
    x0: usize,
    y0: usize,
    tile_w: usize,
    tile_h: usize,
) -> Vec<u16> {
    let mut tile = vec![0u16; tile_w * tile_h];
    for ty in 0..tile_h {
        let sy = (y0 + ty).min(src_h - 1);
        let src_row = &plane[sy * src_w..(sy + 1) * src_w];
        let dst_row = &mut tile[ty * tile_w..(ty + 1) * tile_w];
        for tx in 0..tile_w {
            dst_row[tx] = src_row[(x0 + tx).min(src_w - 1)];
        }
    }
    tile
}

pub(crate) fn validate_dims(width: u32, height: u32) -> Result<(), EncodeError> {
    if width < MIN_DIM || height < MIN_DIM || width > MAX_DIM || height > MAX_DIM {
        return Err(EncodeError::InvalidDimensions { width, height });
    }
    Ok(())
}

fn validate_quality(quality: u8) -> Result<(), EncodeError> {
    if quality == 0 || quality > 100 {
        return Err(EncodeError::InvalidInput);
    }
    Ok(())
}

fn validate_buf_u8(buf: &[u8], w: u32, h: u32, ch: usize) -> Result<(), EncodeError> {
    let needed = checked_buffer_size::<u8>(w as usize, h as usize, ch)?;
    if buf.len() != needed {
        return Err(EncodeError::InvalidInput);
    }
    Ok(())
}

fn validate_buf_u16(buf: &[u16], w: u32, h: u32, ch: usize) -> Result<(), EncodeError> {
    let needed = checked_buffer_size::<u16>(w as usize, h as usize, ch)?;
    if buf.len() != needed {
        return Err(EncodeError::InvalidInput);
    }
    Ok(())
}

pub(crate) fn checked_buffer_size<T>(
    width: usize,
    height: usize,
    channels: usize,
) -> Result<usize, EncodeError> {
    let pixel_size = size_of::<T>();
    width
        .checked_mul(height)
        .and_then(|v| v.checked_mul(channels))
        .and_then(|v| {
            v.checked_mul(pixel_size)
                .and_then(|b| isize::try_from(b).ok())?;
            Some(v)
        })
        .ok_or(EncodeError::InvalidInput)
}

fn encoded_dims(width: u32, height: u32, chroma: ChromaFormat) -> (u32, u32) {
    let sw = chroma.sub_w() as u32;
    let sh = chroma.sub_h() as u32;
    (width.div_ceil(sw) * sw, height.div_ceil(sh) * sh)
}

/// Replicate-pad a planar buffer from `(w, h)` to `(nw, nh)`.
/// `channels` is the number of interleaved u16 samples per pixel.
fn pad_buf<const N: usize>(src: &[u16], w: u32, h: u32, nw: u32, nh: u32) -> Vec<u16> {
    let (w, h, nw, nh) = (w as usize, h as usize, nw as usize, nh as usize);
    let src_stride = w * N;
    let dst_stride = nw * N;
    let mut out = vec![0u16; nw * nh * N];

    for (dst_row_idx, dst_row) in out.chunks_exact_mut(dst_stride).enumerate() {
        let sr = dst_row_idx.min(h - 1);
        let src_row = &src[sr * src_stride..(sr + 1) * src_stride];
        let (real, pad) = dst_row.split_at_mut(src_stride);
        real.copy_from_slice(src_row);
        if !pad.is_empty() {
            let last_px = &src_row[src_row.len() - N..];
            for px in pad.as_chunks_mut::<N>().0.iter_mut() {
                px.copy_from_slice(last_px);
            }
        }
    }
    out
}

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

    #[test]
    fn grid_thread_budgets_use_capacity_without_oversubscription() {
        let four_cells = parallel_try_map::<usize, (), _>(4, 10, |_, budget| Ok(budget)).unwrap();
        assert_eq!(four_cells, [3, 3, 2, 2]);
        assert_eq!(four_cells.iter().sum::<usize>(), 10);

        let many_cells = parallel_try_map::<usize, (), _>(12, 8, |_, budget| Ok(budget)).unwrap();
        assert_eq!(many_cells, [1; 12]);

        let one_cell = parallel_try_map::<usize, (), _>(1, 8, |_, budget| Ok(budget)).unwrap();
        assert_eq!(one_cell, [8]);
    }

    fn cfg() -> EncodeConfig {
        EncodeConfig::new()
    }

    // ── validation ───────────────────────────────────────────────────────

    #[test]
    fn rejects_zero_dims() {
        assert!(validate_dims(0, 1).is_err());
        assert!(validate_dims(1, 0).is_err());
    }

    #[test]
    fn rejects_oversized_dims() {
        assert!(validate_dims(MAX_DIM + 1, 1).is_err());
        assert!(validate_dims(1, MAX_DIM + 1).is_err());
    }

    #[test]
    fn rejects_quality_bounds() {
        assert!(cfg().with_quality(0).validate().is_err());
        assert!(cfg().with_quality(101).validate().is_err());
        assert!(cfg().with_quality(1).validate().is_ok());
        assert!(cfg().with_quality(100).validate().is_ok());
    }

    #[test]
    fn validates_variance_boost_options() {
        assert!(cfg().with_variance_boost(6, 2.0, false).validate().is_ok());
        assert!(cfg().with_variance_boost(0, 2.0, false).validate().is_err());
        assert!(cfg().with_variance_boost(9, 2.0, false).validate().is_err());
        assert!(
            cfg()
                .with_variance_boost(6, -1.0, false)
                .validate()
                .is_err()
        );
        assert!(
            cfg()
                .with_variance_boost(6, f32::NAN, false)
                .validate()
                .is_err()
        );
    }

    #[test]
    fn rejects_wrong_buffer_size() {
        assert!(encode_rgb(&vec![0u8; 46], 4, 4, &cfg()).is_err());
        assert!(encode_rgb(&vec![0u8; 49], 4, 4, &cfg()).is_err());
        assert!(encode_rgb(&vec![0u8; 48], 4, 4, &cfg()).is_ok());
    }

    // ── 8-bit RGB / RGBA ─────────────────────────────────────────────────

    #[test]
    fn encode_rgb8_produces_heic() {
        let out = encode_rgb(&vec![100u8; 16 * 16 * 3], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_rgb8_without_sao_produces_heic() {
        let pixels: Vec<u8> = (0..128 * 128 * 3).map(|i| (i & 255) as u8).collect();
        let out = encode_rgb(&pixels, 128, 128, &cfg().with_quality(30).with_sao(false)).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_rgba8_strips_alpha() {
        let out = encode_rgba(&vec![100u8; 16 * 16 * 4], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_rgba8_with_alpha_produces_heic() {
        let out = encode_rgba_with_alpha(&vec![200u8; 16 * 16 * 4], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    // ── 10-bit RGB / RGBA ────────────────────────────────────────────────

    #[test]
    fn encode_rgb10_produces_heic() {
        let out = encode_rgb10(&vec![512u16; 16 * 16 * 3], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_rgba10_strips_alpha() {
        let out = encode_rgba10(&vec![512u16; 16 * 16 * 4], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_rgba10_with_alpha_produces_heic() {
        let out = encode_rgba10_with_alpha(&vec![512u16; 16 * 16 * 4], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_rgb12_produces_heic() {
        let out = encode_rgb12(&vec![2048u16; 16 * 16 * 3], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_rgba12_with_alpha_produces_heic() {
        let out = encode_rgba12_with_alpha(&vec![2048u16; 16 * 16 * 4], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_gray8_produces_heic() {
        let out = encode_gray(&vec![128u8; 16 * 16], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_gray_alpha8_strips_alpha() {
        let out = encode_gray_alpha(&vec![200u8; 16 * 16 * 2], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_gray_alpha8_with_alpha_produces_heic() {
        let out = encode_gray_alpha_with_alpha(&vec![180u8; 16 * 16 * 2], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_gray10_produces_heic() {
        let out = encode_gray10(&vec![512u16; 16 * 16], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_gray_alpha10_with_alpha_produces_heic() {
        let out =
            encode_gray_alpha10_with_alpha(&vec![512u16; 16 * 16 * 2], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_gray12_produces_heic() {
        let out = encode_gray12(&vec![2048u16; 16 * 16], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    #[test]
    fn encode_gray_alpha12_with_alpha_produces_heic() {
        let out =
            encode_gray_alpha12_with_alpha(&vec![2048u16; 16 * 16 * 2], 16, 16, &cfg()).unwrap();
        assert!(out.len() > 100);
    }

    // ── YUV direct API ───────────────────────────────────────────────────

    #[test]
    fn encode_yuv_roundtrips() {
        let rgb = vec![128u16; 16 * 16 * 3];
        let yuv = yuv::rgb_to_yuv(&rgb, 16, 16, ChromaFormat::Yuv420, BitDepth::Eight);
        let out = encode_yuv(&yuv, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_yuv_rejects_invalid_planes() {
        let bad = Yuv::from_planes(
            vec![0u16; 15], // should be 16
            vec![0u16; 4],
            vec![0u16; 4],
            4,
            4,
            ChromaFormat::Yuv420,
            BitDepth::Eight,
        );
        assert!(bad.is_err());
    }

    #[test]
    fn odd_dimensions_reported_in_ispe() {
        let rgb = vec![100u8; 281 * 181 * 3];
        let out = encode_rgb(&rgb, 281, 181, &cfg().with_chroma(ChromaFormat::Yuv420)).unwrap();

        let ispe = out
            .array_windows::<4>()
            .position(|w| w == b"ispe")
            .expect("ispe");
        let wpos = ispe + 4 + 4;
        let w = u32::from_be_bytes(out[wpos..wpos + 4].try_into().unwrap());
        let h = u32::from_be_bytes(out[wpos + 4..wpos + 8].try_into().unwrap());
        assert_eq!((w, h), (281, 181));
    }

    #[test]
    fn encode_1x1_rgb8() {
        assert!(encode_rgb(&[255, 0, 0], 1, 1, &cfg()).is_ok());
    }

    #[test]
    fn encode_1x1_gray8() {
        assert!(encode_gray(&[128], 1, 1, &cfg()).is_ok());
    }

    #[test]
    fn encode_1x1_rgba8_with_alpha() {
        assert!(encode_rgba_with_alpha(&[255, 0, 0, 255], 1, 1, &cfg()).is_ok());
    }

    #[test]
    fn tiled_rgb8_produces_grid_heic() {
        // 1024×768 triggers 2×2 GridWpp tiling. Quality 30 also exercises
        // activity AQ independently inside every WPP-coded grid cell.
        let px: Vec<u8> = (0u32..1024 * 768 * 3).map(|i| (i % 256) as u8).collect();
        let out = encode_rgb(&px, 1024, 768, &cfg().with_quality(30)).unwrap();
        assert!(out.len() > 1000);
        assert_eq!(&out[4..8], b"ftyp");
        // A grid HEIC has a 'grid' item type in iinf.
        assert!(
            out.array_windows::<4>().any(|w| w == b"grid"),
            "expected grid item"
        );
    }

    #[test]
    fn tiled_rgb10_produces_grid_heic() {
        let px = vec![512u16; 1024 * 768 * 3];
        let out = encode_rgb10(&px, 1024, 768, &cfg()).unwrap();
        assert!(out.array_windows::<4>().any(|w| w == b"grid"));
    }

    #[test]
    fn tiled_gray8_produces_grid_heic() {
        let px: Vec<u8> = (0u32..1024 * 768).map(|i| (i % 256) as u8).collect();
        let out = encode_gray(&px, 1024, 768, &cfg()).unwrap();
        assert!(out.array_windows::<4>().any(|w| w == b"grid"));
    }

    #[test]
    fn tiled_yuv_produces_grid_heic() {
        let rgb = vec![200u16; 1024 * 768 * 3];
        let yuv = yuv::rgb_to_yuv(&rgb, 1024, 768, ChromaFormat::Yuv420, BitDepth::Eight);
        let out = encode_yuv(&yuv, &cfg()).unwrap();
        assert!(out.array_windows::<4>().any(|w| w == b"grid"));
    }

    #[test]
    fn tiled_grid_has_correct_ispe() {
        // ispe for the grid item should reflect the full image dimensions.
        let px: Vec<u8> = vec![128u8; 1024 * 768 * 3];
        let out = encode_rgb(&px, 1024, 768, &cfg()).unwrap();
        // Find the ispe that has 1024×768 (not the tile-size ispe 512×512).
        let mut found = false;
        let mut i = 0;
        while i + 16 <= out.len() {
            if &out[i..i + 4] == b"ispe" {
                let w = u32::from_be_bytes(out[i + 8..i + 12].try_into().unwrap());
                let h = u32::from_be_bytes(out[i + 12..i + 16].try_into().unwrap());
                if w == 1024 && h == 768 {
                    found = true;
                    break;
                }
            }
            i += 1;
        }
        assert!(found, "no ispe 1024×768 found in tiled output");
    }

    // ── tiled alpha ──────────────────────────────────────────────────────

    #[test]
    fn tiled_rgba8_with_alpha_produces_grid_heic() {
        let px: Vec<u8> = (0u32..1024 * 768 * 4).map(|i| (i % 256) as u8).collect();
        let out = encode_rgba_with_alpha(&px, 1024, 768, &cfg()).unwrap();
        assert!(
            out.array_windows::<4>().any(|w| w == b"grid"),
            "expected grid item"
        );
        assert!(
            out.array_windows::<4>().any(|w| w == b"auxl"),
            "expected auxl reference"
        );
        assert!(
            out.array_windows::<4>().any(|w| w == b"auxC"),
            "expected auxC property"
        );
    }

    #[test]
    fn tiled_rgba10_with_alpha_produces_grid_heic() {
        let px = vec![512u16; 1024 * 768 * 4];
        let out = encode_rgba10_with_alpha(&px, 1024, 768, &cfg()).unwrap();
        assert!(out.array_windows::<4>().any(|w| w == b"grid"));
        assert!(out.array_windows::<4>().any(|w| w == b"auxl"));
    }

    #[test]
    fn tiled_gray_alpha8_with_alpha_produces_grid_heic() {
        let px: Vec<u8> = (0u32..1024 * 768 * 2).map(|i| (i % 256) as u8).collect();
        let out = encode_gray_alpha_with_alpha(&px, 1024, 768, &cfg()).unwrap();
        assert!(out.array_windows::<4>().any(|w| w == b"grid"));
        assert!(out.array_windows::<4>().any(|w| w == b"auxl"));
    }

    #[test]
    fn tiled_alpha_grid_has_correct_ispe() {
        let px: Vec<u8> = vec![200u8; 1024 * 768 * 4];
        let out = encode_rgba_with_alpha(&px, 1024, 768, &cfg()).unwrap();
        // Must contain an ispe 1024×768 for the color grid item.
        let mut found = false;
        let mut i = 0;
        while i + 16 <= out.len() {
            if &out[i..i + 4] == b"ispe" {
                let w = u32::from_be_bytes(out[i + 8..i + 12].try_into().unwrap());
                let h = u32::from_be_bytes(out[i + 12..i + 16].try_into().unwrap());
                if w == 1024 && h == 768 {
                    found = true;
                    break;
                }
            }
            i += 1;
        }
        assert!(found, "no ispe 1024×768 in tiled alpha output");
    }

    #[test]
    fn tiled_alpha_has_two_grid_items() {
        let px: Vec<u8> = vec![128u8; 1024 * 768 * 4];
        let out = encode_rgba_with_alpha(&px, 1024, 768, &cfg()).unwrap();
        // Two 'grid' entries in iinf: color grid + alpha grid.
        let count = out.array_windows::<4>().filter(|w| *w == b"grid").count();
        assert_eq!(
            count, 2,
            "expected 2 grid items (color + alpha), got {count}"
        );
    }
    // ── checked_buffer_size ──────────────────────────────────────────────

    #[test]
    fn buffer_size_correct() {
        assert_eq!(checked_buffer_size::<u16>(4, 4, 3).unwrap(), 48);
        assert_eq!(checked_buffer_size::<u8>(1, 1, 1).unwrap(), 1);
    }

    #[test]
    fn buffer_size_overflow() {
        assert!(checked_buffer_size::<u16>(usize::MAX, usize::MAX, 3).is_err());
    }

    #[test]
    fn pad_replicates_column() {
        let src = vec![10u16, 20, 30];
        assert_eq!(pad_buf::<3>(&src, 1, 1, 2, 1), vec![10, 20, 30, 10, 20, 30]);
    }

    #[test]
    fn pad_replicates_row() {
        let src = vec![10u16, 20, 30];
        assert_eq!(pad_buf::<3>(&src, 1, 1, 1, 2), vec![10, 20, 30, 10, 20, 30]);
    }

    #[test]
    fn pad_noop_when_aligned() {
        let src: Vec<u16> = (0..12).collect();
        assert_eq!(pad_buf::<3>(&src, 2, 2, 2, 2), src);
    }

    #[test]
    fn encode_yuv_with_alpha_roundtrips() {
        let rgb = vec![128u16; 16 * 16 * 3];
        let yuv = yuv::rgb_to_yuv(&rgb, 16, 16, ChromaFormat::Yuv420, BitDepth::Eight);
        let alpha = vec![200u16; 16 * 16];
        let out = encode_yuv_with_alpha(&yuv, &alpha, &cfg()).unwrap();
        assert!(out.len() > 100);
        assert_eq!(&out[4..8], b"ftyp");
        // The auxiliary alpha item adds an `auxl` item reference.
        assert!(
            out.array_windows::<4>().any(|w| w == b"auxl"),
            "expected an auxl reference for the alpha aux image"
        );
    }

    #[test]
    fn encode_yuv_with_alpha_444_roundtrips() {
        let rgb = vec![64u16; 16 * 16 * 3];
        let yuv = yuv::rgb_to_yuv(&rgb, 16, 16, ChromaFormat::Yuv444, BitDepth::Eight);
        let alpha = vec![255u16; 16 * 16];
        let out = encode_yuv_with_alpha(&yuv, &alpha, &cfg()).unwrap();
        assert_eq!(&out[4..8], b"ftyp");
    }

    #[test]
    fn encode_yuv_with_alpha_rejects_bad_alpha_len() {
        let rgb = vec![128u16; 16 * 16 * 3];
        let yuv = yuv::rgb_to_yuv(&rgb, 16, 16, ChromaFormat::Yuv420, BitDepth::Eight);
        let short_alpha = vec![0u16; 16 * 16 - 1];
        assert!(encode_yuv_with_alpha(&yuv, &short_alpha, &cfg()).is_err());
    }
}