transmux 0.27.4

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
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
//! Biting tests for the fMP4/CMAF conformance validator (issue #481).
//!
//! Each Error check gets BOTH a positive (clean → no such issue) and a negative
//! (broken → the exact `code`) assertion, so it cannot be satisfied by an
//! always-pass or always-fail validator. Clean segments are built from the real
//! codec configs + real coded samples of `h264_aac_frag.mp4` via the crate's own
//! `build_init_segment` / `build_media_segment`.

use broadcast_common::Parse;
use transmux::TrackId;
use transmux::{
    CodecConfig, FragmentTrackData, MovieBox, MovieFragmentBox, Sample, SampleEntryVariant,
    Severity, StblChild, TrackSpec, build_init_segment, build_media_segment, validate_cmaf_track,
    validate_init_segment, validate_media_segment,
};

// ---------------------------------------------------------------------------
// Fixture plumbing (mirrors tests/pipeline.rs)
// ---------------------------------------------------------------------------

fn fixture() -> Vec<u8> {
    test_fixtures::read("transmux/h264_aac_frag.mp4")
}

fn find_top_box(data: &[u8], fourcc: &[u8; 4]) -> (usize, Vec<u8>) {
    let mut off = 0usize;
    while off + 8 <= data.len() {
        let size =
            u32::from_be_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]) as usize;
        if size < 8 {
            break;
        }
        if &data[off + 4..off + 8] == fourcc {
            return (off, data[off..off + size].to_vec());
        }
        off += size;
    }
    panic!("box {:?} not found", std::str::from_utf8(fourcc).unwrap());
}

fn track_stsd_entry(moov: &MovieBox, track_idx: usize) -> SampleEntryVariant {
    let stbl = moov.tracks[track_idx]
        .mdia
        .as_ref()
        .unwrap()
        .minf
        .as_ref()
        .unwrap()
        .stbl
        .as_ref()
        .unwrap();
    stbl.children
        .iter()
        .find_map(|c| match c {
            StblChild::Stsd(s) => Some(s),
            _ => None,
        })
        .unwrap()
        .entries[0]
        .clone()
}

fn track_timescale(moov: &MovieBox, track_idx: usize) -> u32 {
    moov.tracks[track_idx]
        .mdia
        .as_ref()
        .unwrap()
        .mdhd
        .as_ref()
        .unwrap()
        .timescale
}

/// Build a single-video-track spec from the fixture's real avcC.
fn video_spec(moov: &MovieBox) -> TrackSpec {
    let avc = match track_stsd_entry(moov, 0) {
        SampleEntryVariant::Avc1(a) => a,
        _ => panic!("expected avc1"),
    };
    TrackSpec::new(
        TrackId::new(1),
        track_timescale(moov, 0),
        CodecConfig::Avc {
            config: avc.config.clone(),
            width: avc.visual.width,
            height: avc.visual.height,
        },
    )
}

/// Extract the first moof's video samples (track index 0).
fn video_samples(data: &[u8]) -> Vec<Sample> {
    let (moof_off, moof_bytes) = find_top_box(data, b"moof");
    let moof = MovieFragmentBox::parse_body(&moof_bytes[8..]).expect("moof");
    let traf = &moof.traf[0];
    let trun = &traf.trun[0];
    let base = moof_off + trun.data_offset.expect("data_offset") as usize;
    let mut samples = Vec::new();
    let mut cursor = base;
    // Absolute dts from the running trun duration sum (media plane step 2c);
    // pts folds in the trun composition offset.
    let mut next_dts: i64 = 0;
    for (i, ts) in trun.samples.iter().enumerate() {
        let size = ts.sample_size.expect("sample_size") as usize;
        let dur = ts.sample_duration.unwrap_or(3000);
        let co = ts.sample_composition_time_offset.unwrap_or(0);
        samples.push(Sample::new(
            data[cursor..cursor + size].to_vec(),
            Some(next_dts),
            Some(next_dts + co),
            Some(dur),
            i == 0,
        ));
        next_dts += i64::from(dur);
        cursor += size;
    }
    samples
}

