musefs-format 1.2.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
mod art_source;
mod b64;
mod crc;
mod page;

pub use art_source::{ArtSource, MapArtSource};

pub use b64::{B64Window, b64_len, b64_len_checked, b64_window, encode_b64_slice};
pub use page::{
    PageHeader, parse_page, patch_page_header, patch_page_header_algebraic, verify_page_crc,
};

use crate::error::{FormatError, Result};
use crate::probe::Extent;
use crate::size;

/// The codec carried inside an Ogg logical bitstream that we synthesize.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Codec {
    Opus,
    Vorbis,
    OggFlac,
}

const METADATA_BLOCK_PICTURE_KEY: &[u8] = b"METADATA_BLOCK_PICTURE=";

fn detect_codec(first_packet: &[u8]) -> Result<Codec> {
    if first_packet.len() >= 8 && &first_packet[0..8] == b"OpusHead" {
        Ok(Codec::Opus)
    } else if first_packet.len() >= 7 && &first_packet[0..7] == b"\x01vorbis" {
        Ok(Codec::Vorbis)
    } else if first_packet.len() >= 5 && &first_packet[0..5] == b"\x7FFLAC" {
        Ok(Codec::OggFlac)
    } else {
        Err(FormatError::Malformed)
    }
}

/// For OggFLAC, packet 0 is `0x7F "FLAC" major minor count(2, BE) "fLaC" STREAMINFO`.
/// The 16-bit big-endian count is the number of metadata-block packets that follow
/// packet 0.
fn oggflac_following_packets(first_packet: &[u8]) -> Result<usize> {
    if first_packet.len() < 9 {
        return Err(FormatError::Malformed);
    }
    Ok(u16::from_be_bytes([first_packet[7], first_packet[8]]) as usize)
}

/// The parsed Ogg header region: codec, serial, the reassembled header packets,
/// the number of header pages, and where audio begins.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OggHeader {
    pub codec: Codec,
    pub serial: u32,
    pub packets: Vec<Vec<u8>>,
    pub header_pages: u32,
    pub audio_offset: u64,
}

/// Reject multiplexed/chained Ogg: within the header region every page must share
/// the first page's serial and only the first page may carry BOS.
fn validate_single_bitstream(data: &[u8], audio_offset: u64, serial: u32) -> Result<()> {
    let mut pos = 0usize;
    let mut first = true;
    while (pos as u64) < audio_offset {
        let h = crate::ogg::page::parse_page(data, pos)?;
        if h.serial != serial {
            return Err(FormatError::Malformed);
        }
        if !first && (h.header_type & crate::ogg::page::FLAG_BOS) != 0 {
            return Err(FormatError::Malformed);
        }
        first = false;
        pos += h.total_len();
    }
    Ok(())
}

/// Parse the header region from the front of a logical bitstream. `data` may be the
/// whole file or just `[0, audio_offset)`; either way parsing stops once all header
/// packets are reassembled.
pub fn read_header(data: &[u8]) -> Result<OggHeader> {
    let first_page = page::parse_page(data, 0)?;
    let serial = first_page.serial;

    // Reassemble the first packet to detect the codec and (for OggFLAC) the count.
    let first = page::read_packets(data, 1)?;
    let first_pkt = first.first().ok_or(FormatError::Malformed)?;
    let codec = detect_codec(&first_pkt.data)?;

    let want = match codec {
        Codec::Opus => 2,
        Codec::Vorbis => 3,
        Codec::OggFlac => 1 + oggflac_following_packets(&first_pkt.data)?,
    };

    let pkts = page::read_packets(data, want)?;
    if pkts.len() != want {
        return Err(FormatError::Malformed);
    }
    let last = pkts.last().unwrap();
    let audio_offset = last.end_offset as u64;
    validate_single_bitstream(data, audio_offset, serial)?;
    Ok(OggHeader {
        codec,
        serial,
        packets: pkts.iter().map(|p| p.data.clone()).collect(),
        header_pages: last.pages_through_end,
        audio_offset,
    })
}

/// Strip a codec's comment-packet prefix, returning the VorbisComment body slice.
fn comment_body(codec: Codec, packet: &[u8]) -> Result<&[u8]> {
    let prefix = match codec {
        Codec::Opus => 8,    // "OpusTags"
        Codec::Vorbis => 7,  // 0x03 "vorbis"
        Codec::OggFlac => 4, // FLAC metadata block header (type + 24-bit length)
    };
    if packet.len() < prefix {
        return Err(FormatError::Malformed);
    }
    Ok(&packet[prefix..])
}

/// The index of the comment packet within the reassembled header packets.
fn comment_packet_index(header: &OggHeader) -> usize {
    match header.codec {
        Codec::Opus | Codec::Vorbis => 1,
        // OggFLAC: packet 0 is the mapping header; the VORBIS_COMMENT block is
        // whichever following packet has block type 4.
        Codec::OggFlac => header
            .packets
            .iter()
            .enumerate()
            .skip(1)
            .find(|(_, p)| !p.is_empty() && (p[0] & 0x7F) == 4)
            .map_or(0, |(i, _)| i),
    }
}

/// Read existing `(FIELD, value)` tags from a complete file. Empty if none.
pub fn read_tags(data: &[u8]) -> Result<Vec<(String, String)>> {
    let header = read_header(data)?;
    let idx = comment_packet_index(&header);
    if idx == 0 {
        return Ok(Vec::new()); // no comment packet present
    }
    let body = comment_body(header.codec, &header.packets[idx])?;
    let mut tags = crate::vorbiscomment::parse(body)?;
    // Cover art rides in the comment as a base64 METADATA_BLOCK_PICTURE entry, but
    // it has its own channel (read_pictures). Excluding it keeps read_tags
    // text-only and prevents the art being stored — and re-synthesized — twice.
    tags.retain(|(field, _)| !field.eq_ignore_ascii_case("METADATA_BLOCK_PICTURE"));
    Ok(tags)
}

use crate::input::EmbeddedPicture;

/// Extract embedded pictures from a complete file for scan-time ingestion.
///
/// Opus/Vorbis carry art as a base64 `METADATA_BLOCK_PICTURE` comment whose decoded
/// bytes are a FLAC PICTURE block body; OggFLAC carries native PICTURE block
/// packets (block type 6). Plan 1 only *reads* art (to seed the DB); synthesis does
/// not yet re-embed it.
pub fn read_pictures(data: &[u8]) -> Result<Vec<EmbeddedPicture>> {
    use base64::Engine;
    let header = read_header(data)?;
    let mut out = Vec::new();
    match header.codec {
        Codec::Opus | Codec::Vorbis => {
            let idx = comment_packet_index(&header);
            if idx == 0 {
                return Ok(out);
            }
            let body = comment_body(header.codec, &header.packets[idx])?;
            for (field, value) in crate::vorbiscomment::parse(body)? {
                if field.eq_ignore_ascii_case("METADATA_BLOCK_PICTURE") {
                    let raw = base64::engine::general_purpose::STANDARD
                        .decode(value.as_bytes())
                        .map_err(|_| FormatError::Malformed)?;
                    out.push(crate::flac::parse_picture_block(&raw)?);
                }
            }
        }
        Codec::OggFlac => {
            for pkt in header.packets.iter().skip(1) {
                // `pkt.len() >= 4` guards the `&pkt[4..]` slice: the packet length is
                // attacker-controlled, so a 1-3 byte type-6 packet must not panic.
                if pkt.len() >= 4 && (pkt[0] & 0x7F) == 6 {
                    // Strip the 4-byte FLAC metadata block header.
                    out.push(crate::flac::parse_picture_block(&pkt[4..])?);
                }
            }
        }
    }
    Ok(out)
}

/// Audio bounds + codec from a complete file, for the scanner.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OggScan {
    pub codec: Codec,
    pub audio_offset: u64,
    pub audio_length: u64,
}

pub fn locate_audio(data: &[u8]) -> Result<OggScan> {
    let header = read_header(data)?;
    if header.audio_offset > data.len() as u64 {
        return Err(FormatError::Malformed);
    }
    Ok(OggScan {
        codec: header.codec,
        audio_offset: header.audio_offset,
        audio_length: data.len() as u64 - header.audio_offset,
    })
}

/// The header region parsed from the front of the file (`[0, audio_offset)`), for
/// synthesis. Identical to `read_header` but named to mirror `flac::read_metadata`.
pub fn read_metadata(front: &[u8]) -> Result<OggHeader> {
    read_header(front)
}

