pub mod aac;
pub mod av1;
pub mod avc;
pub mod flac;
pub mod hvc;
pub mod nal;
pub mod time;
use std::collections::HashMap;
use std::io::{Read, Seek, Write};
use rff_core::{
CleanAperture, CodecId, ColorInfo, ColorRange, ContentLightLevel, Dictionary, Error,
MasteringDisplay, MediaType, Packet, PixelFormat, Rational, Result, SampleFormat, Timecode,
};
#[derive(Debug, Clone)]
pub struct Stream {
pub index: usize,
pub codec_id: CodecId,
pub media_type: MediaType,
pub time_base: Rational,
pub width: u32,
pub height: u32,
pub pixel_format: Option<PixelFormat>,
pub color_range: ColorRange,
pub sample_rate: u32,
pub channels: u16,
pub sample_format: Option<SampleFormat>,
pub extradata: Vec<u8>,
pub duration: Option<i64>,
pub nb_frames: Option<u64>,
pub codec_tag: Option<[u8; 4]>,
pub color: ColorInfo,
pub mastering_display: Option<MasteringDisplay>,
pub content_light: Option<ContentLightLevel>,
pub pixel_aspect: Option<(u32, u32)>,
pub clean_aperture: Option<CleanAperture>,
pub timecode: Option<Timecode>,
pub alpha_mode: bool,
pub codec_delay_ns: u64,
pub seek_preroll_ns: u64,
pub display_matrix: Option<[i32; 9]>,
pub language: Option<String>,
pub name: Option<String>,
pub disposition: Disposition,
pub field_order: Option<u8>,
pub stereo_mode: Option<u8>,
pub codec_string: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Disposition {
pub default: Option<bool>,
pub enabled: Option<bool>,
pub forced: bool,
pub hearing_impaired: bool,
pub visual_impaired: bool,
pub original: bool,
pub commentary: bool,
}
pub fn rotation_matrix(degrees: f64, width: u32, height: u32) -> [i32; 9] {
const ONE: i32 = 1 << 16;
const W: i32 = 1 << 30;
let fixed = |v: u32| i32::try_from(i64::from(v) << 16).unwrap_or(i32::MAX);
let (w, h) = (fixed(width), fixed(height));
let turn = degrees.rem_euclid(360.0);
match turn {
0.0 => [ONE, 0, 0, 0, ONE, 0, 0, 0, W],
90.0 => [0, ONE, 0, -ONE, 0, 0, h, 0, W],
180.0 => [-ONE, 0, 0, 0, -ONE, 0, w, h, W],
270.0 => [0, -ONE, 0, ONE, 0, 0, 0, w, W],
t => {
let (s, c) = t.to_radians().sin_cos();
let q = |v: f64| (v * f64::from(ONE)).round() as i32;
[q(c), q(s), 0, q(-s), q(c), 0, 0, 0, W]
}
}
}
pub fn matrix_rotation(m: &[i32; 9]) -> Option<f64> {
let f = |v: i32| f64::from(v) / 65536.0;
let (a, b, c, d) = (f(m[0]), f(m[1]), f(m[3]), f(m[4]));
let tol = 1e-3;
if (a - d).abs() > tol || (b + c).abs() > tol || (a * a + b * b - 1.0).abs() > 2.0 * tol {
return None;
}
let deg = b.atan2(a).to_degrees().rem_euclid(360.0);
let snapped = deg.round();
let deg = if (deg - snapped).abs() < 1e-2 {
snapped.rem_euclid(360.0)
} else {
deg
};
Some(deg)
}
impl Stream {
pub fn rotation(&self) -> Option<f64> {
match &self.display_matrix {
None => Some(0.0),
Some(m) => matrix_rotation(m),
}
}
pub fn set_rotation(&mut self, degrees: f64) {
self.display_matrix = if degrees.rem_euclid(360.0) == 0.0 {
None
} else {
Some(rotation_matrix(degrees, self.width, self.height))
};
}
}
impl Stream {
pub fn new(index: usize, codec_id: CodecId) -> Stream {
Stream {
index,
codec_id,
media_type: codec_id.media_type(),
time_base: Rational::new(1, 1000),
width: 0,
height: 0,
pixel_format: None,
color_range: ColorRange::Unspecified,
sample_rate: 0,
channels: 0,
sample_format: None,
extradata: Vec::new(),
duration: None,
nb_frames: None,
codec_tag: None,
color: ColorInfo::UNSPECIFIED,
mastering_display: None,
content_light: None,
pixel_aspect: None,
clean_aperture: None,
timecode: None,
alpha_mode: false,
codec_delay_ns: 0,
seek_preroll_ns: 0,
display_matrix: None,
language: None,
name: None,
disposition: Disposition::default(),
field_order: None,
stereo_mode: None,
codec_string: None,
}
}
}
pub type Input = Box<dyn Read + Send>;
pub trait ReadSeek: Read + Seek {}
impl<T: Read + Seek> ReadSeek for T {}
pub type SeekInput = Box<dyn ReadSeek + Send>;
pub type Output = Box<dyn Write + Send>;
pub trait WriteSeek: Write + Seek {}
impl<T: Write + Seek> WriteSeek for T {}
pub type SeekOutput = Box<dyn WriteSeek + Send>;
pub trait Demuxer: Send {
fn read_header(&mut self) -> Result<Vec<Stream>>;
fn read_packet(&mut self) -> Result<Packet>;
fn set_discard(&mut self, _discard: &[bool]) {}
fn sample_index(&mut self) -> Option<&mut dyn SampleIndex> {
None
}
fn set_raw_samples(&mut self, _raw: bool) -> bool {
false
}
fn metadata(&self) -> Option<&Dictionary> {
None
}
fn stream_metadata(&self, _index: usize) -> Option<&Dictionary> {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SampleInfo {
pub offset: u64,
pub size: u32,
pub dts: i64,
pub pts: i64,
pub duration: i64,
pub sync: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EditEntry {
pub segment_duration: i64,
pub media_time: i64,
pub media_rate: i32,
}
pub trait SampleIndex {
fn sample_count(&self, stream: usize) -> u64;
fn sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo>;
fn read_sample(&mut self, stream: usize, index: u64) -> Result<Packet>;
fn sync_at_or_before(&self, stream: usize, pts: i64) -> Option<u64>;
fn edit_list(&self, _stream: usize) -> &[EditEntry] {
&[]
}
fn movie_timescale(&self) -> Option<u32> {
None
}
fn raw_sample_count(&self, stream: usize) -> u64 {
self.sample_count(stream)
}
fn raw_sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo> {
self.sample_info(stream, index)
}
fn read_raw_sample(&mut self, stream: usize, index: u64) -> Result<Packet> {
self.read_sample(stream, index)
}
fn sample_source(&mut self) -> Option<std::sync::Arc<dyn SampleSource>> {
None
}
}
pub trait SampleSource: Send + Sync {
fn sample_count(&self, stream: usize) -> u64;
fn sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo>;
fn read_sample(&self, stream: usize, index: u64) -> Result<Packet>;
fn sync_at_or_before(&self, stream: usize, pts: i64) -> Option<u64>;
fn edit_list(&self, _stream: usize) -> &[EditEntry] {
&[]
}
fn movie_timescale(&self) -> Option<u32> {
None
}
fn raw_sample_count(&self, stream: usize) -> u64 {
self.sample_count(stream)
}
fn raw_sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo> {
self.sample_info(stream, index)
}
fn read_raw_sample(&self, stream: usize, index: u64) -> Result<Packet> {
self.read_sample(stream, index)
}
}
#[derive(Clone)]
pub struct SharedInput {
inner: std::sync::Arc<std::sync::Mutex<(SeekInput, Option<u64>)>>,
pos: u64,
}
impl SharedInput {
pub fn new(mut input: SeekInput) -> SharedInput {
let pos = input.stream_position().unwrap_or(0);
SharedInput {
inner: std::sync::Arc::new(std::sync::Mutex::new((input, Some(pos)))),
pos,
}
}
}
type SharedState = std::sync::Mutex<(SeekInput, Option<u64>)>;
fn lock_shared(
inner: &SharedState,
) -> std::io::Result<std::sync::MutexGuard<'_, (SeekInput, Option<u64>)>> {
inner
.lock()
.map_err(|_| std::io::Error::other("shared input poisoned"))
}
impl Read for SharedInput {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut g = lock_shared(&self.inner)?;
let (input, at) = &mut *g;
if *at != Some(self.pos) {
*at = None;
input.seek(std::io::SeekFrom::Start(self.pos))?;
}
let n = input.read(buf)?;
self.pos += n as u64;
*at = Some(self.pos);
Ok(n)
}
}
impl Seek for SharedInput {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
let invalid = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek before start");
self.pos = match pos {
std::io::SeekFrom::Start(n) => n,
std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).ok_or_else(invalid)?,
std::io::SeekFrom::End(d) => {
let mut g = lock_shared(&self.inner)?;
let (input, at) = &mut *g;
let end = input.seek(std::io::SeekFrom::End(0))?;
*at = Some(end);
end.checked_add_signed(d).ok_or_else(invalid)?
}
};
Ok(self.pos)
}
}
pub trait Muxer: Send {
fn set_metadata(&mut self, _metadata: &Dictionary) {}
fn set_stream_metadata(&mut self, _index: usize, _metadata: &Dictionary) {}
fn set_option(&mut self, _key: &str, _value: &str) -> bool {
false
}
fn set_edit_list(&mut self, _stream: usize, _edits: &[EditEntry]) -> bool {
false
}
fn write_header(&mut self, streams: &[Stream]) -> Result<()>;
fn write_packet(&mut self, packet: &Packet) -> Result<()>;
fn write_trailer(&mut self) -> Result<()>;
}
pub type DemuxerFactory = fn(Input) -> Box<dyn Demuxer>;
pub type SeekableDemuxerFactory = fn(SeekInput) -> Box<dyn Demuxer>;
pub type MuxerFactory = fn(Output) -> Box<dyn Muxer>;
pub type SeekableMuxerFactory = fn(SeekOutput) -> Box<dyn Muxer>;
pub type PathMuxerFactory = fn(&std::path::Path, &Dictionary) -> Result<Box<dyn Muxer>>;
pub type ProbeFn = fn(&[u8]) -> i32;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MuxCaps {
pub codecs: &'static [CodecId],
pub max_streams: Option<usize>,
pub still_image: bool,
}
impl MuxCaps {
pub const NONE: MuxCaps = MuxCaps {
codecs: &[],
max_streams: Some(0),
still_image: false,
};
pub const fn container(codecs: &'static [CodecId]) -> MuxCaps {
MuxCaps {
codecs,
max_streams: None,
still_image: false,
}
}
pub const fn single(codecs: &'static [CodecId]) -> MuxCaps {
MuxCaps {
codecs,
max_streams: Some(1),
still_image: false,
}
}
pub const fn image(self) -> MuxCaps {
MuxCaps {
codecs: self.codecs,
max_streams: self.max_streams,
still_image: true,
}
}
pub fn accepts(&self, id: CodecId) -> bool {
self.codecs.contains(&id)
}
pub fn accepts_media(&self, media: MediaType) -> bool {
self.codecs.iter().any(|c| c.media_type() == media)
}
pub fn codecs_for(&self, media: MediaType) -> impl Iterator<Item = CodecId> + '_ {
self.codecs
.iter()
.copied()
.filter(move |c| c.media_type() == media)
}
}
pub struct Format {
pub name: &'static str,
pub long_name: &'static str,
pub extensions: &'static [&'static str],
pub demuxer: Option<DemuxerFactory>,
pub muxer: Option<MuxerFactory>,
pub muxer_path: Option<PathMuxerFactory>,
pub probe: Option<ProbeFn>,
pub mux_caps: MuxCaps,
}
impl Format {
pub fn can_demux(&self) -> bool {
self.demuxer.is_some()
}
pub fn can_mux(&self) -> bool {
self.muxer.is_some() || self.muxer_path.is_some()
}
}
#[derive(Default)]
pub struct FormatRegistry {
by_name: HashMap<&'static str, Format>,
seekable: HashMap<&'static str, SeekableDemuxerFactory>,
seekable_muxers: HashMap<&'static str, SeekableMuxerFactory>,
}
impl FormatRegistry {
pub fn new() -> FormatRegistry {
FormatRegistry::default()
}
pub fn register(&mut self, format: Format) {
self.by_name.insert(format.name, format);
}
pub fn register_seekable_demuxer(
&mut self,
name: &'static str,
factory: SeekableDemuxerFactory,
) {
self.seekable.insert(name, factory);
}
pub fn by_name(&self, name: &str) -> Option<&Format> {
self.by_name.get(name)
}
pub fn by_extension(&self, ext: &str) -> Option<&Format> {
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
self.by_name
.values()
.find(|f| f.extensions.iter().any(|e| e.eq_ignore_ascii_case(&ext)))
}
pub fn probe(&self, data: &[u8]) -> Option<&Format> {
self.by_name
.values()
.filter_map(|f| f.probe.map(|p| (p(data), f)))
.filter(|(score, _)| *score > 0)
.max_by_key(|(score, _)| *score)
.map(|(_, f)| f)
}
pub fn open_demuxer(&self, name: &str, input: Input) -> Result<Box<dyn Demuxer>> {
self.by_name
.get(name)
.and_then(|f| f.demuxer)
.map(|factory| factory(input))
.ok_or_else(|| Error::DemuxerNotFound(name.to_string()))
}
pub fn open_demuxer_seekable(&self, name: &str, input: SeekInput) -> Result<Box<dyn Demuxer>> {
if !self.by_name.get(name).is_some_and(Format::can_demux) {
return Err(Error::DemuxerNotFound(name.to_string()));
}
match self.seekable.get(name) {
Some(factory) => Ok(factory(input)),
None => self.open_demuxer(name, input),
}
}
pub fn register_seekable_muxer(&mut self, name: &'static str, factory: SeekableMuxerFactory) {
self.seekable_muxers.insert(name, factory);
}
pub fn open_muxer_seekable(&self, name: &str, output: SeekOutput) -> Result<Box<dyn Muxer>> {
if self.by_name.get(name).is_none_or(|f| f.muxer.is_none()) {
return Err(Error::MuxerNotFound(name.to_string()));
}
match self.seekable_muxers.get(name) {
Some(factory) => Ok(factory(output)),
None => self.open_muxer(name, output),
}
}
pub fn open_muxer(&self, name: &str, output: Output) -> Result<Box<dyn Muxer>> {
self.by_name
.get(name)
.and_then(|f| f.muxer)
.map(|factory| factory(output))
.ok_or_else(|| Error::MuxerNotFound(name.to_string()))
}
pub fn iter(&self) -> impl Iterator<Item = &Format> {
self.by_name.values()
}
pub fn len(&self) -> usize {
self.by_name.len()
}
pub fn is_empty(&self) -> bool {
self.by_name.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
struct Tagged(usize);
impl Demuxer for Tagged {
fn read_header(&mut self) -> Result<Vec<Stream>> {
Ok((0..self.0).map(|i| Stream::new(i, CodecId::None)).collect())
}
fn read_packet(&mut self) -> Result<rff_core::Packet> {
Err(Error::Eof)
}
}
fn format(name: &'static str) -> Format {
Format {
name,
long_name: name,
extensions: &[],
demuxer: Some(|_| Box::new(Tagged(1))),
muxer: None,
muxer_path: None,
probe: None,
mux_caps: MuxCaps::NONE,
}
}
fn streams(mut d: Box<dyn Demuxer>) -> usize {
d.read_header().unwrap().len()
}
#[test]
fn shared_input_handles_keep_their_own_positions() {
let data: Vec<u8> = (0..=255).collect();
let mut a = SharedInput::new(Box::new(Cursor::new(data)));
let mut b = a.clone();
b.seek(std::io::SeekFrom::Start(200)).unwrap();
let mut x = [0u8; 3];
a.read_exact(&mut x).unwrap();
assert_eq!(x, [0, 1, 2]);
b.read_exact(&mut x).unwrap();
assert_eq!(x, [200, 201, 202]);
a.read_exact(&mut x).unwrap();
assert_eq!(x, [3, 4, 5]);
assert_eq!(b.seek(std::io::SeekFrom::End(-1)).unwrap(), 255);
let t = std::thread::spawn(move || {
let mut y = [0u8; 1];
b.read_exact(&mut y).unwrap();
y[0]
});
assert_eq!(t.join().unwrap(), 255);
}
#[test]
fn rotation_matrices_round_trip() {
for deg in [0.0, 90.0, 180.0, 270.0, 30.0, 315.0] {
let m = rotation_matrix(deg, 1920, 1080);
assert_eq!(matrix_rotation(&m), Some(deg), "{deg}");
}
let m = rotation_matrix(-270.0, 1920, 1080);
assert_eq!(m, [0, 0x10000, 0, -0x10000, 0, 0, 1080 << 16, 0, 1 << 30]);
let flip = [-0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 1 << 30];
assert_eq!(matrix_rotation(&flip), None);
let mut s = Stream::new(0, CodecId::H264);
(s.width, s.height) = (640, 480);
assert_eq!(s.rotation(), Some(0.0));
s.set_rotation(90.0);
assert_eq!(s.rotation(), Some(90.0));
s.set_rotation(360.0);
assert_eq!(s.display_matrix, None);
}
#[test]
fn seekable_open_prefers_the_seekable_factory_and_falls_back() {
let mut r = FormatRegistry::new();
r.register(format("plain"));
r.register(format("seeky"));
r.register_seekable_demuxer("seeky", |_| Box::new(Tagged(2)));
let input = || -> SeekInput { Box::new(Cursor::new(vec![0u8; 4])) };
assert_eq!(
streams(r.open_demuxer_seekable("seeky", input()).unwrap()),
2
);
assert_eq!(
streams(r.open_demuxer_seekable("plain", input()).unwrap()),
1
);
assert_eq!(
streams(
r.open_demuxer("seeky", Box::new(Cursor::new(vec![])))
.unwrap()
),
1
);
assert!(matches!(
r.open_demuxer_seekable("missing", input()),
Err(Error::DemuxerNotFound(_))
));
}
struct TaggedMux(&'static str);
impl Muxer for TaggedMux {
fn write_header(&mut self, _: &[Stream]) -> Result<()> {
Ok(())
}
fn write_packet(&mut self, _: &rff_core::Packet) -> Result<()> {
Ok(())
}
fn write_trailer(&mut self) -> Result<()> {
Err(Error::invalid(self.0))
}
}
fn tag(mut m: Box<dyn Muxer>) -> String {
m.write_trailer().unwrap_err().to_string()
}
#[test]
fn seekable_muxer_open_prefers_the_seekable_factory_and_falls_back() {
let mut r = FormatRegistry::new();
let with_muxer = |name| Format {
muxer: Some(|_| Box::new(TaggedMux("plain"))),
..format(name)
};
r.register(with_muxer("plain"));
r.register(with_muxer("seeky"));
r.register(format("demux_only"));
r.register_seekable_muxer("seeky", |_| Box::new(TaggedMux("seekable")));
let output = || -> SeekOutput { Box::new(Cursor::new(Vec::new())) };
assert!(tag(r.open_muxer_seekable("seeky", output()).unwrap()).contains("seekable"));
assert!(tag(r.open_muxer_seekable("plain", output()).unwrap()).contains("plain"));
assert!(tag(r.open_muxer("seeky", Box::new(Vec::new())).unwrap()).contains("plain"));
assert!(matches!(
r.open_muxer_seekable("demux_only", output()),
Err(Error::MuxerNotFound(_))
));
assert!(matches!(
r.open_muxer_seekable("missing", output()),
Err(Error::MuxerNotFound(_))
));
}
}