/// A clean init segment (single video track) built from the fixture.
fn clean_init() -> Vec<u8> {
    let data = fixture();
    let (_, moov_bytes) = find_top_box(&data, b"moov");
    let moov = MovieBox::parse(&moov_bytes).unwrap();
    build_init_segment(&[video_spec(&moov)], 1000).expect("build init")
}

/// A clean media segment with the given sequence_number + base decode time,
/// carrying the real video samples.
fn clean_media(seq: u32, base_time: u64, samples: &[Sample]) -> Vec<u8> {
    build_media_segment(
        seq,
        &[FragmentTrackData::new(TrackId::new(1), base_time, samples)],
    )
    .expect("build media")
}

// ---------------------------------------------------------------------------
// Box-tree mutation helpers (test-only)
// ---------------------------------------------------------------------------

/// Walk top-level boxes, returning (offset, size, fourcc) for each.
fn top_boxes(data: &[u8]) -> Vec<(usize, usize, [u8; 4])> {
    let mut out = Vec::new();
    let mut off = 0usize;
    while off + 8 <= data.len() {
        let size =
            u32::from_be_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]) as usize;
        if size < 8 || off + size > data.len() {
            break;
        }
        out.push((
            off,
            size,
            [data[off + 4], data[off + 5], data[off + 6], data[off + 7]],
        ));
        off += size;
    }
    out
}

const CONTAINERS: &[&[u8; 4]] = &[
    b"moov", b"trak", b"mdia", b"minf", b"stbl", b"mvex", b"moof", b"traf", b"edts", b"dinf",
];

/// Remove the first descendant box of `fourcc` found anywhere inside `data`
/// (recursive descent through container boxes), shrinking every enclosing box's
/// size field. Returns the mutated buffer. Simple byte-splice; sufficient for
/// test stimuli.
fn strip_box(data: &[u8], fourcc: &[u8; 4]) -> Vec<u8> {
    // Locate the box in the ORIGINAL coordinate space.
    let (start, size) = find_box_range(data, 0, data.len(), fourcc).expect("box to strip present");
    // Copy, then decrement the size of every ancestor whose original span
    // contained [start, start+size), before splicing the bytes out.
    let mut out = data.to_vec();
    shrink_ancestors(&mut out, 0, data.len(), start, size);
    out.drain(start..start + size);
    out
}

/// Recursively locate a box of `fourcc` within [lo, hi). Returns (abs_offset,
/// box_size). Descends into known container boxes.
fn find_box_range(data: &[u8], lo: usize, hi: usize, fourcc: &[u8; 4]) -> Option<(usize, usize)> {
    let mut off = lo;
    while off + 8 <= hi {
        let size =
            u32::from_be_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]) as usize;
        if size < 8 || off + size > hi {
            break;
        }
        let t = [data[off + 4], data[off + 5], data[off + 6], data[off + 7]];
        if &t == fourcc {
            return Some((off, size));
        }
        if CONTAINERS.contains(&&t)
            && let Some(found) = find_box_range(data, off + 8, off + size, fourcc)
        {
            return Some(found);
        }
        off += size;
    }
    None
}

/// Decrement (in place, ORIGINAL coordinate space) the 32-bit size of every box
/// in [lo, hi) whose span contains the region [cut_start, cut_start+cut_len).
fn shrink_ancestors(data: &mut [u8], lo: usize, hi: usize, cut_start: usize, cut_len: usize) {
    let mut off = lo;
    while off + 8 <= hi {
        let size =
            u32::from_be_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]) as usize;
        if size < 8 || off + size > hi {
            break;
        }
        let t = [data[off + 4], data[off + 5], data[off + 6], data[off + 7]];
        // Ancestor if it strictly contains the cut (but is not the cut box).
        if off < cut_start && cut_start + cut_len <= off + size {
            let new_size = (size - cut_len) as u32;
            data[off..off + 4].copy_from_slice(&new_size.to_be_bytes());
            if CONTAINERS.contains(&&t) {
                shrink_ancestors(data, off + 8, off + size, cut_start, cut_len);
            }
        }
        off += size;
    }
}

