mp4_muxer 0.1.0

Zero-dependency MP4 muxer for AV1 video streams
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
//! # mp4_muxer
//!
//! A tiny, dependency-free MP4 muxer for AV1 video streams.
//!
//! Given a sequence of AV1 OBU packets — one per frame — this crate produces
//! an ISO Base Media File Format (ISOBMFF / MP4) container playable by
//! browsers, VLC, QuickTime, and every other mainstream player.
//!
//! ## What it does
//!
//! * Writes a valid, seekable `.mp4` in a single pass.
//! * Uses AV1 (`av01`) as the video codec.
//! * Handles files larger than 4 GiB by transparently switching to 64-bit
//!   chunk offsets (`co64` instead of `stco`).
//! * Zero runtime dependencies.
//!
//! ## What it doesn't do
//!
//! * No audio track.
//! * No B-frames / re-ordering: the muxer assumes every frame is displayed in
//!   the order it was written (`pts == dts`).
//! * No fragmented MP4 (fMP4 / DASH / HLS) output.
//! * Doesn't inspect the AV1 bitstream — you must correctly tag keyframes.
//!
//! ## Output layout
//!
//! ```text
//! ftyp  — file type box (isom / av01)
//! mdat  — raw AV1 OBU packet data
//! moov  — movie metadata
//!   mvhd — movie header
//!   trak — video track
//!     tkhd — track header (width, height)
//!     mdia
//!       mdhd — media header
//!       hdlr — handler type = "vide"
//!       minf
//!         vmhd — video media header
//!         dinf → dref — self-contained data reference
//!         stbl — sample table
//!           stsd → av01 → av1C
//!           stts — sample durations
//!           stss — sync (keyframe) sample indices
//!           stsc — sample-to-chunk mapping
//!           stsz — sample sizes
//!           stco / co64 — chunk offsets (absolute file positions)
//! ```
//!
//! Because `mdat` comes before `moov`, chunk offsets are known at
//! finalisation time — no second-pass rewrite of the file is needed.
//!
//! ## Usage
//!
//! ```no_run
//! use mp4_muxer::Mp4Writer;
//! use std::fs::File;
//!
//! # fn get_obu(_i: usize) -> Vec<u8> { vec![] }
//! # fn n_frames() -> usize { 0 }
//! let file = File::create("output.mp4")?;
//! let mut muxer = Mp4Writer::new(file, 1920, 1080, 30, 1)?;
//!
//! for i in 0..n_frames() {
//!     let obu = get_obu(i);
//!     let is_keyframe = i == 0;
//!     muxer.write_frame(&obu, is_keyframe)?;
//! }
//!
//! muxer.finish()?;
//! # Ok::<(), mp4_muxer::Error>(())
//! ```

use std::io::{self, Seek, SeekFrom, Write};

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors returned by [`Mp4Writer`].
#[derive(Debug)]
pub enum Error {
    /// The underlying writer returned an I/O error.
    Io(io::Error),
    /// [`Mp4Writer::finish`] was called with no frames written.
    NoFrames,
    /// `fps_num` or `fps_den` was zero.
    InvalidFps,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Io(e)      => write!(f, "I/O error: {e}"),
            Error::NoFrames   => write!(f, "cannot finish: no frames were written"),
            Error::InvalidFps => write!(f, "fps_num and fps_den must both be non-zero"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            _ => None,
        }
    }
}

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

/// Convenient result alias for the muxer's public API.
pub type Result<T> = std::result::Result<T, Error>;

// ---------------------------------------------------------------------------
// Frame metadata
// ---------------------------------------------------------------------------

/// Per-frame bookkeeping accumulated during `write_frame`.
struct Frame {
    /// Absolute byte offset of this frame's data in the file.
    offset: u64,
    /// Size of the OBU data in bytes.
    size: u32,
    /// True for sync samples (keyframes / IDR).
    is_keyframe: bool,
}

// ---------------------------------------------------------------------------
// Low-level write helpers
// ---------------------------------------------------------------------------

