malmal 0.5.1

Upload scanner for images, SVG, PDF and PostScript files
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
//! An AVIF image, as a PNG of the picture it shows.
//!
//! The primary item is decoded with `filmcraft-av1`, an AV1 decoder in safe
//! Rust that gives the samples libdav1d gives; a grid of tiles is put
//! together first. Its samples are turned into RGB by the matrix and range
//! the file gives, at 8 bits a channel or, if it holds more, at 16, with
//! the auxiliary alpha image if there is one. The picture is then cut,
//! turned and mirrored as its properties say, and its colours brought into
//! sRGB from its ICC profile or from the primaries and transfer it names;
//! or, when they are to be kept, left as they are under the profile written
//! anew, or with the primaries and transfer named in the PNG (`cICP`).
//! Pictures in a range only a display for high dynamic range shows (PQ,
//! HLG) cannot be brought into sRGB as they are: they are left as they
//! are, at 16 bits a channel, with what they are named in the PNG, or tone
//! mapped into sRGB when that is asked.

use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb, Rgba};
use moxcms::{
    CicpColorPrimaries, CicpProfile, ColorProfile, MatrixCoefficients, TransferCharacteristics,
};

use super::{Deadline, Error, ToSrgb, colour};
use crate::detect::FileType;
use crate::limits::Limits;

fn broken(what: &str) -> Error {
    Error::Decode(format!("AVIF {what}"))
}

fn refused(reason: &'static str) -> Error {
    Error::Unsupported {
        file_type: FileType::Avif,
        reason,
    }
}

/// Boxes nested deeper than this, or more of them, are refused.
const MOST_BOXES: usize = 1 << 16;
/// Tiles of a grid, and items, at most.
const MOST_ITEMS: usize = 1 << 12;

/// The boxes laid end to end in `body`.
/// Boxes by kind, each with its body.
type Boxes<'a> = Vec<([u8; 4], &'a [u8])>;

fn boxes(body: &[u8]) -> Result<Boxes<'_>, Error> {
    let mut found = Vec::new();
    let mut rest = body;
    while !rest.is_empty() {
        let short = || broken("box is cut short");
        let size = u32::from_be_bytes(rest.get(..4).ok_or_else(short)?.try_into().unwrap());
        let kind: [u8; 4] = rest.get(4..8).ok_or_else(short)?.try_into().unwrap();
        let (start, size) = match size {
            0 => (8, rest.len()),
            1 => {
                let large = rest.get(8..16).ok_or_else(short)?;
                (
                    16,
                    usize::try_from(u64::from_be_bytes(large.try_into().unwrap()))
                        .map_err(|_| short())?,
                )
            }
            size => (8, size as usize),
        };
        if size < start || size > rest.len() || found.len() >= MOST_BOXES {
            return Err(broken("box does not fit"));
        }
        found.push((kind, &rest[start..size]));
        rest = &rest[size..];
    }
    Ok(found)
}

/// The boxes at the top of a file, up to the first that is not one:
/// whatever follows them is not part of the image.
fn top_level(data: &[u8]) -> Boxes<'_> {
    let mut found = Vec::new();
    let mut rest = data;
    while rest.len() >= 8 {
        let size = u32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
        let size = if size == 0 { rest.len() } else { size };
        if size < 8 || size > rest.len() || found.len() >= MOST_BOXES {
            break;
        }
        found.push((rest[4..8].try_into().unwrap(), &rest[8..size]));
        rest = &rest[size..];
    }
    found
}

/// Big-endian fields read one after another.
struct Fields<'a> {
    data: &'a [u8],
    at: usize,
}

impl<'a> Fields<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, at: 0 }
    }

    /// An unsigned field of `width` bytes, 0 to 8.
    fn take(&mut self, width: usize) -> Result<u64, Error> {
        let bytes = self
            .data
            .get(self.at..self.at + width)
            .filter(|_| width <= 8)
            .ok_or_else(|| broken("box is cut short"))?;
        self.at += width;
        Ok(bytes.iter().fold(0, |value, &b| value << 8 | u64::from(b)))
    }

    fn u8(&mut self) -> Result<u8, Error> {
        Ok(self.take(1)? as u8)
    }

    fn u16(&mut self) -> Result<u16, Error> {
        Ok(self.take(2)? as u16)
    }

    fn u32(&mut self) -> Result<u32, Error> {
        Ok(self.take(4)? as u32)
    }

    fn four(&mut self) -> Result<[u8; 4], Error> {
        Ok(self.u32()?.to_be_bytes())
    }

    fn rest(&self) -> &'a [u8] {
        self.data.get(self.at..).unwrap_or_default()
    }
}

/// Where the bytes of an item are: in the file, or in the `idat` box.
struct Extent {
    in_idat: bool,
    offset: u64,
    length: u64,
}

struct Item {
    id: u32,
    kind: [u8; 4],
    extents: Vec<Extent>,
    /// Indexes into the properties, 1 for the first, and whether each is
    /// essential.
    properties: Vec<(bool, usize)>,
}

/// The items of the file and what is known of them.
struct Heif<'a> {
    data: &'a [u8],
    primary: u32,
    items: Vec<Item>,
    properties: Boxes<'a>,
    /// References: kind, from, to.
    references: Vec<([u8; 4], u32, Vec<u32>)>,
    idat: &'a [u8],
}

impl<'a> Heif<'a> {
    fn parse(data: &'a [u8]) -> Result<Self, Error> {
        let top = top_level(data);
        let meta = top
            .iter()
            .find(|(kind, _)| kind == b"meta")
            .map(|(_, body)| *body)
            .ok_or_else(|| refused("it holds no still image"))?;
        let mut heif = Self {
            data,
            primary: 0,
            items: Vec::new(),
            properties: Vec::new(),
            references: Vec::new(),
            idat: &[],
        };
        let mut primary = None;
        let mut associations = Vec::new();
        for (kind, body) in boxes(meta.get(4..).unwrap_or_default())? {
            let mut fields = Fields::new(body);
            match &kind {
                b"pitm" => {
                    let version = fields.u8()?;
                    fields.take(3)?;
                    primary = Some(if version == 0 {
                        u32::from(fields.u16()?)
                    } else {
                        fields.u32()?
                    });
                }
                b"iinf" => {
                    let version = fields.u8()?;
                    fields.take(3)?;
                    fields.take(if version == 0 { 2 } else { 4 })?;
                    for (entry, body) in boxes(fields.rest())? {
                        if &entry != b"infe" {
                            continue;
                        }
                        let mut fields = Fields::new(body);
                        let version = fields.u8()?;
                        fields.take(3)?;
                        if version < 2 {
                            continue;
                        }
                        let id = if version == 2 {
                            u32::from(fields.u16()?)
                        } else {
                            fields.u32()?
                        };
                        fields.u16()?;
                        let kind = fields.four()?;
                        // Placed already, if `iloc` came first.
                        if let Some(item) = heif.items.iter_mut().find(|i| i.id == id) {
                            item.kind = kind;
                            continue;
                        }
                        if heif.items.len() >= MOST_ITEMS {
                            return Err(refused("it has too many items"));
                        }
                        heif.items.push(Item {
                            id,
                            kind,
                            extents: Vec::new(),
                            properties: Vec::new(),
                        });
                    }
                }
                b"iloc" => {
                    for (id, extents) in locations(body)? {
                        if let Some(item) = heif.items.iter_mut().find(|i| i.id == id) {
                            item.extents = extents;
                        } else {
                            heif.items.push(Item {
                                id,
                                kind: *b"    ",
                                extents,
                                properties: Vec::new(),
                            });
                        }
                    }
                }
                b"iref" => {
                    let version = fields.u8()?;
                    fields.take(3)?;
                    let width = if version == 0 { 2 } else { 4 };
                    for (kind, body) in boxes(fields.rest())? {
                        let mut fields = Fields::new(body);
                        let from = fields.take(width)? as u32;
                        let count = fields.u16()?;
                        let to = (0..count)
                            .map(|_| fields.take(width).map(|v| v as u32))
                            .collect::<Result<Vec<_>, _>>()?;
                        heif.references.push((kind, from, to));
                    }
                }
                b"iprp" => {
                    for (kind, body) in boxes(body)? {
                        match &kind {
                            b"ipco" => heif.properties = boxes(body)?,
                            b"ipma" => associations.push(body),
                            _ => {}
                        }
                    }
                }
                b"idat" => heif.idat = body,
                _ => {}
            }
        }
        for body in associations {
            let mut fields = Fields::new(body);
            let version = fields.u8()?;
            let flags = fields.take(3)?;
            for _ in 0..fields.u32()? {
                let id = if version == 0 {
                    u32::from(fields.u16()?)
                } else {
                    fields.u32()?
                };
                let count = fields.u8()?;
                let mut properties = Vec::with_capacity(count.into());
                for _ in 0..count {
                    let (essential, index) = if flags & 1 == 1 {
                        let v = fields.u16()?;
                        (v & 0x8000 != 0, usize::from(v & 0x7FFF))
                    } else {
                        let v = fields.u8()?;
                        (v & 0x80 != 0, usize::from(v & 0x7F))
                    };
                    properties.push((essential, index));
                }
                if let Some(item) = heif.items.iter_mut().find(|i| i.id == id) {
                    item.properties.extend(properties);
                }
            }
        }
        heif.primary = primary.ok_or_else(|| broken("has no primary item"))?;
        Ok(heif)
    }