/// Rename the first descendant box of `from` to `to` (same-length 4-CC),/// Rename the first descendant box of `from` to `to` (same-length 4-CC),
/// leaving every size unchanged. Used to "remove" a box structurally (the
/// validator no longer sees it) without disturbing sibling offsets — e.g.
/// turning `tfdt` into `free` so the trun `data_offset` arithmetic still holds.
fn rename_box(data: &[u8], from: &[u8; 4], to: &[u8; 4]) -> Vec<u8> {
    let (start, _) = find_box_range(data, 0, data.len(), from).expect("box to rename present");
    let mut out = data.to_vec();
    out[start + 4..start + 8].copy_from_slice(to);
    out
}

fn has_code(issues: &[transmux::ConformanceIssue], code: &str) -> bool {
    issues.iter().any(|i| i.code == code)
}

fn errors(issues: &[transmux::ConformanceIssue]) -> Vec<&str> {
    issues
        .iter()
        .filter(|i| i.severity == Severity::Error)
        .map(|i| i.code)
        .collect()
}

// ---------------------------------------------------------------------------
// 1. Clean segments pass (no Errors)
// ---------------------------------------------------------------------------

#[test]
fn clean_init_has_no_errors() {
    let init = clean_init();
    let issues = validate_init_segment(&init);
    assert!(
        errors(&issues).is_empty(),
        "clean init flagged errors: {:?}",
        errors(&issues)
    );
}

#[test]
fn clean_media_has_no_errors() {
    let data = fixture();
    let samples = video_samples(&data);
    let media = clean_media(1, 0, &samples);
    let issues = validate_media_segment(&media);
    assert!(
        errors(&issues).is_empty(),
        "clean media flagged errors: {:?}",
        errors(&issues)
    );
}

#[test]
fn clean_track_has_no_errors() {
    let data = fixture();
    let samples = video_samples(&data);
    let init = clean_init();
    let total: u64 = samples.iter().map(|s| s.duration.unwrap_or(0) as u64).sum();
    let seg1 = clean_media(1, 0, &samples);
    let seg2 = clean_media(2, total, &samples);
    let issues = validate_cmaf_track(&init, &[&seg1, &seg2]);
    assert!(
        errors(&issues).is_empty(),
        "clean track flagged errors: {:?}",
        errors(&issues)
    );
}

// ---------------------------------------------------------------------------
// 2. Each Error check bites (positive + negative)
// ---------------------------------------------------------------------------

#[test]
fn tfdt_missing_bites() {
    let data = fixture();
    let samples = video_samples(&data);
    let media = clean_media(1, 0, &samples);

    // positive: clean media → no tfdt.missing.
    assert!(!has_code(
        &validate_media_segment(&media),
        "media.tfdt.missing"
    ));

    // negative: turn the tfdt into a free box (same size → offsets intact) so
    // ONLY the missing-tfdt error fires, not a flood of size-driven ones.
    let broken = rename_box(&media, b"tfdt", b"free");
    let issues = validate_media_segment(&broken);
    assert!(
        has_code(&issues, "media.tfdt.missing"),
        "expected media.tfdt.missing, got {:?}",
        errors(&issues)
    );
    // Structural sanity: no unrelated moof/mfhd/traf/trun/mdat errors.
    let errs = errors(&issues);
    for bad in [
        "media.moof.missing",
        "media.mfhd.missing",
        "media.traf.missing",
        "media.trun.missing",
        "media.mdat.missing",
        "media.mdat.overrun",
    ] {
        assert!(!errs.contains(&bad), "unexpected {bad} in {errs:?}");
    }
}

