mkvparser 0.2.0

MKV and WebM parser
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
#![forbid(missing_docs)]

//! Parse MKV and WebM content
//!
//! Provides a set of Matroska structures and
//! functions to parse Matroska elements.

use std::ops::Not;

use chrono::prelude::*;
use nom::combinator::peek;
use nom::ToUsize;
use serde::{Serialize, Serializer};
use serde_with::skip_serializing_none;

mod ebml;
/// Matroska elements
pub mod elements;
/// Matroska enumerations
pub mod enumerations;
mod error;
/// The tree module contains helpers for building tree
/// structures from parsed elements
pub mod tree;

use crate::elements::{Id, Type};
use crate::enumerations::Enumeration;
pub use error::Error;

/// Result type helper
pub type Result<T> = std::result::Result<T, Error>;
type IResult<T, O> = Result<(T, O)>;

fn take<'a>(
    len: impl ToUsize,
) -> impl Fn(&'a [u8]) -> std::result::Result<(&'a [u8], &'a [u8]), nom::Err<()>> {
    nom::bytes::streaming::take(len)
}

pub(crate) fn parse_id(input: &[u8]) -> IResult<&[u8], Id> {
    let (input, first_byte) = peek(take(1usize))(input)?;
    let first_byte = first_byte[0];

    let num_bytes = count_leading_zero_bits(first_byte) + 1;

    // IDs can only have up to 4 bytes in Matroska
    if num_bytes > 4 {
        return Err(Error::InvalidId);
    }

    let (input, varint_bytes) = take(num_bytes)(input)?;
    let mut value_buffer = [0u8; 4];
    value_buffer[(4 - varint_bytes.len())..].copy_from_slice(varint_bytes);
    let id = u32::from_be_bytes(value_buffer);

    Ok((input, Id::new(id)))
}

/// Represents an [EBML Header](https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown#ebml-header)
#[skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Header {
    /// The Element ID
    pub id: Id,
    /// Size of the header itself
    pub header_size: usize,
    /// Size of the Element Body
    #[serde(skip_serializing)]
    pub body_size: Option<usize>,
    /// Size of Header + Body
    #[serialize_always]
    #[serde(serialize_with = "serialize_size")]
    pub size: Option<usize>,
    /// Position in the input
    pub position: Option<usize>,
}

fn serialize_size<S: Serializer>(
    size: &Option<usize>,
    s: S,
) -> std::result::Result<S::Ok, S::Error> {
    if let Some(size) = size {
        s.serialize_u64(*size as u64)
    } else {
        s.serialize_str("Unknown")
    }
}

impl Header {
    /// Create a new Header
    pub fn new(id: Id, header_size: usize, body_size: usize) -> Self {
        Self {
            id,
            header_size,
            body_size: Some(body_size),
            size: Some(header_size + body_size),
            position: None,
        }
    }

    fn with_unknown_size(id: Id, header_size: usize) -> Self {
        Self {
            id,
            header_size,
            body_size: None,
            size: None,
            position: None,
        }
    }
}

fn count_leading_zero_bits(input: u8) -> u8 {
    const MASK: u8 = 0b10000000;
    for leading_zeros in 0..8 {
        if input >= (MASK >> leading_zeros) {
            return leading_zeros;
        }
    }
    8
}

fn parse_varint(first_input: &[u8]) -> IResult<&[u8], Option<usize>> {
    let (input, first_byte) = peek(take(1usize))(first_input)?;
    let first_byte = first_byte[0];

    let vint_prefix_size = count_leading_zero_bits(first_byte) + 1;

    // Maximum 8 bytes, i.e. first byte can't be 0
    if vint_prefix_size > 8 {
        return Err(Error::InvalidVarint);
    }

    let (input, varint_bytes) = take(vint_prefix_size)(input)?;
    // any efficient way to avoid this copy here?
    let mut value_buffer = [0u8; 8];
    value_buffer[(8 - varint_bytes.len())..].copy_from_slice(varint_bytes);
    let mut value = u64::from_be_bytes(value_buffer);

    // discard varint prefix (zeros + market bit)
    let num_bits_in_value = 7 * vint_prefix_size;
    let bitmask = (1 << num_bits_in_value) - 1;
    value &= bitmask;

    // If all VINT_DATA bits are set to 1, it's an unkown size/value
    // https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown#unknown-data-size
    //
    // In 32-bit plaforms, the conversion from u64 to usize will fail if the value
    // is bigger than u32::MAX.
    let result = (value != bitmask).then(|| value.try_into()).transpose()?;

    Ok((input, result))
}

