oxideav-avif 0.0.15

Pure-Rust AVIF (AV1 Image File Format) decoder — HEIF meta-box walk + primary-item / av1C extraction, handed to oxideav-av1 for end-to-end pixel decode; grid + alpha + irot/imir/clap composition
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
//! Pixel → AVIF **still-image encoder** — registry-gated.
//!
//! This module closes the gap the container muxer ([`crate::mux`])
//! deliberately left open: it turns raw pixels into the coded AV1
//! Image Item Data by driving `oxideav_av1`'s conformance-grade
//! KEY-frame encoder, then wraps the result through [`crate::AvifMuxer`]
//! / [`crate::AvifGridMuxer`] into a conformant AVIF file.
//!
//! # Coverage
//!
//! * Every conformant (bit depth, chroma format) pairing the AV1
//!   spec admits: 8 / 10 / 12-bit samples in 4:2:0, 4:2:2, 4:4:4 or
//!   monochrome layout (§6.4.1 `seq_profile` is elected per pairing by
//!   the AV1 encoder; the emitted `av1C` record mirrors the sequence
//!   header per av1-avif §2.2.1 "The values of the fields in the
//!   AV1ItemConfigurationProperty shall match those of the Sequence
//!   Header OBU in the AV1 Image Item Data").
//! * **RGB(A)** input via the H.273 identity matrix
//!   (`matrix_coefficients = 0`) in 4:4:4 — the mapping is exact
//!   (Y = G, Cb = B, Cr = R; see [`crate::cicp::CicpTriple::is_identity_matrix`]),
//!   so a lossless encode round-trips RGB byte-for-byte. The `colr`
//!   `nclx` property signals the identity triple with full range.
//! * **Alpha** as a separate AV1-coded monochrome auxiliary item
//!   (av1-avif §4.1): same bit depth as the master (the §4.1 `shall`),
//!   no `colr` (the §4.1 `should`), hidden item + `auxC` alpha URN +
//!   `auxl` iref, `prem` iref when premultiplied.
//! * **Arbitrary dimensions.** The AV1 encoder codes multiples of 8
//!   per axis (min 8); other extents are edge-replicated up to the
//!   next multiple and cropped back with an essential `clap` property
//!   anchored top-left (av1-avif §2.2.3). `ispe` always documents the
//!   coded frame extents per the §2.2.2 `shall` (`image_width` /
//!   `image_height` equal `UpscaledWidth` / `FrameHeight`).
//! * **Grid encode** ([`encode_still_grid`]) for canvases beyond the
//!   single-item limit: the canvas splits into equal coded tiles
//!   (HEIF §6.6.2 `grid` derived item, `dimg` irefs), the declared
//!   output extents trim the right/bottom overflow, and out-of-canvas
//!   tile content is edge-replicated.
//! * The `ftyp` profile brand follows the coded `seq_profile`
//!   (av1-avif §8): Main → `MA1B`, High → `MA1A`, Professional
//!   (4:2:2 / 12-bit) → general brands only (§8.1).
//!
//! # Exactness
//!
//! At `base_q_idx = 0` the AV1 encode is lossless — the AVIF file
//! decodes back (through this crate's own [`crate::AvifDecoder`] or
//! any conformant reader) to the input samples exactly. Lossy encodes
//! are validated PSNR-gated in the test suite.

use crate::api::EncodeSpeed;
use crate::error::{AvifError as Error, Result};
use crate::meta::{Clap, Colr};
use crate::mux::{
    AvifGridMuxer, AvifMuxer, AvifOverlayMuxer, GridTile, IdentityDerivation, OverlayLayer,
    ToneMapItem,
};

use oxideav_av1::encoder::scalable_gop::encode_spatial_layered_gop_yuv_with_q;
use oxideav_av1::encoder::still::{
    auto_tile_layout, encode_key_frame_yuv_with_options, encode_still_yuv, StillOptions, StillSpeed,
};
use oxideav_av1::encoder::temporal_unit::encode_sequence_header_obu;
use oxideav_av1::encoder::yuv_frame::{ChromaFormat, YuvFrame};
use oxideav_av1::{parse_obu, ObuType, SequenceHeader};

pub use crate::api::{EncodeOptions, StillChroma};

/// The encode options under their pre-contract name.
#[deprecated(
    since = "0.0.13",
    note = "renamed to `oxideav_avif::EncodeOptions` (image-crate API contract)"
)]
pub type StillEncodeOptions = EncodeOptions;

impl StillChroma {
    pub(crate) fn to_av1(self) -> ChromaFormat {
        match self {
            StillChroma::Yuv420 => ChromaFormat::Yuv420,
            StillChroma::Yuv422 => ChromaFormat::Yuv422,
            StillChroma::Yuv444 => ChromaFormat::Yuv444,
            StillChroma::Monochrome => ChromaFormat::Monochrome,
        }
    }
}

/// One still image handed to [`encode_still`] / [`encode_still_grid`].
///
/// Samples are carried as `u16` regardless of bit depth (values must
/// fit `bit_depth` bits); the 8-bit constructors widen for you. Planes
/// are tightly packed row-major at their natural (subsampled) extents.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct StillImage {
    /// Luma width in pixels (≥ 1).
    pub width: u32,
    /// Luma height in pixels (≥ 1).
    pub height: u32,
    /// 8, 10 or 12.
    pub bit_depth: u8,
    /// Chroma layout.
    pub chroma: StillChroma,
    /// Luma plane, `width × height`.
    pub y: Vec<u16>,
    /// Cb plane at the subsampled extent (empty for monochrome).
    pub u: Vec<u16>,
    /// Cr plane at the subsampled extent (empty for monochrome).
    pub v: Vec<u16>,
    /// Optional full-resolution alpha plane (`width × height`, same
    /// bit depth as the colour planes — the av1-avif §4.1 `shall`).
    pub alpha: Option<Vec<u16>>,
    /// Optional full-resolution depth map (`width × height`, coded as a
    /// monochrome auxiliary at the master's bit depth — av1-avif §4.1 /
    /// HEIF §6.9.2 `urn:mpeg:mpegB:cicp:systems:auxiliary:depth`).
    pub depth_map: Option<Vec<u16>>,
    /// Optional `colr` colour-information property for the primary
    /// item. The RGB(A) constructors pre-fill the identity-matrix
    /// `nclx` triple; YUV constructors leave it `None`.
    pub colr: Option<Colr>,
    /// Optional pass-through container properties (Exif / XMP /
    /// HDR metadata / orientation), muxed alongside the coded item.
    pub props: StillProperties,
}

impl StillImage {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        width: u32,
        height: u32,
        bit_depth: u8,
        chroma: StillChroma,
        y: Vec<u16>,
        u: Vec<u16>,
        v: Vec<u16>,
        alpha: Option<Vec<u16>>,
        depth_map: Option<Vec<u16>>,
        colr: Option<Colr>,
        props: StillProperties,
    ) -> Self {
        Self {
            width,
            height,
            bit_depth,
            chroma,
            y,
            u,
            v,
            alpha,
            depth_map,
            colr,
            props,
        }
    }
}

/// Pass-through container properties for [`encode_still`] — carried
/// straight to the muxer, no pixel-path involvement.
///
/// * `exif` — an `ExifDataBlock` (4-byte `exif_tiff_header_offset` +
///   TIFF-structured bytes), linked via a `cdsc` iref (av1-avif §5.2).
/// * `xmp` — an XMP packet as a `mime` item (`application/rdf+xml`),
///   linked via `cdsc` (av1-avif §5.3).
/// * `mdcv` / `clli` / `amve` — HDR descriptive properties.
/// * `irot` / `imir` — essential transformative orientation
///   properties (HEIF §6.5.10 application order `clap` → `irot` →
///   `imir`; the encoder's own padding `clap` composes with them).
/// * `pasp` — pixel aspect ratio.
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct StillProperties {
    /// Exif payload (av1-avif §5.2).
    pub exif: Option<Vec<u8>>,
    /// XMP payload (av1-avif §5.3).
    pub xmp: Option<Vec<u8>>,
    /// Mastering display colour volume (ISO/IEC 14496-12 §12.1.5.3).
    pub mdcv: Option<crate::meta::Mdcv>,
    /// Content light level (ISO/IEC 14496-12 §12.1.5.4).
    pub clli: Option<crate::meta::Clli>,
    /// Ambient viewing environment (AVIF §6.5.36).
    pub amve: Option<crate::meta::Amve>,
    /// Rotation, anti-clockwise quarter turns 0..=3.
    pub irot: Option<u8>,
    /// Mirror axis (0 = vertical flip, 1 = horizontal flip).
    pub imir: Option<u8>,
    /// Pixel aspect ratio.
    pub pasp: Option<crate::meta::Pasp>,
    /// Make the primary an `iden` identity derivation of the coded
    /// image carrying these transformative properties (HEIF
    /// §6.6.2.1) — the coded item stays exposed untransformed
    /// alongside. See [`AvifMuxer::with_identity_derivation`].
    pub identity_derivation: Option<IdentityDerivation>,
    /// A gain map (ISO 21496-1) making the file a `tmap` tone-map
    /// derived image (HEIF Amd 1:2025 §6.6.2.4, av1-avif §4.2.2) with
    /// this picture as the base. See [`GainMapSpec`].
    pub gain_map: Option<Box<GainMapSpec>>,
    /// An ICC profile, written as a second (`prof`) `colr` property
    /// next to the `nclx` one ([`AvifMuxer::with_icc`]). Not a
    /// positional argument of [`Self::new`]; set it with
    /// [`Self::with_icc`].
    pub icc: Option<Vec<u8>>,
}