    fn item(&self, id: u32) -> Result<&Item, Error> {
        self.items
            .iter()
            .find(|i| i.id == id)
            .ok_or_else(|| broken("names an item it does not have"))
    }

    /// The properties of an item, in the order they are given. One that is
    /// essential and not understood here refuses the item.
    fn properties(&self, item: &Item) -> Result<Boxes<'a>, Error> {
        const KNOWN: [&[u8; 4]; 9] = [
            b"av1C", b"ispe", b"pixi", b"colr", b"irot", b"imir", b"clap", b"auxC", b"a1lx",
        ];
        let mut found = Vec::new();
        for &(essential, index) in &item.properties {
            if index == 0 {
                continue;
            }
            let property = *self
                .properties
                .get(index - 1)
                .ok_or_else(|| broken("names a property it does not have"))?;
            if essential && !KNOWN.contains(&&property.0) {
                return Err(refused("one of its properties is not one this reads"));
            }
            found.push(property);
        }
        Ok(found)
    }

    fn property(&self, item: &Item, kind: &[u8; 4]) -> Result<Option<&'a [u8]>, Error> {
        Ok(self
            .properties(item)?
            .into_iter()
            .find(|(k, _)| k == kind)
            .map(|(_, body)| body))
    }

    /// The items `from` points to by references of `kind`.
    fn references(&self, kind: &[u8; 4], from: u32) -> Vec<u32> {
        self.references
            .iter()
            .filter(|(k, f, _)| k == kind && *f == from)
            .flat_map(|(_, _, to)| to.iter().copied())
            .collect()
    }

    /// The items that point to `to` by references of `kind`.
    fn referring(&self, kind: &[u8; 4], to: u32) -> Vec<u32> {
        self.references
            .iter()
            .filter(|(k, _, t)| k == kind && t.contains(&to))
            .map(|(_, from, _)| *from)
            .collect()
    }

    fn bytes(&self, item: &Item) -> Result<Vec<u8>, Error> {
        let mut out = Vec::new();
        for extent in &item.extents {
            let source = if extent.in_idat { self.idat } else { self.data };
            let start =
                usize::try_from(extent.offset).map_err(|_| broken("item is out of bounds"))?;
            // A length of 0 is the rest of the file.
            let end = match extent.length {
                0 => source.len(),
                length => usize::try_from(length)
                    .ok()
                    .and_then(|l| start.checked_add(l))
                    .ok_or_else(|| broken("item is out of bounds"))?,
            };
            out.extend_from_slice(
                source
                    .get(start..end)
                    .ok_or_else(|| broken("item is out of bounds"))?,
            );
        }
        Ok(out)
    }
}

/// The extents of each item that `iloc` places.
fn locations(body: &[u8]) -> Result<Vec<(u32, Vec<Extent>)>, Error> {
    let mut fields = Fields::new(body);
    let version = fields.u8()?;
    fields.take(3)?;
    if version > 2 {
        return Err(broken("item locations are of a version this does not read"));
    }
    let sizes = fields.u8()?;
    let more = fields.u8()?;
    let (offset_size, length_size) = (usize::from(sizes >> 4), usize::from(sizes & 15));
    let base_size = usize::from(more >> 4);
    let index_size = if version >= 1 {
        usize::from(more & 15)
    } else {
        0
    };
    let count = if version < 2 {
        fields.take(2)?
    } else {
        fields.take(4)?
    };
    let mut found = Vec::new();
    for _ in 0..count {
        if found.len() >= MOST_ITEMS {
            return Err(refused("it has too many items"));
        }
        let id = if version < 2 {
            fields.take(2)?
        } else {
            fields.take(4)?
        } as u32;
        let method = if version >= 1 { fields.u16()? & 15 } else { 0 };
        fields.u16()?;
        let base = fields.take(base_size)?;
        let extents = fields.u16()?;
        let mut list = Vec::new();
        for _ in 0..extents {
            fields.take(index_size)?;
            let offset = fields.take(offset_size)?;
            let length = fields.take(length_size)?;
            list.push(Extent {
                in_idat: method == 1,
                offset: base.saturating_add(offset),
                length,
            });
        }
        if method > 1 {
            return Err(refused("its items are stored in a way this does not read"));
        }
        found.push((id, list));
    }
    Ok(found)
}

/// Decoded samples of an item: one plane, or three.
struct Planes {
    width: u32,
    height: u32,
    depth: u8,
    subsampling: (u8, u8),
    mono: bool,
    planes: [Vec<u16>; 3],
    /// The colour description the AV1 stream itself gives.
    matrix: u8,
    full_range: bool,
}

impl Planes {
    fn plane_size(&self, plane: usize) -> (usize, usize) {
        if plane == 0 {
            return (self.width as usize, self.height as usize);
        }
        let (x, y) = self.subsampling;
        (
            ((self.width + u32::from(x)) >> x) as usize,
            ((self.height + u32::from(y)) >> y) as usize,
        )
    }
}

/// The OBUs of a stream, with their types.
fn obus(data: &[u8]) -> Result<Vec<(u8, &[u8])>, Error> {
    let mut found = Vec::new();
    let mut at = 0;
    while at < data.len() {
        let header = data[at];
        let kind = (header >> 3) & 15;
        let extension = (header >> 2) & 1 == 1;
        let has_size = (header >> 1) & 1 == 1;
        at += 1 + usize::from(extension);
        let size = if has_size {
            let mut size = 0u64;
            let mut shift = 0;
            loop {
                let byte = *data
                    .get(at)
                    .ok_or_else(|| broken("AV1 stream is cut short"))?;
                at += 1;
                size |= u64::from(byte & 0x7F) << shift;
                if byte & 0x80 == 0 || shift >= 56 {
                    break;
                }
                shift += 7;
            }
            usize::try_from(size).map_err(|_| broken("AV1 stream is cut short"))?
        } else {
            data.len().saturating_sub(at)
        };
        let payload = data
            .get(at..at.saturating_add(size))
            .ok_or_else(|| broken("AV1 stream is cut short"))?;
        found.push((kind, payload));
        at += size;
    }
    Ok(found)
}

