sharkyflac 0.2.0

A pure rust FLAC decoder and encoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
// TODO: rewrite parsers to use `BitReader` properly

use bitflags::bitflags;
use byteorder::{BE, LE, ReadBytesExt, WriteBytesExt};
use std::io;
use std::io::{Read, Seek};
use std::num::{NonZero, NonZeroU32};
use std::ops::Deref;
use strum::Display;

use crate::ascii_str::{self, ArrayList, AsciiArray, AsciiStr};
use crate::bit_io::{BitRead, BitReader, BitWrite};
use crate::bits::Bitset;
use crate::num::*;
use crate::{Decode, Encode};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("IO: {0}")]
    Io(#[from] io::Error),

    #[error("The metadata block type is 127, which is forbidden")]
    ForbiddenBlockType,

    #[error("Block size {1} is invalid for block type {0}")]
    InvalidBlockSize(BlockType, U24),

    #[error("A reserved block type was used")]
    ReservedBlockType,

    #[error("The picture's type is reserved")]
    ReservedPictureType,

    #[error(
        "{0} is not contained within the valid range `4..=32`: The streaminfo block indicated an invalid bits_per_channel"
    )]
    InvalidBitsPerSample(U5),

    #[error("{0} is an invalid maximum block size")]
    InvalidMaxBlockSize(u16),

    #[error("{0} is an invalid minimum block size")]
    InvalidMinBlockSize(u16),

    #[error("{0}")]
    InvalidUtf8String(#[from] std::string::FromUtf8Error),

    #[error("{0}")]
    InvalidUtf8(#[from] std::str::Utf8Error),

    #[error("{0}")]
    ParseInt(#[from] std::num::ParseIntError),

    #[error("Invalid vorbis comment")]
    InvalidVorbisComment,

    #[error("Vorbis comment key contains invalid ASCII")]
    CommentKeyNotAscii,

    #[error("Invalid cuesheet")]
    InvalidCuesheet,

    #[error("Invalid cuesheet track")]
    InvalidCuesheetTrack,

    #[error("Invalid cuesheet track index points")]
    InvalidCuesheetIndexPoints,

    #[error("Invalid cuesheet track index point")]
    InvalidCuesheetIndexPoint,

    #[error("Invalid channel mask")]
    InvalidChannelMask,

    #[error("Non-ASCII ISRC in cuesheet track")]
    NonAscii(#[from] ascii_str::NonAscii),

    #[error("The lengths coded within the metadata block exceed the block length")]
    BlockExceededLength,

    #[error("The vendor string is too long for a vorbis comment block")]
    VendorTooLong,

    #[error("The number of user comments is too long for a vorbis comment block")]
    UserCommentsTooLong,

    #[error("The user comment string is too long for a vorbis comment block")]
    UserComment,

    #[error("There are too many cuesheet tracks (must be less than u8::MAX)")]
    CuesheetTrackCount,

    #[error("Picture description is too large (was > u32::MAX)")]
    OverlongDescription,

    #[error("Picture data is too large (was > u32::MAX)")]
    OverlongPictureData,
}

/// See <https://www.ietf.org/rfc/rfc9639.html#section-8.1-1>
#[derive(Debug, Clone, Copy, Eq, Display, PartialEq)]
#[repr(u8)]
pub enum BlockType {
    Streaminfo = 0,
    Padding,
    Application,
    SeekTable,
    VorbisComment,
    Cuesheet,
    Picture,
}

impl TryFrom<u8> for BlockType {
    type Error = Error;

    #[inline]
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        Ok(match value {
            0 => Self::Streaminfo,
            1 => Self::Padding,
            2 => Self::Application,
            3 => Self::SeekTable,
            4 => Self::VorbisComment,
            5 => Self::Cuesheet,
            6 => Self::Picture,
            127 => return Err(Error::ForbiddenBlockType),
            _ => return Err(Error::ReservedBlockType),
        })
    }
}

impl From<BlockType> for u8 {
    #[inline]
    fn from(value: BlockType) -> Self {
        match value {
            BlockType::Streaminfo => 0,
            BlockType::Padding => 1,
            BlockType::Application => 2,
            BlockType::SeekTable => 3,
            BlockType::VorbisComment => 4,
            BlockType::Cuesheet => 5,
            BlockType::Picture => 6,
        }
    }
}

impl Encode for BlockType {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        writer.write_bits(u8::from(*self).into(), 7)?;
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
pub struct BlockHeader {
    /// Whether this is the final metadata block
    pub is_final: bool,
    pub kind:     BlockType,
    /// The size of the metadata block in bytes
    pub size:     U24,
}

impl BlockHeader {
    /// Get the metadata block type
    #[inline]
    pub fn block_type_num_from_u8(byte: u8) -> Result<BlockType, Error> {
        BlockType::try_from(byte.get_bit_range_msb(1, 7))
    }
}

impl Decode<()> for BlockHeader {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Error> {
        let kind = reader.read_u8()?;
        let size = U24::new(reader.read_u24::<BE>()?).expect("this is a valid u24");

        let is_final = kind.get_bit_msb(0);
        let kind = Self::block_type_num_from_u8(kind)?;

        Ok(Self {
            is_final,
            kind,
            size,
        })
    }
}

impl Encode for BlockHeader {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        debug_assert!(writer.is_byte_aligned());

        writer.write_bit(self.is_final)?;
        self.kind.encode(writer, ())?;
        writer.write_bits(self.size.inner().into(), 24)?;

        debug_assert!(writer.is_byte_aligned());
        Ok(())
    }
}

#[derive(Clone)]
pub struct ReservedData(pub Vec<u8>);

impl std::fmt::Debug for ReservedData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReservedData").finish_non_exhaustive()
    }
}

#[derive(Debug, Clone)]
pub enum BlockData {
    Streaminfo(Streaminfo),
    /// Padding hasn't any data.
    Padding,
    Application(Application),
    SeekTable(SeekTable),
    VorbisComment(VorbisComment),
    Cuesheet(Cuesheet),
    Picture(Picture),
}

