alpha2-container 0.6.2

alpha2's own media container layer: MP4/MOV/M4A, Matroska/WebM and audio-only files, demuxed and muxed in pure Rust with edit lists, priming and deterministic output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! alpha2's own media container layer, for hosts without libavformat.
//!
//! [`open`] sniffs a file and returns a [`ContainerReader`] that lists its tracks and hands out
//! compressed packets per track; [`ContainerWriter`]s write MP4/MOV and Matroska/WebM. Timestamps
//! are in each track's timescale, on the presentation timeline after edit lists, and match what
//! `FFmpeg`'s demuxer reports for the same file, which the tests use as the oracle.
//!
//! Inputs are untrusted: sizes, counts and dimensions are bounded before anything is allocated
//! (frames at most 16384 pixels per side and 2^26 pixels in all, as the engine refuses larger).
//! Arithmetic with an operand from the file uses the `checked_`, `saturating_` or `wrapping_`
//! method that says what an out-of-range result means, since release builds panic on overflow.
//! Memory is bounded per file, not only per allocation: at most 256 tracks and 2^23
//! MP4 index entries over all tracks.

use std::path::Path;

use alpha2_media::{ColorMetadata, Orientation, Rect, SampleAspectRatio, SpeakerLayout};
use alpha2_time::FrameRate;
use bytes::Bytes;

/// The most tracks a file may have.
pub(crate) const MAX_TRACKS: usize = 256;

mod audio;
mod error;
mod matroska;
mod mp4;

pub use audio::vorbis_order;
pub use error::{DemuxError, MuxError};
pub use matroska::{MatroskaFlavor, MatroskaReader, MatroskaWriter};
pub use mp4::{Mp4Flavor, Mp4Reader, Mp4Writer};

/// A track's number within its container (MP4 `track_ID`, Matroska `TrackNumber`).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TrackId(pub u32);

/// What a track carries.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TrackKind {
    /// Pictures.
    Video,
    /// Sound.
    Audio,
    /// Anything else (subtitles, timecode, metadata), listed but never decoded.
    Other,
}

/// A four-character code, as MP4 sample entries name codecs.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct FourCc(pub [u8; 4]);

impl std::fmt::Display for FourCc {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for byte in self.0 {
            let shown = if byte.is_ascii_graphic() || byte == b' ' {
                char::from(byte)
            } else {
                '?'
            };
            write!(formatter, "{shown}")?;
        }
        Ok(())
    }
}

/// A video codec, as the container declares it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VideoCodec {
    /// H.264/AVC; `codec_private` is the `AVCDecoderConfigurationRecord` (`avcC`).
    H264,
    /// H.265/HEVC; `codec_private` is the `HEVCDecoderConfigurationRecord` (`hvcC`).
    Hevc,
    /// VP8; no `codec_private`.
    Vp8,
    /// VP9; `codec_private` is the `vpcC` body (version, flags and config), when present.
    Vp9,
    /// AV1; `codec_private` is the `AV1CodecConfigurationRecord` (`av1C`).
    Av1,
    /// MPEG-4 Part 2; `codec_private` is the decoder-specific info from `esds`.
    Mpeg4Part2,
    /// Apple `ProRes`, by its sample-entry four-character code.
    ProRes(FourCc),
    /// Anything else, by its four-character code or Matroska codec ID's first four bytes.
    Other(FourCc),
}

/// How PCM samples are stored.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PcmFormat {
    /// Bits per sample: 8, 16, 24, 32 or 64.
    pub bits: u16,
    /// IEEE float rather than integer.
    pub float: bool,
    /// Big-endian rather than little-endian.
    pub big_endian: bool,
    /// Signed integers (8-bit WAV is unsigned).
    pub signed: bool,
}