/// The pictures an AV1 `stream` of frames of up to `pixels` shows. A large
/// one is decoded on up to four threads, a tile to each. With a deadline
/// the decoder runs on a thread of its own, and is not waited for past it:
/// the answer is then [`Error::TimedOut`], though the thread runs on until
/// the picture is done, which the limits on its size keep short.
fn av1(
    stream: Vec<u8>,
    pixels: u64,
    deadline: Deadline,
) -> Result<Vec<filmcraft_av1::Picture>, Error> {
    let threads = if pixels >= 1 << 20 {
        std::thread::available_parallelism().map_or(1, |n| n.get().min(4))
    } else {
        1
    };
    // Set when the answer is no longer waited for, so that the decoder
    // stops at its next row of superblocks instead of running on.
    let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let flag = cancel.clone();
    let run = move || -> Result<Vec<filmcraft_av1::Picture>, Error> {
        let failed = |e: filmcraft_av1::Error| match e {
            filmcraft_av1::Error::Cancelled => Error::TimedOut,
            e => broken(&format!("AV1 image: {e}")),
        };
        let mut decoder = filmcraft_av1::Decoder::with_threads(threads);
        decoder.set_cancel(flag);
        let mut pictures = decoder.decode(&stream).map_err(failed)?;
        pictures.extend(decoder.flush_result().map_err(failed)?);
        Ok(pictures)
    };
    let Some(at) = deadline.0 else {
        return run();
    };
    let (sender, receiver) = std::sync::mpsc::channel();
    std::thread::Builder::new()
        .name("malmal-av1".into())
        .spawn(move || {
            let _ = sender.send(run());
        })
        .map_err(|e| broken(&format!("no thread for the AV1 decoder: {e}")))?;
    match receiver.recv_timeout(at.saturating_duration_since(std::time::Instant::now())) {
        Ok(answer) => answer,
        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
            cancel.store(true, std::sync::atomic::Ordering::Relaxed);
            Err(Error::TimedOut)
        }
        // It stopped without an answer: it panicked.
        Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(broken("AV1 decoder failed")),
    }
}

/// The item decoded: an AV1 image, or a grid of them.
fn decode(
    heif: &Heif<'_>,
    id: u32,
    limits: &Limits,
    deadline: Deadline,
    nested: bool,
) -> Result<Planes, Error> {
    deadline.check()?;
    let item = heif.item(id)?;
    match &item.kind {
        b"av01" => {
            // The sequence header the configuration holds, then the image.
            let mut stream = Vec::new();
            if let Some(config) = heif.property(item, b"av1C")? {
                stream.extend_from_slice(config.get(4..).unwrap_or_default());
            }
            stream.extend_from_slice(&heif.bytes(item)?);
            let sequence = obus(&stream)?
                .into_iter()
                .find(|(kind, _)| *kind == 1)
                .ok_or_else(|| broken("AV1 image has no sequence header"))?;
            let header = filmcraft_av1::SequenceHeader::parse(sequence.1)
                .map_err(|e| broken(&format!("sequence header: {e}")))?;
            let pixels = u64::from(header.max_frame_width) * u64::from(header.max_frame_height);
            if pixels > limits.max_pixels || pixels * 6 > limits.max_decompressed {
                return Err(Error::TooLarge);
            }
            let pictures = av1(stream, pixels, deadline)?;
            deadline.check()?;
            let picture = pictures
                .into_iter()
                .next()
                .ok_or_else(|| broken("AV1 image shows nothing"))?;
            Ok(Planes {
                width: picture.width,
                height: picture.height,
                depth: picture.bit_depth,
                subsampling: (picture.subsampling_x, picture.subsampling_y),
                mono: picture.mono_chrome,
                matrix: picture.matrix_coefficients,
                full_range: picture.full_range,
                planes: picture.planes,
            })
        }
        b"grid" if !nested => {
            let description = heif.bytes(item)?;
            let mut fields = Fields::new(&description);
            fields.u8()?;
            let wide = fields.u8()? & 1 == 1;
            let rows = usize::from(fields.u8()?) + 1;
            let columns = usize::from(fields.u8()?) + 1;
            let width = fields.take(if wide { 4 } else { 2 })? as u32;
            let height = fields.take(if wide { 4 } else { 2 })? as u32;
            if u64::from(width) * u64::from(height) > limits.max_pixels {
                return Err(Error::TooLarge);
            }
            let tiles = heif.references(b"dimg", id);
            if tiles.len() != rows * columns {
                return Err(broken("grid has the wrong number of tiles"));
            }
            let mut decoded = Vec::with_capacity(tiles.len());
            let mut held = 0u64;
            for tile in tiles {
                let planes = decode(heif, tile, limits, deadline, true)?;
                held += u64::from(planes.width) * u64::from(planes.height);
                if held > limits.max_pixels.saturating_mul(2) {
                    return Err(Error::TooLarge);
                }
                decoded.push(planes);
            }
            grid(decoded, columns, width, height)
        }
        _ => Err(refused("its image is of a kind this does not read")),
    }
}

/// Tiles of the same size and format, row by row, cut to `width` by
/// `height`.
fn grid(tiles: Vec<Planes>, columns: usize, width: u32, height: u32) -> Result<Planes, Error> {
    let first = &tiles[0];
    let (tile_width, tile_height) = (first.width, first.height);
    let same = |t: &Planes| {
        (t.width, t.height, t.depth, t.subsampling, t.mono)
            == (
                tile_width,
                tile_height,
                first.depth,
                first.subsampling,
                first.mono,
            )
    };
    if !tiles.iter().all(same) {
        return Err(broken("grid tiles differ"));
    }
    let rows = tiles.len() / columns;
    if width > tile_width * columns as u32 || height > tile_height * rows as u32 {
        return Err(broken("grid is larger than its tiles"));
    }
    let mut out = Planes {
        width,
        height,
        depth: first.depth,
        subsampling: first.subsampling,
        mono: first.mono,
        matrix: first.matrix,
        full_range: first.full_range,
        planes: Default::default(),
    };
    for plane in 0..if first.mono { 1 } else { 3 } {
        let (out_width, out_height) = out.plane_size(plane);
        let (piece_width, piece_height) = first.plane_size(plane);
        let mut samples = vec![0u16; out_width * out_height];
        for (index, tile) in tiles.iter().enumerate() {
            let (left, top) = (
                (index % columns) * piece_width,
                (index / columns) * piece_height,
            );
            for y in 0..piece_height {
                let to_y = top + y;
                if to_y >= out_height || left >= out_width {
                    continue;
                }
                let count = piece_width.min(out_width - left);
                let from = &tile.planes[plane][y * piece_width..][..count];
                samples[to_y * out_width + left..][..count].copy_from_slice(from);
            }
        }
        out.planes[plane] = samples;
    }
    Ok(out)
}

/// How colour samples become RGB.
#[derive(Clone, Copy)]
enum Matrix {
    /// Green, blue and red as they are stored.
    Identity,
    /// The weights of red and blue in luma.
    Luma(f32, f32),
}

impl Matrix {
    fn of(code: u8) -> Result<Self, Error> {
        Ok(match code {
            0 => Self::Identity,
            1 => Self::Luma(0.2126, 0.0722),
            4 => Self::Luma(0.30, 0.11),
            7 => Self::Luma(0.212, 0.087),
            9 | 10 => Self::Luma(0.2627, 0.0593),
            // BT.601, which an unspecified matrix is taken to be.
            2 | 5 | 6 => Self::Luma(0.299, 0.114),
            _ => return Err(refused("its colours are coded in a way this does not read")),
        })
    }
}