#[inline]
fn write_u16be(w: &mut impl Write, v: u16) -> io::Result<()> {
    w.write_all(&v.to_be_bytes())
}

#[inline]
fn write_u32be(w: &mut impl Write, v: u32) -> io::Result<()> {
    w.write_all(&v.to_be_bytes())
}

#[inline]
fn write_u64be(w: &mut impl Write, v: u64) -> io::Result<()> {
    w.write_all(&v.to_be_bytes())
}

/// Wrap a payload in an ISOBMFF box: `[size u32][fourcc 4b][payload]`.
///
/// All boxes shorter than 4 GiB are written with a 32-bit size field — that
/// covers every box this crate emits (only `mdat`, patched separately, may
/// grow beyond that limit).
fn wrap_box(fourcc: &[u8; 4], payload: &[u8]) -> Vec<u8> {
    let size = 8 + payload.len();
    debug_assert!(size <= u32::MAX as usize, "box '{}' too large for 32-bit size field", std::str::from_utf8(fourcc).unwrap_or("?"));

    let mut out = Vec::with_capacity(size);
    out.extend_from_slice(&(size as u32).to_be_bytes());
    out.extend_from_slice(fourcc);
    out.extend_from_slice(payload);
    out
}

/// Concatenate several boxes into a single payload.
fn concat(boxes: &[&[u8]]) -> Vec<u8> {
    let total: usize = boxes.iter().map(|b| b.len()).sum();
    let mut out = Vec::with_capacity(total);
    for b in boxes { out.extend_from_slice(b); }
    out
}

// ---------------------------------------------------------------------------
// Box builders
// ---------------------------------------------------------------------------

/// `ftyp` — major brand `isom`, compatible brand `av01`.
fn build_ftyp() -> Vec<u8> {
    let mut payload = Vec::with_capacity(16);
    payload.extend_from_slice(b"isom");            // major brand
    payload.extend_from_slice(&0x0200u32.to_be_bytes()); // minor version
    payload.extend_from_slice(b"isomav01");        // compatible brands
    wrap_box(b"ftyp", &payload)
}

/// `mvhd` (version 1, 64-bit timestamps).
fn build_mvhd(duration_ts: u64, timescale: u32) -> Vec<u8> {
    let mut p = Vec::with_capacity(108);
    p.extend_from_slice(&[1, 0, 0, 0]);            // version=1, flags=0
    write_u64be(&mut p, 0).unwrap();               // creation_time
    write_u64be(&mut p, 0).unwrap();               // modification_time
    write_u32be(&mut p, timescale).unwrap();
    write_u64be(&mut p, duration_ts).unwrap();
    write_u32be(&mut p, 0x00010000).unwrap();      // rate = 1.0 (16.16)
    write_u16be(&mut p, 0x0100).unwrap();          // volume = 1.0 (8.8)
    p.extend_from_slice(&[0u8; 10]);               // reserved
    write_unity_matrix(&mut p);
    p.extend_from_slice(&[0u8; 24]);               // pre-defined
    write_u32be(&mut p, 2).unwrap();               // next_track_id
    wrap_box(b"mvhd", &p)
}

/// `tkhd` (version 1).
fn build_tkhd(duration_ts: u64, width: u32, height: u32) -> Vec<u8> {
    let mut p = Vec::with_capacity(92);
    p.extend_from_slice(&[1, 0, 0, 3]);            // v=1, flags=3 (enabled+in_movie)
    write_u64be(&mut p, 0).unwrap();               // creation_time
    write_u64be(&mut p, 0).unwrap();               // modification_time
    write_u32be(&mut p, 1).unwrap();               // track_id
    write_u32be(&mut p, 0).unwrap();               // reserved
    write_u64be(&mut p, duration_ts).unwrap();
    p.extend_from_slice(&[0u8; 8]);                // reserved
    write_u16be(&mut p, 0).unwrap();               // layer
    write_u16be(&mut p, 0).unwrap();               // alternate_group
    write_u16be(&mut p, 0).unwrap();               // volume (video → 0)
    write_u16be(&mut p, 0).unwrap();               // reserved
    write_unity_matrix(&mut p);
    write_u32be(&mut p, width << 16).unwrap();     // width  (16.16 fixed)
    write_u32be(&mut p, height << 16).unwrap();    // height (16.16 fixed)
    wrap_box(b"tkhd", &p)
}