/// Bounded twin of [`read_metadata`]. OGG header packets (and all OGG embedded
/// art) are front-anchored, so a prefix covering the header region is sufficient.
/// `read_header` does not expose an exact byte need, so on a short/truncated
/// prefix this geometrically grows the window (doubling, capped at `file_len`):
/// header regions are tiny, so the first 1 MiB window almost always completes,
/// and the cap guarantees the worst case equals reading the whole file.
pub fn read_metadata_bounded(prefix: &[u8], file_len: u64) -> Result<Extent<OggHeader>> {
    match read_header(prefix) {
        Ok(header) => Ok(Extent::Complete(header)),
        // `read_header` cannot distinguish a truncated front from genuine
        // corruption, so we widen optimistically; a real error resurfaces via the
        // `Err(e)` arm once `prefix` reaches `file_len` (and the caller's retry
        // limit + full-read fallback bound the cost).
        Err(_) if (prefix.len() as u64) < file_len => {
            let grown = ((prefix.len() as u64).saturating_mul(2)).max(64 * 1024);
            Ok(Extent::NeedMore {
                up_to: grown.min(file_len),
            })
        }
        Err(e) => Err(e),
    }
}

use crate::input::TagInput;
use crate::layout::{RegionLayout, Segment};

pub fn synthesize_layout(
    header: &OggHeader,
    audio_offset: u64,
    audio_length: u64,
    tags: &[TagInput],
    arts: &[OggArt],
    src: &dyn ArtSource,
) -> Result<RegionLayout> {
    let arts: Vec<OggArt> = arts.to_vec();
    let packet_chunks = build_packets_with_art(header, tags, &arts)?;
    let mut segments: Vec<Segment> = Vec::new();
    let mut seq = 0u32;
    for (i, chunks) in packet_chunks.iter().enumerate() {
        let (segs, used) =
            crate::ogg::page::lace_chunks_to_segments(header.serial, seq, i == 0, chunks, src)?;
        segments.extend(segs);
        seq += used;
    }
    let seq_delta = i64::from(seq) - i64::from(header.header_pages);
    segments.push(Segment::OggAudio {
        offset: audio_offset,
        len: audio_length,
        seq_delta,
    });
    Ok(RegionLayout::validated(segments)?)
}

/// Build the FLAC PICTURE block *body prefix* (everything before the image data:
/// type, mime, description, dimensions, depth, colors, data-length) for `art`,
/// padding the description with spaces so the prefix length is a multiple of 3.
/// This makes `base64(prefix ++ image) == base64(prefix) ++ base64(image)`, so the
/// image's base64 is an independent substring that can be served incrementally.
/// The declared data-length field is the true image length (`art.data_len`).
///
/// The actual byte layout is shared with the plain FLAC write path via
/// [`crate::flac::picture_body_framing`]; only the description padding is unique here.
fn picture_prefix(art: &crate::input::ArtInput) -> Result<Vec<u8>> {
    // Unpadded prefix length = 4(type)+4(mimelen)+mime +4(desclen)+desc
    //   +4(w)+4(h)+4(depth)+4(colors)+4(datalen) = 32 + mime + desc.
    let base = 32 + art.mime.len() + art.description.len();
    let pad = (3 - base % 3) % 3;
    let description = format!("{}{}", art.description, " ".repeat(pad));
    crate::flac::picture_body_framing(art, &description)
}

use crate::ogg::page::PayloadChunk;
use base64::Engine;

/// One image to embed: its metadata. Bytes are read from an `ArtSource` only to
/// compute page CRCs at synthesis time; they are never retained in the layout.
#[derive(Clone, Copy)]
pub struct OggArt<'a> {
    pub meta: &'a crate::input::ArtInput,
}

fn b64_encode(bytes: &[u8]) -> Vec<u8> {
    base64::engine::general_purpose::STANDARD
        .encode(bytes)
        .into_bytes()
}

/// Build the regenerated header packets as chunk lists, embedding `arts`.
/// Opus/Vorbis: art goes into the comment packet as `METADATA_BLOCK_PICTURE`
/// comments (last). OggFLAC: each art is a native PICTURE block packet.
fn build_packets_with_art(
    header: &OggHeader,
    tags: &[TagInput],
    arts: &[OggArt],
) -> Result<Vec<Vec<PayloadChunk>>> {
    match header.codec {
        Codec::Opus | Codec::Vorbis => {
            // VorbisComment value length is a 32-bit field; guard against overflow
            // for absurdly large images (cover art is far below this). The full
            // value includes the key, base64 of the picture prefix, and base64 of
            // the image; any one of these alone may fit in u32 but the sum may not.
            for a in arts {
                let prefix = picture_prefix(a.meta)?;
                let b64_prefix_len =
                    b64_len_checked(prefix.len() as u64).ok_or(FormatError::TooLarge)?;
                let b64_image_len =
                    b64_len_checked(a.meta.data_len.get()).ok_or(FormatError::TooLarge)?;
                let value_len = size::checked_sum([
                    METADATA_BLOCK_PICTURE_KEY.len() as u64,
                    b64_prefix_len,
                    b64_image_len,
                ])?;
                if value_len > u64::from(u32::MAX) {
                    return Err(FormatError::TooLarge);
                }
            }
            if header.codec == Codec::Opus {
                Ok(vec![
                    vec![PayloadChunk::Bytes(header.packets[0].clone())],
                    comment_packet_chunks(b"OpusTags", tags, arts, false)?,
                ])
            } else {
                Ok(vec![
                    vec![PayloadChunk::Bytes(header.packets[0].clone())],
                    comment_packet_chunks(b"\x03vorbis", tags, arts, true)?,
                    vec![PayloadChunk::Bytes(header.packets[2].clone())],
                ])
            }
        }
        Codec::OggFlac => oggflac_packets_with_art(header, tags, arts),
    }
}

/// Build a VorbisComment-style comment packet (Opus `OpusTags` / Vorbis
/// `0x03vorbis`) as chunks: a leading `Bytes` chunk (magic + vendor + count + text
/// comments + each art comment's framing and base64(prefix)), an `Art` chunk per
/// image (base64 of the image), and — for Vorbis — a trailing framing-bit `Bytes`
/// chunk.
fn comment_packet_chunks(
    magic: &[u8],
    tags: &[TagInput],
    arts: &[OggArt],
    framing_bit: bool,
) -> Result<Vec<PayloadChunk>> {
    let text_body = crate::vorbiscomment::build(tags)?; // vendor + count(text) + text comments
    let vendor_len = u32::from_le_bytes(text_body[0..4].try_into().unwrap()) as usize;
    let count_pos = 4 + vendor_len;
    let text_count = u32::from_le_bytes(text_body[count_pos..count_pos + 4].try_into().unwrap());
    let mut leading = text_body.clone();
    let new_count = text_count + u32::try_from(arts.len()).map_err(|_| FormatError::TooLarge)?;
    leading[count_pos..count_pos + 4].copy_from_slice(&new_count.to_le_bytes());

    let mut chunks: Vec<PayloadChunk> = Vec::new();
    let mut head = magic.to_vec();
    head.extend_from_slice(&leading);

    for art in arts {
        let prefix = picture_prefix(art.meta)?;
        let b64_prefix = b64_encode(&prefix);
        let b64_image_len =
            b64_len_checked(art.meta.data_len.get()).ok_or(FormatError::TooLarge)?;
        let value_len = size::checked_sum([
            METADATA_BLOCK_PICTURE_KEY.len() as u64,
            b64_prefix.len() as u64,
            b64_image_len,
        ])?;
        head.extend_from_slice(
            &u32::try_from(value_len)
                .map_err(|_| FormatError::TooLarge)?
                .to_le_bytes(),
        );
        head.extend_from_slice(METADATA_BLOCK_PICTURE_KEY);
        head.extend_from_slice(&b64_prefix);
        chunks.push(PayloadChunk::Bytes(std::mem::take(&mut head)));
        chunks.push(PayloadChunk::Art {
            art_id: art.meta.art_id,
            base64: true,
            art_total: art.meta.data_len.get(),
        });
    }
    if framing_bit {
        head.push(0x01);
    }
    if !head.is_empty() {
        chunks.push(PayloadChunk::Bytes(head));
    }
    Ok(chunks)
}

