syom 0.8.0

AAC to planar f32. LC, HE-AAC, AAC-LD. ADTS, M4A, LATM. Zero deps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
//! Minimal ISOBMFF (MP4/M4A) demuxer for the in-tree AAC path.
//!
//! Scope: locate the first AAC audio track and extract its
//! AudioSpecificConfig plus the byte ranges of every compressed sample.
//! Everything else the container
//! can carry is skipped, never interpreted:
//!
//! * `meta` / `ilst` / `udta` (tags, artwork) — walked past, not parsed;
//! * video / subtitle / hint tracks — ignored (the first usable `soun` track
//!   with an `mp4a` sample entry wins, mirroring symphonia's default-track
//!   pick; broken or non-AAC sound tracks are skipped);
//! * fragmented MP4 (`moof` / `mvex`) — bounded fMP4 (one unencrypted AAC
//!   track) is parsed by [`frag`] (TASK-124); the flat sample-table path
//!   here still rejects fragmentation boxes;
//! * encrypted content — `enca` sample entries are rejected with a clean
//!   error; CENC-style files hide the `esds` inside a `sinf` wrapper that is
//!   never descended into, so such tracks carry no usable esds and are
//!   skipped like any other unusable track;
//! * non-AAC sample entries (`alac`, `twos`, `sowt`, …) — the track is
//!   skipped; if no usable AAC track remains, a clean error is returned.
//!
//! Boxes parsed: `ftyp` (sniff only), `moov/trak/mdia/minf/stbl`, `hdlr`
//! (handler `soun`), `mvhd`/`mdhd` (timescale and duration), `edts`/`elst`
//! (one supported edit: priming `media_time` and presentation duration;
//! empty/multiple/non-1.0/inexact edits are errors),
//! `stsd` (`mp4a` entry → `esds` → ES_Descriptor(0x03) →
//! DecoderConfigDescriptor(0x04) → DecoderSpecificInfo(0x05) = ASC),
//! `stts` (total sample count for the duration budget), `stsc`, `stsz`,
//! `stco`/`co64` (sample → byte-range mapping).
//!
//! All arithmetic is checked and every offset is bounds-validated against the
//! input before indexing: untrusted input must produce errors, never panics
//! and never out-of-bounds reads.

use crate::budgets::{BudgetKind, MemoryBudgets, check_planned};
use crate::error::{AacError, Result};

fn fence_entries(mem: &MemoryBudgets, count: u64, bytes_per: u64) -> Result<()> {
    mem.check_index(count, bytes_per)
        .map(|_| ())
        .map_err(AacError::from)
}

fn fence_depth(mem: &MemoryBudgets, depth: u32) -> Result<()> {
    mem.check_box_depth(depth).map_err(AacError::from)
}

/// One extracted AAC audio track: the codec configuration and the location of
/// every compressed sample (each sample is one AAC `raw_data_block()`).
#[derive(Debug)]
pub(crate) struct AacTrack {
    /// AudioSpecificConfig bytes (esds DecoderSpecificInfo).
    pub asc: Vec<u8>,
    /// Total samples per channel declared by `stts` (each AAC frame covers
    /// 1024 core samples); used for the duration budget before allocation.
    pub total_samples: u64,
    /// `(offset, len)` of every audio sample in decode order.
    pub frames: Vec<(u64, u32)>,
    /// First supported `elst.media_time` (ISO-BMFF media timescale), or 0.
    pub edit_start: u64,
    /// Supported `elst.segment_duration` (movie timescale), or 0.
    pub edit_duration: u64,
    /// `mvhd` timescale for `edit_duration`. 0 if the box is missing.
    pub movie_timescale: u32,
    /// `mdhd` timescale for `edit_start`. 0 if the box is missing.
    pub media_timescale: u32,
    /// `mdhd` duration (coded media units). 0 if missing/truncated.
    #[cfg_attr(not(test), allow(dead_code))]
    pub media_duration: u64,
    /// True when a supported one-entry `elst` is present (duration 0 still
    /// trims to nothing). Missing `edts`/`elst` plays the whole decode.
    pub has_elst: bool,
    /// fMP4 only (DASH init segments declare a priming edit before the media
    /// duration is known): a zero `elst.segment_duration` caps nothing and
    /// plays to the end of the fragments. Flat M4A keeps duration 0 = trim
    /// to nothing.
    pub edit_open_end: bool,
}

impl AacTrack {
    /// Native-rate samples to drop after decode (AAC encoder delay).
    #[must_use]
    #[cfg(test)]
    pub(crate) fn skip_samples(&self, sample_rate: u32) -> usize {
        if self.edit_start == 0 || self.media_timescale == 0 || sample_rate == 0 {
            return 0;
        }
        let n = self.edit_start.saturating_mul(u64::from(sample_rate))
            / u64::from(self.media_timescale);
        usize::try_from(n).unwrap_or(usize::MAX)
    }

    /// `(skip, play)` at `sample_rate`. `play = None` means no end trim.
    /// Inexact timescale conversion, missing timescale, and overflow error
    /// instead of a silent prefix skip.
    pub(crate) fn edit_window(&self, sample_rate: u32) -> Result<(usize, Option<usize>)> {
        if !self.has_elst {
            return Ok((0, None));
        }
        let skip = convert_exact(
            self.edit_start,
            sample_rate,
            self.media_timescale,
            "elst media_time",
        )?;
        if self.edit_open_end && self.edit_duration == 0 {
            return Ok((skip, None));
        }
        let play = convert_exact(
            self.edit_duration,
            sample_rate,
            self.movie_timescale,
            "elst duration",
        )?;
        Ok((skip, Some(play)))
    }

    /// Presentation length in media units: `elst.segment_duration` converted
    /// with checked movie→media timescale. `None` if a timescale is missing
    /// or the multiply overflows.
    #[must_use]
    pub(crate) fn presentation_samples(&self) -> Option<u64> {
        if self.movie_timescale == 0 {
            return None;
        }
        self.edit_duration
            .checked_mul(u64::from(self.media_timescale))?
            .checked_div(u64::from(self.movie_timescale))
    }