/// A sample of `planes`, a chroma plane brought up to the size of luma, as
/// a value from 0 to 1, or centred on 0 if it is `chroma`.
fn sample(
    planes: &Planes,
    plane: usize,
    (x, y): (usize, usize),
    full_range: bool,
    chroma: bool,
) -> f32 {
    let (width, height) = planes.plane_size(plane);
    let samples = &planes.planes[plane];
    let value = if plane == 0 || planes.subsampling == (0, 0) {
        f32::from(samples[y * width + x])
    } else {
        // Between the chroma samples around the pixel's centre.
        let (sx, sy) = planes.subsampling;
        let at = |p: usize, s: u8| (p as f32 + 0.5) / f32::from(1u8 << s) - 0.5;
        let (fx, fy) = (at(x, sx).max(0.0), at(y, sy).max(0.0));
        let (x0, y0) = (fx as usize, fy as usize);
        let (x1, y1) = ((x0 + 1).min(width - 1), (y0 + 1).min(height - 1));
        let (wx, wy) = (fx - x0 as f32, fy - y0 as f32);
        let get =
            |x: usize, y: usize| f32::from(samples[y.min(height - 1) * width + x.min(width - 1)]);
        let top = get(x0, y0) * (1.0 - wx) + get(x1, y0) * wx;
        let bottom = get(x0, y1) * (1.0 - wx) + get(x1, y1) * wx;
        top * (1.0 - wy) + bottom * wy
    };
    let scale = f32::from(1u16 << (planes.depth - 8));
    let most = f32::from(((1u32 << planes.depth) - 1) as u16);
    match (chroma, full_range) {
        (false, true) => value / most,
        (false, false) => (value - 16.0 * scale) / (219.0 * scale),
        (true, true) => (value - 128.0 * scale) / most,
        (true, false) => (value - 128.0 * scale) / (224.0 * scale),
    }
}

/// The picture of `planes` as RGB, or grey, with `alpha`.
fn picture(
    planes: &Planes,
    matrix: Matrix,
    full_range: bool,
    alpha: Option<&Planes>,
    deadline: Deadline,
) -> Result<DynamicImage, Error> {
    let (width, height) = (planes.width as usize, planes.height as usize);
    let deep = planes.depth > 8;
    let most = if deep { 65535.0 } else { 255.0 };
    let level = |v: f32| (v.clamp(0.0, 1.0) * most).round() as u16;
    if let Some(alpha) = alpha
        && (alpha.width, alpha.height) != (planes.width, planes.height)
    {
        return Err(broken("alpha is not the size of the image"));
    }
    let channels = if planes.mono { 1 } else { 3 } + usize::from(alpha.is_some());
    let mut samples = Vec::with_capacity(width * height * channels);
    for y in 0..height {
        if y % 64 == 0 {
            deadline.check()?;
        }
        for x in 0..width {
            let luma = sample(planes, 0, (x, y), full_range, false);
            if planes.mono {
                samples.push(level(luma));
            } else {
                let (r, g, b) = match matrix {
                    // Green, blue and red, each read as luma is.
                    Matrix::Identity => (
                        sample(planes, 2, (x, y), full_range, false),
                        luma,
                        sample(planes, 1, (x, y), full_range, false),
                    ),
                    Matrix::Luma(kr, kb) => {
                        let u = sample(planes, 1, (x, y), full_range, true);
                        let v = sample(planes, 2, (x, y), full_range, true);
                        let kg = 1.0 - kr - kb;
                        let r = luma + 2.0 * (1.0 - kr) * v;
                        let b = luma + 2.0 * (1.0 - kb) * u;
                        (r, (luma - kr * r - kb * b) / kg, b)
                    }
                };
                samples.extend([level(r), level(g), level(b)]);
            }
            if let Some(alpha) = alpha {
                samples.push(level(sample(alpha, 0, (x, y), alpha.full_range, false)));
            }
        }
    }
    let (w, h) = (planes.width, planes.height);
    let narrow = |s: Vec<u16>| s.into_iter().map(|v| v as u8).collect::<Vec<u8>>();
    let wrong = || broken("image is not what it says");
    Ok(match (deep, planes.mono, alpha.is_some()) {
        (false, true, false) => ImageBuffer::<Luma<u8>, _>::from_raw(w, h, narrow(samples))
            .ok_or_else(wrong)?
            .into(),
        (false, true, true) => ImageBuffer::<LumaA<u8>, _>::from_raw(w, h, narrow(samples))
            .ok_or_else(wrong)?
            .into(),
        (false, false, false) => ImageBuffer::<Rgb<u8>, _>::from_raw(w, h, narrow(samples))
            .ok_or_else(wrong)?
            .into(),
        (false, false, true) => ImageBuffer::<Rgba<u8>, _>::from_raw(w, h, narrow(samples))
            .ok_or_else(wrong)?
            .into(),
        (true, true, false) => ImageBuffer::<Luma<u16>, _>::from_raw(w, h, samples)
            .ok_or_else(wrong)?
            .into(),
        (true, true, true) => ImageBuffer::<LumaA<u16>, _>::from_raw(w, h, samples)
            .ok_or_else(wrong)?
            .into(),
        (true, false, false) => ImageBuffer::<Rgb<u16>, _>::from_raw(w, h, samples)
            .ok_or_else(wrong)?
            .into(),
        (true, false, true) => ImageBuffer::<Rgba<u16>, _>::from_raw(w, h, samples)
            .ok_or_else(wrong)?
            .into(),
    })
}

/// The part a clean aperture box keeps: left, top, width, height.
fn aperture(body: &[u8], width: u32, height: u32) -> Result<(u32, u32, u32, u32), Error> {
    let mut fields = Fields::new(body);
    let mut fraction = |signed: bool| -> Result<f64, Error> {
        let n = fields.u32()?;
        let d = fields.u32()?;
        if d == 0 {
            return Err(broken("clean aperture divides by 0"));
        }
        let n = if signed {
            f64::from(n as i32)
        } else {
            f64::from(n)
        };
        Ok(n / f64::from(d))
    };
    let (w, h) = (fraction(false)?, fraction(false)?);
    let (dx, dy) = (fraction(true)?, fraction(true)?);
    // The offsets are of the centre of the aperture from that of the image.
    let left = dx + (f64::from(width) - 1.0) / 2.0 - (w - 1.0) / 2.0;
    let top = dy + (f64::from(height) - 1.0) / 2.0 - (h - 1.0) / 2.0;
    let whole = |v: f64| v.fract() == 0.0 && v >= 0.0;
    if !(whole(left) && whole(top) && whole(w) && whole(h))
        || w < 1.0
        || h < 1.0
        || left + w > f64::from(width)
        || top + h > f64::from(height)
    {
        return Err(refused("its clean aperture does not fall on whole pixels"));
    }
    Ok((left as u32, top as u32, w as u32, h as u32))
}

/// What the colours of the picture are, as the file says.
enum Described {
    Srgb,
    Icc(Vec<u8>),
    /// Primaries and transfer, as ITU-T H.273 numbers them.
    Cicp(u8, u8),
}

fn described(colour: Option<&[u8]>) -> Result<Described, Error> {
    let Some(body) = colour else {
        return Ok(Described::Srgb);
    };
    let mut fields = Fields::new(body);
    match &fields.four()? {
        b"prof" | b"rICC" => Ok(Described::Icc(fields.rest().to_vec())),
        b"nclx" => {
            let primaries = fields.u16()?;
            let transfer = fields.u16()?;
            // Those of sRGB, or close enough that every viewer shows them
            // as sRGB, or not given.
            if matches!(primaries, 1 | 2) && matches!(transfer, 1 | 2 | 6 | 13 | 14 | 15) {
                return Ok(Described::Srgb);
            }
            let known = |v: u16| u8::try_from(v).map_err(|_| refused("its colours are unknown"));
            // Not given is taken to be sRGB's.
            let primaries = match primaries {
                2 => 1,
                p => known(p)?,
            };
            let transfer = match transfer {
                2 => 13,
                t => known(t)?,
            };
            CicpColorPrimaries::try_from(primaries)
                .map_err(|_| refused("its colour primaries are unknown"))?;
            TransferCharacteristics::try_from(transfer)
                .map_err(|_| refused("its transfer function is unknown"))?;
            Ok(Described::Cicp(primaries, transfer))
        }
        _ => Ok(Described::Srgb),
    }
}