/// OggFLAC header packets with art: the text comment packet (no art) plus one
/// native PICTURE block packet per image. The last metadata-block packet carries
/// the last-block flag, and packet 0's 16-bit following-packet count is recomputed.
fn oggflac_packets_with_art(
    header: &OggHeader,
    tags: &[TagInput],
    arts: &[OggArt],
) -> Result<Vec<Vec<PayloadChunk>>> {
    if header.packets.is_empty() {
        return Err(FormatError::Malformed);
    }
    let mut structural: Vec<Vec<u8>> = Vec::new();
    for pkt in header.packets.iter().skip(1) {
        if !pkt.is_empty() && matches!(pkt[0] & 0x7F, 2 | 3 | 5) {
            structural.push(pkt.clone());
        }
    }

    let vc = crate::vorbiscomment::build(tags)?;
    if vc.len() as u64 > crate::flac::MAX_BLOCK_BODY {
        return Err(FormatError::TooLarge);
    }
    let mut comment = Vec::new();
    crate::flac::push_block_header(&mut comment, 4, vc.len(), false)?;
    comment.extend_from_slice(&vc);

    let following_count = structural.len() + 1 + arts.len();
    let count = u16::try_from(following_count).map_err(|_| FormatError::TooLarge)?;

    let mut block_packets: Vec<Vec<PayloadChunk>> = Vec::new();
    for s in &structural {
        block_packets.push(vec![PayloadChunk::Bytes(s.clone())]);
    }
    block_packets.push(vec![PayloadChunk::Bytes(comment)]);
    for art in arts {
        let prefix = picture_prefix(art.meta)?;
        let body_len = size::checked_add(prefix.len() as u64, art.meta.data_len.get())?;
        if body_len > crate::flac::MAX_BLOCK_BODY {
            return Err(FormatError::TooLarge);
        }
        let mut blk = Vec::new();
        crate::flac::push_block_header(&mut blk, 6, crate::convert::usize_from(body_len), false)?;
        blk.extend_from_slice(&prefix);
        block_packets.push(vec![
            PayloadChunk::Bytes(blk),
            PayloadChunk::Art {
                art_id: art.meta.art_id,
                base64: false,
                art_total: art.meta.data_len.get(),
            },
        ]);
    }

    let n = block_packets.len();
    for (i, bp) in block_packets.iter_mut().enumerate() {
        if let Some(PayloadChunk::Bytes(b)) = bp.first_mut() {
            if i + 1 == n {
                b[0] |= 0x80;
            } else {
                b[0] &= 0x7F;
            }
        }
    }

    let mut mapping = header.packets[0].clone();
    if mapping.len() < 9 {
        return Err(FormatError::Malformed);
    }
    mapping[7..9].copy_from_slice(&count.to_be_bytes());

    let mut out = vec![vec![PayloadChunk::Bytes(mapping)]];
    out.extend(block_packets);
    Ok(out)
}

#[doc(hidden)]
pub mod page_test_support {
    pub use crate::ogg::page::{build_header as build_header_pub, lace_packet as lace_packet_pub};