/// Parse element header
pub fn parse_header(input: &[u8]) -> IResult<&[u8], Header> {
    let initial_len = input.len();
    let (input, id) = parse_id(input)?;
    let (input, body_size) = parse_varint(input)?;

    // Only Segment and Cluster have unknownsizeallowed="1" in ebml_matroska.xml.
    // Also mentioned in https://www.w3.org/TR/mse-byte-stream-format-webm/
    if body_size.is_none() && id != Id::Segment && id != Id::Cluster {
        return Err(Error::ForbiddenUnknownSize);
    }

    let header_size = initial_len - input.len();

    let header = match body_size {
        Some(body_size) => Header::new(id, header_size, body_size),
        None => Header::with_unknown_size(id, header_size),
    };

    Ok((input, header))
}

#[derive(Debug, Clone, PartialEq, Serialize)]
enum Lacing {
    Xiph,
    Ebml,
    FixedSize,
}

/// A Matroska [Block](https://www.matroska.org/technical/basics.html#block-structure)
#[skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Block {
    track_number: usize,
    timestamp: i16,
    #[serde(skip_serializing_if = "Not::not")]
    invisible: bool,
    lacing: Option<Lacing>,
    num_frames: Option<u8>,
}

/// A Matroska [SimpleBlock](https://www.matroska.org/technical/basics.html#simpleblock-structure)
#[skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SimpleBlock {
    track_number: usize,
    timestamp: i16,
    #[serde(skip_serializing_if = "Not::not")]
    keyframe: bool,
    #[serde(skip_serializing_if = "Not::not")]
    invisible: bool,
    lacing: Option<Lacing>,
    #[serde(skip_serializing_if = "Not::not")]
    discardable: bool,
    num_frames: Option<u8>,
}

/// Enumeration with possible binary value payloads
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Binary {
    /// A standard binary payload that will not be parsed further
    Standard(String),
    /// A SeekId payload
    SeekId(Id),
    /// A SimpleBlock
    SimpleBlock(SimpleBlock),
    /// A Block
    Block(Block),
    /// Void
    Void,
    /// Represents the payload of a corrupted region of the file
    Corrupted,
}

fn parse_binary<'a>(header: &Header, input: &'a [u8]) -> IResult<&'a [u8], Binary> {
    let body_size = header.body_size.ok_or(Error::ForbiddenUnknownSize)?;
    let (input, binary) = peek_binary(header, input)?;
    // Actually consume the bytes from the body
    let (input, _) = take(body_size)(input)?;
    Ok((input, binary))
}

/// Peek into Binary body without advancing the buffer.
///
/// It may be useful to parse just the first bytes of the binary body
/// without requiring the whole binary to be loaded into memory.
pub fn peek_binary<'a>(header: &Header, input: &'a [u8]) -> IResult<&'a [u8], Binary> {
    let body_size = header.body_size.ok_or(Error::ForbiddenUnknownSize)?;

    let binary = match header.id {
        Id::SeekId => Binary::SeekId(parse_id(input)?.1),
        Id::SimpleBlock => Binary::SimpleBlock(parse_simple_block(input)?.1),
        Id::Block => Binary::Block(parse_block(input)?.1),
        Id::Void => Binary::Void,
        _ => Binary::Standard(peek_standard_binary(input, body_size)?.1),
    };

    Ok((input, binary))
}

