mp4forge 0.8.0

Rust library and CLI for inspecting, probing, extracting, muxing, and rewriting MP4 structures
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
//! Depth-first box traversal with path tracking and lazy payload access.

use std::error::Error;
use std::fmt;
#[cfg(feature = "async")]
use std::future::Future;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::ops::Deref;
#[cfg(feature = "async")]
use std::pin::Pin;
use std::str::FromStr;

use crate::FourCc;
#[cfg(feature = "async")]
use crate::async_io::{AsyncReadSeek, AsyncWrite};
use crate::boxes::iso14496_12::{
    AudioSampleEntry, Ftyp, VisualSampleEntry, split_box_children_with_optional_trailing_bytes,
};
use crate::boxes::metadata::Keys;
use crate::boxes::{BoxLookupContext, BoxRegistry, default_registry};
#[cfg(feature = "async")]
use crate::codec::unmarshal_any_with_context_async;
use crate::codec::{CodecError, DynCodecBox, unmarshal, unmarshal_any_with_context};
use crate::fourcc::ParseFourCcError;
use crate::header::{BoxInfo, HeaderError, SMALL_HEADER_SIZE};
#[cfg(feature = "async")]
use tokio::io::{AsyncReadExt, AsyncSeekExt};

const FTYP: FourCc = FourCc::from_bytes(*b"ftyp");
const KEYS: FourCc = FourCc::from_bytes(*b"keys");
const QT_BRAND: FourCc = FourCc::from_bytes(*b"qt  ");
const ROOT_MARKER: &str = "<root>";
const WILDCARD_SEGMENT: &str = "*";

/// Depth-first traversal decision returned by a walk visitor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WalkControl {
    /// Skip the current box children and continue with the next sibling.
    Continue,
    /// Expand the current box and visit its children before the next sibling.
    Descend,
}

/// Ordered sequence of box identifiers from the root to the current box.
///
/// Path comparisons used by the extraction and rewrite helpers honor [`FourCc::ANY`] as a
/// wildcard segment.
///
/// In addition to low-level array-based construction, paths can be parsed from slash-delimited
/// strings such as `moov/trak/tkhd`. The segment `*` maps to [`FourCc::ANY`], and the string
/// `<root>` maps to the empty path.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BoxPath(Vec<FourCc>);

impl BoxPath {
    /// Creates an empty path.
    pub const fn empty() -> Self {
        Self(Vec::new())
    }

    /// Returns the path as a borrowed slice.
    pub fn as_slice(&self) -> &[FourCc] {
        &self.0
    }

    /// Returns `true` when the path contains no box identifiers.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of box identifiers in the path.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Parses a slash-delimited path string into a [`BoxPath`].
    ///
    /// Each non-wildcard segment must contain exactly four bytes and is parsed using
    /// [`FourCc::from_str`]. The segment `*` maps to [`FourCc::ANY`], and `<root>` returns the
    /// empty path.
    pub fn parse(value: &str) -> Result<Self, ParseBoxPathError> {
        if value == ROOT_MARKER {
            return Ok(Self::empty());
        }

        let mut path = Vec::new();
        for (index, segment) in value.split('/').enumerate() {
            if segment.is_empty() {
                return Err(ParseBoxPathError::EmptySegment { index });
            }
            if segment == ROOT_MARKER {
                return Err(ParseBoxPathError::RootMarkerMustAppearAlone);
            }
            if segment == WILDCARD_SEGMENT {
                path.push(FourCc::ANY);
                continue;
            }

            let box_type =
                FourCc::try_from(segment).map_err(|source| ParseBoxPathError::InvalidSegment {
                    index,
                    segment: segment.to_owned(),
                    source,
                })?;
            path.push(box_type);
        }

        Ok(Self(path))
    }

    fn child_path(&self, box_type: FourCc) -> Self {
        let mut path = self.0.clone();
        path.push(box_type);
        Self(path)
    }

    pub(crate) fn compare_with(&self, other: &Self) -> PathMatch {
        if self.len() > other.len() {
            return PathMatch::default();
        }

        for (lhs, rhs) in self.iter().zip(other.iter()) {
            if !lhs.matches(*rhs) {
                return PathMatch::default();
            }
        }

        if self.len() < other.len() {
            return PathMatch {
                forward_match: true,
                exact_match: false,
            };
        }

        PathMatch {
            forward_match: false,
            exact_match: true,
        }
    }
}