#[derive(Debug)]
pub struct Block {
    pub header: BlockHeader,
    pub data:   BlockData,
}

impl Decode<()> for Block {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Error> {
        let header = BlockHeader::decode(reader, ())?;

        let invalid_block_size = Err(Error::InvalidBlockSize(header.kind, header.size));

        let data = match header.kind {
            // error states
            BlockType::Streaminfo if header.size != 34 => return invalid_block_size,
            BlockType::VorbisComment if header.size < 8 => return invalid_block_size,
            BlockType::Cuesheet if header.size < 432 => return invalid_block_size,
            BlockType::Picture if header.size < 32 => return invalid_block_size,
            BlockType::Padding if header.size == 0 => BlockData::Padding,

            BlockType::Padding => {
                reader.seek_relative(i64::from(header.size.inner()))?;
                BlockData::Padding
            }

            BlockType::Streaminfo => BlockData::Streaminfo(Streaminfo::decode(reader, ())?),
            BlockType::Application => {
                BlockData::Application(Application::decode(reader, header.size)?)
            }
            BlockType::SeekTable => BlockData::SeekTable(SeekTable::decode(reader, header.size)?),
            BlockType::VorbisComment => {
                BlockData::VorbisComment(VorbisComment::decode(reader, ())?)
            }
            BlockType::Cuesheet => BlockData::Cuesheet(Cuesheet::decode(reader, ())?),
            BlockType::Picture => BlockData::Picture(Picture::decode(reader, header.size.inner())?),
        };

        Ok(Self { header, data })
    }
}

impl Encode for Block {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        self.header.encode(writer, ())?;

        let invalid_block_size = Err(Error::InvalidBlockSize(self.header.kind, self.header.size));
        match &self.data {
            // error states
            BlockData::Streaminfo(_) if self.header.size != 34 => return invalid_block_size,
            BlockData::VorbisComment(_) if self.header.size < 8 => return invalid_block_size,
            BlockData::Cuesheet(_) if self.header.size < 432 => return invalid_block_size,
            BlockData::Picture(_) if self.header.size < 32 => return invalid_block_size,

            BlockData::Padding => {
                for _ in 0..self.header.size.inner() {
                    writer.write_u8(0)?;
                }
            }
            BlockData::Streaminfo(d) => d.encode(writer, ())?,
            BlockData::Application(d) => d.encode(writer, ())?,
            BlockData::SeekTable(d) => d.encode(writer, ())?,
            BlockData::VorbisComment(d) => d.encode(writer, ())?,
            BlockData::Cuesheet(d) => d.encode(writer, ())?,
            BlockData::Picture(d) => d.encode(writer, ())?,
        }

        Ok(())
    }
}

/// Iteratively read [`Block`]s.
pub struct BlockIter<'a, R: Read + Seek> {
    reader: &'a mut BitReader<R>,
    ended:  bool,
}

impl<'a, R: Read + Seek> BlockIter<'a, R> {
    pub fn new(reader: &'a mut BitReader<R>) -> Self {
        Self {
            reader,
            ended: false,
        }
    }
}

