Skip to main content

alpha2_container/mp4/
write.rs

1//! The MP4/MOV muxer. Timescales, edit lists and durations follow `FFmpeg`'s MOV muxer, so
2//! `FFmpeg` reads the output as it reads its own stream copy; output bytes depend only on the
3//! packets.
4
5use std::collections::VecDeque;
6use std::io::{Read, Seek, SeekFrom, Write};
7
8use alpha2_media::{
9    ColorMatrix, ColorPrimaries, ColorRange, Orientation, Rotation, TransferFunction,
10};
11use bytes::{BufMut, Bytes, BytesMut};
12
13use super::index::rescale;
14use crate::{
15    AudioCodec, AudioTrack, ContainerWriter, FourCc, MuxError, Packet, TrackId, TrackInfo,
16    TrackKind, VideoCodec, VideoTrack,
17};
18
19/// Which brand of ISO base media file to write.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum Mp4Flavor {
22    /// ISO MP4 (`isom` brand).
23    Mp4,
24    /// `QuickTime` MOV (`qt  ` brand), which also carries `ProRes`.
25    Mov,
26}
27
28/// The movie timescale `FFmpeg` writes.
29const MOVIE_TIMESCALE: u32 = 1000;
30/// Bytes of buffered media after which chunks are written without waiting for other tracks.
31const MAX_BUFFERED: usize = 64 << 20;
32/// Block size when the media data moves to make room for the index.
33const MOVE_BLOCK: usize = 1 << 20;
34
35trait Sink: Read + Write + Seek + Send {}
36
37impl<T: Read + Write + Seek + Send> Sink for T {}
38
39/// Writes MP4 or MOV files with the index before the media data (faststart), tracks interleaved
40/// in chunks of about half a second.
41pub struct Mp4Writer {
42    sink: Box<dyn Sink>,
43    flavor: Mp4Flavor,
44    tracks: Vec<Track>,
45    started: bool,
46    /// Where the 16 bytes before the media data start: a `free` box and the `mdat` header.
47    mdat_at: u64,
48    /// Media bytes written so far.
49    written: u64,
50    buffered: usize,
51}
52
53impl std::fmt::Debug for Mp4Writer {
54    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        formatter
56            .debug_struct("Mp4Writer")
57            .field("flavor", &self.flavor)
58            .field("tracks", &self.tracks.len())
59            .finish_non_exhaustive()
60    }
61}
62
63#[derive(Clone, Copy)]
64struct Sample {
65    size: u32,
66    dts: i64,
67    cts: i64,
68    duration: i64,
69    keyframe: bool,
70}
71
72struct Chunk {
73    start: i64,
74    samples: Vec<(Sample, Bytes)>,
75}
76
77struct Track {
78    info: TrackInfo,
79    /// The sample entry box, built when the track is added.
80    entry: Bytes,
81    in_timescale: u32,
82    timescale: u32,
83    /// The duration a packet without one gets from the frame rate, in `timescale` units.
84    nominal_duration: Option<i64>,
85    pending: VecDeque<Chunk>,
86    last_dts: Option<i64>,
87    samples: Vec<Sample>,
88    /// Chunk offsets from the start of the media data, and their sample counts.
89    chunks: Vec<(u64, u32)>,
90}
91
92impl Mp4Writer {
93    /// A writer into `file`, which must be open for reading as well as writing
94    /// (`OpenOptions::new().read(true).write(true)`): `finish` moves the media data.
95    #[must_use]
96    pub fn create(file: std::fs::File, flavor: Mp4Flavor) -> Self {
97        Self::new(file, flavor)
98    }
99
100    /// A writer into any readable, writable and seekable `sink`, starting at its offset 0.
101    pub fn new<W: Read + Write + Seek + Send + 'static>(sink: W, flavor: Mp4Flavor) -> Self {
102        Self {
103            sink: Box::new(sink),
104            flavor,
105            tracks: Vec::new(),
106            started: false,
107            mdat_at: 0,
108            written: 0,
109            buffered: 0,
110        }
111    }
112
113    fn start(&mut self) -> Result<(), MuxError> {
114        let ftyp = self.ftyp();
115        self.sink.seek(SeekFrom::Start(0))?;
116        self.sink.write_all(&ftyp)?;
117        self.mdat_at = ftyp.len() as u64;
118        let mut header = BytesMut::with_capacity(16);
119        header.put_u32(8);
120        header.put_slice(if self.flavor == Mp4Flavor::Mov {
121            b"wide"
122        } else {
123            b"free"
124        });
125        header.put_u32(8);
126        header.put_slice(b"mdat");
127        self.sink.write_all(&header)?;
128        self.started = true;
129        Ok(())
130    }
131
132    fn ftyp(&self) -> Bytes {
133        let mut brands: Vec<&[u8; 4]> = Vec::new();
134        let major: &[u8; 4] = match self.flavor {
135            Mp4Flavor::Mov => {
136                brands.push(b"qt  ");
137                b"qt  "
138            }
139            Mp4Flavor::Mp4 => {
140                brands.extend([b"isom", b"iso2"]);
141                if self.tracks.iter().any(|track| matches!(&track.info.video, Some(video) if video.codec == VideoCodec::H264)) {
142                    brands.push(b"avc1");
143                }
144                if self.tracks.iter().any(|track| matches!(&track.info.video, Some(video) if video.codec == VideoCodec::Av1)) {
145                    brands.push(b"av01");
146                }
147                brands.push(b"mp41");
148                b"isom"
149            }
150        };
151        let mut payload = BytesMut::new();
152        payload.put_slice(major);
153        payload.put_u32(0x200);
154        for brand in brands {
155            payload.put_slice(brand);
156        }
157        boxed(*b"ftyp", &payload)
158    }
159
160    /// Writes chunks that no other track can still precede; with `all`, every chunk.
161    fn flush(&mut self, all: bool) -> Result<(), MuxError> {
162        loop {
163            let Some((track, forced)) = self.next_chunk(all) else {
164                return Ok(());
165            };
166            if !forced && !all && !self.ready(track) {
167                return Ok(());
168            }
169            let chunk = self.tracks[track].pending.pop_front().expect("chunk");
170            let offset = self.written;
171            let mut count = 0_u32;
172            for (sample, data) in &chunk.samples {
173                self.sink.write_all(data)?;
174                self.written += data.len() as u64;
175                self.buffered -= data.len();
176                self.tracks[track].samples.push(*sample);
177                count += 1;
178            }
179            self.tracks[track].chunks.push((offset, count));
180        }
181    }
182
183    /// The earliest chunk that may be written: complete chunks (every chunk but each track's
184    /// last, or all of them with `all`), or any chunk once too much is buffered. The flag tells
185    /// whether memory forces it.
186    fn next_chunk(&self, all: bool) -> Option<(usize, bool)> {
187        let forced = self.buffered > MAX_BUFFERED;
188        let mut best: Option<(usize, i64, u32)> = None;
189        for (position, track) in self.tracks.iter().enumerate() {
190            let complete = if all || forced {
191                track.pending.len()
192            } else {
193                track.pending.len().saturating_sub(1)
194            };
195            if complete == 0 {
196                continue;
197            }
198            let start = track.pending[0].start;
199            let earlier = best.is_none_or(|(_, best_start, best_scale)| {
200                i128::from(start) * i128::from(best_scale)
201                    < i128::from(best_start) * i128::from(track.timescale)
202            });
203            if earlier {
204                best = Some((position, start, track.timescale));
205            }
206        }
207        best.map(|(position, _, _)| (position, forced))
208    }
209
210    /// Whether every other track has moved past the start of `track`'s first chunk.
211    fn ready(&self, track: usize) -> bool {
212        let candidate = &self.tracks[track];
213        let start = i128::from(candidate.pending[0].start);
214        self.tracks.iter().enumerate().all(|(position, other)| {
215            if position == track {
216                return true;
217            }
218            let reached = match (other.pending.front(), other.last_dts) {
219                (Some(chunk), _) => chunk.start,
220                (None, Some(last)) => last,
221                (None, None) => return false,
222            };
223            i128::from(reached) * i128::from(candidate.timescale)
224                >= start * i128::from(other.timescale)
225        })
226    }
227
228    fn finish_inner(&mut self) -> Result<(), MuxError> {
229        if !self.started {
230            self.start()?;
231        }
232        self.flush(true)?;
233        let header_len = 16;
234        let data_end = self.mdat_at + header_len + self.written;
235        let mdat_size = 8 + self.written;
236        let mut header = BytesMut::with_capacity(16);
237        if let Ok(size) = u32::try_from(mdat_size) {
238            header.put_u32(8);
239            header.put_slice(if self.flavor == Mp4Flavor::Mov {
240                b"wide"
241            } else {
242                b"free"
243            });
244            header.put_u32(size);
245            header.put_slice(b"mdat");
246        } else {
247            header.put_u32(1);
248            header.put_slice(b"mdat");
249            header.put_u64(16 + self.written);
250        }
251        self.sink.seek(SeekFrom::Start(self.mdat_at))?;
252        self.sink.write_all(&header)?;
253        let compact_len = self.moov(0, false).len() as u64;
254        let last_chunk = self
255            .tracks
256            .iter()
257            .flat_map(|track| track.chunks.iter().map(|chunk| chunk.0))
258            .max()
259            .unwrap_or(0);
260        let compact_base = self.mdat_at + compact_len + header_len;
261        let moov = if u32::try_from(compact_base + last_chunk).is_ok() {
262            self.moov(compact_base, false)
263        } else {
264            let wide_len = self.moov(0, true).len() as u64;
265            self.moov(self.mdat_at + wide_len + header_len, true)
266        };
267        move_forward(
268            self.sink.as_mut(),
269            self.mdat_at,
270            data_end,
271            moov.len() as u64,
272        )?;
273        self.sink.seek(SeekFrom::Start(self.mdat_at))?;
274        self.sink.write_all(&moov)?;
275        self.sink.flush()?;
276        Ok(())
277    }
278
279    fn moov(&self, base: u64, wide: bool) -> Bytes {
280        let mut payload = BytesMut::new();
281        let durations = self
282            .tracks
283            .iter()
284            .filter(|track| !track.samples.is_empty())
285            .map(|track| {
286                rescale_up(
287                    track.end_pts(),
288                    i64::from(MOVIE_TIMESCALE),
289                    i64::from(track.timescale),
290                )
291            })
292            .max()
293            .unwrap_or(0);
294        payload.put_slice(&mvhd(
295            durations,
296            u32::try_from(self.tracks.len() + 1).unwrap_or(u32::MAX),
297        ));
298        for (position, track) in self.tracks.iter().enumerate() {
299            let id = u32::try_from(position + 1).unwrap_or(u32::MAX);
300            payload.put_slice(&track.trak(id, base, wide, self.flavor));
301        }
302        boxed(*b"moov", &payload)
303    }
304}
305
306/// Moves `[from, to)` forward by `by` bytes, from the end backwards.
307fn move_forward(sink: &mut dyn Sink, from: u64, to: u64, by: u64) -> Result<(), MuxError> {
308    let mut buffer = vec![0; MOVE_BLOCK];
309    let mut end = to;
310    while end > from {
311        let length = usize::try_from((end - from).min(MOVE_BLOCK as u64)).unwrap_or(MOVE_BLOCK);
312        let start = end - length as u64;
313        sink.seek(SeekFrom::Start(start))?;
314        sink.read_exact(&mut buffer[..length])?;
315        sink.seek(SeekFrom::Start(start + by))?;
316        sink.write_all(&buffer[..length])?;
317        end = start;
318    }
319    Ok(())
320}
321
322/// `a * b / c` rounded up, for positive `c`.
323fn rescale_up(a: i64, b: i64, c: i64) -> i64 {
324    if c <= 0 {
325        return 0;
326    }
327    let product = i128::from(a) * i128::from(b);
328    let c = i128::from(c);
329    let quotient = product.div_euclid(c) + i128::from(product.rem_euclid(c) != 0);
330    i64::try_from(quotient).unwrap_or(i64::MAX)
331}
332
333/// `a * b / c` rounded down, for positive `c`.
334fn rescale_down(a: i64, b: i64, c: i64) -> i64 {
335    if c <= 0 {
336        return 0;
337    }
338    let quotient = (i128::from(a) * i128::from(b)).div_euclid(i128::from(c));
339    i64::try_from(quotient).unwrap_or(i64::MIN)
340}
341
342fn boxed(kind: [u8; 4], payload: &[u8]) -> Bytes {
343    let mut out = BytesMut::with_capacity(payload.len() + 16);
344    if let Ok(size) = u32::try_from(payload.len() + 8) {
345        out.put_u32(size);
346        out.put_slice(&kind);
347    } else {
348        out.put_u32(1);
349        out.put_slice(&kind);
350        out.put_u64(payload.len() as u64 + 16);
351    }
352    out.put_slice(payload);
353    out.freeze()
354}
355
356fn full_box(kind: [u8; 4], version: u8, flags: u32, payload: &[u8]) -> Bytes {
357    let mut body = BytesMut::with_capacity(payload.len() + 4);
358    body.put_u32((u32::from(version) << 24) | (flags & 0x00ff_ffff));
359    body.put_slice(payload);
360    boxed(kind, &body)
361}
362
363/// Writes a non-negative duration or offset as 64 bits in a version 1 box, else 32.
364fn put_wide(out: &mut BytesMut, version: u8, value: i64) {
365    let value = u64::try_from(value).unwrap_or(0);
366    if version == 1 {
367        out.put_u64(value);
368    } else {
369        out.put_u32(u32::try_from(value).unwrap_or(u32::MAX));
370    }
371}
372
373fn put_matrix(out: &mut BytesMut, matrix: [i32; 9]) {
374    for value in matrix {
375        out.put_i32(value);
376    }
377}
378
379const IDENTITY: [i32; 9] = [1 << 16, 0, 0, 0, 1 << 16, 0, 0, 0, 1 << 30];
380
381/// The display matrix the reader turns back into `orientation`: the clockwise rotation, its first
382/// column negated for a mirror (as `FFmpeg`'s `-display_hflip`).
383pub(crate) fn display_matrix(orientation: Orientation) -> [i32; 9] {
384    let (cos, sin): (i32, i32) = match orientation.rotation {
385        Rotation::Deg0 => (1, 0),
386        Rotation::Deg90 => (0, 1),
387        Rotation::Deg180 => (-1, 0),
388        Rotation::Deg270 => (0, -1),
389    };
390    let mut matrix = [
391        cos << 16,
392        sin << 16,
393        0,
394        -sin << 16,
395        cos << 16,
396        0,
397        0,
398        0,
399        1 << 30,
400    ];
401    if orientation.mirror {
402        matrix[0] = -cos << 16;
403        matrix[1] = -sin << 16;
404    }
405    matrix
406}
407
408fn mvhd(duration: i64, next_track: u32) -> Bytes {
409    let version = u8::from(duration >= i64::from(i32::MAX));
410    let mut payload = BytesMut::new();
411    put_wide(&mut payload, version, 0);
412    put_wide(&mut payload, version, 0);
413    payload.put_u32(MOVIE_TIMESCALE);
414    put_wide(&mut payload, version, duration);
415    payload.put_u32(0x0001_0000);
416    payload.put_u16(0x0100);
417    payload.put_slice(&[0; 10]);
418    put_matrix(&mut payload, IDENTITY);
419    payload.put_slice(&[0; 24]);
420    payload.put_u32(next_track);
421    full_box(*b"mvhd", version, 0, &payload)
422}
423
424/// An `esds` box for MPEG-4 object type `object_type` and stream type `stream_type`.
425fn esds(
426    track_id: u16,
427    object_type: u8,
428    audio: bool,
429    info: &[u8],
430    bit_rates: (u32, u32, u32),
431) -> Bytes {
432    fn descriptor(out: &mut BytesMut, tag: u8, length: usize) {
433        out.put_u8(tag);
434        let length = u32::try_from(length).unwrap_or(0x0fff_ffff);
435        out.put_u8(0x80 | ((length >> 21) & 0x7f) as u8);
436        out.put_u8(0x80 | ((length >> 14) & 0x7f) as u8);
437        out.put_u8(0x80 | ((length >> 7) & 0x7f) as u8);
438        out.put_u8((length & 0x7f) as u8);
439    }
440    let info_len = if info.is_empty() { 0 } else { 5 + info.len() };
441    let mut payload = BytesMut::new();
442    descriptor(&mut payload, 3, 3 + 5 + 13 + info_len + 5 + 1);
443    payload.put_u16(track_id);
444    payload.put_u8(0);
445    descriptor(&mut payload, 4, 13 + info_len);
446    payload.put_u8(object_type);
447    payload.put_u8(if audio { 0x15 } else { 0x11 });
448    let (buffer, max, average) = bit_rates;
449    payload.put_uint(u64::from(buffer.min(0x00ff_ffff)), 3);
450    payload.put_u32(max);
451    payload.put_u32(average);
452    if !info.is_empty() {
453        descriptor(&mut payload, 5, info.len());
454        payload.put_slice(info);
455    }
456    descriptor(&mut payload, 6, 1);
457    payload.put_u8(2);
458    full_box(*b"esds", 0, 0, &payload)
459}
460
461/// The `dOps` box for an Ogg `OpusHead`.
462fn dops(head: &[u8]) -> Option<Bytes> {
463    if head.len() < 19 || &head[..8] != b"OpusHead" {
464        return None;
465    }
466    let channels = head[9];
467    let family = head[18];
468    let mut payload = BytesMut::new();
469    payload.put_u8(0);
470    payload.put_u8(channels);
471    payload.put_u16(u16::from_le_bytes([head[10], head[11]]));
472    payload.put_u32(u32::from_le_bytes([head[12], head[13], head[14], head[15]]));
473    payload.put_u16(u16::from_le_bytes([head[16], head[17]]));
474    payload.put_u8(family);
475    if family != 0 {
476        payload.put_slice(head.get(19..21 + usize::from(channels))?);
477    }
478    Some(boxed(*b"dOps", &payload))
479}
480
481fn color_box(color: alpha2_media::ColorMetadata) -> Bytes {
482    let primaries: u16 = match color.primaries {
483        ColorPrimaries::Bt601 => 6,
484        ColorPrimaries::Bt709 => 1,
485        ColorPrimaries::Bt2020 => 9,
486        ColorPrimaries::DisplayP3 => 12,
487    };
488    let transfer: u16 = match color.transfer {
489        TransferFunction::Bt709 => 1,
490        TransferFunction::Srgb => 13,
491        TransferFunction::Pq => 16,
492        TransferFunction::Hlg => 18,
493    };
494    let matrix: u16 = match color.matrix {
495        ColorMatrix::Bt601 => 6,
496        ColorMatrix::Bt709 => 1,
497        ColorMatrix::Bt2020Ncl => 9,
498        ColorMatrix::Rgb => 0,
499    };
500    let mut payload = BytesMut::new();
501    payload.put_slice(b"nclx");
502    payload.put_u16(primaries);
503    payload.put_u16(transfer);
504    payload.put_u16(matrix);
505    payload.put_u8(if color.range == ColorRange::Full {
506        0x80
507    } else {
508        0
509    });
510    boxed(*b"colr", &payload)
511}
512
513fn video_entry(video: &VideoTrack, flavor: Mp4Flavor) -> Result<Bytes, MuxError> {
514    let (format, config): (FourCc, Option<Bytes>) = match video.codec {
515        VideoCodec::H264 => (
516            FourCc(if video.in_band_parameter_sets {
517                *b"avc3"
518            } else {
519                *b"avc1"
520            }),
521            Some(boxed(*b"avcC", &video.codec_private)),
522        ),
523        VideoCodec::Hevc => (
524            FourCc(if video.in_band_parameter_sets {
525                *b"hev1"
526            } else {
527                *b"hvc1"
528            }),
529            Some(boxed(*b"hvcC", &video.codec_private)),
530        ),
531        VideoCodec::Av1 => (
532            FourCc(*b"av01"),
533            Some(boxed(*b"av1C", &video.codec_private)),
534        ),
535        VideoCodec::Vp9 => {
536            if video.codec_private.len() < 4 {
537                return Err(MuxError::Unsupported(
538                    "VP9 needs its vpcC configuration to be written to MP4".into(),
539                ));
540            }
541            (
542                FourCc(*b"vp09"),
543                Some(boxed(*b"vpcC", &video.codec_private)),
544            )
545        }
546        VideoCodec::Mpeg4Part2 => (FourCc(*b"mp4v"), None),
547        VideoCodec::ProRes(code) if flavor == Mp4Flavor::Mov => (code, None),
548        VideoCodec::ProRes(_) => {
549            return Err(MuxError::Unsupported(
550                "ProRes is written to MOV, not MP4".into(),
551            ));
552        }
553        VideoCodec::Vp8 | VideoCodec::Other(_) => {
554            return Err(MuxError::Unsupported(format!(
555                "{:?} video is not written to MP4 or MOV",
556                video.codec
557            )));
558        }
559    };
560    if matches!(
561        video.codec,
562        VideoCodec::H264 | VideoCodec::Hevc | VideoCodec::Av1
563    ) && video.codec_private.is_empty()
564    {
565        return Err(MuxError::Unsupported(format!(
566            "{:?} needs its decoder configuration record",
567            video.codec
568        )));
569    }
570    let (Ok(width), Ok(height)) = (u16::try_from(video.width), u16::try_from(video.height)) else {
571        return Err(MuxError::Unsupported(
572            "the picture is too large for a sample entry".into(),
573        ));
574    };
575    let mut payload = BytesMut::new();
576    payload.put_slice(&[0; 6]);
577    payload.put_u16(1);
578    payload.put_slice(&[0; 16]);
579    payload.put_u16(width);
580    payload.put_u16(height);
581    payload.put_u32(0x0048_0000);
582    payload.put_u32(0x0048_0000);
583    payload.put_u32(0);
584    payload.put_u16(1);
585    payload.put_slice(&[0; 32]);
586    payload.put_u16(0x18);
587    payload.put_i16(-1);
588    if let Some(config) = config {
589        payload.put_slice(&config);
590    }
591    if video.codec == VideoCodec::Mpeg4Part2 {
592        payload.put_slice(&esds(0, 0x20, false, &video.codec_private, (0, 0, 0)));
593    }
594    if let Some(color) = video.color {
595        payload.put_slice(&color_box(color));
596    }
597    if let Some(ratio) = video.sample_aspect_ratio {
598        let mut pasp = BytesMut::new();
599        pasp.put_u32(ratio.num);
600        pasp.put_u32(ratio.den);
601        payload.put_slice(&boxed(*b"pasp", &pasp));
602    }
603    Ok(boxed(format.0, &payload))
604}
605
606fn audio_entry(audio: &AudioTrack, flavor: Mp4Flavor) -> Result<Bytes, MuxError> {
607    let mut channels = audio.channels;
608    let mut rate = audio.sample_rate;
609    let (format, config): (&[u8; 4], Bytes) = match audio.codec {
610        AudioCodec::Aac => (b"mp4a", Bytes::new()),
611        AudioCodec::Opus if flavor == Mp4Flavor::Mp4 => {
612            let config = dops(&audio.codec_private).ok_or_else(|| {
613                MuxError::Unsupported("Opus needs its OpusHead to be written to MP4".into())
614            })?;
615            channels = u32::from(audio.codec_private[9]);
616            rate = 48_000;
617            (b"Opus", config)
618        }
619        codec => {
620            return Err(MuxError::Unsupported(format!(
621                "{codec:?} audio is not written to {}",
622                if flavor == Mp4Flavor::Mov {
623                    "MOV"
624                } else {
625                    "MP4"
626                }
627            )));
628        }
629    };
630    let mut payload = BytesMut::new();
631    payload.put_slice(&[0; 6]);
632    payload.put_u16(1);
633    payload.put_slice(&[0; 8]);
634    payload.put_u16(u16::try_from(channels).unwrap_or(2));
635    payload.put_u16(16);
636    payload.put_u16(0);
637    payload.put_u16(0);
638    payload.put_u32(if rate <= 0xffff { rate << 16 } else { 0 });
639    payload.put_slice(&config);
640    Ok(boxed(*format, &payload))
641}
642
643fn language_code(language: Option<&str>) -> u16 {
644    let code = language.unwrap_or("und");
645    let letters = code.as_bytes();
646    if letters.len() == 3 && letters.iter().all(u8::is_ascii_lowercase) {
647        letters
648            .iter()
649            .fold(0, |packed, letter| (packed << 5) | u16::from(letter - 0x60))
650    } else {
651        0x55c4
652    }
653}
654
655impl Track {
656    /// The presentation end: the latest `pts + duration`.
657    fn end_pts(&self) -> i64 {
658        self.samples
659            .iter()
660            .map(|sample| {
661                sample
662                    .dts
663                    .saturating_add(sample.cts)
664                    .saturating_add(sample.duration)
665            })
666            .max()
667            .unwrap_or(0)
668    }
669
670    /// The first sample's presentation time.
671    fn start_pts(&self) -> i64 {
672        self.samples
673            .first()
674            .map_or(0, |sample| sample.dts.saturating_add(sample.cts))
675    }
676
677    fn trak(&self, id: u32, base: u64, wide: bool, flavor: Mp4Flavor) -> Bytes {
678        let mut payload = BytesMut::new();
679        payload.put_slice(&self.tkhd(id));
680        if self.samples.first().is_some_and(|first| first.dts != 0)
681            || self.samples.iter().any(|sample| sample.cts != 0)
682        {
683            payload.put_slice(&self.edts());
684        }
685        payload.put_slice(&self.mdia(base, wide, flavor));
686        boxed(*b"trak", &payload)
687    }
688
689    fn tkhd(&self, id: u32) -> Bytes {
690        let duration = if self.samples.is_empty() {
691            0
692        } else {
693            rescale_up(
694                self.end_pts(),
695                i64::from(MOVIE_TIMESCALE),
696                i64::from(self.timescale),
697            )
698        };
699        let version = u8::from(duration >= i64::from(i32::MAX));
700        let mut payload = BytesMut::new();
701        put_wide(&mut payload, version, 0);
702        put_wide(&mut payload, version, 0);
703        payload.put_u32(id);
704        payload.put_u32(0);
705        put_wide(&mut payload, version, duration);
706        payload.put_u64(0);
707        payload.put_u16(0);
708        payload.put_u16(u16::from(self.info.kind == TrackKind::Audio));
709        payload.put_u16(if self.info.kind == TrackKind::Audio {
710            0x0100
711        } else {
712            0
713        });
714        payload.put_u16(0);
715        let matrix = self
716            .info
717            .video
718            .as_ref()
719            .map_or(IDENTITY, |video| display_matrix(video.orientation));
720        put_matrix(&mut payload, matrix);
721        match &self.info.video {
722            Some(video) => {
723                payload.put_u32(video.width << 16);
724                payload.put_u32(video.height << 16);
725            }
726            None => payload.put_u64(0),
727        }
728        let flags = 2 | u32::from(self.info.enabled);
729        full_box(*b"tkhd", version, flags, &payload)
730    }
731
732    /// The edit list `FFmpeg` writes: an empty edit for a positive start, then the media from
733    /// its first presented sample.
734    fn edts(&self) -> Bytes {
735        let timescale = i64::from(self.timescale);
736        let first = self.samples[0];
737        let samples_duration = self.end_pts().saturating_sub(self.start_pts());
738        let mut duration = rescale_up(samples_duration, i64::from(MOVIE_TIMESCALE), timescale);
739        let delay = rescale_down(
740            first.dts.saturating_add(first.cts),
741            i64::from(MOVIE_TIMESCALE),
742            timescale,
743        );
744        let mut start = first.cts;
745        if delay <= 0 {
746            start = -first.dts.min(0);
747            duration = duration.saturating_add(delay);
748        }
749        let version = u8::from(duration >= i64::from(i32::MAX) || delay >= i64::from(i32::MAX));
750        let mut payload = BytesMut::new();
751        payload.put_u32(1 + u32::from(delay > 0));
752        let mut entry = |segment: i64, media: i64| {
753            put_wide(&mut payload, version, segment);
754            if version == 1 {
755                payload.put_i64(media);
756            } else {
757                payload.put_i32(i32::try_from(media).unwrap_or(-1));
758            }
759            payload.put_u32(0x0001_0000);
760        };
761        if delay > 0 {
762            entry(delay, -1);
763        }
764        entry(duration, start);
765        boxed(*b"edts", &full_box(*b"elst", version, 0, &payload))
766    }
767
768    fn mdia(&self, base: u64, wide: bool, flavor: Mp4Flavor) -> Bytes {
769        let duration = if self.samples.is_empty() {
770            0
771        } else {
772            self.end_pts().saturating_sub(self.start_pts())
773        };
774        let version = u8::from(duration >= i64::from(i32::MAX));
775        let mut mdhd = BytesMut::new();
776        put_wide(&mut mdhd, version, 0);
777        put_wide(&mut mdhd, version, 0);
778        mdhd.put_u32(self.timescale);
779        put_wide(&mut mdhd, version, duration);
780        mdhd.put_u16(language_code(self.info.language.as_deref()));
781        mdhd.put_u16(0);
782        let (handler, name): (&[u8; 4], &str) = match self.info.kind {
783            TrackKind::Video => (b"vide", "VideoHandler"),
784            _ => (b"soun", "SoundHandler"),
785        };
786        let mut hdlr = BytesMut::new();
787        hdlr.put_slice(if flavor == Mp4Flavor::Mov {
788            b"mhlr"
789        } else {
790            &[0; 4]
791        });
792        hdlr.put_slice(handler);
793        hdlr.put_slice(&[0; 12]);
794        if flavor == Mp4Flavor::Mov {
795            hdlr.put_u8(u8::try_from(name.len()).unwrap_or(0));
796            hdlr.put_slice(name.as_bytes());
797        } else {
798            hdlr.put_slice(name.as_bytes());
799            hdlr.put_u8(0);
800        }
801        let mut payload = BytesMut::new();
802        payload.put_slice(&full_box(*b"mdhd", version, 0, &mdhd));
803        payload.put_slice(&full_box(*b"hdlr", 0, 0, &hdlr));
804        payload.put_slice(&self.minf(base, wide));
805        boxed(*b"mdia", &payload)
806    }
807
808    fn minf(&self, base: u64, wide: bool) -> Bytes {
809        let mut payload = BytesMut::new();
810        if self.info.kind == TrackKind::Video {
811            payload.put_slice(&full_box(*b"vmhd", 0, 1, &[0; 8]));
812        } else {
813            payload.put_slice(&full_box(*b"smhd", 0, 0, &[0; 4]));
814        }
815        let url = full_box(*b"url ", 0, 1, &[]);
816        let mut dref = BytesMut::new();
817        dref.put_u32(1);
818        dref.put_slice(&url);
819        payload.put_slice(&boxed(*b"dinf", &full_box(*b"dref", 0, 0, &dref)));
820        payload.put_slice(&self.stbl(base, wide));
821        boxed(*b"minf", &payload)
822    }
823
824    fn stbl(&self, base: u64, wide: bool) -> Bytes {
825        let mut payload = BytesMut::new();
826        let mut descriptions = BytesMut::new();
827        descriptions.put_u32(1);
828        descriptions.put_slice(&self.entry_with_rates());
829        payload.put_slice(&full_box(*b"stsd", 0, 0, &descriptions));
830        payload.put_slice(&self.stts());
831        if self.samples.iter().any(|sample| sample.cts != 0) {
832            payload.put_slice(&self.ctts());
833        }
834        if self.samples.iter().any(|sample| !sample.keyframe) {
835            let keys = self
836                .samples
837                .iter()
838                .enumerate()
839                .filter(|(_, sample)| sample.keyframe)
840                .map(|(at, _)| u32::try_from(at + 1).unwrap_or(u32::MAX))
841                .collect::<Vec<_>>();
842            let mut sync = BytesMut::new();
843            sync.put_u32(u32::try_from(keys.len()).unwrap_or(u32::MAX));
844            for key in keys {
845                sync.put_u32(key);
846            }
847            payload.put_slice(&full_box(*b"stss", 0, 0, &sync));
848        }
849        payload.put_slice(&self.stsc());
850        payload.put_slice(&self.stsz());
851        let mut offsets = BytesMut::new();
852        offsets.put_u32(u32::try_from(self.chunks.len()).unwrap_or(u32::MAX));
853        for (offset, _) in &self.chunks {
854            if wide {
855                offsets.put_u64(base + offset);
856            } else {
857                offsets.put_u32(u32::try_from(base + offset).unwrap_or(u32::MAX));
858            }
859        }
860        payload.put_slice(&full_box(
861            if wide { *b"co64" } else { *b"stco" },
862            0,
863            0,
864            &offsets,
865        ));
866        boxed(*b"stbl", &payload)
867    }
868
869    /// The sample entry; an `mp4a` entry gets its `esds` here, once bit rates are known.
870    fn entry_with_rates(&self) -> Bytes {
871        let Some(audio) = &self.info.audio else {
872            return self.entry.clone();
873        };
874        if audio.codec != AudioCodec::Aac {
875            return self.entry.clone();
876        }
877        let total: u64 = self
878            .samples
879            .iter()
880            .map(|sample| u64::from(sample.size))
881            .sum();
882        let largest = self
883            .samples
884            .iter()
885            .map(|sample| sample.size)
886            .max()
887            .unwrap_or(0);
888        let span = self
889            .end_pts()
890            .saturating_sub(self.samples.first().map_or(0, |sample| sample.dts));
891        let average = if span > 0 {
892            u32::try_from(rescale_down(
893                i64::try_from(total * 8).unwrap_or(i64::MAX),
894                i64::from(self.timescale),
895                span,
896            ))
897            .unwrap_or(u32::MAX)
898        } else {
899            0
900        };
901        let esds = esds(
902            0,
903            0x40,
904            true,
905            &audio.codec_private,
906            (largest, average, average),
907        );
908        let mut entry = BytesMut::from(&self.entry[..]);
909        entry.put_slice(&esds);
910        let size = u32::try_from(entry.len()).unwrap_or(u32::MAX);
911        entry[..4].copy_from_slice(&size.to_be_bytes());
912        entry.freeze()
913    }
914
915    fn stts(&self) -> Bytes {
916        let mut entries: Vec<(u32, u32)> = Vec::new();
917        for (at, sample) in self.samples.iter().enumerate() {
918            let delta = match self.samples.get(at + 1) {
919                Some(next) => next.dts.saturating_sub(sample.dts),
920                None => sample.duration,
921            };
922            let delta = u32::try_from(delta.max(0)).unwrap_or(u32::MAX);
923            match entries.last_mut() {
924                Some((count, last)) if *last == delta => *count += 1,
925                _ => entries.push((1, delta)),
926            }
927        }
928        let mut payload = BytesMut::new();
929        payload.put_u32(u32::try_from(entries.len()).unwrap_or(u32::MAX));
930        for (count, delta) in entries {
931            payload.put_u32(count);
932            payload.put_u32(delta);
933        }
934        full_box(*b"stts", 0, 0, &payload)
935    }
936
937    fn ctts(&self) -> Bytes {
938        let mut entries: Vec<(u32, i64)> = Vec::new();
939        for sample in &self.samples {
940            match entries.last_mut() {
941                Some((count, offset)) if *offset == sample.cts => *count += 1,
942                _ => entries.push((1, sample.cts)),
943            }
944        }
945        let negative = entries.iter().any(|(_, offset)| *offset < 0);
946        let mut payload = BytesMut::new();
947        payload.put_u32(u32::try_from(entries.len()).unwrap_or(u32::MAX));
948        for (count, offset) in entries {
949            payload.put_u32(count);
950            payload.put_i32(i32::try_from(offset).unwrap_or(i32::MAX));
951        }
952        full_box(*b"ctts", u8::from(negative), 0, &payload)
953    }
954
955    fn stsc(&self) -> Bytes {
956        let mut entries: Vec<(u32, u32)> = Vec::new();
957        for (at, (_, count)) in self.chunks.iter().enumerate() {
958            if entries.last().is_none_or(|(_, last)| last != count) {
959                entries.push((u32::try_from(at + 1).unwrap_or(u32::MAX), *count));
960            }
961        }
962        let mut payload = BytesMut::new();
963        payload.put_u32(u32::try_from(entries.len()).unwrap_or(u32::MAX));
964        for (first, count) in entries {
965            payload.put_u32(first);
966            payload.put_u32(count);
967            payload.put_u32(1);
968        }
969        full_box(*b"stsc", 0, 0, &payload)
970    }
971
972    fn stsz(&self) -> Bytes {
973        let mut payload = BytesMut::new();
974        let first = self.samples.first().map_or(0, |sample| sample.size);
975        let constant =
976            !self.samples.is_empty() && self.samples.iter().all(|sample| sample.size == first);
977        payload.put_u32(if constant { first } else { 0 });
978        payload.put_u32(u32::try_from(self.samples.len()).unwrap_or(u32::MAX));
979        if !constant {
980            for sample in &self.samples {
981                payload.put_u32(sample.size);
982            }
983        }
984        full_box(*b"stsz", 0, 0, &payload)
985    }
986}
987
988impl ContainerWriter for Mp4Writer {
989    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError> {
990        if self.started {
991            return Err(MuxError::Invalid(
992                "tracks are added before the first packet".into(),
993            ));
994        }
995        if track.timescale == 0 {
996            return Err(MuxError::Invalid("a track needs a timescale".into()));
997        }
998        let (entry, timescale, nominal) = match (track.kind, &track.video, &track.audio) {
999            (TrackKind::Video, Some(video), _) => {
1000                let mut timescale = track.timescale;
1001                while timescale < 10_000 {
1002                    timescale *= 2;
1003                }
1004                let nominal = video.frame_rate.and_then(|rate| {
1005                    let ticks = u64::from(timescale) * u64::from(rate.denominator());
1006                    (ticks % u64::from(rate.numerator()) == 0)
1007                        .then(|| i64::try_from(ticks / u64::from(rate.numerator())).ok())
1008                        .flatten()
1009                });
1010                (video_entry(video, self.flavor)?, timescale, nominal)
1011            }
1012            (TrackKind::Audio, _, Some(audio)) => {
1013                let timescale = if audio.sample_rate > 0 {
1014                    audio.sample_rate
1015                } else {
1016                    track.timescale
1017                };
1018                (audio_entry(audio, self.flavor)?, timescale, None)
1019            }
1020            _ => {
1021                return Err(MuxError::Unsupported(
1022                    "only video and audio tracks are written to MP4".into(),
1023                ));
1024            }
1025        };
1026        if self.tracks.len() >= u16::MAX as usize {
1027            return Err(MuxError::Unsupported("too many tracks".into()));
1028        }
1029        self.tracks.push(Track {
1030            info: track.clone(),
1031            entry,
1032            in_timescale: track.timescale,
1033            timescale,
1034            nominal_duration: nominal,
1035            pending: VecDeque::new(),
1036            last_dts: None,
1037            samples: Vec::new(),
1038            chunks: Vec::new(),
1039        });
1040        Ok(TrackId(
1041            u32::try_from(self.tracks.len()).unwrap_or(u32::MAX),
1042        ))
1043    }
1044
1045    fn write(&mut self, packet: Packet) -> Result<(), MuxError> {
1046        let position = usize::try_from(packet.track.0)
1047            .ok()
1048            .and_then(|id| id.checked_sub(1))
1049            .filter(|position| *position < self.tracks.len())
1050            .ok_or_else(|| MuxError::Invalid(format!("no track {}", packet.track.0)))?;
1051        if !self.started {
1052            self.start()?;
1053        }
1054        let track = &mut self.tracks[position];
1055        let (input, output) = (i64::from(track.in_timescale), i64::from(track.timescale));
1056        let dts = rescale(packet.dts, output, input);
1057        let pts = rescale(packet.pts, output, input);
1058        if track.last_dts.is_some_and(|last| dts <= last) {
1059            return Err(MuxError::Invalid(format!(
1060                "track {} decode times do not increase at {}",
1061                packet.track.0, packet.dts
1062            )));
1063        }
1064        let mut duration = rescale(packet.duration, output, input);
1065        if duration <= 0 {
1066            duration = track.nominal_duration.unwrap_or_else(|| {
1067                track
1068                    .samples
1069                    .last()
1070                    .or_else(|| {
1071                        track
1072                            .pending
1073                            .back()
1074                            .and_then(|chunk| chunk.samples.last().map(|(sample, _)| sample))
1075                    })
1076                    .map_or(0, |previous| dts.saturating_sub(previous.dts).max(0))
1077            });
1078        }
1079        let size = u32::try_from(packet.data.len())
1080            .map_err(|_| MuxError::Unsupported("a packet is larger than 4 GiB".into()))?;
1081        let sample = Sample {
1082            size,
1083            dts,
1084            cts: pts.saturating_sub(dts),
1085            duration,
1086            keyframe: packet.keyframe,
1087        };
1088        let half_second = output / 2;
1089        match track.pending.back_mut() {
1090            Some(chunk) if dts.saturating_sub(chunk.start) < half_second.max(1) => {
1091                chunk.samples.push((sample, packet.data.clone()));
1092            }
1093            _ => track.pending.push_back(Chunk {
1094                start: dts,
1095                samples: vec![(sample, packet.data.clone())],
1096            }),
1097        }
1098        track.last_dts = Some(dts);
1099        self.buffered += packet.data.len();
1100        self.flush(false)
1101    }
1102
1103    fn finish(mut self: Box<Self>) -> Result<(), MuxError> {
1104        self.finish_inner()
1105    }
1106}