impl Deref for BoxPath {
    type Target = [FourCc];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl fmt::Display for BoxPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            return f.write_str("<root>");
        }

        for (index, box_type) in self.0.iter().enumerate() {
            if index != 0 {
                f.write_str("/")?;
            }
            write!(f, "{box_type}")?;
        }

        Ok(())
    }
}

impl From<Vec<FourCc>> for BoxPath {
    fn from(value: Vec<FourCc>) -> Self {
        Self(value)
    }
}

impl TryFrom<&str> for BoxPath {
    type Error = ParseBoxPathError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl<const N: usize> From<[FourCc; N]> for BoxPath {
    fn from(value: [FourCc; N]) -> Self {
        Self(value.into())
    }
}

impl FromIterator<FourCc> for BoxPath {
    fn from_iter<T: IntoIterator<Item = FourCc>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl FromStr for BoxPath {
    type Err = ParseBoxPathError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Error returned when a string cannot be parsed as a [`BoxPath`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParseBoxPathError {
    /// One segment between path separators was empty.
    EmptySegment {
        /// Zero-based index of the empty segment.
        index: usize,
    },
    /// One segment was neither `*` nor a valid four-byte [`FourCc`].
    InvalidSegment {
        /// Zero-based index of the invalid segment.
        index: usize,
        /// Original segment text from the parsed path string.
        segment: String,
        /// Underlying four-character-code parse failure.
        source: ParseFourCcError,
    },
    /// The special `<root>` marker was combined with additional segments.
    RootMarkerMustAppearAlone,
}

impl fmt::Display for ParseBoxPathError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptySegment { index } => {
                write!(f, "box path segment {} must not be empty", index + 1)
            }
            Self::InvalidSegment {
                index,
                segment,
                source,
            } => write!(
                f,
                "invalid box path segment {} ({segment:?}): {source}",
                index + 1
            ),
            Self::RootMarkerMustAppearAlone => {
                write!(f, "box path root marker {ROOT_MARKER:?} must appear alone")
            }
        }
    }
}

impl Error for ParseBoxPathError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::InvalidSegment { source, .. } => Some(source),
            Self::EmptySegment { .. } | Self::RootMarkerMustAppearAlone => None,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct PathMatch {
    pub(crate) forward_match: bool,
    pub(crate) exact_match: bool,
}

/// Visitor view of one box during a depth-first structure walk.
pub struct WalkHandle<'a, R> {
    reader: &'a mut R,
    registry: &'a BoxRegistry,
    info: BoxInfo,
    path: BoxPath,
    descendant_lookup_context: BoxLookupContext,
    children_layout: Option<ChildrenLayout>,
}

/// Boxed future type used by closure-based async walk visitors.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub type AsyncWalkFuture<'a> =
    Pin<Box<dyn Future<Output = Result<WalkControl, WalkError>> + Send + 'a>>;

/// Tokio-based async visitor view of one box during a depth-first structure walk.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub struct AsyncWalkHandle<'a, R> {
    reader: &'a mut R,
    registry: &'a BoxRegistry,
    info: BoxInfo,
    path: BoxPath,
    descendant_lookup_context: BoxLookupContext,
    children_layout: Option<ChildrenLayout>,
}