impl StillProperties {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        exif: Option<Vec<u8>>,
        xmp: Option<Vec<u8>>,
        mdcv: Option<crate::meta::Mdcv>,
        clli: Option<crate::meta::Clli>,
        amve: Option<crate::meta::Amve>,
        irot: Option<u8>,
        imir: Option<u8>,
        pasp: Option<crate::meta::Pasp>,
        identity_derivation: Option<IdentityDerivation>,
        gain_map: Option<Box<GainMapSpec>>,
    ) -> Self {
        Self {
            exif,
            xmp,
            mdcv,
            clli,
            amve,
            irot,
            imir,
            pasp,
            identity_derivation,
            gain_map,
            icc: None,
        }
    }
    /// Setter: replace `icc`.
    pub fn with_icc(mut self, icc: Option<Vec<u8>>) -> Self {
        self.icc = icc;
        self
    }
    /// Setter: replace `exif`.
    pub fn with_exif(mut self, exif: Option<Vec<u8>>) -> Self {
        self.exif = exif;
        self
    }
    /// Setter: replace `xmp`.
    pub fn with_xmp(mut self, xmp: Option<Vec<u8>>) -> Self {
        self.xmp = xmp;
        self
    }
    /// Setter: replace `mdcv`.
    pub fn with_mdcv(mut self, mdcv: Option<crate::meta::Mdcv>) -> Self {
        self.mdcv = mdcv;
        self
    }
    /// Setter: replace `clli`.
    pub fn with_clli(mut self, clli: Option<crate::meta::Clli>) -> Self {
        self.clli = clli;
        self
    }
    /// Setter: replace `amve`.
    pub fn with_amve(mut self, amve: Option<crate::meta::Amve>) -> Self {
        self.amve = amve;
        self
    }
    /// Setter: replace `irot`.
    pub fn with_irot(mut self, irot: Option<u8>) -> Self {
        self.irot = irot;
        self
    }
    /// Setter: replace `imir`.
    pub fn with_imir(mut self, imir: Option<u8>) -> Self {
        self.imir = imir;
        self
    }
    /// Setter: replace `pasp`.
    pub fn with_pasp(mut self, pasp: Option<crate::meta::Pasp>) -> Self {
        self.pasp = pasp;
        self
    }
    /// Setter: replace `identity_derivation`.
    pub fn with_identity_derivation(
        mut self,
        identity_derivation: Option<IdentityDerivation>,
    ) -> Self {
        self.identity_derivation = identity_derivation;
        self
    }
    /// Setter: replace `gain_map`.
    pub fn with_gain_map(mut self, gain_map: Option<Box<GainMapSpec>>) -> Self {
        self.gain_map = gain_map;
        self
    }
}

/// A gain map to author alongside a still (`StillProperties::gain_map`):
/// the map picture is coded as a hidden `av01` item (its own size,
/// depth and chroma; its `colr` matrix / range as given with
/// primaries / transfer forced to 2 per HEIF Amd 1 §6.6.2.4.1), the
/// metadata becomes the `tmap` item body, `alternate_colr` the
/// `tmap` item's own `colr` (the fully-applied rendition's
/// colorimetry), and the `tmap` is placed in an `altr` group with the
/// base, which stays the primary.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct GainMapSpec {
    /// The gain map picture (monochrome, or 3-channel when the
    /// metadata is multichannel; alpha / depth ignored).
    pub map: StillImage,
    /// The ISO 21496-1 metadata (C.2).
    pub metadata: oxideav_heif::gainmap::GainMapMetadata,
    /// The alternate (fully applied) colorimetry.
    pub alternate_colr: Colr,
    /// `clli` of the alternate rendition.
    pub alternate_clli: Option<crate::meta::Clli>,
    /// Bits per channel of the reconstructed image (the `tmap`
    /// `pixi` hint, which also sets the depth the decoder
    /// reconstructs at); defaults to the base's depth.
    pub alternate_bit_depth: Option<u8>,
    /// AV1 `base_q_idx` for the gain map (`0` = lossless).
    pub q: u8,
}

impl GainMapSpec {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        map: StillImage,
        metadata: oxideav_heif::gainmap::GainMapMetadata,
        alternate_colr: Colr,
        alternate_clli: Option<crate::meta::Clli>,
        alternate_bit_depth: Option<u8>,
        q: u8,
    ) -> Self {
        Self {
            map,
            metadata,
            alternate_colr,
            alternate_clli,
            alternate_bit_depth,
            q,
        }
    }
    /// Setter: replace `map`.
    pub fn with_map(mut self, map: StillImage) -> Self {
        self.map = map;
        self
    }
    /// Setter: replace `metadata`.
    pub fn with_metadata(mut self, metadata: oxideav_heif::gainmap::GainMapMetadata) -> Self {
        self.metadata = metadata;
        self
    }
    /// Setter: replace `alternate_colr`.
    pub fn with_alternate_colr(mut self, alternate_colr: Colr) -> Self {
        self.alternate_colr = alternate_colr;
        self
    }
    /// Setter: replace `alternate_clli`.
    pub fn with_alternate_clli(mut self, alternate_clli: Option<crate::meta::Clli>) -> Self {
        self.alternate_clli = alternate_clli;
        self
    }
    /// Setter: replace `alternate_bit_depth`.
    pub fn with_alternate_bit_depth(mut self, alternate_bit_depth: Option<u8>) -> Self {
        self.alternate_bit_depth = alternate_bit_depth;
        self
    }
    /// Setter: replace `q`.
    pub fn with_q(mut self, q: u8) -> Self {
        self.q = q;
        self
    }
}

impl StillImage {
    /// General constructor: any (bit depth, chroma) pairing with
    /// `u16`-carried samples.
    pub fn yuv(
        width: u32,
        height: u32,
        bit_depth: u8,
        chroma: StillChroma,
        y: Vec<u16>,
        u: Vec<u16>,
        v: Vec<u16>,
    ) -> Result<Self> {
        let img = Self {
            width,
            height,
            bit_depth,
            chroma,
            y,
            u,
            v,
            alpha: None,
            depth_map: None,
            colr: None,
            props: StillProperties::default(),
        };
        img.validate()?;
        Ok(img)
    }

    /// 8-bit 4:2:0 constructor (even `width` / `height` required).
    pub fn yuv420_8(width: u32, height: u32, y: &[u8], u: &[u8], v: &[u8]) -> Result<Self> {
        Self::yuv(
            width,
            height,
            8,
            StillChroma::Yuv420,
            widen(y),
            widen(u),
            widen(v),
        )
    }

    /// 8-bit 4:2:2 constructor (even `width` required).
    pub fn yuv422_8(width: u32, height: u32, y: &[u8], u: &[u8], v: &[u8]) -> Result<Self> {
        Self::yuv(
            width,
            height,
            8,
            StillChroma::Yuv422,
            widen(y),
            widen(u),
            widen(v),
        )
    }

    /// 8-bit 4:4:4 constructor.
    pub fn yuv444_8(width: u32, height: u32, y: &[u8], u: &[u8], v: &[u8]) -> Result<Self> {
        Self::yuv(
            width,
            height,
            8,
            StillChroma::Yuv444,
            widen(y),
            widen(u),
            widen(v),
        )
    }

    /// 8-bit monochrome (4:0:0) constructor.
    pub fn gray_8(width: u32, height: u32, y: &[u8]) -> Result<Self> {
        Self::yuv(
            width,
            height,
            8,
            StillChroma::Monochrome,
            widen(y),
            Vec::new(),
            Vec::new(),
        )
    }