impl<R: Read + Seek> Iterator for BlockIter<'_, R> {
    type Item = Result<Block, Error>;

    /// Parse the next [`Block`]. In the event of an error, this will
    /// return that error and return [`None`] on any subsequent calls.
    fn next(&mut self) -> Option<Self::Item> {
        if self.ended {
            return None;
        }

        match Block::decode(self.reader, ()) {
            Err(e) => {
                self.ended = true;
                Some(Err(e))
            }
            Ok(block) => {
                if block.header.is_final {
                    self.ended = true;
                }

                Some(Ok(block))
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Streaminfo {
    /// The minimum block size (in samples) used in the stream, excluding the
    /// last block.
    pub min_block_size: u16,

    /// The maximum block size (in samples) used in the stream.
    pub max_block_size: u16,

    /// The minimum frame size (in bytes) used in the stream. A value of `0`
    /// signifies that the value is not known.
    pub min_frame_size: U24,

    // The maximum frame size (in bytes) used in the stream. A value of `0` signifies that the
    // value is not known.
    pub max_frame_size: U24,

    /// Sample rate in Hz.
    pub sample_rate: U20,

    /// (number of channels) - 1. FLAC supports from `1` to `8` channels. Use
    /// [`Streaminfo::num_channels()`] to get the actual value.
    pub num_channels: U3,

    /// Bits per sample - 1. FLAC supports from `4` to `32` bits per sample. Use
    /// [`Streaminfo::bits_per_sample()`] to get the actual value.
    pub bits_per_sample: U5,

    /// Total number of *interchannel* samples in the stream. A value of `0`
    /// here means the number of total samples is unknown.
    pub num_samples: Option<NonZeroU36>,

    /// MD5 checksum of the unencoded audio data. This allows the decoder to
    /// determine if an error exists in the audio data even when, despite the
    /// error, the bitstream itself is valid. A value of [`None`] signifies that
    /// the value is not known.
    pub md5sum: Option<NonZero<u128>>,
}

impl Streaminfo {
    pub const LARGEST_POSSIBLE_BLOCK_SIZE: u16 = u16::MAX;

    #[inline]
    pub const fn num_channels(&self) -> usize {
        self.num_channels.inner() as usize + 1
    }

    #[inline]
    pub const fn bits_per_sample(&self) -> u8 {
        self.bits_per_sample.inner() + 1
    }
}

impl Decode<()> for Streaminfo {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Self::Error> {
        // https://www.ietf.org/rfc/rfc9639.html#name-streaminfo\

        let min_block_size = reader.read_u16::<BE>()?;
        let max_block_size = reader.read_u16::<BE>()?;
        let min_frame_size = U24::new(reader.read_u24::<BE>()?).expect("Should be valid u24");
        let max_frame_size = U24::new(reader.read_u24::<BE>()?).expect("Should be valid u24");
        let (sample_rate, num_channels, bits_per_sample, num_samples) = {
            let bytes = reader.read_u64::<BE>()?;
            let sample_rate =
                U20::new(bytes.get_bit_range_msb(0, 20) as u32).expect("Should be a valid u20");
            let num_channels =
                U3::new(bytes.get_bit_range_msb(20, 3) as u8).expect("Should be a valid u3");
            let bits_per_sample =
                U5::new(bytes.get_bit_range_msb(23, 5) as u8).expect("Should be a valid u5");
            let num_samples = NonZeroU36::new(
                U36::new(bytes.get_bit_range_msb(28, 36)).expect("Should be a valid u36"),
            );

            (sample_rate, num_channels, bits_per_sample, num_samples)
        };
        let md5sum = NonZero::new(reader.read_u128::<BE>()?);

        if min_block_size < 16 {
            return Err(Error::InvalidMinBlockSize(min_block_size));
        }
        if max_block_size < 16 {
            return Err(Error::InvalidMaxBlockSize(max_block_size));
        }
        if !(4..=32).contains(&bits_per_sample.inner()) {
            return Err(Error::InvalidBitsPerSample(bits_per_sample));
        }

        Ok(Self {
            min_block_size,
            max_block_size,
            min_frame_size,
            max_frame_size,
            sample_rate,
            num_channels,
            bits_per_sample,
            num_samples,
            md5sum,
        })
    }
}

impl Encode for Streaminfo {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        debug_assert!(writer.is_byte_aligned());

        writer.write_u16::<BE>(self.min_block_size)?;
        writer.write_u16::<BE>(self.max_block_size)?;

        writer.write_uint::<BE>(self.min_frame_size.inner().into(), 3)?;
        writer.write_uint::<BE>(self.max_frame_size.inner().into(), 3)?;

        writer.write_bits(self.sample_rate.inner().into(), 20)?;
        writer.write_bits(self.num_channels.inner().into(), 3)?;
        writer.write_bits(self.bits_per_sample.inner().into(), 5)?;
        writer.write_bits(
            self.num_samples
                .map_or_else(Default::default, |x| x.get().inner()),
            36,
        )?;
        writer.write_u128::<BE>(
            self.md5sum
                .map_or_else(u128::default, std::num::NonZero::get),
        )?;

        debug_assert!(writer.is_byte_aligned());
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct Application {
    /// A registered application ID.
    ///
    /// Application IDs are registered in the [IANA "FLAC Application Metadata
    /// Block IDs registry"](https://www.iana.org/assignments/flac/flac.xhtml).
    pub id: u32,

    /// This is `MetadataBlock::size() - 4` bytes in length and is big-endian.
    pub data: Vec<u8>,
}

impl Decode<U24> for Application {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, block_size: U24) -> Result<Self, Self::Error> {
        let mut data = vec![0u8; block_size.inner().saturating_sub(4) as usize];
        let id = reader.read_u32::<BE>()?;
        reader.read_exact(&mut data)?;

        Ok(Self { id, data })
    }
}

impl Encode for Application {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        debug_assert!(writer.is_byte_aligned());
        writer.write_u32::<BE>(self.id)?;
        writer.write_all(&self.data)?;
        Ok(())
    }
}

/// [`SeekPoint`]s are sorted in ascending order by sample number and have
/// unique sample numbers. All placehoder points occur at the end of the table.
#[derive(Debug, Clone)]
pub struct SeekTable(pub Vec<SeekPoint>);

impl Decode<U24> for SeekTable {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, block_size: U24) -> Result<Self, Error> {
        let n_seek_points = block_size.inner() / 18;

        let mut seek_points = Vec::with_capacity(n_seek_points as usize);
        for _ in 0..n_seek_points {
            seek_points.push(SeekPoint::decode(reader, ())?);
        }

        Ok(Self(seek_points))
    }
}

impl Encode for SeekTable {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        for seek_point in &self.0 {
            seek_point.encode(writer, ())?;
        }

        Ok(())
    }
}

/// ## Notes
/// - For placeholder points, the second and third field values are undefined.
/// - The sample offsets are those of an unmuxed FLAC stream. The offsets MUST
///   NOT be updated on muxing to reflect the new offsets of FLAC frames in a
///   container.
#[derive(Debug, Clone, Copy)]
pub struct SeekPoint {
    /// Sample number of the first sample in the target frame or [`u64::MAX`]
    /// for a placeholder point.
    pub sample_idx:   u64,
    /// Offset (in bytes) from the first byte of the first frame header to the
    /// first byte of the target frame's header.
    pub offset:       u64,
    /// Number of samples in the target frame.
    pub sample_count: u16,
}

impl SeekPoint {
    pub const fn is_placeholder(self) -> bool {
        self.sample_idx == u64::MAX
    }
}

impl Decode<()> for SeekPoint {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Error> {
        let sample_idx = reader.read_u64::<BE>()?;
        let offset = reader.read_u64::<BE>()?;
        let sample_count = reader.read_u16::<BE>()?;

        Ok(Self {
            sample_idx,
            offset,
            sample_count,
        })
    }
}

impl Encode for SeekPoint {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        writer.write_u64::<BE>(self.sample_idx)?;
        writer.write_u64::<BE>(self.offset)?;
        writer.write_u16::<BE>(self.sample_count)?;
        Ok(())
    }
}

bitflags! {
    /// The channel mask indicates which channels are present. The flags *only*
    /// signal which channels are present, not in which order, so if a file to be
    /// encoded has channels that are ordered differently, they have to be
    /// reordered.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct ChannelMask: u32 {
        const FRONT_LEFT = 0x1;
        const FRONT_RIGHT = 0x2;
        const FRONT_CENTER = 0x4;
        const LOW_FREQUENCY_EFFECTS = 0x8;
        const BACK_LEFT = 0x10;
        const BACK_RIGHT = 0x20;
        const FRONT_LEFT_OF_CENTER = 0x40;
        const FRONT_RIGHT_OF_CENTER = 0x80;
        const BACK_CENTER = 0x100;
        const SIDE_LEFT = 0x200;
        const SIDE_RIGHT = 0x400;
        const TOP_CENTER = 0x800;
        const TOP_FRONT_LEFT = 0x1000;
        const TOP_FRONT_CENTER = 0x2000;
        const TOP_FRONT_RIGHT = 0x4000;
        const TOP_REAR_LEFT = 0x8000;
        const TOP_REAR_CENTER = 0x10_000;
        const TOP_REAR_RIGHT = 0x20_000;
    }
}