fn peek_standard_binary(input: &[u8], size: usize) -> IResult<&[u8], String> {
    const MAX_LENGTH: usize = 64;
    if size <= MAX_LENGTH {
        let (input, bytes) = peek(take(size))(input)?;
        let string_values = bytes
            .iter()
            .map(|n| format!("{:02x}", n))
            .fold("".to_owned(), |acc, s| acc + &s + " ")
            .trim_end()
            .to_owned();
        Ok((input, format!("[{}]", string_values)))
    } else {
        Ok((input, format!("{} bytes", size)))
    }
}

/// An unsigned value that may contain an enumeration
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Unsigned {
    /// An standard value
    Standard(u64),
    /// An enumerated value
    Enumeration(Enumeration),
}

impl Unsigned {
    fn new(id: &Id, value: u64) -> Self {
        Enumeration::new(id, value).map_or(Self::Standard(value), Self::Enumeration)
    }
}

/// An [EBML Body](https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown#ebml-body)
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Body {
    /// A Master Body contains no data, but will contain zero or more elements
    /// that come after it.
    Master,
    /// An Unsigned Integer that may contain a known Enumeration
    Unsigned(Unsigned),
    /// A Signed Integer
    Signed(i64),
    /// A Float
    Float(f64),
    /// A String
    String(String),
    /// An UTF-8 String
    Utf8(String),
    /// A Date
    Date(DateTime<Utc>),
    /// A Binary
    Binary(Binary),
}

/// Represents an EBML Element
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Element {
    /// The Header
    #[serde(flatten)]
    pub header: Header,
    /// The Body
    #[serde(rename = "value")]
    pub body: Body,
}

const SYNC_ELEMENT_IDS: &[Id] = &[
    Id::Cluster,
    Id::Ebml,
    Id::Segment,
    Id::SeekHead,
    Id::Info,
    Id::Tracks,
    Id::Cues,
    Id::Attachments,
    Id::Chapters,
    Id::Tags,
];

/// Parse corrupt area
///
/// If we ever hit a damaged element, we can try to recover by finding
/// one of those IDs next to start clean. Those are the 4-bytes IDs,
/// which according to the EBML spec:
/// "Four-octet Element IDs are somewhat special in that they are useful
/// for resynchronizing to major structures in the event of data corruption or loss."
///
/// This parser either stops once a valid sync id or consumes the whole buffer.
/// It returns NeedData if the input is an empty slice.
pub fn parse_corrupt(input: &[u8]) -> IResult<&[u8], Element> {
    const SYNC_ID_LEN: usize = 4;

    if input.is_empty() {
        return Err(Error::NeedData);
    }

    for (offset, window) in input.windows(SYNC_ID_LEN).enumerate() {
        for sync_id in SYNC_ELEMENT_IDS {
            let id_value = sync_id.get_value().unwrap();
            let id_bytes = id_value.to_be_bytes();
            if window == id_bytes {
                // TODO: we might want to try and parse the element here, because if the
                // the sync element header itself is corrupt (e.g. invalid varint), then
                // the consuming side might step into an infinite loop.
                return Ok((
                    &input[offset..],
                    Element {
                        header: Header::new(Id::corrupted(), 0, offset),
                        body: Body::Binary(Binary::Corrupted),
                    },
                ));
            }
        }
    }
    Ok((
        &[],
        Element {
            header: Header::new(Id::corrupted(), 0, input.len()),
            body: Body::Binary(Binary::Corrupted),
        },
    ))
}

/// Parse an element
pub fn parse_element(original_input: &[u8]) -> IResult<&[u8], Element> {
    let (input, header) = parse_header(original_input)?;
    let (input, body) = parse_body(&header, input)?;

    let element = Element { header, body };
    Ok((input, element))
}