/// Standard 3×3 unity matrix used by both `mvhd` and `tkhd`.
fn write_unity_matrix(w: &mut Vec<u8>) {
    const M: [u32; 9] = [
        0x00010000, 0, 0,
        0, 0x00010000, 0,
        0, 0, 0x40000000,
    ];
    for &v in &M { write_u32be(w, v).unwrap(); }
}

/// `mdhd` (version 1).
fn build_mdhd(duration_ts: u64, timescale: u32) -> Vec<u8> {
    let mut p = Vec::with_capacity(36);
    p.extend_from_slice(&[1, 0, 0, 0]);            // version=1, flags=0
    write_u64be(&mut p, 0).unwrap();               // creation_time
    write_u64be(&mut p, 0).unwrap();               // modification_time
    write_u32be(&mut p, timescale).unwrap();
    write_u64be(&mut p, duration_ts).unwrap();
    // language 'und', packed as 5-bit chars per ISO-639-2/T:
    // (u-0x60)<<10 | (n-0x60)<<5 | (d-0x60) = 21<<10 | 14<<5 | 4 = 0x55C4.
    write_u16be(&mut p, 0x55C4).unwrap();
    write_u16be(&mut p, 0).unwrap();               // pre-defined
    wrap_box(b"mdhd", &p)
}

/// `hdlr` — video handler.
fn build_hdlr() -> Vec<u8> {
    let name = b"VideoHandler\0";
    let mut p = Vec::with_capacity(24 + name.len());
    p.extend_from_slice(&[0, 0, 0, 0]);            // version=0, flags=0
    write_u32be(&mut p, 0).unwrap();               // pre-defined
    p.extend_from_slice(b"vide");                  // handler_type
    p.extend_from_slice(&[0u8; 12]);               // reserved
    p.extend_from_slice(name);
    wrap_box(b"hdlr", &p)
}

/// `vmhd` — video media header. Flags MUST be 1 per spec.
fn build_vmhd() -> Vec<u8> {
    let mut p = Vec::with_capacity(12);
    p.extend_from_slice(&[0, 0, 0, 1]);            // version=0, flags=1
    p.extend_from_slice(&[0u8; 8]);                // graphicsMode(0) + opcolor(0,0,0)
    wrap_box(b"vmhd", &p)
}

/// `dref` with a single self-contained `url ` entry.
fn build_dref() -> Vec<u8> {
    let url_entry = {
        let mut e = Vec::with_capacity(12);
        write_u32be(&mut e, 12).unwrap();          // box size
        e.extend_from_slice(b"url ");              // fourcc
        e.extend_from_slice(&[0, 0, 0, 1]);        // version=0, flags=1 (self-contained)
        e
    };

    let mut p = Vec::with_capacity(8 + url_entry.len());
    p.extend_from_slice(&[0, 0, 0, 0]);            // version=0, flags=0
    write_u32be(&mut p, 1).unwrap();               // entry_count
    p.extend_from_slice(&url_entry);
    wrap_box(b"dref", &p)
}

fn build_dinf() -> Vec<u8> {
    wrap_box(b"dinf", &build_dref())
}

/// AV1 `av1C` codec configuration record.
///
/// The 4-byte body is a fixed 8-bit 4:2:0 profile suitable for the AV1 streams
/// produced by rav1e's default configuration.
fn build_av1c() -> Vec<u8> {
    // marker=1 | version=1 | seq_profile=0 | seq_level_idx_0=4 |
    // seq_tier_0=0 | high_bitdepth=0 | twelve_bit=0 | mono=0 |
    // chroma_subsampling_x=1 | chroma_subsampling_y=1 | chroma_sample_pos=0.
    let cfg: [u8; 4] = [0x81, 0x04, 0x0C, 0x00];
    wrap_box(b"av1C", &cfg)
}