    /// Interleaved 8-bit RGB (3 bytes per pixel) via the H.273
    /// **identity matrix** in 4:4:4: `Y = G`, `Cb = B`, `Cr = R` —
    /// mathematically exact, so a lossless encode round-trips the RGB
    /// bytes exactly. Pre-fills the `colr` `nclx` identity triple
    /// (BT.709 primaries, sRGB transfer, `matrix_coefficients = 0`,
    /// full range).
    pub fn rgb8(width: u32, height: u32, rgb: &[u8]) -> Result<Self> {
        let n = (width as usize) * (height as usize);
        if rgb.len() != n * 3 {
            return Err(Error::invalid(format!(
                "avif still: rgb8 expects {} bytes for {width}x{height}, got {}",
                n * 3,
                rgb.len()
            )));
        }
        let mut y = Vec::with_capacity(n);
        let mut u = Vec::with_capacity(n);
        let mut v = Vec::with_capacity(n);
        for px in rgb.chunks_exact(3) {
            v.push(px[0] as u16); // R → Cr
            y.push(px[1] as u16); // G → Y
            u.push(px[2] as u16); // B → Cb
        }
        let mut img = Self::yuv(width, height, 8, StillChroma::Yuv444, y, u, v)?;
        img.colr = Some(identity_full_range_colr());
        Ok(img)
    }

    /// Interleaved 8-bit RGBA (4 bytes per pixel) — the RGB channels
    /// as [`Self::rgb8`] plus the A channel as an alpha auxiliary.
    pub fn rgba8(width: u32, height: u32, rgba: &[u8]) -> Result<Self> {
        let n = (width as usize) * (height as usize);
        if rgba.len() != n * 4 {
            return Err(Error::invalid(format!(
                "avif still: rgba8 expects {} bytes for {width}x{height}, got {}",
                n * 4,
                rgba.len()
            )));
        }
        let mut y = Vec::with_capacity(n);
        let mut u = Vec::with_capacity(n);
        let mut v = Vec::with_capacity(n);
        let mut a = Vec::with_capacity(n);
        for px in rgba.chunks_exact(4) {
            v.push(px[0] as u16);
            y.push(px[1] as u16);
            u.push(px[2] as u16);
            a.push(px[3] as u16);
        }
        let mut img = Self::yuv(width, height, 8, StillChroma::Yuv444, y, u, v)?;
        img.colr = Some(identity_full_range_colr());
        img.alpha = Some(a);
        img.validate()?;
        Ok(img)
    }

    /// Attach a full-resolution alpha plane (`width × height` samples
    /// at the image's bit depth).
    /// Attach a depth map (`width × height` samples at the image's
    /// bit depth), encoded as a hidden monochrome auxiliary item.
    pub fn with_depth_map(mut self, depth_map: Vec<u16>) -> Result<Self> {
        if depth_map.len() != self.width as usize * self.height as usize {
            return Err(Error::invalid(format!(
                "avif still: depth map has {} samples, expected {}x{}",
                depth_map.len(),
                self.width,
                self.height
            )));
        }
        self.depth_map = Some(depth_map);
        Ok(self)
    }

    pub fn with_alpha(mut self, alpha: Vec<u16>) -> Result<Self> {
        self.alpha = Some(alpha);
        self.validate()?;
        Ok(self)
    }

    /// Attach a `colr` property for the primary item (overrides any
    /// constructor-provided value).
    pub fn with_colr(mut self, colr: Colr) -> Self {
        self.colr = Some(colr);
        self
    }

    /// Attach pass-through container properties (Exif / XMP / HDR /
    /// orientation / aspect); see [`StillProperties`].
    pub fn with_props(mut self, props: StillProperties) -> Self {
        self.props = props;
        self
    }

    /// Chroma plane extents implied by `(width, height, chroma)`.
    pub(crate) fn chroma_dims(&self) -> (u32, u32) {
        if !self.chroma.has_chroma() {
            return (0, 0);
        }
        let (sx, sy) = self.chroma.subsampling();
        (self.width >> sx, self.height >> sy)
    }

    /// Shape / depth / range validation.
    pub(crate) fn validate(&self) -> Result<()> {
        if self.width == 0 || self.height == 0 {
            return Err(Error::invalid(
                "avif still: dimensions must be at least 1x1",
            ));
        }
        if !matches!(self.bit_depth, 8 | 10 | 12) {
            return Err(Error::invalid(format!(
                "avif still: bit_depth must be 8, 10 or 12, got {}",
                self.bit_depth
            )));
        }
        let (sx, sy) = self.chroma.subsampling();
        if self.chroma.has_chroma()
            && ((sx == 1 && self.width % 2 != 0) || (sy == 1 && self.height % 2 != 0))
        {
            return Err(Error::invalid(format!(
                "avif still: {:?} requires even subsampled extents, got {}x{}",
                self.chroma, self.width, self.height
            )));
        }
        let luma_len = (self.width as usize) * (self.height as usize);
        if self.y.len() != luma_len {
            return Err(Error::invalid(format!(
                "avif still: Y plane length {} != {}x{}",
                self.y.len(),
                self.width,
                self.height
            )));
        }
        let (cw, ch) = self.chroma_dims();
        let chroma_len = (cw as usize) * (ch as usize);
        if self.u.len() != chroma_len || self.v.len() != chroma_len {
            return Err(Error::invalid(format!(
                "avif still: chroma plane lengths ({}, {}) != expected {chroma_len}",
                self.u.len(),
                self.v.len()
            )));
        }
        if let Some(a) = &self.alpha {
            if a.len() != luma_len {
                return Err(Error::invalid(format!(
                    "avif still: alpha plane length {} != {}x{} (alpha is full resolution)",
                    a.len(),
                    self.width,
                    self.height
                )));
            }
        }
        let ceil = 1u32 << self.bit_depth;
        let in_range = |p: &[u16]| p.iter().all(|&s| (s as u32) < ceil);
        if !in_range(&self.y)
            || !in_range(&self.u)
            || !in_range(&self.v)
            || !self.alpha.as_deref().map(in_range).unwrap_or(true)
            || !self.depth_map.as_deref().map(in_range).unwrap_or(true)
        {
            return Err(Error::invalid(format!(
                "avif still: sample exceeds bit_depth {} range",
                self.bit_depth
            )));
        }
        Ok(())
    }
}

/// Per-axis coded-extent bound of the single-item encode (mirrors the
/// AV1 KEY-frame encoder's bound). Larger canvases go through
/// [`encode_still_grid`].
pub const STILL_MAX_CODED_DIM: u32 = 4096;

/// Per-axis floor on a grid tile's coded extents. External AVIF readers
/// reject grids whose tiles are narrower or shorter than 64 pixels
/// (the MIAF grid-tile constraint their diagnostics cite as ISO/IEC
/// 23000-22 §7.3.11.4.2), so the tile election never goes below it.
pub const GRID_MIN_TILE_DIM: u32 = 64;

/// Elect a `(columns, rows)` grid tiling for a `width × height` image
/// whose tiles must fit `max_tile` coded pixels per axis (and stay at
/// least [`GRID_MIN_TILE_DIM`]): the fewest tiles per axis that bring
/// the coded tile extent under the bound. Returns `None` when no
/// tiling satisfies both bounds (an axis shorter than the floor that
/// still needs splitting cannot happen for `max_tile ≥ 64`, so this
/// is only `None` for a zero extent or a bound below the floor).
pub fn elect_grid_tiling(width: u32, height: u32, max_tile: u32) -> Option<(u16, u16)> {
    if width == 0 || height == 0 || max_tile < GRID_MIN_TILE_DIM {
        return None;
    }
    let per_axis = |extent: u32| -> Option<u16> {
        let mut count = 1u32;
        loop {
            let tile = coded_extent(extent.div_ceil(count));
            if tile <= max_tile {
                // Never leave a fully-trimmed tile and never go below
                // the floor.
                if (count - 1) * tile >= extent || (count > 1 && tile < GRID_MIN_TILE_DIM) {
                    return None;
                }
                return u16::try_from(count).ok();
            }
            count += 1;
            if count > 256 {
                return None;
            }
        }
    };
    Some((per_axis(width)?, per_axis(height)?))
}

