alpha2-container 0.6.0

alpha2's own media container layer: MP4/MOV/M4A, Matroska/WebM and audio-only files, demuxed and muxed in pure Rust with edit lists, priming and deterministic output.
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
//! The `moov` box parsed into typed fields. Boxes this layer does not interpret are kept byte for
//! byte beside the fields of the box that holds them.

use bytes::Bytes;

use super::boxes::{RawBox, Reader, children, find};
use crate::{DemuxError, FourCc, MAX_TRACKS};

/// A 3x3 display matrix in 16.16 fixed point, its last column in 2.30.
pub(crate) type Matrix = [[i32; 3]; 3];

pub(crate) const IDENTITY: Matrix = [[1 << 16, 0, 0], [0, 1 << 16, 0], [0, 0, 1 << 30]];

/// What `ftyp` says about how to read `QuickTime` sound descriptions.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Brands {
    /// The major brand is not `qt  `.
    pub isom: bool,
    /// A compatible brand is `qt  `.
    pub quicktime_compatible: bool,
}

impl Brands {
    pub fn of_ftyp(payload: &[u8]) -> Self {
        let major = payload.get(..4);
        let compatible = payload
            .get(8..)
            .unwrap_or_default()
            .as_chunks::<4>()
            .0
            .iter()
            .any(|brand| brand == b"qt  ");
        Self {
            isom: major.is_some_and(|major| major != b"qt  "),
            quicktime_compatible: compatible,
        }
    }
}