/// `av01` sample entry (inside `stsd`).
fn build_av01_entry(width: u32, height: u32) -> Vec<u8> {
    let av1c = build_av1c();

    let mut p = Vec::with_capacity(78 + av1c.len());
    p.extend_from_slice(&[0u8; 6]);                // reserved
    write_u16be(&mut p, 1).unwrap();               // data_reference_index
    p.extend_from_slice(&[0u8; 16]);               // pre-defined + reserved
    write_u16be(&mut p, width as u16).unwrap();
    write_u16be(&mut p, height as u16).unwrap();
    write_u32be(&mut p, 0x00480000).unwrap();      // horizresolution = 72 dpi
    write_u32be(&mut p, 0x00480000).unwrap();      // vertresolution  = 72 dpi
    write_u32be(&mut p, 0).unwrap();               // reserved
    write_u16be(&mut p, 1).unwrap();               // frame_count = 1
    p.extend_from_slice(&[0u8; 32]);               // compressorname (unused)
    write_u16be(&mut p, 0x0018).unwrap();          // depth = 24
    write_u16be(&mut p, 0xFFFF).unwrap();          // pre-defined = -1
    p.extend_from_slice(&av1c);
    wrap_box(b"av01", &p)
}

fn build_stsd(width: u32, height: u32) -> Vec<u8> {
    let av01 = build_av01_entry(width, height);
    let mut p = Vec::with_capacity(8 + av01.len());
    p.extend_from_slice(&[0, 0, 0, 0]);            // version=0, flags=0
    write_u32be(&mut p, 1).unwrap();               // entry_count
    p.extend_from_slice(&av01);
    wrap_box(b"stsd", &p)
}

/// `stts` — all samples share one duration.
fn build_stts(sample_count: u32, sample_duration: u32) -> Vec<u8> {
    let mut p = Vec::with_capacity(16);
    p.extend_from_slice(&[0, 0, 0, 0]);            // version=0, flags=0
    write_u32be(&mut p, 1).unwrap();               // entry_count
    write_u32be(&mut p, sample_count).unwrap();
    write_u32be(&mut p, sample_duration).unwrap();
    wrap_box(b"stts", &p)
}

/// `stss` — sample indices (1-based) that are sync samples.
fn build_stss(frames: &[Frame]) -> Vec<u8> {
    let keys: Vec<u32> = frames.iter().enumerate()
        .filter(|(_, f)| f.is_keyframe)
        .map(|(i, _)| (i + 1) as u32)
        .collect();

    let mut p = Vec::with_capacity(8 + 4 * keys.len());
    p.extend_from_slice(&[0, 0, 0, 0]);
    write_u32be(&mut p, keys.len() as u32).unwrap();
    for k in keys { write_u32be(&mut p, k).unwrap(); }
    wrap_box(b"stss", &p)
}

/// `stsc` — every chunk holds exactly one sample.
fn build_stsc() -> Vec<u8> {
    let mut p = Vec::with_capacity(20);
    p.extend_from_slice(&[0, 0, 0, 0]);
    write_u32be(&mut p, 1).unwrap();               // entry_count
    write_u32be(&mut p, 1).unwrap();               // first_chunk
    write_u32be(&mut p, 1).unwrap();               // samples_per_chunk
    write_u32be(&mut p, 1).unwrap();               // sample_description_index
    wrap_box(b"stsc", &p)
}

/// `stsz` — per-sample sizes.
fn build_stsz(frames: &[Frame]) -> Vec<u8> {
    let mut p = Vec::with_capacity(12 + 4 * frames.len());
    p.extend_from_slice(&[0, 0, 0, 0]);
    write_u32be(&mut p, 0).unwrap();               // sample_size = 0 → variable
    write_u32be(&mut p, frames.len() as u32).unwrap();
    for f in frames { write_u32be(&mut p, f.size).unwrap(); }
    wrap_box(b"stsz", &p)
}

