raves_metadata 0.0.4

A library to parse metadata from media files
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
//! Types for the building "blocks" of GIF files.

use winnow::{Parser, binary::le_u16, binary::u8, error::EmptyError, token::take};

use super::error::GifConstructionError;

/// the magic number should be `b"GIF"`.
pub(super) fn signature(input: &mut &[u8]) -> Result<(), GifConstructionError> {
    log::trace!("Parsing: signature.");

    let bytes: [u8; 3] = take::<_, _, EmptyError>(3_usize)
        .parse_next(input)
        .ok()
        .and_then(|arr| TryInto::<[u8; 3]>::try_into(arr).ok())
        .ok_or_else(|| {
            log::error!("Not enough bytes in the data stream to find magic number!");
            GifConstructionError::NoMagicNumber
        })?;

    // check that it's not ewird
    if bytes != *b"GIF" {
        log::error!("Got a weird magic number -- not a GIF.");
        return Err(GifConstructionError::WeirdMagicNumber(bytes));
    }

    // all good. return nothing
    Ok(())
}

/// Parses a Data Sub-Block.
pub(super) fn data_sub_block(
    input: &mut &[u8],
    output: &mut Vec<u8>,
) -> Result<(), GifConstructionError> {
    log::trace!("Parsing: data sub-block.");

    // grab sub-block data
    let slice: &[u8] = u8
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::warn!("No block size for data sub-block!"))
        .and_then(|block_size: u8| {
            take(block_size).parse_next(input).inspect_err(|_e| {
                log::warn!("Failed to take {block_size} bytes for data sub-block!")
            })
        })
        .map_err(|_e: EmptyError| GifConstructionError::NotEnoughBytes)?;

    // add that to the output list
    output.extend_from_slice(slice);

    // return a happy result
    Ok(())
}

/// Parses a Block Terminator.
pub(super) fn block_terminator(input: &mut &[u8]) -> Result<(), GifConstructionError> {
    // grab the next byte
    let byte: u8 = u8
        .parse_next(input)
        .map_err(|_e: EmptyError| GifConstructionError::NotEnoughBytes)
        .inspect_err(|_e| log::warn!("Failed to parse block terminator! (no byte found)"))?;

    // byte must be 0x00
    if byte != 0x00 {
        return Err(GifConstructionError::BlockTerminatorMismatch(byte));
    }

    Ok(())
}

#[derive(Clone, Debug)]
pub struct GifHeader {
    pub version: [u8; 3],
}

/// Parses the GIF's Header.
pub(super) fn header(input: &mut &[u8]) -> Result<GifHeader, GifConstructionError> {
    fn gif_version(input: &mut &[u8]) -> Result<[u8; 3], GifConstructionError> {
        // grab the first three bytes
        let arr: [u8; 3] = take::<_, _, EmptyError>(3_usize)
            .parse_next(input)
            .ok()
            .and_then(|arr| TryInto::<[u8; 3]>::try_into(arr).ok())
            .ok_or_else(|| {
                log::error!("Not enough bytes for GIF version.");
                GifConstructionError::NoGifVersion
            })?;

        // warn user if it's an unexpected value
        if ![b"87a", b"89a"].contains(&&arr) {
            let chars: [char; 3] = arr.map(char::from);
            log::warn!("Unknown GIF version provided: `{chars:?}`");
        }

        Ok(arr)
    }

    // ck signature (`GIF`)
    signature(input)?;

    // grab version
    let version: [u8; 3] = gif_version(input)?;

    // return a header
    Ok(GifHeader { version })
}

#[derive(Clone, Debug)]
pub struct LogicalScreenDescriptor {
    pub logical_screen_width: u16,

    pub logical_screen_height: u16,

    pub global_color_table_flag: bool,
    pub color_resolution: u8, // range: 1..=4
    pub sort_flag: bool,
    pub size_of_global_color_table: u8,

    pub background_color_index: u8,
    pub pixel_aspect_ratio: Option<u8>,
}