impl ChannelMask {
    /// Parse a [`ChannelMask`] from a hexadecimal string.
    pub fn from_hex(hex: &str) -> Result<Self, std::num::ParseIntError> {
        Ok(Self::from_bits_truncate(u32::from_str_radix(hex, 16)?))
    }
}

#[derive(Debug, Clone)]
#[must_use]
pub struct VorbisComment {
    pub vendor:            String,
    pub user_comment_list: Vec<VorbisUserComment>,
}

impl VorbisComment {
    pub fn get_channel_mask(&self) -> Option<Result<ChannelMask, Error>> {
        self.user_comment_list
            .iter()
            .find(|c| c.key.as_str() == "WAVEFORMATEXTENSIBLE_CHANNEL_MASK")
            .map(|c| {
                // skip the `0x` prefix
                let value = c.value.get(2..).ok_or(Error::InvalidChannelMask);
                value.and_then(|x| ChannelMask::from_hex(x).map_err(Error::from))
            })
    }
}

impl Decode<()> for VorbisComment {
    type Error = Error;

    // NOTE: Vorbis comments are Little Endian!
    // See: https://xiph.org/vorbis/doc/v-comment.html
    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Error> {
        let vendor_length = reader.read_u32::<LE>()?;
        let vendor = {
            let mut buf = vec![0u8; vendor_length as usize];
            reader.read_exact(&mut buf)?;
            String::from_utf8(buf)?
        };

        let user_comment_count = reader.read_u32::<LE>()?;
        let mut user_comment_list = Vec::with_capacity(user_comment_count as usize);

        for _ in 0..user_comment_count {
            // TODO: perhaps ignore invalid fields? Perhaps have this behavior be
            // configurable.
            user_comment_list.push(VorbisUserComment::decode(reader, ())?);
        }

        Ok(Self {
            vendor,
            user_comment_list,
        })
    }
}

impl Encode for VorbisComment {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        debug_assert!(writer.is_byte_aligned());

        writer.write_u32::<LE>(
            self.vendor
                .len()
                .try_into()
                .map_err(|_| Error::VendorTooLong)?,
        )?;
        writer.write_all(self.vendor.as_bytes())?;

        writer.write_u32::<LE>(
            self.user_comment_list
                .len()
                .try_into()
                .map_err(|_| Error::UserCommentsTooLong)?,
        )?;