/// Async visitor interface for the Tokio-based structure walker.
///
/// The first async traversal rollout keeps the existing visitor-driven depth-first walk model but
/// allows the visitor to await payload decode or raw byte reads on the current box.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub trait AsyncWalkVisitor<R>
where
    R: AsyncReadSeek,
    Self: Send,
{
    /// Future returned for one visited box.
    type Future<'a>: Future<Output = Result<WalkControl, WalkError>> + Send + 'a
    where
        Self: 'a,
        R: 'a;

    /// Visits one box and decides whether the walker should descend into its children.
    fn visit<'a, 'r>(&'a mut self, handle: &'a mut AsyncWalkHandle<'r, R>) -> Self::Future<'a>
    where
        'r: 'a;
}

#[cfg(feature = "async")]
impl<R, F> AsyncWalkVisitor<R> for F
where
    R: AsyncReadSeek,
    F: Send + for<'a, 'r> FnMut(&'a mut AsyncWalkHandle<'r, R>) -> AsyncWalkFuture<'a>,
{
    type Future<'a>
        = AsyncWalkFuture<'a>
    where
        Self: 'a,
        R: 'a;

    fn visit<'a, 'r>(&'a mut self, handle: &'a mut AsyncWalkHandle<'r, R>) -> Self::Future<'a>
    where
        'r: 'a,
    {
        self(handle)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ChildrenLayout {
    offset: u64,
    size: u64,
}

impl<'a, R> WalkHandle<'a, R>
where
    R: Read + Seek,
{
    /// Returns the header metadata for the current box.
    pub const fn info(&self) -> &BoxInfo {
        &self.info
    }

    /// Returns the depth-first path to the current box.
    pub fn path(&self) -> &BoxPath {
        &self.path
    }

    /// Returns the lookup context that will apply to direct children of this box.
    pub const fn descendant_lookup_context(&self) -> BoxLookupContext {
        self.descendant_lookup_context
    }

    /// Returns `true` when the current box type is registered in the active lookup context.
    pub fn is_supported_type(&self) -> bool {
        self.registry
            .is_registered_with_context(self.info.box_type(), self.info.lookup_context())
    }

    /// Decodes the current payload into a descriptor-backed runtime box value.
    pub fn read_payload(&mut self) -> Result<(Box<dyn DynCodecBox>, u64), WalkError> {
        validate_box_fits_stream(self.reader, &self.info)?;
        self.info.seek_to_payload(self.reader)?;
        let payload_size = self.info.payload_size()?;
        let (boxed, read) = unmarshal_any_with_context(
            self.reader,
            payload_size,
            self.info.box_type(),
            self.registry,
            self.info.lookup_context(),
            None,
        )?;
        self.children_layout = Some(children_layout_for_payload(
            self.reader,
            &self.info,
            payload_size,
            read,
            boxed.as_ref(),
        )?);
        Ok((boxed, read))
    }

    /// Copies the raw payload bytes into `writer` without decoding them.
    pub fn read_data<W>(&mut self, writer: &mut W) -> Result<u64, WalkError>
    where
        W: Write,
    {
        validate_box_fits_stream(self.reader, &self.info)?;
        self.info.seek_to_payload(self.reader)?;
        let payload_size = self.info.payload_size()?;
        let mut limited = (&mut *self.reader).take(payload_size);
        io::copy(&mut limited, writer).map_err(WalkError::Io)
    }

    fn ensure_children_layout(&mut self) -> Result<ChildrenLayout, WalkError> {
        if let Some(children_layout) = self.children_layout {
            return Ok(children_layout);
        }

        self.read_payload()?;
        if let Some(children_layout) = self.children_layout {
            Ok(children_layout)
        } else {
            unreachable!("read_payload always computes children layout")
        }
    }
}

#[cfg(feature = "async")]
impl<'a, R> AsyncWalkHandle<'a, R>
where
    R: AsyncReadSeek,
{
    /// Returns the header metadata for the current box.
    pub const fn info(&self) -> &BoxInfo {
        &self.info
    }

    /// Returns the depth-first path to the current box.
    pub fn path(&self) -> &BoxPath {
        &self.path
    }

    /// Returns the lookup context that will apply to direct children of this box.
    pub const fn descendant_lookup_context(&self) -> BoxLookupContext {
        self.descendant_lookup_context
    }

    /// Returns `true` when the current box type is registered in the active lookup context.
    pub fn is_supported_type(&self) -> bool {
        self.registry
            .is_registered_with_context(self.info.box_type(), self.info.lookup_context())
    }

    /// Decodes the current payload into a descriptor-backed runtime box value.
    pub async fn read_payload_async(&mut self) -> Result<(Box<dyn DynCodecBox>, u64), WalkError> {
        validate_box_fits_stream_async(self.reader, &self.info).await?;
        self.info.seek_to_payload_async(self.reader).await?;
        let payload_size = self.info.payload_size()?;
        let (boxed, read) = unmarshal_any_with_context_async(
            self.reader,
            payload_size,
            self.info.box_type(),
            self.registry,
            self.info.lookup_context(),
            None,
        )
        .await?;
        self.children_layout = Some(
            children_layout_for_payload_async(
                self.reader,
                &self.info,
                payload_size,
                read,
                boxed.as_ref(),
            )
            .await?,
        );
        Ok((boxed, read))
    }

    /// Copies the raw payload bytes into `writer` without decoding them.
    pub async fn read_data_async<W>(&mut self, writer: &mut W) -> Result<u64, WalkError>
    where
        W: AsyncWrite + Unpin,
    {
        validate_box_fits_stream_async(self.reader, &self.info).await?;
        self.info.seek_to_payload_async(self.reader).await?;
        let payload_size = self.info.payload_size()?;
        let mut limited = (&mut *self.reader).take(payload_size);
        tokio::io::copy(&mut limited, writer)
            .await
            .map_err(WalkError::Io)
    }

    async fn ensure_children_layout_async(&mut self) -> Result<ChildrenLayout, WalkError> {
        if let Some(children_layout) = self.children_layout {
            return Ok(children_layout);
        }

        self.read_payload_async().await?;
        if let Some(children_layout) = self.children_layout {
            Ok(children_layout)
        } else {
            unreachable!("read_payload_async always computes children layout")
        }
    }
}

/// Walks the file from the start in depth-first order using the built-in registry.
pub fn walk_structure<R, F>(reader: &mut R, visitor: F) -> Result<(), WalkError>
where
    R: Read + Seek,
    F: for<'a> FnMut(&mut WalkHandle<'a, R>) -> Result<WalkControl, WalkError>,
{
    let registry = default_registry();
    walk_structure_with_registry(reader, &registry, visitor)
}

/// Walks the file from the start in depth-first order using `registry`.
pub fn walk_structure_with_registry<R, F>(
    reader: &mut R,
    registry: &BoxRegistry,
    mut visitor: F,
) -> Result<(), WalkError>
where
    R: Read + Seek,
    F: for<'a> FnMut(&mut WalkHandle<'a, R>) -> Result<WalkControl, WalkError>,
{
    reader.seek(SeekFrom::Start(0))?;
    walk_sequence(
        reader,
        registry,
        &mut visitor,
        0,
        true,
        &BoxPath::default(),
        BoxLookupContext::new(),
    )
}

/// Walks `parent` and any expanded descendants using the built-in registry.
pub fn walk_structure_from_box<R, F>(
    reader: &mut R,
    parent: &BoxInfo,
    visitor: F,
) -> Result<(), WalkError>
where
    R: Read + Seek,
    F: for<'a> FnMut(&mut WalkHandle<'a, R>) -> Result<WalkControl, WalkError>,
{
    let registry = default_registry();
    walk_structure_from_box_with_registry(reader, parent, &registry, visitor)
}

/// Walks `parent` and any expanded descendants using `registry`.
pub fn walk_structure_from_box_with_registry<R, F>(
    reader: &mut R,
    parent: &BoxInfo,
    registry: &BoxRegistry,
    mut visitor: F,
) -> Result<(), WalkError>
where
    R: Read + Seek,
    F: for<'a> FnMut(&mut WalkHandle<'a, R>) -> Result<WalkControl, WalkError>,
{
    let mut parent = *parent;
    walk_box(
        reader,
        registry,
        &mut visitor,
        &mut parent,
        &BoxPath::default(),
        false,
    )
}