#[test]
fn mdat_overrun_bites() {
    let data = fixture();
    let samples = video_samples(&data);
    let media = clean_media(1, 0, &samples);

    // positive: intact mdat → no overrun.
    assert!(!has_code(
        &validate_media_segment(&media),
        "media.mdat.overrun"
    ));

    // negative: truncate the mdat payload so trun sizes overrun it.
    // Shrink the mdat box size field and drop trailing bytes.
    let boxes = top_boxes(&media);
    let (mdat_off, mdat_size, _) = *boxes.iter().find(|(_, _, t)| t == b"mdat").unwrap();
    let cut = mdat_size / 2; // remove half the payload
    let new_mdat_size = (mdat_size - cut) as u32;
    let mut broken = Vec::new();
    broken.extend_from_slice(&media[..mdat_off]);
    broken.extend_from_slice(&new_mdat_size.to_be_bytes());
    broken.extend_from_slice(&media[mdat_off + 4..mdat_off + 8]); // "mdat"
    broken.extend_from_slice(&media[mdat_off + 8..mdat_off + mdat_size - cut]);
    // (anything after mdat is dropped)

    let issues = validate_media_segment(&broken);
    assert!(
        has_code(&issues, "media.mdat.overrun"),
        "expected media.mdat.overrun, got {:?}",
        errors(&issues)
    );
}

#[test]
fn mdat_overrun_lower_bound_bites() {
    // issue #991: a `data_offset` that points *before* the mdat payload (into
    // the moof itself, or the mdat's own box header) must be rejected even
    // when the sample range still fits comfortably under the upper bound —
    // an overrun check that only compares against `mdat_payload_end` misses
    // this entirely.
    let data = fixture();
    let samples = video_samples(&data);
    let media = clean_media(1, 0, &samples);

    // positive: intact data_offset → no overrun.
    assert!(!has_code(
        &validate_media_segment(&media),
        "media.mdat.overrun"
    ));

    // negative: rewrite trun.data_offset to 0 (the moof's own first byte).
    // The mdat is left completely untouched, so `end` (0 + total_size) still
    // sits well inside the real mdat payload — only the lower-bound check
    // added for #991 catches this.
    let (trun_start, _) = find_box_range(&media, 0, media.len(), b"trun").expect("trun present");
    let mut broken = media.clone();
    // trun layout: box header(8) + FullBox version/flags(4) + sample_count(4)
    // + data_offset(4) — see `TrackFragmentRunBox::parse_body`.
    let data_offset_off = trun_start + 8 + 4 + 4;
    broken[data_offset_off..data_offset_off + 4].copy_from_slice(&0i32.to_be_bytes());

    let issues = validate_media_segment(&broken);
    assert!(
        has_code(&issues, "media.mdat.overrun"),
        "expected media.mdat.overrun (lower bound), got {:?}",
        errors(&issues)
    );
}

#[test]
fn moof_without_mdat_bites() {
    let data = fixture();
    let samples = video_samples(&data);
    let media = clean_media(1, 0, &samples);

    // positive: moof+mdat present → no pairing error.
    let clean = validate_media_segment(&media);
    assert!(!has_code(&clean, "media.mdat.missing"));
    assert!(!has_code(&clean, "media.mdat.orphan"));

    // negative: drop the trailing mdat entirely (styp + moof only).
    let boxes = top_boxes(&media);
    let (mdat_off, _, _) = *boxes.iter().find(|(_, _, t)| t == b"mdat").unwrap();
    let broken = media[..mdat_off].to_vec();

    let issues = validate_media_segment(&broken);
    assert!(
        has_code(&issues, "media.mdat.missing"),
        "expected media.mdat.missing, got {:?}",
        errors(&issues)
    );
}