/// Encode `img` as a single coded item when its coded extents fit
/// [`STILL_MAX_CODED_DIM`], otherwise as a grid with the tiling from
/// [`elect_grid_tiling`]. The one-call entry point for arbitrary
/// canvases.
pub fn encode_still_auto(img: &StillImage, opts: &EncodeOptions) -> Result<Vec<u8>> {
    let (pw, ph) = (coded_extent(img.width), coded_extent(img.height));
    if pw <= STILL_MAX_CODED_DIM && ph <= STILL_MAX_CODED_DIM {
        return encode_still(img, opts);
    }
    let (columns, rows) = elect_grid_tiling(img.width, img.height, STILL_MAX_CODED_DIM)
        .ok_or_else(|| {
            Error::unsupported(format!(
                "avif still: no grid tiling for {}x{} within {STILL_MAX_CODED_DIM}-pixel tiles",
                img.width, img.height
            ))
        })?;
    encode_still_grid(img, opts, columns, rows)
}

fn widen(p: &[u8]) -> Vec<u16> {
    p.iter().map(|&s| s as u16).collect()
}

/// The `colr` `nclx` triple the RGB constructors signal: BT.709
/// primaries, sRGB transfer, H.273 identity matrix, full range.
pub(crate) fn identity_full_range_colr() -> Colr {
    Colr::Nclx {
        colour_primaries: 1,
        transfer_characteristics: 13,
        matrix_coefficients: 0,
        full_range: true,
    }
}

/// Round `v` up to the coded-extent grid (multiple of 8, min 8).
pub(crate) fn coded_extent(v: u32) -> u32 {
    v.max(8).div_ceil(8) * 8
}

/// Edge-replicate `src` (`w × h`, row-major) out to `pw × ph`.
pub(crate) fn pad_plane(src: &[u16], w: usize, h: usize, pw: usize, ph: usize) -> Vec<u16> {
    debug_assert!(pw >= w && ph >= h && src.len() == w * h);
    if (pw, ph) == (w, h) {
        return src.to_vec();
    }
    let mut out = Vec::with_capacity(pw * ph);
    for row in 0..ph {
        let sr = row.min(h - 1);
        let base = sr * w;
        out.extend_from_slice(&src[base..base + w]);
        let edge = src[base + w - 1];
        out.extend(std::iter::repeat(edge).take(pw - w));
    }
    out
}

/// Copy the `tw × th` rectangle at `(x0, y0)` out of `src`
/// (`w × h`, row-major), edge-replicating anything beyond the source
/// extents (used by the grid splitter for right/bottom overflow
/// tiles).
fn extract_rect(
    src: &[u16],
    w: usize,
    h: usize,
    x0: usize,
    y0: usize,
    tw: usize,
    th: usize,
) -> Vec<u16> {
    debug_assert!(src.len() == w * h && x0 < w && y0 < h);
    let mut out = Vec::with_capacity(tw * th);
    for row in 0..th {
        let sr = (y0 + row).min(h - 1);
        let base = sr * w;
        let avail = w - x0;
        let copy = avail.min(tw);
        out.extend_from_slice(&src[base + x0..base + x0 + copy]);
        if copy < tw {
            let edge = src[base + w - 1];
            out.extend(std::iter::repeat(edge).take(tw - copy));
        }
    }
    out
}

/// Build the 4-byte `av1C` record (av1-isobmff §2.3, no `configOBUs`)
/// mirroring the emitted sequence header — the av1-avif §2.2.1 `shall`
/// ("the values of the fields ... shall match those of the Sequence
/// Header OBU in the AV1 Image Item Data").
pub(crate) fn av1c_from_seq(seq: &SequenceHeader) -> Vec<u8> {
    let op = &seq.operating_points[0];
    let cc = &seq.color_config;
    let b0 = 0x80 | 0x01; // marker=1, version=1
    let b1 = (seq.seq_profile << 5) | (op.seq_level_idx & 0x1f);
    let b2 = ((op.seq_tier & 0x1) << 7)
        | ((cc.high_bitdepth as u8) << 6)
        | ((cc.twelve_bit as u8) << 5)
        | ((cc.mono_chrome as u8) << 4)
        | ((cc.subsampling_x as u8) << 3)
        | ((cc.subsampling_y as u8) << 2)
        | (cc.chroma_sample_position & 0x3);
    vec![b0, b1, b2, 0x00]
}

/// Map an AV1-encoder error into the crate error type with context.
pub(crate) fn av1_err(stage: &str, e: oxideav_av1::Error) -> Error {
    Error::invalid(format!("avif still: AV1 {stage} encode failed: {e}"))
}

/// The `clap` property cropping a `pw × ph` coded frame back to the
/// `w × h` input extents, anchored top-left per the av1-avif §2.2.3
/// `shall` ("the origin of the 'clap' item property shall be anchored
/// to 0,0 (top-left) of the input image"). With the HEIF §6.5.11
/// centre geometry, a top-left anchor means
/// `horizOff = (cleanApertureWidth − frameWidth) / 2` (denominator 2
/// keeps the half-pixel exact), and likewise vertically.
pub(crate) fn top_left_clap(w: u32, h: u32, pw: u32, ph: u32) -> Clap {
    Clap {
        clean_aperture_width_n: w as i32,
        clean_aperture_width_d: 1,
        clean_aperture_height_n: h as i32,
        clean_aperture_height_d: 1,
        horiz_off_n: w as i32 - pw as i32,
        horiz_off_d: 2,
        vert_off_n: h as i32 - ph as i32,
        vert_off_d: 2,
    }
}

/// One coded plane set: the AV1 Image Item Data payload plus its
/// `av1C` record and the elected `seq_profile`.
pub(crate) struct CodedItem {
    pub(crate) payload: Vec<u8>,
    pub(crate) av1c: Vec<u8>,
    pub(crate) seq_profile: u8,
}

/// Re-signal §5.5.2 `color_range = 1` (full range) in the temporal
/// unit's Sequence Header OBU by re-encoding the header descriptor
/// with the flag set and splicing it over the original.
///
/// `color_range` is display metadata — a fixed-width `f(1)` field that
/// no reconstruction step reads — so the spliced stream decodes to
/// identical samples; only the signalled interpretation changes. The
/// samples this module codes are always full-range (they come in as
/// raw pixel values), and the flag matters in two places:
///
/// * the **alpha** auxiliary — av1-avif §4.1 makes it a `shall`: "The
///   color_range field in the Sequence Header OBU shall be set to 1"
///   for every AV1 Auxiliary Image Item (readers also ignore any
///   `colr` on the alpha item per §4.1, so the stream flag is the
///   only range signal — a studio-range flag would make conformant
///   readers rescale the plane);
/// * a full-range `colr` `nclx` on the colour item (e.g. the identity
///   RGB path) — MIAF gives the container property precedence, but a
///   matching in-stream flag keeps both signals consistent.
pub(crate) fn full_range_temporal_unit(unit: &[u8], seq: &SequenceHeader) -> Result<Vec<u8>> {
    let mut seq_full = seq.clone();
    seq_full.color_config.color_range = true;
    let new_sh = encode_sequence_header_obu(&seq_full);
    let mut out = Vec::with_capacity(unit.len());
    let mut off = 0usize;
    let mut replaced = false;
    while off < unit.len() {
        let (desc, consumed) = parse_obu(&unit[off..])
            .map_err(|e| Error::invalid(format!("avif still: OBU walk failed: {e}")))?;
        if desc.obu_type == ObuType::SequenceHeader {
            out.extend_from_slice(&new_sh);
            replaced = true;
        } else {
            out.extend_from_slice(&unit[off..off + consumed]);
        }
        off += consumed;
    }
    if !replaced {
        return Err(Error::invalid(
            "avif still: temporal unit carries no Sequence Header OBU",
        ));
    }
    Ok(out)
}

/// The nominal worker count the AV1 tile layout of every coded item is
/// derived from ([`oxideav_av1::encoder::still::auto_tile_layout`]):
/// fixed, so the coded bytes never depend on the thread budget the
/// search actually runs on (tiles ≥ 256 px wide / 128 px tall, at
/// most 8 of them).
pub const TILE_LAYOUT_THREADS: usize = 8;

/// How one coded item's AV1 search runs: effort, worker threads and
/// the sequence-header shape — `still` codes `still_picture = 1` with
/// the reduced still-picture header (an image item), `!still` a KEY
/// frame under a full non-still header (an image-sequence sample).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct CodedTuning {
    pub(crate) speed: EncodeSpeed,
    pub(crate) threads: usize,
    pub(crate) still: bool,
}

impl CodedTuning {
    /// An image item under `opts`.
    pub(crate) fn of(opts: &EncodeOptions) -> Self {
        Self {
            speed: opts.speed,
            threads: opts.threads.max(1),
            still: true,
        }
    }

    /// An image-sequence sample (`still_picture = 0`).
    pub(crate) fn sequence(speed: EncodeSpeed, threads: usize) -> Self {
        Self {
            speed,
            threads: threads.max(1),
            still: false,
        }
    }
}