/// Walks the file from the start in depth-first order through the additive Tokio-based async
/// surface using the built-in registry.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub async fn walk_structure_async<R, V>(reader: &mut R, visitor: V) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
    V: AsyncWalkVisitor<R> + Send,
{
    let registry = default_registry();
    walk_structure_with_registry_async(reader, &registry, visitor).await
}

/// Walks the file from the start in depth-first order through the additive Tokio-based async
/// surface using `registry`.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub async fn walk_structure_with_registry_async<R, V>(
    reader: &mut R,
    registry: &BoxRegistry,
    mut visitor: V,
) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
    V: AsyncWalkVisitor<R> + Send,
{
    reader.seek(SeekFrom::Start(0)).await?;
    walk_sequence_async(
        reader,
        registry,
        &mut visitor,
        0,
        true,
        &BoxPath::default(),
        BoxLookupContext::new(),
    )
    .await
}

/// Walks `parent` and any expanded descendants through the additive Tokio-based async surface
/// using the built-in registry.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub async fn walk_structure_from_box_async<R, V>(
    reader: &mut R,
    parent: &BoxInfo,
    visitor: V,
) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
    V: AsyncWalkVisitor<R> + Send,
{
    let registry = default_registry();
    walk_structure_from_box_with_registry_async(reader, parent, &registry, visitor).await
}

/// Walks `parent` and any expanded descendants through the additive Tokio-based async surface
/// using `registry`.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub async fn walk_structure_from_box_with_registry_async<R, V>(
    reader: &mut R,
    parent: &BoxInfo,
    registry: &BoxRegistry,
    mut visitor: V,
) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
    V: AsyncWalkVisitor<R> + Send,
{
    let mut parent = *parent;
    walk_box_async(
        reader,
        registry,
        &mut visitor,
        &mut parent,
        &BoxPath::default(),
        false,
    )
    .await
}