/// Parses the Logical Screen Descriptor.
pub(super) fn logical_screen_descriptor(
    input: &mut &[u8],
) -> Result<LogicalScreenDescriptor, GifConstructionError> {
    log::trace!("Parsing: logical screen descriptor.");

    let logical_screen_width: u16 = le_u16
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| {
            log::warn!("Logical screen descriptor didn't contain logical screen width!")
        })
        .map_err(|_e: EmptyError| GifConstructionError::LogicalScreenDescriptorMissingData)?;

    let logical_screen_height: u16 = le_u16
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| {
            log::warn!("Logical screen descriptor didn't contain logical screen height!")
        })
        .map_err(|_e: EmptyError| GifConstructionError::LogicalScreenDescriptorMissingData)?;

    let packed: u8 = u8
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::warn!("Logical screen descriptor has no packed field!"))
        .map_err(|_e: EmptyError| GifConstructionError::LogicalScreenDescriptorMissingData)?;
    let global_color_table_flag: bool = (packed & 0b1000_0000) == 0b1000_0000;
    let color_resolution: u8 = ((packed & 0b0111_0000) >> 4) + 1;
    let sort_flag: bool = (packed & 0b0000_1000) == 0b0000_1000;
    let size_of_global_color_table: u8 = packed & 0b0000_0111;

    let background_color_index: u8 = u8
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| {
            log::warn!("Logical screen descriptor has no background color index!")
        })
        .map_err(|_e: EmptyError| GifConstructionError::LogicalScreenDescriptorMissingData)?;

    let pixel_aspect_ratio: u8 = u8
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| {
            log::warn!("Logical screen descriptor has no pixel aspect ratio!")
        })
        .map_err(|_e: EmptyError| GifConstructionError::LogicalScreenDescriptorMissingData)?;

    Ok(LogicalScreenDescriptor {
        logical_screen_width,
        logical_screen_height,
        global_color_table_flag,
        color_resolution,
        sort_flag,
        size_of_global_color_table,
        background_color_index,
        pixel_aspect_ratio: if pixel_aspect_ratio == 0 {
            None
        } else {
            Some(pixel_aspect_ratio)
        },
    })
}

#[derive(Clone, Debug)]
pub struct GlobalColorTable {
    pub rgb_triplets: Vec<(u8, u8, u8)>,
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum GctMissingColor {
    Red,
    Green,
    Blue,
}

/// Parses the Global Color Table.
///
/// Only present if `LogicalScreenDescriptor.global_color_table_flag` is
/// `true`.
pub(super) fn global_color_table(
    size_of_global_color_table: u8,
    input: &mut &[u8],
) -> Result<GlobalColorTable, GifConstructionError> {
    log::trace!("Parsing: global color table.");

    let triplet_ct: u16 = 2_u16.pow(size_of_global_color_table as u32 + 1_u32);
    let mut v: Vec<(u8, u8, u8)> = Vec::with_capacity(triplet_ct as usize);

    // define color getter (helper closure)
    let mut get_color =
        |color_name: &'static str, color: GctMissingColor, triplet_num: u16| {
            u8.parse_next(input)
            .inspect_err(|_e: &EmptyError| {
                log::warn!(
                    "Global color table missing {color_name} at triplet {triplet_num}/{triplet_ct}!"
                )
            })
            .map_err(|_e: EmptyError| GifConstructionError::GlobalColorTableMissingTriplet {
                expected_triplet_ct: triplet_ct,
                errant_triplet: triplet_num as u8,
                missing_color: color,
            })
        };

    // find and set each triplet
    for triplet_num in 0..triplet_ct {
        // grab each color in triplet
        let (red, green, blue): (u8, u8, u8) = (
            get_color("red", GctMissingColor::Red, triplet_num)?,
            get_color("green", GctMissingColor::Green, triplet_num)?,
            get_color("blue", GctMissingColor::Blue, triplet_num)?,
        );

        // set in the list
        v.insert(triplet_num as usize, (red, green, blue));
    }

    Ok(GlobalColorTable { rgb_triplets: v })
}