fn still_speed(speed: EncodeSpeed) -> StillSpeed {
    match speed {
        EncodeSpeed::Fast => StillSpeed::Fast,
        EncodeSpeed::Balanced => StillSpeed::Balanced,
        EncodeSpeed::Thorough => StillSpeed::Thorough,
    }
}

/// Encode one coded item from (already padded) planes through the AV1
/// still encoder: `q` is the `base_q_idx` (`0` = lossless),
/// `full_range` signals §5.5.2 `color_range = 1` in the emitted
/// sequence header, `tuning` the effort / threads / header shape. The
/// tile layout comes from the picture size alone
/// ([`TILE_LAYOUT_THREADS`]), so the bytes are the same at any thread
/// count.
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode_coded_item(
    pw: u32,
    ph: u32,
    bit_depth: u8,
    format: ChromaFormat,
    y: Vec<u16>,
    u: Vec<u16>,
    v: Vec<u16>,
    q: u8,
    full_range: bool,
    tuning: CodedTuning,
    stage: &str,
) -> Result<CodedItem> {
    let frame = YuvFrame {
        width: pw,
        height: ph,
        bit_depth,
        format,
        y,
        u,
        v,
    };
    let mut so = StillOptions::new(q);
    so.speed = still_speed(tuning.speed);
    so.full_range = full_range;
    so.reduced_header = true;
    let (cols, rows) = auto_tile_layout(pw, ph, TILE_LAYOUT_THREADS);
    so.tile_cols_log2 = cols;
    so.tile_rows_log2 = rows;
    so.auto_tiles = false;
    so.threads = tuning.threads.max(1);
    let coded = if tuning.still {
        encode_still_yuv(&frame, &so)
    } else {
        encode_key_frame_yuv_with_options(&frame, &so)
    }
    .map_err(|e| av1_err(stage, e))?;
    // The AV1 Image Item Data is the content of a sync AV1 sample
    // (av1-avif §2.1) — the encoder's §7.5 temporal-unit bytes
    // (TD + SH + frame OBU; exactly one Sequence Header OBU, the
    // §2.1 `shall`). `color_range` is coded natively from
    // `so.full_range`.
    let av1c = av1c_from_seq(&coded.seq);
    Ok(CodedItem {
        payload: coded.temporal_unit_bytes,
        av1c,
        seq_profile: coded.seq.seq_profile,
    })
}

/// True when the image's `colr` property declares full-range `nclx`
/// samples — the in-stream §5.5.2 `color_range` flag then mirrors it.
pub(crate) fn colr_is_full_range(img: &StillImage) -> bool {
    matches!(
        img.colr,
        Some(Colr::Nclx {
            full_range: true,
            ..
        })
    )
}

/// Pad the image's planes to the coded extents and encode the primary
/// coded item.
fn encode_primary(
    img: &StillImage,
    pw: u32,
    ph: u32,
    q: u8,
    tuning: CodedTuning,
) -> Result<CodedItem> {
    let (w, h) = (img.width as usize, img.height as usize);
    let y = pad_plane(&img.y, w, h, pw as usize, ph as usize);
    let (u, v) = if img.chroma.has_chroma() {
        let (sx, sy) = img.chroma.subsampling();
        let (cw, ch) = img.chroma_dims();
        let (pcw, pch) = ((pw >> sx) as usize, (ph >> sy) as usize);
        (
            pad_plane(&img.u, cw as usize, ch as usize, pcw, pch),
            pad_plane(&img.v, cw as usize, ch as usize, pcw, pch),
        )
    } else {
        (Vec::new(), Vec::new())
    };
    encode_coded_item(
        pw,
        ph,
        img.bit_depth,
        img.chroma.to_av1(),
        y,
        u,
        v,
        q,
        colr_is_full_range(img),
        tuning,
        "primary",
    )
}

/// Encode the alpha plane as a monochrome coded item at the same
/// coded extents and bit depth as the master (av1-avif §4.1).
fn encode_alpha(
    img: &StillImage,
    alpha: &[u16],
    pw: u32,
    ph: u32,
    q: u8,
    tuning: CodedTuning,
) -> Result<CodedItem> {
    let (w, h) = (img.width as usize, img.height as usize);
    let a = pad_plane(alpha, w, h, pw as usize, ph as usize);
    // av1-avif §4.1 `shall`s on the auxiliary stream: `mono_chrome = 1`
    // (satisfied by the Monochrome encode below) and `color_range = 1`
    // (the full-range splice — alpha samples are raw coverage values
    // and readers ignore any `colr` on the alpha item).
    encode_coded_item(
        pw,
        ph,
        img.bit_depth,
        ChromaFormat::Monochrome,
        a,
        Vec::new(),
        Vec::new(),
        q,
        true,
        tuning,
        "alpha",
    )
}

/// `pixi` bits-per-channel list for the image's colour item.
pub(crate) fn pixi_bits(img: &StillImage) -> Vec<u8> {
    let channels = if img.chroma.has_chroma() { 3 } else { 1 };
    vec![img.bit_depth; channels]
}

/// Encode `img` into a complete single-item AVIF file.
///
/// The primary is one AV1 KEY-frame coded `av01` item; alpha (when
/// present) is a second, hidden monochrome item. See the module docs
/// for the property/brand mapping. Coded extents are bounded by
/// [`STILL_MAX_CODED_DIM`] per axis — larger canvases go through
/// [`encode_still_grid`].
pub fn encode_still(img: &StillImage, opts: &EncodeOptions) -> Result<Vec<u8>> {
    let (mux, max_profile) = still_muxer(img, opts)?;
    apply_profile_brand_mux(mux, max_profile).build()
}

/// `images[0]` as the primary item plus every further image as a coded
/// item of a `brst` image-burst group (HEIF §6.8.9) — the
/// [`crate::encode_all`] shape for delay-less frames. Every member
/// carries its own `colr` / ICC / `pixi` / `clap` and alpha
/// auxiliary; Exif / XMP ride on the primary only (item metadata
/// references are per item and the burst reader composes the
/// primary's). Each picture must fit the single-item bound.
pub fn encode_still_burst(images: &[StillImage], opts: &EncodeOptions) -> Result<Vec<u8>> {
    let Some(first) = images.first() else {
        return Err(Error::invalid("avif burst: no images"));
    };
    let (mut mux, mut max_profile) = still_muxer(first, opts)?;
    for (i, img) in images.iter().enumerate().skip(1) {
        img.validate()?;
        let (pw, ph) = (coded_extent(img.width), coded_extent(img.height));
        if pw > STILL_MAX_CODED_DIM || ph > STILL_MAX_CODED_DIM {
            return Err(Error::unsupported(format!(
                "avif burst: image {i} coded extents {pw}x{ph} exceed the single-item bound \
                 {STILL_MAX_CODED_DIM}",
            )));
        }
        let coded = encode_primary(img, pw, ph, opts.base_q_idx, CodedTuning::of(opts))?;
        max_profile = max_profile.max(coded.seq_profile);
        let mut member = crate::mux::BurstMember::new(pw, ph, coded.payload, coded.av1c);
        member.pixi = Some(pixi_bits(img));
        member.colr = img.colr.clone();
        member.icc = img.props.icc.clone();
        if (pw, ph) != (img.width, img.height) {
            member.clap = Some(top_left_clap(img.width, img.height, pw, ph));
        }
        if let Some(alpha) = &img.alpha {
            let coded_alpha =
                encode_alpha(img, alpha, pw, ph, opts.alpha_q_idx, CodedTuning::of(opts))?;
            max_profile = max_profile.max(coded_alpha.seq_profile);
            member.alpha = Some(crate::mux::BurstAlpha::new(
                coded_alpha.payload,
                coded_alpha.av1c,
                Some(vec![img.bit_depth]),
                opts.premultiplied_alpha,
            ));
        }
        mux = mux.with_burst_member(member);
    }
    apply_profile_brand_mux(mux, max_profile).build()
}

