sharkyflac 0.1.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
// TODO: rewrite parsers to use `BitReader` properly

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

use crate::Parse;
use crate::ascii_str::{self, AsciiArray, AsciiStr};
use crate::bit_reader::BitReader;
use crate::bits::Bitset;
use crate::num::*;

#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    #[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(
        "{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,
}

#[derive(Debug, Clone, Copy, Eq, Display, PartialEq)]
#[repr(u8)]
pub enum BlockType {
    Streaminfo = 0,
    Padding,
    Application,
    SeekTable,
    VorbisComment,
    Cuesheet,
    Picture,
    Forbidden  = 127,
}

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

    #[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 => Self::Forbidden,
            _ => return Err(ParseError::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,
            BlockType::Forbidden => 127,
        }
    }
}

#[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, ParseError> {
        BlockType::try_from(byte.get_bit_range_msb(1, 7))
    }
}

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

    fn parse_from_reader<R: Read>(reader: &mut BitReader<R>, _opt: ()) -> Result<Self, ParseError> {
        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)?;

        if kind == BlockType::Forbidden {
            return Err(ParseError::ForbiddenBlockType);
        }

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

#[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 Parse<()> for Block {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        _opt: (),
    ) -> Result<Self, ParseError> {
        let header = BlockHeader::parse_from_reader(reader, ())?;

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

        let data = match header.kind {
            // error states
            BlockType::Forbidden => return Err(ParseError::ForbiddenBlockType),
            BlockType::Streaminfo if header.size < 4 => return invalid_block_size,
            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::parse_from_reader(reader, ())?)
            }
            BlockType::Application => {
                BlockData::Application(Application::parse_from_reader(reader, header.size)?)
            }
            BlockType::SeekTable => {
                BlockData::SeekTable(SeekTable::parse_from_reader(reader, header.size)?)
            }
            BlockType::VorbisComment => {
                BlockData::VorbisComment(VorbisComment::parse_from_reader(reader, ())?)
            }
            BlockType::Cuesheet => BlockData::Cuesheet(Cuesheet::parse_from_reader(reader, ())?),
            BlockType::Picture => {
                BlockData::Picture(Picture::parse_from_reader(reader, header.size.inner())?)
            }
        };

        Ok(Self { header, data })
    }
}

/// 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<'a, R: Read + Seek> Iterator for BlockIter<'a, R> {
    type Item = Result<Block, ParseError>;

    /// 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::parse_from_reader(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_excluding_final: 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.
    pub num_channels: U3,

    /// Bits per sample. FLAC supports from `4` to `32` bits per sample.
    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 fn num_channels(&self) -> usize {
        self.num_channels.inner() as usize + 1
    }
}

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

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

        let min_block_size_excluding_final = 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 + 1).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_excluding_final < 16 {
            return Err(ParseError::InvalidMinBlockSize(
                min_block_size_excluding_final,
            ));
        }
        if max_block_size < 16 {
            return Err(ParseError::InvalidMaxBlockSize(max_block_size));
        }
        if !(4..=32).contains(&bits_per_sample.inner()) {
            return Err(ParseError::InvalidBitsPerSample(bits_per_sample));
        }

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

#[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 Parse<U24> for Application {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        block_size: U24,
    ) -> Result<Self, ParseError> {
        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 })
    }
}

/// [`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 Parse<U24> for SeekTable {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        block_size: U24,
    ) -> Result<Self, ParseError> {
        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::parse_from_reader(reader, ())?);
        }

        Ok(Self(seek_points))
    }
}

/// ## 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 Parse<()> for SeekPoint {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        _opt: (),
    ) -> Result<Self, ParseError> {
        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 SeekPoint {
    pub const fn is_placeholder(self) -> bool {
        self.sample_idx == u64::MAX
    }
}

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, ParseError>> {
        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(ParseError::InvalidChannelMask);
                value.and_then(|x| ChannelMask::from_hex(x).map_err(ParseError::from))
            })
    }
}

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

    // NOTE: Vorbis comments are Little Endian!
    // See: https://xiph.org/vorbis/doc/v-comment.html
    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        _opt: (),
    ) -> Result<Self, ParseError> {
        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?
            user_comment_list.push(VorbisUserComment::parse_from_reader(reader, ())?);
        }

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

