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        ColorPrimaries::DisplayP3 => 12,
572    };
573    let range = if color.range == ColorRange::Full {
574        2
575    } else {
576        1
577    };
578    let mut payload = BytesMut::new();
579    put_uint(&mut payload, id::TRANSFER_CHARACTERISTICS, transfer);
580    put_uint(&mut payload, id::MATRIX_COEFFICIENTS, matrix);
581    put_uint(&mut payload, id::PRIMARIES, primaries);
582    put_uint(&mut payload, id::RANGE, range);
583    payload
584}
585
586/// The projection pose `FFmpeg` derives from the display matrix of `orientation`: a yaw of 180
587/// for a mirror and the counter-clockwise roll.
588fn pose(orientation: alpha2_media::Orientation) -> BytesMut {
589    let matrix = crate::mp4::write::display_matrix(orientation);
590    let mut payload = BytesMut::new();
591    if orientation.rotation == Rotation::Deg0 && !orientation.mirror {
592        return payload;
593    }
594    let yaw = if orientation.mirror { 180.0 } else { 0.0 };
595    let roll = f64::from(matrix[3])
596        .atan2(f64::from(matrix[4]))
597        .to_degrees();
598    if orientation.mirror {
599        put_float(&mut payload, id::PROJECTION_POSE_YAW, yaw);
600    }
601    if roll != 0.0 {
602        put_float(&mut payload, id::PROJECTION_POSE_ROLL, roll);
603    }
604    payload
605}
606
607/// The codec-specific parts of a `TrackEntry`.
608struct Parts {
609    codec_id: &'static str,
610    /// `CodecDelay` and `SeekPreRoll`, which `FFmpeg` writes before the track type.
611    delay: BytesMut,
612    kind: u64,
613    /// `DefaultDuration` in nanoseconds, from a frame or sample rate.
614    default_duration: Option<(u64, u64)>,
615    fields: BytesMut,
616    private: BytesMut,
617}
618
619fn video_parts(video: &VideoTrack, webm: bool) -> Result<Parts, MuxError> {
620    let mut private = BytesMut::new();
621    let codec_id = match video.codec {
622        VideoCodec::Vp8 => "V_VP8",
623        // Matroska's VP9 private data is a feature list, not the `vpcC` body; none is needed.
624        VideoCodec::Vp9 => "V_VP9",
625        VideoCodec::Av1 => {
626            private.put_slice(&video.codec_private);
627            "V_AV1"
628        }
629        _ if webm => {
630            return Err(MuxError::Unsupported(format!(
631                "{:?} video is not written to WebM",
632                video.codec
633            )));
634        }
635        VideoCodec::H264 => {
636            private.put_slice(&video.codec_private);
637            "V_MPEG4/ISO/AVC"
638        }
639        VideoCodec::Hevc => {
640            private.put_slice(&video.codec_private);
641            "V_MPEGH/ISO/HEVC"
642        }
643        VideoCodec::Mpeg4Part2 => {
644            private.put_slice(&video.codec_private);
645            "V_MPEG4/ISO/ASP"
646        }
647        VideoCodec::ProRes(code) => {
648            private.put_slice(&code.0);
649            "V_PRORES"
650        }
651        VideoCodec::Other(code) => {
652            return Err(MuxError::Unsupported(format!(
653                "{code} video is not written to Matroska"
654            )));
655        }
656    };
657    let mut fields = BytesMut::new();
658    put_uint(&mut fields, id::PIXEL_WIDTH, u64::from(video.width));
659    put_uint(&mut fields, id::PIXEL_HEIGHT, u64::from(video.height));
660    if video.alpha {
661        put_uint(&mut fields, id::ALPHA_MODE, 1);
662    }
663    match video.sample_aspect_ratio {
664        Some(ratio) if ratio.num != ratio.den => {
665            let (width, height) = (u64::from(video.width), u64::from(video.height));
666            if webm {
667                let display = rescale(
668                    i64::from(video.width),
669                    i64::from(ratio.num),
670                    i64::from(ratio.den),
671                );
672                put_uint(&mut fields, id::DISPLAY_WIDTH, display.unsigned_abs());
673                put_uint(&mut fields, id::DISPLAY_HEIGHT, height);
674            } else {
675                let (num, den) = reduce(
676                    width * u64::from(ratio.num),
677                    height * u64::from(ratio.den),
678                    1 << 20,
679                );
680                put_uint(&mut fields, id::DISPLAY_WIDTH, num);
681                put_uint(&mut fields, id::DISPLAY_HEIGHT, den);
682                put_uint(&mut fields, id::DISPLAY_UNIT, 3);
683            }
684        }
685        None if !webm => put_uint(&mut fields, id::DISPLAY_UNIT, 4),
686        _ => {}
687    }
688    if let Some(color) = video.color {
689        put_master(&mut fields, id::COLOUR, &colour(color));
690    }
691    let pose = pose(video.orientation);
692    if !pose.is_empty() {
693        put_master(&mut fields, id::PROJECTION, &pose);
694    }
695    let mut out = BytesMut::new();
696    put_master(&mut out, id::VIDEO, &fields);
697    Ok(Parts {
698        codec_id,
699        delay: BytesMut::new(),
700        kind: 1,
701        default_duration: video
702            .frame_rate
703            .map(|rate| (u64::from(rate.denominator()), u64::from(rate.numerator()))),
704        fields: out,
705        private,
706    })
707}
708
709/// The core and extension sample rates of an `AudioSpecificConfig`; the second is 0 without SBR.
710fn aac_rates(config: &[u8]) -> Option<(u32, u32)> {
711    const RATES: [u32; 13] = [
712        96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025,
713        8_000, 7_350,
714    ];
715    let mut bits = crate::mp4::nal::Bits::new(config);
716    let mut object_type = bits.read(5)?;
717    if object_type == 31 {
718        object_type = 32 + bits.read(6)?;
719    }
720    let rate_of = |bits: &mut crate::mp4::nal::Bits<'_>| -> Option<u32> {
721        let index = bits.read(4)?;
722        if index == 15 {
723            bits.read(24)
724        } else {
725            RATES.get(index as usize).copied()
726        }
727    };
728    let core = rate_of(&mut bits)?;
729    bits.read(4)?;
730    let extension = if object_type == 5 || object_type == 29 {
731        rate_of(&mut bits)?
732    } else {
733        0
734    };
735    Some((core, extension))
736}
737
738fn audio_parts(audio: &AudioTrack, webm: bool) -> Result<Parts, MuxError> {
739    let mut private = BytesMut::new();
740    let mut sample_rate = audio.sample_rate;
741    let mut output_rate = 0;
742    let mut bit_depth = audio.bits_per_sample.map(u64::from);
743    let mut frame_samples = None;
744    let codec_id = match audio.codec {
745        AudioCodec::Opus => {
746            if audio.codec_private.len() < 19 || !audio.codec_private.starts_with(b"OpusHead") {
747                return Err(MuxError::Unsupported("Opus without an OpusHead".into()));
748            }
749            private.put_slice(&audio.codec_private);
750            "A_OPUS"
751        }
752        AudioCodec::Vorbis => {
753            if xiph_headers(&audio.codec_private).is_none_or(|headers| headers.len() != 3) {
754                return Err(MuxError::Unsupported(
755                    "Vorbis without its three headers".into(),
756                ));
757            }
758            private.put_slice(&audio.codec_private);
759            "A_VORBIS"
760        }
761        _ if webm => {
762            return Err(MuxError::Unsupported(format!(
763                "{:?} audio is not written to WebM",
764                audio.codec
765            )));
766        }
767        AudioCodec::Aac => {
768            if let Some((core, extension)) = aac_rates(&audio.codec_private) {
769                sample_rate = core;
770                output_rate = extension;
771            }
772            private.put_slice(&audio.codec_private);
773            "A_AAC"
774        }
775        AudioCodec::Mp3 => "A_MPEG/L3",
776        AudioCodec::Flac => {
777            private.put_slice(&audio.codec_private);
778            "A_FLAC"
779        }
780        AudioCodec::Alac => {
781            private.put_slice(&audio.codec_private);
782            "A_ALAC"
783        }
784        AudioCodec::Ac3 => {
785            frame_samples = Some(1536);
786            "A_AC3"
787        }
788        AudioCodec::Eac3 => "A_EAC3",
789        AudioCodec::Dts => "A_DTS",
790        AudioCodec::Pcm(format) => {
791            bit_depth = Some(u64::from(format.bits));
792            pcm_codec(format)?
793        }
794        AudioCodec::Other(code) => {
795            return Err(MuxError::Unsupported(format!(
796                "{code} audio is not written to Matroska"
797            )));
798        }
799    };
800    if sample_rate == 0 {
801        return Err(MuxError::Invalid(
802            "an audio track needs a sample rate".into(),
803        ));
804    }
805    let mut fields = BytesMut::new();
806    put_uint(&mut fields, id::CHANNELS, u64::from(audio.channels));
807    put_float(&mut fields, id::SAMPLING_FREQUENCY, f64::from(sample_rate));
808    if output_rate > 0 {
809        put_float(
810            &mut fields,
811            id::OUTPUT_SAMPLING_FREQUENCY,
812            f64::from(output_rate),
813        );
814    }
815    if let Some(bits) = bit_depth {
816        put_uint(&mut fields, id::BIT_DEPTH, bits);
817    }
818    let mut out = BytesMut::new();
819    put_master(&mut out, id::AUDIO, &fields);
820    Ok(Parts {
821        codec_id,
822        delay: delay_elements(audio),
823        kind: 2,
824        default_duration: frame_samples.map(|samples| (samples, u64::from(audio.sample_rate))),
825        fields: out,
826        private,
827    })
828}
829
830/// `CodecDelay` for the priming, and the Opus `SeekPreRoll`.
831fn delay_elements(audio: &AudioTrack) -> BytesMut {
832    let mut delay = BytesMut::new();
833    if audio.priming > 0 {
834        let nanoseconds = rescale(
835            i64::from(audio.priming),
836            1_000_000_000,
837            i64::from(audio.sample_rate.max(1)),
838        );
839        put_uint(&mut delay, id::CODEC_DELAY, nanoseconds.unsigned_abs());
840    }
841    if audio.codec == AudioCodec::Opus {
842        put_uint(&mut delay, id::SEEK_PRE_ROLL, OPUS_SEEK_PRE_ROLL);
843    }
844    delay
845}
846
847/// The Matroska codec ID of a PCM layout `FFmpeg`'s muxer has one for.
848fn pcm_codec(format: PcmFormat) -> Result<&'static str, MuxError> {
849    match (format.bits, format.float, format.big_endian, format.signed) {
850        (32 | 64, true, false, _) => Ok("A_PCM/FLOAT/IEEE"),
851        (8, false, _, false) | (16 | 24 | 32, false, false, true) => Ok("A_PCM/INT/LIT"),
852        (16 | 24 | 32, false, true, true) => Ok("A_PCM/INT/BIG"),
853        _ => Err(MuxError::Unsupported(format!(
854            "{format:?} PCM is not written to Matroska"
855        ))),
856    }
857}
858
859impl ContainerWriter for MatroskaWriter {
860    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError> {
861        if self.started {
862            return Err(MuxError::Invalid(
863                "tracks are added before the first packet".into(),
864            ));
865        }
866        if track.timescale == 0 {
867            return Err(MuxError::Invalid("a track needs a timescale".into()));
868        }
869        let webm = self.webm();
870        let parts = match (track.kind, &track.video, &track.audio) {
871            (TrackKind::Video, Some(video), _) => video_parts(video, webm)?,
872            (TrackKind::Audio, _, Some(audio)) => audio_parts(audio, webm)?,
873            _ => {
874                return Err(MuxError::Unsupported(
875                    "only video and audio tracks are written to Matroska".into(),
876                ));
877            }
878        };
879        let number = self.tracks.len() as u64 + 1;
880        if number > 126 {
881            return Err(MuxError::Unsupported("too many tracks".into()));
882        }
883        let mut payload = BytesMut::new();
884        put_uint(&mut payload, id::TRACK_NUMBER, number);
885        put_uint(&mut payload, id::TRACK_UID, number);
886        put_uint(&mut payload, id::FLAG_LACING, 0);
887        if let Some(title) = &track.title {
888            put_master(&mut payload, id::NAME, title.as_bytes());
889        }
890        let language = track.language.as_deref().filter(|code| !code.is_empty());
891        put_master(
892            &mut payload,
893            id::LANGUAGE,
894            language.unwrap_or("und").as_bytes(),
895        );
896        if !track.default {
897            put_uint(&mut payload, id::FLAG_DEFAULT, 0);
898        }
899        if !track.enabled {
900            put_uint(&mut payload, id::FLAG_ENABLED, 0);
901        }
902        put_master(&mut payload, id::CODEC_ID, parts.codec_id.as_bytes());
903        payload.put_slice(&parts.delay);
904        put_uint(&mut payload, id::TRACK_TYPE, parts.kind);
905        let (mut default_low, mut default_high) = (0, 0);
906        if let Some((num, den)) = parts
907            .default_duration
908            .filter(|(num, den)| *num > 0 && *den > 0)
909        {
910            put_uint(
911                &mut payload,
912                id::DEFAULT_DURATION,
913                1_000_000_000 * num / den,
914            );
915            default_low = i64::try_from(1000 * num / den).unwrap_or(0);
916            default_high = default_low + i64::from((1000 * num) % den != 0);
917        }
918        payload.put_slice(&parts.fields);
919        if !parts.private.is_empty() {
920            put_master(&mut payload, id::CODEC_PRIVATE, &parts.private);
921        }
922        let mut entry = BytesMut::new();
923        put_master(&mut entry, id::TRACK_ENTRY, &payload);
924        let sample_rate = track.audio.as_ref().map_or(0, |audio| audio.sample_rate);
925        let ts_offset = track.audio.as_ref().map_or(0, |audio| {
926            rescale(
927                i64::from(audio.priming),
928                1000,
929                i64::from(audio.sample_rate.max(1)),
930            )
931        });
932        self.tracks.push(Track {
933            info: track.clone(),
934            number,
935            entry,
936            ts_offset,
937            default_low,
938            default_high,
939            sample_rate,
940            queue: VecDeque::new(),
941            last_dts: None,
942            last_ts: 0,
943            has_cue: false,
944        });
945        Ok(TrackId(u32::try_from(number).unwrap_or(u32::MAX)))
946    }
947
948    fn write(&mut self, packet: Packet) -> Result<(), MuxError> {
949        let index = usize::try_from(packet.track.0)
950            .ok()
951            .and_then(|id| id.checked_sub(1))
952            .filter(|index| *index < self.tracks.len())
953            .ok_or_else(|| MuxError::Invalid(format!("no track {}", packet.track.0)))?;
954        if !self.started {
955            self.start()?;
956        }
957        let track = &mut self.tracks[index];
958        if track.last_dts.is_some_and(|last| packet.dts < last) {
959            return Err(MuxError::Invalid(format!(
960                "track {} decode times go back at {}",
961                packet.track.0, packet.dts
962            )));
963        }
964        track.last_dts = Some(packet.dts);
965        track.queue.push_back(packet);
966        self.pump(false)
967    }
968
969    fn finish(mut self: Box<Self>) -> Result<(), MuxError> {
970        self.finish_inner()
971    }
972}