/// The muxer holding `img` as the primary item with all its
/// properties, auxiliaries and metadata, plus the highest AV1
/// sequence profile coded (for the profile brand).
fn still_muxer(img: &StillImage, opts: &EncodeOptions) -> Result<(AvifMuxer, u8)> {
    img.validate()?;
    let (pw, ph) = (coded_extent(img.width), coded_extent(img.height));
    if pw > STILL_MAX_CODED_DIM || ph > STILL_MAX_CODED_DIM {
        return Err(Error::unsupported(format!(
            "avif still: coded extents {pw}x{ph} exceed the single-item bound \
             {STILL_MAX_CODED_DIM}; use encode_still_grid",
        )));
    }
    let primary = encode_primary(img, pw, ph, opts.base_q_idx, CodedTuning::of(opts))?;
    let mut max_profile = primary.seq_profile;

    // ispe documents the coded extents (av1-avif §2.2.2); clap crops
    // back to the requested extents when padding was needed.
    let mut mux = AvifMuxer::new(pw, ph, primary.payload, primary.av1c).with_pixi(pixi_bits(img));
    if (pw, ph) != (img.width, img.height) {
        mux = mux.with_clap(top_left_clap(img.width, img.height, pw, ph));
    }
    if let Some(colr) = &img.colr {
        mux = mux.with_colr(colr.clone());
    }
    let props = &img.props;
    if let Some(exif) = &props.exif {
        mux = mux.with_exif(exif.clone());
    }
    if let Some(xmp) = &props.xmp {
        mux = mux.with_xmp(xmp.clone());
    }
    if let Some(icc) = &props.icc {
        mux = mux.with_icc(icc.clone());
    }
    if let Some(mdcv) = props.mdcv {
        mux = mux.with_mdcv(mdcv);
    }
    if let Some(clli) = props.clli {
        mux = mux.with_clli(clli);
    }
    if let Some(amve) = props.amve {
        mux = mux.with_amve(amve);
    }
    if let Some(pasp) = props.pasp {
        mux = mux.with_pasp(pasp);
    }
    if let Some(angle) = props.irot {
        mux = mux.with_irot(angle);
    }
    if let Some(axis) = props.imir {
        mux = mux.with_imir(axis);
    }
    if let Some(iden) = &props.identity_derivation {
        mux = mux.with_identity_derivation(iden.clone());
    }
    if let Some(gm) = &props.gain_map {
        gm.map.validate()?;
        let (gw, gh) = (coded_extent(gm.map.width), coded_extent(gm.map.height));
        if (gw, gh) != (gm.map.width, gm.map.height) {
            return Err(Error::unsupported(format!(
                "avif still: gain map extents {}x{} are not on the coded 8-grid (a padded gain \
                 map would need its own clap, which the tmap derivation does not carry)",
                gm.map.width, gm.map.height
            )));
        }
        let coded_map = encode_primary(&gm.map, gw, gh, gm.q, CodedTuning::of(opts))?;
        max_profile = max_profile.max(coded_map.seq_profile);
        let channels = if gm.map.chroma == StillChroma::Monochrome {
            1
        } else {
            3
        };
        let alt_depth = gm.alternate_bit_depth.unwrap_or(img.bit_depth);
        mux = mux.with_tone_map(ToneMapItem {
            payload: coded_map.payload,
            av1c: coded_map.av1c,
            width: gw,
            height: gh,
            pixi: Some(vec![gm.map.bit_depth; channels]),
            colr: gm.map.colr.clone().unwrap_or(Colr::Nclx {
                colour_primaries: 2,
                transfer_characteristics: 2,
                matrix_coefficients: 2,
                full_range: colr_is_full_range(&gm.map),
            }),
            metadata: gm.metadata.clone(),
            alternate_colr: gm.alternate_colr.clone(),
            alternate_clli: gm.alternate_clli,
            alternate_pixi: Some(vec![alt_depth; pixi_bits(img).len()]),
        });
    }
    if let Some(alpha) = &img.alpha {
        let coded_alpha =
            encode_alpha(img, alpha, pw, ph, opts.alpha_q_idx, CodedTuning::of(opts))?;
        max_profile = max_profile.max(coded_alpha.seq_profile);
        mux = mux
            .with_alpha(
                coded_alpha.payload,
                coded_alpha.av1c,
                opts.premultiplied_alpha,
            )
            .with_alpha_pixi(vec![img.bit_depth]);
    }
    if let Some(depth) = &img.depth_map {
        let coded_depth =
            encode_alpha(img, depth, pw, ph, opts.alpha_q_idx, CodedTuning::of(opts))?;
        max_profile = max_profile.max(coded_depth.seq_profile);
        mux = mux.with_depth(coded_depth.payload, coded_depth.av1c);
    }
    Ok((mux, max_profile))
}

pub(crate) fn apply_profile_brand_mux(mux: AvifMuxer, seq_profile: u8) -> AvifMuxer {
    match seq_profile {
        0 => mux, // Main → Baseline (MA1B) — the muxer default
        1 => mux.advanced_profile(),
        _ => mux.no_profile_brand(),
    }
}

/// Encode `img` as a **grid-derived** AVIF: the canvas splits into
/// `columns × rows` equal coded tiles (HEIF §6.6.2), each an
/// independently coded AV1 KEY frame. Tile extents are
/// `ceil(extent / count)` rounded up to the coded grid; the grid
/// descriptor's declared output extents trim the right/bottom
/// overflow, so no `clap` is needed (per av1-avif §4.2.1 / MIAF,
/// transformative properties may only sit on the grid item anyway).
///
/// Alpha rides as a hidden alpha `grid` of monochrome tiles (`auxl` →
/// the colour grid); pass-through properties land on the grid item.
pub fn encode_still_grid(
    img: &StillImage,
    opts: &EncodeOptions,
    columns: u16,
    rows: u16,
) -> Result<Vec<u8>> {
    img.validate()?;
    if img.props.identity_derivation.is_some() {
        return Err(Error::unsupported(
            "avif still: an identity derivation over a grid primary is not supported",
        ));
    }
    if img.depth_map.is_some() {
        return Err(Error::unsupported(
            "avif still: a depth map on the grid encode path is not supported",
        ));
    }
    if columns == 0 || rows == 0 {
        return Err(Error::invalid("avif still: grid needs at least 1x1 tiles"));
    }
    let tile_w = coded_extent(img.width.div_ceil(columns as u32));
    let tile_h = coded_extent(img.height.div_ceil(rows as u32));
    if tile_w > STILL_MAX_CODED_DIM || tile_h > STILL_MAX_CODED_DIM {
        return Err(Error::unsupported(format!(
            "avif still: {columns}x{rows} tiling of {}x{} needs {tile_w}x{tile_h} tiles, \
             beyond the per-tile bound {STILL_MAX_CODED_DIM}",
            img.width, img.height
        )));
    }
    if tile_w < GRID_MIN_TILE_DIM || tile_h < GRID_MIN_TILE_DIM {
        return Err(Error::invalid(format!(
            "avif still: {columns}x{rows} tiling of {}x{} yields {tile_w}x{tile_h} tiles, \
             below the {GRID_MIN_TILE_DIM}-pixel grid-tile floor external readers enforce",
            img.width, img.height
        )));
    }
    // Every tile must contribute visible pixels (HEIF §6.6.2.3.1: the
    // tiled extent covers the canvas, and trimming happens only on the
    // last row/column).
    if (columns as u32 - 1) * tile_w >= img.width || (rows as u32 - 1) * tile_h >= img.height {
        return Err(Error::invalid(format!(
            "avif still: {columns}x{rows} tiling of {}x{} leaves fully-trimmed tiles \
             (tile extents {tile_w}x{tile_h})",
            img.width, img.height
        )));
    }

    let (w, h) = (img.width as usize, img.height as usize);
    let (sx, sy) = img.chroma.subsampling();
    let (cw, ch) = img.chroma_dims();
    let mut muxer =
        AvifGridMuxer::new(rows, columns, img.width, img.height).with_pixi(pixi_bits(img));
    if let Some(colr) = &img.colr {
        muxer = muxer.with_colr(colr.clone());
    }
    let props = &img.props;
    if let Some(exif) = &props.exif {
        muxer = muxer.with_exif(exif.clone());
    }
    if let Some(xmp) = &props.xmp {
        muxer = muxer.with_xmp(xmp.clone());
    }
    if let Some(icc) = &props.icc {
        muxer = muxer.with_icc(icc.clone());
    }
    if let Some(mdcv) = props.mdcv {
        muxer = muxer.with_mdcv(mdcv);
    }
    if let Some(clli) = props.clli {
        muxer = muxer.with_clli(clli);
    }
    if let Some(amve) = props.amve {
        muxer = muxer.with_amve(amve);
    }
    if let Some(pasp) = props.pasp {
        muxer = muxer.with_pasp(pasp);
    }
    if let Some(angle) = props.irot {
        muxer = muxer.with_irot(angle);
    }
    if let Some(axis) = props.imir {
        muxer = muxer.with_imir(axis);
    }
    let mut max_profile = 0u8;
    for r in 0..rows as usize {
        for c in 0..columns as usize {
            let x0 = c * tile_w as usize;
            let y0 = r * tile_h as usize;
            let ty = extract_rect(&img.y, w, h, x0, y0, tile_w as usize, tile_h as usize);
            let (tu, tv) = if img.chroma.has_chroma() {
                let (tcx, tcy) = (x0 >> sx, y0 >> sy);
                let (tcw, tch) = ((tile_w >> sx) as usize, (tile_h >> sy) as usize);
                (
                    extract_rect(&img.u, cw as usize, ch as usize, tcx, tcy, tcw, tch),
                    extract_rect(&img.v, cw as usize, ch as usize, tcx, tcy, tcw, tch),
                )
            } else {
                (Vec::new(), Vec::new())
            };
            let coded = encode_coded_item(
                tile_w,
                tile_h,
                img.bit_depth,
                img.chroma.to_av1(),
                ty,
                tu,
                tv,
                opts.base_q_idx,
                colr_is_full_range(img),
                CodedTuning::of(opts),
                "grid tile",
            )?;
            max_profile = max_profile.max(coded.seq_profile);
            muxer = muxer.tile(GridTile {
                width: tile_w,
                height: tile_h,
                payload: coded.payload,
                av1c: coded.av1c,
            });
            if let Some(alpha) = &img.alpha {
                // Alpha tiles: same geometry, monochrome, full range
                // (av1-avif §4.1) — stitched by a hidden alpha `grid`.
                let ta = extract_rect(alpha, w, h, x0, y0, tile_w as usize, tile_h as usize);
                let coded_alpha = encode_coded_item(
                    tile_w,
                    tile_h,
                    img.bit_depth,
                    ChromaFormat::Monochrome,
                    ta,
                    Vec::new(),
                    Vec::new(),
                    opts.alpha_q_idx,
                    true,
                    CodedTuning::of(opts),
                    "grid alpha tile",
                )?;
                max_profile = max_profile.max(coded_alpha.seq_profile);
                muxer = muxer.alpha_tile(GridTile {
                    width: tile_w,
                    height: tile_h,
                    payload: coded_alpha.payload,
                    av1c: coded_alpha.av1c,
                });
            }
        }
    }
    if img.alpha.is_some() {
        muxer = muxer
            .with_alpha_pixi(vec![img.bit_depth])
            .premultiplied_alpha(opts.premultiplied_alpha);
    }
    muxer = match max_profile {
        0 => muxer,
        1 => muxer.advanced_profile(),
        _ => muxer.no_profile_brand(),
    };
    muxer.build()
}