#[test]
fn mdat_orphan_bites() {
    // A bare mdat with no preceding moof.
    let mut buf = Vec::new();
    // styp
    let styp: [u8; 4] = *b"styp";
    buf.extend_from_slice(&24u32.to_be_bytes());
    buf.extend_from_slice(&styp);
    buf.extend_from_slice(b"msdh");
    buf.extend_from_slice(&0u32.to_be_bytes());
    buf.extend_from_slice(b"msix");
    buf.extend_from_slice(b"msdh");
    // mdat with no moof before it
    buf.extend_from_slice(&12u32.to_be_bytes());
    buf.extend_from_slice(b"mdat");
    buf.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]);

    let issues = validate_media_segment(&buf);
    assert!(
        has_code(&issues, "media.mdat.orphan"),
        "expected media.mdat.orphan, got {:?}",
        errors(&issues)
    );
}

#[test]
fn tfdt_continuity_bites() {
    let data = fixture();
    let samples = video_samples(&data);
    let total: u64 = samples.iter().map(|s| s.duration.unwrap_or(0) as u64).sum();
    let init = clean_init();

    // positive: two contiguous segments → no continuity error.
    let seg1 = clean_media(1, 0, &samples);
    let seg2_ok = clean_media(2, total, &samples);
    let ok = validate_cmaf_track(&init, &[&seg1, &seg2_ok]);
    assert!(
        !has_code(&ok, "track.tfdt.discontinuity"),
        "contiguous segments must not flag discontinuity: {:?}",
        errors(&ok)
    );

    // negative: segment 2 tfdt < segment 1 (rewinds) → continuity error.
    let seg2_bad = clean_media(2, 0, &samples); // same base time as seg1
    let bad = validate_cmaf_track(&init, &[&seg1, &seg2_bad]);
    assert!(
        has_code(&bad, "track.tfdt.discontinuity"),
        "expected track.tfdt.discontinuity, got {:?}",
        errors(&bad)
    );
}

#[test]
fn mfhd_sequence_bites() {
    let data = fixture();
    let samples = video_samples(&data);
    let total: u64 = samples.iter().map(|s| s.duration.unwrap_or(0) as u64).sum();
    let init = clean_init();

    let seg1 = clean_media(5, 0, &samples);
    // Second segment with a NON-increasing sequence number (same as first).
    let seg2 = clean_media(5, total, &samples);
    let issues = validate_cmaf_track(&init, &[&seg1, &seg2]);
    assert!(
        issues
            .iter()
            .any(|i| i.code == "track.mfhd.sequence" && i.severity == Severity::Warning),
        "expected track.mfhd.sequence warning, got {issues:?}"
    );
}

#[test]
fn zero_duration_sample_bites() {
    let data = fixture();
    let mut samples = video_samples(&data);
    // positive path already covered by clean_media_has_no_errors.
    // negative: force a zero-duration sample.
    samples[0].duration = Some(0);
    let media = clean_media(1, 0, &samples);
    let issues = validate_media_segment(&media);
    assert!(
        has_code(&issues, "media.sample.zero-duration"),
        "expected media.sample.zero-duration, got {:?}",
        errors(&issues)
    );
}

// ---------------------------------------------------------------------------
// Init-segment error checks bite
// ---------------------------------------------------------------------------

#[test]
fn init_missing_moov_bites() {
    let init = clean_init();
    // positive
    assert!(!has_code(
        &validate_init_segment(&init),
        "init.moov.missing"
    ));
    // negative: strip moov.
    let broken = strip_box(&init, b"moov");
    let issues = validate_init_segment(&broken);
    assert!(
        has_code(&issues, "init.moov.missing"),
        "expected init.moov.missing, got {:?}",
        errors(&issues)
    );
}