    /// Unplayed tail: `mdhd.duration − priming − presentation`. `None` when
    /// presentation is unknown or the counts underflow (coded vs presentation
    /// must not be swapped).
    #[must_use]
    pub(crate) fn remainder_samples(&self) -> Option<u64> {
        let valid = self.presentation_samples()?;
        self.media_duration
            .checked_sub(self.edit_start)?
            .checked_sub(valid)
    }

    /// Tail reported on a finished decode. A flat edit uses the container
    /// counts. An open fragment edit (DASH `segment_duration` 0) has no
    /// container cap, so the tail is whatever of `total_samples` was not
    /// emitted after priming.
    pub(crate) fn unplayed_tail(&self, skip: u64, samples_out: u64) -> Option<u64> {
        if !self.has_elst {
            return None;
        }
        if self.edit_open_end {
            Some(
                self.total_samples
                    .saturating_sub(skip)
                    .saturating_sub(samples_out),
            )
        } else {
            self.remainder_samples()
        }
    }
}

/// ASC + container timing without a sample-table index (TASK-54 probe).
#[derive(Debug)]
pub(crate) struct AacMeta {
    pub asc: Vec<u8>,
    pub edit_start: u64,
    pub edit_duration: u64,
    pub movie_timescale: u32,
    pub media_timescale: u32,
    pub media_duration: u64,
    pub has_elst: bool,
}

/// 4-byte box type.
type FourCc = [u8; 4];

const BOX_MOOV: FourCc = *b"moov";
const BOX_TRAK: FourCc = *b"trak";
const BOX_MOOF: FourCc = *b"moof";
const BOX_MVEX: FourCc = *b"mvex";

/// A parsed box header: content range within the input.
#[derive(Debug, Clone, Copy)]
struct BoxHdr {
    /// Offset of the box content (after the 8/16-byte header).
    content_start: usize,
    /// End of the box content (exclusive).
    content_end: usize,
}

/// Read the box header at `pos`; returns the header and the box type, or
/// `None` when fewer than 8 bytes remain (trailing padding). Errors on
/// malformed sizes (truncated header, size overflowing the input).
fn read_box(data: &[u8], pos: usize) -> Result<Option<(BoxHdr, FourCc)>> {
    let Some(hdr) = data.get(pos..pos.saturating_add(8)) else {
        return Ok(None);
    };
    let size32 = u32::from_be_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]) as u64;
    let typ: FourCc = [hdr[4], hdr[5], hdr[6], hdr[7]];
    let (size, head_len) = match size32 {
        1 => {
            // 64-bit largesize follows the type.
            let ext = data
                .get(pos + 8..pos.saturating_add(16))
                .ok_or_else(|| AacError::format("isomp4: truncated 64-bit box size"))?;
            let arr: [u8; 8] = ext
                .try_into()
                .map_err(|_| AacError::format("isomp4: truncated 64-bit box size"))?;
            (u64::from_be_bytes(arr), 16u64)
        }
        0 => {
            // "to end of file" box: only legal at top level; treat the rest
            // of the input as the content.
            ((data.len() - pos) as u64, 8u64)
        }
        s => (s, 8u64),
    };
    if size < head_len {
        return Err(AacError::format(format!(
            "isomp4: box size {size} smaller than its header"
        )));
    }
    // Stay in u64 until the end is known to fit the slice. Casting `size`
    // to `usize` first truncates on 32-bit targets (wasm32 included): a
    // largesize of 2^32 becomes 0, `content_end` does not advance, and the
    // child walker loops.
    let end_u = (pos as u64)
        .checked_add(size)
        .ok_or_else(|| AacError::format("isomp4: box size overflow"))?;
    if end_u > data.len() as u64 {
        return Err(AacError::format("isomp4: box extends past end of input"));
    }
    let end = usize::try_from(end_u).map_err(|_| AacError::format("isomp4: box exceeds usize"))?;
    let content_start = (pos as u64)
        .checked_add(head_len)
        .ok_or_else(|| AacError::format("isomp4: box size overflow"))?;
    let content_start = usize::try_from(content_start)
        .map_err(|_| AacError::format("isomp4: box exceeds usize"))?;
    Ok(Some((
        BoxHdr {
            content_start,
            content_end: end,
        },
        typ,
    )))
}

/// Top-level box read for the fMP4 whole-slice walk: a partial header or a
/// declared size beyond the buffer is stream truncation, typed
/// [`AacError::Truncated`] (`read_box` itself stays Format-class for the
/// flat path's `NotAac` collapse).
fn read_top_box(data: &[u8], pos: usize) -> Result<(BoxHdr, FourCc)> {
    let truncated = || AacError::Truncated {
        at: Some(pos as u64),
    };
    let avail = data.len() - pos;
    if avail < 8 {
        return Err(truncated());
    }
    let size32 = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
    let size = match size32 {
        1 => {
            let Some(ext) = data.get(pos.saturating_add(8)..pos.saturating_add(16)) else {
                return Err(truncated());
            };
            u64::from_be_bytes(ext.try_into().map_err(|_| truncated())?)
        }
        0 => avail as u64, // to-end-of-input box
        s => u64::from(s),
    };
    if size > avail as u64 {
        return Err(truncated());
    }
    read_box(data, pos)?.ok_or_else(truncated)
}

/// Iterate the child boxes of `data[start..end]`.
struct BoxIter<'a> {
    data: &'a [u8],
    pos: usize,
    end: usize,
}

impl<'a> BoxIter<'a> {
    fn new(data: &'a [u8], start: usize, end: usize) -> Self {
        BoxIter {
            data,
            pos: start,
            end,
        }
    }
}

impl Iterator for BoxIter<'_> {
    type Item = Result<(BoxHdr, FourCc)>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.end {
            return None;
        }
        match read_box(&self.data[..self.end], self.pos) {
            Ok(Some((hdr, typ))) => {
                self.pos = hdr.content_end;
                Some(Ok((hdr, typ)))
            }
            Ok(None) => {
                // Trailing slack (e.g. `free` padding to a 4-byte boundary):
                // stop without error.
                self.pos = self.end;
                None
            }
            Err(e) => {
                self.pos = self.end;
                Some(Err(e))
            }
        }
    }
}