/// Parse element body
pub fn parse_body<'a>(header: &Header, input: &'a [u8]) -> IResult<&'a [u8], Body> {
    let element_type = header.id.get_type();
    let (input, body) = match element_type {
        Type::Master => (input, Body::Master),
        Type::Unsigned => {
            let (input, value) = parse_int(header, input)?;
            (input, Body::Unsigned(Unsigned::new(&header.id, value)))
        }
        Type::Signed => {
            let (input, value) = parse_int(header, input)?;
            (input, Body::Signed(value))
        }
        Type::Float => {
            let (input, value) = parse_float(header, input)?;
            (input, Body::Float(value))
        }
        Type::String => {
            let (input, value) = parse_string(header, input)?;
            (input, Body::String(value))
        }
        Type::Utf8 => {
            let (input, value) = parse_string(header, input)?;
            (input, Body::Utf8(value))
        }
        Type::Date => {
            let (input, value) = parse_date(header, input)?;
            (input, Body::Date(value))
        }
        Type::Binary => {
            let (input, value) = parse_binary(header, input)?;
            (input, Body::Binary(value))
        }
    };
    Ok((input, body))
}

fn parse_string<'a>(header: &Header, input: &'a [u8]) -> IResult<&'a [u8], String> {
    let body_size = header.body_size.ok_or(Error::ForbiddenUnknownSize)?;
    let (input, string_bytes) = take(body_size)(input)?;
    let value = String::from_utf8(string_bytes.to_vec())?;

    // Remove trimming null characters
    let value = value.trim_end_matches('\0').to_string();

    Ok((input, value))
}

fn parse_date<'a>(header: &Header, input: &'a [u8]) -> IResult<&'a [u8], DateTime<Utc>> {
    let (input, timestamp_nanos_to_2001) = parse_int::<i64>(header, input)?;
    let nanos_2001 = NaiveDate::from_ymd_opt(2001, 1, 1)
        .ok_or(Error::InvalidDate)?
        .and_hms_opt(0, 0, 0)
        .ok_or(Error::InvalidDate)?
        .timestamp_nanos();
    let timestamp_seconds_to_1970 = (timestamp_nanos_to_2001 + nanos_2001) / 1_000_000_000;
    Ok((
        input,
        DateTime::<Utc>::from_utc(
            NaiveDateTime::from_timestamp_opt(timestamp_seconds_to_1970, 0)
                .ok_or(Error::InvalidDate)?,
            Utc,
        ),
    ))
}

trait Integer64FromBigEndianBytes {
    fn from_be_bytes(input: [u8; 8]) -> Self;
}

impl Integer64FromBigEndianBytes for u64 {
    fn from_be_bytes(input: [u8; 8]) -> Self {
        u64::from_be_bytes(input)
    }
}

impl Integer64FromBigEndianBytes for i64 {
    fn from_be_bytes(input: [u8; 8]) -> Self {
        i64::from_be_bytes(input)
    }
}

fn parse_int<'a, T: Integer64FromBigEndianBytes>(
    header: &Header,
    input: &'a [u8],
) -> IResult<&'a [u8], T> {
    let body_size = header.body_size.ok_or(Error::ForbiddenUnknownSize)?;
    if body_size > 8 {
        return Err(Error::ForbiddenIntegerSize);
    }

    let (input, int_bytes) = take(body_size)(input)?;

    let mut value_buffer = [0u8; 8];
    value_buffer[(8 - int_bytes.len())..].copy_from_slice(int_bytes);
    let value = T::from_be_bytes(value_buffer);

    Ok((input, value))
}

fn parse_float<'a>(header: &Header, input: &'a [u8]) -> IResult<&'a [u8], f64> {
    let body_size = header.body_size.ok_or(Error::ForbiddenUnknownSize)?;

    if body_size == 4 {
        let (input, float_bytes) = take(body_size)(input)?;
        let value = f32::from_be_bytes(float_bytes.try_into().unwrap()) as f64;
        Ok((input, value))
    } else if body_size == 8 {
        let (input, float_bytes) = take(body_size)(input)?;
        let value = f64::from_be_bytes(float_bytes.try_into().unwrap());
        Ok((input, value))
    } else if body_size == 0 {
        Ok((input, 0f64))
    } else {
        Err(Error::ForbiddenFloatSize)
    }
}