/// An audio codec, as the container declares it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AudioCodec {
    /// AAC; `codec_private` is the `AudioSpecificConfig`.
    Aac,
    /// MPEG-1/2 Layer III; no `codec_private`.
    Mp3,
    /// Opus; `codec_private` is the `OpusHead` (identification header).
    Opus,
    /// Vorbis; `codec_private` holds the three headers, Xiph-laced as Matroska stores them.
    Vorbis,
    /// FLAC; `codec_private` is `fLaC` followed by the metadata blocks (at least `STREAMINFO`).
    Flac,
    /// Apple Lossless; `codec_private` is the `ALACSpecificConfig` (magic cookie).
    Alac,
    /// Uncompressed PCM.
    Pcm(PcmFormat),
    /// AC-3; no `codec_private`.
    Ac3,
    /// E-AC-3; no `codec_private`.
    Eac3,
    /// DTS; no `codec_private`.
    Dts,
    /// Anything else, by its four-character code or Matroska codec ID's first four bytes.
    Other(FourCc),
}

/// A video track's picture facts.
#[derive(Clone, Debug, PartialEq)]
pub struct VideoTrack {
    /// The codec.
    pub codec: VideoCodec,
    /// The decoder configuration record (see [`VideoCodec`]); empty when the codec has none.
    pub codec_private: Bytes,
    /// Whether parameter sets also travel in the packets (`hev1`, `avc3`).
    pub in_band_parameter_sets: bool,
    /// Coded width in pixels, as the sample entry stores it.
    pub width: u32,
    /// Coded height in pixels.
    pub height: u32,
    /// How the stored picture is shown: the track matrix, or the Matroska projection pose, with
    /// `FFmpeg`'s rotation and mirror semantics.
    pub orientation: Orientation,
    /// The pixel aspect ratio the container declares (`pasp`, Matroska display size).
    pub sample_aspect_ratio: Option<SampleAspectRatio>,
    /// The color the container declares (`colr` `nclx`, Matroska `Colour`).
    pub color: Option<ColorMetadata>,
    /// The clean aperture (`clap`), when declared.
    pub clean_aperture: Option<Rect>,
    /// The nominal frame rate, when the container states one.
    pub frame_rate: Option<FrameRate>,
    /// Whether the track carries alpha the way alpha2 reads it (HEVC alpha layer, VP9 block
    /// additions).
    pub alpha: bool,
    /// The most pictures that precede any picture in decode order and follow it in presentation
    /// order, as the bitstream declares or implies it; `None` when unknown.
    ///
    /// H.264 takes `max_num_reorder_frames` (inferred per ITU-T H.264 E.2.1 when the VUI has no
    /// bitstream restriction), HEVC `sps_max_num_reorder_pics` of the highest sub-layer, MPEG-4
    /// Part 2 1 when B-VOPs may follow. VP8, VP9, AV1 and `ProRes` are 0: each packet yields at
    /// most one shown picture, in packet order.
    pub reorder_depth: Option<usize>,
}

/// An audio track's sound facts.
#[derive(Clone, Debug, PartialEq)]
pub struct AudioTrack {
    /// The codec.
    pub codec: AudioCodec,
    /// The codec's setup data (see [`AudioCodec`]); empty when it has none.
    pub codec_private: Bytes,
    /// Samples per second.
    pub sample_rate: u32,
    /// Channel count.
    pub channels: u32,
    /// Speaker positions the container declares (`chan`, `WAVEFORMATEXTENSIBLE` mask), when it
    /// does.
    pub speakers: Option<SpeakerLayout>,
    /// Bits per decoded sample, when stated.
    pub bits_per_sample: Option<u16>,
    /// Decoder output samples to drop at the start: AAC priming from the edit list or
    /// `iTunSMPB`, Matroska `CodecDelay`, Opus pre-skip.
    pub priming: u32,
    /// Samples a decoder needs to decode before a seek target to converge, in the units of
    /// [`Self::priming`] (Matroska `SeekPreRoll`), when the container declares it.
    pub seek_preroll: Option<u32>,
}

