musefs-format 1.0.0

On-the-fly audio metadata synthesis and byte-layout for musefs (FLAC/MP3/MP4/Ogg/WAV).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
//! Hand-rolled MP4/M4A box layer: parse the structure, read iTunes metadata, and
//! regenerate `moov` (with patched chunk offsets) to synthesize a re-tagged file
//! whose `mdat` audio payload is served verbatim. Strict: anything outside the
//! supported shape (single audio track, one `mdat`, non-fragmented) is rejected.

use crate::convert::usize_from;
use crate::error::{FormatError, Result};
use crate::input::{
    ArtInput, BinaryTagInput, EmbeddedBinaryTag, EmbeddedPicture, PictureType, TagInput,
};
use crate::layout::{RegionLayout, Segment};
use crate::size;
use std::io::{self, Read, Seek, SeekFrom};

const MAX_MP4_METADATA_BYTES: u64 = 256 * 1024 * 1024;

fn be_u32(b: &[u8], pos: usize) -> Result<u32> {
    let s = b.get(pos..pos + 4).ok_or(FormatError::Malformed)?;
    Ok(u32::from_be_bytes(s.try_into().unwrap()))
}

fn be_u64(b: &[u8], pos: usize) -> Result<u64> {
    let s = b.get(pos..pos + 8).ok_or(FormatError::Malformed)?;
    Ok(u64::from_be_bytes(s.try_into().unwrap()))
}

/// A located box header within some buffer. `start` is relative to that buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct BoxRef {
    kind: [u8; 4],
    start: usize,
    header_len: usize, // 8, or 16 for 64-bit largesize
    total_len: usize,  // header + payload
}

impl BoxRef {
    fn payload_start(&self) -> usize {
        self.start + self.header_len
    }
    fn end(&self) -> usize {
        self.start + self.total_len
    }
    /// `buf` must be the same buffer `read_box` parsed this header from — offsets
    /// are relative to it. The debug assertion catches a wrong-buffer call in tests.
    fn payload<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
        debug_assert!(
            self.end() <= buf.len(),
            "BoxRef::payload called with a buffer it was not parsed from"
        );
        &buf[self.payload_start()..self.end()]
    }
}

/// A parsed box header (the payload need not be in memory). Public so the core
/// reader can reason about box bounds while seeking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BoxHeader {
    /// The 4-byte box type, e.g. `*b"moov"`.
    pub kind: [u8; 4],
    /// 8, or 16 for a 64-bit largesize.
    pub header_len: u64,
    /// Total box length: header + payload.
    pub total_len: u64,
}

/// Parse a box header from `hdr` (>= 8 bytes; >= 16 if it uses a 64-bit
/// largesize). `remaining` is the byte count from this box's start to EOF, used
/// to resolve a `size == 0` ("extends to end") box.
pub fn box_header(hdr: &[u8], remaining: u64) -> Result<BoxHeader> {
    let size32 = u64::from(be_u32(hdr, 0)?);
    let kind: [u8; 4] = hdr
        .get(4..8)
        .ok_or(FormatError::Malformed)?
        .try_into()
        .unwrap();
    let (header_len, total_len) = match size32 {
        1 => (16u64, be_u64(hdr, 8)?),
        0 => (8u64, remaining),
        n => (8u64, n),
    };
    if total_len < header_len || total_len > remaining {
        return Err(FormatError::Malformed);
    }
    Ok(BoxHeader {
        kind,
        header_len,
        total_len,
    })
}