fn parse_i16(input: &[u8]) -> IResult<&[u8], i16> {
    let (input, bytes) = take(2usize)(input)?;
    let value = i16::from_be_bytes(bytes.try_into().unwrap());
    Ok((input, value))
}

fn is_invisible(flags: u8) -> bool {
    (flags & (1 << 3)) != 0
}

fn get_lacing(flags: u8) -> Option<Lacing> {
    match (flags & (0b110)) >> 1 {
        0b01 => Some(Lacing::Xiph),
        0b11 => Some(Lacing::Ebml),
        0b10 => Some(Lacing::FixedSize),
        _ => None,
    }
}

fn parse_block(input: &[u8]) -> IResult<&[u8], Block> {
    let (input, track_number) = parse_varint(input)?;
    let track_number = track_number.ok_or(Error::MissingTrackNumber)?;
    let (input, timestamp) = parse_i16(input)?;
    let (input, flags) = take(1usize)(input)?;
    let flags = flags[0];

    let invisible = is_invisible(flags);
    let lacing = get_lacing(flags);
    let (input, num_frames) = if lacing.is_some() {
        let (input, next_byte) = take(1usize)(input)?;
        let num_frames = next_byte[0];
        (input, Some(num_frames + 1))
    } else {
        (input, None)
    };

    Ok((
        input,
        Block {
            track_number,
            timestamp,
            invisible,
            lacing,
            num_frames,
        },
    ))
}

fn parse_simple_block(input: &[u8]) -> IResult<&[u8], SimpleBlock> {
    let (input, track_number) = parse_varint(input)?;
    let track_number = track_number.ok_or(Error::MissingTrackNumber)?;
    let (input, timestamp) = parse_i16(input)?;
    let (input, flags) = take(1usize)(input)?;
    let flags = flags[0];

    let keyframe = (flags & (1 << 7)) != 0;
    let invisible = is_invisible(flags);
    let lacing = get_lacing(flags);
    let discardable = (flags & 0b1) != 0;
    let (input, num_frames) = if lacing.is_some() {
        let (input, next_byte) = take(1usize)(input)?;
        let num_frames = next_byte[0];
        (input, Some(num_frames + 1))
    } else {
        (input, None)
    };

    Ok((
        input,
        SimpleBlock {
            track_number,
            timestamp,
            keyframe,
            invisible,
            lacing,
            discardable,
            num_frames,
        },
    ))
}

/// Helper to add resiliency to corrupt inputs
pub fn parse_element_or_corrupted(input: &[u8]) -> IResult<&[u8], Element> {
    parse_element(input).or_else(|_| parse_corrupt(input))
}

#[cfg(test)]
mod tests {
    use crate::enumerations::TrackType;

    use super::*;

    const EMPTY: &[u8] = &[];
    const UNKNOWN_VARINT: &[u8] = &[0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];

    #[test]
    fn test_count_leading_zero_bits() {
        assert_eq!(count_leading_zero_bits(0b10000000), 0);
        assert_eq!(count_leading_zero_bits(0b01000000), 1);
        assert_eq!(count_leading_zero_bits(0b00000001), 7);
        assert_eq!(count_leading_zero_bits(0b00000000), 8);
    }