/// `stco` (32-bit) or `co64` (64-bit) — chunk offsets.
///
/// One chunk per sample, so this is one offset per frame. `co64` is emitted
/// automatically when any offset does not fit in a `u32`.
fn build_stco_or_co64(frames: &[Frame]) -> Vec<u8> {
    let needs_co64 = frames.iter().any(|f| f.offset > u32::MAX as u64);

    if needs_co64 {
        let mut p = Vec::with_capacity(8 + 8 * frames.len());
        p.extend_from_slice(&[0, 0, 0, 0]);
        write_u32be(&mut p, frames.len() as u32).unwrap();
        for f in frames { write_u64be(&mut p, f.offset).unwrap(); }
        wrap_box(b"co64", &p)
    } else {
        let mut p = Vec::with_capacity(8 + 4 * frames.len());
        p.extend_from_slice(&[0, 0, 0, 0]);
        write_u32be(&mut p, frames.len() as u32).unwrap();
        for f in frames { write_u32be(&mut p, f.offset as u32).unwrap(); }
        wrap_box(b"stco", &p)
    }
}

fn build_stbl(frames: &[Frame], width: u32, height: u32,
              sample_count: u32, sample_duration: u32) -> Vec<u8> {
    let stsd = build_stsd(width, height);
    let stts = build_stts(sample_count, sample_duration);
    let stss = build_stss(frames);
    let stsc = build_stsc();
    let stsz = build_stsz(frames);
    let stco = build_stco_or_co64(frames);
    let payload = concat(&[&stsd, &stts, &stss, &stsc, &stsz, &stco]);
    wrap_box(b"stbl", &payload)
}

fn build_minf(frames: &[Frame], width: u32, height: u32,
              sample_count: u32, sample_duration: u32) -> Vec<u8> {
    let vmhd = build_vmhd();
    let dinf = build_dinf();
    let stbl = build_stbl(frames, width, height, sample_count, sample_duration);
    let payload = concat(&[&vmhd, &dinf, &stbl]);
    wrap_box(b"minf", &payload)
}

fn build_mdia(frames: &[Frame], width: u32, height: u32,
              sample_count: u32, sample_duration: u32,
              duration_ts: u64, timescale: u32) -> Vec<u8> {
    let mdhd = build_mdhd(duration_ts, timescale);
    let hdlr = build_hdlr();
    let minf = build_minf(frames, width, height, sample_count, sample_duration);
    let payload = concat(&[&mdhd, &hdlr, &minf]);
    wrap_box(b"mdia", &payload)
}

#[allow(clippy::too_many_arguments)]
fn build_trak(frames: &[Frame], width: u32, height: u32,
              sample_count: u32, sample_duration: u32,
              duration_ts: u64, timescale: u32,
              movie_timescale: u32) -> Vec<u8> {
    // tkhd duration is in the movie timescale, not the media timescale.
    let tkhd_duration = duration_ts * movie_timescale as u64 / timescale as u64;
    let tkhd = build_tkhd(tkhd_duration, width, height);
    let mdia = build_mdia(frames, width, height, sample_count, sample_duration,
                          duration_ts, timescale);
    let payload = concat(&[&tkhd, &mdia]);
    wrap_box(b"trak", &payload)
}