#[test]
fn init_missing_mvhd_bites() {
    let init = clean_init();
    assert!(!has_code(
        &validate_init_segment(&init),
        "init.mvhd.missing"
    ));
    let broken = strip_box(&init, b"mvhd");
    let issues = validate_init_segment(&broken);
    assert!(
        has_code(&issues, "init.mvhd.missing"),
        "expected init.mvhd.missing, got {:?}",
        errors(&issues)
    );
}

#[test]
fn init_incomplete_trak_bites() {
    let init = clean_init();
    assert!(!has_code(
        &validate_init_segment(&init),
        "init.trak.incomplete"
    ));
    // strip the stsd (deep inside trak>mdia>minf>stbl).
    let broken = strip_box(&init, b"stsd");
    let issues = validate_init_segment(&broken);
    assert!(
        has_code(&issues, "init.trak.incomplete"),
        "expected init.trak.incomplete, got {:?}",
        errors(&issues)
    );
}

#[test]
fn init_missing_mvex_warns() {
    let init = clean_init();
    // clean fragmented init HAS mvex → no warning.
    assert!(!has_code(
        &validate_init_segment(&init),
        "init.mvex.missing"
    ));
    // strip mvex → warning (not error).
    let broken = strip_box(&init, b"mvex");
    let issues = validate_init_segment(&broken);
    assert!(
        issues
            .iter()
            .any(|i| i.code == "init.mvex.missing" && i.severity == Severity::Warning),
        "expected init.mvex.missing warning, got {issues:?}"
    );
    assert!(
        errors(&issues).is_empty(),
        "mvex absence must not be an error"
    );
}

// ---------------------------------------------------------------------------
// 3. Garbage / malformed input → issues, no panic
// ---------------------------------------------------------------------------