/// Error from the seeking MP4 reader: an IO failure reading the file, or a
/// structural/format problem. Kept distinct so the core layer can map IO to
/// `CoreError::Io` (preserving errno) and format to `CoreError::Format`.
#[derive(Debug, thiserror::Error)]
pub enum Mp4ScanError {
    #[error(transparent)]
    Io(#[from] io::Error),
    #[error(transparent)]
    Format(#[from] FormatError),
    #[error("MP4 {box_kind} box is {size} bytes, exceeds the {cap}-byte metadata cap")]
    MetadataTooLarge {
        box_kind: &'static str,
        size: u64,
        cap: u64,
    },
}

fn read_box(buf: &[u8], pos: usize) -> Result<BoxRef> {
    let size32 = u64::from(be_u32(buf, pos)?);
    let kind: [u8; 4] = buf
        .get(pos + 4..pos + 8)
        .ok_or(FormatError::Malformed)?
        .try_into()
        .unwrap();
    let (header_len, total) = match size32 {
        1 => (16usize, be_u64(buf, pos + 8)?),
        0 => (8usize, (buf.len() - pos) as u64),
        n => (8usize, n),
    };
    let total = usize_from(total);
    let Some(end) = pos.checked_add(total) else {
        return Err(FormatError::Malformed);
    };
    if total < header_len || end > buf.len() {
        return Err(FormatError::Malformed);
    }
    Ok(BoxRef {
        kind,
        start: pos,
        header_len,
        total_len: total,
    })
}

fn child_boxes(buf: &[u8]) -> Result<Vec<BoxRef>> {
    let mut out = Vec::new();
    let mut pos = 0;
    while pos + 8 <= buf.len() {
        let b = read_box(buf, pos)?;
        pos = b.end();
        out.push(b);
    }
    Ok(out)
}

fn find_box(buf: &[u8], kind: &[u8; 4]) -> Result<Option<BoxRef>> {
    Ok(child_boxes(buf)?.into_iter().find(|b| &b.kind == kind))
}

/// Descend a path of box types; return `(payload_start, payload_len)` relative to
/// `buf` for the box at the end of the path, or None if any step is missing.
fn find_path(buf: &[u8], path: &[&[u8; 4]]) -> Result<Option<(usize, usize)>> {
    let mut base = 0usize;
    let mut last = None;
    for kind in path {
        let region = &buf[base..];
        let Some(b) = find_box(region, kind)? else {
            return Ok(None);
        };
        let ps = base + b.payload_start();
        last = Some((ps, b.total_len - b.header_len));
        base = ps;
    }
    Ok(last)
}

/// Audio payload bounds within the backing file (the verbatim `mdat` payload).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mp4Bounds {
    pub audio_offset: u64,
    pub audio_length: u64,
}

/// Validate the internal `moov` shape: no fragmentation (`mvex`), exactly one
/// track, and that track is audio (`soun`). `moov_payload` is the bytes inside
/// the `moov` box (after its header).
fn validate_moov(moov_payload: &[u8]) -> Result<()> {
    if find_box(moov_payload, b"mvex")?.is_some() {
        return Err(FormatError::NotMp4);
    }
    let traks: Vec<_> = child_boxes(moov_payload)?
        .into_iter()
        .filter(|b| &b.kind == b"trak")
        .collect();
    if traks.len() != 1 {
        return Err(FormatError::NotMp4);
    }
    let trak = traks[0].payload(moov_payload);
    let (hp, hl) = find_path(trak, &[b"mdia", b"hdlr"])?.ok_or(FormatError::NotMp4)?;
    if trak[hp..hp + hl].get(8..12) != Some(b"soun") {
        return Err(FormatError::NotMp4);
    }
    Ok(())
}

/// Validate the supported shape; return the ftyp/moov/mdat boxes (absolute offsets
/// in `buf`). Rejects fragmented, video, multi-track, and multi-`mdat` files.
fn locate(buf: &[u8]) -> Result<(BoxRef, BoxRef, BoxRef)> {
    let top = child_boxes(buf).map_err(|_| FormatError::NotMp4)?;
    if top.iter().any(|b| &b.kind == b"moof") {
        return Err(FormatError::NotMp4);
    }
    let one = |kind: &[u8; 4]| -> Result<BoxRef> {
        let mut it = top.iter().filter(|b| &b.kind == kind);
        let first = it.next().copied().ok_or(FormatError::NotMp4)?;
        if it.next().is_some() {
            return Err(FormatError::NotMp4);
        }
        Ok(first)
    };
    let ftyp = one(b"ftyp")?;
    let moov = one(b"moov")?;
    let mdat = one(b"mdat")?;

    validate_moov(moov.payload(buf))?;
    Ok((ftyp, moov, mdat))
}

/// Parse the file and return the `mdat` payload bounds, or an error to skip it.
pub fn locate_audio(buf: &[u8]) -> Result<Mp4Bounds> {
    let (_ftyp, _moov, mdat) = locate(buf)?;
    Ok(Mp4Bounds {
        audio_offset: mdat.payload_start() as u64,
        audio_length: (mdat.total_len - mdat.header_len) as u64,
    })
}

/// Everything `synthesize_layout` needs, read from the backing file once.
#[derive(Debug, Clone, PartialEq)]
pub struct Mp4Scan {
    pub ftyp: Vec<u8>,
    pub moov: Vec<u8>,
    pub mdat_header: Vec<u8>,
    pub mdat_payload_offset: u64,
    pub mdat_payload_len: u64,
}

pub fn read_structure(buf: &[u8]) -> Result<Mp4Scan> {
    let (ftyp, moov, mdat) = locate(buf)?;
    Ok(Mp4Scan {
        ftyp: buf[ftyp.start..ftyp.end()].to_vec(),
        moov: buf[moov.start..moov.end()].to_vec(),
        mdat_header: buf[mdat.start..mdat.payload_start()].to_vec(),
        mdat_payload_offset: mdat.payload_start() as u64,
        mdat_payload_len: (mdat.total_len - mdat.header_len) as u64,
    })
}

/// Read the structural boxes (`ftyp`, `moov`, and the `mdat` header) by seeking,
/// **never** reading the `mdat` payload — for audiobooks that payload is hundreds
/// of MB and is served from the backing file at read time. Produces an `Mp4Scan`
/// byte-identical to `read_structure` on the same file, so synthesis is unchanged.
///
/// The header walk reads only 8 bytes per top-level box (16 for a 64-bit
/// largesize), so it skips over the `mdat` payload to reach a trailing `moov`.
pub fn read_structure_from<R: Read + Seek>(
    r: &mut R,
    file_len: u64,
) -> std::result::Result<Mp4Scan, Mp4ScanError> {
    fn region<R: Read + Seek>(r: &mut R, off: u64, len: usize) -> io::Result<Vec<u8>> {
        r.seek(SeekFrom::Start(off))?;
        let mut buf = vec![0u8; len];
        r.read_exact(&mut buf)?;
        Ok(buf)
    }

    // (start_offset, header) for each box we care about.
    let mut ftyp: Option<(u64, BoxHeader)> = None;
    let mut moov: Option<(u64, BoxHeader)> = None;
    let mut mdat: Option<(u64, BoxHeader)> = None;
    let mut dup = false;

    let mut pos = 0u64;
    while pos + 8 <= file_len {
        // Read exactly the header — 8 bytes, plus 8 more only for a largesize box.
        // This guarantees we never touch a box's payload (notably mdat's).
        let first8 = region(r, pos, 8)?;
        let size32 = u32::from_be_bytes(first8[0..4].try_into().unwrap());
        // A largesize box needs 8 more header bytes; if the file is truncated
        // mid-header this read surfaces as Mp4ScanError::Io (UnexpectedEof).
        let hdr = if size32 == 1 {
            let mut h = first8;
            h.extend_from_slice(&region(r, pos + 8, 8)?);
            h
        } else {
            first8
        };
        let bh = box_header(&hdr, file_len - pos)?;
        let total = bh.total_len;
        match &bh.kind {
            b"moof" => return Err(FormatError::NotMp4.into()),
            b"ftyp" => dup |= ftyp.replace((pos, bh)).is_some(),
            b"moov" => dup |= moov.replace((pos, bh)).is_some(),
            b"mdat" => dup |= mdat.replace((pos, bh)).is_some(),
            _ => {}
        }
        pos += total;
    }
    if dup {
        return Err(FormatError::NotMp4.into());
    }

    let (ftyp_s, ftyp_h) = ftyp.ok_or(FormatError::NotMp4)?;
    let (moov_s, moov_h) = moov.ok_or(FormatError::NotMp4)?;
    let (mdat_s, mdat_h) = mdat.ok_or(FormatError::NotMp4)?;

    for (box_kind, total_len) in [("ftyp", ftyp_h.total_len), ("moov", moov_h.total_len)] {
        if total_len > MAX_MP4_METADATA_BYTES {
            return Err(Mp4ScanError::MetadataTooLarge {
                box_kind,
                size: total_len,
                cap: MAX_MP4_METADATA_BYTES,
            });
        }
    }

    // `try_from` rather than `as usize`: on a 32-bit target an oversized box would
    // truncate silently; a box larger than `usize` is malformed for our purposes.
    let ftyp_len = usize::try_from(ftyp_h.total_len).map_err(|_| FormatError::Malformed)?;
    let moov_len = usize::try_from(moov_h.total_len).map_err(|_| FormatError::Malformed)?;
    let ftyp_bytes = region(r, ftyp_s, ftyp_len)?;
    let moov_bytes = region(r, moov_s, moov_len)?;
    let mdat_header = region(r, mdat_s, usize_from(mdat_h.header_len))?;

    validate_moov(&moov_bytes[usize_from(moov_h.header_len)..])?;

    Ok(Mp4Scan {
        ftyp: ftyp_bytes,
        moov: moov_bytes,
        mdat_header,
        mdat_payload_offset: mdat_s + mdat_h.header_len,
        mdat_payload_len: mdat_h.total_len - mdat_h.header_len,
    })
}

/// Locate `moov/udta/meta/ilst`; `meta` is a FullBox (4 version/flags bytes before
/// its children). Returns the ilst payload range absolute within `buf`.
fn ilst_region(buf: &[u8]) -> Option<(usize, usize)> {
    let moov = find_box(buf, b"moov").ok()??;
    let mp = moov.payload(buf);
    let base = moov.payload_start();
    let (up, ul) = find_path(mp, &[b"udta"]).ok()??;
    let udta = &mp[up..up + ul];
    let meta = find_box(udta, b"meta").ok()??;
    let meta_children = udta.get(meta.payload_start() + 4..meta.end())?;
    let il = find_box(meta_children, b"ilst").ok()??;
    let start = base + up + meta.payload_start() + 4 + il.payload_start();
    Some((start, il.total_len - il.header_len))
}

/// Parse a `----` freeform atom payload into `(key, value)`. Folds (mean, name)
/// to a canonical key via the vocabulary, else keys on the verbatim `name`. Only
/// the first `data` atom is read (multi-value freeform is rare). None if malformed.
fn read_freeform(inner: &[u8]) -> Option<(String, String)> {
    let name_box = find_box(inner, b"name").ok()??;
    let data_box = find_box(inner, b"data").ok()??;
    let np = name_box.payload(inner);
    let dp = data_box.payload(inner);
    if np.len() < 4 || dp.len() < 8 {
        return None;
    }
    // The `data` box is `[type: u32][locale: u32][value]`; type 1 == UTF-8 text.
    // Binary-typed freeform values are not text tags, so skip them.
    let type_code = u32::from_be_bytes([dp[0], dp[1], dp[2], dp[3]]);
    if type_code != 1 {
        return None;
    }
    // name/mean payloads start with a 4-byte FullBox [version 1][flags 3] prefix.
    let name = std::str::from_utf8(&np[4..]).ok()?;
    let value = std::str::from_utf8(&dp[8..]).ok()?;
    let mean = find_box(inner, b"mean")
        .ok()
        .flatten()
        .map_or("com.apple.iTunes", |m| {
            let p = m.payload(inner);
            if p.len() >= 4 {
                std::str::from_utf8(&p[4..]).unwrap_or("com.apple.iTunes")
            } else {
                "com.apple.iTunes"
            }
        });
    let key = crate::tagmap::mp4_freeform_to_key(mean, name)
        .map_or_else(|| name.to_string(), str::to_string);
    Some((key, value.to_string()))
}

/// Lenient: returns empty / skips any malformed atom and never errors — this only
/// seeds metadata from existing files, so a missing or garbled tag must simply be
/// absent. Text atoms map via the vocabulary; `trkn`/`disk` yield track/disc
/// numbers; `----` freeform atoms key on their name (folded when known). Other
/// atoms are skipped.
pub fn read_tags(buf: &[u8]) -> Vec<(String, String)> {
    let Some((start, len)) = ilst_region(buf) else {
        return Vec::new();
    };
    let ilst = &buf[start..start + len];
    let mut out = Vec::new();
    for atom in child_boxes(ilst).unwrap_or_default() {
        let inner = atom.payload(ilst);
        if &atom.kind == b"----" {
            if let Some(pair) = read_freeform(inner) {
                out.push(pair);
            }
            continue;
        }
        let Ok(Some(data)) = find_box(inner, b"data") else {
            continue;
        };
        let dp = data.payload(inner);
        if dp.len() < 8 {
            continue;
        }
        let value = &dp[8..]; // skip [type 4][locale 4]
        if let Some(key) = crate::tagmap::mp4_atom_to_key(&atom.kind) {
            if let Ok(s) = std::str::from_utf8(value) {
                out.push((key.to_string(), s.to_string()));
            }
        } else if &atom.kind == b"trkn" && value.len() >= 4 {
            out.push((
                "tracknumber".into(),
                u16::from_be_bytes([value[2], value[3]]).to_string(),
            ));
        } else if &atom.kind == b"disk" && value.len() >= 4 {
            out.push((
                "discnumber".into(),
                u16::from_be_bytes([value[2], value[3]]).to_string(),
            ));
        }
    }
    out
}

/// Lenient: returns empty / skips any malformed atom and never errors — this only
/// seeds cover art from existing files, so a missing or garbled picture must simply be absent.
/// Every `data` child of every `covr` atom yields one picture (the iTunes
/// multiple-artwork convention); non-`data` children are skipped.
///
/// `max_art_bytes` caps each image body: a `data` payload whose image bytes
/// (after the 8-byte `[type][locale]` header) exceed it is skipped before any
/// copy, so an oversized `covr` in a large `moov` is never materialized.
pub fn read_pictures(buf: &[u8], max_art_bytes: usize) -> Vec<EmbeddedPicture> {
    let Some((start, len)) = ilst_region(buf) else {
        return Vec::new();
    };
    let ilst = &buf[start..start + len];
    let mut out = Vec::new();
    for atom in child_boxes(ilst).unwrap_or_default() {
        if &atom.kind != b"covr" {
            continue;
        }
        let inner = atom.payload(ilst);
        for data in child_boxes(inner).unwrap_or_default() {
            if &data.kind != b"data" {
                continue;
            }
            let dp = data.payload(inner);
            if dp.len() < 8 {
                continue;
            }
            if dp.len() - 8 > max_art_bytes {
                continue;
            }
            let mime = match u32::from_be_bytes([dp[0], dp[1], dp[2], dp[3]]) {
                13 => "image/jpeg",
                14 => "image/png",
                _ => continue,
            };
            out.push(EmbeddedPicture {
                mime: mime.to_string(),
                picture_type: PictureType::new(3).expect("3 is in range"),
                description: String::new(),
                width: 0,
                height: 0,
                data: dp[8..].to_vec(),
            });
        }
    }
    out
}

/// Extract opaque (non-text) MP4 `----` freeform atoms for binary-tag passthrough.
/// One `EmbeddedBinaryTag` per `----` atom whose first `data` sub-box is
/// binary-typed (type code != 1): key `----:<mean>:<name>`, payload the `data`
/// value bytes (after the 8-byte `[type][locale]` header). Text freeform atoms
/// (type 1) are handled by `read_tags`, so the two paths never double-store.
/// Lenient: malformed atoms are skipped. Only the first `data` sub-box is read
/// (multi-value freeform is rare; mirrors `read_freeform`).
///
/// `max_binary_tag_bytes` caps each value: a `data` payload whose value bytes
/// (after the 8-byte `[type][locale]` header) exceed it is skipped before any
/// copy, so an oversized `----` in a large `moov` is never materialized.
pub fn read_binary_tags(buf: &[u8], max_binary_tag_bytes: usize) -> Vec<EmbeddedBinaryTag> {
    let Some((start, len)) = ilst_region(buf) else {
        return Vec::new();
    };
    let ilst = &buf[start..start + len];
    let mut out = Vec::new();
    for atom in child_boxes(ilst).unwrap_or_default() {
        if &atom.kind != b"----" {
            continue;
        }
        let inner = atom.payload(ilst);
        let Ok(Some(data)) = find_box(inner, b"data") else {
            continue;
        };
        let dp = data.payload(inner);
        if dp.len() < 8 {
            continue;
        }
        if dp.len() - 8 > max_binary_tag_bytes {
            continue;
        }
        // `data` body is `[type: u32][locale: u32][value]`; type 1 == UTF-8 text,
        // which is the text path's job. Everything else is opaque binary.
        let type_code = u32::from_be_bytes([dp[0], dp[1], dp[2], dp[3]]);
        if type_code == 1 {
            continue;
        }
        // name/mean payloads carry a 4-byte FullBox prefix; default mean to iTunes.
        let Some(name) = find_box(inner, b"name").ok().flatten().and_then(|n| {
            let p = n.payload(inner);
            (p.len() >= 4)
                .then(|| std::str::from_utf8(&p[4..]).ok())
                .flatten()
        }) else {
            continue;
        };
        let mean = find_box(inner, b"mean")
            .ok()
            .flatten()
            .map_or("com.apple.iTunes", |m| {
                let p = m.payload(inner);
                if p.len() >= 4 {
                    std::str::from_utf8(&p[4..]).unwrap_or("com.apple.iTunes")
                } else {
                    "com.apple.iTunes"
                }
            });
        out.push(EmbeddedBinaryTag {
            key: format!("----:{mean}:{name}"),
            payload: dp[8..].to_vec(),
        });
    }
    out
}

fn boxed(kind: &[u8; 4], payload: &[u8]) -> Result<Vec<u8>> {
    let size = u32::try_from(8 + payload.len()).map_err(|_| FormatError::TooLarge)?;
    let mut v = size.to_be_bytes().to_vec();
    v.extend_from_slice(kind);
    v.extend_from_slice(payload);
    Ok(v)
}

fn text_atom(kind: &[u8; 4], values: &[&str]) -> Result<Vec<u8>> {
    let mut inner = Vec::new();
    for v in values {
        let mut data = 1u32.to_be_bytes().to_vec(); // type 1 = UTF-8
        data.extend_from_slice(&0u32.to_be_bytes()); // locale
        data.extend_from_slice(v.as_bytes());
        inner.extend(boxed(b"data", &data)?);
    }
    boxed(kind, &inner)
}

fn number_atom(kind: &[u8; 4], n: u16, width: usize) -> Result<Vec<u8>> {
    debug_assert!(
        width >= 4,
        "number_atom width must hold the 4-byte reserved+value prefix"
    );
    let mut data = 0u32.to_be_bytes().to_vec(); // type 0 = binary
    data.extend_from_slice(&0u32.to_be_bytes()); // locale
    let mut body = vec![0u8, 0];
    body.extend_from_slice(&n.to_be_bytes());
    body.resize(width, 0);
    data.extend_from_slice(&body);
    boxed(kind, &boxed(b"data", &data)?)
}

/// Emit a `----` freeform atom: a `mean` and `name` sub-box (each with a 4-byte
/// FullBox prefix) followed by one UTF-8 `data` sub-box per value. Note that the
/// scan path (`read_freeform`) only recovers the first value on read-back, so
/// multi-value freeform tags round-trip only their first value.
fn freeform_atom(mean: &str, name: &str, values: &[&str]) -> Result<Vec<u8>> {
    let mut inner = Vec::new();
    let mut mean_body = 0u32.to_be_bytes().to_vec(); // version/flags
    mean_body.extend_from_slice(mean.as_bytes());
    inner.extend(boxed(b"mean", &mean_body)?);
    let mut name_body = 0u32.to_be_bytes().to_vec();
    name_body.extend_from_slice(name.as_bytes());
    inner.extend(boxed(b"name", &name_body)?);
    for v in values {
        let mut data = 1u32.to_be_bytes().to_vec(); // type 1 = UTF-8
        data.extend_from_slice(&0u32.to_be_bytes()); // locale
        data.extend_from_slice(v.as_bytes());
        inner.extend(boxed(b"data", &data)?);
    }
    boxed(b"----", &inner)
}

/// Parse a `----:<mean>:<name>` opaque key back into `(mean, name)`. `name` may
/// contain `:` (only the first separator splits). `None` if not a freeform key.
fn parse_freeform_key(key: &str) -> Option<(&str, &str)> {
    key.strip_prefix("----:")?.split_once(':')
}

/// Inline framing for an opaque binary `----` atom whose `data` value
/// (`payload_len` bytes) streams next:
/// `[---- size][----][mean box][name box][data size][data][type 0][locale 0]`.
/// Mirrors `freeform_atom` but emits type code 0 (binary) and no value bytes — the
/// value is served from the DB as a `Segment::BinaryTag`.
fn freeform_binary_prefix(mean: &str, name: &str, payload_len: u64) -> Result<Vec<u8>> {
    let mut mean_body = 0u32.to_be_bytes().to_vec(); // version/flags
    mean_body.extend_from_slice(mean.as_bytes());
    let mean_box = boxed(b"mean", &mean_body)?;
    let mut name_body = 0u32.to_be_bytes().to_vec();
    name_body.extend_from_slice(name.as_bytes());
    let name_box = boxed(b"name", &name_body)?;

    let data_size = size::checked_add(16, payload_len)?; // data header + type + locale + payload
    let inner_len = size::checked_sum([mean_box.len() as u64, name_box.len() as u64, data_size])?;

    let outer_len = size::checked_add(8, inner_len)?;
    let mut out = u32::try_from(outer_len)
        .map_err(|_| FormatError::TooLarge)?
        .to_be_bytes()
        .to_vec();
    out.extend_from_slice(b"----");
    out.extend_from_slice(&mean_box);
    out.extend_from_slice(&name_box);
    out.extend_from_slice(
        &u32::try_from(data_size)
            .map_err(|_| FormatError::TooLarge)?
            .to_be_bytes(),
    );
    out.extend_from_slice(b"data");
    out.extend_from_slice(&0u32.to_be_bytes()); // type 0 = binary/implicit
    out.extend_from_slice(&0u32.to_be_bytes()); // locale
    Ok(out)
}

/// Build the `udta` box as an ordered segment list: `Segment::Inline` for all box
/// framing, with each opaque `----` value and each cover image streamed from the DB
/// (`Segment::BinaryTag`/`Segment::ArtImage`) rather than materialized. Returns
/// `(segments, streamed_total)` where `streamed_total` sums every streamed payload
/// length (binary `----` values + art). Every enclosing box size
/// (`----`/`ilst`/`meta`/`udta`) accounts for `streamed_total` at the right nesting
/// depth, so the streamed bytes splice in correctly at read time.
fn build_udta(
    tags: &[TagInput],
    binary_tags: &[BinaryTagInput],
    arts: &[ArtInput],
) -> Result<(Vec<Segment>, u64)> {
    // Group consecutive same-key text values (the DB returns tags ordered by key).
    let mut groups: Vec<(&str, Vec<&str>)> = Vec::new();
    for t in tags {
        match groups.last_mut() {
            Some(g) if g.0 == t.key => g.1.push(&t.value),
            _ => groups.push((&t.key, vec![&t.value])),
        }
    }

    // ilst content: text atoms first (materialized), then opaque `----` (streamed),
    // then cover art (streamed). `ilst_inline` accumulates framing until a streamed
    // segment forces a flush.
    let mut ilst_inline: Vec<u8> = Vec::new();
    for (key, values) in &groups {
        match crate::tagmap::key_to_mp4(key) {
            Some(crate::tagmap::Mp4Slot::Text(atom)) => {
                ilst_inline.extend(text_atom(atom, values)?);
            }
            Some(crate::tagmap::Mp4Slot::Number(atom, width)) => {
                if let Ok(n) = values.first().copied().unwrap_or("").parse::<u16>() {
                    ilst_inline.extend(number_atom(atom, n, width)?);
                }
            }
            Some(crate::tagmap::Mp4Slot::Freeform(mean, name)) => {
                ilst_inline.extend(freeform_atom(mean, name, values)?);
            }
            None => ilst_inline.extend(freeform_atom("com.apple.iTunes", key, values)?),
        }
    }

    let mut ilst_segments: Vec<Segment> = Vec::new();
    let mut streamed_total: u64 = 0;

    for bt in binary_tags {
        let Some((mean, name)) = parse_freeform_key(&bt.key) else {
            // Not a `----:<mean>:<name>` key; skip defensively (no double-store path).
            continue;
        };
        ilst_inline.extend_from_slice(&freeform_binary_prefix(mean, name, bt.len.get())?);
        ilst_segments.push(Segment::Inline(std::mem::take(&mut ilst_inline)));
        ilst_segments.push(Segment::BinaryTag {
            payload_id: bt.payload_id,
            len: bt.len,
        });
        streamed_total = size::checked_add(streamed_total, bt.len.get())?;
    }

    if !arts.is_empty() {
        // One covr atom; each art is its own `data` child (the iTunes
        // convention for multiple artworks).
        let covr_size: u64 = arts.iter().try_fold(8u64, |acc, a| {
            size::checked_add(acc, size::checked_add(16, a.data_len.get())?)
        })?;
        ilst_inline.extend_from_slice(
            &u32::try_from(covr_size)
                .map_err(|_| FormatError::TooLarge)?
                .to_be_bytes(),
        );
        ilst_inline.extend_from_slice(b"covr");
        for a in arts {
            let type_code: u32 = if a.mime == "image/png" { 14 } else { 13 };
            let data_size = size::checked_add(16, a.data_len.get())?; // data header + type + locale + image
            ilst_inline.extend_from_slice(
                &u32::try_from(data_size)
                    .map_err(|_| FormatError::TooLarge)?
                    .to_be_bytes(),
            );
            ilst_inline.extend_from_slice(b"data");
            ilst_inline.extend_from_slice(&type_code.to_be_bytes());
            ilst_inline.extend_from_slice(&0u32.to_be_bytes()); // locale; image streams next
            ilst_segments.push(Segment::Inline(std::mem::take(&mut ilst_inline)));
            ilst_segments.push(Segment::ArtImage {
                art_id: a.art_id,
                len: a.data_len,
            });
            streamed_total = size::checked_add(streamed_total, a.data_len.get())?;
        }
    } else if !ilst_inline.is_empty() {
        ilst_segments.push(Segment::Inline(std::mem::take(&mut ilst_inline)));
    }

    let ilst_inline_len: u64 = ilst_segments
        .iter()
        .map(|s| match s {
            Segment::Inline(b) => b.len() as u64,
            _ => 0,
        })
        .sum();

    let mut hdlr_body = vec![0u8; 8];
    hdlr_body.extend_from_slice(b"mdir");
    hdlr_body.extend_from_slice(b"appl");
    hdlr_body.extend_from_slice(&[0u8; 9]);
    let hdlr = boxed(b"hdlr", &hdlr_body)?;

    // Box sizes. Each enclosing box adds its 8-byte header to the inline content of
    // its child and carries `streamed_total` through unchanged (the streamed bytes
    // live at the deepest level, inside ilst).
    let ilst_size = size::checked_sum([8, ilst_inline_len, streamed_total])?;
    let meta_inline_len = 4 + hdlr.len() as u64 + 8 + ilst_inline_len; // [vf][hdlr][ilst hdr][ilst inline]
    let meta_size = size::checked_sum([8, meta_inline_len, streamed_total])?;
    let udta_inline_len = 8 + meta_inline_len; // [meta hdr][meta inline]
    let udta_size = size::checked_sum([8, udta_inline_len, streamed_total])?;

    // MP4 box sizes are 32-bit. udta encloses all inner boxes, so converting it
    // first bounds them all; refuse oversized metadata at the format boundary
    // rather than emit a silently-truncated (corrupt) size field.
    let udta_size = u32::try_from(udta_size).map_err(|_| FormatError::TooLarge)?;
    let meta_size = u32::try_from(meta_size).map_err(|_| FormatError::TooLarge)?;
    let ilst_size = u32::try_from(ilst_size).map_err(|_| FormatError::TooLarge)?;

    // Leading framing: everything up to the start of ilst content.
    let mut header = udta_size.to_be_bytes().to_vec();
    header.extend_from_slice(b"udta");
    header.extend_from_slice(&meta_size.to_be_bytes());
    header.extend_from_slice(b"meta");
    header.extend_from_slice(&0u32.to_be_bytes()); // meta FullBox version/flags
    header.extend_from_slice(&hdlr);
    header.extend_from_slice(&ilst_size.to_be_bytes());
    header.extend_from_slice(b"ilst");

    // Merge the header into the first ilst inline segment (always Inline when present,
    // since streamed segments are preceded by their framing).
    let mut segments: Vec<Segment> = Vec::new();
    let mut lead = header;
    for seg in ilst_segments {
        match seg {
            Segment::Inline(b) => lead.extend_from_slice(&b),
            other => {
                segments.push(Segment::Inline(std::mem::take(&mut lead)));
                segments.push(other);
            }
        }
    }
    // `lead` is empty only when the loop's last segment was streamed (it was
    // `take`n); otherwise it still holds the udta/meta/ilst header (when there are
    // no streamed segments) or trailing framing. Pushing an empty `lead` would
    // produce an EmptySegment that fails layout validation, so guard on non-empty.
    if !lead.is_empty() {
        segments.push(Segment::Inline(lead));
    }
    Ok((segments, streamed_total))
}

/// Patch every `stco` (4-byte) or `co64` (8-byte) chunk offset in `kept` (moov
/// children minus udta) by `delta`. Errors if a 32-bit offset would overflow.
fn patch_chunk_offsets(kept: &mut [u8], delta: i64) -> Result<()> {
    let (range, entry) = match find_path(kept, &[b"trak", b"mdia", b"minf", b"stbl", b"stco"])? {
        Some(r) => (r, 4usize),
        None => match find_path(kept, &[b"trak", b"mdia", b"minf", b"stbl", b"co64"])? {
            Some(r) => (r, 8usize),
            None => return Err(FormatError::Malformed),
        },
    };
    let (start, len) = range;
    let count = be_u32(kept, start + 4)? as usize;
    for i in 0..count {
        let pos = start + 8 + i * entry;
        if pos + entry > start + len {
            return Err(FormatError::Malformed);
        }
        if entry == 4 {
            let v = i64::from(be_u32(kept, pos)?) + delta;
            let new_val = u32::try_from(v).map_err(|_| FormatError::TooLarge)?;
            kept[pos..pos + 4].copy_from_slice(&new_val.to_be_bytes());
        } else {
            let v = be_u64(kept, pos)?.cast_signed() + delta;
            if v < 0 {
                return Err(FormatError::Malformed);
            }
            kept[pos..pos + 8].copy_from_slice(&v.cast_unsigned().to_be_bytes());
        }
    }
    Ok(())
}

/// Regenerate a re-tagged `moov` and produce the serving layout
/// `[ftyp][regenerated moov][mdat header][mdat payload]`. The mdat payload is
/// served verbatim, merely relocated, so every chunk offset shifts by a constant
/// `delta`. Patching only offset VALUES (never box sizes) means `new_moov_size`
/// is computable before `delta` — no circular dependency. Cover art (every non-empty art row, in input order) and opaque `----`
/// binary tags stream from the DB at read time, splicing into the layout.
pub fn synthesize_layout(
    scan: &Mp4Scan,
    tags: &[TagInput],
    binary_tags: &[BinaryTagInput],
    arts: &[ArtInput],
) -> Result<RegionLayout> {
    let moov_payload_start = read_box(&scan.moov, 0)?.payload_start();
    let moov_payload = &scan.moov[moov_payload_start..];
    let mut kept = Vec::new();
    for b in child_boxes(moov_payload)? {
        if &b.kind != b"udta" {
            kept.extend_from_slice(&moov_payload[b.start..b.end()]);
        }
    }

    // All art inputs are non-zero-length (the bridge drops zero-length at construction).
    let arts: Vec<ArtInput> = arts.to_vec();
    let (udta_segments, _streamed_total) = build_udta(tags, binary_tags, &arts)?;
    let udta_total: u64 = udta_segments.iter().map(Segment::len).sum();

    let new_moov_size = size::checked_sum([8, kept.len() as u64, udta_total])?;
    // MP4 box sizes are 32-bit; mirror build_udta's bound. The try_from below
    // (writing the size field) is the enforcing check.
    let new_moov_size_u32 = u32::try_from(new_moov_size).map_err(|_| FormatError::TooLarge)?;
    let new_mdat_payload_pos = size::checked_sum([
        scan.ftyp.len() as u64,
        new_moov_size,
        scan.mdat_header.len() as u64,
    ])?;
    let delta = new_mdat_payload_pos.cast_signed() - scan.mdat_payload_offset.cast_signed();

    patch_chunk_offsets(&mut kept, delta)?;

    let mut head = Vec::new();
    head.extend_from_slice(&scan.ftyp);
    head.extend_from_slice(&new_moov_size_u32.to_be_bytes());
    head.extend_from_slice(b"moov");
    head.extend_from_slice(&kept);

    // Splice the udta segment list after the moov head. `build_udta` guarantees a
    // non-empty list whose first element is the leading `Inline` framing (it opens
    // with the udta/meta/ilst header), so fold that into `head`; the rest (streamed
    // payloads + interleaved inline) follow. Finally append the truncated mdat header
    // to the last inline run before backing audio.
    let mut udta_iter = udta_segments.into_iter();
    let Some(Segment::Inline(first)) = udta_iter.next() else {
        // build_udta always yields a leading Inline; anything else is a producer bug.
        return Err(FormatError::ProducerBug(
            "build_udta did not yield a leading Inline framing segment",
        ));
    };
    head.extend_from_slice(&first);
    let mut segments: Vec<Segment> = vec![Segment::Inline(head)];
    segments.extend(udta_iter);
    match segments.last_mut() {
        Some(Segment::Inline(b)) => b.extend_from_slice(&scan.mdat_header),
        _ => segments.push(Segment::Inline(scan.mdat_header.clone())),
    }
    segments.push(Segment::BackingAudio {
        offset: scan.mdat_payload_offset,
        len: scan.mdat_payload_len,
    });
    Ok(RegionLayout::validated(segments)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::{BlobLen, PictureType};

    /// Build a 32-bit-size box: [size][type][payload].
    fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
        let mut v = u32::try_from(8 + payload.len())
            .unwrap()
            .to_be_bytes()
            .to_vec();
        v.extend_from_slice(kind);
        v.extend_from_slice(payload);
        v
    }

    #[test]
    fn walks_top_level_boxes() {
        let mut buf = bx(b"ftyp", b"M4A ");
        buf.extend(bx(b"free", b"\x00\x00"));
        let boxes = child_boxes(&buf).unwrap();
        assert_eq!(boxes.len(), 2);
        assert_eq!(&boxes[0].kind, b"ftyp");
        assert_eq!(boxes[0].payload(&buf), b"M4A ");
        assert_eq!(&boxes[1].kind, b"free");
    }

    #[test]
    fn find_box_and_nested_path() {
        let mut hdlr_payload = vec![0u8; 8];
        hdlr_payload.extend_from_slice(b"soun");
        hdlr_payload.extend_from_slice(&[0u8; 12]);
        let moov = bx(
            b"moov",
            &bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &hdlr_payload))),
        );

        let m = find_box(&moov, b"moov").unwrap().unwrap();
        let (start, len) = find_path(m.payload(&moov), &[b"trak", b"mdia", b"hdlr"])
            .unwrap()
            .unwrap();
        assert_eq!(&m.payload(&moov)[start..start + len][8..12], b"soun");
    }

    #[test]
    fn rejects_truncated_box() {
        let buf = [0u8, 0, 0, 99, b'm', b'o', b'o', b'v']; // claims 99, only 8 present
        assert!(child_boxes(&buf).is_err());
    }

    /// Minimal accepted MP4: ftyp, then (per `moov_first`) moov(one soun trak with
    /// an stco) and mdat. `mdat_payload` is the verbatim audio.
    fn mk_mp4(moov_first: bool, mdat_payload: &[u8], stco_entries: &[u32]) -> Vec<u8> {
        let mut stco = vec![0u8; 4];
        stco.extend_from_slice(&u32::try_from(stco_entries.len()).unwrap().to_be_bytes());
        for e in stco_entries {
            stco.extend_from_slice(&e.to_be_bytes());
        }
        let mut hdlr_p = vec![0u8; 8];
        hdlr_p.extend_from_slice(b"soun");
        hdlr_p.extend_from_slice(&[0u8; 12]);
        let minf = bx(b"minf", &bx(b"stbl", &bx(b"stco", &stco)));
        let mdia = bx(b"mdia", &[bx(b"hdlr", &hdlr_p), minf].concat());
        let trak = bx(b"trak", &mdia);
        let moov = bx(b"moov", &[bx(b"mvhd", &[0u8; 8]), trak].concat());
        let mdat = bx(b"mdat", mdat_payload);
        let ftyp = bx(b"ftyp", b"M4A isom");
        if moov_first {
            [ftyp, moov, mdat].concat()
        } else {
            [ftyp, mdat, moov].concat()
        }
    }

    #[test]
    fn locates_audio_moov_first_and_last() {
        for moov_first in [true, false] {
            let buf = mk_mp4(moov_first, b"AUDIODATA", &[0]);
            let b = locate_audio(&buf).unwrap();
            assert_eq!(b.audio_length, 9);
            assert_eq!(&buf[usize_from(b.audio_offset)..][..9], b"AUDIODATA");
        }
    }

    #[test]
    fn rejects_fragmented_video_and_multi_mdat() {
        let base = mk_mp4(true, b"X", &[0]);
        let mut frag = base.clone();
        frag.extend(bx(b"moof", b"\x00"));
        assert!(locate_audio(&frag).is_err());

        let mut two = base.clone();
        two.extend(bx(b"mdat", b"Y"));
        assert!(locate_audio(&two).is_err());

        let mut hdlr_p = vec![0u8; 8];
        hdlr_p.extend_from_slice(b"vide");
        hdlr_p.extend_from_slice(&[0u8; 12]);
        let video_moov = bx(b"moov", &bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &hdlr_p))));
        let vbuf = [bx(b"ftyp", b"M4A "), video_moov, bx(b"mdat", b"Z")].concat();
        assert!(locate_audio(&vbuf).is_err());
    }

    /// A `soun` trak built the way `mk_mp4` does (hdlr + minf/stbl/stco), for
    /// reuse when hand-assembling a moov to exercise a specific reject branch.
    fn soun_trak() -> Vec<u8> {
        let mut stco = vec![0u8; 4];
        stco.extend_from_slice(&1u32.to_be_bytes());
        stco.extend_from_slice(&0u32.to_be_bytes());
        let mut hdlr_p = vec![0u8; 8];
        hdlr_p.extend_from_slice(b"soun");
        hdlr_p.extend_from_slice(&[0u8; 12]);
        let minf = bx(b"minf", &bx(b"stbl", &bx(b"stco", &stco)));
        let mdia = bx(b"mdia", &[bx(b"hdlr", &hdlr_p), minf].concat());
        bx(b"trak", &mdia)
    }

    #[test]
    fn rejects_mvex_in_moov() {
        // A moov carrying an mvex box (movie-extends header => fragmented) is
        // rejected even though it otherwise holds a single valid soun trak.
        let moov = bx(
            b"moov",
            &[bx(b"mvhd", &[0u8; 8]), bx(b"mvex", b"\x00"), soun_trak()].concat(),
        );
        let buf = [bx(b"ftyp", b"M4A isom"), moov, bx(b"mdat", b"X")].concat();
        assert!(locate_audio(&buf).is_err());
    }

    #[test]
    fn rejects_multi_trak() {
        // Two trak children in moov is rejected (musefs serves single-track audio).
        let moov = bx(
            b"moov",
            &[bx(b"mvhd", &[0u8; 8]), soun_trak(), soun_trak()].concat(),
        );
        let buf = [bx(b"ftyp", b"M4A isom"), moov, bx(b"mdat", b"X")].concat();
        assert!(locate_audio(&buf).is_err());
    }

    #[test]
    fn reads_structure_parts() {
        let buf = mk_mp4(false, b"AUDIODATA", &[0]); // moov last
        let s = read_structure(&buf).unwrap();
        assert_eq!(&s.ftyp[4..8], b"ftyp");
        assert_eq!(&s.moov[4..8], b"moov");
        assert_eq!(&s.mdat_header[4..8], b"mdat");
        assert_eq!(s.mdat_payload_len, 9);
        assert_eq!(&buf[usize_from(s.mdat_payload_offset)..][..9], b"AUDIODATA");
    }

    fn data_atom(type_code: u32, value: &[u8]) -> Vec<u8> {
        let mut p = type_code.to_be_bytes().to_vec();
        p.extend_from_slice(&0u32.to_be_bytes()); // locale
        p.extend_from_slice(value);
        bx(b"data", &p)
    }

    /// Accepted file with udta/meta/ilst injected (meta is a FullBox).
    fn mp4_with_ilst(ilst_atoms: &[u8], moov_first: bool) -> Vec<u8> {
        let ilst = bx(b"ilst", ilst_atoms);
        let mut hdlr = vec![0u8; 8];
        hdlr.extend_from_slice(b"mdir");
        hdlr.extend_from_slice(b"appl");
        hdlr.extend_from_slice(&[0u8; 9]);
        let mut meta = vec![0u8; 4]; // FullBox version/flags
        meta.extend(bx(b"hdlr", &hdlr));
        meta.extend(ilst);
        let udta = bx(b"udta", &bx(b"meta", &meta));

        let mut hdlr_p = vec![0u8; 8];
        hdlr_p.extend_from_slice(b"soun");
        hdlr_p.extend_from_slice(&[0u8; 12]);
        let mut stco = vec![0u8; 4];
        stco.extend_from_slice(&1u32.to_be_bytes());
        stco.extend_from_slice(&0u32.to_be_bytes());
        let minf = bx(b"minf", &bx(b"stbl", &bx(b"stco", &stco)));
        let trak = bx(
            b"trak",
            &bx(b"mdia", &[bx(b"hdlr", &hdlr_p), minf].concat()),
        );
        let moov = bx(b"moov", &[bx(b"mvhd", &[0u8; 8]), trak, udta].concat());
        let ftyp = bx(b"ftyp", b"M4A ");
        let mdat = bx(b"mdat", b"AUDIO");
        if moov_first {
            [ftyp, moov, mdat].concat()
        } else {
            [ftyp, mdat, moov].concat()
        }
    }

    #[test]
    fn reads_text_and_track_tags() {
        let atoms = [
            bx(b"\xa9nam", &data_atom(1, b"Song")),
            bx(b"aART", &data_atom(1, b"Band")),
            bx(b"trkn", &data_atom(0, &[0, 0, 0, 3, 0, 0, 0, 0])),
        ]
        .concat();
        let buf = mp4_with_ilst(&atoms, true);
        let tags = read_tags(&buf);
        assert!(tags.contains(&("title".into(), "Song".into())));
        assert!(tags.contains(&("albumartist".into(), "Band".into())));
        assert!(tags.contains(&("tracknumber".into(), "3".into())));
    }

    #[test]
    fn reads_cover_art() {
        let jpeg = [0xff, 0xd8, 0xff, 0xe0, 1, 2, 3];
        let buf = mp4_with_ilst(&bx(b"covr", &data_atom(13, &jpeg)), false);
        let pics = read_pictures(&buf, usize::MAX);
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].mime, "image/jpeg");
        assert_eq!(pics[0].data, jpeg);
    }

    #[test]
    fn read_side_never_panics_on_garbage() {
        // Empty buffer.
        assert!(read_tags(&[]).is_empty());
        assert!(read_pictures(&[], usize::MAX).is_empty());

        // Random non-MP4 bytes.
        let garbage = b"not an mp4 file at all............";
        assert!(read_tags(garbage).is_empty());
        assert!(read_pictures(garbage, usize::MAX).is_empty());

        // Valid moov but no udta/meta/ilst.
        let no_ilst = mk_mp4(true, b"AUDIO", &[0]);
        assert!(read_tags(&no_ilst).is_empty());
        assert!(read_pictures(&no_ilst, usize::MAX).is_empty());

        // A meta FullBox whose payload is shorter than the 4 version/flags bytes it
        // needs: exercises the `udta.get(meta.payload_start()+4..meta.end())?` guard.
        let truncated_meta = bx(b"udta", &bx(b"meta", &[0u8, 0]));
        let moov = bx(b"moov", &[bx(b"mvhd", &[0u8; 8]), truncated_meta].concat());
        let ftyp = bx(b"ftyp", b"M4A ");
        let mdat = bx(b"mdat", b"AUDIO");
        let lying = [ftyp, moov, mdat].concat();
        assert!(read_tags(&lying).is_empty());
        assert!(read_pictures(&lying, usize::MAX).is_empty());
    }

    #[test]
    fn build_udta_no_art_round_trips() {
        let tags = vec![
            TagInput::new("title", "Song"),
            TagInput::new("tracknumber", "5"),
        ];
        let (segs, streamed) = build_udta(&tags, &[], &[]).unwrap();
        assert_eq!(streamed, 0);
        let prefix = materialize_udta(&segs);
        let b = read_box(&prefix, 0).unwrap();
        assert_eq!(&b.kind, b"udta");
        assert_eq!(b.total_len, prefix.len());
        // Wrap in a moov and read back through our own reader.
        let buf = [
            bx(b"ftyp", b"M4A "),
            bx(b"moov", &prefix),
            bx(b"mdat", b"A"),
        ]
        .concat();
        let tags = read_tags(&buf);
        assert!(tags.contains(&("title".into(), "Song".into())));
        assert!(tags.contains(&("tracknumber".into(), "5".into())));
    }

    #[test]
    fn build_udta_with_art_reserves_size_without_image() {
        let art = ArtInput {
            art_id: 1,
            mime: "image/png".into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(100).unwrap(),
        };
        let (segs, streamed) = build_udta(&[TagInput::new("title", "T")], &[], &[art]).unwrap();
        assert_eq!(streamed, 100);
        // The image streams as the final segment; the udta size field accounts for it.
        assert!(matches!(
            segs.last(),
            Some(Segment::ArtImage { len, .. }) if len.get() == 100
        ));
        let inline_total: usize = segs
            .iter()
            .filter_map(|s| match s {
                Segment::Inline(b) => Some(b.len()),
                _ => None,
            })
            .sum();
        let Segment::Inline(head) = &segs[0] else {
            panic!("first udta segment is inline framing");
        };
        let declared = u32::from_be_bytes(head[0..4].try_into().unwrap()) as usize;
        assert_eq!(declared, inline_total + 100);
        // The leading inline ends right after the covr/data header (image streams next).
        assert!(head.windows(4).any(|w| w == b"covr"));
    }

    #[test]
    fn build_udta_rejects_oversize_art() {
        let art = ArtInput {
            art_id: 1,
            mime: "image/jpeg".into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(u64::from(u32::MAX) + 1).unwrap(),
        };
        assert!(matches!(
            build_udta(&[TagInput::new("title", "T")], &[], &[art]),
            Err(FormatError::TooLarge)
        ));
    }

    #[test]
    fn build_udta_groups_multi_value_text() {
        // Two consecutive same-key text tags must collapse into ONE ilst atom
        // carrying REPEATED `data` sub-boxes (iTunes multi-value convention),
        // not two separate atoms and not a dropped value.
        let tags = vec![
            TagInput::new("genre", "Rock"),
            TagInput::new("genre", "Metal"),
        ];
        let (segs, streamed) = build_udta(&tags, &[], &[]).unwrap();
        assert_eq!(streamed, 0);
        let prefix = materialize_udta(&segs);

        // Exactly one `©gen` atom.
        let gen_count = prefix.windows(4).filter(|w| *w == b"\xa9gen").count();
        assert_eq!(
            gen_count, 1,
            "expected exactly one genre atom, got {gen_count}"
        );

        // Locate the `©gen` atom header and parse its children: must be two `data`
        // sub-boxes. The 4-byte kind sits at offset +4 of the box, so back up 4.
        let kind_at = prefix
            .windows(4)
            .position(|w| w == b"\xa9gen")
            .expect("genre atom present");
        let atom = read_box(&prefix, kind_at - 4).unwrap();
        assert_eq!(&atom.kind, b"\xa9gen");
        let children = child_boxes(atom.payload(&prefix)).unwrap();
        let data_count = children.iter().filter(|c| &c.kind == b"data").count();
        assert_eq!(
            data_count, 2,
            "expected two data sub-boxes, got {data_count}"
        );

        // Both values survive into the bytes.
        assert!(prefix.windows(4).any(|w| w == b"Rock"));
        assert!(prefix.windows(5).any(|w| w == b"Metal"));
    }

    #[test]
    fn build_udta_empty_tags_is_valid() {
        // A real file with no tags must still yield a structurally valid (empty)
        // udta, not a malformed box.
        let (segs, streamed) = build_udta(&[], &[], &[]).unwrap();
        assert_eq!(streamed, 0);
        let prefix = materialize_udta(&segs);
        let b = read_box(&prefix, 0).unwrap();
        assert_eq!(&b.kind, b"udta");
        assert_eq!(b.total_len, prefix.len());
        // Round-trips as having no tags.
        let buf = [
            bx(b"ftyp", b"M4A "),
            bx(b"moov", &prefix),
            bx(b"mdat", b"A"),
        ]
        .concat();
        assert!(read_tags(&buf).is_empty());
    }

    fn inline_head(layout: &RegionLayout) -> Vec<u8> {
        match &layout.segments()[0] {
            Segment::Inline(b) => b.clone(),
            _ => panic!("expected Inline head"),
        }
    }
    /// Concatenate a udta segment list into a contiguous buffer, substituting `len`
    /// zero bytes for each streamed (BinaryTag/ArtImage) segment. Box-size fields
    /// already account for these, so the result parses as a complete udta box.
    /// Do NOT use for huge reserved art lengths — read the size field off `segs[0]`.
    fn materialize_udta(segments: &[Segment]) -> Vec<u8> {
        let mut out = Vec::new();
        for seg in segments {
            match seg {
                Segment::Inline(b) => out.extend_from_slice(b),
                Segment::BinaryTag { len, .. } | Segment::ArtImage { len, .. } => {
                    out.resize(out.len() + usize_from(len.get()), 0);
                }
                other => panic!("unexpected segment in udta: {other:?}"),
            }
        }
        out
    }
    /// Locate `moov` by reading complete boxes from the front, stopping before
    /// the trailing `mdat` header (whose declared size includes the payload that
    /// is *not* present in the synthesized head — it streams as BackingAudio).
    fn find_moov_in_head(head: &[u8]) -> BoxRef {
        let mut pos = 0;
        loop {
            let b = read_box(head, pos).unwrap();
            if &b.kind == b"moov" {
                return b;
            }
            pos = b.end();
        }
    }
    fn first_stco(head: &[u8]) -> Vec<u32> {
        let moov = find_moov_in_head(head);
        let mp = moov.payload(head);
        let (sp, sl) = find_path(mp, &[b"trak", b"mdia", b"minf", b"stbl", b"stco"])
            .unwrap()
            .unwrap();
        let stco = &mp[sp..sp + sl];
        let count = u32::from_be_bytes(stco[4..8].try_into().unwrap()) as usize;
        (0..count)
            .map(|i| u32::from_be_bytes(stco[8 + i * 4..12 + i * 4].try_into().unwrap()))
            .collect()
    }

    #[test]
    fn synthesize_no_art_patches_stco() {
        let buf = mk_mp4(true, b"AUDIODATA", &[42, 100]);
        let scan = read_structure(&buf).unwrap();
        let layout = synthesize_layout(&scan, &[TagInput::new("title", "New")], &[], &[]).unwrap();

        match layout.segments().last().unwrap() {
            Segment::BackingAudio { offset, len } => {
                assert_eq!(*offset, scan.mdat_payload_offset);
                assert_eq!(*len, scan.mdat_payload_len);
            }
            _ => panic!("expected BackingAudio tail"),
        }
        let head = inline_head(&layout);
        // The synthesized head is [ftyp][moov][mdat header]; the mdat payload is
        // served verbatim as the BackingAudio tail, so its new position is exactly
        // where the head ends.
        let new_mdat = head.len() as u64;
        let delta = new_mdat - scan.mdat_payload_offset;
        assert_eq!(
            first_stco(&head),
            vec![
                42 + u32::try_from(delta).unwrap(),
                100 + u32::try_from(delta).unwrap()
            ]
        );
        // The new file head re-parses as a valid moov of the declared size.
        let moov = find_moov_in_head(&head);
        assert_eq!(moov.end(), head.len() - scan.mdat_header.len());
    }

    /// Like `mk_mp4` but the soun trak's stbl carries a `co64` (8-byte offsets)
    /// box instead of an `stco`. moov-first, since that's all this exercises.
    fn mk_mp4_co64(mdat_payload: &[u8], co64_entries: &[u64]) -> Vec<u8> {
        let mut co64 = vec![0u8; 4];
        co64.extend_from_slice(&u32::try_from(co64_entries.len()).unwrap().to_be_bytes());
        for e in co64_entries {
            co64.extend_from_slice(&e.to_be_bytes());
        }
        let mut hdlr_p = vec![0u8; 8];
        hdlr_p.extend_from_slice(b"soun");
        hdlr_p.extend_from_slice(&[0u8; 12]);
        let minf = bx(b"minf", &bx(b"stbl", &bx(b"co64", &co64)));
        let mdia = bx(b"mdia", &[bx(b"hdlr", &hdlr_p), minf].concat());
        let trak = bx(b"trak", &mdia);
        let moov = bx(b"moov", &[bx(b"mvhd", &[0u8; 8]), trak].concat());
        let mdat = bx(b"mdat", mdat_payload);
        let ftyp = bx(b"ftyp", b"M4A isom");
        [ftyp, moov, mdat].concat()
    }

    fn first_co64(head: &[u8]) -> Vec<u64> {
        let moov = find_moov_in_head(head);
        let mp = moov.payload(head);
        let (sp, sl) = find_path(mp, &[b"trak", b"mdia", b"minf", b"stbl", b"co64"])
            .unwrap()
            .unwrap();
        let co64 = &mp[sp..sp + sl];
        let count = u32::from_be_bytes(co64[4..8].try_into().unwrap()) as usize;
        (0..count)
            .map(|i| u64::from_be_bytes(co64[8 + i * 8..16 + i * 8].try_into().unwrap()))
            .collect()
    }

    #[test]
    fn synthesize_patches_co64() {
        let buf = mk_mp4_co64(b"AUDIODATA", &[42, 100]);
        let scan = read_structure(&buf).unwrap();
        let layout = synthesize_layout(&scan, &[TagInput::new("title", "New")], &[], &[]).unwrap();

        match layout.segments().last().unwrap() {
            Segment::BackingAudio { offset, len } => {
                assert_eq!(*offset, scan.mdat_payload_offset);
                assert_eq!(*len, scan.mdat_payload_len);
            }
            _ => panic!("expected BackingAudio tail"),
        }
        let head = inline_head(&layout);
        // mdat payload is served as the BackingAudio tail, so its new position is
        // exactly where the head ends; co64 offsets shift by the same delta.
        let new_mdat = head.len() as u64;
        let delta = new_mdat - scan.mdat_payload_offset;
        assert_eq!(first_co64(&head), vec![42 + delta, 100 + delta]);
        // The new file head re-parses as a valid moov of the declared size.
        let moov = find_moov_in_head(&head);
        assert_eq!(moov.end(), head.len() - scan.mdat_header.len());
    }

    #[test]
    fn synthesize_with_art_splits_for_streaming() {
        let buf = mk_mp4(false, b"AUDIODATA", &[0]);
        let scan = read_structure(&buf).unwrap();
        let art = ArtInput {
            art_id: 7,
            mime: "image/jpeg".into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(50).unwrap(),
        };
        let layout = synthesize_layout(&scan, &[TagInput::new("title", "T")], &[], &[art]).unwrap();
        let segs = layout.segments();
        assert!(matches!(segs[1], Segment::ArtImage { art_id: 7, len, .. } if len.get() == 50));
        assert!(matches!(segs[2], Segment::Inline(_))); // mdat header
        assert!(matches!(segs.last().unwrap(), Segment::BackingAudio { .. }));
    }

    #[test]
    fn synthesize_picks_first_nonempty_art() {
        // With multiple non-empty arts, the real art must be served.
        let buf = mk_mp4(false, b"AUDIODATA", &[0]);
        let scan = read_structure(&buf).unwrap();
        let real = ArtInput {
            art_id: 9,
            mime: "image/png".into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(40).unwrap(),
        };
        let layout =
            synthesize_layout(&scan, &[TagInput::new("title", "T")], &[], &[real]).unwrap();
        let segs = layout.segments();
        assert!(
            segs.iter()
                .any(|s| matches!(s, Segment::ArtImage { art_id: 9, len, .. } if len.get() == 40)),
            "the first nonempty art must be served"
        );
    }

    #[test]
    fn synthesize_handles_zero_length_mdat() {
        let buf = mk_mp4(true, b"", &[0]); // empty mdat payload
        let scan = read_structure(&buf).unwrap();
        assert_eq!(scan.mdat_payload_len, 0);
        let layout = synthesize_layout(&scan, &[TagInput::new("title", "Z")], &[], &[]).unwrap();
        match layout.segments().last().unwrap() {
            Segment::BackingAudio { offset, len } => {
                assert_eq!(*offset, scan.mdat_payload_offset);
                assert_eq!(*len, 0);
            }
            _ => panic!("expected BackingAudio tail"),
        }
    }

    #[test]
    fn box_header_parses_8_byte_16_byte_and_size0() {
        // 8-byte header: size 16, type "moov".
        let mut h = 16u32.to_be_bytes().to_vec();
        h.extend_from_slice(b"moov");
        let bh = box_header(&h, 1000).unwrap();
        assert_eq!(&bh.kind, b"moov");
        assert_eq!(bh.header_len, 8);
        assert_eq!(bh.total_len, 16);

        // 64-bit largesize: size32==1, then u64 size = 40.
        let mut h = 1u32.to_be_bytes().to_vec();
        h.extend_from_slice(b"mdat");
        h.extend_from_slice(&40u64.to_be_bytes());
        let bh = box_header(&h, 1000).unwrap();
        assert_eq!(bh.header_len, 16);
        assert_eq!(bh.total_len, 40);

        // size32==0 means "extends to EOF" -> total_len == remaining.
        let mut h = 0u32.to_be_bytes().to_vec();
        h.extend_from_slice(b"mdat");
        let bh = box_header(&h, 500).unwrap();
        assert_eq!(bh.header_len, 8);
        assert_eq!(bh.total_len, 500);
    }

    #[test]
    fn box_header_rejects_impossible_sizes() {
        // total_len < header_len.
        let mut h = 4u32.to_be_bytes().to_vec();
        h.extend_from_slice(b"moov");
        assert_eq!(box_header(&h, 1000), Err(FormatError::Malformed));
        // total_len > remaining.
        let mut h = 2000u32.to_be_bytes().to_vec();
        h.extend_from_slice(b"moov");
        assert_eq!(box_header(&h, 100), Err(FormatError::Malformed));
        // header shorter than 8 bytes.
        assert_eq!(box_header(&[0u8; 4], 1000), Err(FormatError::Malformed));
    }

    #[test]
    fn read_structure_from_matches_buffer_path() {
        // Both moov-first and moov-last (moov-last is the audiobook spike case).
        for moov_first in [true, false] {
            let buf = mk_mp4(moov_first, &vec![0xABu8; 4096], &[0]);
            let from_buf = read_structure(&buf).unwrap();
            let mut cur = std::io::Cursor::new(buf.clone());
            let from_stream = read_structure_from(&mut cur, buf.len() as u64).unwrap();
            assert_eq!(from_stream, from_buf);
        }
    }

    #[test]
    fn read_structure_from_never_reads_mdat_payload() {
        // moov LAST: reaching it requires skipping the mdat payload.
        let buf = mk_mp4(false, &vec![0xCDu8; 100_000], &[0]);
        let scan = read_structure(&buf).unwrap();
        let pay_start = scan.mdat_payload_offset;
        let pay_end = pay_start + scan.mdat_payload_len;

        // A reader that records every byte range it is asked to read.
        struct Tracking {
            inner: std::io::Cursor<Vec<u8>>,
            touched: Vec<(u64, u64)>,
        }
        impl std::io::Read for Tracking {
            fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> {
                let off = self.inner.position();
                let n = std::io::Read::read(&mut self.inner, b)?;
                self.touched.push((off, off + n as u64));
                Ok(n)
            }
        }
        impl std::io::Seek for Tracking {
            fn seek(&mut self, p: std::io::SeekFrom) -> std::io::Result<u64> {
                self.inner.seek(p)
            }
        }

        let mut tr = Tracking {
            inner: std::io::Cursor::new(buf.clone()),
            touched: Vec::new(),
        };
        let from_stream = read_structure_from(&mut tr, buf.len() as u64).unwrap();
        assert_eq!(from_stream, scan);
        for (s, e) in &tr.touched {
            assert!(
                *e <= pay_start || *s >= pay_end,
                "read [{s},{e}) overlaps mdat payload [{pay_start},{pay_end})"
            );
        }
    }

    #[test]
    fn read_freeform_extracts_name_and_value() {
        // Build a minimal `----` atom: mean + name + data(UTF-8).
        let mut mean_body = 0u32.to_be_bytes().to_vec();
        mean_body.extend_from_slice(b"com.apple.iTunes");
        let mut name_body = 0u32.to_be_bytes().to_vec();
        name_body.extend_from_slice(b"MusicBrainz Album Id");
        let mut data = 1u32.to_be_bytes().to_vec(); // type 1 = UTF-8
        data.extend_from_slice(&0u32.to_be_bytes()); // locale
        data.extend_from_slice(b"abc-123");
        let mut inner = boxed(b"mean", &mean_body).unwrap();
        inner.extend(boxed(b"name", &name_body).unwrap());
        inner.extend(boxed(b"data", &data).unwrap());

        let (key, value) = read_freeform(&inner).unwrap();
        assert_eq!(key, "musicbrainz_albumid"); // folded via vocabulary
        assert_eq!(value, "abc-123");
    }

    #[test]
    fn read_freeform_unknown_name_passes_through_verbatim() {
        let mut mean_body = 0u32.to_be_bytes().to_vec();
        mean_body.extend_from_slice(b"com.apple.iTunes");
        let mut name_body = 0u32.to_be_bytes().to_vec();
        name_body.extend_from_slice(b"My Custom Field");
        let mut data = 1u32.to_be_bytes().to_vec(); // type 1 = UTF-8
        data.extend_from_slice(&0u32.to_be_bytes()); // locale
        data.extend_from_slice(b"hello");
        let mut inner = boxed(b"mean", &mean_body).unwrap();
        inner.extend(boxed(b"name", &name_body).unwrap());
        inner.extend(boxed(b"data", &data).unwrap());

        let (key, value) = read_freeform(&inner).unwrap();
        assert_eq!(key, "My Custom Field"); // not in vocabulary -> verbatim name
        assert_eq!(value, "hello");
    }

    #[test]
    fn read_freeform_skips_binary_typed_data() {
        let mut name_body = 0u32.to_be_bytes().to_vec();
        name_body.extend_from_slice(b"My Custom Field");
        let mut data = 0u32.to_be_bytes().to_vec(); // type 0 = binary, not text
        data.extend_from_slice(&0u32.to_be_bytes()); // locale
        data.extend_from_slice(&[0xff, 0x00, 0x01]);
        let mut inner = boxed(b"name", &name_body).unwrap();
        inner.extend(boxed(b"data", &data).unwrap());

        assert!(read_freeform(&inner).is_none()); // binary-typed data is skipped
    }

    #[test]
    fn build_udta_round_trips_freeform_and_vocabulary() {
        let tags = vec![
            TagInput::new("title", "Song"),
            TagInput::new("tracknumber", "3"),
            TagInput::new("MyRating", "5"), // user-defined -> ----
            TagInput::new("musicbrainz_albumid", "abc-123"), // vocabulary -> ----
        ];
        let (segs, _streamed) = build_udta(&tags, &[], &[]).unwrap();
        let udta = materialize_udta(&segs);
        // build_udta returns a full `udta` box; read_tags expects a buffer containing
        // moov/udta/meta/ilst, so wrap udta in a minimal moov for the round trip.
        let moov = boxed(b"moov", &udta).unwrap();

        let tags = read_tags(&moov);
        for expected in [
            ("title", "Song"),
            ("tracknumber", "3"),
            ("MyRating", "5"),
            ("musicbrainz_albumid", "abc-123"),
        ] {
            assert!(
                tags.contains(&(expected.0.to_string(), expected.1.to_string())),
                "missing {expected:?} in {tags:?}"
            );
        }
    }

    #[test]
    fn read_box_rejects_overflowing_extended_size() {
        // The extended-size path (size32 == 1) reads a 64-bit box length from
        // untrusted input. Before the checked_add fix, `pos + total` overflowed
        // usize in debug (panic) or wrapped silently in release (accepting a
        // bogus length). This test feeds size32=1 with a u64::MAX extended size
        // and asserts the parser returns an error rather than panicking.
        // Bytes: [00 00 00 01] (size32=1) + b"moov" + [FF FF FF FF FF FF FF FF] (u64::MAX)
        let mut bytes = 1u32.to_be_bytes().to_vec(); // size32 = 1 → extended-size
        bytes.extend_from_slice(b"moov");
        bytes.extend_from_slice(&u64::MAX.to_be_bytes()); // huge 64-bit size
        assert!(
            read_structure(&bytes).is_err(),
            "must return an error, not panic"
        );
    }

    #[test]
    fn read_structure_from_handles_largesize_mdat() {
        // Re-encode a normal fixture's mdat with a 64-bit largesize header (the
        // real >4GB audiobook shape) and confirm both readers agree.
        fn largesize_mdat(payload: &[u8]) -> Vec<u8> {
            let total = 16 + payload.len() as u64;
            let mut v = 1u32.to_be_bytes().to_vec(); // size32 == 1
            v.extend_from_slice(b"mdat");
            v.extend_from_slice(&total.to_be_bytes()); // 64-bit largesize
            v.extend_from_slice(payload);
            v
        }
        let normal = mk_mp4(true, &[0xABu8; 64], &[0]); // [ftyp][moov][mdat]
        let scan = read_structure(&normal).unwrap();
        let payload_start = usize_from(scan.mdat_payload_offset);
        let mdat_box_start = payload_start - scan.mdat_header.len(); // normal 8-byte header
        let payload = normal[payload_start..].to_vec();
        let mut buf = normal[..mdat_box_start].to_vec(); // ftyp + moov
        buf.extend(largesize_mdat(&payload));

        let from_buf = read_structure(&buf).unwrap();
        let mut cur = std::io::Cursor::new(buf.clone());
        let from_stream = read_structure_from(&mut cur, buf.len() as u64).unwrap();
        assert_eq!(from_stream, from_buf);
        assert_eq!(from_stream.mdat_header.len(), 16); // largesize header
        assert_eq!(from_stream.mdat_payload_len, payload.len() as u64);
    }

    #[test]
    fn box_header_accepts_empty_payload_box() {
        // total_len == header_len (an 8-byte box, no payload) must be accepted.
        // `< -> <=` would make the equal case reject.
        let mut h = 8u32.to_be_bytes().to_vec();
        h.extend_from_slice(b"free");
        let bh = box_header(&h, 1000).unwrap();
        assert_eq!(bh.header_len, 8);
        assert_eq!(bh.total_len, 8);
    }

    #[test]
    fn read_box_size0_extends_to_end_from_offset() {
        // A size-0 box ("extends to EOF") at pos > 0: total_len must be
        // buf.len() - pos. `- -> +` (buf.len() + pos) and `- -> /` (buf.len() / pos)
        // both diverge. The box is placed at pos = 8 with pos + 8 <= buf.len() so the
        // be_u32 size read and the kind slice both succeed BEFORE the size-0 branch.
        let mut buf = bx(b"free", b""); // 8-byte box at pos 0
        buf.extend_from_slice(&0u32.to_be_bytes()); // size32 = 0 at pos 8
        buf.extend_from_slice(b"mdat"); // kind at pos 12..16
        buf.extend_from_slice(b"AUDIOPAYLOAD"); // 12 payload bytes
        assert_eq!(buf.len(), 28);
        let b = read_box(&buf, 8).unwrap();
        assert_eq!(&b.kind, b"mdat");
        assert_eq!(b.total_len, buf.len() - 8); // 20
    }

    #[test]
    fn read_structure_from_rejects_box_overrunning_eof() {
        // box_header's `remaining` arg is `file_len - pos`. Inflating the mdat box's
        // declared size past the bytes remaining must be rejected. `- -> +` inflates
        // `remaining` to `file_len + pos`, wrongly accepting the overrun (returns Ok).
        let mut buf = mk_mp4(true, b"AUDIO", &[0]); // [ftyp][moov][mdat], mdat last
        let scan = read_structure(&buf).unwrap();
        let mdat_start = usize_from(scan.mdat_payload_offset - scan.mdat_header.len() as u64);
        let real = u32::from_be_bytes(buf[mdat_start..mdat_start + 4].try_into().unwrap());
        buf[mdat_start..mdat_start + 4].copy_from_slice(&(real + 100).to_be_bytes());
        let mut cur = std::io::Cursor::new(buf.clone());
        assert!(read_structure_from(&mut cur, buf.len() as u64).is_err());
    }

    #[test]
    fn read_structure_from_rejects_moof() {
        // A `moof` (fragmented MP4) top-level box must be rejected via the seeking
        // path. Deleting the `b"moof"` match arm drops it to `_ => {}` and accepts.
        let mut buf = mk_mp4(true, b"AUDIO", &[0]);
        buf.extend(bx(b"moof", b"\x00\x00\x00\x00"));
        let mut cur = std::io::Cursor::new(buf.clone());
        assert!(read_structure_from(&mut cur, buf.len() as u64).is_err());
    }

    #[test]
    fn read_structure_from_rejects_duplicate_top_level_boxes() {
        // Each `dup |= X.replace(..).is_some()` accumulates a duplicate. `|= -> &=`
        // can never set `dup` (it starts false), so a duplicate box is wrongly
        // accepted. One duplicated box per kind isolates each of the three `|=` lines.
        let dup = |extra: Vec<u8>| {
            let mut buf = mk_mp4(true, b"AUDIO", &[0]);
            buf.extend(extra);
            let mut cur = std::io::Cursor::new(buf.clone());
            read_structure_from(&mut cur, buf.len() as u64).is_err()
        };
        assert!(dup(bx(b"ftyp", b"M4A isom")), "duplicate ftyp must reject"); // ftyp |= line
        // duplicate moov: reuse the moov from a fresh fixture so it is structurally valid.
        let extra_moov = {
            let other = mk_mp4(true, b"AUDIO", &[0]);
            let s = read_structure(&other).unwrap();
            s.moov
        };
        assert!(dup(extra_moov), "duplicate moov must reject"); // moov |= line
        assert!(dup(bx(b"mdat", b"Y")), "duplicate mdat must reject"); // mdat |= line
    }

    #[test]
    fn read_freeform_accepts_minimal_name_and_data() {
        // name payload == 4 (empty name) and data payload == 8 (empty value) is the
        // boundary of `np.len() < 4 || dp.len() < 8`. Both operands at the boundary,
        // so flipping EITHER `<` to `==`/`<=` makes that side true -> None.
        let name_body = 0u32.to_be_bytes().to_vec(); // exactly 4 bytes
        let mut data = 1u32.to_be_bytes().to_vec(); // type 1 = UTF-8
        data.extend_from_slice(&0u32.to_be_bytes()); // locale -> dp.len() == 8
        let mut inner = boxed(b"name", &name_body).unwrap();
        inner.extend(boxed(b"data", &data).unwrap());
        let (key, value) = read_freeform(&inner).unwrap();
        assert_eq!(key, ""); // empty name, not in vocabulary -> verbatim ""
        assert_eq!(value, "");
    }

    #[test]
    fn read_freeform_short_name_returns_none() {
        // name payload 3 bytes (< 4) with a valid 8-byte data payload. `|| -> &&`
        // makes `true && false == false`, falling through to `&np[4..]` (out of bounds
        // -> panic).
        let name_body = vec![0u8, 0, 0]; // 3 bytes
        let mut data = 1u32.to_be_bytes().to_vec();
        data.extend_from_slice(&0u32.to_be_bytes());
        let mut inner = boxed(b"name", &name_body).unwrap();
        inner.extend(boxed(b"data", &data).unwrap());
        assert!(read_freeform(&inner).is_none());
    }

    #[test]
    fn read_freeform_mean_payload_exactly_4_uses_empty_mean() {
        // mean payload == 4 (FullBox prefix, empty mean). `p.len() >= 4` must take the
        // utf8 branch (mean ""), so the vocabulary does NOT fold the iTunes name.
        // `>= -> <` falls to the default "com.apple.iTunes" mean and wrongly folds.
        let mean_body = vec![0u8, 0, 0, 0]; // exactly 4 bytes
        let mut name_body = 0u32.to_be_bytes().to_vec();
        name_body.extend_from_slice(b"MusicBrainz Album Id");
        let mut data = 1u32.to_be_bytes().to_vec();
        data.extend_from_slice(&0u32.to_be_bytes());
        data.extend_from_slice(b"abc-123");
        let mut inner = boxed(b"mean", &mean_body).unwrap();
        inner.extend(boxed(b"name", &name_body).unwrap());
        inner.extend(boxed(b"data", &data).unwrap());
        let (key, value) = read_freeform(&inner).unwrap();
        assert_eq!(key, "MusicBrainz Album Id"); // empty mean -> not folded
        assert_eq!(value, "abc-123");
    }

    #[test]
    fn read_tags_data_payload_exactly_8_is_read() {
        // A `data` payload of exactly 8 bytes (type+locale, empty value) is the
        // boundary of `dp.len() < 8`. The (empty) value must be read; `< -> ==`/`<= `
        // would skip it.
        let atoms = bx(b"\xa9nam", &data_atom(1, b"")); // dp.len() == 8
        let buf = mp4_with_ilst(&atoms, true);
        assert!(read_tags(&buf).contains(&("title".into(), String::new())));
    }

    #[test]
    fn read_tags_disk_exact_4_byte_value_yields_discnumber() {
        // disk atom, value exactly 4 bytes: `kind == disk` (== branch) `&&`
        // `value.len() >= 4` (>= branch). Kills `== -> !=` (mutant skips a real disk)
        // and `>= -> <` (mutant skips the boundary length).
        let atoms = bx(b"disk", &data_atom(0, &[0, 0, 0, 2])); // disc 2, value len 4
        let buf = mp4_with_ilst(&atoms, true);
        assert!(read_tags(&buf).contains(&("discnumber".into(), "2".into())));
    }

    #[test]
    fn read_tags_disk_short_value_is_skipped() {
        // disk with a value shorter than 4 bytes: the guard is false. `&& -> ||`
        // makes it true and indexes value[2]/value[3] out of bounds (panic).
        let atoms = bx(b"disk", &data_atom(0, &[0, 0])); // value len 2
        let buf = mp4_with_ilst(&atoms, true);
        assert!(!read_tags(&buf).iter().any(|(k, _)| k == "discnumber"));
    }

    #[test]
    fn read_tags_trkn_short_value_is_skipped() {
        // trkn with a value shorter than 4 bytes: `kind == trkn && value.len() >= 4`
        // is false. `&& -> ||` makes it true and indexes value[2]/value[3] (panic).
        let atoms = bx(b"trkn", &data_atom(0, &[0, 0])); // value len 2
        let buf = mp4_with_ilst(&atoms, true);
        assert!(!read_tags(&buf).iter().any(|(k, _)| k == "tracknumber"));
    }

    #[test]
    fn read_pictures_data_payload_exactly_8_is_read() {
        // covr/data payload of exactly 8 bytes (type+locale, empty image) is the
        // boundary of `dp.len() < 8`; the (empty) picture must be read.
        let buf = mp4_with_ilst(&bx(b"covr", &data_atom(13, b"")), true);
        let pics = read_pictures(&buf, usize::MAX);
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].mime, "image/jpeg");
        assert!(pics[0].data.is_empty());
    }

    #[test]
    fn read_pictures_recognizes_png() {
        // A covr `data` atom with type code 14 is PNG. Deleting the `14 =>` match arm
        // drops it to `_ => continue` and yields no picture.
        let png = [0x89, b'P', b'N', b'G', 1, 2, 3];
        let buf = mp4_with_ilst(&bx(b"covr", &data_atom(14, &png)), false);
        let pics = read_pictures(&buf, usize::MAX);
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].mime, "image/png");
        assert_eq!(pics[0].data, png);
    }

    #[test]
    fn read_pictures_reads_all_data_atoms_in_one_covr() {
        // iTunes convention: multiple artworks are multiple `data` children of
        // one `covr`. An unknown type code skips that child only, not its
        // siblings.
        let jpeg = [0xFF, 0xD8, 0xFF, 1];
        let png = [0x89, b'P', b'N', b'G', 2];
        let covr = bx(
            b"covr",
            &[
                data_atom(13, &jpeg),
                data_atom(99, b"skipped"), // unknown type code: this child only
                data_atom(14, &png),
            ]
            .concat(),
        );
        let buf = mp4_with_ilst(&covr, true);
        let pics = read_pictures(&buf, usize::MAX);
        assert_eq!(pics.len(), 2);
        assert_eq!(pics[0].mime, "image/jpeg");
        assert_eq!(pics[0].data, jpeg);
        assert_eq!(pics[1].mime, "image/png");
        assert_eq!(pics[1].data, png);
    }

    #[test]
    fn read_pictures_skips_art_over_budget() {
        let over = vec![0xFFu8; 5];
        let buf = mp4_with_ilst(&bx(b"covr", &data_atom(13, &over)), true);
        assert!(read_pictures(&buf, 4).is_empty());
    }

    #[test]
    fn read_pictures_accepts_art_exactly_at_budget() {
        let exact = vec![0xFFu8; 4];
        let buf = mp4_with_ilst(&bx(b"covr", &data_atom(13, &exact)), true);
        let pics = read_pictures(&buf, 4);
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].data, exact);
    }

    #[test]
    fn read_pictures_skips_non_data_children_of_covr() {
        // A non-`data` child inside covr (rare but legal) is silently skipped.
        let png = [0x89, b'P', b'N', b'G'];
        let covr = bx(
            b"covr",
            &[bx(b"free", b"pad"), data_atom(14, &png)].concat(),
        );
        let buf = mp4_with_ilst(&covr, false);
        let pics = read_pictures(&buf, usize::MAX);
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].mime, "image/png");
        assert_eq!(pics[0].data, png);
    }

    #[test]
    fn build_udta_png_art_uses_type_code_14() {
        // PNG art => covr/data type code 14; JPEG => 13. `== -> !=` flips them.
        for (mime, expected) in [("image/png", 14u32), ("image/jpeg", 13u32)] {
            let art = ArtInput {
                art_id: 1,
                mime: mime.into(),
                description: String::new(),
                picture_type: PictureType::new(3).unwrap(),
                width: 0,
                height: 0,
                data_len: BlobLen::new(10).unwrap(),
            };
            let (segs, _) = build_udta(&[TagInput::new("title", "T")], &[], &[art]).unwrap();
            let prefix = materialize_udta(&segs);
            // covr layout: [covr_size u32]["covr"][data_size u32]["data"][type u32][locale u32]
            let cpos = prefix.windows(4).position(|w| w == b"covr").expect("covr");
            assert_eq!(&prefix[cpos + 8..cpos + 12], b"data");
            let type_code = u32::from_be_bytes(prefix[cpos + 12..cpos + 16].try_into().unwrap());
            assert_eq!(type_code, expected, "mime {mime}");
        }
    }

    #[test]
    fn build_udta_art_box_sizes_are_exact() {
        // data_size = 8 + 8 + data_len; covr_size = 8 + data_size. The `+ -> -`/`+ -> *`
        // mutations change the emitted box sizes.
        let art = ArtInput {
            art_id: 1,
            mime: "image/jpeg".into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(10).unwrap(),
        };
        let (segs, _) = build_udta(&[TagInput::new("title", "T")], &[], &[art]).unwrap();
        let prefix = materialize_udta(&segs);
        let cpos = prefix.windows(4).position(|w| w == b"covr").expect("covr");
        let covr_size = u32::from_be_bytes(prefix[cpos - 4..cpos].try_into().unwrap());
        let data_size = u32::from_be_bytes(prefix[cpos + 4..cpos + 8].try_into().unwrap());
        assert_eq!(data_size, 8 + 8 + 10); // 26
        assert_eq!(covr_size, 8 + data_size); // 34
    }

    #[test]
    fn build_udta_multiple_arts_one_covr_n_data_atoms() {
        let art = |id: i64, mime: &str, len: u64| ArtInput {
            art_id: id,
            mime: mime.into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(len).unwrap(),
        };
        let arts = [art(1, "image/jpeg", 10), art(2, "image/png", 20)];
        let (segs, streamed) = build_udta(&[TagInput::new("title", "T")], &[], &arts).unwrap();
        assert_eq!(streamed, 30);

        // Exactly one covr atom, sized for both data atoms: 8 + Σ(16 + len).
        let prefix = materialize_udta(&segs);
        let covr_positions: Vec<usize> = prefix
            .windows(4)
            .enumerate()
            .filter_map(|(i, w)| (w == b"covr").then_some(i))
            .collect();
        assert_eq!(covr_positions.len(), 1);
        let cpos = covr_positions[0];
        let covr_size = u32::from_be_bytes(prefix[cpos - 4..cpos].try_into().unwrap());
        assert_eq!(covr_size, 8 + (16 + 10) + (16 + 20));

        // First data atom: jpeg (type 13), size 16+10; second: png (14), 16+20.
        let d1 = cpos + 4;
        assert_eq!(&prefix[d1 + 4..d1 + 8], b"data");
        assert_eq!(
            u32::from_be_bytes(prefix[d1..d1 + 4].try_into().unwrap()),
            26
        );
        assert_eq!(
            u32::from_be_bytes(prefix[d1 + 8..d1 + 12].try_into().unwrap()),
            13
        );
        let d2 = d1 + 26;
        assert_eq!(&prefix[d2 + 4..d2 + 8], b"data");
        assert_eq!(
            u32::from_be_bytes(prefix[d2..d2 + 4].try_into().unwrap()),
            36
        );
        assert_eq!(
            u32::from_be_bytes(prefix[d2 + 8..d2 + 12].try_into().unwrap()),
            14
        );

        // Streamed segments: one ArtImage per art, in input order.
        let art_segs: Vec<(i64, u64)> = segs
            .iter()
            .filter_map(|s| match s {
                Segment::ArtImage { art_id, len } => Some((*art_id, len.get())),
                _ => None,
            })
            .collect();
        assert_eq!(art_segs, vec![(1, 10), (2, 20)]);
    }

    #[test]
    fn build_udta_two_arts_round_trips_through_read_pictures() {
        // materialize_udta zero-fills streamed payloads, so assert order +
        // mime only (mime derives from the inline type code, which survives).
        let art = |id: i64, mime: &str, len: u64| ArtInput {
            art_id: id,
            mime: mime.into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(len).unwrap(),
        };
        let arts = [art(1, "image/jpeg", 5), art(2, "image/png", 9)];
        let (segs, _) = build_udta(&[TagInput::new("title", "Song")], &[], &arts).unwrap();
        let prefix = materialize_udta(&segs);
        let buf = [
            bx(b"ftyp", b"M4A "),
            bx(b"moov", &prefix),
            bx(b"mdat", b"A"),
        ]
        .concat();
        let pics = read_pictures(&buf, usize::MAX);
        assert_eq!(pics.len(), 2);
        assert_eq!(pics[0].mime, "image/jpeg");
        assert_eq!(pics[0].data.len(), 5);
        assert_eq!(pics[1].mime, "image/png");
        assert_eq!(pics[1].data.len(), 9);
    }

    #[test]
    fn build_udta_udta_size_exactly_u32_max_is_ok() {
        // The guard is `udta_size > u32::MAX` (strict). udta_size == u32::MAX must be
        // accepted; `> -> >=` rejects the exact boundary. data_len is reserved as a
        // number (no image bytes), so the boundary is cheap to hit.
        fn art(data_len: u64) -> ArtInput {
            ArtInput {
                art_id: 1,
                mime: "image/jpeg".into(),
                description: String::new(),
                picture_type: PictureType::new(3).unwrap(),
                width: 0,
                height: 0,
                data_len: BlobLen::new(data_len).unwrap(),
            }
        }
        // Derive the fixed overhead from the udta size field (segs[0] inline), with
        // data_len 1 (BlobLen is non-zero), without materializing any image bytes.
        let (segs0, _) = build_udta(&[TagInput::new("title", "T")], &[], &[art(1)]).unwrap();
        let Segment::Inline(h0) = &segs0[0] else {
            panic!("inline head")
        };
        let overhead = u64::from(u32::from_be_bytes(h0[0..4].try_into().unwrap())) - 1;
        let max_len = u64::from(u32::MAX) - overhead;

        let (segs_max, streamed) =
            build_udta(&[TagInput::new("title", "T")], &[], &[art(max_len)]).unwrap();
        assert_eq!(streamed, max_len);
        let Segment::Inline(h_max) = &segs_max[0] else {
            panic!("inline head")
        };
        assert_eq!(
            u32::from_be_bytes(h_max[0..4].try_into().unwrap()),
            u32::MAX
        );

        assert!(matches!(
            build_udta(&[TagInput::new("title", "T")], &[], &[art(max_len + 1)]),
            Err(FormatError::TooLarge)
        ));
    }

    #[test]
    fn patch_chunk_offsets_stco_overflow_and_underflow_boundaries() {
        // kept = a single soun trak with one stco entry (offset 0). v = 0 + delta is
        // guarded by `v < 0 || v > u32::MAX`. Boundary deltas pin every guard mutant;
        // delta 0 (accepted) also pins the `:590` `+ -> *` bound at i = 0.
        let mut k = soun_trak();
        assert!(patch_chunk_offsets(&mut k, 0).is_ok()); // v == 0

        let mut k = soun_trak();
        assert!(patch_chunk_offsets(&mut k, i64::from(u32::MAX)).is_ok()); // v == u32::MAX

        let mut k = soun_trak();
        assert!(matches!(
            patch_chunk_offsets(&mut k, i64::from(u32::MAX) + 1), // v == u32::MAX + 1
            Err(FormatError::TooLarge)
        ));

        let mut k = soun_trak();
        assert!(matches!(
            patch_chunk_offsets(&mut k, -1), // v == -1
            Err(FormatError::TooLarge)
        ));
    }

    #[test]
    fn patch_chunk_offsets_rejects_count_past_table() {
        // stco declares 2 entries but only 1 entry's bytes are present (followed by an
        // unrelated `free` box for padding). `pos + entry > start + len` must reject
        // the 2nd entry. `+ -> -` shrinks the bound and reads into the `free` box
        // instead of erroring (returns Ok).
        let mut stco = vec![0u8; 4]; // version/flags
        stco.extend_from_slice(&2u32.to_be_bytes()); // count = 2 (a lie)
        stco.extend_from_slice(&0u32.to_be_bytes()); // only 1 entry present
        let stbl = bx(
            b"stbl",
            &[bx(b"stco", &stco), bx(b"free", &[0u8; 8])].concat(),
        );
        let mut kept = bx(b"trak", &bx(b"mdia", &bx(b"minf", &stbl)));
        assert!(matches!(
            patch_chunk_offsets(&mut kept, 0),
            Err(FormatError::Malformed)
        ));
    }

    #[test]
    fn patch_chunk_offsets_co64_zero_offset_is_ok() {
        // co64 path guard is `v < 0`. offset 0 + delta 0 => v == 0 must be accepted;
        // `< -> ==`/`<= ` reject the boundary.
        let mut co64 = vec![0u8; 4]; // version/flags
        co64.extend_from_slice(&1u32.to_be_bytes()); // count 1
        co64.extend_from_slice(&0u64.to_be_bytes()); // offset 0
        let stbl = bx(b"stbl", &bx(b"co64", &co64));
        let mut kept = bx(b"trak", &bx(b"mdia", &bx(b"minf", &stbl)));
        assert!(patch_chunk_offsets(&mut kept, 0).is_ok());
    }

    /// Build a `----` freeform atom with an explicit data `type_code` and raw value.
    fn freeform_atom_typed(mean: &str, name: &str, type_code: u32, value: &[u8]) -> Vec<u8> {
        let mut mean_body = 0u32.to_be_bytes().to_vec();
        mean_body.extend_from_slice(mean.as_bytes());
        let mut name_body = 0u32.to_be_bytes().to_vec();
        name_body.extend_from_slice(name.as_bytes());
        let mut data_body = type_code.to_be_bytes().to_vec();
        data_body.extend_from_slice(&0u32.to_be_bytes()); // locale
        data_body.extend_from_slice(value);
        let mut inner = boxed(b"mean", &mean_body).unwrap();
        inner.extend(boxed(b"name", &name_body).unwrap());
        inner.extend(boxed(b"data", &data_body).unwrap());
        boxed(b"----", &inner).unwrap()
    }

    /// Wrap an `ilst` body in the moov/udta/meta/ilst boxes `ilst_region` expects.
    fn moov_with_ilst(ilst_body: &[u8]) -> Vec<u8> {
        let ilst = boxed(b"ilst", ilst_body).unwrap();
        let mut meta = 0u32.to_be_bytes().to_vec(); // FullBox version/flags
        meta.extend(boxed(b"hdlr", &[0u8; 25]).unwrap());
        meta.extend_from_slice(&ilst);
        let udta = boxed(b"udta", &boxed(b"meta", &meta).unwrap()).unwrap();
        boxed(b"moov", &udta).unwrap()
    }

    #[test]
    fn read_binary_tags_extracts_opaque_freeform_skips_text() {
        let serato = vec![0x00, 0xff, 0x10, 0x42, 0x99];
        let binary = freeform_atom_typed("com.serato.dj", "analysis", 0, &serato);
        let text = freeform_atom_typed("com.apple.iTunes", "MOOD", 1, b"calm");
        let moov = moov_with_ilst(&[binary, text].concat());

        let tags = read_binary_tags(&moov, usize::MAX);
        assert_eq!(tags.len(), 1, "only the binary `----` is opaque");
        assert_eq!(tags[0].key, "----:com.serato.dj:analysis");
        assert_eq!(tags[0].payload, serato);

        // The text `----` is the text path's job, never opaque.
        assert!(
            read_binary_tags(&moov, usize::MAX)
                .iter()
                .all(|t| t.key != "----:com.apple.iTunes:MOOD")
        );
    }

    #[test]
    fn read_binary_tags_handles_data_box_length_boundary() {
        // A `data` box shorter than the 8-byte `[type][locale]` header is malformed:
        // it must be skipped, never indexed into (no panic).
        let mut short_inner = boxed(b"mean", &{
            let mut b = 0u32.to_be_bytes().to_vec();
            b.extend_from_slice(b"com.serato.dj");
            b
        })
        .unwrap();
        short_inner.extend(
            boxed(b"name", &{
                let mut b = 0u32.to_be_bytes().to_vec();
                b.extend_from_slice(b"short");
                b
            })
            .unwrap(),
        );
        short_inner.extend(boxed(b"data", &[0u8; 5]).unwrap()); // 5 < 8: truncated header
        let short = boxed(b"----", &short_inner).unwrap();

        // A `data` box of exactly 8 bytes (binary type 0, no value) is well-formed
        // with an empty payload — it must be emitted, not skipped.
        let empty = freeform_atom_typed("com.serato.dj", "empty", 0, b"");
        let moov = moov_with_ilst(&[short, empty].concat());

        let tags = read_binary_tags(&moov, usize::MAX);
        assert_eq!(tags.len(), 1, "short data skipped, 8-byte data emitted");
        assert_eq!(tags[0].key, "----:com.serato.dj:empty");
        assert!(tags[0].payload.is_empty());
    }

    #[test]
    fn read_binary_tags_skips_payload_over_budget() {
        // A `----` value of 5 bytes with a budget of 4: skipped before any copy.
        let over = vec![0xABu8; 5];
        let atom = freeform_atom_typed("com.serato.dj", "analysis", 0, &over);
        let moov = moov_with_ilst(&atom);
        assert!(read_binary_tags(&moov, 4).is_empty());
    }

    #[test]
    fn read_binary_tags_accepts_payload_exactly_at_budget() {
        // Boundary: value length == budget is still extracted.
        let exact = vec![0xABu8; 4];
        let atom = freeform_atom_typed("com.serato.dj", "analysis", 0, &exact);
        let moov = moov_with_ilst(&atom);
        let tags = read_binary_tags(&moov, 4);
        assert_eq!(tags.len(), 1);
        assert_eq!(tags[0].payload, exact);
    }

    #[test]
    fn synthesize_interleaves_binary_freeform_segment() {
        let buf = mk_mp4(true, b"AUDIODATA", &[42, 100]);
        let scan = read_structure(&buf).unwrap();
        let payload = vec![0xde, 0xad, 0xbe, 0xef, 0x00, 0x01];
        let bins = vec![BinaryTagInput {
            key: "----:com.serato.dj:analysis".into(),
            payload_id: 7,
            len: BlobLen::new(payload.len() as u64).unwrap(),
        }];
        let layout = synthesize_layout(&scan, &[TagInput::new("title", "T")], &bins, &[]).unwrap();

        // Exactly one streamed BinaryTag carrying our handle + length.
        let bt: Vec<_> = layout
            .segments()
            .iter()
            .filter_map(|s| match s {
                Segment::BinaryTag { payload_id, len } => Some((*payload_id, len.get())),
                _ => None,
            })
            .collect();
        assert_eq!(bt, vec![(7, payload.len() as u64)]);

        // Audio is still served verbatim as the trailing BackingAudio run.
        match layout.segments().last().unwrap() {
            Segment::BackingAudio { offset, len } => {
                assert_eq!(*offset, scan.mdat_payload_offset);
                assert_eq!(*len, scan.mdat_payload_len);
            }
            _ => panic!("expected BackingAudio tail"),
        }

        // Box sizes are self-consistent: materialize the served file (binary payload
        // + backing audio substituted) and re-parse. `read_structure` validates every
        // moov/mdat box size, so a green re-parse proves the ----/ilst/meta/udta/moov
        // sizes all account for the streamed payload — and the opaque `----` survives
        // the round trip byte-identically.
        //
        // NOTE: do NOT use `inline_head`/`find_moov_in_head` here — the moov box now
        // spans multiple segments (the streamed BinaryTag splits it), so `read_box`
        // on `segments[0]` alone returns `Malformed`. Materialize the whole file.
        let mut served = Vec::new();
        for seg in layout.segments() {
            match seg {
                Segment::Inline(b) => served.extend_from_slice(b),
                Segment::BinaryTag { .. } => served.extend_from_slice(&payload),
                Segment::BackingAudio { offset, len } => {
                    let s = usize_from(*offset);
                    served.extend_from_slice(&buf[s..s + usize_from(*len)]);
                }
                other => panic!("unexpected segment: {other:?}"),
            }
        }
        read_structure(&served).expect("synthesized file re-parses to a valid moov/mdat");
        // `read_binary_tags` returns a bare Vec (no promotion for MP4) and emits the
        // raw `mean:name` key WITHOUT folding through the vocabulary — `com.serato.dj`
        // is not in any vocabulary entry, so the key is preserved verbatim.
        let reparsed = read_binary_tags(&served, usize::MAX);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].key, "----:com.serato.dj:analysis");
        assert_eq!(reparsed[0].payload, payload);
    }

    #[test]
    fn synthesize_new_moov_size_exactly_u32_max_is_ok() {
        // `if new_moov_size > u32::MAX` is strict. new_moov_size == u32::MAX must be
        // accepted; `> -> ==`/`>= ` reject the exact boundary. data_len (the art size)
        // is reserved as a number, so the boundary is cheap.
        fn art(data_len: u64) -> ArtInput {
            ArtInput {
                art_id: 1,
                mime: "image/jpeg".into(),
                description: String::new(),
                picture_type: PictureType::new(3).unwrap(),
                width: 0,
                height: 0,
                data_len: BlobLen::new(data_len).unwrap(),
            }
        }
        let buf = mk_mp4(true, b"AUDIO", &[0]);
        let scan = read_structure(&buf).unwrap();
        let tags = [TagInput::new("title", "T")];

        // Synthesize once with a 1-byte art. The head is [ftyp][moov], where the moov
        // box header declares new_moov_size = overhead + 1. The actual moov bytes in the
        // head are new_moov_size - 1 (the art is a separate ArtImage segment). So the
        // head length = ftyp.len() + (overhead + 1 - 1) = ftyp.len() + overhead.
        let layout1 = synthesize_layout(&scan, &tags, &[], &[art(1)]).unwrap();
        let head_len = inline_head(&layout1).len();
        let overhead = (head_len as u64) - (scan.ftyp.len() as u64);
        let max_len = u64::from(u32::MAX) - overhead;

        assert!(max_len > 0, "overhead {overhead} must be < u32::MAX");
        // Boundary accepted
        assert!(synthesize_layout(&scan, &tags, &[], &[art(max_len)]).is_ok());
        // Boundary+1 rejected
        assert!(matches!(
            synthesize_layout(&scan, &tags, &[], &[art(max_len + 1)]),
            Err(FormatError::TooLarge)
        ));
    }

    #[test]
    fn synthesize_layout_emits_all_nonzero_arts() {
        // Both non-empty arts stream, in input order.
        let art = |id: i64, len: u64| ArtInput {
            art_id: id,
            mime: "image/jpeg".into(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(len).unwrap(),
        };
        let buf = mk_mp4(true, b"AUDIO", &[0]);
        let scan = read_structure(&buf).unwrap();
        let layout = synthesize_layout(
            &scan,
            &[TagInput::new("title", "T")],
            &[],
            &[art(1, 5), art(3, 7)],
        )
        .unwrap();
        let art_segs: Vec<(i64, u64)> = layout
            .segments()
            .iter()
            .filter_map(|s| match s {
                Segment::ArtImage { art_id, len } => Some((*art_id, len.get())),
                _ => None,
            })
            .collect();
        assert_eq!(art_segs, vec![(1, 5), (3, 7)]);
    }

    #[test]
    fn read_structure_from_rejects_oversized_moov() {
        use std::io::Cursor;
        let moov_size: u32 = 600 * 1024 * 1024;
        let mut buf = Vec::new();
        buf.extend_from_slice(&16u32.to_be_bytes());
        buf.extend_from_slice(b"ftyp");
        buf.extend_from_slice(&[0u8; 8]);
        buf.extend_from_slice(&16u32.to_be_bytes());
        buf.extend_from_slice(b"mdat");
        buf.extend_from_slice(&[0u8; 8]);
        buf.extend_from_slice(&moov_size.to_be_bytes());
        buf.extend_from_slice(b"moov");
        assert_eq!(buf.len(), 40);
        let file_len = 32 + u64::from(moov_size);
        let mut cur = Cursor::new(buf);
        match read_structure_from(&mut cur, file_len).unwrap_err() {
            Mp4ScanError::MetadataTooLarge {
                box_kind,
                size,
                cap,
            } => {
                assert_eq!(box_kind, "moov");
                assert_eq!(size, u64::from(moov_size));
                assert_eq!(cap, 256 * 1024 * 1024);
            }
            other => panic!("expected MetadataTooLarge, got {other:?}"),
        }
    }

    #[test]
    fn read_structure_from_admits_box_at_exactly_the_cap() {
        use std::io::Cursor;
        let cap: u32 = 256 * 1024 * 1024;
        let mut buf = Vec::new();
        buf.extend_from_slice(&16u32.to_be_bytes());
        buf.extend_from_slice(b"ftyp");
        buf.extend_from_slice(&[0u8; 8]);
        buf.extend_from_slice(&16u32.to_be_bytes());
        buf.extend_from_slice(b"mdat");
        buf.extend_from_slice(&[0u8; 8]);
        buf.extend_from_slice(&cap.to_be_bytes());
        buf.extend_from_slice(b"moov");
        let file_len = 32 + u64::from(cap);
        let mut cur = Cursor::new(buf);
        let err = read_structure_from(&mut cur, file_len).unwrap_err();
        assert!(
            matches!(err, Mp4ScanError::Io(_)),
            "exact-cap box must pass the strict `>` guard (got {err:?})"
        );
    }

    #[test]
    fn build_udta_checked_art_len_rejects_overflow() {
        // A hostile art data_len near u64::MAX must fail closed with TooLarge at
        // the covr_size fold, not panic (debug) / wrap (release).
        let mk = |data_len: u64| crate::input::ArtInput {
            art_id: 1,
            mime: "image/png".to_string(),
            description: String::new(),
            picture_type: PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: BlobLen::new(data_len).unwrap(),
        };
        assert_eq!(
            build_udta(&[], &[], &[mk(u64::MAX)]).err(),
            Some(FormatError::TooLarge)
        );
    }

    #[test]
    fn build_udta_checked_binary_tag_len_rejects_overflow() {
        // A hostile freeform binary-tag len near u64::MAX must fail closed with
        // TooLarge inside freeform_binary_prefix's data_size/inner_len arithmetic,
        // not panic (debug) / wrap (release) before the u32 box-size narrowing.
        let bins = vec![crate::input::BinaryTagInput {
            key: "----:com.example:x".to_string(),
            payload_id: 1,
            len: BlobLen::new(u64::MAX).unwrap(),
        }];
        assert_eq!(
            build_udta(&[], &bins, &[]).err(),
            Some(FormatError::TooLarge)
        );
    }

    #[test]
    fn freeform_binary_prefix_checked_outer_box_size_rejects_overflow() {
        // A payload_len that slips past the data_size and inner_len checks can
        // still overflow the outer `8 + inner_len` box-size add. With 1-char
        // mean/name each boxed mean/name is 13 bytes, so inner_len = 26 + data_size
        // = 42 + payload_len; payload_len = u64::MAX - 42 drives inner_len to exactly
        // u64::MAX, so the outer add must fail closed, not panic (debug) / wrap (release).
        assert_eq!(
            freeform_binary_prefix("m", "n", u64::MAX - 42).err(),
            Some(FormatError::TooLarge)
        );
    }
}