/// Variable-length descriptor size (ISO/IEC 14496-1 §8.3.3): up to 4 bytes,
/// 7 bits each, MSB = continuation.
fn read_desc_len(data: &[u8], pos: usize) -> Result<(usize, usize)> {
    let mut len = 0usize;
    for i in 0..4 {
        let &b = data
            .get(pos + i)
            .ok_or_else(|| AacError::format("isomp4: truncated descriptor length"))?;
        len = (len << 7) | usize::from(b & 0x7F);
        if b & 0x80 == 0 {
            return Ok((len, pos + i + 1));
        }
    }
    Err(AacError::format(
        "isomp4: descriptor length exceeds 4 bytes",
    ))
}

/// Extract the DecoderSpecificInfo (AudioSpecificConfig) bytes from an `esds`
/// box body (after the 8-byte box header: 4 bytes version/flags, then the
/// descriptor tree). Only the descriptor *lengths* are walked; descriptor
/// payloads other than tag 0x05 are never interpreted.
fn parse_esds(data: &[u8]) -> Result<Vec<u8>> {
    let pos = 4usize; // skip version/flags
    // ES_Descriptor (0x03).
    if data.get(pos) != Some(&0x03) {
        return Err(AacError::format(
            "isomp4: esds does not start with ES_Descriptor",
        ));
    }
    let (es_len, mut p) = read_desc_len(data, pos + 1)?;
    let es_end = p
        .checked_add(es_len)
        .filter(|&e| e <= data.len())
        .ok_or_else(|| AacError::format("isomp4: ES_Descriptor overruns esds box"))?;
    // ES_ID(2) + flags(1).
    p = p
        .checked_add(3)
        .filter(|&e| e <= es_end)
        .ok_or_else(|| AacError::format("isomp4: truncated ES_Descriptor"))?;
    let flags = data[p - 1];
    if flags & 0x80 != 0 {
        p = p
            .checked_add(2)
            .filter(|&e| e <= es_end)
            .ok_or_else(|| AacError::format("isomp4: truncated streamDependence"))?;
    }
    if flags & 0x40 != 0 {
        let url_len = *data
            .get(p)
            .ok_or_else(|| AacError::format("isomp4: truncated URL flag"))?
            as usize;
        p = p
            .checked_add(1 + url_len)
            .filter(|&e| e <= es_end)
            .ok_or_else(|| AacError::format("isomp4: truncated URL string"))?;
    }
    if flags & 0x20 != 0 {
        p = p
            .checked_add(2)
            .filter(|&e| e <= es_end)
            .ok_or_else(|| AacError::format("isomp4: truncated OCR flag"))?;
    }
    // DecoderConfigDescriptor (0x04).
    if data.get(p) != Some(&0x04) {
        return Err(AacError::format(
            "isomp4: no DecoderConfigDescriptor in esds",
        ));
    }
    let (dc_len, mut p) = read_desc_len(data, p + 1)?;
    let dc_end = p
        .checked_add(dc_len)
        .filter(|&e| e <= es_end)
        .ok_or_else(|| AacError::format("isomp4: DecoderConfigDescriptor overruns"))?;
    // objectTypeIndication(1) + streamType(1) + bufferSizeDB(3) +
    // maxBitrate(4) + avgBitrate(4) = 13 bytes of fixed fields.
    let object_type = *data
        .get(p)
        .ok_or_else(|| AacError::format("isomp4: truncated DecoderConfigDescriptor"))?;
    if object_type != 0x40 {
        return Err(AacError::format(format!(
            "isomp4: unsupported MPEG-4 object type 0x{object_type:02x} (only 0x40 = AAC is handled)"
        )));
    }
    p = p
        .checked_add(13)
        .filter(|&e| e <= dc_end)
        .ok_or_else(|| AacError::format("isomp4: truncated DecoderConfigDescriptor body"))?;
    // Sub-descriptors: DecoderSpecificInfo (0x05) is the ASC.
    while p < dc_end {
        let tag = data[p];
        let (len, body) = read_desc_len(data, p + 1)?;
        let end = body
            .checked_add(len)
            .filter(|&e| e <= dc_end)
            .ok_or_else(|| AacError::format("isomp4: sub-descriptor overruns"))?;
        if tag == 0x05 {
            if len == 0 {
                return Err(AacError::format("isomp4: empty AudioSpecificConfig"));
            }
            return Ok(data[body..end].to_vec());
        }
        p = end;
    }
    Err(AacError::format(
        "isomp4: no DecoderSpecificInfo (AudioSpecificConfig) in esds",
    ))
}

/// Find the `esds` box inside an `mp4a` sample entry and return the ASC.
/// Direct children are scanned first; a `wave` wrapper (QuickTime) is looked
/// through one level deep. Anything else is ignored.
fn extract_asc(data: &[u8], children: BoxHdr) -> Result<Vec<u8>> {
    for child in BoxIter::new(data, children.content_start, children.content_end) {
        let (hdr, typ) = child?;
        match &typ {
            b"esds" => return parse_esds(&data[hdr.content_start..hdr.content_end]),
            b"wave" => {
                for sub in BoxIter::new(data, hdr.content_start, hdr.content_end) {
                    let (shdr, styp) = sub?;
                    if &styp == b"esds" {
                        return parse_esds(&data[shdr.content_start..shdr.content_end]);
                    }
                }
            }
            _ => {}
        }
    }
    Err(AacError::format("isomp4: mp4a entry carries no esds box"))
}

/// Parsed sample-table boxes of one track.
struct SampleTable {
    /// Per-sample byte sizes from `stsz`.
    sizes: Vec<u32>,
    /// `stsc` entries: (first_chunk 1-based, samples_per_chunk).
    stsc: Vec<(u32, u32)>,
    /// Chunk byte offsets from `stco`/`co64`.
    chunk_offsets: Vec<u64>,
    /// Total per-channel samples from `stts`.
    total_samples: u64,
}