    #[test]
    fn test_parse_id() {
        assert_eq!(parse_id(&[0x1A, 0x45, 0xDF, 0xA3]), Ok((EMPTY, Id::Ebml)));
        assert_eq!(parse_id(&[0x42, 0x86]), Ok((EMPTY, Id::EbmlVersion)));
        assert_eq!(parse_id(&[0x23, 0x83, 0xE3]), Ok((EMPTY, Id::FrameRate)));

        // 1 byte missing from FrameRate (3-bytes long)
        assert_eq!(parse_id(&[0x23, 0x83]), Err(Error::NeedData));

        // Longer than 4 bytes
        const FAILURE_INPUT: &[u8] = &[0x08, 0x45, 0xDF, 0xA3];
        assert_eq!(parse_id(FAILURE_INPUT), Err(Error::InvalidId));

        // Unknown ID
        let (remaining, id) = parse_id(&[0x19, 0xAB, 0xCD, 0xEF]).unwrap();
        assert_eq!((remaining, &id), (EMPTY, &Id::Unknown(0x19ABCDEF)));
        assert_eq!(serde_yaml::to_string(&id).unwrap().trim(), "'0x19ABCDEF'");
        assert_eq!(id.get_value().unwrap(), 0x19ABCDEF);
    }

    #[test]
    fn test_parse_varint() {
        assert_eq!(parse_varint(&[0x9F]), Ok((EMPTY, Some(31))));
        assert_eq!(parse_varint(&[0x81]), Ok((EMPTY, Some(1))));
        assert_eq!(parse_varint(&[0x53, 0xAC]), Ok((EMPTY, Some(5036))));

        const INVALID_VARINT: &[u8] = &[0x00, 0xAC];
        assert_eq!(parse_varint(INVALID_VARINT), Err(Error::InvalidVarint));

        assert_eq!(parse_varint(UNKNOWN_VARINT), Ok((EMPTY, None)));
    }

    #[test]
    fn test_parse_element_header() {
        const INPUT: &[u8] = &[0x1A, 0x45, 0xDF, 0xA3, 0x9F];
        assert_eq!(
            parse_header(INPUT),
            Ok((EMPTY, Header::new(Id::Ebml, 5, 31)))
        );
    }

    #[test]
    fn test_parse_string() {
        assert_eq!(
            parse_string(&Header::new(Id::DocType, 3, 4), &[0x77, 0x65, 0x62, 0x6D]),
            Ok((EMPTY, "webm".to_string()))
        );

        assert_eq!(
            parse_string(
                &Header::new(Id::DocType, 3, 6),
                &[0x77, 0x65, 0x62, 0x6D, 0x00, 0x00]
            ),
            Ok((EMPTY, "webm".to_string()))
        );

        assert_eq!(
            parse_string(&Header::with_unknown_size(Id::DocType, 3), EMPTY),
            Err(Error::ForbiddenUnknownSize)
        );
    }

    #[test]
    fn test_parse_corrupted() {
        // This integer would have more than 8 bytes.
        // It needs to find a valid 4-byte Element ID, but can't
        // so we get an incomplete.
        assert_eq!(
            parse_element(&[0x42, 0x87, 0x90, 0x01]),
            Err(Error::ForbiddenIntegerSize)
        );

        // Now it finds a Segment.
        const SEGMENT_ID: &[u8] = &[0x18, 0x53, 0x80, 0x67];
        let (remaining, element) =
            parse_element_or_corrupted(&[0x42, 0x87, 0x90, 0x01, 0x18, 0x53, 0x80, 0x67]).unwrap();
        assert_eq!(
            (remaining, &element),
            (
                SEGMENT_ID,
                &Element {
                    header: Header::new(Id::corrupted(), 0, 4),
                    body: Body::Binary(Binary::Corrupted),
                },
            )
        );
        assert!(element.header.id.get_value().is_none());
    }

    #[test]
    fn test_parse_corrupted_unknown_size() {
        // String
        assert_eq!(
            parse_element(&[0x86, 0xFF, 0x56, 0x5F, 0x54]),
            Err(Error::ForbiddenUnknownSize)
        );

        // Binary
        assert_eq!(
            parse_element(&[0x63, 0xA2, 0xFF]),
            Err(Error::ForbiddenUnknownSize)
        );

        // Integer
        assert_eq!(
            parse_element(&[0x42, 0x87, 0xFF, 0x01]),
            Err(Error::ForbiddenUnknownSize)
        );

        // Float
        assert_eq!(
            parse_element(&[0x44, 0x89, 0xFF, 0x01]),
            Err(Error::ForbiddenUnknownSize)
        );
    }