#[derive(Clone, Debug)]
pub struct ImageDescriptor {
    pub image_left_position: u16,

    pub image_top_position: u16,

    pub image_width: u16,

    pub image_height: u16,

    pub local_color_table_flag: bool,
    pub interlace_flag: bool,
    pub sort_flag: bool,

    pub size_of_local_color_table: u8,
}

/// Parses the Image Descriptor block.
pub(super) fn image_descriptor(input: &mut &[u8]) -> Result<ImageDescriptor, GifConstructionError> {
    log::trace!("Parsing: image descriptor.");

    // grab and check image separator (constant value)
    const IMAGE_SEPARATOR: u8 = 0x2c;
    let image_separator: u8 = u8
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::error!("Image descriptor had no image separator!"))
        .map_err(|_e: EmptyError| GifConstructionError::ImageDescriptorNoSeparator)?;
    if image_separator != IMAGE_SEPARATOR {
        log::error!(
            "Image descriptor had wrong image separator! \
            got: `0x{image_separator:x}`, expected: 0x{IMAGE_SEPARATOR:x} "
        );
        return Err(GifConstructionError::ImageDescriptorSeparatorWrong(
            image_separator,
        ));
    }

    // image left position
    let image_left_position: u16 = le_u16
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::error!("Image descriptor had no image left position!"))
        .map_err(|_e: EmptyError| GifConstructionError::ImageDescriptorMissingData)?;

    // image top position
    let image_top_position: u16 = le_u16
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::error!("Image descriptor had no image top position!"))
        .map_err(|_e: EmptyError| GifConstructionError::ImageDescriptorMissingData)?;

    // image width
    let image_width: u16 = le_u16
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::error!("Image descriptor had no image width!"))
        .map_err(|_e: EmptyError| GifConstructionError::ImageDescriptorMissingData)?;

    // image height
    let image_height: u16 = le_u16
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::error!("Image descriptor had no image height!"))
        .map_err(|_e: EmptyError| GifConstructionError::ImageDescriptorMissingData)?;

    let packed: u8 = u8
        .parse_next(input)
        .inspect_err(|_e: &EmptyError| log::error!("Image descriptor had no packed field!"))
        .map_err(|_e: EmptyError| GifConstructionError::ImageDescriptorMissingData)?;

    let local_color_table_flag: bool = packed & 0b1000_0000 == 0b1000_0000;
    let interlace_flag: bool = packed & 0b0100_0000 == 0b0100_0000;
    let sort_flag: bool = packed & 0b0010_0000 == 0b0010_0000;
    let _reserved = ();
    let size_of_local_color_table: u8 = packed & 0b0000_0111;

    Ok(ImageDescriptor {
        image_left_position,
        image_top_position,
        image_width,
        image_height,
        local_color_table_flag,
        interlace_flag,
        sort_flag,
        size_of_local_color_table,
    })
}

pub type LocalColorTable = GlobalColorTable;

/// Parses the Local Color Table block.
pub(super) fn local_color_table(
    size: u8,
    input: &mut &[u8],
) -> Result<LocalColorTable, GifConstructionError> {
    log::trace!("Parsing: local color table.");
    global_color_table(size, input)
}

/// Parses table-based image data.
pub(super) fn table_based_image_data(input: &mut &[u8]) -> Result<(), GifConstructionError> {
    log::trace!("Parsing: table-based image data.");

    let _lzw_min_code_size: u8 = u8.parse_next(input).map_err(|_e: EmptyError| {
        log::error!("Table-based image data is missing its LWZ minimum code size field!");
        GifConstructionError::TableBasedImageDataNoLzw
    })?;

    // parse sub-blocks til we find the terminator.
    //
    // TODO: store offsets/indices for later rewriting
    let mut _buf: Vec<u8> = vec![];
    while let Some(b) = input.first()
        && *b != 0x00
    {
        data_sub_block(input, &mut _buf)?;
    }

    // eat the terminator
    block_terminator.parse_next(input)?;

    Ok(())
}

