use std::path::Path;
use alpha2_media::{ColorMetadata, Orientation, Rect, SampleAspectRatio, SpeakerLayout};
use alpha2_time::FrameRate;
use bytes::Bytes;
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};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TrackId(pub u32);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TrackKind {
Video,
Audio,
Other,
}
#[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(())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VideoCodec {
H264,
Hevc,
Vp8,
Vp9,
Av1,
Mpeg4Part2,
ProRes(FourCc),
Other(FourCc),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PcmFormat {
pub bits: u16,
pub float: bool,
pub big_endian: bool,
pub signed: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AudioCodec {
Aac,
Mp3,
Opus,
Vorbis,
Flac,
Alac,
Pcm(PcmFormat),
Ac3,
Eac3,
Dts,
Other(FourCc),
}
#[derive(Clone, Debug, PartialEq)]
pub struct VideoTrack {
pub codec: VideoCodec,
pub codec_private: Bytes,
pub in_band_parameter_sets: bool,
pub width: u32,
pub height: u32,
pub orientation: Orientation,
pub sample_aspect_ratio: Option<SampleAspectRatio>,
pub color: Option<ColorMetadata>,
pub clean_aperture: Option<Rect>,
pub frame_rate: Option<FrameRate>,
pub alpha: bool,
pub reorder_depth: Option<usize>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AudioTrack {
pub codec: AudioCodec,
pub codec_private: Bytes,
pub sample_rate: u32,
pub channels: u32,
pub speakers: Option<SpeakerLayout>,
pub bits_per_sample: Option<u16>,
pub priming: u32,
pub seek_preroll: Option<u32>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TrackInfo {
pub id: TrackId,
pub kind: TrackKind,
pub timescale: u32,
pub duration: Option<i64>,
pub language: Option<String>,
pub title: Option<String>,
pub default: bool,
pub enabled: bool,
pub video: Option<VideoTrack>,
pub audio: Option<AudioTrack>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Packet {
pub track: TrackId,
pub pts: i64,
pub dts: i64,
pub duration: i64,
pub keyframe: bool,
pub data: Bytes,
pub discard: (u32, u32),
}
pub trait ContainerReader: Send {
fn tracks(&self) -> &[TrackInfo];
fn default_video(&self) -> Option<usize> {
default_track(self.tracks(), TrackKind::Video)
}
fn default_audio(&self) -> Option<usize> {
default_track(self.tracks(), TrackKind::Audio)
}
fn seek(&mut self, track: TrackId, pts: i64) -> Result<Option<i64>, DemuxError>;
fn next_packet(&mut self, track: TrackId) -> Result<Option<Packet>, DemuxError>;
}
pub trait ContainerWriter: Send {
fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError>;
fn write(&mut self, packet: Packet) -> Result<(), MuxError>;
fn finish(self: Box<Self>) -> Result<(), MuxError>;
}
#[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))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContainerFormat {
Mp4,
Matroska,
Wav,
Mp3,
Adts,
Flac,
Ogg,
}
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(),
))
}
pub trait Source: std::io::Read + std::io::Seek + Send {}
impl<T: std::io::Read + std::io::Seek + Send> Source for T {}
pub fn open(path: &Path) -> Result<Box<dyn ContainerReader>, DemuxError> {
open_source(Box::new(std::fs::File::open(path)?))
}
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;