    #[test]
    fn test_parse_int() {
        assert_eq!(
            parse_int(&Header::new(Id::EbmlVersion, 3, 1), &[0x01]),
            Ok((EMPTY, 1u64))
        );
        assert_eq!(
            parse_int::<u64>(&Header::with_unknown_size(Id::EbmlVersion, 3), EMPTY),
            Err(Error::ForbiddenUnknownSize)
        );
        assert_eq!(
            parse_int::<i64>(&Header::with_unknown_size(Id::EbmlVersion, 3), EMPTY),
            Err(Error::ForbiddenUnknownSize)
        );
    }

    #[test]
    fn test_parse_float() {
        assert_eq!(
            parse_float(&Header::new(Id::Duration, 3, 4), &[0x45, 0x7A, 0x30, 0x00]),
            Ok((EMPTY, 4003.))
        );
        assert_eq!(
            parse_float(
                &Header::new(Id::Duration, 3, 8),
                &[0x40, 0xAF, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00]
            ),
            Ok((EMPTY, 4003.))
        );
        assert_eq!(
            parse_float(&Header::new(Id::Duration, 3, 0), EMPTY),
            Ok((EMPTY, 0.))
        );
        assert_eq!(
            parse_float(&Header::new(Id::Duration, 3, 7), EMPTY),
            Err(Error::ForbiddenFloatSize)
        );
        assert_eq!(
            parse_float(&Header::with_unknown_size(Id::Duration, 3), EMPTY),
            Err(Error::ForbiddenUnknownSize)
        );
    }

    #[test]
    fn test_parse_binary() {
        const BODY: &[u8] = &[0x15, 0x49, 0xA9, 0x66];
        assert_eq!(
            parse_binary(&Header::new(Id::SeekId, 3, 4), BODY),
            Ok((EMPTY, Binary::SeekId(Id::Info)))
        );
        assert_eq!(
            parse_binary(&Header::with_unknown_size(Id::SeekId, 3), EMPTY),
            Err(Error::ForbiddenUnknownSize)
        );
    }

    #[test]
    fn test_parse_date() {
        let expected_datetime = DateTime::<Utc>::from_utc(
            NaiveDate::from_ymd_opt(2022, 8, 11)
                .unwrap()
                .and_hms_opt(8, 27, 15)
                .unwrap(),
            Utc,
        );
        assert_eq!(
            parse_date(
                &Header::new(Id::DateUtc, 1, 8),
                &[0x09, 0x76, 0x97, 0xbd, 0xca, 0xc9, 0x1e, 0x00]
            ),
            Ok((EMPTY, expected_datetime))
        )
    }

    #[test]
    fn test_parse_master_element() {
        const INPUT: &[u8] = &[
            0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x86, 0x81, 0x01, 0x42, 0xF7, 0x81, 0x01, 0x42,
            0xF2, 0x81, 0x04, 0x42, 0xF3, 0x81, 0x08, 0x42, 0x82, 0x84, 0x77, 0x65, 0x62, 0x6D,
            0x42, 0x87, 0x81, 0x04, 0x42, 0x85, 0x81, 0x02,
        ];

        let result = parse_element(INPUT);
        assert_eq!(
            result,
            Ok((
                &INPUT[5..],
                Element {
                    header: Header::new(Id::Ebml, 5, 31),
                    body: Body::Master
                }
            ))
        );
    }