#[derive(Clone, Debug)]
pub struct GraphicControlExtension {
    pub disposal_method: u8,
    pub user_input_flag: bool,
    pub transparent_color_flag: bool,

    pub delay_time: u16,

    pub transparent_color_index: u8,
}

pub(super) fn graphic_control_extension(
    input: &mut &[u8],
) -> Result<GraphicControlExtension, GifConstructionError> {
    log::trace!("Parsing: graphic control extension.");

    // extension introducer
    helpers::extension_introducer.parse_next(input)?;

    // extension label
    helpers::extension_label(input, "Graphic Control Extension", 0xF9)?;

    // block size
    {
        let block_size = helpers::block_size.parse_next(input)?;
        if block_size != 4 {
            log::error!(
                "Graphic control extension had incorrect block size!\
            expected: `4`, got: `{block_size}`"
            );
            return Err(GifConstructionError::GraphicExtMissingData);
        };
    }

    let packed: u8 = u8
        .parse_next(input)
        .map_err(|_: EmptyError| GifConstructionError::GraphicExtMissingData)
        .inspect_err(|_| log::error!("Graphic control extension missing packed field!"))?;
    let disposal_method: u8 = (packed & 0b0011_1000) >> 3;
    let user_input_flag: bool = (packed & 0b0100_0000) == 0b0100_0000;
    let transparent_color_flag: bool = (packed & 0b1000_0000) == 0b1000_0000;

    let delay_time: u16 = le_u16.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Graphic control extension is missing delay time!");
        GifConstructionError::GraphicExtMissingData
    })?;

    let transparent_color_index: u8 = u8.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Graphic control extension is missing transparent color index!");
        GifConstructionError::GraphicExtMissingData
    })?;

    block_terminator.parse_next(input).inspect_err(|_| {
        log::error!("Graphic control extension is missing block terminator!");
    })?;

    Ok(GraphicControlExtension {
        disposal_method,
        user_input_flag,
        transparent_color_flag,
        delay_time,
        transparent_color_index,
    })
}

#[derive(Clone, Debug)]
pub struct CommentExtension {
    pub data: Vec<u8>,
}

/// Parses a Comment Extension block.
pub(super) fn comment_extension(
    input: &mut &[u8],
) -> Result<CommentExtension, GifConstructionError> {
    log::trace!("Parsing: comment extension.");

    // extension introducer
    helpers::extension_introducer.parse_next(input)?;

    // extension label
    helpers::extension_label(input, "Comment Extension", 0xFE)?;

    // keep reading subblock til we find the terminator
    let mut buf: Vec<u8> = Vec::new();
    while input[0] != 0x00 {
        data_sub_block(input, &mut buf)?;
    }

    block_terminator(input)?;

    Ok(CommentExtension { data: buf })
}

#[derive(Clone, Debug)]
pub struct PlainTextExtension {
    pub text_grid_left_position: u16,
    pub text_grid_top_position: u16,
    pub text_grid_width: u16,
    pub text_grid_height: u16,

    pub character_cell_width: u8,
    pub character_cell_height: u8,

    pub text_foreground_color_index: u8,
    pub text_background_color_index: u8,

    pub plain_text_data: Vec<u8>,
}