struct SoundMdia {
    asc: Vec<u8>,
    table: SampleTable,
    timescale: u32,
    duration: u64,
}

/// `base + index * stride`, or an overflow error. The add stays checked
/// so a raised index budget cannot panic on a 32-bit target.
fn table_pos(base: usize, index: usize, stride: usize, what: &'static str) -> Result<usize> {
    index
        .checked_mul(stride)
        .and_then(|span| base.checked_add(span))
        .ok_or_else(|| AacError::format(format!("isomp4: {what} overflow")))
}

/// Parse one `stts` box body: total sample count is Σ entry.sample_count.
fn parse_stts(data: &[u8], mem: &MemoryBudgets) -> Result<u64> {
    let count = read_u32(data, 4)? as usize;
    fence_entries(mem, count as u64, 8)?;
    let mut total = 0u64;
    for i in 0..count {
        let sample_count = read_u32(data, table_pos(8, i, 8, "stts")?)?;
        total = total
            .checked_add(u64::from(sample_count))
            .ok_or_else(|| AacError::format("isomp4: stts total overflow"))?;
    }
    Ok(total)
}

fn read_u32(data: &[u8], pos: usize) -> Result<u32> {
    let end = pos
        .checked_add(4)
        .ok_or_else(|| AacError::format("isomp4: truncated table"))?;
    let b = data
        .get(pos..end)
        .ok_or_else(|| AacError::format("isomp4: truncated table"))?;
    let arr: [u8; 4] = b
        .try_into()
        .map_err(|_| AacError::format("isomp4: truncated table"))?;
    Ok(u32::from_be_bytes(arr))
}

fn read_u64(data: &[u8], pos: usize) -> Result<u64> {
    let hi = u64::from(read_u32(data, pos)?);
    let lo_at = pos
        .checked_add(4)
        .ok_or_else(|| AacError::format("isomp4: truncated table"))?;
    let lo = u64::from(read_u32(data, lo_at)?);
    Ok((hi << 32) | lo)
}

pub(crate) fn convert_units(value: u64, dst_ts: u32, src_ts: u32, what: &str) -> Result<u64> {
    if src_ts == 0 || dst_ts == 0 {
        return Err(AacError::format(format!("isomp4: {what} timescale is 0")));
    }
    let prod = value
        .checked_mul(u64::from(dst_ts))
        .ok_or_else(|| AacError::format(format!("isomp4: {what} overflow")))?;
    if prod % u64::from(src_ts) != 0 {
        return Err(AacError::format(format!(
            "isomp4: {what} is not an integer number of samples"
        )));
    }
    Ok(prod / u64::from(src_ts))
}

fn convert_exact(value: u64, dst_ts: u32, src_ts: u32, what: &str) -> Result<usize> {
    usize::try_from(convert_units(value, dst_ts, src_ts, what)?)
        .map_err(|_| AacError::format(format!("isomp4: {what} exceeds usize")))
}

fn parse_stsz(data: &[u8], file_len: u64, mem: &MemoryBudgets) -> Result<Vec<u32>> {
    let default_size = read_u32(data, 4)?;
    let count = read_u32(data, 8)? as usize;
    fence_entries(mem, count as u64, 4)?;
    if default_size != 0 {
        // No per-entry table follows, so `count` is bounded only by the
        // declaration itself: a crafted header could force a multi-GiB
        // allocation before the duration budget fires. The samples are
        // disjoint byte ranges inside the file, so their total size cannot
        // exceed the whole input length — fence against `file_len`, not the
        // stsz body (always 12 bytes here, which would reject any legit
        // CBR file with more than 12 frames; ffmpeg movenc writes exactly
        // this shape). The byte-range walk in build_frame_index re-checks
        // every sample against the real offsets.
        let total = u64::from(default_size)
            .checked_mul(count as u64)
            .ok_or_else(|| AacError::format("isomp4: stsz overflow"))?;
        if total > file_len {
            return Err(AacError::format(format!(
                "isomp4: stsz declares {count} samples of {default_size} bytes, more than the input holds"
            )));
        }
        let mut sizes = Vec::new();
        sizes.try_reserve(count).map_err(|_| {
            AacError::from(crate::budgets::BudgetExceeded {
                kind: crate::budgets::BudgetKind::Metadata,
                observed: (count as u64).saturating_mul(4),
                max: mem.max_metadata_bytes,
            })
        })?;
        sizes.resize(count, default_size);
        return Ok(sizes);
    }
    let mut sizes = Vec::new();
    sizes.try_reserve(count).map_err(|_| {
        AacError::from(crate::budgets::BudgetExceeded {
            kind: crate::budgets::BudgetKind::Metadata,
            observed: (count as u64).saturating_mul(4),
            max: mem.max_metadata_bytes,
        })
    })?;
    for i in 0..count {
        sizes.push(read_u32(data, table_pos(12, i, 4, "stsz")?)?);
    }
    Ok(sizes)
}

fn parse_stsc(data: &[u8], mem: &MemoryBudgets) -> Result<Vec<(u32, u32)>> {
    let count = read_u32(data, 4)? as usize;
    fence_entries(mem, count as u64, 12)?;
    let mut out = Vec::new();
    out.try_reserve(count).map_err(|_| {
        AacError::from(crate::budgets::BudgetExceeded {
            kind: crate::budgets::BudgetKind::Metadata,
            observed: (count as u64).saturating_mul(12),
            max: mem.max_metadata_bytes,
        })
    })?;
    for i in 0..count {
        let base = table_pos(8, i, 12, "stsc")?;
        let first_chunk = read_u32(data, base)?;
        let samples_per_chunk = read_u32(data, table_pos(base, 1, 4, "stsc")?)?;
        // sample_description_index (base + 8) is read but only the first
        // entry's mp4a is ever used; a mid-file switch is rejected later by
        // the byte-range walk producing garbage — ffmpeg never emits it.
        out.push((first_chunk, samples_per_chunk));
    }
    if out.is_empty() {
        return Err(AacError::format("isomp4: empty stsc"));
    }
    Ok(out)
}

