Skip to main content

alpha2_container/
lib.rs

1//! alpha2's own media container layer, for hosts without libavformat.
2//!
3//! [`open`] sniffs a file and returns a [`ContainerReader`] that lists its tracks and hands out
4//! compressed packets per track; [`ContainerWriter`]s write MP4/MOV and Matroska/WebM. Timestamps
5//! are in each track's timescale, on the presentation timeline after edit lists, and match what
6//! `FFmpeg`'s demuxer reports for the same file, which the tests use as the oracle.
7//!
8//! Inputs are untrusted: sizes, counts and dimensions are bounded before anything is allocated
9//! (frames at most 16384 pixels per side and 2^26 pixels in all, as the engine refuses larger).
10//! Arithmetic with an operand from the file uses the `checked_`, `saturating_` or `wrapping_`
11//! method that says what an out-of-range result means, since release builds panic on overflow.
12//! Memory is bounded per file, not only per allocation: at most 256 tracks and 2^23
13//! MP4 index entries over all tracks.
14
15use std::path::Path;
16
17use alpha2_media::{ColorMetadata, Orientation, Rect, SampleAspectRatio, SpeakerLayout};
18use alpha2_time::FrameRate;
19use bytes::Bytes;
20
21/// The most tracks a file may have.
22pub(crate) const MAX_TRACKS: usize = 256;
23
24mod audio;
25mod error;
26mod matroska;
27mod mp4;
28
29pub use audio::vorbis_order;
30pub use error::{DemuxError, MuxError};
31pub use matroska::{MatroskaFlavor, MatroskaReader, MatroskaWriter};
32pub use mp4::{Mp4Flavor, Mp4Reader, Mp4Writer};
33
34/// A track's number within its container (MP4 `track_ID`, Matroska `TrackNumber`).
35#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
36pub struct TrackId(pub u32);
37
38/// What a track carries.
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub enum TrackKind {
41    /// Pictures.
42    Video,
43    /// Sound.
44    Audio,
45    /// Anything else (subtitles, timecode, metadata), listed but never decoded.
46    Other,
47}
48
49/// A four-character code, as MP4 sample entries name codecs.
50#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
51pub struct FourCc(pub [u8; 4]);
52
53impl std::fmt::Display for FourCc {
54    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        for byte in self.0 {
56            let shown = if byte.is_ascii_graphic() || byte == b' ' {
57                char::from(byte)
58            } else {
59                '?'
60            };
61            write!(formatter, "{shown}")?;
62        }
63        Ok(())
64    }
65}
66
67/// A video codec, as the container declares it.
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub enum VideoCodec {
70    /// H.264/AVC; `codec_private` is the `AVCDecoderConfigurationRecord` (`avcC`).
71    H264,
72    /// H.265/HEVC; `codec_private` is the `HEVCDecoderConfigurationRecord` (`hvcC`).
73    Hevc,
74    /// VP8; no `codec_private`.
75    Vp8,
76    /// VP9; `codec_private` is the `vpcC` body (version, flags and config), when present.
77    Vp9,
78    /// AV1; `codec_private` is the `AV1CodecConfigurationRecord` (`av1C`).
79    Av1,
80    /// MPEG-4 Part 2; `codec_private` is the decoder-specific info from `esds`.
81    Mpeg4Part2,
82    /// Apple `ProRes`, by its sample-entry four-character code.
83    ProRes(FourCc),
84    /// Anything else, by its four-character code or Matroska codec ID's first four bytes.
85    Other(FourCc),
86}
87
88/// How PCM samples are stored.
89#[derive(Clone, Copy, Debug, Eq, PartialEq)]
90pub struct PcmFormat {
91    /// Bits per sample: 8, 16, 24, 32 or 64.
92    pub bits: u16,
93    /// IEEE float rather than integer.
94    pub float: bool,
95    /// Big-endian rather than little-endian.
96    pub big_endian: bool,
97    /// Signed integers (8-bit WAV is unsigned).
98    pub signed: bool,
99}
100
101/// An audio codec, as the container declares it.
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum AudioCodec {
104    /// AAC; `codec_private` is the `AudioSpecificConfig`.
105    Aac,
106    /// MPEG-1/2 Layer III; no `codec_private`.
107    Mp3,
108    /// Opus; `codec_private` is the `OpusHead` (identification header).
109    Opus,
110    /// Vorbis; `codec_private` holds the three headers, Xiph-laced as Matroska stores them.
111    Vorbis,
112    /// FLAC; `codec_private` is `fLaC` followed by the metadata blocks (at least `STREAMINFO`).
113    Flac,
114    /// Apple Lossless; `codec_private` is the `ALACSpecificConfig` (magic cookie).
115    Alac,
116    /// Uncompressed PCM.
117    Pcm(PcmFormat),
118    /// AC-3; no `codec_private`.
119    Ac3,
120    /// E-AC-3; no `codec_private`.
121    Eac3,
122    /// DTS; no `codec_private`.
123    Dts,
124    /// Anything else, by its four-character code or Matroska codec ID's first four bytes.
125    Other(FourCc),
126}
127
128/// A video track's picture facts.
129#[derive(Clone, Debug, PartialEq)]
130pub struct VideoTrack {
131    /// The codec.
132    pub codec: VideoCodec,
133    /// The decoder configuration record (see [`VideoCodec`]); empty when the codec has none.
134    pub codec_private: Bytes,
135    /// Whether parameter sets also travel in the packets (`hev1`, `avc3`).
136    pub in_band_parameter_sets: bool,
137    /// Coded width in pixels, as the sample entry stores it.
138    pub width: u32,
139    /// Coded height in pixels.
140    pub height: u32,
141    /// How the stored picture is shown: the track matrix, or the Matroska projection pose, with
142    /// `FFmpeg`'s rotation and mirror semantics.
143    pub orientation: Orientation,
144    /// The pixel aspect ratio the container declares (`pasp`, Matroska display size).
145    pub sample_aspect_ratio: Option<SampleAspectRatio>,
146    /// The color the container declares (`colr` `nclx`, Matroska `Colour`).
147    pub color: Option<ColorMetadata>,
148    /// The clean aperture (`clap`), when declared.
149    pub clean_aperture: Option<Rect>,
150    /// The nominal frame rate, when the container states one.
151    pub frame_rate: Option<FrameRate>,
152    /// Whether the track carries alpha the way alpha2 reads it (HEVC alpha layer, VP9 block
153    /// additions).
154    pub alpha: bool,
155    /// The most pictures that precede any picture in decode order and follow it in presentation
156    /// order, as the bitstream declares or implies it; `None` when unknown.
157    ///
158    /// H.264 takes `max_num_reorder_frames` (inferred per ITU-T H.264 E.2.1 when the VUI has no
159    /// bitstream restriction), HEVC `sps_max_num_reorder_pics` of the highest sub-layer, MPEG-4
160    /// Part 2 1 when B-VOPs may follow. VP8, VP9, AV1 and `ProRes` are 0: each packet yields at
161    /// most one shown picture, in packet order.
162    pub reorder_depth: Option<usize>,
163}
164
165/// An audio track's sound facts.
166#[derive(Clone, Debug, PartialEq)]
167pub struct AudioTrack {
168    /// The codec.
169    pub codec: AudioCodec,
170    /// The codec's setup data (see [`AudioCodec`]); empty when it has none.
171    pub codec_private: Bytes,
172    /// Samples per second.
173    pub sample_rate: u32,
174    /// Channel count.
175    pub channels: u32,
176    /// Speaker positions the container declares (`chan`, `WAVEFORMATEXTENSIBLE` mask), when it
177    /// does.
178    pub speakers: Option<SpeakerLayout>,
179    /// Bits per decoded sample, when stated.
180    pub bits_per_sample: Option<u16>,
181    /// Decoder output samples to drop at the start: AAC priming from the edit list or
182    /// `iTunSMPB`, Matroska `CodecDelay`, Opus pre-skip.
183    pub priming: u32,
184    /// Samples a decoder needs to decode before a seek target to converge, in the units of
185    /// [`Self::priming`] (Matroska `SeekPreRoll`), when the container declares it.
186    pub seek_preroll: Option<u32>,
187}
188
189/// One track of a container.
190#[derive(Clone, Debug, PartialEq)]
191pub struct TrackInfo {
192    /// The track's number.
193    pub id: TrackId,
194    /// What it carries.
195    pub kind: TrackKind,
196    /// Units per second of its timestamps.
197    pub timescale: u32,
198    /// Presentation duration in `timescale` units, after edits, when known.
199    pub duration: Option<i64>,
200    /// ISO 639-2 language, when tagged and not `und`.
201    pub language: Option<String>,
202    /// The track's name, when tagged.
203    pub title: Option<String>,
204    /// Flagged as a default track (`tkhd` enabled for MP4, `FlagDefault` for Matroska).
205    pub default: bool,
206    /// Flagged enabled (MP4 `tkhd`, Matroska `FlagEnabled`).
207    pub enabled: bool,
208    /// Picture facts of a video track.
209    pub video: Option<VideoTrack>,
210    /// Sound facts of an audio track.
211    pub audio: Option<AudioTrack>,
212}
213
214/// One compressed frame of one track.
215#[derive(Clone, Debug, PartialEq)]
216pub struct Packet {
217    /// The track it belongs to.
218    pub track: TrackId,
219    /// Presentation time in the track's timescale, after edits; negative for priming and
220    /// pre-roll.
221    pub pts: i64,
222    /// Decode time in the track's timescale.
223    pub dts: i64,
224    /// Duration in the track's timescale; 0 when unknown.
225    pub duration: i64,
226    /// Decodable on its own (a sync sample).
227    pub keyframe: bool,
228    /// The frame, as the codec stores it (length-prefixed NAL units for `avcC`/`hvcC` tracks).
229    pub data: Bytes,
230    /// Decoded samples to drop from the start and end of this packet's output (Matroska
231    /// `DiscardPadding`, the last AAC frame's padding), as `FFmpeg`'s skip-samples side data.
232    pub discard: (u32, u32),
233}
234
235/// A demuxer: the tracks of one file and their packets.
236///
237/// Each track is read on its own, in decode order, as if no other track existed. Hosts open one
238/// reader per consumer when they read several tracks at different positions.
239pub trait ContainerReader: Send {
240    /// The tracks, in container order.
241    fn tracks(&self) -> &[TrackInfo];
242
243    /// The index into [`Self::tracks`] of the default video track: the first enabled video
244    /// track flagged default, else the first video track.
245    fn default_video(&self) -> Option<usize> {
246        default_track(self.tracks(), TrackKind::Video)
247    }
248
249    /// The index into [`Self::tracks`] of the default audio track, by the same rule.
250    fn default_audio(&self) -> Option<usize> {
251        default_track(self.tracks(), TrackKind::Audio)
252    }
253
254    /// Positions `track` so its next packet is the latest keyframe whose presentation time is at
255    /// or before `pts`, or its first packet when none is. Returns that keyframe's `pts`; `None`
256    /// for a track without packets.
257    ///
258    /// # Errors
259    /// An unknown track, or a file that cannot be read there.
260    fn seek(&mut self, track: TrackId, pts: i64) -> Result<Option<i64>, DemuxError>;
261
262    /// The next packet of `track` in decode order; `None` at its end.
263    ///
264    /// # Errors
265    /// An unknown track, damaged data, or a read failure.
266    fn next_packet(&mut self, track: TrackId) -> Result<Option<Packet>, DemuxError>;
267}
268
269/// A muxer: writes tracks' packets into one file.
270pub trait ContainerWriter: Send {
271    /// Adds a track described by `track` (its `id` is ignored) and returns the id it gets.
272    ///
273    /// # Errors
274    /// A codec the container cannot carry, or a track added after the first packet.
275    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError>;
276
277    /// Writes `packet`. Packets of each track arrive in decode order, and the writer interleaves
278    /// the tracks. A track may run ahead of the others by up to 10 s (Matroska) or 64 MiB of
279    /// packets (MP4) before the file's layout degrades: the leading track is then written in one
280    /// run, and a reader seeking in it finds the other tracks far away.
281    ///
282    /// # Errors
283    /// Timestamps that go backward, or a write failure.
284    fn write(&mut self, packet: Packet) -> Result<(), MuxError>;
285
286    /// Writes the index and closes the file.
287    ///
288    /// # Errors
289    /// A write failure.
290    fn finish(self: Box<Self>) -> Result<(), MuxError>;
291}
292
293/// The first enabled track of `kind` flagged default, else the first of `kind`.
294#[must_use]
295pub fn default_track(tracks: &[TrackInfo], kind: TrackKind) -> Option<usize> {
296    tracks
297        .iter()
298        .position(|track| track.kind == kind && track.enabled && track.default)
299        .or_else(|| tracks.iter().position(|track| track.kind == kind))
300}
301
302/// The container formats this layer reads, as a sniff of the first bytes finds them.
303#[derive(Clone, Copy, Debug, Eq, PartialEq)]
304pub enum ContainerFormat {
305    /// ISO base media: MP4, MOV, M4A.
306    Mp4,
307    /// Matroska and `WebM`.
308    Matroska,
309    /// RIFF WAVE.
310    Wav,
311    /// MPEG audio (MP3), with or without an `ID3v2` tag.
312    Mp3,
313    /// AAC in ADTS frames.
314    Adts,
315    /// Native FLAC.
316    Flac,
317    /// Ogg (Opus, Vorbis, FLAC).
318    Ogg,
319}
320
321/// The format of a file starting with `head` (at least its first 4096 bytes when it has them).
322///
323/// # Errors
324/// [`DemuxError::Unsupported`] for MPEG-TS, AVI and anything unrecognized.
325pub fn sniff(head: &[u8]) -> Result<ContainerFormat, DemuxError> {
326    let at = |offset: usize, bytes: &[u8]| head.get(offset..offset + bytes.len()) == Some(bytes);
327    if at(4, b"ftyp") || at(4, b"moov") || at(4, b"mdat") || at(4, b"wide") || at(4, b"free") {
328        return Ok(ContainerFormat::Mp4);
329    }
330    if at(0, &[0x1a, 0x45, 0xdf, 0xa3]) {
331        return Ok(ContainerFormat::Matroska);
332    }
333    if at(0, b"RIFF") && at(8, b"WAVE") {
334        return Ok(ContainerFormat::Wav);
335    }
336    if at(0, b"RIFF") && at(8, b"AVI ") {
337        return Err(DemuxError::Unsupported(
338            "AVI files are not read on this platform; convert to MP4 or MOV".into(),
339        ));
340    }
341    if at(0, b"fLaC") {
342        return Ok(ContainerFormat::Flac);
343    }
344    if at(0, b"OggS") {
345        return Ok(ContainerFormat::Ogg);
346    }
347    if head.first() == Some(&0x47) && head.get(188) == Some(&0x47) {
348        return Err(DemuxError::Unsupported(
349            "MPEG-TS files are not read on this platform; convert to MP4 or MOV".into(),
350        ));
351    }
352    if at(0, b"ID3") {
353        return Ok(ContainerFormat::Mp3);
354    }
355    if head.len() >= 2 && head[0] == 0xff && head[1] & 0xf6 == 0xf0 {
356        return Ok(ContainerFormat::Adts);
357    }
358    if head.len() >= 2 && head[0] == 0xff && head[1] & 0xe0 == 0xe0 {
359        return Ok(ContainerFormat::Mp3);
360    }
361    Err(DemuxError::Unsupported(
362        "the file is not a container this platform reads".into(),
363    ))
364}
365
366/// A seekable byte stream a demuxer reads a file from.
367pub trait Source: std::io::Read + std::io::Seek + Send {}
368
369impl<T: std::io::Read + std::io::Seek + Send> Source for T {}
370
371/// Opens `path` with the demuxer its first bytes call for.
372///
373/// # Errors
374/// [`DemuxError::Unsupported`] for a format this layer does not read; read or parse failures.
375pub fn open(path: &Path) -> Result<Box<dyn ContainerReader>, DemuxError> {
376    open_source(Box::new(std::fs::File::open(path)?))
377}
378
379/// Opens the file `source` holds with the demuxer its first bytes call for.
380///
381/// # Errors
382/// [`DemuxError::Unsupported`] for a format this layer does not read; read or parse failures.
383pub fn open_source(mut source: Box<dyn Source>) -> Result<Box<dyn ContainerReader>, DemuxError> {
384    use std::io::{Read, Seek, SeekFrom};
385    let mut head = Vec::with_capacity(4096);
386    (&mut source).take(4096).read_to_end(&mut head)?;
387    source.seek(SeekFrom::Start(0))?;
388    let format = sniff(&head)?;
389    match format {
390        ContainerFormat::Wav
391        | ContainerFormat::Mp3
392        | ContainerFormat::Adts
393        | ContainerFormat::Flac
394        | ContainerFormat::Ogg => audio::open(format, source),
395        ContainerFormat::Mp4 => Ok(Box::new(Mp4Reader::new(source)?)),
396        ContainerFormat::Matroska => Ok(Box::new(MatroskaReader::new(source)?)),
397    }
398}
399
400#[cfg(test)]
401mod tests;
402#[cfg(test)]
403mod work_tests;