fn walk_sequence<R, F>(
    reader: &mut R,
    registry: &BoxRegistry,
    visitor: &mut F,
    mut remaining_size: u64,
    is_root: bool,
    path: &BoxPath,
    mut sibling_lookup_context: BoxLookupContext,
) -> Result<(), WalkError>
where
    R: Read + Seek,
    F: for<'a> FnMut(&mut WalkHandle<'a, R>) -> Result<WalkControl, WalkError>,
{
    loop {
        if !is_root && remaining_size < SMALL_HEADER_SIZE {
            break;
        }

        let start = reader.stream_position()?;
        let mut info = match BoxInfo::read(reader) {
            Ok(info) => info,
            Err(HeaderError::Io(error)) if is_root && clean_root_eof(reader, start, &error)? => {
                return Ok(());
            }
            Err(error) => return Err(error.into()),
        };

        if !is_root && info.size() > remaining_size {
            return Err(WalkError::TooLargeBoxSize {
                box_type: info.box_type(),
                size: info.size(),
                available_size: remaining_size,
            });
        }
        if !is_root {
            remaining_size -= info.size();
        }

        info.set_lookup_context(sibling_lookup_context);
        walk_box(reader, registry, visitor, &mut info, path, is_root)?;

        if info.lookup_context().is_quicktime_compatible() {
            sibling_lookup_context = sibling_lookup_context.with_quicktime_compatible(true);
        }
        if info.box_type() == KEYS {
            sibling_lookup_context = sibling_lookup_context
                .with_metadata_keys_entry_count(info.lookup_context().metadata_keys_entry_count());
        }
    }

    if !is_root && remaining_size != 0 && !sibling_lookup_context.is_quicktime_compatible() {
        return Err(WalkError::UnexpectedEof);
    }

    Ok(())
}

fn walk_box<R, F>(
    reader: &mut R,
    registry: &BoxRegistry,
    visitor: &mut F,
    info: &mut BoxInfo,
    path: &BoxPath,
    is_root: bool,
) -> Result<(), WalkError>
where
    R: Read + Seek,
    F: for<'a> FnMut(&mut WalkHandle<'a, R>) -> Result<WalkControl, WalkError>,
{
    inspect_context_carriers(reader, info, path)?;

    let path = path.child_path(info.box_type());
    let descendant_lookup_context = info.lookup_context().enter(info.box_type());
    let mut handle = WalkHandle {
        reader,
        registry,
        info: *info,
        path,
        descendant_lookup_context,
        children_layout: None,
    };

    let control = visitor(&mut handle)?;
    if matches!(control, WalkControl::Descend) {
        let children_layout = handle.ensure_children_layout()?;
        handle
            .reader
            .seek(SeekFrom::Start(children_layout.offset))?;
        walk_sequence(
            handle.reader,
            handle.registry,
            visitor,
            children_layout.size,
            false,
            &handle.path,
            handle.descendant_lookup_context,
        )?;
    }

    seek_to_box_end(handle.reader, &handle.info, is_root)?;
    Ok(())
}

#[cfg(feature = "async")]
async fn walk_sequence_async<R, V>(
    reader: &mut R,
    registry: &BoxRegistry,
    visitor: &mut V,
    mut remaining_size: u64,
    is_root: bool,
    path: &BoxPath,
    mut sibling_lookup_context: BoxLookupContext,
) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
    V: AsyncWalkVisitor<R> + Send,
{
    loop {
        if !is_root && remaining_size < SMALL_HEADER_SIZE {
            break;
        }

        let start = reader.stream_position().await?;
        let mut info = match BoxInfo::read_async(reader).await {
            Ok(info) => info,
            Err(HeaderError::Io(error))
                if is_root && clean_root_eof_async(reader, start, &error).await? =>
            {
                return Ok(());
            }
            Err(error) => return Err(error.into()),
        };

        if !is_root && info.size() > remaining_size {
            return Err(WalkError::TooLargeBoxSize {
                box_type: info.box_type(),
                size: info.size(),
                available_size: remaining_size,
            });
        }
        if !is_root {
            remaining_size -= info.size();
        }

        info.set_lookup_context(sibling_lookup_context);
        walk_box_async(reader, registry, visitor, &mut info, path, is_root).await?;

        if info.lookup_context().is_quicktime_compatible() {
            sibling_lookup_context = sibling_lookup_context.with_quicktime_compatible(true);
        }
        if info.box_type() == KEYS {
            sibling_lookup_context = sibling_lookup_context
                .with_metadata_keys_entry_count(info.lookup_context().metadata_keys_entry_count());
        }
    }

    if !is_root && remaining_size != 0 && !sibling_lookup_context.is_quicktime_compatible() {
        return Err(WalkError::UnexpectedEof);
    }

    Ok(())
}