fn parse_stco(data: &[u8], wide: bool, mem: &MemoryBudgets) -> Result<Vec<u64>> {
    let count = read_u32(data, 4)? as usize;
    let bpe = if wide { 8 } else { 4 };
    fence_entries(mem, count as u64, bpe)?;
    let mut out = Vec::new();
    out.try_reserve(count).map_err(|_| {
        AacError::from(crate::budgets::BudgetExceeded {
            kind: crate::budgets::BudgetKind::Metadata,
            observed: (count as u64).saturating_mul(bpe),
            max: mem.max_metadata_bytes,
        })
    })?;
    for i in 0..count {
        let off = if wide {
            let base = table_pos(8, i, 8, "co64")?;
            let hi = read_u32(data, base)? as u64;
            let lo = read_u32(data, table_pos(base, 1, 4, "co64")?)? as u64;
            (hi << 32) | lo
        } else {
            read_u32(data, table_pos(8, i, 4, "stco")?)? as u64
        };
        out.push(off);
    }
    Ok(out)
}

/// Parse the sample-table boxes of one track's `stbl`.
fn parse_stbl(
    data: &[u8],
    stbl: BoxHdr,
    mem: &MemoryBudgets,
    file_len: u64,
) -> Result<(Vec<u8>, SampleTable)> {
    let mut asc = None;
    let mut stts_total = None;
    let mut sizes = None;
    let mut stsc = None;
    let mut chunk_offsets = None;
    for child in BoxIter::new(data, stbl.content_start, stbl.content_end) {
        let (hdr, typ) = child?;
        let body = &data[hdr.content_start..hdr.content_end];
        match &typ {
            b"stsd" => asc = Some(parse_stsd_asc(body)?),
            b"stts" => stts_total = Some(parse_stts(body, mem)?),
            b"stsz" => sizes = Some(parse_stsz(body, file_len, mem)?),
            b"stsc" => stsc = Some(parse_stsc(body, mem)?),
            b"stco" => chunk_offsets = Some(parse_stco(body, false, mem)?),
            b"co64" => chunk_offsets = Some(parse_stco(body, true, mem)?),
            _ => {}
        }
    }
    let asc =
        asc.ok_or_else(|| AacError::format("isomp4: no AAC sample description (stsd/mp4a)"))?;
    let table = SampleTable {
        sizes: sizes.ok_or_else(|| AacError::format("isomp4: missing stsz"))?,
        stsc: stsc.ok_or_else(|| AacError::format("isomp4: missing stsc"))?,
        chunk_offsets: chunk_offsets
            .ok_or_else(|| AacError::format("isomp4: missing stco/co64"))?,
        total_samples: stts_total.ok_or_else(|| AacError::format("isomp4: missing stts"))?,
    };
    Ok((asc, table))
}

fn parse_stsd_asc(body: &[u8]) -> Result<Vec<u8>> {
    let entries = read_u32(body, 4)? as usize;
    if entries == 0 {
        return Err(AacError::format("isomp4: stsd with no sample entries"));
    }
    let (ehdr, etyp) =
        read_box(body, 8)?.ok_or_else(|| AacError::format("isomp4: truncated stsd entry"))?;
    match &etyp {
        b"mp4a" => {}
        b"enca" => {
            return Err(AacError::format(
                "isomp4: encrypted (DRM) audio is not supported",
            ));
        }
        other => {
            return Err(AacError::format(format!(
                "isomp4: unsupported audio sample entry '{}'",
                String::from_utf8_lossy(other)
            )));
        }
    }
    let body_start = ehdr.content_start;
    let version = u16::from_be_bytes([
        *body
            .get(body_start + 8)
            .ok_or_else(|| AacError::format("isomp4: truncated mp4a entry"))?,
        *body
            .get(body_start + 9)
            .ok_or_else(|| AacError::format("isomp4: truncated mp4a entry"))?,
    ]);
    let fixed = match version {
        0 => 28usize,
        1 => 28 + 16,
        2 => 28 + 36,
        v => {
            return Err(AacError::format(format!(
                "isomp4: unsupported sound sample entry version {v}"
            )));
        }
    };
    let children = BoxHdr {
        content_start: body_start
            .checked_add(fixed)
            .filter(|&e| e <= ehdr.content_end)
            .ok_or_else(|| AacError::format("isomp4: truncated mp4a entry"))?,
        content_end: ehdr.content_end,
    };
    extract_asc(body, children)
}

fn parse_stbl_asc(data: &[u8], stbl: BoxHdr) -> Result<Vec<u8>> {
    for child in BoxIter::new(data, stbl.content_start, stbl.content_end) {
        let (hdr, typ) = child?;
        if &typ == b"stsd" {
            return parse_stsd_asc(&data[hdr.content_start..hdr.content_end]);
        }
    }
    Err(AacError::format(
        "isomp4: no AAC sample description (stsd/mp4a)",
    ))
}

/// Supported `elst`: no entries, or exactly one playable entry
/// (`media_time >= 0`, `media_rate = 1`). Empty edits, multiple edits,
/// other rates, and unknown versions are errors — never a silent prefix skip.
fn parse_elst(body: &[u8], mem: &MemoryBudgets) -> Result<Option<(u64, u64)>> {
    let version = *body
        .first()
        .ok_or_else(|| AacError::format("isomp4: truncated elst"))?;
    let count = read_u32(body, 4)? as usize;
    fence_entries(mem, count as u64, if version == 1 { 20 } else { 12 })?;
    if count == 0 {
        return Ok(None);
    }
    if count != 1 {
        return Err(AacError::format(
            "isomp4: multiple elst edits are not supported",
        ));
    }
    let (segment_duration, media_time, rate) = if version == 1 {
        let seg = read_u64(body, 8)?;
        let mt = i64::from_be_bytes(read_u64(body, 16)?.to_be_bytes());
        (seg, mt, read_u32(body, 24)?)
    } else if version == 0 {
        (
            u64::from(read_u32(body, 8)?),
            i64::from(read_u32(body, 12)? as i32),
            read_u32(body, 16)?,
        )
    } else {
        return Err(AacError::format("isomp4: unsupported elst version"));
    };
    if media_time < 0 {
        return Err(AacError::format("isomp4: empty elst edit is not supported"));
    }
    if rate != 0x0001_0000 {
        return Err(AacError::format(
            "isomp4: elst media_rate other than 1 is not supported",
        ));
    }
    Ok(Some((media_time as u64, segment_duration)))
}