/// Parses a Plain Text Extension block.
pub(super) fn plain_text_extension(
    input: &mut &[u8],
) -> Result<PlainTextExtension, GifConstructionError> {
    log::trace!("Parsing: plain text extension.");

    // extension introducer
    helpers::extension_introducer.parse_next(input)?;

    // plain text label (0x01)
    helpers::extension_label(input, "Plain Text Extension", 0x01)?;

    // block size
    match helpers::block_size(input) {
        Err(e) => return Err(e),
        Ok(12) => (),
        Ok(other) => {
            log::error!(
                "Plain text extension had a wrong block size! \
                Expected `12`, got `{other}`."
            );
            return Err(GifConstructionError::ExtensionHasWeirdBlockSize {
                got: other,
                expected: 12_u8,
            });
        }
    };

    let text_grid_left_position: u16 = le_u16.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing text grid left position.");
        GifConstructionError::PlainTextExtMissingData
    })?;
    let text_grid_top_position: u16 = le_u16.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing text grid top position.");
        GifConstructionError::PlainTextExtMissingData
    })?;
    let text_grid_width: u16 = le_u16.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing text grid width.");
        GifConstructionError::PlainTextExtMissingData
    })?;
    let text_grid_height: u16 = le_u16.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing text grid height.");
        GifConstructionError::PlainTextExtMissingData
    })?;

    let character_cell_width: u8 = u8.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing character cell width.");
        GifConstructionError::PlainTextExtMissingData
    })?;
    let character_cell_height: u8 = u8.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing character cell height.");
        GifConstructionError::PlainTextExtMissingData
    })?;

    let text_foreground_color_index: u8 = u8.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing text foreground color index.");
        GifConstructionError::PlainTextExtMissingData
    })?;
    let text_background_color_index: u8 = u8.parse_next(input).map_err(|_: EmptyError| {
        log::error!("Plain text extension missing text background color index.");
        GifConstructionError::PlainTextExtMissingData
    })?;

    // actually read the text data
    let mut plain_text_data: Vec<u8> = vec![];
    while let Some(b) = input.first()
        && *b != 0x00
    {
        data_sub_block(input, &mut plain_text_data)?;
    }

    // finally, eat the block terminator
    block_terminator.parse_next(input)?;

    Ok(PlainTextExtension {
        text_grid_left_position,
        text_grid_top_position,
        text_grid_width,
        text_grid_height,
        character_cell_width,
        character_cell_height,
        text_foreground_color_index,
        text_background_color_index,
        plain_text_data,
    })
}

#[derive(Clone, Debug)]
pub struct ApplicationExtension {
    pub application_identifier: [u8; 8],
    pub application_authentication_code: [u8; 3],
    pub application_data: Vec<u8>,
}

/// Parses an Application Extension block.
pub(super) fn application_extension(
    input: &mut &[u8],
) -> Result<ApplicationExtension, GifConstructionError> {
    log::trace!("Parsing: application extension.");

    // extension introducer
    helpers::extension_introducer.parse_next(input)?;

    // extension label
    helpers::extension_label(input, "Application Extension", 0xFF)?;

    // block size
    {
        let block_size: u8 = helpers::block_size.parse_next(input)?;
        if block_size != 11 {
            log::error!(
                "App extension had incorrect block size!\
            expected: `11`, got: `{block_size}`"
            );
            return Err(GifConstructionError::AppExtMissingData);
        }
    }

    // application ident
    let app_ident: [u8; 8] = take(8_usize)
        .parse_next(input)
        .map_err(|_: EmptyError| GifConstructionError::AppExtMissingData)
        .and_then(|slice: &[u8]| -> Result<[u8; 8], GifConstructionError> {
            TryFrom::try_from(slice).map_err(|_| GifConstructionError::AppExtMissingData)
        })
        .inspect_err(|_| log::error!("App extension missing application identifier!"))?;

    // application auth code
    let app_auth_code: [u8; 3] = take(3_usize)
        .parse_next(input)
        .map_err(|_: EmptyError| GifConstructionError::AppExtMissingData)
        .and_then(|slice: &[u8]| -> Result<[u8; 3], GifConstructionError> {
            TryFrom::try_from(slice).map_err(|_| GifConstructionError::AppExtMissingData)
        })
        .inspect_err(|_| log::error!("App extension missing application auth code!"))?;

    // non-compliant writers can omit the subblocks and just use a "raw" byte
    // stream.
    //
    // soo, prepare for that, too
    if app_ident == *b"XMP Data" && app_auth_code == *b"XMP" {
        const MAGIC_TRAILER_NO_BLOCK_TERMINATOR: [u8; 257] = {
            let mut arr: [u8; 257] = [0x00; 257];

            arr[0] = 0x01;

            let mut idx: usize = 1;
            let mut k: u8 = 0xFF;
            loop {
                arr[idx] = k;
                idx += 1;
                if k == 0x00 {
                    break;
                }
                k -= 1;
            }

            arr
        };

        let remaining: &[u8] = input;
        if let Some(trailer_start) = remaining
            .windows(MAGIC_TRAILER_NO_BLOCK_TERMINATOR.len())
            .position(|window| window == MAGIC_TRAILER_NO_BLOCK_TERMINATOR)
        {
            let data_end: usize = trailer_start + MAGIC_TRAILER_NO_BLOCK_TERMINATOR.len();
            let application_data: Vec<u8> = remaining[..data_end].to_vec();
            *input = &remaining[data_end..];

            // eat gif block terminator after the raw XMP payload
            block_terminator(input)?;

            return Ok(ApplicationExtension {
                application_identifier: app_ident,
                application_authentication_code: app_auth_code,
                application_data,
            });
        }
    }

    // read data sub-blocks until we reach this block's terminator
    let mut buf: Vec<u8> = Vec::new();
    while input[0] != 0x00 {
        data_sub_block(input, &mut buf)?;
    }

    // end with block terminator
    block_terminator(input)?;

    Ok(ApplicationExtension {
        application_identifier: app_ident,
        application_authentication_code: app_auth_code,
        application_data: buf,
    })
}