fn build_moov(frames: &[Frame], width: u32, height: u32,
              sample_count: u32, sample_duration: u32,
              duration_ts: u64, timescale: u32) -> Vec<u8> {
    /// Movie-level timescale: 1000 ticks per second (millisecond resolution).
    const MOVIE_TIMESCALE: u32 = 1000;

    let movie_duration = duration_ts * MOVIE_TIMESCALE as u64 / timescale as u64;
    let mvhd = build_mvhd(movie_duration, MOVIE_TIMESCALE);
    let trak = build_trak(frames, width, height, sample_count, sample_duration,
                          duration_ts, timescale, MOVIE_TIMESCALE);
    let payload = concat(&[&mvhd, &trak]);
    wrap_box(b"moov", &payload)
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Incremental MP4 muxer for AV1 OBU streams.
///
/// Frames are written to the underlying `writer` as soon as [`write_frame`]
/// is called. When you're done, call [`finish`] to patch the `mdat` size
/// header and append the `moov` metadata box.
///
/// Output layout:
/// ```text
/// [ftyp][mdat …frame data… ][moov]
/// ```
/// Because `mdat` precedes `moov`, all chunk offsets stored inside `moov` are
/// absolute file positions known at finalisation time. No second pass over
/// the frames is required.
///
/// [`write_frame`]: Mp4Writer::write_frame
/// [`finish`]: Mp4Writer::finish
pub struct Mp4Writer<W: Write + Seek> {
    writer: W,
    width: u32,
    height: u32,
    fps_num: u32,
    fps_den: u32,
    frames: Vec<Frame>,
    /// File position of the first byte of `mdat`'s data area (i.e. just past
    /// the `[size][mdat]` header — the size field will be patched in `finish`).
    mdat_data_start: u64,
}

impl<W: Write + Seek> Mp4Writer<W> {
    /// Create a new muxer.
    ///
    /// Writes the `ftyp` box and a placeholder `mdat` header immediately.
    ///
    /// # Arguments
    /// * `writer`  — destination (file, `Cursor<Vec<u8>>`, etc.)
    /// * `width`   — frame width in pixels
    /// * `height`  — frame height in pixels
    /// * `fps_num` — FPS numerator (e.g. `30` for 30 fps, `60000` for 59.94)
    /// * `fps_den` — FPS denominator (e.g. `1` for 30 fps, `1001` for 59.94)
    ///
    /// # Errors
    /// * [`Error::InvalidFps`] if either FPS component is zero.
    /// * [`Error::Io`] if writing the initial headers fails.
    pub fn new(mut writer: W, width: u32, height: u32, fps_num: u32, fps_den: u32) -> Result<Self> {
        if fps_num == 0 || fps_den == 0 {
            return Err(Error::InvalidFps);
        }

        // ftyp goes first.
        let ftyp = build_ftyp();
        writer.write_all(&ftyp)?;

        // Placeholder mdat header: [size=0][fourcc "mdat"]. Size is patched
        // during `finish` once we know the total payload length.
        writer.write_all(&[0, 0, 0, 0])?;
        writer.write_all(b"mdat")?;

        let mdat_data_start = ftyp.len() as u64 + 8;

        Ok(Mp4Writer {
            writer, width, height, fps_num, fps_den,
            frames: Vec::new(),
            mdat_data_start,
        })
    }

    /// Append one AV1 OBU packet (one video frame).
    ///
    /// * `obu_data`    — raw AV1 OBU bytes for this frame
    /// * `is_keyframe` — mark this as a sync sample (IDR / key frame)
    ///
    /// The muxer does not inspect the bitstream; you are responsible for
    /// tagging keyframes correctly, otherwise seek performance will suffer.
    pub fn write_frame(&mut self, obu_data: &[u8], is_keyframe: bool) -> Result<()> {
        let offset = self.writer.stream_position()?;
        let size = obu_data.len() as u32;
        self.writer.write_all(obu_data)?;
        self.frames.push(Frame { offset, size, is_keyframe });
        Ok(())
    }

    /// Number of frames written so far.
    pub fn frames_written(&self) -> usize { self.frames.len() }

    /// Finalise the file: patch the `mdat` size header and append `moov`.
    ///
    /// Returns the underlying writer so callers can flush, reuse, or inspect
    /// the produced bytes (e.g. `Cursor::into_inner()` on an in-memory buffer).
    ///
    /// # Errors
    /// * [`Error::NoFrames`] if no frames were written.
    /// * [`Error::Io`] on any write / seek failure.
    pub fn finish(mut self) -> Result<W> {
        if self.frames.is_empty() {
            return Err(Error::NoFrames);
        }

        // ── Patch mdat size ────────────────────────────────────────────────
        let end_pos = self.writer.stream_position()?;
        let mdat_header_pos = self.mdat_data_start - 8;
        let mdat_size = end_pos - mdat_header_pos;

        // The mdat size field is a u32. Larger payloads would need the
        // "extended size" trick (size=1 + 64-bit largesize); we don't emit
        // that yet, so cap at 4 GiB of frame data.
        if mdat_size > u32::MAX as u64 {
            return Err(Error::Io(io::Error::new(
                io::ErrorKind::InvalidData,
                "mdat exceeds 4 GiB — extended size not yet supported",
            )));
        }

        self.writer.seek(SeekFrom::Start(mdat_header_pos))?;
        write_u32be(&mut self.writer, mdat_size as u32)?;
        self.writer.seek(SeekFrom::Start(end_pos))?;

        // ── Timing ─────────────────────────────────────────────────────────
        // Use fps_num as the media timescale so sample duration equals fps_den
        // exactly (no accumulated drift for rationals like 60000/1001).
        let timescale = self.fps_num;
        let sample_duration = self.fps_den;
        let sample_count = self.frames.len() as u32;
        let duration_ts = sample_count as u64 * sample_duration as u64;

        // ── Append moov ────────────────────────────────────────────────────
        let moov = build_moov(
            &self.frames, self.width, self.height,
            sample_count, sample_duration,
            duration_ts, timescale,
        );
        self.writer.write_all(&moov)?;
        Ok(self.writer)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    /// Minimal synthetic AV1 OBU bytes. Not a real bitstream — enough to
    /// exercise the muxer.
    fn fake_obu(is_key: bool) -> Vec<u8> {
        if is_key { vec![0x12, 0x00, 0xAA, 0xBB, 0xCC] }
        else      { vec![0x32, 0x00, 0xDD, 0xEE] }
    }

    /// Mux `frames` fake frames into an in-memory buffer and return the bytes.
    fn mux_to_vec(width: u32, height: u32, frames: usize) -> Vec<u8> {
        let mut muxer = Mp4Writer::new(Cursor::new(Vec::new()), width, height, 30, 1).unwrap();
        for i in 0..frames {
            muxer.write_frame(&fake_obu(i == 0), i == 0).unwrap();
        }
        muxer.finish().unwrap().into_inner()
    }

    #[test]
    fn happy_path() {
        let mut muxer = Mp4Writer::new(Cursor::new(Vec::new()), 320, 240, 30, 1).unwrap();
        for i in 0..4 {
            muxer.write_frame(&fake_obu(i == 0), i == 0).unwrap();
        }
        assert_eq!(muxer.frames_written(), 4);
        muxer.finish().unwrap();
    }

    #[test]
    fn produces_ftyp_mdat_moov_in_order() {
        let bytes = mux_to_vec(640, 360, 10);
        // First box: ftyp
        assert_eq!(&bytes[4..8], b"ftyp");
        let ftyp_size = u32::from_be_bytes(bytes[0..4].try_into().unwrap()) as usize;
        // Second box: mdat
        assert_eq!(&bytes[ftyp_size + 4..ftyp_size + 8], b"mdat");
        let mdat_size = u32::from_be_bytes(bytes[ftyp_size..ftyp_size + 4].try_into().unwrap()) as usize;
        // Third box: moov
        let moov_start = ftyp_size + mdat_size;
        assert_eq!(&bytes[moov_start + 4..moov_start + 8], b"moov");
    }

    #[test]
    fn empty_finish_returns_error() {
        let muxer = Mp4Writer::new(Cursor::new(Vec::new()), 100, 100, 30, 1).unwrap();
        assert!(matches!(muxer.finish(), Err(Error::NoFrames)));
    }

    #[test]
    fn zero_fps_rejected() {
        let r = Mp4Writer::new(Cursor::new(Vec::new()), 100, 100, 0, 1);
        assert!(matches!(r, Err(Error::InvalidFps)));
        let r = Mp4Writer::new(Cursor::new(Vec::new()), 100, 100, 30, 0);
        assert!(matches!(r, Err(Error::InvalidFps)));
    }

    #[test]
    fn ftyp_declares_isom_and_av01() {
        let ftyp = build_ftyp();
        assert_eq!(&ftyp[4..8], b"ftyp");
        assert_eq!(&ftyp[8..12], b"isom");
        // compatible brands contain av01
        assert!(ftyp.windows(4).any(|w| w == b"av01"));
    }

    #[test]
    fn every_box_reports_its_own_length() {
        for b in [
            build_ftyp(),
            build_vmhd(),
            build_dinf(),
            build_hdlr(),
            build_av1c(),
            build_stsc(),
            build_mvhd(90_000, 1000),
            build_tkhd(90_000, 320, 240),
            build_mdhd(90_000, 30),
        ] {
            let reported = u32::from_be_bytes(b[0..4].try_into().unwrap()) as usize;
            assert_eq!(reported, b.len(),
                "box size mismatch for '{}'",
                std::str::from_utf8(&b[4..8]).unwrap_or("?"));
        }
    }

    #[test]
    fn stts_encodes_one_entry() {
        let stts = build_stts(100, 3000);
        assert_eq!(&stts[4..8], b"stts");
        assert_eq!(&stts[8..12], &[0, 0, 0, 0]);                          // v+flags
        assert_eq!(u32::from_be_bytes(stts[12..16].try_into().unwrap()), 1);    // entries
        assert_eq!(u32::from_be_bytes(stts[16..20].try_into().unwrap()), 100);  // count
        assert_eq!(u32::from_be_bytes(stts[20..24].try_into().unwrap()), 3000); // duration
    }

    #[test]
    fn stss_lists_keyframes_by_1based_index() {
        let frames = vec![
            Frame { offset: 0,  size: 10, is_keyframe: true  },
            Frame { offset: 10, size: 8,  is_keyframe: false },
            Frame { offset: 18, size: 12, is_keyframe: true  },
        ];
        let stss = build_stss(&frames);
        assert_eq!(u32::from_be_bytes(stss[12..16].try_into().unwrap()), 2);
        assert_eq!(u32::from_be_bytes(stss[16..20].try_into().unwrap()), 1);
        assert_eq!(u32::from_be_bytes(stss[20..24].try_into().unwrap()), 3);
    }

    #[test]
    fn stsz_lists_per_sample_sizes() {
        let frames = vec![
            Frame { offset: 0,  size: 42, is_keyframe: true  },
            Frame { offset: 42, size: 17, is_keyframe: false },
        ];
        let stsz = build_stsz(&frames);
        assert_eq!(u32::from_be_bytes(stsz[16..20].try_into().unwrap()), 2);
        assert_eq!(u32::from_be_bytes(stsz[20..24].try_into().unwrap()), 42);
        assert_eq!(u32::from_be_bytes(stsz[24..28].try_into().unwrap()), 17);
    }

    #[test]
    fn stco_used_for_small_files() {
        // Layout: [size 4][fourcc 4][ver+flags 4][entry_count 4][off_1 4][off_2 4]…
        let frames = vec![
            Frame { offset: 1000, size: 50, is_keyframe: true  },
            Frame { offset: 1050, size: 60, is_keyframe: false },
        ];
        let out = build_stco_or_co64(&frames);
        assert_eq!(&out[4..8], b"stco");
        assert_eq!(u32::from_be_bytes(out[12..16].try_into().unwrap()), 2);       // entry_count
        assert_eq!(u32::from_be_bytes(out[16..20].try_into().unwrap()), 1000);
        assert_eq!(u32::from_be_bytes(out[20..24].try_into().unwrap()), 1050);
    }

    #[test]
    fn co64_kicks_in_past_4_gib() {
        // Layout: [size 4][fourcc 4][ver+flags 4][entry_count 4][off_1 8][off_2 8]…
        let frames = vec![
            Frame { offset: 0,                         size: 10, is_keyframe: true },
            Frame { offset: (u32::MAX as u64) + 1_000, size: 10, is_keyframe: false },
        ];
        let out = build_stco_or_co64(&frames);
        assert_eq!(&out[4..8], b"co64");
        assert_eq!(u32::from_be_bytes(out[12..16].try_into().unwrap()), 2);       // entry_count
        assert_eq!(u64::from_be_bytes(out[16..24].try_into().unwrap()), 0);
        assert_eq!(
            u64::from_be_bytes(out[24..32].try_into().unwrap()),
            (u32::MAX as u64) + 1_000,
        );
    }
}