#[cfg(test)]
fn parse_elst_start(body: &[u8], mem: &MemoryBudgets) -> Result<u64> {
    Ok(parse_elst(body, mem)?.map_or(0, |e| e.0))
}

fn parse_mdhd_timescale(body: &[u8]) -> Result<u32> {
    let version = *body
        .first()
        .ok_or_else(|| AacError::format("isomp4: truncated mdhd"))?;
    let off = match version {
        0 => 12usize,
        1 => 20usize,
        _ => return Err(AacError::format("isomp4: unsupported mdhd version")),
    };
    read_u32(body, off)
}

fn parse_mdhd_duration(body: &[u8]) -> Result<u64> {
    let version = *body
        .first()
        .ok_or_else(|| AacError::format("isomp4: truncated mdhd"))?;
    match version {
        0 => Ok(u64::from(read_u32(body, 16)?)),
        1 => read_u64(body, 24),
        _ => Err(AacError::format("isomp4: unsupported mdhd version")),
    }
}

fn parse_mvhd_timescale(body: &[u8]) -> Result<u32> {
    let version = *body
        .first()
        .ok_or_else(|| AacError::format("isomp4: truncated mvhd"))?;
    let off = match version {
        0 => 12usize,
        1 => 20usize,
        _ => return Err(AacError::format("isomp4: unsupported mvhd version")),
    };
    read_u32(body, off)
}

/// Walk one `mdia` box: is it sound (`hdlr` = 'soun'), and if so parse its
/// `minf/stbl` and `mdhd` timescale. Returns `None` for non-sound tracks.
fn parse_mdia(
    data: &[u8],
    mdia: BoxHdr,
    mem: &MemoryBudgets,
    file_len: u64,
) -> Result<Option<SoundMdia>> {
    let mut is_sound = false;
    let mut table = None;
    let mut timescale = 0u32;
    let mut media_duration = 0u64;
    for child in BoxIter::new(data, mdia.content_start, mdia.content_end) {
        let (hdr, typ) = child?;
        match &typ {
            b"hdlr" => {
                // version/flags(4) + pre_defined(4) + handler_type(4).
                let handler = data
                    .get(hdr.content_start + 8..hdr.content_start + 12)
                    .ok_or_else(|| AacError::format("isomp4: truncated hdlr"))?;
                is_sound = handler == b"soun";
            }
            b"mdhd" => {
                let body = &data[hdr.content_start..hdr.content_end];
                timescale = parse_mdhd_timescale(body)?;
                media_duration = parse_mdhd_duration(body).unwrap_or(0);
            }
            b"minf" => {
                for sub in BoxIter::new(data, hdr.content_start, hdr.content_end) {
                    let (shdr, styp) = sub?;
                    if &styp == b"stbl" {
                        table = Some(parse_stbl(data, shdr, mem, file_len)?);
                    }
                }
            }
            _ => {}
        }
    }
    if is_sound {
        let table = table.ok_or_else(|| AacError::format("isomp4: sound track without stbl"))?;
        Ok(Some(SoundMdia {
            asc: table.0,
            table: table.1,
            timescale,
            duration: media_duration,
        }))
    } else {
        Ok(None)
    }
}

fn parse_mdia_meta(
    data: &[u8],
    mdia: BoxHdr,
    mem: &MemoryBudgets,
) -> Result<Option<(Vec<u8>, u32, u64)>> {
    fence_depth(mem, 3)?;
    let mut is_sound = false;
    let mut asc = None;
    let mut timescale = 0u32;
    let mut media_duration = 0u64;
    for child in BoxIter::new(data, mdia.content_start, mdia.content_end) {
        let (hdr, typ) = child?;
        match &typ {
            b"hdlr" => {
                let handler = data
                    .get(hdr.content_start + 8..hdr.content_start + 12)
                    .ok_or_else(|| AacError::format("isomp4: truncated hdlr"))?;
                is_sound = handler == b"soun";
            }
            b"mdhd" => {
                let body = &data[hdr.content_start..hdr.content_end];
                timescale = parse_mdhd_timescale(body)?;
                media_duration = parse_mdhd_duration(body).unwrap_or(0);
            }
            b"minf" => {
                for sub in BoxIter::new(data, hdr.content_start, hdr.content_end) {
                    let (shdr, styp) = sub?;
                    if &styp == b"stbl" {
                        fence_depth(mem, 4)?;
                        asc = Some(parse_stbl_asc(data, shdr)?);
                    }
                }
            }
            _ => {}
        }
    }
    if is_sound {
        let asc = asc.ok_or_else(|| AacError::format("isomp4: sound track without stbl"))?;
        Ok(Some((asc, timescale, media_duration)))
    } else {
        Ok(None)
    }
}