/// The canvas of an overlay-derived encode ([`encode_still_overlay`]).
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct OverlayCanvas {
    /// `output_width` of the `iovl` descriptor (HEIF §6.6.2.2.3).
    pub width: u32,
    /// `output_height`.
    pub height: u32,
    /// `canvas_fill_value` — sRGB RGBA, 16 bits per channel, `A`
    /// linear 0 (transparent) … 65535 (opaque). Shows wherever no
    /// layer covers the canvas.
    pub fill_rgba: [u16; 4],
    /// `colr` for the overlay item; defaults to the first layer's.
    pub colr: Option<Colr>,
    /// `irot` on the overlay item (applies to the composed canvas).
    pub irot: Option<u8>,
    /// `imir` on the overlay item.
    pub imir: Option<u8>,
}

impl OverlayCanvas {
    /// Setter: replace `width`.
    pub fn with_width(mut self, width: u32) -> Self {
        self.width = width;
        self
    }
    /// Setter: replace `height`.
    pub fn with_height(mut self, height: u32) -> Self {
        self.height = height;
        self
    }
    /// Setter: replace `fill_rgba`.
    pub fn with_fill_rgba(mut self, fill_rgba: [u16; 4]) -> Self {
        self.fill_rgba = fill_rgba;
        self
    }
    /// Setter: replace `colr`.
    pub fn with_colr(mut self, colr: Option<Colr>) -> Self {
        self.colr = colr;
        self
    }
    /// Setter: replace `irot`.
    pub fn with_irot(mut self, irot: Option<u8>) -> Self {
        self.irot = irot;
        self
    }
    /// Setter: replace `imir`.
    pub fn with_imir(mut self, imir: Option<u8>) -> Self {
        self.imir = imir;
        self
    }
}

impl OverlayCanvas {
    /// An opaque-black canvas of the given extents.
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            fill_rgba: [0, 0, 0, 65535],
            colr: None,
            irot: None,
            imir: None,
        }
    }
}

/// One layer of an overlay-derived encode: a still image and the
/// canvas position of its top-left corner (signed — partially or
/// wholly off-canvas placements are legal and clipped, §6.6.2.2.3).
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub struct OverlayLayerImage<'a> {
    /// The layer's pixels (alpha optional, encoded as its auxiliary).
    pub image: &'a StillImage,
    /// `horizontal_offset`.
    pub x: i32,
    /// `vertical_offset`.
    pub y: i32,
}

impl<'a> OverlayLayerImage<'a> {
    /// Every field as a positional argument, in declaration order
    /// (the record is `#[non_exhaustive]`: build it here, or from
    /// `Default` where one exists, then read / assign the public
    /// fields).
    #[allow(clippy::too_many_arguments)]
    pub fn new(image: &'a StillImage, x: i32, y: i32) -> Self {
        Self { image, x, y }
    }
    /// Setter: replace `image`.
    pub fn with_image(mut self, image: &'a StillImage) -> Self {
        self.image = image;
        self
    }
    /// Setter: replace `x`.
    pub fn with_x(mut self, x: i32) -> Self {
        self.x = x;
        self
    }
    /// Setter: replace `y`.
    pub fn with_y(mut self, y: i32) -> Self {
        self.y = y;
        self
    }
}