#[derive(Clone, Debug, Default)]
pub(crate) struct Movie {
    /// `mvhd` timescale; 0 without one, 1 for an invalid one.
    pub timescale: u32,
    pub matrix: Matrix,
    pub tracks: Vec<Trak>,
    pub trex: Vec<Trex>,
    /// `iTunSMPB` priming and the index of the track parsed before it.
    pub smpb: Option<(usize, u32)>,
    pub other: Vec<RawBox>,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct Trex {
    pub track_id: u32,
    pub stsd_id: u32,
    pub duration: u32,
    pub size: u32,
    pub flags: u32,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Edit {
    /// In the movie timescale.
    pub duration: u64,
    /// In the media timescale; -1 for an empty edit.
    pub media_time: i64,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct Trak {
    pub track_id: u32,
    pub enabled: bool,
    pub matrix: Matrix,
    /// `tkhd` width and height in whole pixels.
    pub display_size: (u32, u32),
    pub timescale: u32,
    pub media_duration: u64,
    pub language: u16,
    pub handler: [u8; 4],
    pub title: Option<String>,
    pub edits: Vec<Edit>,
    pub stsd_version: u8,
    pub entries: Vec<SampleEntry>,
    /// Index of the sample entry whose packets the track delivers, or `None` for every entry
    /// (as `FFmpeg`'s `pseudo_stream_id`).
    pub pseudo_entry: Option<u32>,
    pub tables: Tables,
    /// Uninterpreted boxes of `trak`, `mdia`, `minf` and `stbl`, in that order of nesting.
    pub other: Vec<RawBox>,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct Tables {
    /// `stts` sample counts and deltas.
    pub stts: Vec<(u32, u32)>,
    /// `ctts` sample counts and signed offsets, for entries with a positive count.
    pub ctts: Vec<(u32, i32)>,
    /// The largest negative composition offset, negated (`FFmpeg`'s `dts_shift`).
    pub dts_shift: i32,
    /// `stss` sample numbers, empty when the box lists none and `None` without the box.
    pub stss: Option<Vec<u32>>,
    pub stps: Vec<u32>,
    pub stsc: Vec<Stsc>,
    /// `stsz` constant size, 0 when sizes are listed.
    pub constant_size: u32,
    pub sample_count: u32,
    pub sizes: Vec<u32>,
    pub chunks: Vec<u64>,
    /// `sbgp` `rap ` sample counts and description indexes.
    pub rap_groups: Vec<(u32, u32)>,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct Stsc {
    pub first: u32,
    pub count: u32,
    pub id: u32,
}

/// One `stsd` entry.
#[derive(Clone, Debug)]
pub(crate) struct SampleEntry {
    pub format: FourCc,
    pub fields: EntryFields,
    /// The child boxes after the fixed fields (`avcC`, `esds`, `colr`, `wave`), or the whole
    /// entry when it is skipped.
    pub children: Vec<RawBox>,
}

#[derive(Clone, Debug)]
pub(crate) enum EntryFields {
    Video { width: u16, height: u16 },
    Audio(AudioFields),
    Other,
}

#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct AudioFields {
    pub channels: u32,
    pub sample_size: u32,
    pub sample_rate: f64,
    pub samples_per_frame: u32,
    pub bytes_per_frame: u32,
    /// The `lpcm` format flags of a version 2 description.
    pub lpcm_flags: Option<u32>,
}

/// Parses `moov`.
pub(crate) fn parse_moov(data: &Bytes, brands: Brands) -> Result<Movie, DemuxError> {
    let mut movie = Movie {
        matrix: IDENTITY,
        ..Movie::default()
    };
    for child in children(data) {
        match &child.kind.0 {
            b"mvhd" => parse_mvhd(&child, &mut movie)?,
            b"trak" => {
                if movie.tracks.len() == MAX_TRACKS {
                    return Err(DemuxError::Invalid(
                        "the file has more tracks than this layer reads".into(),
                    ));
                }
                let trak = parse_trak(&child, brands, movie.matrix)?;
                movie.tracks.push(trak);
            }
            b"mvex" => {
                for entry in children(&child.bytes.slice(child.header..)) {
                    if &entry.kind.0 == b"trex" {
                        movie.trex.push(parse_trex(&entry)?);
                    } else {
                        movie.other.push(entry);
                    }
                }
            }
            b"udta" => {
                if let Some(priming) = udta_smpb(&child)
                    && let Some(last) = movie.tracks.len().checked_sub(1)
                {
                    movie.smpb = Some((last, priming));
                }
                movie.other.push(child);
            }
            _ => movie.other.push(child),
        }
    }
    Ok(movie)
}

fn parse_mvhd(mvhd: &RawBox, movie: &mut Movie) -> Result<(), DemuxError> {
    let mut reader = Reader::new(mvhd.payload(), "mvhd");
    let (version, _) = reader.version_flags()?;
    reader.skip(if version == 1 { 16 } else { 8 })?;
    let timescale = reader.u32()?;
    movie.timescale = if timescale == 0 || i32::try_from(timescale).is_err() {
        1
    } else {
        timescale
    };
    reader.skip(if version == 1 { 8 } else { 4 })?;
    reader.skip(4 + 2 + 10)?;
    movie.matrix = read_matrix(&mut reader)?;
    Ok(())
}

fn read_matrix(reader: &mut Reader<'_>) -> Result<Matrix, DemuxError> {
    let mut matrix = [[0; 3]; 3];
    for row in &mut matrix {
        for value in row {
            *value = reader.i32()?;
        }
    }
    Ok(matrix)
}

fn parse_trex(trex: &RawBox) -> Result<Trex, DemuxError> {
    let mut reader = Reader::new(trex.payload(), "trex");
    reader.version_flags()?;
    Ok(Trex {
        track_id: reader.u32()?,
        stsd_id: reader.u32()?,
        duration: reader.u32()?,
        size: reader.u32()?,
        flags: reader.u32()?,
    })
}

fn body(raw: &RawBox) -> Bytes {
    raw.bytes.slice(raw.header..)
}

fn parse_trak(trak_box: &RawBox, brands: Brands, movie_matrix: Matrix) -> Result<Trak, DemuxError> {
    let mut trak = Trak {
        matrix: IDENTITY,
        ..Trak::default()
    };
    let mut tkhd_seen = false;
    for child in children(&body(trak_box)) {
        match &child.kind.0 {
            b"tkhd" if !tkhd_seen => {
                tkhd_seen = true;
                parse_tkhd(&child, &mut trak, movie_matrix)?;
            }
            b"tkhd" => {
                return Err(DemuxError::Invalid("a track has two tkhd boxes".into()));
            }
            b"edts" => {
                for edit in children(&body(&child)) {
                    if &edit.kind.0 == b"elst" {
                        trak.edits = parse_elst(&edit)?;
                    }
                }
                trak.other.push(child);
            }
            b"mdia" => parse_mdia(&child, &mut trak, brands)?,
            b"udta" => {
                trak.title = udta_title(&child);
                trak.other.push(child);
            }
            _ => trak.other.push(child),
        }
    }
    Ok(trak)
}

fn parse_tkhd(tkhd: &RawBox, trak: &mut Trak, movie_matrix: Matrix) -> Result<(), DemuxError> {
    let mut reader = Reader::new(tkhd.payload(), "tkhd");
    let (version, flags) = reader.version_flags()?;
    trak.enabled = flags & 1 != 0;
    reader.skip(if version == 1 { 16 } else { 8 })?;
    trak.track_id = reader.u32()?;
    reader.skip(4)?;
    reader.skip(if version == 1 { 8 } else { 4 })?;
    reader.skip(8 + 8)?;
    let own = read_matrix(&mut reader)?;
    // The movie matrix applies after the track's, in the fixed-point arithmetic of `FFmpeg`.
    let shifts = [16, 16, 30];
    let mut combined = [[0_i64; 3]; 3];
    for (row, own_row) in combined.iter_mut().zip(own) {
        for (column, value) in row.iter_mut().enumerate() {
            for (inner, shift) in shifts.iter().enumerate() {
                *value +=
                    (i64::from(own_row[inner]) * i64::from(movie_matrix[inner][column])) >> shift;
            }
        }
    }
    trak.matrix = combined.map(|row| {
        row.map(|value| i32::try_from(value).unwrap_or(if value < 0 { i32::MIN } else { i32::MAX }))
    });
    trak.display_size = (reader.u32()? >> 16, reader.u32()? >> 16);
    Ok(())
}

fn parse_elst(elst: &RawBox) -> Result<Vec<Edit>, DemuxError> {
    let mut reader = Reader::new(elst.payload(), "elst");
    let (version, _) = reader.version_flags()?;
    let declared = reader.u32()? as usize;
    let entry = if version == 1 { 20 } else { 12 };
    let count = declared.min(reader.remaining() / entry);
    let mut edits = Vec::with_capacity(count);
    for _ in 0..count {
        let (duration, media_time) = if version == 1 {
            (reader.u64()?, reader.i64()?)
        } else {
            (u64::from(reader.u32()?), i64::from(reader.i32()?))
        };
        reader.skip(4)?;
        edits.push(Edit {
            duration,
            media_time,
        });
    }
    Ok(edits)
}

fn parse_mdia(mdia: &RawBox, trak: &mut Trak, brands: Brands) -> Result<(), DemuxError> {
    let mut stbl = None;
    for child in children(&body(mdia)) {
        match &child.kind.0 {
            b"mdhd" => {
                let mut reader = Reader::new(child.payload(), "mdhd");
                let (version, _) = reader.version_flags()?;
                if version > 1 {
                    return Err(DemuxError::Unsupported(format!(
                        "mdhd version {version} is not read"
                    )));
                }
                reader.skip(if version == 1 { 16 } else { 8 })?;
                trak.timescale = reader.u32()?;
                if trak.timescale == 0 || i32::try_from(trak.timescale).is_err() {
                    trak.timescale = 1;
                }
                trak.media_duration = if version == 1 {
                    match reader.u64()? {
                        u64::MAX => 0,
                        duration => duration,
                    }
                } else {
                    match reader.u32()? {
                        u32::MAX => 0,
                        duration => u64::from(duration),
                    }
                };
                trak.language = reader.u16()?;
            }
            b"hdlr" => {
                if let Some(handler) = child.payload().get(8..12) {
                    trak.handler.copy_from_slice(handler);
                }
                trak.other.push(child);
            }
            b"minf" => {
                for leaf in children(&body(&child)) {
                    if &leaf.kind.0 == b"stbl" {
                        stbl = Some(leaf);
                    } else {
                        trak.other.push(leaf);
                    }
                }
            }
            _ => trak.other.push(child),
        }
    }
    if let Some(stbl) = stbl {
        parse_stbl(&stbl, trak, brands)?;
    }
    Ok(())
}

fn parse_stbl(stbl: &RawBox, trak: &mut Trak, brands: Brands) -> Result<(), DemuxError> {
    for child in children(&body(stbl)) {
        let payload = child.payload();
        let tables = &mut trak.tables;
        match &child.kind.0 {
            b"stsd" => parse_stsd(&child, trak, brands)?,
            b"stts" => tables.stts = pairs(payload, "stts")?,
            b"ctts" => {
                let entries = pairs(payload, "ctts")?;
                let total = entries.len();
                for (index, (count, offset)) in entries.into_iter().enumerate() {
                    let offset = i32::from_be_bytes(offset.to_be_bytes());
                    if count == 0 || i32::try_from(count).is_err() {
                        continue;
                    }
                    tables.ctts.push((count, offset));
                    // `FFmpeg` ignores the last two entries when it shifts decode times.
                    if index + 2 < total && offset < 0 {
                        tables.dts_shift = tables.dts_shift.max(offset.saturating_neg());
                    }
                }
            }
            b"stss" => tables.stss = Some(words(payload, "stss")?),
            b"stps" => tables.stps = words(payload, "stps")?,
            b"stsc" => tables.stsc = parse_stsc(payload)?,
            b"stsz" | b"stz2" => parse_stsz(&child, tables)?,
            b"stco" | b"co64" => {
                if tables.chunks.is_empty() {
                    tables.chunks = parse_stco(&child)?;
                }
            }
            b"sbgp" => {
                parse_sbgp(payload, tables)?;
                trak.other.push(child);
            }
            _ => trak.other.push(child),
        }
    }
    Ok(())
}

/// A full box's entry count, capped at what its payload holds at `size` bytes an entry.
fn entry_count(reader: &mut Reader<'_>, size: usize) -> Result<usize, DemuxError> {
    let declared = reader.u32()? as usize;
    Ok(declared.min(reader.remaining() / size))
}

fn pairs(payload: &[u8], what: &'static str) -> Result<Vec<(u32, u32)>, DemuxError> {
    let mut reader = Reader::new(payload, what);
    reader.version_flags()?;
    let count = entry_count(&mut reader, 8)?;
    (0..count)
        .map(|_| Ok((reader.u32()?, reader.u32()?)))
        .collect()
}

fn words(payload: &[u8], what: &'static str) -> Result<Vec<u32>, DemuxError> {
    let mut reader = Reader::new(payload, what);
    reader.version_flags()?;
    let count = entry_count(&mut reader, 4)?;
    (0..count).map(|_| reader.u32()).collect()
}

/// `stsc` entries, repaired the way `FFmpeg` repairs out-of-order or zero entries.
fn parse_stsc(payload: &[u8]) -> Result<Vec<Stsc>, DemuxError> {
    let mut reader = Reader::new(payload, "stsc");
    reader.version_flags()?;
    let declared = reader.u32()? as usize;
    if declared.saturating_mul(12) > reader.remaining() {
        return Err(DemuxError::Invalid("the stsc box is truncated".into()));
    }
    let mut entries = (0..declared)
        .map(|_| {
            Ok(Stsc {
                first: reader.u32()?,
                count: reader.u32()?,
                id: reader.u32()?,
            })
        })
        .collect::<Result<Vec<_>, DemuxError>>()?;
    let mut index = entries.len();
    while index > 0 {
        index -= 1;
        let first_min = index as u64 + 1;
        let entry = entries[index];
        let next = entries.get(index + 1).copied();
        let previous = index.checked_sub(1).map(|at| entries[at]);
        let invalid = next.is_some_and(|next| entry.first >= next.first)
            || previous.is_some_and(|previous| entry.first <= previous.first)
            || u64::from(entry.first) < first_min
            || entry.count < 1
            || entry.id < 1;
        if !invalid {
            continue;
        }
        match next {
            None => {
                if entry.count == 0 && index > 0 {
                    entries.pop();
                    continue;
                }
                let mut fixed = entry;
                fixed.first = fixed
                    .first
                    .max(u32::try_from(first_min).unwrap_or(u32::MAX));
                if let Some(previous) = previous
                    && fixed.first <= previous.first
                {
                    fixed.first = previous
                        .first
                        .saturating_add(1)
                        .min(i32::MAX.unsigned_abs());
                }
                fixed.count = fixed.count.max(1);
                fixed.id = fixed.id.max(1);
                entries[index] = fixed;
            }
            Some(next) => {
                entries[index] = Stsc {
                    first: next.first.saturating_sub(1).max(1),
                    count: next.count,
                    id: next.id,
                };
            }
        }
    }
    Ok(entries)
}

fn parse_stsz(stsz: &RawBox, tables: &mut Tables) -> Result<(), DemuxError> {
    let mut reader = Reader::new(stsz.payload(), "stsz");
    reader.version_flags()?;
    let field = if &stsz.kind.0 == b"stsz" {
        tables.constant_size = reader.u32()?;
        32
    } else {
        reader.skip(3)?;
        u32::from(reader.u8()?)
    };
    let count = reader.u32()?;
    tables.sample_count = count;
    if tables.constant_size != 0 {
        return Ok(());
    }
    if ![4, 8, 16, 32].contains(&field) {
        return Err(DemuxError::Invalid(format!(
            "the sample size field is {field} bits wide"
        )));
    }
    let available = (reader.remaining() as u64 * 8) / u64::from(field);
    if u64::from(count) > available {
        // `FFmpeg` drops a truncated size table, which leaves the track without samples.
        tables.sample_count = 0;
        return Ok(());
    }
    let data = reader.rest();
    tables.sizes = (0..count as usize)
        .map(|index| match field {
            32 => u32::from_be_bytes([
                data[index * 4],
                data[index * 4 + 1],
                data[index * 4 + 2],
                data[index * 4 + 3],
            ]),
            16 => u32::from(u16::from_be_bytes([data[index * 2], data[index * 2 + 1]])),
            8 => u32::from(data[index]),
            _ => u32::from(if index % 2 == 0 {
                data[index / 2] >> 4
            } else {
                data[index / 2] & 0x0f
            }),
        })
        .collect();
    Ok(())
}

fn parse_stco(stco: &RawBox) -> Result<Vec<u64>, DemuxError> {
    let mut reader = Reader::new(stco.payload(), "stco");
    reader.version_flags()?;
    let wide = &stco.kind.0 == b"co64";
    let count = entry_count(&mut reader, if wide { 8 } else { 4 })?;
    (0..count)
        .map(|_| {
            if wide {
                let offset = reader.u64()?;
                Ok(if offset > i64::MAX as u64 { 0 } else { offset })
            } else {
                reader.u32().map(u64::from)
            }
        })
        .collect()
}

/// The `rap ` sample groups of an `sbgp` box, which mark sync samples.
fn parse_sbgp(payload: &[u8], tables: &mut Tables) -> Result<(), DemuxError> {
    let mut reader = Reader::new(payload, "sbgp");
    let (version, _) = reader.version_flags()?;
    if &reader.fourcc()?.0 != b"rap " {
        return Ok(());
    }
    if version == 1 {
        reader.skip(4)?;
    }
    let count = entry_count(&mut reader, 8)?;
    if count > 0 {
        tables.rap_groups = (0..count)
            .map(|_| Ok((reader.u32()?, reader.u32()?)))
            .collect::<Result<_, DemuxError>>()?;
    }
    Ok(())
}

/// Bytes of a video sample entry's fixed fields after its 8-byte header.
const VIDEO_FIELDS: usize = 78;
/// Bytes of a version 0 sound sample entry's fixed fields after its 8-byte header.
const AUDIO_FIELDS: usize = 28;

fn parse_stsd(stsd: &RawBox, trak: &mut Trak, brands: Brands) -> Result<(), DemuxError> {
    if !trak.entries.is_empty() {
        return Err(DemuxError::Invalid("a track has two stsd boxes".into()));
    }
    let mut reader = Reader::new(stsd.payload(), "stsd");
    let (version, _) = reader.version_flags()?;
    trak.stsd_version = version;
    let declared = reader.u32()?;
    if declared == 0 || declared > 1024 || declared as usize > stsd.payload().len() / 8 {
        return Err(DemuxError::Invalid(format!(
            "the stsd box declares {declared} entries"
        )));
    }
    let entries = children(&stsd.bytes.slice(stsd.header + 8..));
    let mut first_format: Option<FourCc> = None;
    for (index, raw) in entries.into_iter().take(declared as usize).enumerate() {
        if raw.bytes.len() < 16 {
            return Err(DemuxError::Invalid("an stsd entry is truncated".into()));
        }
        let format = raw.kind;
        let index = u32::try_from(index).unwrap_or(u32::MAX);
        if let Some(first) = first_format {
            if !same_codec(first, format) {
                // `FFmpeg` reads one codec per track and skips entries of another.
                trak.entries.push(SampleEntry {
                    format,
                    fields: EntryFields::Other,
                    children: vec![raw],
                });
                continue;
            }
            trak.pseudo_entry = None;
        } else {
            first_format = Some(format);
            trak.pseudo_entry = Some(index);
        }
        trak.entries
            .push(parse_entry(&raw, trak.handler, version, brands)?);
    }
    Ok(())
}

fn same_codec(first: FourCc, format: FourCc) -> bool {
    first == format
        || matches!(&first.0, b"apcn" | b"apch" | b"dvpp" | b"dvcp")
        || (&first.0 == b"AV1x" && &format.0 == b"AVup")
        || &first.0 == b"jpeg"
}

fn parse_entry(
    raw: &RawBox,
    handler: [u8; 4],
    stsd_version: u8,
    brands: Brands,
) -> Result<SampleEntry, DemuxError> {
    let payload = raw.payload();
    let mut reader = Reader::new(payload, "sample entry");
    reader.skip(8)?;
    let (fields, fields_end) = match &handler {
        b"vide" if payload.len() >= VIDEO_FIELDS => {
            reader.skip(16)?;
            let width = reader.u16()?;
            let height = reader.u16()?;
            (EntryFields::Video { width, height }, VIDEO_FIELDS)
        }
        b"soun" if payload.len() >= AUDIO_FIELDS => {
            let (fields, end) = parse_audio_fields(&mut reader, stsd_version, brands)?;
            (EntryFields::Audio(fields), end)
        }
        _ => (EntryFields::Other, payload.len()),
    };
    let children = if fields_end + 8 < payload.len() {
        children(&raw.bytes.slice(raw.header + fields_end..))
    } else {
        Vec::new()
    };
    Ok(SampleEntry {
        format: raw.kind,
        fields,
        children,
    })
}

fn parse_audio_fields(
    reader: &mut Reader<'_>,
    stsd_version: u8,
    brands: Brands,
) -> Result<(AudioFields, usize), DemuxError> {
    let version = reader.u16()?;
    reader.skip(2 + 4)?;
    let mut fields = AudioFields {
        channels: u32::from(reader.u16()?),
        sample_size: u32::from(reader.u16()?),
        ..AudioFields::default()
    };
    reader.skip(4)?;
    fields.sample_rate = f64::from(reader.u32()? >> 16);
    let quicktime =
        !brands.isom || brands.quicktime_compatible || (stsd_version == 0 && version > 0);
    if quicktime && version == 1 {
        fields.samples_per_frame = reader.u32()?;
        reader.skip(4)?;
        fields.bytes_per_frame = reader.u32()?;
        reader.skip(4)?;
    } else if quicktime && version == 2 {
        reader.skip(4)?;
        fields.sample_rate = f64::from_bits(reader.u64()?);
        fields.channels = reader.u32()?;
        reader.skip(4)?;
        fields.sample_size = reader.u32()?;
        fields.lpcm_flags = Some(reader.u32()?);
        fields.bytes_per_frame = reader.u32()?;
        fields.samples_per_frame = reader.u32()?;
    }
    Ok((fields, reader.position()))
}

/// The `iTunSMPB` priming in the metadata list of a `udta` box, as `FFmpeg` accepts it.
fn udta_smpb(udta: &RawBox) -> Option<u32> {
    let meta = children(&body(udta))
        .into_iter()
        .find(|child| &child.kind.0 == b"meta")?;
    let payload = body(&meta);
    let start = if payload.get(4..8) == Some(b"hdlr") {
        0
    } else {
        4
    };
    let ilst = children(&payload.slice(start.min(payload.len())..))
        .into_iter()
        .find(|child| &child.kind.0 == b"ilst")?;
    for item in children(&body(&ilst)) {
        if &item.kind.0 != b"----" {
            continue;
        }
        let parts = children(&body(&item));
        let name = find(&parts, b"name")?.payload().get(4..)?;
        if name != b"iTunSMPB" {
            continue;
        }
        let value = find(&parts, b"data")?.payload().get(8..)?;
        let text = std::str::from_utf8(value).ok()?;
        let mut words = text.split_whitespace().skip(1);
        let priming = u32::from_str_radix(words.next()?, 16).ok()?;
        words.next()?;
        words.next()?;
        return (priming > 0 && priming < 16_384).then_some(priming);
    }
    None
}

/// Whether `moov` holds a compressed header (`cmov`).
pub(crate) fn has_compressed_header(moov: &RawBox) -> bool {
    children(&body(moov))
        .iter()
        .any(|child| &child.kind.0 == b"cmov")
}

/// A track title from `udta` `name` or `(c)nam`.
fn udta_title(udta: &RawBox) -> Option<String> {
    for child in children(&body(udta)) {
        let text = match &child.kind.0 {
            b"name" => child.payload(),
            [0xa9, b'n', b'a', b'm'] => {
                let payload = child.payload();
                let length = usize::from(u16::from_be_bytes([*payload.first()?, *payload.get(1)?]));
                payload.get(4..4 + length)?
            }
            _ => continue,
        };
        let text = String::from_utf8_lossy(text)
            .trim_end_matches('\0')
            .to_string();
        if !text.is_empty() {
            return Some(text);
        }
    }
    None
}