/// Map the sample table to absolute byte ranges, one per AAC frame.
fn build_frame_index(
    data_len: u64,
    table: &SampleTable,
    mem: &MemoryBudgets,
) -> Result<Vec<(u64, u32)>> {
    let n_samples = table.sizes.len();
    fence_entries(mem, n_samples as u64, 16)?;
    let mut frames = Vec::new();
    frames.try_reserve(n_samples).map_err(|_| {
        AacError::from(crate::budgets::BudgetExceeded {
            kind: crate::budgets::BudgetKind::Metadata,
            observed: (n_samples as u64).saturating_mul(16),
            max: mem.max_metadata_bytes,
        })
    })?;
    let mut sample_idx = 0usize;
    let mut stsc_idx = 0usize;
    for (chunk_i, &chunk_off) in table.chunk_offsets.iter().enumerate() {
        // stsc entries are sorted by first_chunk (1-based); advance while the
        // next entry starts at or before this chunk.
        let chunk_no = chunk_i as u32 + 1;
        while stsc_idx + 1 < table.stsc.len() && table.stsc[stsc_idx + 1].0 <= chunk_no {
            stsc_idx += 1;
        }
        let per_chunk = table.stsc[stsc_idx].1 as usize;
        let mut off = chunk_off;
        for _ in 0..per_chunk {
            let Some(&size) = table.sizes.get(sample_idx) else {
                return Err(AacError::format(
                    "isomp4: stsc/stsz disagree on the sample count",
                ));
            };
            let end = off
                .checked_add(u64::from(size))
                .filter(|&e| e <= data_len)
                .ok_or_else(|| AacError::format("isomp4: sample extends past end of input"))?;
            frames.push((off, size));
            off = end;
            sample_idx += 1;
        }
    }
    if sample_idx != n_samples {
        return Err(AacError::format(format!(
            "isomp4: stsz declares {n_samples} samples but the chunk walk placed {sample_idx}"
        )));
    }
    if frames.is_empty() {
        return Err(AacError::format("isomp4: track has no audio samples"));
    }
    Ok(frames)
}

/// Parse `data` as an ISOBMFF file and extract its first AAC audio track.
///
/// Errors are all clean `AacError` returns; no input can panic or index out
/// of bounds.
#[cfg(test)]
pub(crate) fn parse_aac_track(data: &[u8]) -> Result<AacTrack> {
    parse_aac_track_with(data, &MemoryBudgets::default())
}

pub(crate) fn parse_aac_track_with(data: &[u8], mem: &MemoryBudgets) -> Result<AacTrack> {
    parse_aac_track_with_len(data, data.len() as u64, mem)
}

/// Like [`parse_aac_track_with`], but `file_len` is the ISOBMFF file size
/// used for `stsz`/`stco` range fences. `data` may be the whole file or a
/// standalone `moov` box (seekable demux loads only `moov`).
pub(crate) fn parse_aac_track_with_len(
    data: &[u8],
    file_len: u64,
    mem: &MemoryBudgets,
) -> Result<AacTrack> {
    fence_depth(mem, 0)?;
    let mut moov = None;
    for top in BoxIter::new(data, 0, data.len()) {
        let (hdr, typ) = top?;
        if typ == BOX_MOOV {
            moov = Some(hdr);
        } else if typ == BOX_MOOF || typ == BOX_MVEX {
            return Err(AacError::format("isomp4: fragmented MP4 is not supported"));
        }
    }
    let moov = moov.ok_or_else(|| AacError::format("isomp4: no moov box"))?;

    // Nested containers contain no moof/mvex at their level; fragmentation
    // also shows up as an `mvex` child of moov.
    fence_depth(mem, 1)?;
    let mut track = None;
    let mut movie_timescale = 0u32;
    for child in BoxIter::new(data, moov.content_start, moov.content_end) {
        let (hdr, typ) = child?;
        if typ == BOX_MVEX {
            return Err(AacError::format("isomp4: fragmented MP4 is not supported"));
        } else if &typ == b"mvhd" {
            movie_timescale = parse_mvhd_timescale(&data[hdr.content_start..hdr.content_end])?;
        } else if typ == BOX_TRAK {
            if track.is_some() {
                continue;
            }
            fence_depth(mem, 2)?;
            let mut edit_start = 0u64;
            let mut edit_duration = 0u64;
            let mut has_elst = false;
            let mut mdia_track = None;
            for sub in BoxIter::new(data, hdr.content_start, hdr.content_end) {
                let (shdr, styp) = sub?;
                match &styp {
                    b"edts" => {
                        fence_depth(mem, 3)?;
                        for ed in BoxIter::new(data, shdr.content_start, shdr.content_end) {
                            let (ehdr, etyp) = ed?;
                            if &etyp == b"elst" {
                                fence_depth(mem, 4)?;
                                if let Some((start, dur)) =
                                    parse_elst(&data[ehdr.content_start..ehdr.content_end], mem)?
                                {
                                    edit_start = start;
                                    edit_duration = dur;
                                    has_elst = true;
                                }
                            }
                        }
                    }
                    b"mdia" => {
                        fence_depth(mem, 3)?;
                        // A broken or non-AAC sound track must not sink the
                        // whole file: skip it and keep looking for a usable
                        // AAC track. Structural box-walk errors stay fatal.
                        match parse_mdia(data, shdr, mem, file_len) {
                            Ok(Some(t)) => mdia_track = Some(t),
                            Ok(None) => {}
                            Err(e @ AacError::Limit { .. }) => return Err(e),
                            Err(_) => {}
                        }
                    }
                    _ => {}
                }
            }
            if let Some(mdia) = mdia_track {
                track = Some((
                    mdia.asc,
                    mdia.table,
                    mdia.timescale,
                    edit_start,
                    edit_duration,
                    mdia.duration,
                    has_elst,
                ));
            }
        }
    }
    let (asc, table, media_timescale, edit_start, edit_duration, media_duration, has_elst) =
        track.ok_or_else(|| AacError::format("isomp4: no AAC audio track found"))?;
    let frames = build_frame_index(file_len, &table, mem)?;
    Ok(AacTrack {
        asc,
        total_samples: table.total_samples,
        frames,
        edit_start,
        edit_duration,
        movie_timescale,
        media_timescale,
        media_duration,
        has_elst,
        edit_open_end: false,
    })
}