    /// An empty VorbisComment body (vendor + zero comments), for fixtures.
    pub fn vorbis_body_empty() -> Vec<u8> {
        crate::vorbiscomment::build(&[]).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ogg::page::{build_header, lace_packet};

    fn opus_headers() -> Vec<u8> {
        let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".to_vec();
        let tags = b"OpusTags\x06\x00\x00\x00musefs\x00\x00\x00\x00".to_vec();
        let (bytes, _) = build_header(0x1234, &[&head, &tags]);
        bytes
    }

    #[test]
    fn locate_audio_reports_bounds() {
        let mut data = opus_headers();
        let header_len = data.len();
        let (audio, _) = crate::ogg::page::lace_packet(0x1234, 2, false, 960, &[0u8; 120]);
        data.extend_from_slice(&audio);

        let scan = locate_audio(&data).unwrap();
        assert_eq!(scan.codec, Codec::Opus);
        assert_eq!(scan.audio_offset, header_len as u64);
        assert_eq!(scan.audio_length, (data.len() - header_len) as u64);
    }

    #[test]
    fn reads_opus_header() {
        let mut data = opus_headers();
        // Append one audio page so audio_offset lands before EOF.
        let (audio, _) = lace_packet(0x1234, 2, false, 960, &[0u8; 100]);
        let header_len = data.len();
        data.extend_from_slice(&audio);

        let h = read_header(&data).unwrap();
        assert_eq!(h.codec, Codec::Opus);
        assert_eq!(h.serial, 0x1234);
        assert_eq!(h.packets.len(), 2);
        assert_eq!(h.audio_offset, header_len as u64);
        assert_eq!(h.header_pages, 2);
    }

    #[test]
    fn oggflac_following_packets_accepts_minimal_9_byte_packet() {
        // The 16-bit count lives in bytes [7],[8], so a 9-byte first packet is the
        // minimum valid input (`len < 9` rejects anything shorter). `<=` would
        // wrongly reject this exact-length packet.
        let mut pkt = [0u8; 9];
        pkt[7] = 0x00;
        pkt[8] = 0x03; // 3 following metadata-block packets
        assert_eq!(oggflac_following_packets(&pkt).unwrap(), 3);
    }

    #[test]
    fn comment_body_accepts_packet_with_empty_body() {
        // A packet exactly `prefix` bytes long has an empty (but valid) comment
        // body: `&packet[prefix..]` is the empty slice. `len < prefix` rejects only
        // shorter packets; `<=` would wrongly reject this one. Opus prefix = 8.
        assert!(comment_body(Codec::Opus, b"OpusTags").unwrap().is_empty());
    }

    #[test]
    fn read_tags_opus() {
        // Build an OpusTags packet with one real comment via the shared builder.
        let body =
            crate::vorbiscomment::build(&[crate::input::TagInput::new("title", "Sun")]).unwrap();
        let mut tags_pkt = b"OpusTags".to_vec();
        tags_pkt.extend_from_slice(&body);
        let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".to_vec();
        let (mut data, _) = crate::ogg::page::build_header(7, &[&head, &tags_pkt]);
        let (audio, _) = crate::ogg::page::lace_packet(7, 2, false, 960, &[0u8; 50]);
        data.extend_from_slice(&audio);

        let tags = read_tags(&data).unwrap();
        assert_eq!(tags, vec![("title".to_string(), "Sun".to_string())]);
    }

    #[test]
    fn read_tags_excludes_metadata_block_picture() {
        // A METADATA_BLOCK_PICTURE comment whose value is a base64 FLAC picture
        // block carrying a 1-byte image, plus one ordinary text tag.
        let mut block = Vec::new();
        block.extend_from_slice(&3u32.to_be_bytes()); // picture type: front cover
        block.extend_from_slice(&9u32.to_be_bytes());
        block.extend_from_slice(b"image/png");
        block.extend_from_slice(&0u32.to_be_bytes()); // description length
        block.extend_from_slice(&1u32.to_be_bytes()); // width
        block.extend_from_slice(&1u32.to_be_bytes()); // height
        block.extend_from_slice(&8u32.to_be_bytes()); // depth
        block.extend_from_slice(&0u32.to_be_bytes()); // colors used
        block.extend_from_slice(&1u32.to_be_bytes()); // image length
        block.push(0xAB);
        let pic_value = base64::engine::general_purpose::STANDARD.encode(&block);

        let body = crate::vorbiscomment::build(&[
            crate::input::TagInput::new("title", "Sun"),
            crate::input::TagInput::new("METADATA_BLOCK_PICTURE", &pic_value),
        ])
        .unwrap();
        let mut tags_pkt = b"OpusTags".to_vec();
        tags_pkt.extend_from_slice(&body);
        let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".to_vec();
        let (mut data, _) = crate::ogg::page::build_header(7, &[&head, &tags_pkt]);
        let (audio, _) = crate::ogg::page::lace_packet(7, 2, false, 960, &[0u8; 50]);
        data.extend_from_slice(&audio);

        // read_tags returns only the text tag — the picture comment is excluded...
        let tags = read_tags(&data).unwrap();
        assert_eq!(tags, vec![("title".to_string(), "Sun".to_string())]);
        // ...while read_pictures still finds the embedded art.
        let pics = read_pictures(&data).unwrap();
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].data, vec![0xAB]);
    }

    #[test]
    fn synthesize_opus_emits_valid_header_and_audio_segment() {
        let mut data = opus_headers();
        let scan = locate_audio({
            let (audio, _) = crate::ogg::page::lace_packet(0x1234, 2, false, 960, &[0u8; 80]);
            data.extend_from_slice(&audio);
            &data
        })
        .unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("album", "Geogaddi")],
            &[],
            &MapArtSource::default(),
        )
        .unwrap();

        // Collect all Inline header bytes (one per page) until OggAudio.
        let mut header_bytes: Vec<u8> = Vec::new();
        let mut audio_seg = None;
        for seg in layout.segments() {
            match seg {
                Segment::Inline(b) => header_bytes.extend_from_slice(b),
                Segment::OggAudio { offset, len, .. } => {
                    audio_seg = Some((*offset, *len));
                    break;
                }
                other => panic!("unexpected segment {other:?}"),
            }
        }
        let h = read_header(&header_bytes).unwrap();
        assert_eq!(h.codec, Codec::Opus);
        let body = comment_body(Codec::Opus, &h.packets[1]).unwrap();
        let tags = crate::vorbiscomment::parse(body).unwrap();
        assert_eq!(tags, vec![("album".to_string(), "Geogaddi".to_string())]);
        let (offset, len) = audio_seg.expect("expected OggAudio segment");
        assert_eq!(offset, scan.audio_offset);
        assert_eq!(len, scan.audio_length);
    }

    #[test]
    fn synthesize_emits_nonzero_seq_delta_when_header_page_count_changes() {
        // seq_delta = synthesized_page_count - original_header_pages. When the
        // original header spanned a different number of pages than the regenerated
        // one, the delta is non-zero — pins the subtraction at the OggAudio segment.
        let mut data = opus_headers();
        let (audio, _) = crate::ogg::page::lace_packet(0x1234, 2, false, 960, &[0u8; 80]);
        data.extend_from_slice(&audio);
        let scan = locate_audio(&data).unwrap();
        let mut header =
            read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        // Synthesis re-lays the Opus header into a known page count; record it.
        let baseline = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[],
            &[],
            &MapArtSource::default(),
        )
        .unwrap();
        let synth_pages = baseline
            .segments()
            .iter()
            .filter(|s| matches!(s, Segment::Inline(_)))
            .count();
        assert!(synth_pages >= 1);

        // Pretend the ORIGINAL header spanned three extra pages, so the served audio
        // pages must be renumbered downward by exactly three.
        let original_pages = u32::try_from(synth_pages).unwrap() + 3;
        header.header_pages = original_pages;
        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[],
            &[],
            &MapArtSource::default(),
        )
        .unwrap();
        let delta = layout
            .segments()
            .iter()
            .find_map(|s| match s {
                Segment::OggAudio { seq_delta, .. } => Some(*seq_delta),
                _ => None,
            })
            .expect("expected an OggAudio segment");
        assert_eq!(
            delta,
            i64::try_from(synth_pages).unwrap() - i64::from(original_pages),
            "seq_delta must be synthesized pages minus original header pages"
        );
        assert_eq!(delta, -3);
    }

    fn vorbis_headers_with(setup: &[u8]) -> Vec<u8> {
        // Minimal-but-shaped Vorbis ID header (30 bytes from 0x01"vorbis").
        let mut id = b"\x01vorbis".to_vec();
        id.extend_from_slice(&0u32.to_le_bytes()); // version
        id.push(2); // channels
        id.extend_from_slice(&44100u32.to_le_bytes()); // sample rate
        id.extend_from_slice(&0u32.to_le_bytes()); // bitrate max
        id.extend_from_slice(&128_000u32.to_le_bytes()); // nominal
        id.extend_from_slice(&0u32.to_le_bytes()); // min
        id.push(0xB8); // blocksizes
        id.push(0x01); // framing bit
        let mut comment = b"\x03vorbis".to_vec();
        comment.extend_from_slice(&crate::vorbiscomment::build(&[]).unwrap());
        comment.push(0x01);
        let (bytes, _) = crate::ogg::page::build_header(55, &[&id, &comment, setup]);
        bytes
    }

    #[test]
    fn synthesize_vorbis_preserves_setup_and_rewrites_comment() {
        let setup = b"\x05vorbis-SETUP-CODEBOOKS-PLACEHOLDER".to_vec();
        let mut data = vorbis_headers_with(&setup);
        let (audio, _) = crate::ogg::page::lace_packet(55, 99, false, 1024, &[0u8; 64]);
        data.extend_from_slice(&audio);

        let scan = locate_audio(&data).unwrap();
        assert_eq!(scan.codec, Codec::Vorbis);
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();
        // The original setup packet (3rd header packet) must be carried through.
        assert_eq!(header.packets[2], setup);

        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("artist", "Autechre")],
            &[],
            &MapArtSource::default(),
        )
        .unwrap();

        let mut header_bytes: Vec<u8> = Vec::new();
        for seg in layout.segments() {
            match seg {
                Segment::Inline(b) => header_bytes.extend_from_slice(b),
                Segment::OggAudio { .. } => break,
                other => panic!("unexpected segment {other:?}"),
            }
        }
        let h = read_header(&header_bytes).unwrap();
        assert_eq!(h.codec, Codec::Vorbis);
        assert_eq!(h.packets[2], setup); // setup preserved byte-for-byte
        let body = comment_body(Codec::Vorbis, &h.packets[1]).unwrap();
        let tags = crate::vorbiscomment::parse(body).unwrap();
        assert_eq!(tags, vec![("artist".to_string(), "Autechre".to_string())]);
    }

    #[test]
    fn read_pictures_opus_decodes_metadata_block_picture() {
        use base64::Engine;
        // A minimal FLAC PICTURE block body: type=3, mime="image/png", empty desc,
        // 1x1, depth 0, colors 0, data="PNG".
        let mut pic = Vec::new();
        pic.extend_from_slice(&3u32.to_be_bytes());
        let mime = b"image/png";
        pic.extend_from_slice(&u32::try_from(mime.len()).unwrap().to_be_bytes());
        pic.extend_from_slice(mime);
        pic.extend_from_slice(&0u32.to_be_bytes()); // desc len
        pic.extend_from_slice(&1u32.to_be_bytes()); // width
        pic.extend_from_slice(&1u32.to_be_bytes()); // height
        pic.extend_from_slice(&0u32.to_be_bytes()); // depth
        pic.extend_from_slice(&0u32.to_be_bytes()); // colors
        let img = b"PNG";
        pic.extend_from_slice(&u32::try_from(img.len()).unwrap().to_be_bytes());
        pic.extend_from_slice(img);
        let b64 = base64::engine::general_purpose::STANDARD.encode(&pic);

        let mut body = Vec::new();
        body.extend_from_slice(
            &u32::try_from(crate::vorbiscomment::VENDOR.len())
                .unwrap()
                .to_le_bytes(),
        );
        body.extend_from_slice(crate::vorbiscomment::VENDOR.as_bytes());
        body.extend_from_slice(&1u32.to_le_bytes()); // one comment
        let comment = format!("METADATA_BLOCK_PICTURE={b64}");
        body.extend_from_slice(&u32::try_from(comment.len()).unwrap().to_le_bytes());
        body.extend_from_slice(comment.as_bytes());

        let mut tags_pkt = b"OpusTags".to_vec();
        tags_pkt.extend_from_slice(&body);
        let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".to_vec();
        let (mut data, _) = crate::ogg::page::build_header(7, &[&head, &tags_pkt]);
        let (audio, _) = crate::ogg::page::lace_packet(7, 2, false, 960, &[0u8; 50]);
        data.extend_from_slice(&audio);

        let pics = read_pictures(&data).unwrap();
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].mime, "image/png");
        assert_eq!(pics[0].data, b"PNG");
    }

    #[test]
    fn read_pictures_oggflac_short_picture_packet_does_not_panic() {
        // Crafted OggFLAC: a structurally-valid mapping header declaring one
        // following packet, where that packet is a 1-byte type-6 (PICTURE) block —
        // too short for the 4-byte FLAC metadata block header. The `&pkt[4..]`
        // slice must not panic (issue #365).
        let mut mapping = vec![0x7F];
        mapping.extend_from_slice(b"FLAC");
        mapping.push(1);
        mapping.push(0);
        mapping.extend_from_slice(&1u16.to_be_bytes()); // one following packet
        mapping.extend_from_slice(b"fLaC");
        let mut streaminfo = Vec::new();
        crate::flac::push_block_header(&mut streaminfo, 0, 34, false).unwrap();
        streaminfo.extend(std::iter::repeat_n(0u8, 34));
        mapping.extend_from_slice(&streaminfo);

        // One lacing byte yields this 1-byte packet: block type 6, no body.
        let short_picture = vec![0x06u8];

        let (data, _) = crate::ogg::page::build_header(77, &[&mapping, &short_picture]);

        // Sanity: the header parses, so we actually reach the picture loop.
        assert_eq!(read_header(&data).unwrap().codec, Codec::OggFlac);
        assert!(read_pictures(&data).unwrap().is_empty());
    }

    fn oggflac_headers() -> Vec<u8> {
        // STREAMINFO block (type 0): 4-byte header + 34-byte body (zeros are fine
        // for our framing test).
        let mut streaminfo = Vec::new();
        crate::flac::push_block_header(&mut streaminfo, 0, 34, false).unwrap();
        streaminfo.extend(std::iter::repeat_n(0u8, 34));

        // Mapping header packet: 0x7F "FLAC" v1.0 count "fLaC" STREAMINFO.
        let mut mapping = vec![0x7F];
        mapping.extend_from_slice(b"FLAC");
        mapping.push(1);
        mapping.push(0);
        mapping.extend_from_slice(&2u16.to_be_bytes()); // count: SEEKTABLE + VORBIS_COMMENT
        mapping.extend_from_slice(b"fLaC");
        mapping.extend_from_slice(&streaminfo);

        // A SEEKTABLE block (type 3, structural — must be preserved).
        let mut seektable = Vec::new();
        crate::flac::push_block_header(&mut seektable, 3, 18, false).unwrap();
        seektable.extend(std::iter::repeat_n(0xEEu8, 18));

        // An existing VORBIS_COMMENT (type 4, last) to be replaced.
        let mut old_vc = Vec::new();
        let body = crate::vorbiscomment::build(&[crate::input::TagInput::new("x", "old")]).unwrap();
        crate::flac::push_block_header(&mut old_vc, 4, body.len(), true).unwrap();
        old_vc.extend_from_slice(&body);

        let (bytes, _) = crate::ogg::page::build_header(77, &[&mapping, &seektable, &old_vc]);
        bytes
    }

    #[test]
    fn rejects_multiplexed_second_bitstream() {
        // Two BOS pages with DIFFERENT serials at the start => multiplexed; must reject.
        let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".to_vec();
        let (mut data, _) = crate::ogg::page::lace_packet(0x1111, 0, true, 0, &head);
        // A second logical stream's BOS page (different serial).
        let (other, _) = crate::ogg::page::lace_packet(
            0x2222,
            0,
            true,
            0,
            b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".as_ref(),
        );
        data.extend_from_slice(&other);
        // Some audio after, so audio_offset (if it were accepted) is past these pages.
        let (audio, _) = crate::ogg::page::lace_packet(0x1111, 1, false, 960, &[0u8; 50]);
        data.extend_from_slice(&audio);
        assert!(read_header(&data).is_err());
        assert!(locate_audio(&data).is_err());
    }

    #[test]
    fn synthesize_oggflac_keeps_seektable_replaces_comment_and_count() {
        let mut data = oggflac_headers();
        let (audio, _) = crate::ogg::page::lace_packet(77, 3, false, 4096, &[0u8; 64]);
        data.extend_from_slice(&audio);

        let scan = locate_audio(&data).unwrap();
        assert_eq!(scan.codec, Codec::OggFlac);
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("title", "Kaini Industries")],
            &[],
            &MapArtSource::default(),
        )
        .unwrap();

        let mut header_bytes: Vec<u8> = Vec::new();
        for seg in layout.segments() {
            match seg {
                Segment::Inline(b) => header_bytes.extend_from_slice(b),
                Segment::OggAudio { .. } => break,
                other => panic!("unexpected segment {other:?}"),
            }
        }
        let h = read_header(&header_bytes).unwrap();
        assert_eq!(h.codec, Codec::OggFlac);
        // packet 0 mapping count == number of following blocks (SEEKTABLE + VC == 2)
        assert_eq!(u16::from_be_bytes([h.packets[0][7], h.packets[0][8]]), 2);
        // SEEKTABLE preserved
        assert!(h.packets.iter().skip(1).any(|p| (p[0] & 0x7F) == 3));
        // exactly one VORBIS_COMMENT, with the new tag, flagged last
        let vc = h
            .packets
            .iter()
            .skip(1)
            .find(|p| (p[0] & 0x7F) == 4)
            .unwrap();
        assert_eq!(vc[0] & 0x80, 0x80);
        let tags = crate::vorbiscomment::parse(&vc[4..]).unwrap();
        assert_eq!(
            tags,
            vec![("title".to_string(), "Kaini Industries".to_string())]
        );
    }

    #[test]
    fn synthesize_opus_embeds_art_that_round_trips() {
        let mut data = opus_headers();
        let (audio, _) = crate::ogg::page::lace_packet(0x1234, 2, false, 960, &[0u8; 80]);
        data.extend_from_slice(&audio);
        let scan = locate_audio(&data).unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let image: Vec<u8> = (0..5000u32).map(|i| (i % 251) as u8).collect();
        let meta = crate::input::ArtInput {
            art_id: 7,
            mime: "image/jpeg".to_string(),
            description: String::new(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 64,
            height: 64,
            data_len: crate::input::BlobLen::new(image.len() as u64).unwrap(),
        };
        let src = MapArtSource::new([(meta.art_id, image.clone())]);
        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("title", "Cover")],
            &[OggArt { meta: &meta }],
            &src,
        )
        .unwrap();

        // Materialize the header region from the layout, expanding OggArtSlice by
        // re-deriving its bytes from `image` (mirrors what read_at does).
        let mut bytes = Vec::new();
        for s in layout.segments() {
            match s {
                Segment::Inline(b) => bytes.extend_from_slice(b),
                Segment::OggArtSlice {
                    offset,
                    len,
                    base64,
                    art_total,
                    ..
                } => {
                    assert!(*base64);
                    let w = b64_window(*offset, len.get(), *art_total);
                    let raw = &image[crate::convert::usize_from(w.in_start)
                        ..crate::convert::usize_from(w.in_start + w.in_len)];
                    bytes.extend_from_slice(
                        &encode_b64_slice(raw, w.skip, crate::convert::usize_from(len.get()))
                            .expect("window lies within the encoded output"),
                    );
                }
                Segment::OggAudio { .. } => break, // header region ends here
                other => panic!("unexpected {other:?}"),
            }
        }

        let pics = read_pictures(&bytes).unwrap();
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].mime, "image/jpeg");
        assert_eq!(pics[0].data, image);
        let h = read_header(&bytes).unwrap();
        assert_eq!(h.codec, Codec::Opus);
    }

    // Materialize the header region of a synthesized layout into bytes, expanding
    // each OggArtSlice from `images` (art_id -> raw image), mirroring read_at.
    fn materialize_header(layout: &RegionLayout, images: &[(i64, &[u8])]) -> Vec<u8> {
        let mut bytes = Vec::new();
        for s in layout.segments() {
            match s {
                Segment::Inline(b) => bytes.extend_from_slice(b),
                Segment::OggArtSlice {
                    art_id,
                    offset,
                    len,
                    base64,
                    art_total,
                } => {
                    let img = images.iter().find(|(id, _)| id == art_id).expect("image").1;
                    if *base64 {
                        let w = b64_window(*offset, len.get(), *art_total);
                        let raw = &img[crate::convert::usize_from(w.in_start)
                            ..crate::convert::usize_from(w.in_start + w.in_len)];
                        bytes.extend_from_slice(
                            &encode_b64_slice(raw, w.skip, crate::convert::usize_from(len.get()))
                                .expect("window lies within the encoded output"),
                        );
                    } else {
                        bytes.extend_from_slice(
                            &img[crate::convert::usize_from(*offset)
                                ..crate::convert::usize_from(*offset + len.get())],
                        );
                    }
                }
                Segment::OggAudio { .. } => break,
                other => panic!("unexpected {other:?}"),
            }
        }
        bytes
    }

    fn art_input(art_id: i64, mime: &str, len: usize) -> crate::input::ArtInput {
        crate::input::ArtInput {
            art_id,
            mime: mime.to_string(),
            description: String::new(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 10,
            height: 10,
            data_len: crate::input::BlobLen::new(len as u64).unwrap(),
        }
    }

    #[test]
    fn synthesize_vorbis_embeds_art_that_round_trips() {
        let setup = b"\x05vorbis-SETUP".to_vec();
        let mut data = vorbis_headers_with(&setup);
        let (audio, _) = crate::ogg::page::lace_packet(55, 99, false, 1024, &[0u8; 64]);
        data.extend_from_slice(&audio);
        let scan = locate_audio(&data).unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let image: Vec<u8> = (0..4000u32).map(|i| (i % 251) as u8).collect();
        let meta = art_input(11, "image/png", image.len());
        let src = MapArtSource::new([(meta.art_id, image.clone())]);
        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("artist", "X")],
            &[OggArt { meta: &meta }],
            &src,
        )
        .unwrap();

        let bytes = materialize_header(&layout, &[(11, &image)]);
        let h = read_header(&bytes).unwrap();
        assert_eq!(h.codec, Codec::Vorbis);
        assert_eq!(h.packets[2], setup); // setup preserved
        let pics = read_pictures(&bytes).unwrap();
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].data, image);
    }

    #[test]
    fn synthesize_oggflac_embeds_art_that_round_trips() {
        let mut data = oggflac_headers();
        let (audio, _) = crate::ogg::page::lace_packet(77, 3, false, 4096, &[0u8; 64]);
        data.extend_from_slice(&audio);
        let scan = locate_audio(&data).unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let image: Vec<u8> = (0..4000u32).map(|i| (i % 251) as u8).collect();
        let meta = art_input(22, "image/png", image.len());
        let src = MapArtSource::new([(meta.art_id, image.clone())]);
        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("title", "Y")],
            &[OggArt { meta: &meta }],
            &src,
        )
        .unwrap();

        let bytes = materialize_header(&layout, &[(22, &image)]);
        let h = read_header(&bytes).unwrap();
        assert_eq!(h.codec, Codec::OggFlac);
        let pics = read_pictures(&bytes).unwrap();
        assert_eq!(pics.len(), 1);
        assert_eq!(pics[0].data, image);
    }

    #[test]
    fn synthesize_oggflac_embeds_large_art_spanning_pages_round_trips() {
        // A >64 KiB raw PICTURE block forces the art run across multiple pages,
        // exercising the non-base64 streaming-CRC path at page boundaries (the
        // base64 path is covered by the lacer test; this pins the raw path).
        let mut data = oggflac_headers();
        let (audio, _) = crate::ogg::page::lace_packet(77, 3, false, 4096, &[0u8; 64]);
        data.extend_from_slice(&audio);
        let scan = locate_audio(&data).unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let image: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();
        let meta = art_input(31, "image/png", image.len());
        let src = MapArtSource::new([(meta.art_id, image.clone())]);
        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("title", "Big")],
            &[OggArt { meta: &meta }],
            &src,
        )
        .unwrap();

        // The art run must split across pages: more than one raw OggArtSlice.
        let art_slices = layout
            .segments()
            .iter()
            .filter(|s| matches!(s, Segment::OggArtSlice { base64: false, .. }))
            .count();
        assert!(
            art_slices >= 2,
            "expected the raw art to span multiple pages, got {art_slices} slice(s)"
        );

        let bytes = materialize_header(&layout, &[(31, &image)]);
        let h = read_header(&bytes).unwrap();
        assert_eq!(h.codec, Codec::OggFlac);
        let pics = read_pictures(&bytes).unwrap();
        assert_eq!(pics.len(), 1);
        assert_eq!(
            pics[0].data, image,
            "large art must round-trip byte-for-byte"
        );
    }

    #[test]
    fn synthesize_opus_embeds_multiple_images() {
        let mut data = opus_headers();
        let (audio, _) = crate::ogg::page::lace_packet(0x1234, 2, false, 960, &[0u8; 64]);
        data.extend_from_slice(&audio);
        let scan = locate_audio(&data).unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let img_a: Vec<u8> = (0..3000u32).map(|i| (i % 251) as u8).collect();
        let img_b: Vec<u8> = (0..1500u32).map(|i| ((i * 3) % 251) as u8).collect();
        let meta_a = art_input(1, "image/png", img_a.len());
        let meta_b = art_input(2, "image/jpeg", img_b.len());
        let src = MapArtSource::new([
            (meta_a.art_id, img_a.clone()),
            (meta_b.art_id, img_b.clone()),
        ]);
        let layout = synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[TagInput::new("title", "Multi")],
            &[OggArt { meta: &meta_a }, OggArt { meta: &meta_b }],
            &src,
        )
        .unwrap();

        let bytes = materialize_header(&layout, &[(1, &img_a), (2, &img_b)]);
        let h = read_header(&bytes).unwrap();
        assert_eq!(h.codec, Codec::Opus);
        let pics = read_pictures(&bytes).unwrap();
        assert_eq!(pics.len(), 2);
        assert_eq!(pics[0].data, img_a);
        assert_eq!(pics[1].data, img_b);
    }

    #[test]
    fn oversized_full_art_value_rejected_by_build_packets() {
        let meta = crate::input::ArtInput {
            art_id: 0,
            mime: "image/jpeg".to_string(),
            description: String::new(),
            data_len: crate::input::BlobLen::new(u64::from(u32::MAX)).unwrap(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
        };
        let art = OggArt { meta: &meta };
        let header = OggHeader {
            codec: Codec::Vorbis,
            serial: 0,
            packets: vec![vec![], vec![], vec![]],
            header_pages: 1,
            audio_offset: 0,
        };
        let result = build_packets_with_art(&header, &[], &[art]);
        assert!(result.is_err(), "expected Err for oversized art");
    }

    #[test]
    fn sum_overflow_art_value_rejected_by_build_packets() {
        // data_len and prefix individually fit in u32, but the full value
        // (key + b64(prefix) + b64(data)) exceeds u32::MAX.
        let meta = crate::input::ArtInput {
            art_id: 0,
            mime: "image/png".to_string(),
            description: "x".repeat(256),
            data_len: crate::input::BlobLen::new(3_221_225_470).unwrap(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
        };
        let art = OggArt { meta: &meta };
        let header = OggHeader {
            codec: Codec::Vorbis,
            serial: 0,
            packets: vec![vec![], vec![], vec![]],
            header_pages: 1,
            audio_offset: 0,
        };
        let result = build_packets_with_art(&header, &[], &[art]);
        assert!(
            result.is_err(),
            "expected Err when key + b64(prefix) + b64(data) overflows u32"
        );
    }

    #[test]
    fn art_value_at_u32_max_boundary_is_accepted_by_build_packets() {
        // Pin the exact `value_len > u32::MAX` boundary: with mime "image/png" and
        // an empty description, key(23) + b64(prefix=42)=56 + b64(data_len) lands on
        // u32::MAX EXACTLY when data_len == 3_221_225_412. A correct `>` admits it
        // (the downstream u32 length field still fits); `>=`/`==` or a `*`-mutated
        // sum would wrongly reject it. The declared 3 GiB image is never
        // materialized (image bytes are empty), so the build is cheap.
        let meta = crate::input::ArtInput {
            art_id: 0,
            mime: "image/png".to_string(),
            description: String::new(),
            data_len: crate::input::BlobLen::new(3_221_225_412).unwrap(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
        };
        let art = OggArt { meta: &meta };
        let header = OggHeader {
            codec: Codec::Vorbis,
            serial: 0,
            packets: vec![vec![], vec![], vec![]],
            header_pages: 1,
            audio_offset: 0,
        };
        let accepted = build_packets_with_art(&header, &[], &[art]).is_ok();
        assert!(
            accepted,
            "value_len exactly u32::MAX must be accepted by build_packets_with_art"
        );
    }

    #[test]
    fn near_u64_max_art_value_rejected_by_build_packets() {
        // data_len near u64::MAX makes b64_len(data_len) overflow u64; the builder
        // must fail closed with TooLarge at the checked b64 length, not panic
        // (debug) inside the pre-flight value_len computation.
        let meta = crate::input::ArtInput {
            art_id: 0,
            mime: "image/jpeg".to_string(),
            description: String::new(),
            data_len: crate::input::BlobLen::new(u64::MAX).unwrap(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
        };
        let art = OggArt { meta: &meta };
        let header = OggHeader {
            codec: Codec::Vorbis,
            serial: 0,
            packets: vec![vec![], vec![], vec![]],
            header_pages: 1,
            audio_offset: 0,
        };
        let result = build_packets_with_art(&header, &[], &[art]);
        let is_too_large = matches!(&result, Err(FormatError::TooLarge));
        assert!(is_too_large, "expected Err(TooLarge) for near-u64::MAX art");
    }

    #[test]
    fn near_u64_max_art_value_rejected_by_oggflac_build_packets() {
        // The Ogg-FLAC art path builds a METADATA_BLOCK_PICTURE body as
        // prefix + raw image. A hostile data_len near u64::MAX must fail closed
        // with TooLarge, not panic (debug) / wrap (release). picture_prefix's u32
        // length field already rejects it; the checked add keeps the body-length
        // site self-defending regardless of that ordering.
        let meta = crate::input::ArtInput {
            art_id: 0,
            mime: "image/jpeg".to_string(),
            description: String::new(),
            data_len: crate::input::BlobLen::new(u64::MAX).unwrap(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
        };
        let art = OggArt { meta: &meta };
        let header = OggHeader {
            codec: Codec::OggFlac,
            serial: 0,
            packets: vec![vec![0x7F]],
            header_pages: 1,
            audio_offset: 0,
        };
        let result = build_packets_with_art(&header, &[], &[art]);
        let is_too_large = matches!(&result, Err(FormatError::TooLarge));
        assert!(is_too_large, "expected Err(TooLarge) for near-u64::MAX art");
    }

    #[test]
    fn picture_prefix_is_3_aligned_and_declares_image_len() {
        let art = crate::input::ArtInput {
            art_id: 1,
            mime: "image/png".to_string(), // 9 -> base = 32+9+0 = 41 -> pad 1
            description: String::new(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 1,
            height: 1,
            data_len: crate::input::BlobLen::new(12345).unwrap(),
        };
        let p = picture_prefix(&art).unwrap();
        assert_eq!(p.len() % 3, 0);
        // datalen is the last 4 bytes (big-endian) and equals the true image length.
        let dl = u32::from_be_bytes(p[p.len() - 4..].try_into().unwrap());
        assert_eq!(dl, 12345);
        // Reusing the existing FLAC picture parser proves the framing is valid:
        // parse_picture_block expects the body (prefix + image); append dummy image.
        let mut body = p.clone();
        body.extend(std::iter::repeat_n(0u8, 12345));
        let pic = crate::flac::parse_picture_block(&body).unwrap();
        assert_eq!(pic.mime, "image/png");
        assert_eq!(pic.picture_type.get(), 3);
    }

    #[test]
    fn detect_codec_matches_each_magic_and_rejects_others() {
        assert_eq!(detect_codec(b"OpusHead........").unwrap(), Codec::Opus);
        assert_eq!(detect_codec(b"\x01vorbis...").unwrap(), Codec::Vorbis);
        assert_eq!(detect_codec(b"\x7FFLAC...").unwrap(), Codec::OggFlac);
        // Too-short and non-matching inputs must error (kills the :25 && -> || and
        // the length-guard mutations).
        assert!(detect_codec(b"OpusHea").is_err()); // 7 bytes, len guard
        assert!(detect_codec(b"XXXXXXXX").is_err()); // right length, wrong magic
        assert!(detect_codec(b"\x01vorbi").is_err()); // 6 bytes
    }

    #[test]
    fn comment_body_strips_each_codec_prefix_and_guards_length() {
        assert_eq!(comment_body(Codec::Opus, b"OpusTagsBODY").unwrap(), b"BODY");
        assert_eq!(
            comment_body(Codec::Vorbis, b"\x03vorbisBODY").unwrap(),
            b"BODY"
        );
        assert_eq!(
            comment_body(Codec::OggFlac, b"\x04\x00\x00\x00BODY").unwrap(),
            b"BODY"
        );
        // packet shorter than the prefix errors (kills :113 < -> ==/<=).
        assert!(comment_body(Codec::Opus, b"OpusTa").is_err());
        assert!(comment_body(Codec::OggFlac, b"\x04\x00\x00").is_err());
    }

    #[test]
    fn oggflac_following_packets_reads_be_count_and_guards_length() {
        // 0x7F"FLAC" major minor count(BE) ... ; count bytes at [7],[8].
        let pkt = b"\x7FFLAC\x01\x00\x00\x05rest";
        assert_eq!(oggflac_following_packets(pkt).unwrap(), 5);
        assert!(oggflac_following_packets(b"\x7FFLAC\x01\x00").is_err()); // 7 bytes (<9)
    }

    #[test]
    fn oggflac_comment_block_size_boundary_is_inclusive() {
        // The regenerated OggFLAC VORBIS_COMMENT block shares FLAC's 24-bit
        // block length. Derive the non-value overhead from production, then
        // size the value so the body lands exactly on the limit; one more byte
        // errors. The `>` accepts the inclusive limit; the `>=` mutant rejects.
        let header = OggHeader {
            codec: Codec::OggFlac,
            serial: 1,
            packets: vec![vec![0x7F; 9]],
            header_pages: 1,
            audio_offset: 0,
        };
        let overhead = crate::vorbiscomment::build(&[crate::input::TagInput::new("title", "")])
            .unwrap()
            .len() as u64;
        let at_limit = "x".repeat(crate::convert::usize_from(
            crate::flac::MAX_BLOCK_BODY - overhead,
        ));
        let tags = [crate::input::TagInput::new("title", at_limit.as_str())];
        assert!(oggflac_packets_with_art(&header, &tags, &[]).is_ok());
        // one byte over must still error, pinning the high side of the boundary.
        let over = format!("{at_limit}x");
        let tags = [crate::input::TagInput::new("title", over.as_str())];
        assert!(matches!(
            oggflac_packets_with_art(&header, &tags, &[]),
            Err(FormatError::TooLarge)
        ));
    }

    #[test]
    fn oggflac_picture_block_size_boundary_is_inclusive() {
        // body_len = picture_prefix(meta).len() + data_len; the guard shares
        // FLAC's 24-bit block limit. data_len is only a count (image bytes are
        // streamed), so the exact boundary is cheap to pin. The `>` accepts the
        // inclusive limit — which also pins the `+` assembly, since a product
        // of the two terms overshoots it — while the `>=` mutant rejects it.
        let header = OggHeader {
            codec: Codec::OggFlac,
            serial: 1,
            packets: vec![vec![0x7F; 9]],
            header_pages: 1,
            audio_offset: 0,
        };
        let mk = |data_len: u64| crate::input::ArtInput {
            art_id: 1,
            mime: "image/png".to_string(),
            description: String::new(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: crate::input::BlobLen::new(data_len).unwrap(),
        };
        let framing_len = picture_prefix(&mk(1)).unwrap().len() as u64;
        let at_limit = mk(crate::flac::MAX_BLOCK_BODY - framing_len);
        let arts = [OggArt { meta: &at_limit }];
        assert!(oggflac_packets_with_art(&header, &[], &arts).is_ok());
        // one byte over must still error, pinning the high side of the boundary.
        let over = mk(crate::flac::MAX_BLOCK_BODY - framing_len + 1);
        let arts = [OggArt { meta: &over }];
        assert!(matches!(
            oggflac_packets_with_art(&header, &[], &arts),
            Err(FormatError::TooLarge)
        ));
    }

    #[test]
    fn comment_packet_index_locates_the_comment_block() {
        // Opus/Vorbis: always packet index 1 (kills :121 -> 1 only if a non-1 case
        // exists; assert OggFLAC search to pin the skip(1)+find logic at :130).
        let opus = OggHeader {
            codec: Codec::Opus,
            serial: 1,
            packets: vec![vec![], vec![]],
            header_pages: 1,
            audio_offset: 0,
        };
        assert_eq!(comment_packet_index(&opus), 1);

        // OggFLAC: packet 0 mapping, packet 1 type 1 (non-comment), packet 2 type 4.
        let oggflac = OggHeader {
            codec: Codec::OggFlac,
            serial: 1,
            packets: vec![vec![0x7F], vec![0x01], vec![0x84]], // 0x84 & 0x7F == 4
            header_pages: 1,
            audio_offset: 0,
        };
        assert_eq!(comment_packet_index(&oggflac), 2);
        // No type-4 block -> 0 (kills the bitmask / == mutations at :130).
        let none = OggHeader {
            codec: Codec::OggFlac,
            serial: 1,
            packets: vec![vec![0x7F], vec![0x01], vec![0x05]],
            header_pages: 1,
            audio_offset: 0,
        };
        assert_eq!(comment_packet_index(&none), 0);
    }

    #[test]
    fn locate_audio_accepts_empty_audio_region() {
        // opus_headers() is header pages only: audio_offset == data.len(). The
        // original `>` yields Ok (audio_length 0); the :196 `==`/`>=` mutants reject.
        let file = opus_headers();
        let scan = locate_audio(&file).unwrap();
        assert_eq!(scan.codec, Codec::Opus);
        assert_eq!(scan.audio_offset, file.len() as u64);
        assert_eq!(scan.audio_length, 0);
    }

    #[test]
    fn picture_prefix_declared_desc_len_pins_padding() {
        let art = crate::input::ArtInput {
            art_id: 1,
            mime: "image/png".into(), // 9
            description: "x".into(),  // 1 -> base = 42, 42 % 3 == 0 -> pad 0
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 1,
            height: 1,
            data_len: crate::input::BlobLen::new(100).unwrap(),
        };
        let prefix = picture_prefix(&art).unwrap();
        assert_eq!(prefix.len() % 3, 0);
        // Declared description length lives at offset 8 + mime.len() (after
        // type[4] + mimelen[4] + mime). pad = declared - desc.len() must be 0..=2.
        let off = 8 + art.mime.len();
        let declared = u32::from_be_bytes(prefix[off..off + 4].try_into().unwrap());
        let pad = declared - u32::try_from(art.description.len()).unwrap();
        assert!(pad <= 2, "pad must be 0..=2, got {pad}");
        assert_eq!(pad, 0, "base % 3 == 0 implies pad 0");
    }

    #[test]
    fn synthesis_reads_art_in_page_bounded_windows() {
        use std::cell::Cell;
        struct Counting<'a> {
            inner: MapArtSource,
            max: &'a Cell<usize>,
        }
        impl ArtSource for Counting<'_> {
            fn read_window(&self, art_id: i64, offset: u64, buf: &mut [u8]) -> crate::Result<()> {
                self.max.set(self.max.get().max(buf.len()));
                self.inner.read_window(art_id, offset, buf)
            }
        }

        // Inline Opus fixture, mirroring synthesize_opus_emits_valid_header_and_audio_segment.
        let mut data = opus_headers();
        let scan = locate_audio({
            let (audio, _) = crate::ogg::page::lace_packet(0x1234, 2, false, 960, &[0u8; 80]);
            data.extend_from_slice(&audio);
            &data
        })
        .unwrap();
        let header = read_metadata(&data[..crate::convert::usize_from(scan.audio_offset)]).unwrap();

        let image: Vec<u8> = (0..500_000u32).map(|i| (i % 251) as u8).collect();
        let meta = crate::input::ArtInput {
            art_id: 7,
            mime: "image/jpeg".to_string(),
            description: String::new(),
            picture_type: crate::input::PictureType::new(3).unwrap(),
            width: 0,
            height: 0,
            data_len: crate::input::BlobLen::new(image.len() as u64).unwrap(),
        };
        let max = Cell::new(0usize);
        let src = Counting {
            inner: MapArtSource::new([(7i64, image.clone())]),
            max: &max,
        };
        synthesize_layout(
            &header,
            scan.audio_offset,
            scan.audio_length,
            &[],
            &[OggArt { meta: &meta }],
            &src,
        )
        .unwrap();
        // One Ogg page's payload is at most 255*255 = 65025 bytes; raw windows are
        // <= that. The 500 KB image is never read in a single call.
        assert!(
            max.get() > 0 && max.get() <= 65_025,
            "max single read was {}",
            max.get()
        );
    }
}

#[cfg(test)]
mod page_test_support_tests {
    /// Pins the fixture's contract: a parseable VorbisComment with zero
    /// comments. Consumers (musefs-core's ogg tests) splice it into OpusTags
    /// packets, but only format-local tests can kill mutations of it — the
    /// mutation gate runs each crate's own suite.
    #[test]
    fn vorbis_body_empty_is_a_parseable_empty_comment() {
        let body = super::page_test_support::vorbis_body_empty();
        let parsed = crate::vorbiscomment::parse(&body).unwrap();
        assert!(parsed.is_empty());
    }
}

#[cfg(test)]
mod bounded_tests {
    use super::*;
    use crate::ogg::page_test_support::{build_header_pub, lace_packet_pub, vorbis_body_empty};

    /// A minimal Opus stream: OpusHead + OpusTags header packets, then a trailing
    /// audio page. Returns (full, audio_offset). Mirrors the proven fixture in
    /// `musefs-core/src/scan.rs::ogg_probe_tests::probe_detects_opus_and_seeds_tags`.
    /// `build_header_pub(serial, &[&[u8]])` laces *all* header packets across
    /// pages (BOS set once) and returns `(Vec<u8>, u32)`; `lace_packet_pub` takes
    /// `(serial, seq_start, bos, granule, packet)` and returns `(Vec<u8>, u32)`.
    fn opus_stream() -> (Vec<u8>, u64) {
        let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00".to_vec();
        let mut tags = b"OpusTags".to_vec();
        tags.extend_from_slice(&vorbis_body_empty());
        let serial = 0x1234;
        let (mut v, _) = build_header_pub(serial, &[&head, &tags]);
        let audio_offset = v.len() as u64;
        let (audio, _) = lace_packet_pub(serial, 2, false, 960, &[0u8; 100]);
        v.extend_from_slice(&audio);
        (v, audio_offset)
    }

    #[test]
    fn read_metadata_bounded_complete_when_prefix_covers_header() {
        let (full, audio_offset) = opus_stream();
        let file_len = full.len() as u64;
        let prefix = &full[..crate::convert::usize_from(audio_offset)]; // exactly the header region
        match read_metadata_bounded(prefix, file_len).unwrap() {
            Extent::Complete(h) => assert_eq!(h.audio_offset, audio_offset),
            other @ Extent::NeedMore { .. } => panic!("expected Complete, got {other:?}"),
        }
    }

    #[test]
    fn read_metadata_bounded_needmore_when_header_truncated() {
        let (full, _audio_offset) = opus_stream();
        let file_len = full.len() as u64;
        let prefix = &full[..20]; // mid first page
        match read_metadata_bounded(prefix, file_len).unwrap() {
            Extent::NeedMore { up_to } => assert!(up_to > 20 && up_to <= file_len),
            other @ Extent::Complete(_) => panic!("expected NeedMore, got {other:?}"),
        }
    }

    #[test]
    fn read_metadata_bounded_errors_when_whole_file_is_unparseable() {
        // A short garbage buffer that IS the whole file: prefix.len() == file_len and
        // read_header errors. The guard `(prefix.len() as u64) < file_len` is FALSE,
        // so the function must fall to the `Err(e)` arm and return Err — never grow.
        let bad: &[u8] = b"not an ogg stream at all"; // capture pattern != "OggS"
        // Confirm the premise: read_header genuinely errors on this buffer.
        assert!(read_header(bad).is_err());
        let len = bad.len() as u64;
        // kills ogg L226 guard `< file_len` -> `true`: under `true` this returns
        // NeedMore; correct is Err.
        // kills ogg L226 `<` -> `<=`: `len <= len` is true -> NeedMore; correct is Err.
        match read_metadata_bounded(bad, len) {
            Err(_) => {}
            Ok(other) => panic!("expected Err when whole file unparseable, got {other:?}"),
        }
    }

    #[test]
    fn read_metadata_bounded_doubles_window_exactly() {
        // L = 100_000 bytes of garbage (read_header errors): L > 64*1024 so `.max`
        // does not mask, and file_len = 10_000_000 > L*2 so `.min` does not clamp.
        // Correct up_to = L*2 = 200_000. `+`->100_002, `/`->50_000 all differ.
        let buf = vec![0u8; 100_000]; // all zeros: capture pattern != "OggS" -> errors
        // Confirm the premise: read_header genuinely errors on this buffer.
        assert!(read_header(&buf).is_err());
        let file_len = 10_000_000u64;
        match read_metadata_bounded(&buf, file_len).unwrap() {
            Extent::NeedMore { up_to } => assert_eq!(up_to, 200_000),
            other @ Extent::Complete(_) => panic!("expected NeedMore, got {other:?}"),
        }
    }

    #[test]
    fn read_metadata_bounded_floor_is_64kib_for_small_prefix() {
        // The `*` at L227 col 74 is the `64 * 1024` FLOOR in `.max(64 * 1024)`,
        // not the doubling. To exercise it the floor must bind: a tiny prefix whose
        // doubled length (200) is below 64 KiB, with file_len well above 64 KiB so
        // `.min(file_len)` doesn't clamp. Correct floor = 65_536.
        let buf = vec![0u8; 100]; // garbage: read_header errors
        assert!(read_header(&buf).is_err());
        let file_len = 10_000_000u64;
        // kills ogg L227 `64 * 1024` -> `64 + 1024` (=1088) and `64 / 1024` (=0):
        // only `*` yields the 65_536 floor when the doubled length is smaller.
        match read_metadata_bounded(&buf, file_len).unwrap() {
            Extent::NeedMore { up_to } => assert_eq!(up_to, 65_536),
            other @ Extent::Complete(_) => panic!("expected NeedMore, got {other:?}"),
        }
    }

    #[test]
    fn read_metadata_bounded_grows_when_truncated_prefix_shorter_than_file() {
        // Pins the TRUE side of the guard: a truncated valid-prefix where
        // prefix.len() < file_len must return NeedMore (kills `<`->`<=` from the
        // other direction by requiring growth here while requiring Err when equal).
        let (full, _audio_offset) = opus_stream();
        let file_len = full.len() as u64;
        let prefix = &full[..10]; // far short of the header region
        assert!(read_header(prefix).is_err());
        match read_metadata_bounded(prefix, file_len).unwrap() {
            Extent::NeedMore { up_to } => assert!(up_to > prefix.len() as u64),
            other @ Extent::Complete(_) => panic!("expected NeedMore, got {other:?}"),
        }
    }
}