/// One track of a container.
#[derive(Clone, Debug, PartialEq)]
pub struct TrackInfo {
    /// The track's number.
    pub id: TrackId,
    /// What it carries.
    pub kind: TrackKind,
    /// Units per second of its timestamps.
    pub timescale: u32,
    /// Presentation duration in `timescale` units, after edits, when known.
    pub duration: Option<i64>,
    /// ISO 639-2 language, when tagged and not `und`.
    pub language: Option<String>,
    /// The track's name, when tagged.
    pub title: Option<String>,
    /// Flagged as a default track (`tkhd` enabled for MP4, `FlagDefault` for Matroska).
    pub default: bool,
    /// Flagged enabled (MP4 `tkhd`, Matroska `FlagEnabled`).
    pub enabled: bool,
    /// Picture facts of a video track.
    pub video: Option<VideoTrack>,
    /// Sound facts of an audio track.
    pub audio: Option<AudioTrack>,
}

/// One compressed frame of one track.
#[derive(Clone, Debug, PartialEq)]
pub struct Packet {
    /// The track it belongs to.
    pub track: TrackId,
    /// Presentation time in the track's timescale, after edits; negative for priming and
    /// pre-roll.
    pub pts: i64,
    /// Decode time in the track's timescale.
    pub dts: i64,
    /// Duration in the track's timescale; 0 when unknown.
    pub duration: i64,
    /// Decodable on its own (a sync sample).
    pub keyframe: bool,
    /// The frame, as the codec stores it (length-prefixed NAL units for `avcC`/`hvcC` tracks).
    pub data: Bytes,
    /// Decoded samples to drop from the start and end of this packet's output (Matroska
    /// `DiscardPadding`, the last AAC frame's padding), as `FFmpeg`'s skip-samples side data.
    pub discard: (u32, u32),
}

/// A demuxer: the tracks of one file and their packets.
///
/// Each track is read on its own, in decode order, as if no other track existed. Hosts open one
/// reader per consumer when they read several tracks at different positions.
pub trait ContainerReader: Send {
    /// The tracks, in container order.
    fn tracks(&self) -> &[TrackInfo];

    /// The index into [`Self::tracks`] of the default video track: the first enabled video
    /// track flagged default, else the first video track.
    fn default_video(&self) -> Option<usize> {
        default_track(self.tracks(), TrackKind::Video)
    }

    /// The index into [`Self::tracks`] of the default audio track, by the same rule.
    fn default_audio(&self) -> Option<usize> {
        default_track(self.tracks(), TrackKind::Audio)
    }

    /// Positions `track` so its next packet is the latest keyframe whose presentation time is at
    /// or before `pts`, or its first packet when none is. Returns that keyframe's `pts`; `None`
    /// for a track without packets.
    ///
    /// # Errors
    /// An unknown track, or a file that cannot be read there.
    fn seek(&mut self, track: TrackId, pts: i64) -> Result<Option<i64>, DemuxError>;

    /// The next packet of `track` in decode order; `None` at its end.
    ///
    /// # Errors
    /// An unknown track, damaged data, or a read failure.
    fn next_packet(&mut self, track: TrackId) -> Result<Option<Packet>, DemuxError>;
}

/// A muxer: writes tracks' packets into one file.
pub trait ContainerWriter: Send {
    /// Adds a track described by `track` (its `id` is ignored) and returns the id it gets.
    ///
    /// # Errors
    /// A codec the container cannot carry, or a track added after the first packet.
    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError>;

    /// Writes `packet`. Packets of each track arrive in decode order, and the writer interleaves
    /// the tracks. A track may run ahead of the others by up to 10 s (Matroska) or 64 MiB of
    /// packets (MP4) before the file's layout degrades: the leading track is then written in one
    /// run, and a reader seeking in it finds the other tracks far away.
    ///
    /// # Errors
    /// Timestamps that go backward, or a write failure.
    fn write(&mut self, packet: Packet) -> Result<(), MuxError>;

    /// Writes the index and closes the file.
    ///
    /// # Errors
    /// A write failure.
    fn finish(self: Box<Self>) -> Result<(), MuxError>;
}

/// The first enabled track of `kind` flagged default, else the first of `kind`.
#[must_use]
pub fn default_track(tracks: &[TrackInfo], kind: TrackKind) -> Option<usize> {
    tracks
        .iter()
        .position(|track| track.kind == kind && track.enabled && track.default)
        .or_else(|| tracks.iter().position(|track| track.kind == kind))
}