/// Parses the Trailer block.
pub(super) fn trailer(input: &mut &[u8]) -> Result<(), GifConstructionError> {
    let value: u8 = u8
        .parse_next(input)
        .map_err(|_: EmptyError| GifConstructionError::TrailerMissing)
        .inspect_err(|_| log::error!("Trailer block is completely missing!"))?;

    if value != 0x3b {
        log::error!(
            "Found an unexpected trailer value. \
            Found `0x{value:x}`, but expected `0x3b`. \
            This is an implementation problem, so please report this message it as a bug!"
        );
        return Err(GifConstructionError::TrailerMissing);
    }

    Ok(())
}

pub(super) mod helpers {
    use winnow::{Parser, binary::u8, error::EmptyError};

    use super::super::error::GifConstructionError;

    /// Parses out an Extension Introducer.
    pub fn extension_introducer(input: &mut &[u8]) -> Result<(), GifConstructionError> {
        log::trace!("Parsing: extension introducer.");

        let extension_introducer: u8 = u8
            .parse_next(input)
            .map_err(|_: EmptyError| GifConstructionError::NotEnoughBytes)
            .inspect_err(|_| log::error!("Extension missing introducer!"))?;

        if extension_introducer != 0x21 {
            log::error!(
                "Extension had incorrect introducer! \
            expected: `0x21`, got: `0x{extension_introducer:x}`. \
            This is a bug. Please report it on GitHub."
            );
            return Err(GifConstructionError::NotEnoughBytes);
        }

        Ok(())
    }

    /// Parses out a label for the given extension type.
    pub fn extension_label(
        input: &mut &[u8],
        extension_type: &'static str,
        expected_label_value: u8,
    ) -> Result<(), GifConstructionError> {
        log::trace!("Parsing: extension label.");

        let extension_label: u8 = u8
            .parse_next(input)
            .map_err(|_: EmptyError| GifConstructionError::NotEnoughBytes)
            .inspect_err(|_| log::error!("{extension_type} missing label!"))?;

        if extension_label != expected_label_value {
            log::error!(
                "{extension_type} had incorrect label! \
            expected: `0x{expected_label_value:x}`, got: `0x{extension_label:x}`"
            );
            return Err(GifConstructionError::UnknownExtensionFound {
                label: extension_label,
            });
        }

        Ok(())
    }

    /// Parses out the block size byte for an extension block.
    pub fn block_size(input: &mut &[u8]) -> Result<u8, GifConstructionError> {
        log::trace!("Parsing: block size.");

        u8.parse_next(input).map_err(|_: EmptyError| {
            log::error!("Graphic control extension missing block size!");
            GifConstructionError::NotEnoughBytes
        })
    }
}