#[cfg(feature = "async")]
async fn walk_box_async<R, V>(
    reader: &mut R,
    registry: &BoxRegistry,
    visitor: &mut V,
    info: &mut BoxInfo,
    path: &BoxPath,
    is_root: bool,
) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
    V: AsyncWalkVisitor<R> + Send,
{
    inspect_context_carriers_async(reader, info, path).await?;

    let path = path.child_path(info.box_type());
    let descendant_lookup_context = info.lookup_context().enter(info.box_type());
    let mut handle = AsyncWalkHandle {
        reader,
        registry,
        info: *info,
        path,
        descendant_lookup_context,
        children_layout: None,
    };

    let control = {
        let future = visitor.visit(&mut handle);
        future.await?
    };
    if matches!(control, WalkControl::Descend) {
        let children_layout = handle.ensure_children_layout_async().await?;
        let path = handle.path.clone();
        let descendant_lookup_context = handle.descendant_lookup_context;
        handle
            .reader
            .seek(SeekFrom::Start(children_layout.offset))
            .await?;
        Box::pin(walk_sequence_async(
            handle.reader,
            handle.registry,
            visitor,
            children_layout.size,
            false,
            &path,
            descendant_lookup_context,
        ))
        .await?;
    }

    let info = handle.info;
    seek_to_box_end_async(handle.reader, &info, is_root).await?;
    Ok(())
}

fn children_layout_for_payload<R>(
    reader: &mut R,
    info: &BoxInfo,
    payload_size: u64,
    payload_read: u64,
    payload: &dyn DynCodecBox,
) -> Result<ChildrenLayout, WalkError>
where
    R: Read + Seek,
{
    let offset = info.offset() + info.header_size() + payload_read;
    let size = if payload_uses_optional_trailing_bytes(payload) {
        visual_sample_entry_child_payload_size(
            reader,
            offset,
            payload_size.saturating_sub(payload_read),
        )?
    } else {
        payload_size.saturating_sub(payload_read)
    };

    Ok(ChildrenLayout { offset, size })
}

#[cfg(feature = "async")]
async fn children_layout_for_payload_async<R>(
    reader: &mut R,
    info: &BoxInfo,
    payload_size: u64,
    payload_read: u64,
    payload: &dyn DynCodecBox,
) -> Result<ChildrenLayout, WalkError>
where
    R: AsyncReadSeek,
{
    let offset = info.offset() + info.header_size() + payload_read;
    let size = if payload_uses_optional_trailing_bytes(payload) {
        visual_sample_entry_child_payload_size_async(
            reader,
            offset,
            payload_size.saturating_sub(payload_read),
        )
        .await?
    } else {
        payload_size.saturating_sub(payload_read)
    };

    Ok(ChildrenLayout { offset, size })
}

fn payload_uses_optional_trailing_bytes(payload: &dyn DynCodecBox) -> bool {
    payload.as_any().is::<VisualSampleEntry>() || payload.as_any().is::<AudioSampleEntry>()
}

fn visual_sample_entry_child_payload_size<R>(
    reader: &mut R,
    extension_offset: u64,
    extension_size: u64,
) -> Result<u64, WalkError>
where
    R: Read + Seek,
{
    let checkpoint = reader.stream_position()?;
    reader.seek(SeekFrom::Start(extension_offset))?;
    let bytes = read_extension_bytes(reader, extension_size)?;
    reader.seek(SeekFrom::Start(checkpoint))?;
    Ok(split_box_children_with_optional_trailing_bytes(&bytes) as u64)
}

fn read_extension_bytes<R>(reader: &mut R, extension_size: u64) -> Result<Vec<u8>, WalkError>
where
    R: Read,
{
    let extension_len = usize::try_from(extension_size).map_err(|_| {
        io::Error::new(io::ErrorKind::InvalidData, "payload extension is too large")
    })?;
    let mut bytes = vec![0; extension_len];
    reader.read_exact(&mut bytes)?;
    Ok(bytes)
}