/// Encode `layers` (bottom-most first) as an **overlay-derived** AVIF:
/// the primary is an `iovl` item (HEIF §6.6.2.2) whose hidden `av01`
/// inputs are the layers, each coded exactly like an [`encode_still`]
/// primary (edge-replicated pad to the coded 8-grid + top-left `clap`,
/// same-depth monochrome alpha auxiliary with `auxl` / `prem`). Every
/// layer must share one bit depth and chroma layout so a reader can
/// composite them without colour conversion.
pub fn encode_still_overlay(
    canvas: &OverlayCanvas,
    layers: &[OverlayLayerImage<'_>],
    opts: &EncodeOptions,
) -> Result<Vec<u8>> {
    if layers.is_empty() {
        return Err(Error::invalid(
            "avif still: overlay needs at least one layer",
        ));
    }
    if canvas.width == 0 || canvas.height == 0 {
        return Err(Error::invalid("avif still: overlay canvas dimensions zero"));
    }
    let first = layers[0].image;
    let mut muxer = AvifOverlayMuxer::new(canvas.width, canvas.height)
        .with_fill(canvas.fill_rgba)
        .with_pixi(pixi_bits(first));
    if let Some(colr) = canvas.colr.as_ref().or(first.colr.as_ref()) {
        muxer = muxer.with_colr(colr.clone());
    }
    if let Some(angle) = canvas.irot {
        muxer = muxer.with_irot(angle);
    }
    if let Some(axis) = canvas.imir {
        muxer = muxer.with_imir(axis);
    }
    let mut max_profile = 0u8;
    for (i, layer) in layers.iter().enumerate() {
        let img = layer.image;
        img.validate()?;
        if (img.bit_depth, img.chroma) != (first.bit_depth, first.chroma) {
            return Err(Error::unsupported(format!(
                "avif still: overlay layer {i} is {}-bit {:?} but layer 0 is {}-bit {:?} — \
                 layers must share one coded layout",
                img.bit_depth, img.chroma, first.bit_depth, first.chroma
            )));
        }
        let (pw, ph) = (coded_extent(img.width), coded_extent(img.height));
        if pw > STILL_MAX_CODED_DIM || ph > STILL_MAX_CODED_DIM {
            return Err(Error::unsupported(format!(
                "avif still: overlay layer {i} coded extents {pw}x{ph} exceed {STILL_MAX_CODED_DIM}"
            )));
        }
        let coded = encode_primary(img, pw, ph, opts.base_q_idx, CodedTuning::of(opts))?;
        max_profile = max_profile.max(coded.seq_profile);
        let clap = ((pw, ph) != (img.width, img.height))
            .then(|| top_left_clap(img.width, img.height, pw, ph));
        let alpha = match &img.alpha {
            Some(a) => {
                let coded_alpha =
                    encode_alpha(img, a, pw, ph, opts.alpha_q_idx, CodedTuning::of(opts))?;
                max_profile = max_profile.max(coded_alpha.seq_profile);
                Some((coded_alpha.payload, coded_alpha.av1c))
            }
            None => None,
        };
        muxer = muxer.layer(OverlayLayer {
            width: pw,
            height: ph,
            payload: coded.payload,
            av1c: coded.av1c,
            pixi: Some(pixi_bits(img)),
            colr: img.colr.clone(),
            clap,
            alpha_pixi: alpha.as_ref().map(|_| vec![img.bit_depth]),
            alpha,
            premultiplied: opts.premultiplied_alpha,
            offset_x: layer.x,
            offset_y: layer.y,
        });
    }
    muxer = match max_profile {
        0 => muxer,
        1 => muxer.advanced_profile(),
        _ => muxer.no_profile_brand(),
    };
    muxer.build()
}

/// Per-layer byte sizes of a layered AV1 Image Item Data payload, in
/// increasing `spatial_id` order — the `a1lx` `layer_size` values
/// (av1-avif §2.3.2.3.4). OBUs without an extension header (temporal
/// delimiter, sequence header) belong to `spatial_id` 0.
#[doc(hidden)]
pub fn layer_byte_sizes(payload: &[u8]) -> Result<Vec<u32>> {
    let mut sizes = [0u32; 4];
    let mut max_layer = 0usize;
    let mut off = 0usize;
    while off < payload.len() {
        let (obu, consumed) = parse_obu(&payload[off..])
            .map_err(|e| Error::invalid(format!("avif still: layered payload OBU walk: {e}")))?;
        let layer = usize::from(obu.spatial_id.min(3));
        max_layer = max_layer.max(layer);
        sizes[layer] += consumed as u32;
        off += consumed;
    }
    Ok(sizes[..=max_layer].to_vec())
}

/// Encode a **layered** (progressive) AVIF: `layers` are renditions of
/// one image at increasing resolution — every layer at most the top
/// layer's extents, all sharing one bit depth and chroma layout, 2 to
/// 4 of them — coded as independently decodable AV1 spatial layers
/// inside a single temporal unit (one Sequence Header, av1-avif §2.1;
/// each layer's frame OBUs carry `spatial_id`, §2.3.1). The item
/// carries `a1lx` (per-layer byte sizes, §2.3.2.3) and `lsel`
/// (HEIF §6.5.11): `render_layer = None` writes `0xFFFF`, allowing a
/// reader to render every layer progressively and finish on the top
/// one; `Some(s)` pins layer `s`. `ispe` / `clap` describe the
/// selected layer (§2.2.2: the last frame decoded at operating point 0
/// when unpinned).
///
/// Alpha (of the top layer only) rides as the usual single-layer
/// auxiliary. Pass-through properties come from the top layer.
pub fn encode_still_layered(
    layers: &[&StillImage],
    render_layer: Option<u8>,
    opts: &EncodeOptions,
) -> Result<Vec<u8>> {
    if !(2..=4).contains(&layers.len()) {
        return Err(Error::invalid(format!(
            "avif still: layered encode needs 2..=4 layers, got {}",
            layers.len()
        )));
    }
    let top = layers[layers.len() - 1];
    top.validate()?;
    let mut frames: Vec<Vec<YuvFrame>> = Vec::with_capacity(layers.len());
    let mut coded_dims = Vec::with_capacity(layers.len());
    for (i, layer) in layers.iter().enumerate() {
        layer.validate()?;
        if (layer.bit_depth, layer.chroma) != (top.bit_depth, top.chroma) {
            return Err(Error::unsupported(format!(
                "avif still: layer {i} is {}-bit {:?} but the top layer is {}-bit {:?}",
                layer.bit_depth, layer.chroma, top.bit_depth, top.chroma
            )));
        }
        if layer.width > top.width || layer.height > top.height {
            return Err(Error::invalid(format!(
                "avif still: layer {i} ({}x{}) exceeds the top layer ({}x{})",
                layer.width, layer.height, top.width, top.height
            )));
        }
        let (pw, ph) = (coded_extent(layer.width), coded_extent(layer.height));
        if pw > STILL_MAX_CODED_DIM || ph > STILL_MAX_CODED_DIM {
            return Err(Error::unsupported(format!(
                "avif still: layer {i} coded extents {pw}x{ph} exceed {STILL_MAX_CODED_DIM}"
            )));
        }
        let (w, h) = (layer.width as usize, layer.height as usize);
        let y = pad_plane(&layer.y, w, h, pw as usize, ph as usize);
        let (u, v) = if layer.chroma.has_chroma() {
            let (sx, sy) = layer.chroma.subsampling();
            let (cw, ch) = layer.chroma_dims();
            let (pcw, pch) = ((pw >> sx) as usize, (ph >> sy) as usize);
            (
                pad_plane(&layer.u, cw as usize, ch as usize, pcw, pch),
                pad_plane(&layer.v, cw as usize, ch as usize, pcw, pch),
            )
        } else {
            (Vec::new(), Vec::new())
        };
        frames.push(vec![YuvFrame {
            width: pw,
            height: ph,
            bit_depth: layer.bit_depth,
            format: layer.chroma.to_av1(),
            y,
            u,
            v,
        }]);
        coded_dims.push((pw, ph));
    }
    let selected = match render_layer {
        Some(s) if usize::from(s) < layers.len() => usize::from(s),
        Some(s) => {
            return Err(Error::invalid(format!(
                "avif still: render_layer {s} out of range for {} layers",
                layers.len()
            )))
        }
        None => layers.len() - 1,
    };
    let coded = encode_spatial_layered_gop_yuv_with_q(&frames, opts.base_q_idx)
        .map_err(|e| av1_err("layered", e))?;
    let unit =
        coded.temporal_units.into_iter().next().ok_or_else(|| {
            Error::invalid("avif still: layered encode produced no temporal unit")
        })?;
    let payload = if colr_is_full_range(top) {
        full_range_temporal_unit(&unit, &coded.seq)?
    } else {
        unit
    };
    let sizes = layer_byte_sizes(&payload)?;
    if sizes.len() != layers.len() {
        return Err(Error::invalid(format!(
            "avif still: layered payload carries {} spatial layers, expected {}",
            sizes.len(),
            layers.len()
        )));
    }
    let mut a1lx = [0u32; 3];
    for (slot, size) in a1lx.iter_mut().zip(&sizes[..sizes.len() - 1]) {
        *slot = *size;
    }
    let av1c = av1c_from_seq(&coded.seq);
    let mut max_profile = coded.seq.seq_profile;

    let (pw, ph) = coded_dims[selected];
    let sel_img = layers[selected];
    let mut mux = AvifMuxer::new(pw, ph, payload, av1c)
        .with_pixi(pixi_bits(top))
        .with_layered_index(a1lx)
        .with_layer_selector(render_layer.map_or(0xFFFF, u16::from));
    if (pw, ph) != (sel_img.width, sel_img.height) {
        mux = mux.with_clap(top_left_clap(sel_img.width, sel_img.height, pw, ph));
    }
    if let Some(colr) = &top.colr {
        mux = mux.with_colr(colr.clone());
    }
    let props = &top.props;
    if let Some(exif) = &props.exif {
        mux = mux.with_exif(exif.clone());
    }
    if let Some(xmp) = &props.xmp {
        mux = mux.with_xmp(xmp.clone());
    }
    if let Some(icc) = &props.icc {
        mux = mux.with_icc(icc.clone());
    }
    if let Some(mdcv) = props.mdcv {
        mux = mux.with_mdcv(mdcv);
    }
    if let Some(clli) = props.clli {
        mux = mux.with_clli(clli);
    }
    if let Some(amve) = props.amve {
        mux = mux.with_amve(amve);
    }
    if let Some(pasp) = props.pasp {
        mux = mux.with_pasp(pasp);
    }
    if let Some(angle) = props.irot {
        mux = mux.with_irot(angle);
    }
    if let Some(axis) = props.imir {
        mux = mux.with_imir(axis);
    }
    if selected == layers.len() - 1 {
        if let Some(alpha) = &top.alpha {
            let coded_alpha =
                encode_alpha(top, alpha, pw, ph, opts.alpha_q_idx, CodedTuning::of(opts))?;
            max_profile = max_profile.max(coded_alpha.seq_profile);
            mux = mux
                .with_alpha(
                    coded_alpha.payload,
                    coded_alpha.av1c,
                    opts.premultiplied_alpha,
                )
                .with_alpha_pixi(vec![top.bit_depth]);
        }
    }
    mux = apply_profile_brand_mux(mux, max_profile);
    mux.build()
}