Skip to main content

alpha2_container/matroska/
write.rs

1//! The Matroska and `WebM` muxer. Layout, clusters, cues, codec delay and block durations follow
2//! `FFmpeg`'s Matroska muxer writing a seekable file, so `FFmpeg` reads the output as it reads
3//! its own stream copy; output bytes depend only on the tracks and packets.
4
5use std::collections::VecDeque;
6use std::io::{Seek, SeekFrom, Write};
7
8use alpha2_media::{ColorMatrix, ColorPrimaries, ColorRange, Rotation, TransferFunction};
9use bytes::{BufMut, BytesMut};
10
11use super::describe::{reduce, rescale, xiph_headers};
12use super::ebml::{
13    id, put_float, put_id, put_master, put_sint, put_size, put_uint, put_void, size_len,
14};
15use crate::{
16    AudioCodec, AudioTrack, ContainerWriter, MuxError, Packet, PcmFormat, TrackId, TrackInfo,
17    TrackKind, VideoCodec, VideoTrack,
18};
19
20/// Which flavor of Matroska to write.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum MatroskaFlavor {
23    /// Matroska (`.mkv`, `.mka`), with CRC-32 elements.
24    Matroska,
25    /// `WebM`: VP8, VP9 or AV1 video and Opus or Vorbis audio only.
26    WebM,
27}
28
29/// The space reserved for the `SeekHead`: seven entries, its header, a CRC-32 and room for a
30/// Void after it.
31const SEEK_HEAD_SPACE: usize = 7 * 21 + 14;
32/// A new cluster starts past these many bytes or milliseconds, or at a video keyframe past
33/// `KEYFRAME_CLUSTER_SIZE` bytes.
34const CLUSTER_SIZE: usize = 5 << 20;
35const CLUSTER_TIME: i64 = 5000;
36const KEYFRAME_CLUSTER_SIZE: usize = 4 << 10;
37/// Packets of one track are written ahead of a silent track once they span this many
38/// microseconds (`FFmpeg`'s `max_interleave_delta`).
39const MAX_INTERLEAVE_DELTA: i128 = 10_000_000;
40/// The Opus `SeekPreRoll` `FFmpeg` writes, in nanoseconds.
41const OPUS_SEEK_PRE_ROLL: u64 = 80_000_000;
42
43trait Sink: Write + Seek + Send {}
44
45impl<T: Write + Seek + Send> Sink for T {}
46
47/// Writes Matroska or `WebM` files: the header, clusters of blocks with millisecond timestamps,
48/// cues at the end, then the `SeekHead` and duration filled in by seeking back.
49pub struct MatroskaWriter {
50    sink: Box<dyn Sink>,
51    flavor: MatroskaFlavor,
52    tracks: Vec<Track>,
53    started: bool,
54    /// File positions: the Segment's payload (where the `SeekHead` space starts), the `Info` and
55    /// `Tracks` elements, and the end of what is written.
56    segment: u64,
57    info_at: u64,
58    tracks_at: u64,
59    written: u64,
60    /// Milliseconds every timestamp moves by so none is negative, once known.
61    shift: Option<i64>,
62    cluster: Option<Cluster>,
63    /// An audio packet written after the next packet decides where clusters start.
64    held_audio: Option<Ready>,
65    cues: Vec<Cue>,
66    /// The latest block end, in milliseconds.
67    duration: i64,
68}
69
70impl std::fmt::Debug for MatroskaWriter {
71    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        formatter
73            .debug_struct("MatroskaWriter")
74            .field("flavor", &self.flavor)
75            .field("tracks", &self.tracks.len())
76            .finish_non_exhaustive()
77    }
78}
79
80struct Track {
81    info: TrackInfo,
82    number: u64,
83    entry: BytesMut,
84    /// Milliseconds the codec delay moves block timestamps by.
85    ts_offset: i64,
86    /// The `DefaultDuration` rounded down and up to milliseconds; 0 without one.
87    default_low: i64,
88    default_high: i64,
89    sample_rate: u32,
90    queue: VecDeque<Packet>,
91    last_dts: Option<i64>,
92    last_ts: i64,
93    has_cue: bool,
94}
95
96/// A packet in milliseconds, ready for a block.
97struct Ready {
98    track: usize,
99    ts: i64,
100    duration: i64,
101    keyframe: bool,
102    packet: Packet,
103}
104
105struct Cluster {
106    /// Where the Cluster element starts in the file.
107    at: u64,
108    timestamp: i64,
109    /// The payload so far, after six bytes held for the CRC-32 in Matroska.
110    payload: BytesMut,
111}
112
113#[derive(Clone, Copy)]
114struct Cue {
115    ts: i64,
116    track: usize,
117    /// The cluster's position in the Segment, and the block's in the cluster's payload.
118    cluster: u64,
119    relative: u64,
120}
121
122/// The milliseconds of `packet` after its track's codec delay, before the file's shift; `None`
123/// when they do not fit.
124fn unshifted_ms(track: &Track, packet: &Packet) -> Option<i64> {
125    rescale(packet.pts, 1000, i64::from(track.info.timescale)).checked_add(track.ts_offset)
126}
127
128/// CRC-32 (IEEE 802.3, reflected), as Matroska's `CRC-32` element holds it.
129fn crc32(bytes: &[u8]) -> u32 {
130    const TABLE: [u32; 256] = {
131        let mut table = [0_u32; 256];
132        let mut index: u32 = 0;
133        while index < 256 {
134            let mut value = index;
135            let mut bit = 0;
136            while bit < 8 {
137                value = if value & 1 != 0 {
138                    0xedb8_8320 ^ (value >> 1)
139                } else {
140                    value >> 1
141                };
142                bit += 1;
143            }
144            table[index as usize] = value;
145            index += 1;
146        }
147        table
148    };
149    !bytes.iter().fold(u32::MAX, |crc, byte| {
150        TABLE[usize::from(crc.to_le_bytes()[0] ^ byte)] ^ (crc >> 8)
151    })
152}
153
154impl MatroskaWriter {
155    /// A writer into `file`.
156    #[must_use]
157    pub fn create(file: std::fs::File, flavor: MatroskaFlavor) -> Self {
158        Self::new(file, flavor)
159    }
160
161    /// A writer into any writable and seekable `sink`, starting at its offset 0.
162    pub fn new<W: Write + Seek + Send + 'static>(sink: W, flavor: MatroskaFlavor) -> Self {
163        Self {
164            sink: Box::new(sink),
165            flavor,
166            tracks: Vec::new(),
167            started: false,
168            segment: 0,
169            info_at: 0,
170            tracks_at: 0,
171            written: 0,
172            shift: None,
173            cluster: None,
174            held_audio: None,
175            cues: Vec::new(),
176            duration: 0,
177        }
178    }
179
180    fn webm(&self) -> bool {
181        self.flavor == MatroskaFlavor::WebM
182    }
183
184    /// A level-1 element, with a CRC-32 of its payload first in Matroska.
185    fn level1(&self, element: u32, payload: &[u8]) -> BytesMut {
186        let mut body = BytesMut::with_capacity(payload.len() + 6);
187        if !self.webm() {
188            put_master(&mut body, id::CRC32, &crc32(payload).to_le_bytes());
189        }
190        body.put_slice(payload);
191        let mut out = BytesMut::with_capacity(body.len() + 12);
192        put_master(&mut out, element, &body);
193        out
194    }
195
196    fn emit(&mut self, bytes: &[u8]) -> Result<(), MuxError> {
197        self.sink.write_all(bytes)?;
198        self.written += bytes.len() as u64;
199        Ok(())
200    }
201
202    fn info(&self) -> BytesMut {
203        let mut payload = BytesMut::new();
204        put_uint(&mut payload, id::TIMESTAMP_SCALE, 1_000_000);
205        put_master(&mut payload, id::MUXING_APP, b"alpha2");
206        put_master(&mut payload, id::WRITING_APP, b"alpha2");
207        #[allow(clippy::cast_precision_loss)]
208        put_float(&mut payload, id::DURATION, self.duration as f64);
209        self.level1(id::INFO, &payload)
210    }
211
212    fn start(&mut self) -> Result<(), MuxError> {
213        let opus = self.tracks.iter().any(|track| {
214            track.info.audio.as_ref().map(|audio| audio.codec) == Some(AudioCodec::Opus)
215        });
216        let version = if !self.webm() || opus { 4 } else { 2 };
217        let mut header = BytesMut::new();
218        put_uint(&mut header, id::EBML_VERSION, 1);
219        put_uint(&mut header, id::EBML_READ_VERSION, 1);
220        put_uint(&mut header, id::EBML_MAX_ID_LENGTH, 4);
221        put_uint(&mut header, id::EBML_MAX_SIZE_LENGTH, 8);
222        let doc_type: &[u8] = if self.webm() { b"webm" } else { b"matroska" };
223        put_master(&mut header, id::DOC_TYPE, doc_type);
224        put_uint(&mut header, id::DOC_TYPE_VERSION, version);
225        put_uint(&mut header, id::DOC_TYPE_READ_VERSION, 2);
226        let mut out = BytesMut::new();
227        put_master(&mut out, id::EBML, &header);
228        put_id(&mut out, id::SEGMENT);
229        out.put_slice(&[0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
230        self.sink.seek(SeekFrom::Start(0))?;
231        self.written = 0;
232        self.emit(&out)?;
233        self.segment = self.written;
234        let mut reserved = BytesMut::new();
235        put_void(&mut reserved, SEEK_HEAD_SPACE);
236        self.emit(&reserved)?;
237        self.info_at = self.written;
238        let info = self.info();
239        self.emit(&info)?;
240        self.tracks_at = self.written;
241        let mut entries = BytesMut::new();
242        for track in &self.tracks {
243            entries.put_slice(&track.entry);
244        }
245        let tracks = self.level1(id::TRACKS, &entries);
246        self.emit(&tracks)?;
247        self.started = true;
248        Ok(())
249    }
250
251    /// Writes queued packets in decode-time order across tracks while every track has one
252    /// queued, or one track runs too far ahead; with `all`, every queued packet.
253    fn pump(&mut self, all: bool) -> Result<(), MuxError> {
254        loop {
255            let mut earliest: Option<usize> = None;
256            for (index, track) in self.tracks.iter().enumerate() {
257                let Some(head) = track.queue.front() else {
258                    continue;
259                };
260                let earlier = earliest.is_none_or(|best| {
261                    let best = &self.tracks[best];
262                    let other = best.queue.front().map_or(0, |packet| packet.dts);
263                    i128::from(head.dts) * i128::from(best.info.timescale)
264                        < i128::from(other) * i128::from(track.info.timescale)
265                });
266                if earlier {
267                    earliest = Some(index);
268                }
269            }
270            let Some(index) = earliest else {
271                return Ok(());
272            };
273            if !all && self.tracks.iter().any(|track| track.queue.is_empty()) {
274                let micros = |track: &Track, dts: i64| {
275                    i128::from(dts) * 1_000_000 / i128::from(track.info.timescale.max(1))
276                };
277                let head = &self.tracks[index];
278                let top = micros(head, head.queue.front().map_or(0, |packet| packet.dts));
279                let ahead = self
280                    .tracks
281                    .iter()
282                    .filter_map(|track| track.queue.back().map(|last| micros(track, last.dts)))
283                    .map(|last| last - top)
284                    .max()
285                    .unwrap_or(0);
286                if ahead <= MAX_INTERLEAVE_DELTA {
287                    return Ok(());
288                }
289            }
290            let packet = self.tracks[index].queue.pop_front().expect("queued packet");
291            self.mux(index, packet)?;
292        }
293    }
294
295    /// Milliseconds every timestamp moves by: enough that the earliest of `first` and the queued
296    /// packets is not negative after its codec delay (`FFmpeg`'s `avoid_negative_ts`). `None`
297    /// when a time does not fit.
298    fn shift_for(&self, track: usize, first: &Packet) -> Option<i64> {
299        let lowest = self
300            .tracks
301            .iter()
302            .flat_map(|track| {
303                track
304                    .queue
305                    .iter()
306                    .map(move |packet| unshifted_ms(track, packet))
307            })
308            .chain(std::iter::once(unshifted_ms(&self.tracks[track], first)))
309            .try_fold(0, |lowest: i64, ms| Some(lowest.min(ms?)))?;
310        lowest.checked_neg()
311    }
312
313    /// Hands one packet, in interleaved order, to the cluster logic.
314    fn mux(&mut self, index: usize, packet: Packet) -> Result<(), MuxError> {
315        let unfit = || {
316            MuxError::Invalid(format!(
317                "track {} has a packet at {} that does not fit a Matroska timestamp",
318                packet.track.0, packet.pts
319            ))
320        };
321        let shift = if let Some(shift) = self.shift {
322            shift
323        } else {
324            let shift = self.shift_for(index, &packet).ok_or_else(unfit)?;
325            self.shift = Some(shift);
326            shift
327        };
328        let track = &self.tracks[index];
329        let timescale = i64::from(track.info.timescale);
330        let duration = rescale(packet.duration, 1000, timescale).max(0);
331        let ts = unshifted_ms(track, &packet)
332            .and_then(|ms| ms.checked_add(shift))
333            .filter(|ts| ts.checked_add(duration).is_some())
334            .ok_or_else(unfit)?;
335        let video = track.info.kind == TrackKind::Video;
336        let audio = track.info.kind == TrackKind::Audio;
337        let keyframe = packet.keyframe;
338        if let Some(cluster) = &self.cluster {
339            let size = cluster.payload.len();
340            if size > CLUSTER_SIZE
341                || ts.saturating_sub(cluster.timestamp) > CLUSTER_TIME
342                || (video && keyframe && size > KEYFRAME_CLUSTER_SIZE)
343            {
344                self.end_cluster()?;
345            }
346        }
347        if let Some(held) = self.held_audio.take() {
348            self.write_block(held)?;
349        }
350        let ready = Ready {
351            track: index,
352            ts,
353            duration,
354            keyframe,
355            packet,
356        };
357        if audio {
358            self.held_audio = Some(ready);
359            Ok(())
360        } else {
361            self.write_block(ready)
362        }
363    }
364
365    fn end_cluster(&mut self) -> Result<(), MuxError> {
366        let Some(cluster) = self.cluster.take() else {
367            return Ok(());
368        };
369        if !self
370            .tracks
371            .iter()
372            .any(|track| track.info.kind == TrackKind::Video)
373        {
374            for track in &mut self.tracks {
375                track.has_cue = false;
376            }
377        }
378        let skip = if self.webm() { 0 } else { 6 };
379        let element = self.level1(id::CLUSTER, &cluster.payload[skip..]);
380        self.emit(&element)
381    }
382
383    /// Writes a packet as a `SimpleBlock`, or a `BlockGroup` when it needs a duration or discard
384    /// padding.
385    fn write_block(&mut self, ready: Ready) -> Result<(), MuxError> {
386        let Ready {
387            track: index,
388            ts,
389            duration,
390            keyframe,
391            packet,
392        } = ready;
393        if let Some(cluster) = &self.cluster
394            && i16::try_from(ts.saturating_sub(cluster.timestamp)).is_err()
395        {
396            self.end_cluster()?;
397        }
398        if self.cluster.is_none() {
399            let mut payload = BytesMut::new();
400            if !self.webm() {
401                payload.put_bytes(0, 6);
402            }
403            let timestamp = ts.max(0);
404            put_uint(
405                &mut payload,
406                id::CLUSTER_TIMESTAMP,
407                timestamp.unsigned_abs(),
408            );
409            self.cluster = Some(Cluster {
410                at: self.written,
411                timestamp,
412                payload,
413            });
414        }
415        let segment = self.segment;
416        let video = self
417            .tracks
418            .iter()
419            .any(|track| track.info.kind == TrackKind::Video);
420        let track = &mut self.tracks[index];
421        let cluster = self.cluster.as_mut().expect("open cluster");
422        let relative = cluster.payload.len() as u64;
423        let mut block = BytesMut::with_capacity(packet.data.len() + 12);
424        put_size(&mut block, track.number, size_len(track.number));
425        let offset = i16::try_from(ts.saturating_sub(cluster.timestamp)).unwrap_or(0);
426        block.put_i16(offset);
427        let mut extra = BytesMut::new();
428        if duration > 0
429            && track.default_high > 0
430            && duration != track.default_high
431            && duration != track.default_low
432        {
433            put_uint(&mut extra, id::BLOCK_DURATION, duration.unsigned_abs());
434        }
435        if packet.discard.1 > 0 {
436            let padding = rescale(
437                i64::from(packet.discard.1),
438                1_000_000_000,
439                i64::from(track.sample_rate.max(1)),
440            );
441            put_sint(&mut extra, id::DISCARD_PADDING, padding);
442        }
443        if extra.is_empty() {
444            block.put_u8(if keyframe { 0x80 } else { 0 });
445            block.put_slice(&packet.data);
446            put_master(&mut cluster.payload, id::SIMPLE_BLOCK, &block);
447        } else {
448            block.put_u8(0);
449            block.put_slice(&packet.data);
450            let mut group = BytesMut::with_capacity(block.len() + extra.len() + 16);
451            put_master(&mut group, id::BLOCK, &block);
452            group.put_slice(&extra);
453            if !keyframe {
454                put_sint(
455                    &mut group,
456                    id::REFERENCE_BLOCK,
457                    track.last_ts.saturating_sub(ts),
458                );
459            }
460            put_master(&mut cluster.payload, id::BLOCK_GROUP, &group);
461        }
462        let cued = track.info.kind == TrackKind::Video || (!video && !track.has_cue);
463        if keyframe && cued {
464            if ts >= 0 {
465                self.cues.push(Cue {
466                    ts,
467                    track: index,
468                    cluster: cluster.at - segment,
469                    relative,
470                });
471            }
472            track.has_cue = true;
473        }
474        track.last_ts = ts;
475        self.duration = self.duration.max(ts.saturating_add(duration));
476        Ok(())
477    }
478
479    fn cues_element(&self) -> BytesMut {
480        let mut cues = self.cues.clone();
481        cues.sort_by_key(|cue| cue.ts);
482        let mut payload = BytesMut::new();
483        let mut at = 0;
484        while at < cues.len() {
485            let ts = cues[at].ts;
486            let mut point = BytesMut::new();
487            put_uint(&mut point, id::CUE_TIME, ts.unsigned_abs());
488            let mut seen = Vec::new();
489            while at < cues.len() && cues[at].ts == ts {
490                let cue = cues[at];
491                at += 1;
492                if seen.contains(&cue.track) {
493                    continue;
494                }
495                seen.push(cue.track);
496                let mut position = BytesMut::new();
497                put_uint(&mut position, id::CUE_TRACK, self.tracks[cue.track].number);
498                put_uint(&mut position, id::CUE_CLUSTER_POSITION, cue.cluster);
499                put_uint(&mut position, id::CUE_RELATIVE_POSITION, cue.relative);
500                put_master(&mut point, id::CUE_TRACK_POSITIONS, &position);
501            }
502            put_master(&mut payload, id::CUE_POINT, &point);
503        }
504        self.level1(id::CUES, &payload)
505    }
506
507    fn finish_inner(&mut self) -> Result<(), MuxError> {
508        if !self.started {
509            self.start()?;
510        }
511        self.pump(true)?;
512        if let Some(held) = self.held_audio.take() {
513            self.write_block(held)?;
514        }
515        self.end_cluster()?;
516        let mut seeks = vec![
517            (id::INFO, self.info_at - self.segment),
518            (id::TRACKS, self.tracks_at - self.segment),
519        ];
520        if !self.cues.is_empty() {
521            seeks.push((id::CUES, self.written - self.segment));
522            let cues = self.cues_element();
523            self.emit(&cues)?;
524        }
525        let end = self.written;
526        self.sink.seek(SeekFrom::Start(self.segment - 8))?;
527        let mut size = BytesMut::new();
528        put_size(&mut size, end - self.segment, 8);
529        self.sink.write_all(&size)?;
530        let mut entries = BytesMut::new();
531        for (element, position) in seeks {
532            let mut seek = BytesMut::new();
533            let mut target = BytesMut::new();
534            put_id(&mut target, element);
535            put_master(&mut seek, id::SEEK_ID, &target);
536            put_uint(&mut seek, id::SEEK_POSITION, position);
537            put_master(&mut entries, id::SEEK, &seek);
538        }
539        let mut seek_head = self.level1(id::SEEK_HEAD, &entries);
540        let filler = SEEK_HEAD_SPACE - seek_head.len();
541        put_void(&mut seek_head, filler);
542        self.sink.seek(SeekFrom::Start(self.segment))?;
543        self.sink.write_all(&seek_head)?;
544        let info = self.info();
545        self.sink.seek(SeekFrom::Start(self.info_at))?;
546        self.sink.write_all(&info)?;
547        self.sink.seek(SeekFrom::Start(end))?;
548        self.sink.flush()?;
549        Ok(())
550    }
551}
552
553/// The H.273 codes of `color`, in the order `FFmpeg` writes them.
554fn colour(color: alpha2_media::ColorMetadata) -> BytesMut {
555    let transfer = match color.transfer {
556        TransferFunction::Bt709 => 1,
557        TransferFunction::Srgb => 13,
558        TransferFunction::Pq => 16,
559        TransferFunction::Hlg => 18,
560    };
561    let matrix = match color.matrix {
562        ColorMatrix::Rgb => 0,
563        ColorMatrix::Bt709 => 1,
564        ColorMatrix::Bt601 => 6,
565        ColorMatrix::Bt2020Ncl => 9,
566    };
567    let primaries = match color.primaries {
568        ColorPrimaries::Bt709 => 1,
569        ColorPrimaries::Bt601 => 6,
570        ColorPrimaries::Bt2020 => 9,
571    };
572    let range = if color.range == ColorRange::Full {
573        2
574    } else {
575        1
576    };
577    let mut payload = BytesMut::new();
578    put_uint(&mut payload, id::TRANSFER_CHARACTERISTICS, transfer);
579    put_uint(&mut payload, id::MATRIX_COEFFICIENTS, matrix);
580    put_uint(&mut payload, id::PRIMARIES, primaries);
581    put_uint(&mut payload, id::RANGE, range);
582    payload
583}
584
585/// The projection pose `FFmpeg` derives from the display matrix of `orientation`: a yaw of 180
586/// for a mirror and the counter-clockwise roll.
587fn pose(orientation: alpha2_media::Orientation) -> BytesMut {
588    let matrix = crate::mp4::write::display_matrix(orientation);
589    let mut payload = BytesMut::new();
590    if orientation.rotation == Rotation::Deg0 && !orientation.mirror {
591        return payload;
592    }
593    let yaw = if orientation.mirror { 180.0 } else { 0.0 };
594    let roll = f64::from(matrix[3])
595        .atan2(f64::from(matrix[4]))
596        .to_degrees();
597    if orientation.mirror {
598        put_float(&mut payload, id::PROJECTION_POSE_YAW, yaw);
599    }
600    if roll != 0.0 {
601        put_float(&mut payload, id::PROJECTION_POSE_ROLL, roll);
602    }
603    payload
604}
605
606/// The codec-specific parts of a `TrackEntry`.
607struct Parts {
608    codec_id: &'static str,
609    /// `CodecDelay` and `SeekPreRoll`, which `FFmpeg` writes before the track type.
610    delay: BytesMut,
611    kind: u64,
612    /// `DefaultDuration` in nanoseconds, from a frame or sample rate.
613    default_duration: Option<(u64, u64)>,
614    fields: BytesMut,
615    private: BytesMut,
616}
617
618fn video_parts(video: &VideoTrack, webm: bool) -> Result<Parts, MuxError> {
619    let mut private = BytesMut::new();
620    let codec_id = match video.codec {
621        VideoCodec::Vp8 => "V_VP8",
622        // Matroska's VP9 private data is a feature list, not the `vpcC` body; none is needed.
623        VideoCodec::Vp9 => "V_VP9",
624        VideoCodec::Av1 => {
625            private.put_slice(&video.codec_private);
626            "V_AV1"
627        }
628        _ if webm => {
629            return Err(MuxError::Unsupported(format!(
630                "{:?} video is not written to WebM",
631                video.codec
632            )));
633        }
634        VideoCodec::H264 => {
635            private.put_slice(&video.codec_private);
636            "V_MPEG4/ISO/AVC"
637        }
638        VideoCodec::Hevc => {
639            private.put_slice(&video.codec_private);
640            "V_MPEGH/ISO/HEVC"
641        }
642        VideoCodec::Mpeg4Part2 => {
643            private.put_slice(&video.codec_private);
644            "V_MPEG4/ISO/ASP"
645        }
646        VideoCodec::ProRes(code) => {
647            private.put_slice(&code.0);
648            "V_PRORES"
649        }
650        VideoCodec::Other(code) => {
651            return Err(MuxError::Unsupported(format!(
652                "{code} video is not written to Matroska"
653            )));
654        }
655    };
656    let mut fields = BytesMut::new();
657    put_uint(&mut fields, id::PIXEL_WIDTH, u64::from(video.width));
658    put_uint(&mut fields, id::PIXEL_HEIGHT, u64::from(video.height));
659    if video.alpha {
660        put_uint(&mut fields, id::ALPHA_MODE, 1);
661    }
662    match video.sample_aspect_ratio {
663        Some(ratio) if ratio.num != ratio.den => {
664            let (width, height) = (u64::from(video.width), u64::from(video.height));
665            if webm {
666                let display = rescale(
667                    i64::from(video.width),
668                    i64::from(ratio.num),
669                    i64::from(ratio.den),
670                );
671                put_uint(&mut fields, id::DISPLAY_WIDTH, display.unsigned_abs());
672                put_uint(&mut fields, id::DISPLAY_HEIGHT, height);
673            } else {
674                let (num, den) = reduce(
675                    width * u64::from(ratio.num),
676                    height * u64::from(ratio.den),
677                    1 << 20,
678                );
679                put_uint(&mut fields, id::DISPLAY_WIDTH, num);
680                put_uint(&mut fields, id::DISPLAY_HEIGHT, den);
681                put_uint(&mut fields, id::DISPLAY_UNIT, 3);
682            }
683        }
684        None if !webm => put_uint(&mut fields, id::DISPLAY_UNIT, 4),
685        _ => {}
686    }
687    if let Some(color) = video.color {
688        put_master(&mut fields, id::COLOUR, &colour(color));
689    }
690    let pose = pose(video.orientation);
691    if !pose.is_empty() {
692        put_master(&mut fields, id::PROJECTION, &pose);
693    }
694    let mut out = BytesMut::new();
695    put_master(&mut out, id::VIDEO, &fields);
696    Ok(Parts {
697        codec_id,
698        delay: BytesMut::new(),
699        kind: 1,
700        default_duration: video
701            .frame_rate
702            .map(|rate| (u64::from(rate.denominator()), u64::from(rate.numerator()))),
703        fields: out,
704        private,
705    })
706}
707
708/// The core and extension sample rates of an `AudioSpecificConfig`; the second is 0 without SBR.
709fn aac_rates(config: &[u8]) -> Option<(u32, u32)> {
710    const RATES: [u32; 13] = [
711        96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025,
712        8_000, 7_350,
713    ];
714    let mut bits = crate::mp4::nal::Bits::new(config);
715    let mut object_type = bits.read(5)?;
716    if object_type == 31 {
717        object_type = 32 + bits.read(6)?;
718    }
719    let rate_of = |bits: &mut crate::mp4::nal::Bits<'_>| -> Option<u32> {
720        let index = bits.read(4)?;
721        if index == 15 {
722            bits.read(24)
723        } else {
724            RATES.get(index as usize).copied()
725        }
726    };
727    let core = rate_of(&mut bits)?;
728    bits.read(4)?;
729    let extension = if object_type == 5 || object_type == 29 {
730        rate_of(&mut bits)?
731    } else {
732        0
733    };
734    Some((core, extension))
735}
736
737fn audio_parts(audio: &AudioTrack, webm: bool) -> Result<Parts, MuxError> {
738    let mut private = BytesMut::new();
739    let mut sample_rate = audio.sample_rate;
740    let mut output_rate = 0;
741    let mut bit_depth = audio.bits_per_sample.map(u64::from);
742    let mut frame_samples = None;
743    let codec_id = match audio.codec {
744        AudioCodec::Opus => {
745            if audio.codec_private.len() < 19 || !audio.codec_private.starts_with(b"OpusHead") {
746                return Err(MuxError::Unsupported("Opus without an OpusHead".into()));
747            }
748            private.put_slice(&audio.codec_private);
749            "A_OPUS"
750        }
751        AudioCodec::Vorbis => {
752            if xiph_headers(&audio.codec_private).is_none_or(|headers| headers.len() != 3) {
753                return Err(MuxError::Unsupported(
754                    "Vorbis without its three headers".into(),
755                ));
756            }
757            private.put_slice(&audio.codec_private);
758            "A_VORBIS"
759        }
760        _ if webm => {
761            return Err(MuxError::Unsupported(format!(
762                "{:?} audio is not written to WebM",
763                audio.codec
764            )));
765        }
766        AudioCodec::Aac => {
767            if let Some((core, extension)) = aac_rates(&audio.codec_private) {
768                sample_rate = core;
769                output_rate = extension;
770            }
771            private.put_slice(&audio.codec_private);
772            "A_AAC"
773        }
774        AudioCodec::Mp3 => "A_MPEG/L3",
775        AudioCodec::Flac => {
776            private.put_slice(&audio.codec_private);
777            "A_FLAC"
778        }
779        AudioCodec::Alac => {
780            private.put_slice(&audio.codec_private);
781            "A_ALAC"
782        }
783        AudioCodec::Ac3 => {
784            frame_samples = Some(1536);
785            "A_AC3"
786        }
787        AudioCodec::Eac3 => "A_EAC3",
788        AudioCodec::Dts => "A_DTS",
789        AudioCodec::Pcm(format) => {
790            bit_depth = Some(u64::from(format.bits));
791            pcm_codec(format)?
792        }
793        AudioCodec::Other(code) => {
794            return Err(MuxError::Unsupported(format!(
795                "{code} audio is not written to Matroska"
796            )));
797        }
798    };
799    if sample_rate == 0 {
800        return Err(MuxError::Invalid(
801            "an audio track needs a sample rate".into(),
802        ));
803    }
804    let mut fields = BytesMut::new();
805    put_uint(&mut fields, id::CHANNELS, u64::from(audio.channels));
806    put_float(&mut fields, id::SAMPLING_FREQUENCY, f64::from(sample_rate));
807    if output_rate > 0 {
808        put_float(
809            &mut fields,
810            id::OUTPUT_SAMPLING_FREQUENCY,
811            f64::from(output_rate),
812        );
813    }
814    if let Some(bits) = bit_depth {
815        put_uint(&mut fields, id::BIT_DEPTH, bits);
816    }
817    let mut out = BytesMut::new();
818    put_master(&mut out, id::AUDIO, &fields);
819    Ok(Parts {
820        codec_id,
821        delay: delay_elements(audio),
822        kind: 2,
823        default_duration: frame_samples.map(|samples| (samples, u64::from(audio.sample_rate))),
824        fields: out,
825        private,
826    })
827}
828
829/// `CodecDelay` for the priming, and the Opus `SeekPreRoll`.
830fn delay_elements(audio: &AudioTrack) -> BytesMut {
831    let mut delay = BytesMut::new();
832    if audio.priming > 0 {
833        let nanoseconds = rescale(
834            i64::from(audio.priming),
835            1_000_000_000,
836            i64::from(audio.sample_rate.max(1)),
837        );
838        put_uint(&mut delay, id::CODEC_DELAY, nanoseconds.unsigned_abs());
839    }
840    if audio.codec == AudioCodec::Opus {
841        put_uint(&mut delay, id::SEEK_PRE_ROLL, OPUS_SEEK_PRE_ROLL);
842    }
843    delay
844}
845
846/// The Matroska codec ID of a PCM layout `FFmpeg`'s muxer has one for.
847fn pcm_codec(format: PcmFormat) -> Result<&'static str, MuxError> {
848    match (format.bits, format.float, format.big_endian, format.signed) {
849        (32 | 64, true, false, _) => Ok("A_PCM/FLOAT/IEEE"),
850        (8, false, _, false) | (16 | 24 | 32, false, false, true) => Ok("A_PCM/INT/LIT"),
851        (16 | 24 | 32, false, true, true) => Ok("A_PCM/INT/BIG"),
852        _ => Err(MuxError::Unsupported(format!(
853            "{format:?} PCM is not written to Matroska"
854        ))),
855    }
856}
857
858impl ContainerWriter for MatroskaWriter {
859    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError> {
860        if self.started {
861            return Err(MuxError::Invalid(
862                "tracks are added before the first packet".into(),
863            ));
864        }
865        if track.timescale == 0 {
866            return Err(MuxError::Invalid("a track needs a timescale".into()));
867        }
868        let webm = self.webm();
869        let parts = match (track.kind, &track.video, &track.audio) {
870            (TrackKind::Video, Some(video), _) => video_parts(video, webm)?,
871            (TrackKind::Audio, _, Some(audio)) => audio_parts(audio, webm)?,
872            _ => {
873                return Err(MuxError::Unsupported(
874                    "only video and audio tracks are written to Matroska".into(),
875                ));
876            }
877        };
878        let number = self.tracks.len() as u64 + 1;
879        if number > 126 {
880            return Err(MuxError::Unsupported("too many tracks".into()));
881        }
882        let mut payload = BytesMut::new();
883        put_uint(&mut payload, id::TRACK_NUMBER, number);
884        put_uint(&mut payload, id::TRACK_UID, number);
885        put_uint(&mut payload, id::FLAG_LACING, 0);
886        if let Some(title) = &track.title {
887            put_master(&mut payload, id::NAME, title.as_bytes());
888        }
889        let language = track.language.as_deref().filter(|code| !code.is_empty());
890        put_master(
891            &mut payload,
892            id::LANGUAGE,
893            language.unwrap_or("und").as_bytes(),
894        );
895        if !track.default {
896            put_uint(&mut payload, id::FLAG_DEFAULT, 0);
897        }
898        if !track.enabled {
899            put_uint(&mut payload, id::FLAG_ENABLED, 0);
900        }
901        put_master(&mut payload, id::CODEC_ID, parts.codec_id.as_bytes());
902        payload.put_slice(&parts.delay);
903        put_uint(&mut payload, id::TRACK_TYPE, parts.kind);
904        let (mut default_low, mut default_high) = (0, 0);
905        if let Some((num, den)) = parts
906            .default_duration
907            .filter(|(num, den)| *num > 0 && *den > 0)
908        {
909            put_uint(
910                &mut payload,
911                id::DEFAULT_DURATION,
912                1_000_000_000 * num / den,
913            );
914            default_low = i64::try_from(1000 * num / den).unwrap_or(0);
915            default_high = default_low + i64::from((1000 * num) % den != 0);
916        }
917        payload.put_slice(&parts.fields);
918        if !parts.private.is_empty() {
919            put_master(&mut payload, id::CODEC_PRIVATE, &parts.private);
920        }
921        let mut entry = BytesMut::new();
922        put_master(&mut entry, id::TRACK_ENTRY, &payload);
923        let sample_rate = track.audio.as_ref().map_or(0, |audio| audio.sample_rate);
924        let ts_offset = track.audio.as_ref().map_or(0, |audio| {
925            rescale(
926                i64::from(audio.priming),
927                1000,
928                i64::from(audio.sample_rate.max(1)),
929            )
930        });
931        self.tracks.push(Track {
932            info: track.clone(),
933            number,
934            entry,
935            ts_offset,
936            default_low,
937            default_high,
938            sample_rate,
939            queue: VecDeque::new(),
940            last_dts: None,
941            last_ts: 0,
942            has_cue: false,
943        });
944        Ok(TrackId(u32::try_from(number).unwrap_or(u32::MAX)))
945    }
946
947    fn write(&mut self, packet: Packet) -> Result<(), MuxError> {
948        let index = usize::try_from(packet.track.0)
949            .ok()
950            .and_then(|id| id.checked_sub(1))
951            .filter(|index| *index < self.tracks.len())
952            .ok_or_else(|| MuxError::Invalid(format!("no track {}", packet.track.0)))?;
953        if !self.started {
954            self.start()?;
955        }
956        let track = &mut self.tracks[index];
957        if track.last_dts.is_some_and(|last| packet.dts < last) {
958            return Err(MuxError::Invalid(format!(
959                "track {} decode times go back at {}",
960                packet.track.0, packet.dts
961            )));
962        }
963        track.last_dts = Some(packet.dts);
964        track.queue.push_back(packet);
965        self.pump(false)
966    }
967
968    fn finish(mut self: Box<Self>) -> Result<(), MuxError> {
969        self.finish_inner()
970    }
971}