    #[test]
    fn test_parse_enumeration() {
        const INPUT: &[u8] = &[0x83, 0x81, 0x01];
        assert_eq!(
            parse_element(INPUT),
            Ok((
                EMPTY,
                Element {
                    header: Header::new(Id::TrackType, 2, 1),
                    body: Body::Unsigned(Unsigned::Enumeration(Enumeration::TrackType(
                        TrackType::Video
                    )))
                }
            ))
        );

        const INPUT_UNKNOWN_ENUMERATION: &[u8] = &[0x83, 0x81, 0xFF];
        let (remaining, element) = parse_element(INPUT_UNKNOWN_ENUMERATION).unwrap();
        assert_eq!(
            (remaining, &element),
            (
                EMPTY,
                &Element {
                    header: Header::new(Id::TrackType, 2, 1),
                    body: Body::Unsigned(Unsigned::Standard(255))
                }
            )
        );
        assert_eq!(
            serde_yaml::to_string(&element).unwrap().trim(),
            "id: TrackType\nheader_size: 2\nsize: 3\nvalue: 255"
        );
    }

    #[test]
    fn test_parse_seek_id() {
        assert_eq!(
            parse_element(&[0x53, 0xAB, 0x84, 0x15, 0x49, 0xA9, 0x66]),
            Ok((
                EMPTY,
                Element {
                    header: Header::new(Id::SeekId, 3, 4),
                    body: Body::Binary(Binary::SeekId(Id::Info))
                }
            ))
        );
    }

    #[test]
    fn test_parse_crc32() {
        assert_eq!(
            parse_element(&[0xBF, 0x84, 0xAF, 0x93, 0x97, 0x18]),
            Ok((
                EMPTY,
                Element {
                    header: Header::new(Id::Crc32, 2, 4),
                    body: Body::Binary(Binary::Standard("[af 93 97 18]".into()))
                }
            ))
        );
    }

    #[test]
    fn test_parse_empty() {
        assert_eq!(
            parse_element(&[0x63, 0xC0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
            Ok((
                EMPTY,
                Element {
                    header: Header::new(Id::Targets, 10, 0),
                    body: Body::Master
                }
            ))
        );
    }

    #[test]
    fn test_parse_block() {
        assert_eq!(
            parse_block(&[0x81, 0x0F, 0x7A, 0x00]),
            Ok((
                EMPTY,
                Block {
                    track_number: 1,
                    timestamp: 3962,
                    invisible: false,
                    lacing: None,
                    num_frames: None
                }
            ))
        );

        assert_eq!(parse_block(UNKNOWN_VARINT), Err(Error::MissingTrackNumber));
    }

    #[test]
    fn test_parse_simple_block() {
        assert_eq!(
            parse_simple_block(&[0x81, 0x00, 0x53, 0x00]),
            Ok((
                EMPTY,
                SimpleBlock {
                    track_number: 1,
                    timestamp: 83,
                    keyframe: false,
                    invisible: false,
                    lacing: None,
                    discardable: false,
                    num_frames: None,
                }
            ))
        );

        assert_eq!(
            parse_simple_block(UNKNOWN_VARINT),
            Err(Error::MissingTrackNumber)
        );
    }

    #[test]
    fn test_peek_standard_binary() -> Result<()> {
        let input = &[1, 2, 3];
        assert_eq!(peek_standard_binary(input, 3)?.1, "[01 02 03]");

        let input = &[0; 5];
        assert_eq!(peek_standard_binary(input, 65)?.1, "65 bytes");
        Ok(())
    }

    #[test]
    fn test_serialize_enumeration() {
        assert_eq!(
            serde_yaml::to_string(&Enumeration::TrackType(TrackType::Video))
                .unwrap()
                .trim(),
            "video"
        );
        assert_eq!(
            serde_yaml::to_string(&Unsigned::Standard(5))
                .unwrap()
                .trim(),
            "5"
        );
    }

    #[test]
    fn test_parse_corrupt() {
        // can not find a valid sync id in  a bonkers array, so it should consume the
        // entire buffer
        assert_eq!(
            parse_corrupt(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
            Ok((
                EMPTY,
                Element {
                    header: Header::new(Id::corrupted(), 0, 10),
                    body: Body::Binary(Binary::Corrupted)
                }
            ))
        );
    }
}