        for comment in &self.user_comment_list {
            comment.encode(writer, ())?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct VorbisUserComment {
    pub key:   Box<AsciiStr>,
    pub value: String,
}

impl VorbisUserComment {
    pub fn new(key: &AsciiStr, value: impl Into<String>) -> Option<Self> {
        let key: Box<_> = key.into();
        let value = value.into();

        Self::key_is_valid(&key).then_some(Self { key, value })
    }

    /// `key` can contain all printable ASCII characters except `=`.
    #[inline]
    pub fn key_is_valid(key: &AsciiStr) -> bool {
        key.bytes().all(|byte| byte != b'=')
    }
}

impl Decode<()> for VorbisUserComment {
    type Error = Error;

    // NOTE: Vorbis comments are Little Endian!
    // See: https://xiph.org/vorbis/doc/v-comment.html
    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Error> {
        let length = reader.read_u32::<LE>()?;

        let mut buf = vec![0u8; length as usize];
        reader.read_exact(&mut buf)?;

        let (key, value) = buf
            .iter()
            .position(|&x| x == b'=')
            .map(|pos| buf.split_at(pos))
            .map(|(key, value)| (key, &value[1..]))
            .ok_or(Error::InvalidVorbisComment)?;
        let key = Box::from(AsciiStr::from_bytes(key).ok_or(Error::CommentKeyNotAscii)?);
        let value = str::from_utf8(value)?.to_string();

        Ok(Self { key, value })
    }
}

impl Encode for VorbisUserComment {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        let length: u32 = (self.key.len() + self.value.len() + 1)
            .try_into()
            .map_err(|_| Error::VendorTooLong)?;

        writer.write_u32::<LE>(length)?;

        writer.write_all(self.key.as_bytes())?;
        writer.write_u8(b'=')?;
        writer.write_all(self.value.as_bytes())?;

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct Cuesheet {
    /// Media catalog number in ASCII printable characters (`0x20..=0x7E`). If
    /// the media catalog number is less than 128 bytes long, it is right-padded
    /// with `0x00` bytes.
    pub media_catalog_number: AsciiArray<128>,

    /// Number of lead-in samples.
    ///
    /// The number of lead-in samples has meaning only for CD-DA cuesheets; for
    /// other uses, it should be 0.
    pub lead_in_samples: u64,

    /// The cuesheet corresponds to a CD-DA.
    pub is_cdda: bool,

    // u(7+258*8) 	Reserved. All bits MUST be set to zero.
    pub tracks: Vec<CuesheetTrack>,
}

impl Cuesheet {
    #[inline]
    pub const fn is_valid(&self) -> bool {
        if let Some(x) = self.tracks.as_slice().last() {
            x.is_lead_out(self.is_cdda)
        } else {
            false
        }
    }
}

impl Decode<()> for Cuesheet {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, _opt: ()) -> Result<Self, Error> {
        let media_catalog_number = {
            let mut n = [0u8; 128];
            reader.read_exact(&mut n)?;
            let mut n = AsciiArray::try_from(n)?;
            // If the media catalog number is less than 128 bytes long, it is right-padded
            // with 0x00 bytes
            n.rtrim(b"\0");

            n
        };

        let lead_in_samples = reader.read_u64::<BE>()?;
        let is_cdda = {
            // NOTE: there are 7 reserved bits after the cdda bool.
            let cdda = reader.read_u8()?;
            cdda.get_bit_msb(0)
        };

        // NOTE: There are 258 reserved bytes after `is_cdda`
        reader.seek_relative(258)?;

        let track_count = reader.read_u8()?;

        let mut tracks = Vec::with_capacity(track_count.into());
        for _ in 0..track_count {
            tracks.push(CuesheetTrack::decode(reader, is_cdda)?);
        }

        let cuesheet = Self {
            media_catalog_number,
            lead_in_samples,
            is_cdda,
            tracks,
        };

        cuesheet
            .is_valid()
            .then_some(cuesheet)
            .ok_or(Error::InvalidCuesheet)
    }
}

impl Encode for Cuesheet {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        let mut cat_num = self.media_catalog_number;
        cat_num.fill_rest(0u8);

        writer.write_all(&cat_num)?;
        writer.write_u64::<BE>(self.lead_in_samples)?;
        writer.write_bit(self.is_cdda)?;

        // reserved
        writer.flush_bits()?;
        writer.write_all(&[0u8; 258])?;

        writer.write_u8(
            self.tracks
                .len()
                .try_into()
                .map_err(|_| Error::CuesheetTrackCount)?,
        )?;

        for track in &self.tracks {
            track.encode(writer, self.is_cdda)?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CuesheetTrack {
    /// Track offset of the first index point in samples, relative to the
    /// beginning of the FLAC audio stream.
    ///
    /// Note that the track offset differs from the one in CD-DA, where the
    /// track's offset in the table of contents (TOC) is that of the track's
    /// INDEX 01 even if there is an INDEX 00. For CD-DA, the track offset MUST
    /// be evenly divisible by `588` samples (`588 samples == 44100 samples/s *
    /// 1/75 s`).
    pub offset:       u64,
    /// Track number.
    pub number:       NonZero<u8>,
    /// Track a 12-digit, alphanumeric ASCII ISRC code.
    pub isrc:         Option<AsciiArray<12>>,
    /// Whether the track type is 'audio'.  This corresponds to the CD-DA
    /// Q-channel control bit 3.
    pub is_audio:     bool,
    /// The pre-emphasis flag: `false` for no pre-emphasis, `true` for
    /// pre-emphasis. This corresponds to the CD-DA Q-channel control bit 5.
    pub pre_emphasis: bool,
    // 6 + 8*13 of reserved space
    pub index_points: CuesheetTrackIndexPoints,
}

impl CuesheetTrack {
    #[inline]
    pub const fn is_lead_out(&self, cdda: bool) -> bool {
        !cdda && self.number.get() == 255 || self.number.get() == 170
    }

    #[inline]
    pub fn is_valid(&self, cdda: bool) -> bool {
        // https://www.ietf.org/rfc/rfc9639.html#section-8.7.1

        let is_number_valid = match (cdda, self.number.get()) {
            (true, 1..=99 | 170) // CD-DA: tracks 1-99 + lead-out 170
            | (false, 1..=255) => true, // non-CD-DA: any track 1-254 + lead-out 255
            _ => false,
        };
        let is_offset_valid = !cdda || (self.offset.is_multiple_of(588));
        let is_index_point_count_valid = if cdda {
            // CD-DA: at most 100 index points per track (except the lead-out)
            self.index_points.len <= 100 || self.is_lead_out(cdda)
        } else {
            // non-CD-DA: no limit at all
            true
        };
        let is_isrc_valid = match self.isrc {
            None => true,
            Some(isrc) => {
                let mut valid = true;
                let mut i = 0usize;
                while valid && i < 12 {
                    valid = valid && isrc.get(i) != 0 && isrc.get(i).is_ascii_alphanumeric();
                    i += 1;
                }
                valid
            }
        };

        is_offset_valid
            && is_number_valid
            && is_index_point_count_valid
            && is_isrc_valid
            && self.index_points.is_valid(cdda)
    }
}

impl Decode<bool> for CuesheetTrack {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, is_cdda: bool) -> Result<Self, Error> {
        let offset = reader.read_u64::<BE>()?;
        let number = NonZero::new(reader.read_u8()?).ok_or(Error::InvalidCuesheetTrack)?;
        let isrc = {
            let mut isrc = [0u8; 12];
            reader.read_exact(&mut isrc)?;
            if isrc.iter().all(|&x| x == 0) {
                None
            } else {
                Some(AsciiArray::try_from(isrc)?)
            }
        };
        let (is_audio, pre_emphasis) = {
            let flags = reader.read_u8()?;
            let is_audio = !flags.get_bit_msb(0);
            let pre_emphasis = flags.get_bit_msb(1);
            // NOTE: The remaining 6 bits are reserved.
            (is_audio, pre_emphasis)
        };
        // Skip the 13 reserved bytes.
        reader.seek_relative(13)?;

        let index_points = CuesheetTrackIndexPoints::decode(reader, is_cdda)?;

        let x = Self {
            offset,
            number,
            isrc,
            is_audio,
            pre_emphasis,
            index_points,
        };

        if x.is_valid(is_cdda) {
            Ok(x)
        } else {
            Err(Error::InvalidCuesheetTrack)
        }
    }
}

impl Encode<bool> for CuesheetTrack {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, is_cdda: bool) -> Result<(), Self::Error> {
        if cfg!(debug_assertions) && !self.is_valid(is_cdda) {
            return Err(Error::InvalidCuesheetTrack);
        }

        let mut isrc = self.isrc.unwrap_or_default();
        isrc.fill_rest(0);
        debug_assert_eq!(isrc.len(), 12);

        writer.write_u64::<BE>(self.offset)?;
        writer.write_u8(self.number.get())?;
        writer.write_all(&isrc)?;
        writer.write_bit(!self.is_audio)?;
        writer.write_bit(self.pre_emphasis)?;

        // reserved
        writer.flush_bits()?;
        writer.write_all(&[0; 13])?;

        self.index_points.encode(writer, is_cdda)?;

        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CuesheetTrackIndexPoints {
    /// The number of track index points.
    pub len:          u8,
    pub index_points: ArrayList<CuesheetTrackIndexPoint, 255>,
}

impl Deref for CuesheetTrackIndexPoints {
    type Target = [CuesheetTrackIndexPoint];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.index_points
            .split_at_checked(self.len as usize)
            .unwrap()
            .0
    }
}

impl CuesheetTrackIndexPoints {
    pub fn is_valid_cdda(&self) -> bool {
        // > For CD-DA, a track index point number of 0 corresponds to the track
        // > pre-gap.
        // > The first index point in a track MUST have a number of 0 or 1, and
        // > subsequently, index point numbers MUST increase by 1.

        let mut valid = true;
        let mut i = 0usize;

        while valid && i < self.len as usize {
            let point = self.index_points[i];
            if i == 0 {
                valid = valid && matches!(point.number, 0 | 1);
            } else {
                let prev = self.index_points[i - 1];
                valid = valid && point.number > prev.number;
            }

            valid = valid && point.is_valid_cdda();

            i += 1;
        }

        valid
    }

    pub fn is_valid(&self, cdda: bool) -> bool {
        let is_unique = {
            let mut valid = true;
            let mut i = 1usize;

            while valid && i < self.len as usize {
                let point = self.index_points[i];
                let prev = self.index_points[i - 1];
                valid = valid && point.number != prev.number;
                i += 1;
            }

            valid
        };

        (!cdda || self.is_valid_cdda()) && is_unique
    }
}

impl Decode<bool> for CuesheetTrackIndexPoints {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, is_cdda: bool) -> Result<Self, Error> {
        let len = reader.read_u8()?;
        let mut index_points = ArrayList::default();

        for _ in 0..len {
            index_points.push(CuesheetTrackIndexPoint::decode(reader, is_cdda)?);
        }

        let x = Self { len, index_points };
        if x.is_valid(is_cdda) {
            Ok(x)
        } else {
            Err(Error::InvalidCuesheetIndexPoints)
        }
    }
}

impl Encode<bool> for CuesheetTrackIndexPoints {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, is_cdda: bool) -> Result<(), Self::Error> {
        debug_assert!(writer.is_byte_aligned());

        if cfg!(debug_assertions) && !self.is_valid(is_cdda) {
            return Err(Error::InvalidCuesheetIndexPoints);
        }

        writer.write_u8(self.len)?;
        for point in &*self.index_points {
            point.encode(writer, is_cdda)?;
        }

        Ok(())
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Eq, Default)]
pub struct CuesheetTrackIndexPoint {
    /// Offset in samples, relative to the track offset, of the index point.
    pub offset: u64,
    /// The track index point number.
    pub number: u8,
    // [u8;3] of reserved bytes
}

impl CuesheetTrackIndexPoint {
    #[inline]
    pub const fn is_valid(self, is_cdda: bool) -> bool {
        !is_cdda || self.is_valid_cdda()
    }