/// ASC + `mdhd`/`elst` timing. Does not allocate `stsz`/`stco`/`stts`.
pub(crate) fn parse_aac_meta(data: &[u8], mem: &MemoryBudgets) -> Result<AacMeta> {
    fence_depth(mem, 0)?;
    let mut moov = None;
    for top in BoxIter::new(data, 0, data.len()) {
        let (hdr, typ) = top?;
        if typ == BOX_MOOV {
            moov = Some(hdr);
        } else if typ == BOX_MOOF || typ == BOX_MVEX {
            return Err(AacError::format("isomp4: fragmented MP4 is not supported"));
        }
    }
    let moov = moov.ok_or_else(|| AacError::format("isomp4: no moov box"))?;
    fence_depth(mem, 1)?;
    let mut track = None;
    let mut movie_timescale = 0u32;
    for child in BoxIter::new(data, moov.content_start, moov.content_end) {
        let (hdr, typ) = child?;
        if typ == BOX_MVEX {
            return Err(AacError::format("isomp4: fragmented MP4 is not supported"));
        } else if &typ == b"mvhd" {
            movie_timescale = parse_mvhd_timescale(&data[hdr.content_start..hdr.content_end])?;
        } else if typ == BOX_TRAK {
            if track.is_some() {
                continue;
            }
            fence_depth(mem, 2)?;
            let mut edit_start = 0u64;
            let mut edit_duration = 0u64;
            let mut has_elst = false;
            let mut mdia_track = None;
            for sub in BoxIter::new(data, hdr.content_start, hdr.content_end) {
                let (shdr, styp) = sub?;
                match &styp {
                    b"edts" => {
                        fence_depth(mem, 3)?;
                        for ed in BoxIter::new(data, shdr.content_start, shdr.content_end) {
                            let (ehdr, etyp) = ed?;
                            if &etyp == b"elst" {
                                fence_depth(mem, 4)?;
                                if let Some((start, dur)) =
                                    parse_elst(&data[ehdr.content_start..ehdr.content_end], mem)?
                                {
                                    edit_start = start;
                                    edit_duration = dur;
                                    has_elst = true;
                                }
                            }
                        }
                    }
                    b"mdia" => match parse_mdia_meta(data, shdr, mem) {
                        Ok(Some(t)) => mdia_track = Some(t),
                        Ok(None) => {}
                        Err(e @ AacError::Limit { .. }) => return Err(e),
                        Err(_) => {}
                    },
                    _ => {}
                }
            }
            if let Some((asc, media_timescale, media_duration)) = mdia_track {
                track = Some((
                    asc,
                    media_timescale,
                    edit_start,
                    edit_duration,
                    media_duration,
                    has_elst,
                ));
            }
        }
    }
    let (asc, media_timescale, edit_start, edit_duration, media_duration, has_elst) =
        track.ok_or_else(|| AacError::format("isomp4: no AAC audio track found"))?;
    Ok(AacMeta {
        asc,
        edit_start,
        edit_duration,
        movie_timescale,
        media_timescale,
        media_duration,
        has_elst,
    })
}

/// Locate a complete `moov` in a slice. Skips `mdat` by declared size so a
/// prefix that does not contain media still probes. Incomplete headers and
/// a missing `moov` are [`AacError::NeedMore`].
pub(crate) fn find_moov_slice<'a>(data: &'a [u8], mem: &MemoryBudgets) -> Result<&'a [u8]> {
    let mut pos = 0usize;
    let n = data.len() as u64;
    loop {
        if (pos as u64).saturating_add(8) > n {
            return Err(AacError::NeedMore {
                have: n,
                need: (pos as u64).saturating_add(8),
            });
        }
        let mut size_bytes = [0u8; 4];
        size_bytes.copy_from_slice(&data[pos..pos + 4]);
        let size32 = u32::from_be_bytes(size_bytes) as u64;
        let typ: FourCc = [data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]];
        let (size, head) = match size32 {
            1 => {
                if (pos as u64).saturating_add(16) > n {
                    return Err(AacError::NeedMore {
                        have: n,
                        need: (pos as u64).saturating_add(16),
                    });
                }
                let mut ext = [0u8; 8];
                ext.copy_from_slice(&data[pos + 8..pos + 16]);
                (u64::from_be_bytes(ext), 16u64)
            }
            0 => (n.saturating_sub(pos as u64), 8u64),
            s => (s, 8u64),
        };
        if size < head {
            return Err(AacError::format(format!(
                "isomp4: box size {size} smaller than its header"
            )));
        }
        let end = (pos as u64)
            .checked_add(size)
            .ok_or_else(|| AacError::format("isomp4: box size overflow"))?;
        if typ == BOX_MOOF || typ == BOX_MVEX {
            return Err(AacError::format("isomp4: fragmented MP4 is not supported"));
        }
        if typ == BOX_MOOV {
            check_planned(BudgetKind::Metadata, size, mem.max_metadata_bytes)?;
            if end > n {
                return Err(AacError::NeedMore { have: n, need: end });
            }
            let end_us =
                usize::try_from(end).map_err(|_| AacError::format("isomp4: moov exceeds usize"))?;
            return Ok(&data[pos..end_us]);
        }
        if size32 == 0 {
            return Err(AacError::format("isomp4: no moov box"));
        }
        if end > n {
            return Err(AacError::NeedMore { have: n, need: end });
        }
        pos = usize::try_from(end).map_err(|_| AacError::format("isomp4: box exceeds usize"))?;
    }
}

/// True when `data` opens with a plausible ISOBMFF `ftyp` box.
pub(crate) fn sniff_is_m4a(data: &[u8]) -> bool {
    if data.len() < 8 {
        return false;
    }
    if &data[4..8] != b"ftyp" {
        return false;
    }
    let size = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
    if size < 8 {
        return false;
    }
    if data.len() >= 12 {
        return data[8..12]
            .iter()
            .all(|b| b.is_ascii_graphic() || *b == b' ');
    }
    true
}

#[inline]
pub fn sniff_is_isobmff(data: &[u8]) -> bool {
    sniff_is_m4a(data)
}

#[path = "isomp4_io.rs"]
mod io;
pub(crate) use io::{TrackBoxes, load_track_boxes};

#[path = "isomp4_frag.rs"]
pub(crate) mod frag;

#[cfg(test)]
#[path = "isomp4_struct_tests.rs"]
mod isomp4_struct_tests;

#[cfg(test)]
#[path = "isomp4_tests.rs"]
mod isomp4_tests;