#[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 Parse<()> for VorbisUserComment {
    type Error = ParseError;

    // NOTE: Vorbis comments are Little Endian!
    // See: https://xiph.org/vorbis/doc/v-comment.html
    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        _opt: (),
    ) -> Result<Self, ParseError> {
        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(ParseError::InvalidVorbisComment)?;
        let key = Box::from(AsciiStr::from_bytes(key).ok_or(ParseError::CommentKeyNotAscii)?);
        let value = str::from_utf8(value)?.to_string();

        Ok(Self { key, value })
    }
}

#[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 Parse<()> for Cuesheet {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        _opt: (),
    ) -> Result<Self, ParseError> {
        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::parse_from_reader(reader, is_cdda)?);
        }

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

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

#[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 const 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()) {
            // CD-DA: tracks 1-99 + lead-out 170
            (true, 1..=99 | 170) => true,
            // non-CD-DA: any track 1-254 + lead-out 255
            (false, 1..=255) => true,
            _ => 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 Parse<bool> for CuesheetTrack {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        is_cdda: bool,
    ) -> Result<Self, ParseError> {
        let offset = reader.read_u64::<BE>()?;
        let number = NonZero::new(reader.read_u8()?).ok_or(ParseError::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::parse_from_reader(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(ParseError::InvalidCuesheetTrack)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CuesheetTrackIndexPoints {
    /// The number of track index points.
    pub len:          u8,
    pub index_points: [CuesheetTrackIndexPoint; u8::MAX as usize],
}

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 {
    #[inline]
    pub const 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
    }

    #[inline]
    pub const 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 Parse<bool> for CuesheetTrackIndexPoints {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        is_cdda: bool,
    ) -> Result<Self, ParseError> {
        let len = reader.read_u8()?;
        let mut index_points = [CuesheetTrackIndexPoint::default(); u8::MAX as usize];

        for i in 0..len {
            index_points[i as usize] = CuesheetTrackIndexPoint::parse_from_reader(reader, is_cdda)?;
        }

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

#[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_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 Parse<bool> for CuesheetTrackIndexPoint {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        is_cdda: bool,
    ) -> Result<Self, ParseError> {
        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 = !is_cdda || x.is_valid_cdda();

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

/// 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,
    Reserved(u32),
}

impl PictureType {
    pub const fn from_repr(num: u32) -> Self {
        use PictureType::*;
        match num {
            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.. => Reserved(num),
        }
    }
}

#[derive(Clone)]
pub enum PictureData {
    Bytes(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(_) => f.debug_tuple("Bytes").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
    /// The media type string as specified by [RFC2046](https://www.rfc-editor.org/rfc/rfc2046.html)
    pub media_type: AsciiArray<255>,

    /// 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 Parse<u32> for Picture {
    type Error = ParseError;

    fn parse_from_reader<R: Read + Seek>(
        reader: &mut BitReader<R>,
        max_length: u32,
    ) -> Result<Self, ParseError> {
        let mut total_length = 0u32;

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

        let kind = PictureType::from_repr(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])?;
            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(data),
            }
        };

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

#[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::parse_bytes(&[0b1000_0000, 0x00, 0x00, 0x00], ()).unwrap());

        assert!(header.is_final);
        let header = dbg!(BlockHeader::parse_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::parse_bytes(&bytes, ()).unwrap();

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

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

    fn parse_block<R: Read + Seek>(reader: &mut BitReader<R>, mut cb: impl FnMut(Block)) {
        loop {
            let block = Block::parse_from_reader(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| {});
    }
}