/// What turns colours of `primaries` and `transfer` into sRGB.
fn cicp_to_srgb(primaries: u8, transfer: u8) -> Result<Option<ToSrgb>, Error> {
    let primaries = CicpColorPrimaries::try_from(primaries)
        .map_err(|_| refused("its colour primaries are unknown"))?;
    let transfer = TransferCharacteristics::try_from(transfer)
        .map_err(|_| refused("its transfer function is unknown"))?;
    let mut profile = ColorProfile::new_srgb();
    let cicp = CicpProfile {
        color_primaries: primaries,
        transfer_characteristics: transfer,
        matrix_coefficients: MatrixCoefficients::Identity,
        full_range: true,
    };
    // What it returns says nothing; the description is kept only when the
    // colours were set from it.
    profile.update_rgb_colorimetry_from_cicp(cicp);
    if profile.cicp.is_none() || profile.red_trc.is_none() {
        return Err(refused("its colours cannot be brought into sRGB"));
    }
    Ok(ToSrgb::of(profile))
}

/// The white of sRGB on a display of high dynamic range, in nits: that of
/// a page of paper or of a graphic (ITU-R BT.2408).
const SDR_WHITE: f64 = 203.0;

/// Colours of `primaries` coded with PQ (`transfer` 16) or HLG (18), as
/// light on a display, brought into sRGB, whose white [`SDR_WHITE`] is:
/// what is darker than 80 percent of it is as it was, and what is
/// brighter, up to `peak` nits, is pressed into the rest, `peak` to white,
/// each colour as a whole so that its hue stays. Colours outside sRGB's are
/// cut to its edge.
fn tone_mapped(
    image: &DynamicImage,
    primaries: u8,
    transfer: u8,
    peak: f64,
    deadline: Deadline,
) -> Result<DynamicImage, Error> {
    // The chromaticities of the red, green and blue of a display, and of
    // its white.
    let chromaticities = |code: u8| match code {
        1 => Some([(0.64, 0.33), (0.30, 0.60), (0.15, 0.06)]),
        9 => Some([(0.708, 0.292), (0.170, 0.797), (0.131, 0.046)]),
        12 => Some([(0.680, 0.320), (0.265, 0.690), (0.150, 0.060)]),
        _ => None,
    };
    const D65: (f64, f64) = (0.3127, 0.3290);
    let from = chromaticities(primaries)
        .ok_or_else(|| refused("its colour primaries cannot be tone mapped"))?;
    let to_srgb = multiply(
        &invert(&to_xyz(chromaticities(1).unwrap_or_default(), D65)),
        &to_xyz(from, D65),
    );
    let luminance = to_xyz(from, D65)[1];
    // The light of each sample, in nits.
    let pq = |e: f64| {
        let (m1, m2) = (2610.0 / 16384.0, 2523.0 / 4096.0 * 128.0);
        let (c1, c2, c3) = (
            3424.0 / 4096.0,
            2413.0 / 4096.0 * 32.0,
            2392.0 / 4096.0 * 32.0,
        );
        let p = e.max(0.0).powf(1.0 / m2);
        10000.0 * ((p - c1).max(0.0) / (c2 - c3 * p)).powf(1.0 / m1)
    };
    let hlg = |e: f64| {
        let (a, b, c) = (0.178_832_77, 0.284_668_92, 0.559_910_73);
        if e <= 0.5 {
            e * e / 3.0
        } else {
            (((e - c) / a).exp() + b) / 12.0
        }
    };
    // Shown on a display of 1000 nits, as BT.2100 has HLG shown.
    let peak = if transfer == 18 { 1000.0 } else { peak };
    let top = (peak / SDR_WHITE).max(1.0);
    const KNEE: f64 = 0.8;
    let press = |m: f64| {
        if m <= KNEE || top <= 1.0 {
            return m.min(1.0);
        }
        // From the knee, at the same slope, to 1 at the top.
        let (t, end) = ((m - KNEE) / (1.0 - KNEE), (top - KNEE) / (1.0 - KNEE));
        KNEE + (1.0 - KNEE) * (t * (1.0 + t / (end * end)) / (1.0 + t)).min(1.0)
    };
    let encode = |v: f64| {
        let v = v.clamp(0.0, 1.0);
        let e = if v <= 0.003_130_8 {
            12.92 * v
        } else {
            1.055 * v.powf(1.0 / 2.4) - 0.055
        };
        (e * 65535.0).round() as u16
    };
    let alpha = image.color().has_alpha();
    let rgba = image.to_rgba16();
    let (width, height) = rgba.dimensions();
    let mut out = Vec::with_capacity(rgba.len());
    for (index, pixel) in rgba.pixels().enumerate() {
        if index % (1 << 16) == 0 {
            deadline.check()?;
        }
        let e = [0, 1, 2].map(|i| f64::from(pixel[i]) / 65535.0);
        let display = if transfer == 16 {
            e.map(pq)
        } else {
            let scene = e.map(hlg);
            let y: f64 = (0..3).map(|i| luminance[i] * scene[i]).sum();
            // The system gamma of 1.2 at 1000 nits.
            let gain = 1000.0 * y.max(1e-6).powf(0.2);
            scene.map(|v| v * gain)
        };
        let linear = [0, 1, 2]
            .map(|r| (0..3).map(|c| to_srgb[r][c] * display[c]).sum::<f64>() / SDR_WHITE)
            .map(|v| v.max(0.0));
        let m = linear.iter().copied().fold(0.0, f64::max);
        let scale = if m > 0.0 { press(m) / m } else { 0.0 };
        out.extend(linear.map(|v| encode(v * scale)));
        if alpha {
            out.push(pixel[3]);
        }
    }
    let image = if alpha {
        ImageBuffer::<Rgba<u16>, _>::from_raw(width, height, out).map(DynamicImage::from)
    } else {
        ImageBuffer::<Rgb<u16>, _>::from_raw(width, height, out).map(DynamicImage::from)
    };
    image.ok_or_else(|| broken("the picture is not the size it says"))
}

/// The matrix from RGB of `primaries` and `white` to XYZ.
fn to_xyz(primaries: [(f64, f64); 3], (wx, wy): (f64, f64)) -> [[f64; 3]; 3] {
    let column = |(x, y): (f64, f64)| [x / y, 1.0, (1.0 - x - y) / y];
    let [r, g, b] = primaries.map(column);
    let m = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]];
    let white = column((wx, wy));
    let inverse = invert(&m);
    let s = [0, 1, 2].map(|i| (0..3).map(|j| inverse[i][j] * white[j]).sum::<f64>());
    m.map(|row| [row[0] * s[0], row[1] * s[1], row[2] * s[2]])
}

fn multiply(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
    [0, 1, 2].map(|i| [0, 1, 2].map(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum()))
}

fn invert(m: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
    let [[a, b, c], [d, e, f], [g, h, i]] = *m;
    let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
    [
        [
            (e * i - f * h) / det,
            (c * h - b * i) / det,
            (b * f - c * e) / det,
        ],
        [
            (f * g - d * i) / det,
            (a * i - c * g) / det,
            (c * d - a * f) / det,
        ],
        [
            (d * h - e * g) / det,
            (b * g - a * h) / det,
            (a * e - b * d) / det,
        ],
    ]
}

/// What the colours of a picture read are in.
pub(super) enum Space {
    Srgb,
    /// A profile written anew.
    Icc(Vec<u8>),
    /// Primaries, transfer, matrix and range, as a PNG `cICP` chunk has
    /// them.
    Cicp([u8; 4]),
}

/// The picture of an AVIF, and what its colours are in.
pub(super) struct Shown {
    pub(super) image: DynamicImage,
    pub(super) space: Space,
}

/// The AVIF in `data`: its primary image, as it is shown, in sRGB.
#[cfg(test)]
pub(super) fn read(
    data: &[u8],
    limits: &Limits,
    deadline: Deadline,
) -> Result<DynamicImage, Error> {
    let shown = shown(data, limits, deadline, false, false)?;
    match shown.space {
        Space::Srgb => Ok(shown.image),
        _ => Err(refused(
            "its colours are for a display of high dynamic range",
        )),
    }
}

