diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ff8d01fd --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +target/ +fixtures/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..eeffe8cd --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ec-core" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..d424d8e1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[workspace] +resolver = "3" +members = ["crates/*", "shims/*", "tools/*"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MIT OR Apache-2.0" +authors = ["Ahmet Kaan Gümüş"] + +[workspace.dependencies] +ec-core = { path = "crates/ec-core", version = "0.1.0" } +# Portable SIMD without asm or build-time tooling (family rule: pure Rust only). +wide = "1.5" + +[profile.release] +opt-level = 3 diff --git a/crates/ec-core/Cargo.toml b/crates/ec-core/Cargo.toml new file mode 100644 index 00000000..ae6c484b --- /dev/null +++ b/crates/ec-core/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "ec-core" +description = "Media IR shared by the edith_codecs family: packets, frames, rational time, bit I/O, codec contracts." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] diff --git a/crates/ec-core/src/bitio.rs b/crates/ec-core/src/bitio.rs new file mode 100644 index 00000000..ce5ac10b --- /dev/null +++ b/crates/ec-core/src/bitio.rs @@ -0,0 +1,594 @@ +//! Bit-level readers and writers shared by every parser in the family. +//! +//! Two orders: MSB-first ([`BitReader`], [`BitWriter`]) for the MPEG/ITU +//! bitstreams and FLAC, LSB-first ([`BitReaderLsb`], [`BitWriterLsb`]) for the +//! Xiph formats. Readers never panic on truncated input — a short buffer is +//! [`Error::NeedMore`], which is also the streaming "feed me more" contract. + +use crate::error::{Error, Result}; + +/// MSB-first bit reader over a borrowed buffer. +#[derive(Debug, Clone)] +pub struct BitReader<'a> { + data: &'a [u8], + pos: u64, +} + +impl<'a> BitReader<'a> { + /// A reader positioned at the first bit of `data`. + pub fn new(data: &'a [u8]) -> BitReader<'a> { + BitReader { data, pos: 0 } + } + + /// Bits consumed so far. + pub fn bit_position(&self) -> u64 { + self.pos + } + + /// Bits left in the buffer. + pub fn bits_remaining(&self) -> u64 { + (self.data.len() as u64 * 8).saturating_sub(self.pos) + } + + /// True when the next bit starts a byte. + pub fn is_byte_aligned(&self) -> bool { + self.pos.is_multiple_of(8) + } + + /// Skip to the next byte boundary; no-op when already aligned. + pub fn align_to_byte(&mut self) { + self.pos = self.pos.div_ceil(8) * 8; + } + + /// Read `n` bits (`n <= 64`) into a `u64`. + /// + /// Panics if `n > 64` (a coding error, not an input error). + pub fn read_bits64(&mut self, n: u32) -> Result { + assert!(n <= 64, "read_bits64: n = {n} > 64"); + if self.bits_remaining() < n as u64 { + return Err(Error::NeedMore); + } + let mut value = 0u64; + let mut left = n; + while left > 0 { + let byte = self.data[(self.pos >> 3) as usize]; + let bit_off = (self.pos & 7) as u32; + let take = left.min(8 - bit_off); + let chunk = (byte << bit_off) >> (8 - take); + value = (value << take) | chunk as u64; + self.pos += take as u64; + left -= take; + } + Ok(value) + } + + /// Read `n` bits (`n <= 32`) into a `u32`. + pub fn read_bits(&mut self, n: u32) -> Result { + assert!(n <= 32, "read_bits: n = {n} > 32"); + Ok(self.read_bits64(n)? as u32) + } + + /// Read `n` bits as a two's-complement signed value (`1 <= n <= 32`). + pub fn read_signed(&mut self, n: u32) -> Result { + assert!((1..=32).contains(&n), "read_signed: n = {n} outside 1..=32"); + let raw = self.read_bits(n)?; + Ok(((raw << (32 - n)) as i32) >> (32 - n)) + } + + /// Read one bit. + pub fn read_bit(&mut self) -> Result { + Ok(self.read_bits64(1)? != 0) + } + + /// Read `n` bits without consuming them. + pub fn peek_bits(&mut self, n: u32) -> Result { + let saved = self.pos; + let v = self.read_bits(n); + self.pos = saved; + v + } + + /// Skip `n` bits, or [`Error::NeedMore`] if fewer remain. + pub fn skip_bits(&mut self, n: u64) -> Result<()> { + if self.bits_remaining() < n { + return Err(Error::NeedMore); + } + self.pos += n; + Ok(()) + } + + /// Borrow `n` whole bytes from the current position, which must be aligned. + pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> { + if !self.is_byte_aligned() { + return Err(Error::corrupt("read_bytes at a non-byte-aligned position")); + } + let start = (self.pos >> 3) as usize; + let end = start.checked_add(n).ok_or(Error::NeedMore)?; + let slice = self.data.get(start..end).ok_or(Error::NeedMore)?; + self.pos += n as u64 * 8; + Ok(slice) + } + + /// Unsigned exp-Golomb `ue(v)`, as used by H.264 and H.265. + /// + /// The prefix is capped at 31 zero bits: 32 or more cannot encode a value + /// in `u32` range, so it is a corrupt bitstream (and, on a fuzzer's input, + /// the difference between an error and an unbounded loop). + pub fn read_ue(&mut self) -> Result { + let mut zeros = 0u32; + while !self.read_bit()? { + zeros += 1; + if zeros > 31 { + return Err(Error::corrupt("exp-Golomb prefix longer than 31 zero bits")); + } + } + if zeros == 0 { + return Ok(0); + } + let suffix = self.read_bits(zeros)?; + Ok((1u32 << zeros) - 1 + suffix) + } + + /// Signed exp-Golomb `se(v)`. + pub fn read_se(&mut self) -> Result { + let k = self.read_ue()? as i64; + let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) }; + i32::try_from(v).map_err(|_| Error::corrupt(format!("se(v) out of i32 range: {v}"))) + } +} + +/// MSB-first bit writer. +#[derive(Debug, Clone, Default)] +pub struct BitWriter { + buf: Vec, + /// Bits already written into the last byte of `buf` (0 means byte aligned). + used: u32, +} + +impl BitWriter { + /// An empty writer. + pub fn new() -> BitWriter { + BitWriter::default() + } + + /// An empty writer with room for `bytes`. + pub fn with_capacity(bytes: usize) -> BitWriter { + BitWriter { + buf: Vec::with_capacity(bytes), + used: 0, + } + } + + /// Bits written so far. + pub fn bit_len(&self) -> u64 { + if self.used == 0 { + self.buf.len() as u64 * 8 + } else { + (self.buf.len() as u64 - 1) * 8 + self.used as u64 + } + } + + /// True when the next bit would start a byte. + pub fn is_byte_aligned(&self) -> bool { + self.used == 0 + } + + /// Write the low `n` bits of `value` (`n <= 64`), most significant first. + pub fn write_bits64(&mut self, value: u64, n: u32) { + assert!(n <= 64, "write_bits64: n = {n} > 64"); + for i in (0..n).rev() { + self.write_bit(value >> i & 1 == 1); + } + } + + /// Write the low `n` bits of `value` (`n <= 32`), most significant first. + pub fn write_bits(&mut self, value: u32, n: u32) { + assert!(n <= 32, "write_bits: n = {n} > 32"); + self.write_bits64(value as u64, n); + } + + /// Write a two's-complement signed value in `n` bits (`1 <= n <= 32`). + pub fn write_signed(&mut self, value: i32, n: u32) { + assert!( + (1..=32).contains(&n), + "write_signed: n = {n} outside 1..=32" + ); + self.write_bits((value as u32) & (u32::MAX >> (32 - n)), n); + } + + /// Write one bit. + pub fn write_bit(&mut self, bit: bool) { + if self.used == 0 { + self.buf.push(0); + } + if bit { + let last = self.buf.len() - 1; + self.buf[last] |= 0x80 >> self.used; + } + self.used = (self.used + 1) % 8; + } + + /// Pad with zero bits up to the next byte boundary. + pub fn align_to_byte(&mut self) { + while self.used != 0 { + self.write_bit(false); + } + } + + /// Unsigned exp-Golomb `ue(v)`. + /// + /// Panics on `u32::MAX`, which has no exp-Golomb form that reads back into + /// `u32`; no codec in the family emits it. + pub fn write_ue(&mut self, value: u32) { + assert!(value != u32::MAX, "write_ue: u32::MAX is not encodable"); + let x = value as u64 + 1; + let bits = 64 - x.leading_zeros(); + self.write_bits64(0, bits - 1); + self.write_bits64(x, bits); + } + + /// Signed exp-Golomb `se(v)`. + pub fn write_se(&mut self, value: i32) { + let k = if value > 0 { + 2 * value as i64 - 1 + } else { + -2 * value as i64 + }; + let k = u32::try_from(k).expect("se(v) out of exp-Golomb range"); + self.write_ue(k); + } + + /// Append whole bytes; the writer must be byte aligned. + /// + /// Panics when misaligned — call [`BitWriter::align_to_byte`] first. + pub fn write_bytes(&mut self, bytes: &[u8]) { + assert!(self.is_byte_aligned(), "write_bytes while not byte aligned"); + self.buf.extend_from_slice(bytes); + } + + /// The bytes written so far; a trailing partial byte is zero padded. + pub fn as_bytes(&self) -> &[u8] { + &self.buf + } + + /// Consume the writer, returning its bytes. + pub fn into_bytes(self) -> Vec { + self.buf + } +} + +/// LSB-first bit reader (Vorbis, and other Xiph-family bitstreams). +#[derive(Debug, Clone)] +pub struct BitReaderLsb<'a> { + data: &'a [u8], + pos: u64, +} + +impl<'a> BitReaderLsb<'a> { + /// A reader positioned at the first bit of `data`. + pub fn new(data: &'a [u8]) -> BitReaderLsb<'a> { + BitReaderLsb { data, pos: 0 } + } + + /// Bits consumed so far. + pub fn bit_position(&self) -> u64 { + self.pos + } + + /// Bits left in the buffer. + pub fn bits_remaining(&self) -> u64 { + (self.data.len() as u64 * 8).saturating_sub(self.pos) + } + + /// True when the next bit starts a byte. + pub fn is_byte_aligned(&self) -> bool { + self.pos.is_multiple_of(8) + } + + /// Skip to the next byte boundary; no-op when already aligned. + pub fn align_to_byte(&mut self) { + self.pos = self.pos.div_ceil(8) * 8; + } + + /// Read `n` bits (`n <= 64`), least significant bit first. + pub fn read_bits64(&mut self, n: u32) -> Result { + assert!(n <= 64, "read_bits64: n = {n} > 64"); + if self.bits_remaining() < n as u64 { + return Err(Error::NeedMore); + } + let mut value = 0u64; + let mut got = 0u32; + while got < n { + let byte = self.data[(self.pos >> 3) as usize]; + let bit_off = (self.pos & 7) as u32; + let take = (n - got).min(8 - bit_off); + let mask = ((1u16 << take) - 1) as u8; + let chunk = (byte >> bit_off) & mask; + value |= (chunk as u64) << got; + self.pos += take as u64; + got += take; + } + Ok(value) + } + + /// Read `n` bits (`n <= 32`), least significant bit first. + pub fn read_bits(&mut self, n: u32) -> Result { + assert!(n <= 32, "read_bits: n = {n} > 32"); + Ok(self.read_bits64(n)? as u32) + } + + /// Read one bit. + pub fn read_bit(&mut self) -> Result { + Ok(self.read_bits64(1)? != 0) + } + + /// Skip `n` bits, or [`Error::NeedMore`] if fewer remain. + pub fn skip_bits(&mut self, n: u64) -> Result<()> { + if self.bits_remaining() < n { + return Err(Error::NeedMore); + } + self.pos += n; + Ok(()) + } +} + +/// LSB-first bit writer. +#[derive(Debug, Clone, Default)] +pub struct BitWriterLsb { + buf: Vec, + used: u32, +} + +impl BitWriterLsb { + /// An empty writer. + pub fn new() -> BitWriterLsb { + BitWriterLsb::default() + } + + /// Bits written so far. + pub fn bit_len(&self) -> u64 { + if self.used == 0 { + self.buf.len() as u64 * 8 + } else { + (self.buf.len() as u64 - 1) * 8 + self.used as u64 + } + } + + /// True when the next bit would start a byte. + pub fn is_byte_aligned(&self) -> bool { + self.used == 0 + } + + /// Write the low `n` bits of `value` (`n <= 64`), least significant first. + pub fn write_bits64(&mut self, value: u64, n: u32) { + assert!(n <= 64, "write_bits64: n = {n} > 64"); + for i in 0..n { + self.write_bit(value >> i & 1 == 1); + } + } + + /// Write the low `n` bits of `value` (`n <= 32`), least significant first. + pub fn write_bits(&mut self, value: u32, n: u32) { + assert!(n <= 32, "write_bits: n = {n} > 32"); + self.write_bits64(value as u64, n); + } + + /// Write one bit. + pub fn write_bit(&mut self, bit: bool) { + if self.used == 0 { + self.buf.push(0); + } + if bit { + let last = self.buf.len() - 1; + self.buf[last] |= 1 << self.used; + } + self.used = (self.used + 1) % 8; + } + + /// Pad with zero bits up to the next byte boundary. + pub fn align_to_byte(&mut self) { + while self.used != 0 { + self.write_bit(false); + } + } + + /// The bytes written so far; a trailing partial byte is zero padded. + pub fn as_bytes(&self) -> &[u8] { + &self.buf + } + + /// Consume the writer, returning its bytes. + pub fn into_bytes(self) -> Vec { + self.buf + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn msb_round_trip_mixed_widths() { + let widths = [1u32, 2, 3, 5, 7, 8, 9, 13, 16, 17, 24, 31, 32]; + let mut w = BitWriter::new(); + let mut values = Vec::new(); + for (i, &n) in widths.iter().enumerate() { + let v = if n == 32 { + u32::MAX + } else { + ((0xDEAD_BEEFu64 >> i) as u32) & (u32::MAX >> (32 - n)) + }; + values.push(v); + w.write_bits(v, n); + } + let bits = w.bit_len(); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + for (&n, &v) in widths.iter().zip(&values) { + assert_eq!(r.read_bits(n).unwrap(), v, "width {n}"); + } + assert_eq!(r.bit_position(), bits); + } + + #[test] + fn msb_bit_order_is_most_significant_first() { + let mut w = BitWriter::new(); + w.write_bits(0b101, 3); + w.align_to_byte(); + assert_eq!(w.as_bytes(), &[0b1010_0000]); + let mut r = BitReader::new(&[0b1010_0000]); + assert!(r.read_bit().unwrap()); + assert!(!r.read_bit().unwrap()); + assert!(r.read_bit().unwrap()); + assert!(!r.is_byte_aligned()); + r.align_to_byte(); + assert!(r.is_byte_aligned()); + assert_eq!(r.bits_remaining(), 0); + } + + #[test] + fn exp_golomb_round_trip_including_edges() { + // 0 is a single '1' bit; the top of the range is 31 zeros + suffix. + let values = [ + 0u32, + 1, + 2, + 3, + 255, + 256, + 65_535, + (1 << 31) - 2, + (1 << 31) - 1, + u32::MAX - 2, + u32::MAX - 1, + ]; + for &v in &values { + let mut w = BitWriter::new(); + w.write_ue(v); + let bits = w.bit_len(); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.read_ue().unwrap(), v, "ue({v})"); + assert_eq!(r.bit_position(), bits, "ue({v}) length"); + } + let mut w = BitWriter::new(); + w.write_ue(0); + w.align_to_byte(); + assert_eq!(w.as_bytes(), &[0b1000_0000]); + } + + #[test] + fn signed_exp_golomb_round_trip() { + for v in [ + 0i32, + 1, + -1, + 2, + -2, + 1000, + -1000, + i32::MAX / 2, + -(i32::MAX / 2), + ] { + let mut w = BitWriter::new(); + w.write_se(v); + let bytes = w.into_bytes(); + assert_eq!(BitReader::new(&bytes).read_se().unwrap(), v, "se({v})"); + } + } + + #[test] + fn truncation_is_need_more_never_panic() { + let mut r = BitReader::new(&[0xFF, 0xFF]); + assert!(r.read_bits(16).is_ok()); + assert!(r.read_bits(1).unwrap_err().is_need_more()); + assert!(BitReader::new(&[]).read_bit().unwrap_err().is_need_more()); + assert!( + BitReader::new(&[0x80]) + .read_bits(9) + .unwrap_err() + .is_need_more() + ); + // A ue() whose suffix is cut off, and one with no terminating 1 bit. + assert!( + BitReader::new(&[0x01]) + .read_ue() + .unwrap_err() + .is_need_more() + ); + assert!( + BitReader::new(&[0x00, 0x00]) + .read_ue() + .unwrap_err() + .is_need_more() + ); + // 32+ zero bits before the 1: corrupt, not an infinite scan. + let long = [0u8, 0, 0, 0, 0x80]; + let err = BitReader::new(&long).read_ue().unwrap_err(); + assert!(matches!(err, Error::Corrupt { .. }), "{err}"); + } + + #[test] + fn signed_fixed_width_and_bytes() { + let mut w = BitWriter::new(); + w.write_signed(-3, 8); + w.write_signed(7, 5); + w.align_to_byte(); + w.write_bytes(&[0xAB, 0xCD]); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.read_signed(8).unwrap(), -3); + assert_eq!(r.read_signed(5).unwrap(), 7); + r.align_to_byte(); + assert_eq!(r.read_bytes(2).unwrap(), &[0xAB, 0xCD]); + assert!(r.read_bytes(1).unwrap_err().is_need_more()); + // Misaligned byte reads are refused rather than silently realigned. + let mut r = BitReader::new(&bytes); + r.read_bit().unwrap(); + assert!(matches!(r.read_bytes(1), Err(Error::Corrupt { .. }))); + } + + #[test] + fn peek_and_skip_do_not_diverge() { + let mut r = BitReader::new(&[0b1011_0010, 0xFF]); + assert_eq!(r.peek_bits(4).unwrap(), 0b1011); + assert_eq!(r.bit_position(), 0); + r.skip_bits(4).unwrap(); + assert_eq!(r.read_bits(4).unwrap(), 0b0010); + assert!(r.skip_bits(9).is_err()); + assert_eq!(r.bits_remaining(), 8); + } + + #[test] + fn lsb_round_trip_and_order() { + let mut w = BitWriterLsb::new(); + w.write_bits(0b101, 3); + w.align_to_byte(); + assert_eq!(w.as_bytes(), &[0b0000_0101]); + + let widths = [1u32, 4, 7, 11, 16, 32]; + let mut w = BitWriterLsb::new(); + let mut values = Vec::new(); + for (i, &n) in widths.iter().enumerate() { + let v = ((0xCAFE_F00Du64 >> i) as u32) & (u32::MAX >> (32 - n)); + values.push(v); + w.write_bits(v, n); + } + let bytes = w.into_bytes(); + let mut r = BitReaderLsb::new(&bytes); + for (&n, &v) in widths.iter().zip(&values) { + assert_eq!(r.read_bits(n).unwrap(), v, "lsb width {n}"); + } + assert_eq!(r.bits_remaining(), 1); // 71 bits written, padded to 9 bytes + } + + #[test] + fn lsb_truncation_is_need_more() { + let mut r = BitReaderLsb::new(&[0x0F]); + assert_eq!(r.read_bits(4).unwrap(), 0x0F); + assert!(r.read_bits(5).unwrap_err().is_need_more()); + assert!(r.skip_bits(5).is_err()); + r.align_to_byte(); + assert_eq!(r.bits_remaining(), 0); + } +} diff --git a/crates/ec-core/src/error.rs b/crates/ec-core/src/error.rs new file mode 100644 index 00000000..189dea8b --- /dev/null +++ b/crates/ec-core/src/error.rs @@ -0,0 +1,89 @@ +//! Family-wide error type. + +use std::fmt; + +/// Result alias used by every crate in the family. +pub type Result = std::result::Result; + +/// Everything that can go wrong in a demuxer, decoder, encoder or muxer. +/// +/// The taxonomy is deliberately small: callers branch on "give me more data" +/// (`NeedMore`), "the stream ended" (`Eof`), "this input is broken" (`Corrupt`) +/// and "we do not implement this" (`Unsupported`). Every `Unsupported` carries +/// both *what* was refused and *why* — a refusal string without a reason is a +/// bug report waiting to happen, not a diagnosis. +#[derive(Debug)] +pub enum Error { + /// Not enough data buffered yet; feed more and retry the same call. + NeedMore, + /// End of stream reached; no further data will ever arrive. + Eof, + /// A capability this build genuinely does not have. + Unsupported { + /// The construct that was refused, e.g. "HE-AAC SBR". + what: String, + /// Why it is refused, e.g. "SBR resampler not implemented". + why: String, + }, + /// The bitstream violates its own format rules. + Corrupt { + /// Where and how, e.g. "H.264 SPS: log2_max_frame_num_minus4 = 13". + context: String, + }, + /// Underlying I/O failure. + Io(std::io::Error), +} + +impl Error { + /// Build an [`Error::Unsupported`] from any two string-likes. + pub fn unsupported(what: impl Into, why: impl Into) -> Self { + Error::Unsupported { + what: what.into(), + why: why.into(), + } + } + + /// Build an [`Error::Corrupt`] from any string-like. + pub fn corrupt(context: impl Into) -> Self { + Error::Corrupt { + context: context.into(), + } + } + + /// True for [`Error::NeedMore`] — the streaming "try again later" contract. + pub fn is_need_more(&self) -> bool { + matches!(self, Error::NeedMore) + } + + /// True for [`Error::Eof`]. + pub fn is_eof(&self) -> bool { + matches!(self, Error::Eof) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NeedMore => write!(f, "need more data"), + Error::Eof => write!(f, "end of stream"), + Error::Unsupported { what, why } => write!(f, "unsupported: {what} ({why})"), + Error::Corrupt { context } => write!(f, "corrupt bitstream: {context}"), + Error::Io(e) => write!(f, "io error: {e}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} diff --git a/crates/ec-core/src/frame.rs b/crates/ec-core/src/frame.rs new file mode 100644 index 00000000..acbe90e1 --- /dev/null +++ b/crates/ec-core/src/frame.rs @@ -0,0 +1,603 @@ +//! Decoded units: pictures and audio blocks. + +use crate::error::{Error, Result}; +use crate::packet::Buf; +use crate::timebase::Timestamp; + +/// Pixel layout of a [`VideoFrame`]. +/// +/// Covers what the family actually moves: planar YUV 8/10/16-bit (software +/// codecs), the semi-planar pairs hardware hands back (NV12, P010) and packed +/// RGB for the display sink. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PixelFormat { + /// Planar Y/U/V 4:2:0, 8-bit. + I420, + /// Planar Y/U/V 4:2:2, 8-bit. + I422, + /// Planar Y/U/V 4:4:4, 8-bit. + I444, + /// Planar Y/U/V 4:2:0, 10-bit in 16-bit little-endian samples. + I010, + /// Planar Y/U/V 4:2:2, 10-bit in 16-bit little-endian samples. + I210, + /// Planar Y/U/V 4:4:4, 10-bit in 16-bit little-endian samples. + I410, + /// Y plane + interleaved U/V, 4:2:0, 8-bit. + Nv12, + /// Y plane + interleaved V/U, 4:2:0, 8-bit. + Nv21, + /// Y plane + interleaved U/V, 4:2:0, 10-bit in the high bits of 16. + P010, + /// Y plane + interleaved U/V, 4:2:0, 16-bit. + P016, + /// Single 8-bit luma plane. + Gray8, + /// Single 16-bit luma plane. + Gray16, + /// Packed 8-bit R,G,B. + Rgb8, + /// Packed 8-bit B,G,R. + Bgr8, + /// Packed 8-bit R,G,B,A. + Rgba8, + /// Packed 8-bit B,G,R,A — edith's display currency. + Bgra8, +} + +impl PixelFormat { + /// Number of planes the format stores. + pub fn plane_count(&self) -> usize { + use PixelFormat::*; + match self { + I420 | I422 | I444 | I010 | I210 | I410 => 3, + Nv12 | Nv21 | P010 | P016 => 2, + Gray8 | Gray16 | Rgb8 | Bgr8 | Rgba8 | Bgra8 => 1, + } + } + + /// True when chroma lives in its own plane(s) rather than packed with luma. + pub fn is_planar(&self) -> bool { + self.plane_count() > 1 + } + + /// True for the YUV families (planar and semi-planar). + pub fn is_yuv(&self) -> bool { + use PixelFormat::*; + matches!( + self, + I420 | I422 | I444 | I010 | I210 | I410 | Nv12 | Nv21 | P010 | P016 + ) + } + + /// True when the format carries an alpha channel. + pub fn has_alpha(&self) -> bool { + matches!(self, PixelFormat::Rgba8 | PixelFormat::Bgra8) + } + + /// Significant bits per component (10 for P010 even though it stores 16). + pub fn bits_per_component(&self) -> u32 { + use PixelFormat::*; + match self { + I010 | I210 | I410 | P010 => 10, + Gray16 | P016 => 16, + _ => 8, + } + } + + /// Storage bytes per component (2 for every 10- and 16-bit format). + pub fn bytes_per_component(&self) -> usize { + if self.bits_per_component() > 8 { 2 } else { 1 } + } + + /// `(log2 horizontal, log2 vertical)` chroma subsampling; `(0, 0)` for + /// non-subsampled and non-YUV formats. + pub fn chroma_shift(&self) -> (u32, u32) { + use PixelFormat::*; + match self { + I420 | I010 | Nv12 | Nv21 | P010 | P016 => (1, 1), + I422 | I210 => (1, 0), + _ => (0, 0), + } + } + + /// Per plane: `(minimum bytes per row, number of rows)` for `width x height`. + pub fn plane_geometry(&self, width: u32, height: u32) -> Vec<(usize, usize)> { + use PixelFormat::*; + let (w, h) = (width as usize, height as usize); + let bpc = self.bytes_per_component(); + let (sx, sy) = self.chroma_shift(); + let cw = w.div_ceil(1 << sx); + let ch = h.div_ceil(1 << sy); + match self { + I420 | I422 | I444 | I010 | I210 | I410 => { + vec![(w * bpc, h), (cw * bpc, ch), (cw * bpc, ch)] + } + Nv12 | Nv21 | P010 | P016 => vec![(w * bpc, h), (cw * 2 * bpc, ch)], + Gray8 | Gray16 => vec![(w * bpc, h)], + Rgb8 | Bgr8 => vec![(w * 3, h)], + Rgba8 | Bgra8 => vec![(w * 4, h)], + } + } +} + +/// One image plane: bytes plus the distance between row starts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Plane { + /// Plane bytes; may be a shared slice of a larger buffer. + pub data: Buf, + /// Bytes from the start of one row to the start of the next. + pub stride: usize, +} + +impl Plane { + /// A plane over `data` with row pitch `stride`. + pub fn new(data: impl Into, stride: usize) -> Plane { + Plane { + data: data.into(), + stride, + } + } + + /// Row `y` of the plane, `len` bytes wide, or `None` when out of range. + pub fn row(&self, y: usize, len: usize) -> Option<&[u8]> { + let start = y.checked_mul(self.stride)?; + self.data.get(start..start.checked_add(len)?) + } +} + +/// CICP (ITU-T H.273) colour code points, carried verbatim. +/// +/// Kept as raw code points here so the IR never loses a value it cannot name; +/// the named tables (BT.709/2020, PQ, HLG, ...) live in the colour module built +/// on top of this. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ColorInfo { + /// `colour_primaries` code point (1 = BT.709, 9 = BT.2020, 2 = unspecified). + pub primaries: u8, + /// `transfer_characteristics` code point (16 = PQ, 18 = HLG). + pub transfer: u8, + /// `matrix_coefficients` code point (1 = BT.709, 9 = BT.2020 NCL). + pub matrix: u8, + /// `video_full_range_flag`: false = limited (16-235), true = full. + pub full_range: bool, +} + +impl Default for ColorInfo { + /// All three code points unspecified (2), limited range. + fn default() -> Self { + ColorInfo { + primaries: 2, + transfer: 2, + matrix: 2, + full_range: false, + } + } +} + +/// A decoded picture. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VideoFrame { + /// Pixel layout of `planes`. + pub format: PixelFormat, + /// Visible width in pixels. + pub width: u32, + /// Visible height in pixels. + pub height: u32, + /// One entry per [`PixelFormat::plane_count`]. + pub planes: Vec, + /// Colour description as signalled by the bitstream or container. + pub color: ColorInfo, + /// Presentation time, when the source provided one. + pub pts: Option, +} + +impl VideoFrame { + /// A frame over existing planes, validating plane count and plane sizes. + /// + /// This is the trust boundary between a decoder and everything that indexes + /// planes afterwards; a short plane fails here rather than in a converter. + pub fn try_new( + format: PixelFormat, + width: u32, + height: u32, + planes: Vec, + ) -> Result { + let geometry = format.plane_geometry(width, height); + if planes.len() != geometry.len() { + return Err(Error::corrupt(format!( + "{format:?} needs {} planes, got {}", + geometry.len(), + planes.len() + ))); + } + for (i, (plane, (row_bytes, rows))) in planes.iter().zip(geometry).enumerate() { + if plane.stride < row_bytes { + return Err(Error::corrupt(format!( + "plane {i}: stride {} < {row_bytes} bytes per row", + plane.stride + ))); + } + // The last row need only hold its visible bytes, not a full stride. + let needed = rows.saturating_sub(1) * plane.stride + row_bytes; + if plane.data.len() < needed { + return Err(Error::corrupt(format!( + "plane {i}: {} bytes for {rows} rows of stride {}", + plane.data.len(), + plane.stride + ))); + } + } + Ok(VideoFrame { + format, + width, + height, + planes, + color: ColorInfo::default(), + pts: None, + }) + } + + /// A zeroed frame with tightly packed planes. + pub fn alloc(format: PixelFormat, width: u32, height: u32) -> VideoFrame { + let planes = format + .plane_geometry(width, height) + .into_iter() + .map(|(row_bytes, rows)| Plane::new(vec![0u8; row_bytes * rows], row_bytes)) + .collect(); + VideoFrame { + format, + width, + height, + planes, + color: ColorInfo::default(), + pts: None, + } + } +} + +/// Sample storage of an [`AudioFrame`]. 24-bit sources decode into [`SampleFormat::S32`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SampleFormat { + /// Unsigned 8-bit. + U8, + /// Signed 16-bit native endian. + S16, + /// Signed 32-bit native endian. + S32, + /// 32-bit float, nominal range -1.0..=1.0 — the family's mixing currency. + F32, + /// 64-bit float. + F64, +} + +impl SampleFormat { + /// Bytes one sample of one channel occupies. + pub fn bytes_per_sample(&self) -> usize { + match self { + SampleFormat::U8 => 1, + SampleFormat::S16 => 2, + SampleFormat::S32 | SampleFormat::F32 => 4, + SampleFormat::F64 => 8, + } + } + + /// True for the float formats. + pub fn is_float(&self) -> bool { + matches!(self, SampleFormat::F32 | SampleFormat::F64) + } +} + +/// A named speaker position. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ChannelPosition { + /// Front left. + FrontLeft, + /// Front right. + FrontRight, + /// Front centre. + FrontCenter, + /// Low frequency effects. + Lfe, + /// Back (surround) left. + BackLeft, + /// Back (surround) right. + BackRight, + /// Side left. + SideLeft, + /// Side right. + SideRight, + /// Back centre. + BackCenter, + /// Front left of centre. + FrontLeftOfCenter, + /// Front right of centre. + FrontRightOfCenter, +} + +use ChannelPosition::*; + +const MONO: &[ChannelPosition] = &[FrontCenter]; +const STEREO: &[ChannelPosition] = &[FrontLeft, FrontRight]; +const SURROUND_5_1: &[ChannelPosition] = + &[FrontLeft, FrontRight, FrontCenter, Lfe, BackLeft, BackRight]; +const SURROUND_7_1: &[ChannelPosition] = &[ + FrontLeft, + FrontRight, + FrontCenter, + Lfe, + BackLeft, + BackRight, + SideLeft, + SideRight, +]; + +/// Channel count plus the meaning and order of each channel. +/// +/// The named layouts fix the interleaving order the family decodes and encodes +/// in; 5.1 is FL, FR, FC, LFE, BL, BR. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ChannelLayout { + /// One channel, front centre. + Mono, + /// FL, FR. + Stereo, + /// FL, FR, FC, LFE, BL, BR. + Surround5_1, + /// FL, FR, FC, LFE, BL, BR, SL, SR. + Surround7_1, + /// Any other ordering a container states explicitly. + Custom(Vec), +} + +impl ChannelLayout { + /// Channel order, as interleaved and as planes are indexed. + pub fn positions(&self) -> &[ChannelPosition] { + match self { + ChannelLayout::Mono => MONO, + ChannelLayout::Stereo => STEREO, + ChannelLayout::Surround5_1 => SURROUND_5_1, + ChannelLayout::Surround7_1 => SURROUND_7_1, + ChannelLayout::Custom(v) => v, + } + } + + /// Number of channels. + pub fn channel_count(&self) -> usize { + self.positions().len() + } + + /// The default layout for a bare channel count, as containers that state + /// only a count intend it. + pub fn from_count(n: usize) -> ChannelLayout { + match n { + 1 => ChannelLayout::Mono, + 2 => ChannelLayout::Stereo, + 6 => ChannelLayout::Surround5_1, + 8 => ChannelLayout::Surround7_1, + _ => ChannelLayout::Custom(vec![FrontCenter; n]), + } + } +} + +/// A decoded block of audio. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AudioFrame { + /// Sample storage format. + pub format: SampleFormat, + /// True when `data` holds one plane per channel, false when interleaved. + pub planar: bool, + /// Channel count, order and meaning. + pub layout: ChannelLayout, + /// Sample rate in Hz. + pub rate: u32, + /// Samples per channel in this frame. + pub samples: usize, + /// One plane when interleaved, one per channel when planar. + pub data: Vec, + /// Presentation time, when the source provided one. + pub pts: Option, +} + +impl AudioFrame { + /// An audio frame over existing planes, validating plane count and length. + pub fn try_new( + format: SampleFormat, + planar: bool, + layout: ChannelLayout, + rate: u32, + samples: usize, + data: Vec, + ) -> Result { + let channels = layout.channel_count(); + let wanted_planes = if planar { channels } else { 1 }; + if data.len() != wanted_planes { + return Err(Error::corrupt(format!( + "{layout:?} {} needs {wanted_planes} planes, got {}", + if planar { "planar" } else { "interleaved" }, + data.len() + ))); + } + let per_plane = if planar { 1 } else { channels }; + let needed = samples * per_plane * format.bytes_per_sample(); + for (i, plane) in data.iter().enumerate() { + if plane.len() < needed { + return Err(Error::corrupt(format!( + "audio plane {i}: {} bytes, {needed} needed for {samples} samples", + plane.len() + ))); + } + } + Ok(AudioFrame { + format, + planar, + layout, + rate, + samples, + data, + pts: None, + }) + } + + /// Channel count of the layout. + pub fn channels(&self) -> usize { + self.layout.channel_count() + } +} + +/// What a decoder produces. +/// +/// Subtitles are deliberately absent: a decoded subtitle is a cue list or a +/// bitmap region set, not a sample grid, so subtitle streams travel as +/// [`crate::packet::Packet`]s and are parsed by the subtitle crate into its own +/// IR. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Frame { + /// A decoded picture. + Video(VideoFrame), + /// A decoded audio block. + Audio(AudioFrame), +} + +impl Frame { + /// Presentation time of either variant. + pub fn pts(&self) -> Option { + match self { + Frame::Video(v) => v.pts, + Frame::Audio(a) => a.pts, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::timebase::TimeBase; + + #[test] + fn plane_geometry_matches_formats() { + // Odd dimensions round chroma up, never down. + assert_eq!( + PixelFormat::I420.plane_geometry(1921, 1081), + vec![(1921, 1081), (961, 541), (961, 541)] + ); + assert_eq!( + PixelFormat::Nv12.plane_geometry(1920, 1080), + vec![(1920, 1080), (1920, 540)] + ); + // P010: 2 bytes per component, interleaved chroma pair. + assert_eq!( + PixelFormat::P010.plane_geometry(1920, 1080), + vec![(3840, 1080), (3840, 540)] + ); + assert_eq!(PixelFormat::Bgra8.plane_geometry(64, 4), vec![(256, 4)]); + assert_eq!(PixelFormat::I444.plane_geometry(16, 16).len(), 3); + assert_eq!(PixelFormat::P010.bits_per_component(), 10); + assert_eq!(PixelFormat::P010.bytes_per_component(), 2); + assert!(PixelFormat::Bgra8.has_alpha()); + assert!(!PixelFormat::Nv12.has_alpha()); + assert!(PixelFormat::Nv12.is_yuv()); + } + + #[test] + fn video_frame_validates_planes() { + let f = VideoFrame::alloc(PixelFormat::I420, 64, 32); + assert_eq!(f.planes.len(), 3); + assert_eq!(f.planes[0].stride, 64); + assert_eq!(f.planes[1].data.len(), 32 * 16); + assert_eq!(f.planes[0].row(31, 64).unwrap().len(), 64); + assert!(f.planes[0].row(32, 64).is_none()); + + // Padded strides are legal; short planes and short strides are not. + let padded = VideoFrame::try_new( + PixelFormat::Gray8, + 4, + 2, + vec![Plane::new(vec![0u8; 8 + 4], 8)], + ); + assert!(padded.is_ok()); + assert!( + VideoFrame::try_new(PixelFormat::Gray8, 4, 2, vec![Plane::new(vec![0u8; 8], 2)]) + .is_err() + ); + assert!( + VideoFrame::try_new(PixelFormat::I420, 4, 2, vec![Plane::new(vec![0u8; 8], 4)]) + .is_err() + ); + } + + #[test] + fn channel_layouts_are_named_and_ordered() { + assert_eq!( + ChannelLayout::Surround5_1.positions(), + &[ + ChannelPosition::FrontLeft, + ChannelPosition::FrontRight, + ChannelPosition::FrontCenter, + ChannelPosition::Lfe, + ChannelPosition::BackLeft, + ChannelPosition::BackRight + ] + ); + assert_eq!(ChannelLayout::Surround7_1.channel_count(), 8); + assert_eq!(ChannelLayout::from_count(6), ChannelLayout::Surround5_1); + assert_eq!(ChannelLayout::from_count(3).channel_count(), 3); + } + + #[test] + fn audio_frame_validates_planes() { + let interleaved = AudioFrame::try_new( + SampleFormat::F32, + false, + ChannelLayout::Surround5_1, + 48_000, + 1024, + vec![Buf::from_vec(vec![0u8; 1024 * 6 * 4])], + ) + .unwrap(); + assert_eq!(interleaved.channels(), 6); + + let planar = AudioFrame::try_new( + SampleFormat::S16, + true, + ChannelLayout::Stereo, + 44_100, + 512, + vec![Buf::from_vec(vec![0u8; 1024]); 2], + ) + .unwrap(); + assert_eq!(planar.data.len(), 2); + + // Wrong plane count and short planes are rejected, not truncated. + assert!( + AudioFrame::try_new( + SampleFormat::F32, + true, + ChannelLayout::Stereo, + 48_000, + 64, + vec![Buf::from_vec(vec![0u8; 256])] + ) + .is_err() + ); + assert!( + AudioFrame::try_new( + SampleFormat::F32, + false, + ChannelLayout::Stereo, + 48_000, + 64, + vec![Buf::from_vec(vec![0u8; 4])] + ) + .is_err() + ); + } + + #[test] + fn frame_pts_passthrough() { + let mut v = VideoFrame::alloc(PixelFormat::Nv12, 16, 16); + v.pts = Some(Timestamp::new(1001, TimeBase::new(1, 24_000))); + let f = Frame::Video(v); + assert_eq!(f.pts().unwrap().ticks, 1001); + } +} diff --git a/crates/ec-core/src/lib.rs b/crates/ec-core/src/lib.rs new file mode 100644 index 00000000..a5bc7688 --- /dev/null +++ b/crates/ec-core/src/lib.rs @@ -0,0 +1,44 @@ +//! The intermediate representation every edith_codecs crate is built on. +//! +//! One vocabulary spans demux, decode, encode and mux: a [`Packet`] of +//! compressed bytes, a [`Frame`] of decoded samples, a [`CodecId`] naming what +//! turns one into the other, [`CodecParameters`] describing a stream before its +//! first packet, and a rational [`TimeBase`] that keeps `24000/1001` exact from +//! the container to the muxer. [`bitio`] holds the one bit reader/writer pair +//! the parsers share. +//! +//! Contracts worth knowing before implementing against this crate: +//! +//! - Timing is integer. `f64` appears only in `as_secs_f64` helpers, for +//! display, and never flows back into a timestamp. +//! - Truncated input is [`Error::NeedMore`], not a panic; a refusal is +//! [`Error::Unsupported`] and always names *what* and *why*. +//! - Codecs are push/pull ([`Decoder::send_packet`] / [`Decoder::receive_frame`]), +//! because packets and frames do not correspond one to one. +//! - Payloads are [`Buf`], a refcounted byte range: cloning a packet or sharing +//! a plane is a refcount bump, not a copy. +//! +//! No async, no unsafe, no external dependencies. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod bitio; +pub mod error; +pub mod frame; +pub mod packet; +pub mod registry; +pub mod timebase; + +pub use bitio::{BitReader, BitReaderLsb, BitWriter, BitWriterLsb}; +pub use error::{Error, Result}; +pub use frame::{ + AudioFrame, ChannelLayout, ChannelPosition, ColorInfo, Frame, PixelFormat, Plane, SampleFormat, + VideoFrame, +}; +pub use packet::{Buf, Packet, PacketFlags, SideData}; +pub use registry::{ + AudioParameters, CodecId, CodecParameters, Decoder, Demuxer, Encoder, MediaParameters, + MediaType, Muxer, SeekMode, StreamInfo, VideoParameters, +}; +pub use timebase::{Rounding, TimeBase, Timestamp}; diff --git a/crates/ec-core/src/packet.rs b/crates/ec-core/src/packet.rs new file mode 100644 index 00000000..9c93fca7 --- /dev/null +++ b/crates/ec-core/src/packet.rs @@ -0,0 +1,238 @@ +//! Compressed data units and the shared cheap-clone byte buffer. + +use std::ops::{Bound, Deref, RangeBounds}; +use std::sync::Arc; + +use crate::timebase::TimeBase; + +/// Reference-counted byte range: clone is a refcount bump, `slice` is free. +/// +/// This is what keeps demuxed packets and decoded planes zero-copy — a +/// container reads one cluster into a `Vec`, wraps it once, and hands out +/// packets that borrow into it without copying or borrowing a lifetime (so the +/// result stays `Send + 'static`). +#[derive(Clone, Default)] +pub struct Buf { + data: Arc<[u8]>, + off: usize, + len: usize, +} + +impl Buf { + /// Empty buffer, no allocation beyond the empty `Arc`. + pub fn new() -> Buf { + Buf::default() + } + + /// Take ownership of a `Vec` without copying its bytes. + pub fn from_vec(v: Vec) -> Buf { + let len = v.len(); + Buf { + data: Arc::from(v), + off: 0, + len, + } + } + + /// Copy a slice into a new buffer. + pub fn copy_from_slice(s: &[u8]) -> Buf { + Buf::from_vec(s.to_vec()) + } + + /// Length in bytes. + pub fn len(&self) -> usize { + self.len + } + + /// True when the buffer holds no bytes. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// A sub-range of this buffer, sharing the same allocation. + /// + /// Panics on an out-of-bounds range, exactly like slicing a `&[u8]`. + pub fn slice(&self, range: impl RangeBounds) -> Buf { + let start = match range.start_bound() { + Bound::Included(&n) => n, + Bound::Excluded(&n) => n + 1, + Bound::Unbounded => 0, + }; + let end = match range.end_bound() { + Bound::Included(&n) => n + 1, + Bound::Excluded(&n) => n, + Bound::Unbounded => self.len, + }; + assert!(start <= end && end <= self.len, "Buf::slice out of bounds"); + Buf { + data: Arc::clone(&self.data), + off: self.off + start, + len: end - start, + } + } +} + +impl Deref for Buf { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + &self.data[self.off..self.off + self.len] + } +} + +impl AsRef<[u8]> for Buf { + fn as_ref(&self) -> &[u8] { + self + } +} + +impl From> for Buf { + fn from(v: Vec) -> Buf { + Buf::from_vec(v) + } +} + +impl From<&[u8]> for Buf { + fn from(s: &[u8]) -> Buf { + Buf::copy_from_slice(s) + } +} + +impl PartialEq for Buf { + fn eq(&self, other: &Buf) -> bool { + **self == **other + } +} + +impl Eq for Buf {} + +impl std::fmt::Debug for Buf { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Buf({} bytes)", self.len) + } +} + +/// Out-of-band data attached to a packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SideData { + /// Codec configuration in the codec's own form (avcC, hvcC, av1C, + /// AudioSpecificConfig, ...) when it arrives in band rather than in + /// [`crate::registry::CodecParameters::extradata`]. + CodecConfig(Buf), + /// Palette for palettised subtitle/image codecs. + Palette(Buf), + /// ISO 14496-12 3x3 display matrix (rotation/flip). + DisplayMatrix(Buf), + /// Anything a single container needs and nothing else understands. + Custom { + /// Container-defined discriminator. + kind: u32, + /// Raw payload. + data: Buf, + }, +} + +/// Per-packet booleans. All default to false. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PacketFlags { + /// Decoding may start here (IDR, audio sync frame, subtitle cue start). + pub keyframe: bool, + /// Carries headers/config only, no presentable sample. + pub header: bool, + /// Known-damaged payload; decoders may attempt it and must not panic. + pub corrupt: bool, + /// Decode for state but do not present (post-seek pre-roll). + pub discard: bool, +} + +/// One compressed access unit of one stream. +/// +/// Fields are public: containers and codecs assemble packets field by field, +/// and a builder chain would only hide that. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Packet { + /// Index of the stream in [`crate::registry::Demuxer::streams`]. + pub stream: u32, + /// Base of `pts`, `dts` and `duration`. + pub time_base: TimeBase, + /// Presentation timestamp, when the container states one. + pub pts: Option, + /// Decode timestamp, when it differs from `pts` (B-frames). + pub dts: Option, + /// Duration in `time_base` ticks, when known. + pub duration: Option, + /// Per-packet flags. + pub flags: PacketFlags, + /// Out-of-band extras; empty for almost every packet. + pub side_data: Vec, + /// Compressed payload. + pub data: Buf, +} + +impl Packet { + /// A packet with no timestamps and no flags set. + pub fn new(stream: u32, time_base: TimeBase, data: impl Into) -> Packet { + Packet { + stream, + time_base, + pts: None, + dts: None, + duration: None, + flags: PacketFlags::default(), + side_data: Vec::new(), + data: data.into(), + } + } + + /// `pts + duration`, when both are known. + pub fn end_pts(&self) -> Option { + self.pts?.checked_add(self.duration?) + } + + /// True when decoding may start at this packet. + pub fn is_keyframe(&self) -> bool { + self.flags.keyframe + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buf_slices_share_one_allocation() { + let buf = Buf::from_vec(vec![0, 1, 2, 3, 4, 5]); + let mid = buf.slice(2..5); + assert_eq!(&*mid, &[2, 3, 4]); + assert_eq!(&*mid.slice(1..), &[3, 4]); + assert_eq!(mid.len(), 3); + assert!(Buf::new().is_empty()); + // Clone is a refcount bump, not a copy: same bytes, no reallocation. + let clone = mid.clone(); + assert_eq!(clone, mid); + assert_eq!(&*buf.slice(..), &[0, 1, 2, 3, 4, 5]); + } + + #[test] + #[should_panic(expected = "out of bounds")] + fn buf_slice_rejects_out_of_range() { + Buf::from_vec(vec![0, 1]).slice(0..3); + } + + #[test] + fn packet_construction() { + let tb = TimeBase::from_rate(48_000); + let mut p = Packet::new(0, tb, vec![0xff; 4]); + assert!(!p.is_keyframe()); + assert_eq!(p.end_pts(), None); + p.pts = Some(1024); + p.duration = Some(1024); + p.flags.keyframe = true; + p.side_data + .push(SideData::CodecConfig(Buf::copy_from_slice(&[0x12, 0x10]))); + assert_eq!(p.end_pts(), Some(2048)); + assert!(p.is_keyframe()); + assert_eq!(p.data.len(), 4); + assert_eq!(p.time_base, TimeBase::new(1, 48_000)); + } +} diff --git a/crates/ec-core/src/registry.rs b/crates/ec-core/src/registry.rs new file mode 100644 index 00000000..788c6392 --- /dev/null +++ b/crates/ec-core/src/registry.rs @@ -0,0 +1,432 @@ +//! Codec identities, stream descriptions and the four trait contracts every +//! container and codec crate in the family implements. + +use crate::error::Result; +use crate::frame::{ChannelLayout, ColorInfo, Frame, PixelFormat, SampleFormat}; +use crate::packet::{Buf, Packet}; +use crate::timebase::{TimeBase, Timestamp}; + +/// Which kind of stream something belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MediaType { + /// Pictures. + Video, + /// Sound. + Audio, + /// Timed text or bitmap overlays. + Subtitle, +} + +/// Every codec the family carries. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CodecId { + /// ITU-T H.264 / MPEG-4 AVC. + H264, + /// ITU-T H.265 / MPEG-H HEVC. + H265, + /// Google VP8 (also the lossy half of WebP). + Vp8, + /// Google VP9. + Vp9, + /// AOMedia AV1. + Av1, + /// MPEG-4 AAC (LC and friends). + Aac, + /// Dolby AC-3. + Ac3, + /// Dolby Digital Plus (E-AC-3). + EAc3, + /// Apple Lossless. + Alac, + /// Xiph FLAC. + Flac, + /// MPEG-1/2 Layer III. + Mp3, + /// Xiph Opus. + Opus, + /// Xiph Vorbis. + Vorbis, + /// Unsigned 8-bit PCM. + PcmU8, + /// Signed 16-bit little-endian PCM. + PcmS16Le, + /// Signed 16-bit big-endian PCM. + PcmS16Be, + /// Signed 24-bit little-endian packed PCM. + PcmS24Le, + /// Signed 32-bit little-endian PCM. + PcmS32Le, + /// 32-bit float little-endian PCM. + PcmF32Le, + /// SubRip text. + Srt, + /// WebVTT text. + WebVtt, + /// Advanced SubStation Alpha (and SSA). + Ass, + /// Blu-ray Presentation Graphic Stream bitmaps. + Pgs, + /// MPEG-4 timed text (3GPP `tx3g`). + Tx3g, +} + +impl CodecId { + /// The media type this codec produces. + pub fn media_type(&self) -> MediaType { + use CodecId::*; + match self { + H264 | H265 | Vp8 | Vp9 | Av1 => MediaType::Video, + Aac | Ac3 | EAc3 | Alac | Flac | Mp3 | Opus | Vorbis | PcmU8 | PcmS16Le | PcmS16Be + | PcmS24Le | PcmS32Le | PcmF32Le => MediaType::Audio, + Srt | WebVtt | Ass | Pgs | Tx3g => MediaType::Subtitle, + } + } + + /// Short lowercase name, stable enough for logs and capability tables. + pub fn name(&self) -> &'static str { + use CodecId::*; + match self { + H264 => "h264", + H265 => "h265", + Vp8 => "vp8", + Vp9 => "vp9", + Av1 => "av1", + Aac => "aac", + Ac3 => "ac3", + EAc3 => "eac3", + Alac => "alac", + Flac => "flac", + Mp3 => "mp3", + Opus => "opus", + Vorbis => "vorbis", + PcmU8 => "pcm_u8", + PcmS16Le => "pcm_s16le", + PcmS16Be => "pcm_s16be", + PcmS24Le => "pcm_s24le", + PcmS32Le => "pcm_s32le", + PcmF32Le => "pcm_f32le", + Srt => "srt", + WebVtt => "webvtt", + Ass => "ass", + Pgs => "pgs", + Tx3g => "tx3g", + } + } +} + +/// Video half of [`CodecParameters`]. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct VideoParameters { + /// Coded width in pixels. + pub width: u32, + /// Coded height in pixels. + pub height: u32, + /// Decoded pixel layout, when the container or headers state one. + pub format: Option, + /// Frame rate *as a rate*: `num/den` is frames per second, so NTSC film is + /// `24000/1001`. Invert it with [`TimeBase::inverse`] for a tick duration. + pub frame_rate: Option, + /// Sample aspect ratio (`num/den`), when not square. + pub sample_aspect_ratio: Option, + /// H.273 colour description. + pub color: ColorInfo, +} + +/// Audio half of [`CodecParameters`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AudioParameters { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count, order and meaning. + pub layout: ChannelLayout, + /// Decoded sample format, when known before the first frame. + pub format: Option, + /// Coded bit depth, when the codec has one (FLAC 24, ALAC 16/24). + pub bits_per_sample: Option, +} + +impl Default for AudioParameters { + fn default() -> Self { + AudioParameters { + sample_rate: 0, + layout: ChannelLayout::Stereo, + format: None, + bits_per_sample: None, + } + } +} + +/// Per-media-type parameters. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MediaParameters { + /// Video stream parameters. + Video(VideoParameters), + /// Audio stream parameters. + Audio(AudioParameters), + /// Subtitle streams carry no dimensions; their setup lives in `extradata` + /// (the ASS header, the PGS palette, ...). + Subtitle, +} + +/// Everything a decoder needs before it sees its first packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodecParameters { + /// Which codec. + pub codec: CodecId, + /// Codec-defined setup bytes: avcC, hvcC, av1C, AudioSpecificConfig, the + /// FLAC STREAMINFO block, the Vorbis header triplet, and so on. + pub extradata: Option, + /// Media-type-specific parameters. + pub media: MediaParameters, +} + +impl CodecParameters { + /// Parameters for `codec` with defaults for its media type and no extradata. + pub fn new(codec: CodecId) -> CodecParameters { + let media = match codec.media_type() { + MediaType::Video => MediaParameters::Video(VideoParameters::default()), + MediaType::Audio => MediaParameters::Audio(AudioParameters::default()), + MediaType::Subtitle => MediaParameters::Subtitle, + }; + CodecParameters { + codec, + extradata: None, + media, + } + } + + /// Video parameters, when this is a video stream. + pub fn video(&self) -> Option<&VideoParameters> { + match &self.media { + MediaParameters::Video(v) => Some(v), + _ => None, + } + } + + /// Audio parameters, when this is an audio stream. + pub fn audio(&self) -> Option<&AudioParameters> { + match &self.media { + MediaParameters::Audio(a) => Some(a), + _ => None, + } + } +} + +/// One stream of a container, as a demuxer reports it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StreamInfo { + /// Index matching [`Packet::stream`]. + pub index: u32, + /// Base of every timestamp on this stream's packets. + pub time_base: TimeBase, + /// Codec and setup data. + pub params: CodecParameters, + /// First presentation timestamp, in `time_base` ticks, when known. + pub start_time: Option, + /// Duration in `time_base` ticks, when the container states one. + pub duration: Option, + /// ISO 639-2 language tag, when the container carries one. + pub language: Option, +} + +impl StreamInfo { + /// A stream with no timing hints and no language. + pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo { + StreamInfo { + index, + time_base, + params, + start_time: None, + duration: None, + language: None, + } + } +} + +/// Where a seek is allowed to land relative to the requested instant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SeekMode { + /// Nearest random access point at or before the target. The default: it is + /// the only mode that lets a decoder reach the target frame exactly, by + /// decoding forward and discarding. + #[default] + SyncBefore, + /// Nearest random access point at or after the target. + SyncAfter, + /// Exact instant, whether or not a random access point sits there; the + /// caller handles the pre-roll. + Exact, +} + +/// A container reader: streams in, packets out. +pub trait Demuxer: Send { + /// The streams found while opening the container. + fn streams(&self) -> &[StreamInfo]; + + /// Next packet in storage order, or [`crate::Error::Eof`] at the end. + fn next_packet(&mut self) -> Result; + + /// Position so that reading resumes near `to` on `stream`. + /// + /// `to` carries its own [`TimeBase`], so callers never have to know the + /// stream's base to seek by wall-clock instant. + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()>; +} + +/// A container writer: streams declared, then packets, then a finish. +pub trait Muxer: Send { + /// Declare a stream; returns the index that its packets must carry. + /// + /// All streams are declared before the first [`Muxer::write_packet`]. + fn add_stream(&mut self, info: StreamInfo) -> Result; + + /// Write one packet. Its `stream` must be an index from + /// [`Muxer::add_stream`] and its timestamps are rescaled by the muxer. + fn write_packet(&mut self, packet: &Packet) -> Result<()>; + + /// Flush indices and trailers. Takes `&mut self` rather than `self` so a + /// muxer stays usable behind `Box`. + fn finish(&mut self) -> Result<()>; +} + +/// A decoder: packets in, frames out. +/// +/// Push/pull rather than `decode(&Packet) -> Vec` because the mapping is +/// genuinely not one to one — a parameter-set packet yields nothing, a +/// reordering decoder yields nothing until its DPB fills, an audio packet can +/// yield several blocks — and because end of stream has to be expressible: +/// [`Decoder::flush`] then drains what reorder delay is still holding. The +/// `Vec` shape would allocate per packet and still need a second entry point +/// for the drain. +pub trait Decoder: Send { + /// The parameters this decoder was configured with, updated in place when + /// in-band headers change them. + fn codec_parameters(&self) -> &CodecParameters; + + /// Submit one packet. Call [`Decoder::receive_frame`] until it answers + /// [`crate::Error::NeedMore`] before submitting the next. + fn send_packet(&mut self, packet: &Packet) -> Result<()>; + + /// Take one decoded frame; [`crate::Error::NeedMore`] when none is ready, + /// [`crate::Error::Eof`] once a flushed decoder is drained. + fn receive_frame(&mut self) -> Result; + + /// Signal end of stream: after this, `receive_frame` returns the delayed + /// frames and then [`crate::Error::Eof`]. + fn flush(&mut self) -> Result<()>; + + /// Drop all buffered state after a seek. Timestamps and references from + /// before the seek are discarded. + fn reset(&mut self); +} + +/// An encoder: frames in, packets out — the mirror of [`Decoder`]. +pub trait Encoder: Send { + /// Parameters describing the encoder's output, including the `extradata` + /// a muxer needs. For codecs whose setup data is derived while encoding + /// (AAC ASC, avcC), this is final after the first + /// [`Encoder::receive_packet`]. + fn codec_parameters(&self) -> &CodecParameters; + + /// Submit one frame. + fn send_frame(&mut self, frame: &Frame) -> Result<()>; + + /// Take one encoded packet; [`crate::Error::NeedMore`] when none is ready, + /// [`crate::Error::Eof`] once a flushed encoder is drained. + fn receive_packet(&mut self) -> Result; + + /// Signal end of input and drain the lookahead. + fn flush(&mut self) -> Result<()>; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_codec_id_has_a_media_type_and_name() { + // The set the family must express, spelled out so a later crate cannot + // quietly lose one (subtitle packets included: they are Packets, not + // Frames). + let all = [ + CodecId::H264, + CodecId::H265, + CodecId::Vp8, + CodecId::Vp9, + CodecId::Av1, + CodecId::Aac, + CodecId::Ac3, + CodecId::EAc3, + CodecId::Alac, + CodecId::Flac, + CodecId::Mp3, + CodecId::Opus, + CodecId::Vorbis, + CodecId::PcmU8, + CodecId::PcmS16Le, + CodecId::PcmS16Be, + CodecId::PcmS24Le, + CodecId::PcmS32Le, + CodecId::PcmF32Le, + CodecId::Srt, + CodecId::WebVtt, + CodecId::Ass, + CodecId::Pgs, + CodecId::Tx3g, + ]; + assert_eq!(all.len(), 24); + let mut names: Vec<&str> = all.iter().map(|c| c.name()).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), all.len(), "codec names must be unique"); + assert_eq!(CodecId::Av1.media_type(), MediaType::Video); + assert_eq!(CodecId::Opus.media_type(), MediaType::Audio); + assert_eq!(CodecId::Pgs.media_type(), MediaType::Subtitle); + } + + #[test] + fn parameters_default_per_media_type() { + let v = CodecParameters::new(CodecId::H265); + assert!(v.video().is_some() && v.audio().is_none()); + let a = CodecParameters::new(CodecId::Opus); + assert_eq!(a.audio().unwrap().layout, ChannelLayout::Stereo); + assert!(matches!( + CodecParameters::new(CodecId::Pgs).media, + MediaParameters::Subtitle + )); + + // NTSC frame rate survives as a rate and inverts into a tick duration. + let mut p = CodecParameters::new(CodecId::H264); + if let MediaParameters::Video(v) = &mut p.media { + v.width = 1920; + v.height = 1080; + v.frame_rate = Some(TimeBase::new(24_000, 1001)); + v.format = Some(PixelFormat::I420); + } + let fr = p.video().unwrap().frame_rate.unwrap(); + assert_eq!(fr.num(), 24_000); + assert_eq!(fr.inverse(), TimeBase::NTSC_FILM); + } + + #[test] + fn stream_info_carries_language_and_timing() { + let mut s = StreamInfo::new(2, TimeBase::MILLIS, CodecParameters::new(CodecId::Srt)); + s.language = Some("tur".into()); + s.duration = Some(3_600_000); + assert_eq!(s.params.codec.media_type(), MediaType::Subtitle); + assert_eq!(s.index, 2); + assert_eq!(s.language.as_deref(), Some("tur")); + } + + #[test] + fn trait_objects_are_send() { + fn assert_send() {} + assert_send::(); + assert_send::(); + assert_send::(); + assert_send::(); + assert_send::(); + assert_send::(); + } +} diff --git a/crates/ec-core/src/timebase.rs b/crates/ec-core/src/timebase.rs new file mode 100644 index 00000000..9b586ea4 --- /dev/null +++ b/crates/ec-core/src/timebase.rs @@ -0,0 +1,345 @@ +//! Exact rational time. No `f64` anywhere on a timing path. +//! +//! Every timestamp in the family is an integer tick count plus the [`TimeBase`] +//! that gives the tick its duration in seconds. NTSC rates are exactly +//! representable (`24000/1001`, `30000/1001`, `60000/1001`) and stay exact +//! through rescaling, which is why `23.976` can never decay into `23.0` here. + +use std::cmp::Ordering; + +use crate::error::{Error, Result}; + +/// A positive rational number of seconds per tick, stored reduced. +/// +/// Also used as a *rate* (frames per second) where a rate is what is meant; +/// [`TimeBase::inverse`] converts between the two readings. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct TimeBase { + num: i64, + den: i64, +} + +const fn gcd(mut a: i64, mut b: i64) -> i64 { + while b != 0 { + let t = a % b; + a = b; + b = t; + } + a +} + +impl TimeBase { + /// Reduced `num/den`. Panics if either part is not positive — for literals; + /// use [`TimeBase::try_new`] for values parsed out of a container. + pub const fn new(num: i64, den: i64) -> TimeBase { + assert!(num > 0 && den > 0, "time base parts must be positive"); + let g = gcd(num, den); + TimeBase { + num: num / g, + den: den / g, + } + } + + /// Reduced `num/den`, or [`Error::Corrupt`] if either part is not positive. + pub fn try_new(num: i64, den: i64) -> Result { + if num <= 0 || den <= 0 { + return Err(Error::corrupt(format!( + "time base {num}/{den} not positive" + ))); + } + Ok(TimeBase::new(num, den)) + } + + /// Tick duration of a sample rate, i.e. `1/rate` (48 kHz audio: `1/48000`). + pub const fn from_rate(rate: u32) -> TimeBase { + TimeBase::new(1, rate as i64) + } + + /// Numerator of the reduced fraction. + pub const fn num(&self) -> i64 { + self.num + } + + /// Denominator of the reduced fraction. + pub const fn den(&self) -> i64 { + self.den + } + + /// `den/num` — a tick duration read as a rate, or a rate as a duration. + pub const fn inverse(&self) -> TimeBase { + TimeBase { + num: self.den, + den: self.num, + } + } + + /// Convert `ticks` from this base into `to`, saturating at [`i64`] bounds. + /// + /// Saturation is unreachable for real media (i64 nanoseconds is 292 years); + /// use [`TimeBase::checked_rescale`] when the input is attacker-controlled + /// and the difference must be observed. + pub fn rescale(&self, ticks: i64, to: TimeBase, rounding: Rounding) -> i64 { + match self.checked_rescale(ticks, to, rounding) { + Some(v) => v, + None if ticks >= 0 => i64::MAX, + None => i64::MIN, + } + } + + /// Convert `ticks` from this base into `to`, or `None` on [`i64`] overflow. + /// + /// Exact: the whole computation runs in [`i128`] and rounds exactly once. + pub fn checked_rescale(&self, ticks: i64, to: TimeBase, rounding: Rounding) -> Option { + let n = ticks as i128 * self.num as i128 * to.den as i128; + let d = self.den as i128 * to.num as i128; + i64::try_from(rounding.div(n, d)).ok() + } + + /// Seconds as a float. Display and logging only — never feed this back into + /// a timestamp. + pub fn as_secs_f64(&self) -> f64 { + self.num as f64 / self.den as f64 + } + + /// Seconds per tick: 1/1. + pub const SECONDS: TimeBase = TimeBase::new(1, 1); + /// Milliseconds: 1/1000 (Matroska default TimestampScale territory). + pub const MILLIS: TimeBase = TimeBase::new(1, 1_000); + /// Microseconds: 1/1_000_000. + pub const MICROS: TimeBase = TimeBase::new(1, 1_000_000); + /// Nanoseconds: 1/1_000_000_000 (Matroska timestamps). + pub const NANOS: TimeBase = TimeBase::new(1, 1_000_000_000); + /// MPEG transport/program stream clock: 1/90000. + pub const MPEG_TS: TimeBase = TimeBase::new(1, 90_000); + /// NTSC film frame duration: 1001/24000 (23.976 fps, exactly). + pub const NTSC_FILM: TimeBase = TimeBase::new(1001, 24_000); + /// NTSC video frame duration: 1001/30000 (29.97 fps, exactly). + pub const NTSC_VIDEO: TimeBase = TimeBase::new(1001, 30_000); +} + +/// How a rescale that does not divide evenly picks its integer result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum Rounding { + /// Toward negative infinity. + Down, + /// Toward positive infinity. + Up, + /// Toward zero (truncate). + Zero, + /// To the nearest, halves away from zero. The default: it is what seek and + /// container timestamp conversion want. + #[default] + Nearest, +} + +impl Rounding { + /// Divide `n` by a positive `d` under this rounding mode. + fn div(self, n: i128, d: i128) -> i128 { + debug_assert!(d > 0, "time base denominators are positive by construction"); + let q = n / d; + let r = n % d; + match self { + Rounding::Zero => q, + Rounding::Down => { + if r < 0 { + q - 1 + } else { + q + } + } + Rounding::Up => { + if r > 0 { + q + 1 + } else { + q + } + } + Rounding::Nearest => { + if r.abs() * 2 >= d { + if n >= 0 { q + 1 } else { q - 1 } + } else { + q + } + } + } + } +} + +/// A tick count carrying its own [`TimeBase`]. +/// +/// Ordering and equality compare *instants*, exactly, across different bases. +#[derive(Debug, Clone, Copy)] +pub struct Timestamp { + /// Tick count in `base`. + pub ticks: i64, + /// Duration of one tick. + pub base: TimeBase, +} + +impl Timestamp { + /// A timestamp of `ticks` in `base`. + pub const fn new(ticks: i64, base: TimeBase) -> Timestamp { + Timestamp { ticks, base } + } + + /// The same instant expressed in `base`, saturating at [`i64`] bounds. + pub fn rescale(&self, base: TimeBase, rounding: Rounding) -> Timestamp { + Timestamp::new(self.base.rescale(self.ticks, base, rounding), base) + } + + /// The same instant expressed in `base`, or `None` on [`i64`] overflow. + pub fn checked_rescale(&self, base: TimeBase, rounding: Rounding) -> Option { + self.base + .checked_rescale(self.ticks, base, rounding) + .map(|t| Timestamp::new(t, base)) + } + + /// Advance by `ticks` of this timestamp's own base. + pub fn checked_add_ticks(&self, ticks: i64) -> Option { + self.ticks + .checked_add(ticks) + .map(|t| Timestamp::new(t, self.base)) + } + + /// `self - other`, in this timestamp's base, exact. + pub fn checked_diff(&self, other: Timestamp) -> Option { + let o = other.checked_rescale(self.base, Rounding::Nearest)?; + self.ticks.checked_sub(o.ticks) + } + + /// Seconds as a float. Display only. + pub fn as_secs_f64(&self) -> f64 { + self.ticks as f64 * self.base.as_secs_f64() + } +} + +impl PartialEq for Timestamp { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl Eq for Timestamp {} + +impl PartialOrd for Timestamp { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Timestamp { + /// Exact cross-base comparison: both sides are put over the common + /// denominator in [`i128`] rather than converted (and rounded) first. + fn cmp(&self, other: &Self) -> Ordering { + let a = self.ticks as i128 * self.base.num() as i128 * other.base.den() as i128; + let b = other.ticks as i128 * other.base.num() as i128 * self.base.den() as i128; + a.cmp(&b) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reduces_and_compares_equal() { + assert_eq!(TimeBase::new(2, 4), TimeBase::new(1, 2)); + // NTSC fractions are already reduced and must survive verbatim. + assert_eq!(TimeBase::NTSC_FILM.num(), 1001); + assert_eq!(TimeBase::NTSC_FILM.den(), 24_000); + assert_eq!(TimeBase::NTSC_FILM.inverse(), TimeBase::new(24_000, 1001)); + } + + #[test] + fn rejects_non_positive_parts() { + assert!(TimeBase::try_new(1, 0).is_err()); + assert!(TimeBase::try_new(0, 1).is_err()); + assert!(TimeBase::try_new(-1, 24_000).is_err()); + } + + #[test] + fn ntsc_ten_hours_zero_drift() { + // 10 h of 24000/1001 film: frame index -> exact base and back. + let frames = 863_136_i64; // 10 h at 23.976 fps + let film = TimeBase::NTSC_FILM; + let fine = TimeBase::new(1, 24_000_000); + let ticks = film + .checked_rescale(frames, fine, Rounding::Nearest) + .unwrap(); + assert_eq!(ticks, frames * 1001 * 1000); + assert_eq!( + fine.checked_rescale(ticks, film, Rounding::Nearest) + .unwrap(), + frames + ); + // Per-frame accumulation must equal the closed form: no drift. + let mut acc = 0_i64; + for _ in 0..frames { + acc += 1001 * 1000; + } + assert_eq!(acc, ticks); + } + + #[test] + fn ntsc_never_becomes_integer_fps() { + // 23.976 fps as a rate, one second of it, in the film base. + let one_second = TimeBase::SECONDS + .checked_rescale(1, TimeBase::NTSC_FILM, Rounding::Nearest) + .unwrap(); + assert_eq!(one_second, 24); // 23.976 frames rounds to 24 ticks, never 23 + // A 24 fps base would be a different instant; prove the two differ. + let film = Timestamp::new(24, TimeBase::NTSC_FILM); + let flat = Timestamp::new(24, TimeBase::new(1, 24)); + assert!(film > flat); + } + + #[test] + fn rounding_modes() { + let ms = TimeBase::MILLIS; + let s = TimeBase::SECONDS; + // 1500 ms -> seconds under each mode. + assert_eq!(ms.rescale(1500, s, Rounding::Down), 1); + assert_eq!(ms.rescale(1500, s, Rounding::Up), 2); + assert_eq!(ms.rescale(1500, s, Rounding::Zero), 1); + assert_eq!(ms.rescale(1500, s, Rounding::Nearest), 2); + // Negative timestamps (B-frame dts) round symmetrically. + assert_eq!(ms.rescale(-1500, s, Rounding::Down), -2); + assert_eq!(ms.rescale(-1500, s, Rounding::Up), -1); + assert_eq!(ms.rescale(-1500, s, Rounding::Zero), -1); + assert_eq!(ms.rescale(-1500, s, Rounding::Nearest), -2); + } + + #[test] + fn overflow_is_reported_not_wrapped() { + // Seconds into nanoseconds: 2^63 seconds does not fit. + let s = TimeBase::SECONDS; + assert_eq!( + s.checked_rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest), + None + ); + assert_eq!( + s.rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest), + i64::MAX + ); + assert_eq!( + s.rescale(i64::MIN, TimeBase::NANOS, Rounding::Nearest), + i64::MIN + ); + // In range, nothing saturates. + assert_eq!( + s.checked_rescale(3, TimeBase::NANOS, Rounding::Nearest), + Some(3_000_000_000) + ); + } + + #[test] + fn timestamp_math() { + let a = Timestamp::new(90_000, TimeBase::MPEG_TS); // 1 s + let b = Timestamp::new(1_000, TimeBase::MILLIS); // 1 s + assert_eq!(a, b); + assert_eq!(a.checked_diff(b), Some(0)); + assert_eq!(a.checked_add_ticks(90_000).unwrap().ticks, 180_000); + assert_eq!(a.rescale(TimeBase::MILLIS, Rounding::Nearest).ticks, 1_000); + assert!(Timestamp::new(0, TimeBase::MILLIS) < a); + } +} diff --git a/shims/.gitkeep b/shims/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tools/.gitkeep b/tools/.gitkeep new file mode 100644 index 00000000..e69de29b