#[test]
fn garbage_buffer_no_panic() {
    let garbage = [0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
    let i1 = validate_init_segment(&garbage);
    let i2 = validate_media_segment(&garbage);
    // No ftyp/moov → init errors.
    assert!(has_code(&i1, "init.ftyp.missing"));
    assert!(has_code(&i1, "init.moov.missing"));
    // No moof → media error.
    assert!(has_code(&i2, "media.moof.missing"));
}

#[test]
fn empty_buffer_no_panic() {
    assert!(!validate_init_segment(&[]).is_empty());
    assert!(!validate_media_segment(&[]).is_empty());
    // cross-segment on empties must not panic.
    let _ = validate_cmaf_track(&[], &[&[], &[]]);
}

#[test]
fn wrong_brand_moov_only_errors_no_panic() {
    // A buffer whose first box is not ftyp (a bare moov-less mess).
    let mut buf = Vec::new();
    buf.extend_from_slice(&16u32.to_be_bytes());
    buf.extend_from_slice(b"free"); // filler first, then a truncated moov
    buf.extend_from_slice(&[0u8; 8]);
    buf.extend_from_slice(&16u32.to_be_bytes());
    buf.extend_from_slice(b"XXXX");
    buf.extend_from_slice(&[0u8; 8]);
    let issues = validate_init_segment(&buf);
    assert!(has_code(&issues, "init.ftyp.missing"));
    assert!(has_code(&issues, "init.moov.missing"));
}

// ---------------------------------------------------------------------------
// Audit r05-W30 — per-trun ranges, multi-moof, track identity, issue dedup
// ---------------------------------------------------------------------------

/// (a) The overrun check must consider **every** `trun`'s own range, not just the
/// smallest offset: a `trun` whose own `data_offset` leaves the mdat used to pass
/// whenever the aggregate fitted.
#[test]
fn mdat_overrun_checks_every_trun_range() {
    let data = fixture();
    let samples = video_samples(&data);
    let media = clean_media(1, 0, &samples);

    // Baseline is clean.
    assert!(!has_code(
        &validate_media_segment(&media),
        "media.mdat.overrun"
    ));

    // Corrupt *only* the trun's `data_offset`: point it well past the mdat.
    // The sample sizes are unchanged, so the only way to see this is to resolve
    // each trun's own range.
    let (trun_start, _) = find_box_range(&media, 0, media.len(), b"trun").expect("trun present");
    let mut broken = media.clone();
    // trun layout: box header(8) + version/flags(4) + sample_count(4) +
    // data_offset(4).
    let data_offset_off = trun_start + 8 + 4 + 4;
    broken[data_offset_off..data_offset_off + 4].copy_from_slice(&0x00FF_FFFFu32.to_be_bytes());

    let issues = validate_media_segment(&broken);
    assert!(
        has_code(&issues, "media.mdat.overrun"),
        "an out-of-range trun data_offset must be caught, got {:?}",
        errors(&issues)
    );

    // And the reverse: the original media (same sizes, in-range offset) is
    // clean — so the check is on the range, not merely on the presence of a
    // trun.
    assert!(!has_code(
        &validate_media_segment(&media),
        "media.mdat.overrun"
    ));
}

/// (b) A segment holding **two** `moof`s must not report a false
/// `track.tfdt.discontinuity`: the cross-segment check must use the segment's
/// last fragment end, not its first tfdt.
#[test]
fn multi_moof_segment_has_no_false_tfdt_discontinuity() {
    let data = fixture();
    let all = video_samples(&data);
    let half = all.len() / 2;
    let (a, b) = all.split_at(half);

    let seg1 = clean_media(1, 0, a);
    let dur_a: u64 = a.iter().map(|s| u64::from(s.duration.unwrap_or(0))).sum();
    let seg2 = clean_media(2, dur_a, b);

    // Concatenating two media segments gives one byte string with two moofs —
    // exactly a multi-fragment segment. The track's decode end after the second
    // fragment is dur_a + dur_b.
    let mut multi = seg1.clone();
    multi.extend_from_slice(&seg2);

    let dur_b: u64 = b.iter().map(|s| u64::from(s.duration.unwrap_or(0))).sum();
    let seg3 = clean_media(3, dur_a + dur_b, a);

    let issues = validate_cmaf_track(&clean_init(), &[&multi, &seg3]);
    assert!(
        !has_code(&issues, "track.tfdt.discontinuity"),
        "a multi-moof segment must not report a false tfdt discontinuity: {:?}",
        errors(&issues)
    );

    // And a genuinely discontinuous next segment still bites.
    let seg_bad = clean_media(3, dur_a + dur_b + 999_999, a);
    let issues = validate_cmaf_track(&clean_init(), &[&multi, &seg_bad]);
    assert!(
        has_code(&issues, "track.tfdt.discontinuity"),
        "a real discontinuity must still be reported"
    );
}

/// (c) A media segment naming a track the init segment does not declare is an
/// error.
#[test]
fn unknown_track_id_bites() {
    let data = fixture();
    let samples = video_samples(&data);
    // Track id 7 is not in `clean_init()` (which carries the fixture's own id).
    let media = build_media_segment(1, &[FragmentTrackData::new(TrackId::new(7), 0, &samples)])
        .expect("build media with an undeclared track id");

    let issues = validate_cmaf_track(&clean_init(), &[&media]);
    assert!(
        has_code(&issues, "track.tfhd.unknown-track"),
        "an undeclared tfhd.track_id must be reported: {:?}",
        errors(&issues)
    );
}

/// (d) A fragment whose samples all have zero duration reports **one**
/// `media.sample.zero-duration` issue, not one per sample.
#[test]
fn zero_duration_reported_once_per_traf() {
    let data = fixture();
    let mut samples = video_samples(&data);
    for s in &mut samples {
        s.duration = Some(0);
    }
    let media = clean_media(1, 0, &samples);

    let issues = validate_media_segment(&media);
    let count = issues
        .iter()
        .filter(|i| i.code == "media.sample.zero-duration")
        .count();
    assert_eq!(
        count,
        1,
        "one deduplicated issue per traf, got {count} (issues: {:?})",
        errors(&issues)
    );
}