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    };
487    let transfer: u16 = match color.transfer {
488        TransferFunction::Bt709 => 1,
489        TransferFunction::Srgb => 13,
490        TransferFunction::Pq => 16,
491        TransferFunction::Hlg => 18,
492    };
493    let matrix: u16 = match color.matrix {
494        ColorMatrix::Bt601 => 6,
495        ColorMatrix::Bt709 => 1,
496        ColorMatrix::Bt2020Ncl => 9,
497        ColorMatrix::Rgb => 0,
498    };
499    let mut payload = BytesMut::new();
500    payload.put_slice(b"nclx");
501    payload.put_u16(primaries);
502    payload.put_u16(transfer);
503    payload.put_u16(matrix);
504    payload.put_u8(if color.range == ColorRange::Full {
505        0x80
506    } else {
507        0
508    });
509    boxed(*b"colr", &payload)
510}
511
512fn video_entry(video: &VideoTrack, flavor: Mp4Flavor) -> Result<Bytes, MuxError> {
513    let (format, config): (FourCc, Option<Bytes>) = match video.codec {
514        VideoCodec::H264 => (
515            FourCc(if video.in_band_parameter_sets {
516                *b"avc3"
517            } else {
518                *b"avc1"
519            }),
520            Some(boxed(*b"avcC", &video.codec_private)),
521        ),
522        VideoCodec::Hevc => (
523            FourCc(if video.in_band_parameter_sets {
524                *b"hev1"
525            } else {
526                *b"hvc1"
527            }),
528            Some(boxed(*b"hvcC", &video.codec_private)),
529        ),
530        VideoCodec::Av1 => (
531            FourCc(*b"av01"),
532            Some(boxed(*b"av1C", &video.codec_private)),
533        ),
534        VideoCodec::Vp9 => {
535            if video.codec_private.len() < 4 {
536                return Err(MuxError::Unsupported(
537                    "VP9 needs its vpcC configuration to be written to MP4".into(),
538                ));
539            }
540            (
541                FourCc(*b"vp09"),
542                Some(boxed(*b"vpcC", &video.codec_private)),
543            )
544        }
545        VideoCodec::Mpeg4Part2 => (FourCc(*b"mp4v"), None),
546        VideoCodec::ProRes(code) if flavor == Mp4Flavor::Mov => (code, None),
547        VideoCodec::ProRes(_) => {
548            return Err(MuxError::Unsupported(
549                "ProRes is written to MOV, not MP4".into(),
550            ));
551        }
552        VideoCodec::Vp8 | VideoCodec::Other(_) => {
553            return Err(MuxError::Unsupported(format!(
554                "{:?} video is not written to MP4 or MOV",
555                video.codec
556            )));
557        }
558    };
559    if matches!(
560        video.codec,
561        VideoCodec::H264 | VideoCodec::Hevc | VideoCodec::Av1
562    ) && video.codec_private.is_empty()
563    {
564        return Err(MuxError::Unsupported(format!(
565            "{:?} needs its decoder configuration record",
566            video.codec
567        )));
568    }
569    let (Ok(width), Ok(height)) = (u16::try_from(video.width), u16::try_from(video.height)) else {
570        return Err(MuxError::Unsupported(
571            "the picture is too large for a sample entry".into(),
572        ));
573    };
574    let mut payload = BytesMut::new();
575    payload.put_slice(&[0; 6]);
576    payload.put_u16(1);
577    payload.put_slice(&[0; 16]);
578    payload.put_u16(width);
579    payload.put_u16(height);
580    payload.put_u32(0x0048_0000);
581    payload.put_u32(0x0048_0000);
582    payload.put_u32(0);
583    payload.put_u16(1);
584    payload.put_slice(&[0; 32]);
585    payload.put_u16(0x18);
586    payload.put_i16(-1);
587    if let Some(config) = config {
588        payload.put_slice(&config);
589    }
590    if video.codec == VideoCodec::Mpeg4Part2 {
591        payload.put_slice(&esds(0, 0x20, false, &video.codec_private, (0, 0, 0)));
592    }
593    if let Some(color) = video.color {
594        payload.put_slice(&color_box(color));
595    }
596    if let Some(ratio) = video.sample_aspect_ratio {
597        let mut pasp = BytesMut::new();
598        pasp.put_u32(ratio.num);
599        pasp.put_u32(ratio.den);
600        payload.put_slice(&boxed(*b"pasp", &pasp));
601    }
602    Ok(boxed(format.0, &payload))
603}
604
605fn audio_entry(audio: &AudioTrack, flavor: Mp4Flavor) -> Result<Bytes, MuxError> {
606    let mut channels = audio.channels;
607    let mut rate = audio.sample_rate;
608    let (format, config): (&[u8; 4], Bytes) = match audio.codec {
609        AudioCodec::Aac => (b"mp4a", Bytes::new()),
610        AudioCodec::Opus if flavor == Mp4Flavor::Mp4 => {
611            let config = dops(&audio.codec_private).ok_or_else(|| {
612                MuxError::Unsupported("Opus needs its OpusHead to be written to MP4".into())
613            })?;
614            channels = u32::from(audio.codec_private[9]);
615            rate = 48_000;
616            (b"Opus", config)
617        }
618        codec => {
619            return Err(MuxError::Unsupported(format!(
620                "{codec:?} audio is not written to {}",
621                if flavor == Mp4Flavor::Mov {
622                    "MOV"
623                } else {
624                    "MP4"
625                }
626            )));
627        }
628    };
629    let mut payload = BytesMut::new();
630    payload.put_slice(&[0; 6]);
631    payload.put_u16(1);
632    payload.put_slice(&[0; 8]);
633    payload.put_u16(u16::try_from(channels).unwrap_or(2));
634    payload.put_u16(16);
635    payload.put_u16(0);
636    payload.put_u16(0);
637    payload.put_u32(if rate <= 0xffff { rate << 16 } else { 0 });
638    payload.put_slice(&config);
639    Ok(boxed(*format, &payload))
640}
641
642fn language_code(language: Option<&str>) -> u16 {
643    let code = language.unwrap_or("und");
644    let letters = code.as_bytes();
645    if letters.len() == 3 && letters.iter().all(u8::is_ascii_lowercase) {
646        letters
647            .iter()
648            .fold(0, |packed, letter| (packed << 5) | u16::from(letter - 0x60))
649    } else {
650        0x55c4
651    }
652}
653
654impl Track {
655    /// The presentation end: the latest `pts + duration`.
656    fn end_pts(&self) -> i64 {
657        self.samples
658            .iter()
659            .map(|sample| {
660                sample
661                    .dts
662                    .saturating_add(sample.cts)
663                    .saturating_add(sample.duration)
664            })
665            .max()
666            .unwrap_or(0)
667    }
668
669    /// The first sample's presentation time.
670    fn start_pts(&self) -> i64 {
671        self.samples
672            .first()
673            .map_or(0, |sample| sample.dts.saturating_add(sample.cts))
674    }
675
676    fn trak(&self, id: u32, base: u64, wide: bool, flavor: Mp4Flavor) -> Bytes {
677        let mut payload = BytesMut::new();
678        payload.put_slice(&self.tkhd(id));
679        if self.samples.first().is_some_and(|first| first.dts != 0)
680            || self.samples.iter().any(|sample| sample.cts != 0)
681        {
682            payload.put_slice(&self.edts());
683        }
684        payload.put_slice(&self.mdia(base, wide, flavor));
685        boxed(*b"trak", &payload)
686    }
687
688    fn tkhd(&self, id: u32) -> Bytes {
689        let duration = if self.samples.is_empty() {
690            0
691        } else {
692            rescale_up(
693                self.end_pts(),
694                i64::from(MOVIE_TIMESCALE),
695                i64::from(self.timescale),
696            )
697        };
698        let version = u8::from(duration >= i64::from(i32::MAX));
699        let mut payload = BytesMut::new();
700        put_wide(&mut payload, version, 0);
701        put_wide(&mut payload, version, 0);
702        payload.put_u32(id);
703        payload.put_u32(0);
704        put_wide(&mut payload, version, duration);
705        payload.put_u64(0);
706        payload.put_u16(0);
707        payload.put_u16(u16::from(self.info.kind == TrackKind::Audio));
708        payload.put_u16(if self.info.kind == TrackKind::Audio {
709            0x0100
710        } else {
711            0
712        });
713        payload.put_u16(0);
714        let matrix = self
715            .info
716            .video
717            .as_ref()
718            .map_or(IDENTITY, |video| display_matrix(video.orientation));
719        put_matrix(&mut payload, matrix);
720        match &self.info.video {
721            Some(video) => {
722                payload.put_u32(video.width << 16);
723                payload.put_u32(video.height << 16);
724            }
725            None => payload.put_u64(0),
726        }
727        let flags = 2 | u32::from(self.info.enabled);
728        full_box(*b"tkhd", version, flags, &payload)
729    }
730
731    /// The edit list `FFmpeg` writes: an empty edit for a positive start, then the media from
732    /// its first presented sample.
733    fn edts(&self) -> Bytes {
734        let timescale = i64::from(self.timescale);
735        let first = self.samples[0];
736        let samples_duration = self.end_pts().saturating_sub(self.start_pts());
737        let mut duration = rescale_up(samples_duration, i64::from(MOVIE_TIMESCALE), timescale);
738        let delay = rescale_down(
739            first.dts.saturating_add(first.cts),
740            i64::from(MOVIE_TIMESCALE),
741            timescale,
742        );
743        let mut start = first.cts;
744        if delay <= 0 {
745            start = -first.dts.min(0);
746            duration = duration.saturating_add(delay);
747        }
748        let version = u8::from(duration >= i64::from(i32::MAX) || delay >= i64::from(i32::MAX));
749        let mut payload = BytesMut::new();
750        payload.put_u32(1 + u32::from(delay > 0));
751        let mut entry = |segment: i64, media: i64| {
752            put_wide(&mut payload, version, segment);
753            if version == 1 {
754                payload.put_i64(media);
755            } else {
756                payload.put_i32(i32::try_from(media).unwrap_or(-1));
757            }
758            payload.put_u32(0x0001_0000);
759        };
760        if delay > 0 {
761            entry(delay, -1);
762        }
763        entry(duration, start);
764        boxed(*b"edts", &full_box(*b"elst", version, 0, &payload))
765    }
766
767    fn mdia(&self, base: u64, wide: bool, flavor: Mp4Flavor) -> Bytes {
768        let duration = if self.samples.is_empty() {
769            0
770        } else {
771            self.end_pts().saturating_sub(self.start_pts())
772        };
773        let version = u8::from(duration >= i64::from(i32::MAX));
774        let mut mdhd = BytesMut::new();
775        put_wide(&mut mdhd, version, 0);
776        put_wide(&mut mdhd, version, 0);
777        mdhd.put_u32(self.timescale);
778        put_wide(&mut mdhd, version, duration);
779        mdhd.put_u16(language_code(self.info.language.as_deref()));
780        mdhd.put_u16(0);
781        let (handler, name): (&[u8; 4], &str) = match self.info.kind {
782            TrackKind::Video => (b"vide", "VideoHandler"),
783            _ => (b"soun", "SoundHandler"),
784        };
785        let mut hdlr = BytesMut::new();
786        hdlr.put_slice(if flavor == Mp4Flavor::Mov {
787            b"mhlr"
788        } else {
789            &[0; 4]
790        });
791        hdlr.put_slice(handler);
792        hdlr.put_slice(&[0; 12]);
793        if flavor == Mp4Flavor::Mov {
794            hdlr.put_u8(u8::try_from(name.len()).unwrap_or(0));
795            hdlr.put_slice(name.as_bytes());
796        } else {
797            hdlr.put_slice(name.as_bytes());
798            hdlr.put_u8(0);
799        }
800        let mut payload = BytesMut::new();
801        payload.put_slice(&full_box(*b"mdhd", version, 0, &mdhd));
802        payload.put_slice(&full_box(*b"hdlr", 0, 0, &hdlr));
803        payload.put_slice(&self.minf(base, wide));
804        boxed(*b"mdia", &payload)
805    }
806
807    fn minf(&self, base: u64, wide: bool) -> Bytes {
808        let mut payload = BytesMut::new();
809        if self.info.kind == TrackKind::Video {
810            payload.put_slice(&full_box(*b"vmhd", 0, 1, &[0; 8]));
811        } else {
812            payload.put_slice(&full_box(*b"smhd", 0, 0, &[0; 4]));
813        }
814        let url = full_box(*b"url ", 0, 1, &[]);
815        let mut dref = BytesMut::new();
816        dref.put_u32(1);
817        dref.put_slice(&url);
818        payload.put_slice(&boxed(*b"dinf", &full_box(*b"dref", 0, 0, &dref)));
819        payload.put_slice(&self.stbl(base, wide));
820        boxed(*b"minf", &payload)
821    }
822
823    fn stbl(&self, base: u64, wide: bool) -> Bytes {
824        let mut payload = BytesMut::new();
825        let mut descriptions = BytesMut::new();
826        descriptions.put_u32(1);
827        descriptions.put_slice(&self.entry_with_rates());
828        payload.put_slice(&full_box(*b"stsd", 0, 0, &descriptions));
829        payload.put_slice(&self.stts());
830        if self.samples.iter().any(|sample| sample.cts != 0) {
831            payload.put_slice(&self.ctts());
832        }
833        if self.samples.iter().any(|sample| !sample.keyframe) {
834            let keys = self
835                .samples
836                .iter()
837                .enumerate()
838                .filter(|(_, sample)| sample.keyframe)
839                .map(|(at, _)| u32::try_from(at + 1).unwrap_or(u32::MAX))
840                .collect::<Vec<_>>();
841            let mut sync = BytesMut::new();
842            sync.put_u32(u32::try_from(keys.len()).unwrap_or(u32::MAX));
843            for key in keys {
844                sync.put_u32(key);
845            }
846            payload.put_slice(&full_box(*b"stss", 0, 0, &sync));
847        }
848        payload.put_slice(&self.stsc());
849        payload.put_slice(&self.stsz());
850        let mut offsets = BytesMut::new();
851        offsets.put_u32(u32::try_from(self.chunks.len()).unwrap_or(u32::MAX));
852        for (offset, _) in &self.chunks {
853            if wide {
854                offsets.put_u64(base + offset);
855            } else {
856                offsets.put_u32(u32::try_from(base + offset).unwrap_or(u32::MAX));
857            }
858        }
859        payload.put_slice(&full_box(
860            if wide { *b"co64" } else { *b"stco" },
861            0,
862            0,
863            &offsets,
864        ));
865        boxed(*b"stbl", &payload)
866    }
867
868    /// The sample entry; an `mp4a` entry gets its `esds` here, once bit rates are known.
869    fn entry_with_rates(&self) -> Bytes {
870        let Some(audio) = &self.info.audio else {
871            return self.entry.clone();
872        };
873        if audio.codec != AudioCodec::Aac {
874            return self.entry.clone();
875        }
876        let total: u64 = self
877            .samples
878            .iter()
879            .map(|sample| u64::from(sample.size))
880            .sum();
881        let largest = self
882            .samples
883            .iter()
884            .map(|sample| sample.size)
885            .max()
886            .unwrap_or(0);
887        let span = self
888            .end_pts()
889            .saturating_sub(self.samples.first().map_or(0, |sample| sample.dts));
890        let average = if span > 0 {
891            u32::try_from(rescale_down(
892                i64::try_from(total * 8).unwrap_or(i64::MAX),
893                i64::from(self.timescale),
894                span,
895            ))
896            .unwrap_or(u32::MAX)
897        } else {
898            0
899        };
900        let esds = esds(
901            0,
902            0x40,
903            true,
904            &audio.codec_private,
905            (largest, average, average),
906        );
907        let mut entry = BytesMut::from(&self.entry[..]);
908        entry.put_slice(&esds);
909        let size = u32::try_from(entry.len()).unwrap_or(u32::MAX);
910        entry[..4].copy_from_slice(&size.to_be_bytes());
911        entry.freeze()
912    }
913
914    fn stts(&self) -> Bytes {
915        let mut entries: Vec<(u32, u32)> = Vec::new();
916        for (at, sample) in self.samples.iter().enumerate() {
917            let delta = match self.samples.get(at + 1) {
918                Some(next) => next.dts.saturating_sub(sample.dts),
919                None => sample.duration,
920            };
921            let delta = u32::try_from(delta.max(0)).unwrap_or(u32::MAX);
922            match entries.last_mut() {
923                Some((count, last)) if *last == delta => *count += 1,
924                _ => entries.push((1, delta)),
925            }
926        }
927        let mut payload = BytesMut::new();
928        payload.put_u32(u32::try_from(entries.len()).unwrap_or(u32::MAX));
929        for (count, delta) in entries {
930            payload.put_u32(count);
931            payload.put_u32(delta);
932        }
933        full_box(*b"stts", 0, 0, &payload)
934    }
935
936    fn ctts(&self) -> Bytes {
937        let mut entries: Vec<(u32, i64)> = Vec::new();
938        for sample in &self.samples {
939            match entries.last_mut() {
940                Some((count, offset)) if *offset == sample.cts => *count += 1,
941                _ => entries.push((1, sample.cts)),
942            }
943        }
944        let negative = entries.iter().any(|(_, offset)| *offset < 0);
945        let mut payload = BytesMut::new();
946        payload.put_u32(u32::try_from(entries.len()).unwrap_or(u32::MAX));
947        for (count, offset) in entries {
948            payload.put_u32(count);
949            payload.put_i32(i32::try_from(offset).unwrap_or(i32::MAX));
950        }
951        full_box(*b"ctts", u8::from(negative), 0, &payload)
952    }
953
954    fn stsc(&self) -> Bytes {
955        let mut entries: Vec<(u32, u32)> = Vec::new();
956        for (at, (_, count)) in self.chunks.iter().enumerate() {
957            if entries.last().is_none_or(|(_, last)| last != count) {
958                entries.push((u32::try_from(at + 1).unwrap_or(u32::MAX), *count));
959            }
960        }
961        let mut payload = BytesMut::new();
962        payload.put_u32(u32::try_from(entries.len()).unwrap_or(u32::MAX));
963        for (first, count) in entries {
964            payload.put_u32(first);
965            payload.put_u32(count);
966            payload.put_u32(1);
967        }
968        full_box(*b"stsc", 0, 0, &payload)
969    }
970
971    fn stsz(&self) -> Bytes {
972        let mut payload = BytesMut::new();
973        let first = self.samples.first().map_or(0, |sample| sample.size);
974        let constant =
975            !self.samples.is_empty() && self.samples.iter().all(|sample| sample.size == first);
976        payload.put_u32(if constant { first } else { 0 });
977        payload.put_u32(u32::try_from(self.samples.len()).unwrap_or(u32::MAX));
978        if !constant {
979            for sample in &self.samples {
980                payload.put_u32(sample.size);
981            }
982        }
983        full_box(*b"stsz", 0, 0, &payload)
984    }
985}
986
987impl ContainerWriter for Mp4Writer {
988    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError> {
989        if self.started {
990            return Err(MuxError::Invalid(
991                "tracks are added before the first packet".into(),
992            ));
993        }
994        if track.timescale == 0 {
995            return Err(MuxError::Invalid("a track needs a timescale".into()));
996        }
997        let (entry, timescale, nominal) = match (track.kind, &track.video, &track.audio) {
998            (TrackKind::Video, Some(video), _) => {
999                let mut timescale = track.timescale;
1000                while timescale < 10_000 {
1001                    timescale *= 2;
1002                }
1003                let nominal = video.frame_rate.and_then(|rate| {
1004                    let ticks = u64::from(timescale) * u64::from(rate.denominator());
1005                    (ticks % u64::from(rate.numerator()) == 0)
1006                        .then(|| i64::try_from(ticks / u64::from(rate.numerator())).ok())
1007                        .flatten()
1008                });
1009                (video_entry(video, self.flavor)?, timescale, nominal)
1010            }
1011            (TrackKind::Audio, _, Some(audio)) => {
1012                let timescale = if audio.sample_rate > 0 {
1013                    audio.sample_rate
1014                } else {
1015                    track.timescale
1016                };
1017                (audio_entry(audio, self.flavor)?, timescale, None)
1018            }
1019            _ => {
1020                return Err(MuxError::Unsupported(
1021                    "only video and audio tracks are written to MP4".into(),
1022                ));
1023            }
1024        };
1025        if self.tracks.len() >= u16::MAX as usize {
1026            return Err(MuxError::Unsupported("too many tracks".into()));
1027        }
1028        self.tracks.push(Track {
1029            info: track.clone(),
1030            entry,
1031            in_timescale: track.timescale,
1032            timescale,
1033            nominal_duration: nominal,
1034            pending: VecDeque::new(),
1035            last_dts: None,
1036            samples: Vec::new(),
1037            chunks: Vec::new(),
1038        });
1039        Ok(TrackId(
1040            u32::try_from(self.tracks.len()).unwrap_or(u32::MAX),
1041        ))
1042    }
1043
1044    fn write(&mut self, packet: Packet) -> Result<(), MuxError> {
1045        let position = usize::try_from(packet.track.0)
1046            .ok()
1047            .and_then(|id| id.checked_sub(1))
1048            .filter(|position| *position < self.tracks.len())
1049            .ok_or_else(|| MuxError::Invalid(format!("no track {}", packet.track.0)))?;
1050        if !self.started {
1051            self.start()?;
1052        }
1053        let track = &mut self.tracks[position];
1054        let (input, output) = (i64::from(track.in_timescale), i64::from(track.timescale));
1055        let dts = rescale(packet.dts, output, input);
1056        let pts = rescale(packet.pts, output, input);
1057        if track.last_dts.is_some_and(|last| dts <= last) {
1058            return Err(MuxError::Invalid(format!(
1059                "track {} decode times do not increase at {}",
1060                packet.track.0, packet.dts
1061            )));
1062        }
1063        let mut duration = rescale(packet.duration, output, input);
1064        if duration <= 0 {
1065            duration = track.nominal_duration.unwrap_or_else(|| {
1066                track
1067                    .samples
1068                    .last()
1069                    .or_else(|| {
1070                        track
1071                            .pending
1072                            .back()
1073                            .and_then(|chunk| chunk.samples.last().map(|(sample, _)| sample))
1074                    })
1075                    .map_or(0, |previous| dts.saturating_sub(previous.dts).max(0))
1076            });
1077        }
1078        let size = u32::try_from(packet.data.len())
1079            .map_err(|_| MuxError::Unsupported("a packet is larger than 4 GiB".into()))?;
1080        let sample = Sample {
1081            size,
1082            dts,
1083            cts: pts.saturating_sub(dts),
1084            duration,
1085            keyframe: packet.keyframe,
1086        };
1087        let half_second = output / 2;
1088        match track.pending.back_mut() {
1089            Some(chunk) if dts.saturating_sub(chunk.start) < half_second.max(1) => {
1090                chunk.samples.push((sample, packet.data.clone()));
1091            }
1092            _ => track.pending.push_back(Chunk {
1093                start: dts,
1094                samples: vec![(sample, packet.data.clone())],
1095            }),
1096        }
1097        track.last_dts = Some(dts);
1098        self.buffered += packet.data.len();
1099        self.flush(false)
1100    }
1101
1102    fn finish(mut self: Box<Self>) -> Result<(), MuxError> {
1103        self.finish_inner()
1104    }
1105}