    #[inline]
    pub const fn is_valid_cdda(self) -> bool {
        // NOTE: the track index point offset MUST be evenly divisible by 588 samples
        // (588 samples = 44100 samples/s * 1/75 s). Note that the offset is from the
        // beginning of the track, not the beginning of the audio data.
        self.offset.is_multiple_of(588)
    }
}

impl Decode<bool> for CuesheetTrackIndexPoint {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, is_cdda: bool) -> Result<Self, Error> {
        let offset = reader.read_u64::<BE>()?;
        let number = reader.read_u8()?;

        // Skip reserved bytes
        reader.seek_relative(3)?;

        let x = Self { offset, number };
        let is_valid = x.is_valid(is_cdda);

        if is_valid {
            Ok(x)
        } else {
            Err(Error::InvalidCuesheetIndexPoint)
        }
    }
}

impl Encode<bool> for CuesheetTrackIndexPoint {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, is_cdda: bool) -> Result<(), Self::Error> {
        if cfg!(debug_assertions) && !self.is_valid(is_cdda) {
            return Err(Error::InvalidCuesheetIndexPoints);
        }

        writer.write_u64::<BE>(self.offset)?;
        writer.write_u8(self.number)?;

        writer.write_all(&[0; 3])?; // reserved

        Ok(())
    }
}

/// See table from RFC9639: <https://www.ietf.org/rfc/rfc9639.html#table-13>
#[derive(Debug, Clone, Copy)]
#[repr(u32)]
pub enum PictureType {
    Other = 0,
    /// PNG file icon of 32x32 pixels (see [RFC2083](https://www.rfc-editor.org/info/rfc2083))
    PngFileIcon,
    /// General file icon
    FileIcon,
    FrontCover,
    BackCover,
    /// Liner notes page
    LinerNotes,
    /// Media label (e.g., CD, Vinyl or Cassette label)
    MediaLabel,
    /// Lead artist, lead performer, or soloist
    LeadArtist,
    /// Artist or performer
    Artist,
    Conductor,
    /// Band or orchestra
    Band,
    Composer,
    /// Lyricist or text writer
    Lyricist,
    RecordingLocation,
    /// During recording
    Recording,
    /// During performance
    Performance,
    /// Movie or video screen capture
    Movie,
    /// A bright colored fish
    ///
    /// > The origin and use of
    /// > [`BrightColoredFish`][PictureType::BrightColoredFish] is unclear.
    /// > This was copied to maintain compatibility with ID3v2. Applications are
    /// > discouraged from offering this value to users when embedding a picture
    ///
    /// <!-- Rust ANALyzer can't parse blockquotes correctly if there's no
    /// newline after -->
    BrightColoredFish,
    Illustration,
    /// Band or artist logotype
    ArtistLogotype,
    /// Publisher or studio logotype
    Publisher,
}