/// The AVIF in `data`: its primary image, as it is shown, its colours
/// left in what they are if `keep_profile` and that can be said in a PNG,
/// in sRGB otherwise. Colours of high dynamic range (PQ, HLG) stay as they
/// are, unless `tone_map`: then they are brought down into sRGB.
pub(super) fn shown(
    data: &[u8],
    limits: &Limits,
    deadline: Deadline,
    keep_profile: bool,
    tone_map: bool,
) -> Result<Shown, Error> {
    let heif = Heif::parse(data)?;
    let primary = heif.item(heif.primary)?;
    let planes = decode(&heif, heif.primary, limits, deadline, false)?;

    // The colour description in the file before that of the stream.
    let colours: Vec<&[u8]> = heif
        .properties(primary)?
        .into_iter()
        .filter(|(k, _)| k == b"colr")
        .map(|(_, body)| body)
        .collect();
    let nclx = colours.iter().find(|b| b.starts_with(b"nclx")).copied();
    let (matrix, full_range) = match nclx {
        Some(body) if body.len() >= 11 && body[8] == 0 => (body[9], body[10] & 0x80 != 0),
        _ => (planes.matrix, planes.full_range),
    };
    let matrix = if planes.mono {
        Matrix::Identity
    } else {
        Matrix::of(matrix)?
    };
    if matches!(matrix, Matrix::Identity) && !planes.mono && planes.subsampling != (0, 0) {
        return Err(broken("colours stored as they are cannot be subsampled"));
    }

    // An auxiliary image of alpha, which points to the primary one.
    let mut alpha = None;
    let mut premultiplied = false;
    for id in heif.referring(b"auxl", heif.primary) {
        let item = heif.item(id)?;
        let urn = heif.property(item, b"auxC")?.unwrap_or_default();
        let urn = urn.get(4..).unwrap_or_default();
        if urn.starts_with(b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha")
            || urn.starts_with(b"urn:mpeg:hevc:2015:auxid:1")
        {
            let planes_of_alpha = decode(&heif, id, limits, deadline, false)?;
            premultiplied = heif.references(b"prem", heif.primary).contains(&id);
            alpha = Some(planes_of_alpha);
            break;
        }
    }
    let mut image = picture(&planes, matrix, full_range, alpha.as_ref(), deadline)?;
    if premultiplied {
        unpremultiply(&mut image);
    }

    let description = described(
        colours
            .iter()
            .find(|b| b.starts_with(b"prof") || b.starts_with(b"rICC"))
            .or(nclx.as_ref())
            .copied(),
    )?;
    let channels = if image.color().has_color() { 3 } else { 1 };
    let space = match description {
        Described::Srgb => Space::Srgb,
        Described::Icc(icc) => match ToSrgb::new(Some(icc.clone())) {
            None => Space::Srgb,
            Some(colors) => match keep_profile
                .then(|| colour::rewritten_screen(&icc, channels))
                .flatten()
            {
                Some(icc) => Space::Icc(icc),
                None => {
                    colors.image(&mut image);
                    Space::Srgb
                }
            },
        },
        // PQ and HLG, brought down into what sRGB can show.
        Described::Cicp(primaries, transfer @ (16 | 18)) if tone_map => {
            // The brightest the picture is, if the file says.
            let peak = heif
                .property(primary, b"clli")?
                .and_then(|b| Some(u16::from_be_bytes([*b.first()?, *b.get(1)?])))
                .filter(|&nits| nits > 0)
                .map_or(1000.0, f64::from);
            image = tone_mapped(&image, primaries, transfer, peak, deadline)?;
            Space::Srgb
        }
        // PQ and HLG otherwise: sRGB cannot show them, so they stay as
        // they are, at 16 bits whatever the stream has.
        Described::Cicp(primaries, transfer @ (16 | 18)) => {
            image = if image.color().has_alpha() {
                image.into_rgba16().into()
            } else {
                image.into_rgb16().into()
            };
            Space::Cicp([primaries, transfer, 0, 1])
        }
        Described::Cicp(primaries, transfer) if keep_profile => {
            Space::Cicp([primaries, transfer, 0, 1])
        }
        Described::Cicp(primaries, transfer) => {
            if let Some(colors) = cicp_to_srgb(primaries, transfer)? {
                colors.image(&mut image);
            }
            Space::Srgb
        }
    };

    // Cut, turned and mirrored in the order the file gives.
    for (kind, body) in heif.properties(primary)? {
        image = match &kind {
            b"clap" => {
                let (left, top, w, h) = aperture(body, image.width(), image.height())?;
                image.crop_imm(left, top, w, h)
            }
            // Turned anticlockwise, a quarter at a time.
            b"irot" => match body.first().map(|a| a & 3) {
                Some(1) => image.rotate270(),
                Some(2) => image.rotate180(),
                Some(3) => image.rotate90(),
                _ => image,
            },
            // About a vertical axis, or a horizontal one.
            b"imir" => match body.first().map(|a| a & 1) {
                Some(0) => image.fliph(),
                Some(_) => image.flipv(),
                None => image,
            },
            _ => image,
        };
    }
    Ok(Shown { image, space })
}

/// Colours divided by their alpha.
fn unpremultiply(image: &mut DynamicImage) {
    fn undo(value: u16, alpha: u16, most: f32) -> u16 {
        match alpha {
            0 => value,
            alpha => (f32::from(value) * most / f32::from(alpha))
                .round()
                .min(most) as u16,
        }
    }
    match image {
        DynamicImage::ImageLumaA8(i) => i.pixels_mut().for_each(|p| {
            p[0] = undo(p[0].into(), p[1].into(), 255.0) as u8;
        }),
        DynamicImage::ImageRgba8(i) => i.pixels_mut().for_each(|p| {
            for c in 0..3 {
                p[c] = undo(p[c].into(), p[3].into(), 255.0) as u8;
            }
        }),
        DynamicImage::ImageLumaA16(i) => i.pixels_mut().for_each(|p| {
            p[0] = undo(p[0], p[1], 65535.0);
        }),
        DynamicImage::ImageRgba16(i) => i.pixels_mut().for_each(|p| {
            for c in 0..3 {
                p[c] = undo(p[c], p[3], 65535.0);
            }
        }),
        _ => {}
    }
}

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

    /// The decoder is not waited for past the deadline.
    #[test]
    fn av1_decoding_stops_being_waited_for_at_the_deadline() {
        let clean = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/corpus/clean");
        let data = std::fs::read(format!("{clean}/photo.avif")).unwrap();
        let heif = Heif::parse(&data).unwrap();
        let item = heif.item(heif.primary).unwrap();
        let mut stream = heif.property(item, b"av1C").unwrap().unwrap()[4..].to_vec();
        stream.extend_from_slice(&heif.bytes(item).unwrap());
        let now = Deadline(Some(std::time::Instant::now()));
        assert!(matches!(av1(stream.clone(), 1, now), Err(Error::TimedOut)));
        let later = Deadline(Some(
            std::time::Instant::now() + std::time::Duration::from_secs(60),
        ));
        assert_eq!(av1(stream.clone(), 1, later).unwrap().len(), 1);
        assert_eq!(av1(stream.clone(), 1, Deadline(None)).unwrap().len(), 1);
        // A decoder told to stop does, with no picture.
        let mut decoder = filmcraft_av1::Decoder::with_threads(1);
        decoder.set_cancel(std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
            true,
        )));
        let decoded = decoder.decode(&stream).and_then(|mut pictures| {
            pictures.extend(decoder.flush_result()?);
            Ok(pictures)
        });
        assert!(matches!(decoded, Err(filmcraft_av1::Error::Cancelled)));
    }

    fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
        [&(body.len() as u32 + 8).to_be_bytes()[..], kind, body].concat()
    }

    fn full(kind: &[u8; 4], version: u8, body: &[u8]) -> Vec<u8> {
        boxed(kind, &[&[version, 0, 0, 0][..], body].concat())
    }

    /// An item: its id, type, bytes and properties, 1 for the first.
    struct Part {
        id: u16,
        kind: &'static [u8; 4],
        bytes: Vec<u8>,
        properties: Vec<u8>,
    }

    /// An AVIF of `parts`, the first of them primary, each stored in
    /// `idat`.
    fn file(
        parts: &[Part],
        properties: &[Vec<u8>],
        references: &[(&[u8; 4], u16, &[u16])],
    ) -> Vec<u8> {
        let mut infe = Vec::new();
        let mut iloc = vec![0x44, 0x00];
        iloc.extend_from_slice(&(parts.len() as u16).to_be_bytes());
        let mut idat = Vec::new();
        let mut ipma = (parts.len() as u32).to_be_bytes().to_vec();
        for part in parts {
            infe.extend(full(
                b"infe",
                2,
                &[&part.id.to_be_bytes()[..], &[0, 0], part.kind].concat(),
            ));
            iloc.extend_from_slice(&part.id.to_be_bytes());
            iloc.extend_from_slice(&[0, 1, 0, 0, 0, 1]);
            iloc.extend_from_slice(&(idat.len() as u32).to_be_bytes());
            iloc.extend_from_slice(&(part.bytes.len() as u32).to_be_bytes());
            idat.extend_from_slice(&part.bytes);
            ipma.extend_from_slice(&part.id.to_be_bytes());
            ipma.push(part.properties.len() as u8);
            ipma.extend_from_slice(&part.properties);
        }
        let mut iref = Vec::new();
        for (kind, from, to) in references {
            let to: Vec<u8> = to.iter().flat_map(|t| t.to_be_bytes()).collect();
            let count = (to.len() as u16 / 2).to_be_bytes();
            iref.extend(boxed(
                kind,
                &[&from.to_be_bytes()[..], &count, &to].concat(),
            ));
        }
        let meta = [
            full(b"hdlr", 0, &[&[0; 4][..], b"pict", &[0; 13]].concat()),
            full(b"pitm", 0, &parts[0].id.to_be_bytes()),
            full(
                b"iinf",
                0,
                &[&(parts.len() as u16).to_be_bytes()[..], &infe].concat(),
            ),
            full(b"iloc", 1, &iloc),
            full(b"iref", 0, &iref),
            boxed(
                b"iprp",
                &[
                    boxed(b"ipco", &properties.concat()),
                    full(b"ipma", 0, &ipma),
                ]
                .concat(),
            ),
            boxed(b"idat", &idat),
        ];
        [
            boxed(b"ftyp", b"avifmif1miafavif"),
            full(b"meta", 0, &meta.concat()),
        ]
        .concat()
    }

    /// The AV1 image of the corpus photo and its configuration.
    fn photo() -> (Vec<u8>, Vec<u8>) {
        av1_of("photo.avif")
    }

    /// The AV1 image of a corpus file and its configuration.
    fn av1_of(name: &str) -> (Vec<u8>, Vec<u8>) {
        let clean = concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/corpus/clean");
        let data = std::fs::read(format!("{clean}/{name}")).unwrap();
        let heif = Heif::parse(&data).unwrap();
        let item = heif.item(heif.primary).unwrap();
        let config = heif.property(item, b"av1C").unwrap().unwrap();
        (heif.bytes(item).unwrap(), boxed(b"av1C", config))
    }

    fn read(data: &[u8]) -> Result<DynamicImage, Error> {
        super::read(data, &Limits::default(), Deadline(None))
    }

    /// The photo with `extra` properties after its configuration.
    fn photo_with(extra: &[Vec<u8>]) -> Vec<u8> {
        with("photo.avif", extra)
    }

    /// The image of a corpus file with `extra` properties after its
    /// configuration.
    fn with(name: &str, extra: &[Vec<u8>]) -> Vec<u8> {
        let (bytes, config) = av1_of(name);
        let properties = [vec![config], extra.to_vec()].concat();
        let indexes = (1..=properties.len() as u8).collect();
        file(
            &[Part {
                id: 1,
                kind: b"av01",
                bytes,
                properties: indexes,
            }],
            &properties,
            &[],
        )
    }

    #[test]
    fn the_picture_is_turned_mirrored_and_cut_as_it_says() {
        let plain = read(&photo_with(&[])).unwrap();
        assert_eq!((plain.width(), plain.height()), (64, 48));
        let turned = read(&photo_with(&[boxed(b"irot", &[1])])).unwrap();
        assert_eq!(turned, plain.rotate270());
        let mirrored = read(&photo_with(&[boxed(b"imir", &[0])])).unwrap();
        assert_eq!(mirrored, plain.fliph());
        // Half of each side, about the centre.
        let fraction = |n: i32, d: u32| [n.to_be_bytes(), d.to_be_bytes()].concat();
        let clap = [
            fraction(32, 1),
            fraction(24, 1),
            fraction(0, 1),
            fraction(0, 1),
        ]
        .concat();
        let cut = read(&photo_with(&[boxed(b"clap", &clap)])).unwrap();
        assert_eq!(cut, plain.crop_imm(16, 12, 32, 24));
        // Cut, then turned: in the order given.
        let both = read(&photo_with(&[boxed(b"clap", &clap), boxed(b"irot", &[3])])).unwrap();
        assert_eq!(both, plain.crop_imm(16, 12, 32, 24).rotate90());
    }

    #[test]
    fn tiles_of_a_grid_are_put_together() {
        let plain = read(&photo_with(&[])).unwrap().to_rgb8();
        let (bytes, config) = photo();
        // Two tiles across, cut to 100 wide.
        let grid = [0, 0, 0, 1, 0, 100, 0, 48].to_vec();
        let parts = [
            Part {
                id: 1,
                kind: b"grid",
                bytes: grid,
                properties: vec![],
            },
            Part {
                id: 2,
                kind: b"av01",
                bytes: bytes.clone(),
                properties: vec![1],
            },
            Part {
                id: 3,
                kind: b"av01",
                bytes,
                properties: vec![1],
            },
        ];
        let data = file(&parts, &[config], &[(b"dimg", 1, &[2, 3])]);
        let image = read(&data).unwrap().to_rgb8();
        assert_eq!(image.dimensions(), (100, 48));
        for (x, y, pixel) in image.enumerate_pixels() {
            assert_eq!(pixel, plain.get_pixel(x % 64, y), "at {x},{y}");
        }
    }

    #[test]
    fn alpha_comes_from_its_auxiliary_image() {
        let plain = read(&photo_with(&[])).unwrap().to_rgb8();
        let (bytes, config) = photo();
        let urn = full(b"auxC", 0, b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0");
        let parts = [
            Part {
                id: 1,
                kind: b"av01",
                bytes: bytes.clone(),
                properties: vec![1],
            },
            Part {
                id: 2,
                kind: b"av01",
                bytes,
                properties: vec![1, 2],
            },
        ];
        let image = read(&file(&parts, &[config, urn], &[(b"auxl", 2, &[1])])).unwrap();
        let DynamicImage::ImageRgba8(image) = image else {
            panic!("no alpha");
        };
        for (x, y, Rgba([r, g, b, a])) in image.enumerate_pixels() {
            assert_eq!(Rgb([*r, *g, *b]), *plain.get_pixel(x, y));
            // The alpha image is the photo itself, whose luma it takes.
            let Rgb([pr, pg, pb]) = *plain.get_pixel(x, y);
            let luma = 0.299 * f32::from(pr) + 0.587 * f32::from(pg) + 0.114 * f32::from(pb);
            assert!(
                (f32::from(*a) - luma).abs() < 3.0,
                "at {x},{y}: {a} for {luma}"
            );
        }
    }

    #[test]
    fn colours_are_brought_into_srgb() {
        let plain = read(&with("colours.avif", &[])).unwrap().to_rgb8();
        // Display P3 with the sRGB curve: the same numbers are more
        // saturated colours, which sRGB shows with more of the others.
        // With the matrix and range of `colours.avif`, or of the photo.
        let described = |primaries: u16, transfer: u16, coding: [u8; 3]| {
            boxed(
                b"colr",
                &[
                    &b"nclx"[..],
                    &primaries.to_be_bytes(),
                    &transfer.to_be_bytes(),
                    &coding,
                ]
                .concat(),
            )
        };
        let nclx = |primaries, transfer| described(primaries, transfer, [0, 2, 0]);
        let photo_nclx = |primaries, transfer| described(primaries, transfer, [0, 6, 0x80]);
        let p3 = read(&with("colours.avif", &[nclx(12, 13)]))
            .unwrap()
            .to_rgb8();
        let apart = |one: &image::RgbImage, other: &image::RgbImage| {
            one.as_raw()
                .iter()
                .zip(other.as_raw())
                .map(|(a, b)| a.abs_diff(*b))
                .max()
                .unwrap()
        };
        assert!(apart(&p3, &plain) > 20, "{}", apart(&p3, &plain));
        // Neither more nor less saturated in grey.
        let grey = read(&photo_with(&[photo_nclx(1, 13)])).unwrap().to_rgb8();
        assert_eq!(grey, read(&photo_with(&[])).unwrap().to_rgb8());
        let p3_grey = read(&photo_with(&[photo_nclx(12, 13)])).unwrap().to_rgb8();
        assert!(apart(&grey, &p3_grey) <= 1);
        let same = read(&with("colours.avif", &[nclx(1, 13)]))
            .unwrap()
            .to_rgb8();
        assert_eq!(same, plain);
        assert!(matches!(
            read(&with("colours.avif", &[nclx(9, 16)])),
            Err(Error::Unsupported { .. })
        ));
    }

    /// PQ and HLG brought into sRGB: the white of a page is the same in
    /// both, darker is as it was, the brightest is white, and the colour of
    /// what is pressed stays.
    #[test]
    fn high_dynamic_range_is_tone_mapped() {
        // The code of PQ for so many nits.
        let pq = |nits: f64| {
            let (m1, m2) = (2610.0 / 16384.0, 2523.0 / 4096.0 * 128.0);
            let (c1, c2, c3) = (
                3424.0 / 4096.0,
                2413.0 / 4096.0 * 32.0,
                2392.0 / 4096.0 * 32.0,
            );
            let y = (nits / 10000.0).powf(m1);
            (((c1 + c2 * y) / (1.0 + c3 * y)).powf(m2) * 65535.0).round() as u16
        };
        let grey = |code: u16| [code, code, code];
        let pixels = [
            grey(0),
            grey(pq(50.0)),
            grey(pq(203.0)),
            grey(pq(1000.0)),
            grey(pq(4000.0)),
            // A bright red of BT.2020, of 600 nits.
            [pq(600.0), pq(20.0), pq(20.0)],
            // HLG's white of a page: 75 percent.
            grey((0.75 * 65535.0f64).round() as u16),
        ];
        let image = |pixels: &[[u16; 3]]| {
            DynamicImage::from(
                ImageBuffer::<Rgb<u16>, _>::from_raw(
                    pixels.len() as u32,
                    1,
                    pixels.iter().flatten().copied().collect(),
                )
                .unwrap(),
            )
        };
        let mapped = |transfer: u8, pixels: &[[u16; 3]]| {
            tone_mapped(&image(pixels), 9, transfer, 1000.0, Deadline(None))
                .unwrap()
                .to_rgb8()
                .pixels()
                .map(|p| p.0)
                .collect::<Vec<_>>()
        };
        let pq_mapped = mapped(16, &pixels[..6]);
        assert_eq!(pq_mapped[0], [0, 0, 0]);
        // 50 nits is a quarter of white, below the knee: as it was,
        // 0.246 of light, 135 in sRGB.
        assert!(
            pq_mapped[1].iter().all(|&v| v.abs_diff(135) <= 1),
            "{:?}",
            pq_mapped[1]
        );
        // White, pressed a little: 0.9 of light.
        assert!(
            pq_mapped[2].iter().all(|&v| v.abs_diff(243) <= 1),
            "{:?}",
            pq_mapped[2]
        );
        assert_eq!(pq_mapped[3], [255, 255, 255]);
        assert_eq!(pq_mapped[4], [255, 255, 255]);
        let [r, g, b] = pq_mapped[5];
        // Its green is outside sRGB's, and cut to the edge.
        assert!(r == 255 && g < 60 && b < 60, "{r} {g} {b}");
        // Darker to brighter stays so.
        let ramp: Vec<[u16; 3]> = (0..=100).map(|i| grey(pq(f64::from(i) * 12.0))).collect();
        let ramp = mapped(16, &ramp);
        assert!(ramp.windows(2).all(|w| w[0][0] <= w[1][0]));
        let hlg = mapped(18, &pixels[6..]);
        assert!(
            hlg[0]
                .iter()
                .zip(pq_mapped[2])
                .all(|(a, b)| a.abs_diff(b) <= 2),
            "{:?}",
            hlg[0]
        );
        // Primaries it does not know are refused.
        assert!(tone_mapped(&image(&pixels), 5, 16, 1000.0, Deadline(None)).is_err());

        // From a file: sRGB, not the colours of the stream.
        let nclx = boxed(
            b"colr",
            &[
                &b"nclx"[..],
                &9u16.to_be_bytes(),
                &16u16.to_be_bytes(),
                &[0, 2, 0],
            ]
            .concat(),
        );
        let data = with("colours.avif", &[nclx]);
        let kept = shown(&data, &Limits::default(), Deadline(None), false, false).unwrap();
        let sdr = shown(&data, &Limits::default(), Deadline(None), false, true).unwrap();
        assert!(matches!(sdr.space, Space::Srgb));
        assert_ne!(sdr.image.to_rgb8(), kept.image.to_rgb8());
    }

    /// Colours to be kept stay as they are, under what the file says they
    /// are in; those of high dynamic range always do, at 16 bits.
    #[test]
    fn colours_are_kept_in_what_they_are_in() {
        let nclx = |primaries: u16, transfer: u16| {
            boxed(
                b"colr",
                &[
                    &b"nclx"[..],
                    &primaries.to_be_bytes(),
                    &transfer.to_be_bytes(),
                    &[0, 2, 0],
                ]
                .concat(),
            )
        };
        let shown = |data: &[u8], keep| {
            shown(data, &Limits::default(), Deadline(None), keep, false).unwrap()
        };
        let plain = read(&with("colours.avif", &[])).unwrap();
        let p3 = shown(&with("colours.avif", &[nclx(12, 13)]), true);
        assert!(matches!(p3.space, Space::Cicp([12, 13, 0, 1])));
        assert_eq!(p3.image, plain);
        let pq = shown(&with("colours.avif", &[nclx(9, 16)]), false);
        assert!(matches!(pq.space, Space::Cicp([9, 16, 0, 1])));
        assert_eq!(pq.image.to_rgb8(), plain.to_rgb8());
        assert!(matches!(pq.image, DynamicImage::ImageRgb16(_)));

        let jpeg = std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/corpus/clean/p3.jpg"
        ))
        .unwrap();
        let mut decoder =
            image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&jpeg)).unwrap();
        let icc = image::ImageDecoder::icc_profile(&mut decoder)
            .unwrap()
            .unwrap();
        let profiled = with(
            "colours.avif",
            &[boxed(b"colr", &[&b"prof"[..], &icc].concat())],
        );
        let kept = shown(&profiled, true);
        assert!(
            matches!(&kept.space, Space::Icc(new) if *new == colour::rewritten_rgb(&icc).unwrap())
        );
        assert_eq!(kept.image, plain);
        let converted = shown(&profiled, false);
        assert!(matches!(converted.space, Space::Srgb));
        assert_ne!(converted.image, plain);
    }

    #[test]
    fn a_property_it_must_understand_and_does_not_is_refused() {
        let (bytes, config) = photo();
        let properties = [config, boxed(b"zzzz", &[])];
        let part = Part {
            id: 1,
            kind: b"av01",
            bytes,
            properties: vec![1, 0x82],
        };
        assert!(matches!(
            read(&file(&[part], &properties, &[])),
            Err(Error::Unsupported { .. })
        ));
    }
}