/// The container formats this layer reads, as a sniff of the first bytes finds them.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContainerFormat {
    /// ISO base media: MP4, MOV, M4A.
    Mp4,
    /// Matroska and `WebM`.
    Matroska,
    /// RIFF WAVE.
    Wav,
    /// MPEG audio (MP3), with or without an `ID3v2` tag.
    Mp3,
    /// AAC in ADTS frames.
    Adts,
    /// Native FLAC.
    Flac,
    /// Ogg (Opus, Vorbis, FLAC).
    Ogg,
}

/// The format of a file starting with `head` (at least its first 4096 bytes when it has them).
///
/// # Errors
/// [`DemuxError::Unsupported`] for MPEG-TS, AVI and anything unrecognized.
pub fn sniff(head: &[u8]) -> Result<ContainerFormat, DemuxError> {
    let at = |offset: usize, bytes: &[u8]| head.get(offset..offset + bytes.len()) == Some(bytes);
    if at(4, b"ftyp") || at(4, b"moov") || at(4, b"mdat") || at(4, b"wide") || at(4, b"free") {
        return Ok(ContainerFormat::Mp4);
    }
    if at(0, &[0x1a, 0x45, 0xdf, 0xa3]) {
        return Ok(ContainerFormat::Matroska);
    }
    if at(0, b"RIFF") && at(8, b"WAVE") {
        return Ok(ContainerFormat::Wav);
    }
    if at(0, b"RIFF") && at(8, b"AVI ") {
        return Err(DemuxError::Unsupported(
            "AVI files are not read on this platform; convert to MP4 or MOV".into(),
        ));
    }
    if at(0, b"fLaC") {
        return Ok(ContainerFormat::Flac);
    }
    if at(0, b"OggS") {
        return Ok(ContainerFormat::Ogg);
    }
    if head.first() == Some(&0x47) && head.get(188) == Some(&0x47) {
        return Err(DemuxError::Unsupported(
            "MPEG-TS files are not read on this platform; convert to MP4 or MOV".into(),
        ));
    }
    if at(0, b"ID3") {
        return Ok(ContainerFormat::Mp3);
    }
    if head.len() >= 2 && head[0] == 0xff && head[1] & 0xf6 == 0xf0 {
        return Ok(ContainerFormat::Adts);
    }
    if head.len() >= 2 && head[0] == 0xff && head[1] & 0xe0 == 0xe0 {
        return Ok(ContainerFormat::Mp3);
    }
    Err(DemuxError::Unsupported(
        "the file is not a container this platform reads".into(),
    ))
}

/// A seekable byte stream a demuxer reads a file from.
pub trait Source: std::io::Read + std::io::Seek + Send {}

impl<T: std::io::Read + std::io::Seek + Send> Source for T {}

/// Opens `path` with the demuxer its first bytes call for.
///
/// # Errors
/// [`DemuxError::Unsupported`] for a format this layer does not read; read or parse failures.
pub fn open(path: &Path) -> Result<Box<dyn ContainerReader>, DemuxError> {
    open_source(Box::new(std::fs::File::open(path)?))
}

/// Opens the file `source` holds with the demuxer its first bytes call for.
///
/// # Errors
/// [`DemuxError::Unsupported`] for a format this layer does not read; read or parse failures.
pub fn open_source(mut source: Box<dyn Source>) -> Result<Box<dyn ContainerReader>, DemuxError> {
    use std::io::{Read, Seek, SeekFrom};
    let mut head = Vec::with_capacity(4096);
    (&mut source).take(4096).read_to_end(&mut head)?;
    source.seek(SeekFrom::Start(0))?;
    let format = sniff(&head)?;
    match format {
        ContainerFormat::Wav
        | ContainerFormat::Mp3
        | ContainerFormat::Adts
        | ContainerFormat::Flac
        | ContainerFormat::Ogg => audio::open(format, source),
        ContainerFormat::Mp4 => Ok(Box::new(Mp4Reader::new(source)?)),
        ContainerFormat::Matroska => Ok(Box::new(MatroskaReader::new(source)?)),
    }
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod work_tests;