impl TryFrom<u32> for PictureType {
    type Error = Error;

    #[inline]
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        use PictureType::*;
        Ok(match value {
            0 => Other,
            1 => PngFileIcon,
            2 => FileIcon,
            3 => FrontCover,
            4 => BackCover,
            5 => LinerNotes,
            6 => MediaLabel,
            7 => LeadArtist,
            8 => Artist,
            9 => Conductor,
            10 => Band,
            11 => Composer,
            12 => Lyricist,
            13 => RecordingLocation,
            14 => Recording,
            15 => Performance,
            16 => Movie,
            17 => BrightColoredFish,
            18 => Illustration,
            19 => ArtistLogotype,
            20 => Publisher,
            21.. => return Err(Error::ReservedPictureType),
        })
    }
}

impl From<PictureType> for u32 {
    fn from(value: PictureType) -> Self {
        use PictureType::*;
        match value {
            Other => 0,
            PngFileIcon => 1,
            FileIcon => 2,
            FrontCover => 3,
            BackCover => 4,
            LinerNotes => 5,
            MediaLabel => 6,
            LeadArtist => 7,
            Artist => 8,
            Conductor => 9,
            Band => 10,
            Composer => 11,
            Lyricist => 12,
            RecordingLocation => 13,
            Recording => 14,
            Performance => 15,
            Movie => 16,
            BrightColoredFish => 17,
            Illustration => 18,
            ArtistLogotype => 19,
            Publisher => 20,
        }
    }
}

#[derive(Clone)]
pub enum PictureData {
    Bytes {
        /// The media type string as specified by [RFC2046](https://www.rfc-editor.org/rfc/rfc2046.html)
        media_type: Box<AsciiArray<255>>,
        data:       Vec<u8>,
    },
    /// A URI pointing to the picture data. The character encoding of the URI is
    /// left unspecified by RFC 9639.
    Uri(Vec<u8>),
}

impl std::fmt::Debug for PictureData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bytes { media_type, .. } => f
                .debug_struct("Bytes")
                .field("media_type", media_type)
                .finish_non_exhaustive(),
            Self::Uri(_) => f.debug_tuple("Uri").finish_non_exhaustive(),
        }
    }
}

/// The `height`, `width`, and `color_depth`, and `color_count` fields are for
/// informational purposes only. Applications MUST NOT use them in decoding the
/// picture or deciding how to display it, but applications MAY use them to
/// decide whether or not to process a block and MAY show them to the user.
#[derive(Debug, Clone)]
pub struct Picture {
    pub kind: PictureType,

    // TODO: Parse Media Types
    /// Description of the picture
    pub description: String,

    /// The width of the picture in pixels. For informational purposes only (See
    /// [`Picture`]).
    pub width: u32,

    /// The height of the picture in pixels. For informational purposes only
    /// (See [`Picture`]).
    pub height: u32,

    /// The color depth of the picture in bits per pixel. For informational
    /// purposes only (See [`Picture`]).
    pub color_depth: u32,

    /// For indexed-color pictures (e.g., GIF), the number of colors used;
    /// [`None`] for non-indexed pictures.
    pub color_count: Option<NonZero<u32>>,

    /// The binary picture data.
    pub data: PictureData,
}

impl Decode<u32> for Picture {
    type Error = Error;

    fn decode<R: BitRead + Seek>(reader: &mut R, max_length: u32) -> Result<Self, Error> {
        let mut total_length = 0u32;

        let mut inc_total_length = |len: u32| -> Result<(), Error> {
            total_length += len;
            if total_length > max_length {
                Err(Error::BlockExceededLength)
            } else {
                Ok(())
            }
        };

        let kind = PictureType::try_from(reader.read_u32::<BE>()?)?;

        let media_type = {
            let length = reader.read_u32::<BE>()?;
            inc_total_length(length)?;

            let mut media_type = [0u8; 255];
            reader.read_exact(&mut media_type[..length as usize])?;
            Box::new(AsciiArray::from_array(media_type, length as usize)?)
        };

        let description = {
            let length = reader.read_u32::<BE>()?;
            inc_total_length(length)?;

            let mut description = vec![0u8; length as usize];
            reader.read_exact(&mut description)?;
            String::from_utf8(description)?
        };

        let width = reader.read_u32::<BE>()?;
        let height = reader.read_u32::<BE>()?;
        let color_depth = reader.read_u32::<BE>()?;
        let color_count = NonZero::new(reader.read_u32::<BE>()?);

        let data = {
            let length = reader.read_u32::<BE>()?;
            inc_total_length(length)?;

            let mut data = vec![0u8; length as usize];
            reader.read_exact(&mut data)?;

            match media_type.as_str() {
                "-->" => PictureData::Uri(data),
                _ => PictureData::Bytes { media_type, data },
            }
        };

        Ok(Self {
            kind,
            description,
            width,
            height,
            color_depth,
            color_count,
            data,
        })
    }
}

impl Encode for Picture {
    type Error = Error;

    fn encode<W: BitWrite>(&self, writer: &mut W, _opt: ()) -> Result<(), Self::Error> {
        let (media_type, data) = match &self.data {
            PictureData::Bytes { media_type, data } => (**media_type, data),
            PictureData::Uri(data) => (AsciiArray::from_bytes(b"-->").unwrap(), data),
        };
        writer.write_u32::<BE>(u32::from(self.kind))?;
        writer.write_u32::<BE>(media_type.len() as u32)?;
        writer.write_all(&media_type)?;
        writer.write_u32::<BE>(
            self.description
                .len()
                .try_into()
                .map_err(|_| Error::OverlongDescription)?,
        )?;
        writer.write_all(self.description.as_bytes())?;
        writer.write_u32::<BE>(self.width)?;
        writer.write_u32::<BE>(self.height)?;
        writer.write_u32::<BE>(self.color_depth)?;
        writer.write_u32::<BE>(self.color_count.map(NonZeroU32::get).unwrap_or_default())?;
        writer.write_u32::<BE>(
            data.len()
                .try_into()
                .map_err(|_| Error::OverlongPictureData)?,
        )?;
        writer.write_all(data)?;

        Ok(())
    }
}