#[cfg(feature = "async")]
async fn visual_sample_entry_child_payload_size_async<R>(
    reader: &mut R,
    extension_offset: u64,
    extension_size: u64,
) -> Result<u64, WalkError>
where
    R: AsyncReadSeek,
{
    let checkpoint = reader.stream_position().await?;
    reader.seek(SeekFrom::Start(extension_offset)).await?;
    let bytes = read_extension_bytes_async(reader, extension_size).await?;
    reader.seek(SeekFrom::Start(checkpoint)).await?;
    Ok(split_box_children_with_optional_trailing_bytes(&bytes) as u64)
}

#[cfg(feature = "async")]
async fn read_extension_bytes_async<R>(
    reader: &mut R,
    extension_size: u64,
) -> Result<Vec<u8>, WalkError>
where
    R: AsyncReadSeek,
{
    let extension_len = usize::try_from(extension_size).map_err(|_| {
        io::Error::new(io::ErrorKind::InvalidData, "payload extension is too large")
    })?;
    let mut bytes = vec![0; extension_len];
    reader.read_exact(&mut bytes).await?;
    Ok(bytes)
}

fn inspect_context_carriers<R>(
    reader: &mut R,
    info: &mut BoxInfo,
    path: &BoxPath,
) -> Result<(), WalkError>
where
    R: Read + Seek,
{
    if path.is_empty() && info.box_type() == FTYP {
        let ftyp = decode_box::<_, Ftyp>(reader, info)?;
        if ftyp.has_compatible_brand(QT_BRAND) {
            info.set_lookup_context(info.lookup_context().with_quicktime_compatible(true));
        }
    }

    if info.box_type() == KEYS {
        let keys = decode_box::<_, Keys>(reader, info)?;
        info.set_lookup_context(
            info.lookup_context()
                .with_metadata_keys_entry_count(keys.entry_count as usize),
        );
    }

    Ok(())
}

#[cfg(feature = "async")]
async fn inspect_context_carriers_async<R>(
    reader: &mut R,
    info: &mut BoxInfo,
    path: &BoxPath,
) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
{
    if path.is_empty() && info.box_type() == FTYP {
        let ftyp = decode_box_async::<_, Ftyp>(reader, info).await?;
        if ftyp.has_compatible_brand(QT_BRAND) {
            info.set_lookup_context(info.lookup_context().with_quicktime_compatible(true));
        }
    }

    if info.box_type() == KEYS {
        let keys = decode_box_async::<_, Keys>(reader, info).await?;
        info.set_lookup_context(
            info.lookup_context()
                .with_metadata_keys_entry_count(keys.entry_count as usize),
        );
    }

    Ok(())
}

fn decode_box<R, B>(reader: &mut R, info: &BoxInfo) -> Result<B, WalkError>
where
    R: Read + Seek,
    B: Default + crate::codec::CodecBox,
{
    info.seek_to_payload(reader)?;
    let mut decoded = B::default();
    unmarshal(reader, info.payload_size()?, &mut decoded, None)?;
    info.seek_to_payload(reader)?;
    Ok(decoded)
}

#[cfg(feature = "async")]
async fn decode_box_async<R, B>(reader: &mut R, info: &BoxInfo) -> Result<B, WalkError>
where
    R: AsyncReadSeek,
    B: Default + crate::codec::CodecBox + Send,
{
    info.seek_to_payload_async(reader).await?;
    let mut decoded = B::default();
    crate::codec::unmarshal_async(reader, info.payload_size()?, &mut decoded, None).await?;
    info.seek_to_payload_async(reader).await?;
    Ok(decoded)
}

fn clean_root_eof<R>(reader: &mut R, start: u64, error: &io::Error) -> Result<bool, io::Error>
where
    R: Seek,
{
    if error.kind() != io::ErrorKind::UnexpectedEof {
        return Ok(false);
    }

    let end = reader.seek(SeekFrom::End(0))?;
    Ok(start >= end)
}

fn validate_box_fits_stream<R>(reader: &mut R, info: &BoxInfo) -> Result<(), WalkError>
where
    R: Seek,
{
    let position = reader.stream_position()?;
    let stream_len = reader.seek(SeekFrom::End(0))?;
    reader.seek(SeekFrom::Start(position))?;
    validate_box_end_within_stream(info, stream_len)
}