#[allow(clippy::dbg_macro)]
#[cfg(test)]
mod tests {
    use crate::MAGIC;

    use super::*;

    const FLAC_BIN: &[u8] = include_bytes!("../tests/audio/binaural-with-picture.flac");

    #[test]
    fn new_vorbis_user_comment() {
        let _mask = VorbisUserComment::new(
            AsciiStr::from_str("WAVEFORMATEXTENSIBLE_CHANNEL_MASK").unwrap(),
            "0x8",
        )
        .unwrap();
    }

    #[test]
    fn get_channel_mask() {
        let mask = VorbisUserComment::new(
            AsciiStr::from_str("WAVEFORMATEXTENSIBLE_CHANNEL_MASK").unwrap(),
            "0x8",
        )
        .unwrap();
        let block = VorbisComment {
            vendor:            String::from("Tgirl hooters"),
            user_comment_list: vec![mask],
        };
        let channel_mask = block.get_channel_mask().unwrap().unwrap();
        assert_eq!(channel_mask, ChannelMask::LOW_FREQUENCY_EFFECTS);
    }

    #[test]
    fn block_header_is_final() {
        // Example: A 'VorbisComment' (Type 4) that is NOT the last block.
        // Binary: 0 (last flag) 0000100 (type 4) -> 00000100 -> 0x04
        // Let's assume this is the start of a 4-byte u32 header: 0x04000006
        let header = dbg!(BlockHeader::decode_bytes(&[0b1000_0000, 0x00, 0x00, 0x00], ()).unwrap());

        assert!(header.is_final);
        let header = dbg!(BlockHeader::decode_bytes(&[0b0000_0000, 0x00, 0x00, 0x00], ()).unwrap());

        assert!(!header.is_final);
    }

    #[test]
    fn block_header_kind() {
        // Example: A 'VorbisComment' (Type 4) that is NOT the last block.
        // Binary: 0 (last flag) 0000100 (type 4) -> 00000100 -> 0x04
        // Let's assume this is the start of a 4-byte u32 header: 0x04000006
        let bytes = [
            0b0000_0100, // is_last=0, block_type=0 (STREAMINFO)
            0x00,
            0x00,
            0x22, // length = 34
        ];
        let header = BlockHeader::decode_bytes(&bytes, ()).unwrap();

        assert_eq!(header.kind, BlockType::VorbisComment);

        // let header = dbg!(BlockHeader::decode_bytes(
        //     &0x0CAFEBABE_u32.to_ne_bytes()
        // )?);
        // assert_eq!(header.kind, BlockType::Reserved(0x4A));
    }

    fn parse_block<R: BitRead + Seek>(reader: &mut R, mut cb: impl FnMut(Block)) {
        loop {
            let block = Block::decode(reader, ()).unwrap();
            let is_final = block.header.is_final;
            println!("{block:#?}");

            cb(block);

            if is_final {
                break;
            }
        }
    }

    #[test]
    fn test_parse_block() {
        let mut flac = BitReader::new(io::Cursor::new(FLAC_BIN));

        let mut magic = [0u8; size_of_val(&MAGIC)];
        flac.read_exact(&mut magic).unwrap();
        assert_eq!(magic, MAGIC);

        parse_block(&mut flac, |_block| {});
    }
}

#[cfg(test)]
mod streaminfo_encode {
    use super::*;
    use crate::Encode;
    use crate::bit_io::{BitReader, BitWriter};
    use std::io::Cursor;

    // The test FLAC file is already embedded by the existing metadata tests.
    const FLAC_BIN: &[u8] = include_bytes!("../tests/audio/binaural-with-picture.flac");

    fn streaminfo_from_file() -> &'static [u8] {
        // NOTE: STREAMINFO is always exactly 34 bytes.
        &FLAC_BIN[8..42] // Skip magic and block header.
    }

    fn parse_streaminfo(raw: &[u8]) -> Streaminfo {
        Streaminfo::decode(&mut BitReader::new(Cursor::new(raw)), ()).unwrap()
    }

    #[test]
    fn round_trip_encode_streaminfo() {
        let original_bytes = streaminfo_from_file();
        let parsed = parse_streaminfo(original_bytes);

        let mut w = BitWriter::new(Vec::new());
        parsed.encode(&mut w, ()).unwrap();
        let encoded = w.into_inner();

        assert_eq!(
            encoded, original_bytes,
            "re-encoded STREAMINFO does not match original bytes from file"
        );
    }

    #[test]
    fn round_trip_encode_streaminfo_parsed() {
        let original_bytes = streaminfo_from_file();
        let original = parse_streaminfo(original_bytes);

        let mut w = BitWriter::new(Vec::new());
        original.encode(&mut w, ()).unwrap();
        let encoded = w.into_inner();

        let decoded = parse_streaminfo(&encoded);
        assert_eq!(original, decoded);
    }

    #[test]
    fn test_block_header_bytes_are_valid() {
        let header_bytes = &FLAC_BIN[4..8];

        let block_type = header_bytes[0] & 0x7F;
        assert_eq!(block_type, 0, "first metadata block must be STREAMINFO");

        let length = u32::from_be_bytes([0, header_bytes[1], header_bytes[2], header_bytes[3]]);
        assert_eq!(length, 34, "STREAMINFO block length must be 34");
    }

    #[test]
    fn round_trip_encode_block_header() {
        let original_header_bytes = &FLAC_BIN[4..8];
        let header =
            BlockHeader::decode(&mut BitReader::new(Cursor::new(original_header_bytes)), ())
                .unwrap();

        let mut w = BitWriter::new(Vec::new());
        header.encode(&mut w, ()).unwrap();
        let encoded = w.into_inner();

        assert_eq!(
            encoded.as_slice(),
            original_header_bytes,
            "re-encoded block header does not match original"
        );
    }
}