fn validate_box_end_within_stream(info: &BoxInfo, stream_len: u64) -> Result<(), WalkError> {
    let end = checked_box_end(info)?;
    if end > stream_len {
        return Err(WalkError::UnexpectedEof);
    }
    Ok(())
}

fn checked_box_end(info: &BoxInfo) -> Result<u64, WalkError> {
    info.offset()
        .checked_add(info.size())
        .ok_or(WalkError::UnexpectedEof)
}

fn seek_to_box_end<R>(
    reader: &mut R,
    info: &BoxInfo,
    clamp_to_stream_end: bool,
) -> Result<u64, WalkError>
where
    R: Seek,
{
    let end = checked_box_end(info)?;
    let target = if clamp_to_stream_end {
        let position = reader.stream_position()?;
        let stream_len = reader.seek(SeekFrom::End(0))?;
        reader.seek(SeekFrom::Start(position))?;
        end.min(stream_len)
    } else {
        end
    };
    reader.seek(SeekFrom::Start(target)).map_err(WalkError::Io)
}

#[cfg(feature = "async")]
async fn clean_root_eof_async<R>(
    reader: &mut R,
    start: u64,
    error: &io::Error,
) -> Result<bool, io::Error>
where
    R: AsyncReadSeek,
{
    if error.kind() != io::ErrorKind::UnexpectedEof {
        return Ok(false);
    }

    let end = reader.seek(SeekFrom::End(0)).await?;
    Ok(start >= end)
}

#[cfg(feature = "async")]
async fn validate_box_fits_stream_async<R>(reader: &mut R, info: &BoxInfo) -> Result<(), WalkError>
where
    R: AsyncReadSeek,
{
    let position = reader.stream_position().await?;
    let stream_len = reader.seek(SeekFrom::End(0)).await?;
    reader.seek(SeekFrom::Start(position)).await?;
    validate_box_end_within_stream(info, stream_len)
}

#[cfg(feature = "async")]
async fn seek_to_box_end_async<R>(
    reader: &mut R,
    info: &BoxInfo,
    clamp_to_stream_end: bool,
) -> Result<u64, WalkError>
where
    R: AsyncReadSeek,
{
    let end = checked_box_end(info)?;
    let target = if clamp_to_stream_end {
        let position = reader.stream_position().await?;
        let stream_len = reader.seek(SeekFrom::End(0)).await?;
        reader.seek(SeekFrom::Start(position)).await?;
        end.min(stream_len)
    } else {
        end
    };
    reader
        .seek(SeekFrom::Start(target))
        .await
        .map_err(WalkError::Io)
}

/// Errors raised while walking a box tree.
#[derive(Debug)]
pub enum WalkError {
    /// An I/O operation failed while reading or seeking.
    Io(io::Error),
    /// Box header metadata was invalid or truncated.
    Header(HeaderError),
    /// Payload decode failed while the walker was inspecting or expanding a box.
    Codec(CodecError),
    /// A child box declared a size larger than the remaining bytes in its parent container.
    TooLargeBoxSize {
        /// Concrete box type whose declared size exceeded the available bytes.
        box_type: FourCc,
        /// Declared child box size.
        size: u64,
        /// Remaining bytes available in the parent container.
        available_size: u64,
    },
    /// A non-QuickTime container ended before all advertised child bytes were consumed.
    UnexpectedEof,
}

impl fmt::Display for WalkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(error) => error.fmt(f),
            Self::Header(error) => error.fmt(f),
            Self::Codec(error) => error.fmt(f),
            Self::TooLargeBoxSize {
                box_type,
                size,
                available_size,
            } => {
                write!(
                    f,
                    "too large box size: type={box_type}, size={size}, actualBufSize={available_size}"
                )
            }
            Self::UnexpectedEof => f.write_str("unexpected EOF"),
        }
    }
}

impl Error for WalkError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::Header(error) => Some(error),
            Self::Codec(error) => Some(error),
            Self::TooLargeBoxSize { .. } | Self::UnexpectedEof => None,
        }
    }
}

impl From<io::Error> for WalkError {
    fn from(value: io::Error) -> Self {
        Self::Io(value)
    }
}

impl From<HeaderError> for WalkError {
    fn from(value: HeaderError) -> Self {
        Self::Header(value)
    }
}

impl From<CodecError> for WalkError {
    fn from(value: CodecError) -> Self {
        Self::Codec(value)
    }
}