Workspace + ec-core IR foundation
Browse files at this commita3c0049bc028d4b97f0692bcee002880e929bca1Root commit (no parents)- feat
- workspace + ec-core IR foundation
13 changed files +2380 -0
- .gitignore +2 -0
- Cargo.lock +7 -0
- Cargo.toml +17 -0
- crates/ec-core/Cargo.toml +9 -0
- crates/ec-core/src/bitio.rs +594 -0
- crates/ec-core/src/error.rs +89 -0
- crates/ec-core/src/frame.rs +603 -0
- crates/ec-core/src/lib.rs +44 -0
- crates/ec-core/src/packet.rs +238 -0
- crates/ec-core/src/registry.rs +432 -0
- crates/ec-core/src/timebase.rs +345 -0
- shims/.gitkeep +0 -0
- tools/.gitkeep +0 -0
.gitignoreadded+2 -0
| @@ -0,0 +1,2 @@ | |||
| 1 | +target/ | ||
| 2 | +fixtures/ | ||
Cargo.lockadded+7 -0
| @@ -0,0 +1,7 @@ | |||
| 1 | +# This file is automatically @generated by Cargo. | ||
| 2 | +# It is not intended for manual editing. | ||
| 3 | +version = 4 | ||
| 4 | + | ||
| 5 | +[[package]] | ||
| 6 | +name = "ec-core" | ||
| 7 | +version = "0.1.0" | ||
Cargo.tomladded+17 -0
| @@ -0,0 +1,17 @@ | |||
| 1 | +[workspace] | ||
| 2 | +resolver = "3" | ||
| 3 | +members = ["crates/*", "shims/*", "tools/*"] | ||
| 4 | + | ||
| 5 | +[workspace.package] | ||
| 6 | +version = "0.1.0" | ||
| 7 | +edition = "2024" | ||
| 8 | +license = "MIT OR Apache-2.0" | ||
| 9 | +authors = ["Ahmet Kaan Gümüş"] | ||
| 10 | + | ||
| 11 | +[workspace.dependencies] | ||
| 12 | +ec-core = { path = "crates/ec-core", version = "0.1.0" } | ||
| 13 | +# Portable SIMD without asm or build-time tooling (family rule: pure Rust only). | ||
| 14 | +wide = "1.5" | ||
| 15 | + | ||
| 16 | +[profile.release] | ||
| 17 | +opt-level = 3 | ||
crates/ec-core/Cargo.tomladded+9 -0
| @@ -0,0 +1,9 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-core" | ||
| 3 | +description = "Media IR shared by the edith_codecs family: packets, frames, rational time, bit I/O, codec contracts." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
crates/ec-core/src/bitio.rsadded+594 -0
| @@ -0,0 +1,594 @@ | |||
| 1 | +//! Bit-level readers and writers shared by every parser in the family. | ||
| 2 | +//! | ||
| 3 | +//! Two orders: MSB-first ([`BitReader`], [`BitWriter`]) for the MPEG/ITU | ||
| 4 | +//! bitstreams and FLAC, LSB-first ([`BitReaderLsb`], [`BitWriterLsb`]) for the | ||
| 5 | +//! Xiph formats. Readers never panic on truncated input — a short buffer is | ||
| 6 | +//! [`Error::NeedMore`], which is also the streaming "feed me more" contract. | ||
| 7 | + | ||
| 8 | +use crate::error::{Error, Result}; | ||
| 9 | + | ||
| 10 | +/// MSB-first bit reader over a borrowed buffer. | ||
| 11 | +#[derive(Debug, Clone)] | ||
| 12 | +pub struct BitReader<'a> { | ||
| 13 | + data: &'a [u8], | ||
| 14 | + pos: u64, | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +impl<'a> BitReader<'a> { | ||
| 18 | + /// A reader positioned at the first bit of `data`. | ||
| 19 | + pub fn new(data: &'a [u8]) -> BitReader<'a> { | ||
| 20 | + BitReader { data, pos: 0 } | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + /// Bits consumed so far. | ||
| 24 | + pub fn bit_position(&self) -> u64 { | ||
| 25 | + self.pos | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + /// Bits left in the buffer. | ||
| 29 | + pub fn bits_remaining(&self) -> u64 { | ||
| 30 | + (self.data.len() as u64 * 8).saturating_sub(self.pos) | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + /// True when the next bit starts a byte. | ||
| 34 | + pub fn is_byte_aligned(&self) -> bool { | ||
| 35 | + self.pos.is_multiple_of(8) | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + /// Skip to the next byte boundary; no-op when already aligned. | ||
| 39 | + pub fn align_to_byte(&mut self) { | ||
| 40 | + self.pos = self.pos.div_ceil(8) * 8; | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + /// Read `n` bits (`n <= 64`) into a `u64`. | ||
| 44 | + /// | ||
| 45 | + /// Panics if `n > 64` (a coding error, not an input error). | ||
| 46 | + pub fn read_bits64(&mut self, n: u32) -> Result<u64> { | ||
| 47 | + assert!(n <= 64, "read_bits64: n = {n} > 64"); | ||
| 48 | + if self.bits_remaining() < n as u64 { | ||
| 49 | + return Err(Error::NeedMore); | ||
| 50 | + } | ||
| 51 | + let mut value = 0u64; | ||
| 52 | + let mut left = n; | ||
| 53 | + while left > 0 { | ||
| 54 | + let byte = self.data[(self.pos >> 3) as usize]; | ||
| 55 | + let bit_off = (self.pos & 7) as u32; | ||
| 56 | + let take = left.min(8 - bit_off); | ||
| 57 | + let chunk = (byte << bit_off) >> (8 - take); | ||
| 58 | + value = (value << take) | chunk as u64; | ||
| 59 | + self.pos += take as u64; | ||
| 60 | + left -= take; | ||
| 61 | + } | ||
| 62 | + Ok(value) | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + /// Read `n` bits (`n <= 32`) into a `u32`. | ||
| 66 | + pub fn read_bits(&mut self, n: u32) -> Result<u32> { | ||
| 67 | + assert!(n <= 32, "read_bits: n = {n} > 32"); | ||
| 68 | + Ok(self.read_bits64(n)? as u32) | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + /// Read `n` bits as a two's-complement signed value (`1 <= n <= 32`). | ||
| 72 | + pub fn read_signed(&mut self, n: u32) -> Result<i32> { | ||
| 73 | + assert!((1..=32).contains(&n), "read_signed: n = {n} outside 1..=32"); | ||
| 74 | + let raw = self.read_bits(n)?; | ||
| 75 | + Ok(((raw << (32 - n)) as i32) >> (32 - n)) | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// Read one bit. | ||
| 79 | + pub fn read_bit(&mut self) -> Result<bool> { | ||
| 80 | + Ok(self.read_bits64(1)? != 0) | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + /// Read `n` bits without consuming them. | ||
| 84 | + pub fn peek_bits(&mut self, n: u32) -> Result<u32> { | ||
| 85 | + let saved = self.pos; | ||
| 86 | + let v = self.read_bits(n); | ||
| 87 | + self.pos = saved; | ||
| 88 | + v | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + /// Skip `n` bits, or [`Error::NeedMore`] if fewer remain. | ||
| 92 | + pub fn skip_bits(&mut self, n: u64) -> Result<()> { | ||
| 93 | + if self.bits_remaining() < n { | ||
| 94 | + return Err(Error::NeedMore); | ||
| 95 | + } | ||
| 96 | + self.pos += n; | ||
| 97 | + Ok(()) | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + /// Borrow `n` whole bytes from the current position, which must be aligned. | ||
| 101 | + pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8]> { | ||
| 102 | + if !self.is_byte_aligned() { | ||
| 103 | + return Err(Error::corrupt("read_bytes at a non-byte-aligned position")); | ||
| 104 | + } | ||
| 105 | + let start = (self.pos >> 3) as usize; | ||
| 106 | + let end = start.checked_add(n).ok_or(Error::NeedMore)?; | ||
| 107 | + let slice = self.data.get(start..end).ok_or(Error::NeedMore)?; | ||
| 108 | + self.pos += n as u64 * 8; | ||
| 109 | + Ok(slice) | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + /// Unsigned exp-Golomb `ue(v)`, as used by H.264 and H.265. | ||
| 113 | + /// | ||
| 114 | + /// The prefix is capped at 31 zero bits: 32 or more cannot encode a value | ||
| 115 | + /// in `u32` range, so it is a corrupt bitstream (and, on a fuzzer's input, | ||
| 116 | + /// the difference between an error and an unbounded loop). | ||
| 117 | + pub fn read_ue(&mut self) -> Result<u32> { | ||
| 118 | + let mut zeros = 0u32; | ||
| 119 | + while !self.read_bit()? { | ||
| 120 | + zeros += 1; | ||
| 121 | + if zeros > 31 { | ||
| 122 | + return Err(Error::corrupt("exp-Golomb prefix longer than 31 zero bits")); | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + if zeros == 0 { | ||
| 126 | + return Ok(0); | ||
| 127 | + } | ||
| 128 | + let suffix = self.read_bits(zeros)?; | ||
| 129 | + Ok((1u32 << zeros) - 1 + suffix) | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + /// Signed exp-Golomb `se(v)`. | ||
| 133 | + pub fn read_se(&mut self) -> Result<i32> { | ||
| 134 | + let k = self.read_ue()? as i64; | ||
| 135 | + let v = if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) }; | ||
| 136 | + i32::try_from(v).map_err(|_| Error::corrupt(format!("se(v) out of i32 range: {v}"))) | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// MSB-first bit writer. | ||
| 141 | +#[derive(Debug, Clone, Default)] | ||
| 142 | +pub struct BitWriter { | ||
| 143 | + buf: Vec<u8>, | ||
| 144 | + /// Bits already written into the last byte of `buf` (0 means byte aligned). | ||
| 145 | + used: u32, | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +impl BitWriter { | ||
| 149 | + /// An empty writer. | ||
| 150 | + pub fn new() -> BitWriter { | ||
| 151 | + BitWriter::default() | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + /// An empty writer with room for `bytes`. | ||
| 155 | + pub fn with_capacity(bytes: usize) -> BitWriter { | ||
| 156 | + BitWriter { | ||
| 157 | + buf: Vec::with_capacity(bytes), | ||
| 158 | + used: 0, | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + /// Bits written so far. | ||
| 163 | + pub fn bit_len(&self) -> u64 { | ||
| 164 | + if self.used == 0 { | ||
| 165 | + self.buf.len() as u64 * 8 | ||
| 166 | + } else { | ||
| 167 | + (self.buf.len() as u64 - 1) * 8 + self.used as u64 | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + /// True when the next bit would start a byte. | ||
| 172 | + pub fn is_byte_aligned(&self) -> bool { | ||
| 173 | + self.used == 0 | ||
| 174 | + } | ||
| 175 | + | ||
| 176 | + /// Write the low `n` bits of `value` (`n <= 64`), most significant first. | ||
| 177 | + pub fn write_bits64(&mut self, value: u64, n: u32) { | ||
| 178 | + assert!(n <= 64, "write_bits64: n = {n} > 64"); | ||
| 179 | + for i in (0..n).rev() { | ||
| 180 | + self.write_bit(value >> i & 1 == 1); | ||
| 181 | + } | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + /// Write the low `n` bits of `value` (`n <= 32`), most significant first. | ||
| 185 | + pub fn write_bits(&mut self, value: u32, n: u32) { | ||
| 186 | + assert!(n <= 32, "write_bits: n = {n} > 32"); | ||
| 187 | + self.write_bits64(value as u64, n); | ||
| 188 | + } | ||
| 189 | + | ||
| 190 | + /// Write a two's-complement signed value in `n` bits (`1 <= n <= 32`). | ||
| 191 | + pub fn write_signed(&mut self, value: i32, n: u32) { | ||
| 192 | + assert!( | ||
| 193 | + (1..=32).contains(&n), | ||
| 194 | + "write_signed: n = {n} outside 1..=32" | ||
| 195 | + ); | ||
| 196 | + self.write_bits((value as u32) & (u32::MAX >> (32 - n)), n); | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + /// Write one bit. | ||
| 200 | + pub fn write_bit(&mut self, bit: bool) { | ||
| 201 | + if self.used == 0 { | ||
| 202 | + self.buf.push(0); | ||
| 203 | + } | ||
| 204 | + if bit { | ||
| 205 | + let last = self.buf.len() - 1; | ||
| 206 | + self.buf[last] |= 0x80 >> self.used; | ||
| 207 | + } | ||
| 208 | + self.used = (self.used + 1) % 8; | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + /// Pad with zero bits up to the next byte boundary. | ||
| 212 | + pub fn align_to_byte(&mut self) { | ||
| 213 | + while self.used != 0 { | ||
| 214 | + self.write_bit(false); | ||
| 215 | + } | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + /// Unsigned exp-Golomb `ue(v)`. | ||
| 219 | + /// | ||
| 220 | + /// Panics on `u32::MAX`, which has no exp-Golomb form that reads back into | ||
| 221 | + /// `u32`; no codec in the family emits it. | ||
| 222 | + pub fn write_ue(&mut self, value: u32) { | ||
| 223 | + assert!(value != u32::MAX, "write_ue: u32::MAX is not encodable"); | ||
| 224 | + let x = value as u64 + 1; | ||
| 225 | + let bits = 64 - x.leading_zeros(); | ||
| 226 | + self.write_bits64(0, bits - 1); | ||
| 227 | + self.write_bits64(x, bits); | ||
| 228 | + } | ||
| 229 | + | ||
| 230 | + /// Signed exp-Golomb `se(v)`. | ||
| 231 | + pub fn write_se(&mut self, value: i32) { | ||
| 232 | + let k = if value > 0 { | ||
| 233 | + 2 * value as i64 - 1 | ||
| 234 | + } else { | ||
| 235 | + -2 * value as i64 | ||
| 236 | + }; | ||
| 237 | + let k = u32::try_from(k).expect("se(v) out of exp-Golomb range"); | ||
| 238 | + self.write_ue(k); | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + /// Append whole bytes; the writer must be byte aligned. | ||
| 242 | + /// | ||
| 243 | + /// Panics when misaligned — call [`BitWriter::align_to_byte`] first. | ||
| 244 | + pub fn write_bytes(&mut self, bytes: &[u8]) { | ||
| 245 | + assert!(self.is_byte_aligned(), "write_bytes while not byte aligned"); | ||
| 246 | + self.buf.extend_from_slice(bytes); | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + /// The bytes written so far; a trailing partial byte is zero padded. | ||
| 250 | + pub fn as_bytes(&self) -> &[u8] { | ||
| 251 | + &self.buf | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + /// Consume the writer, returning its bytes. | ||
| 255 | + pub fn into_bytes(self) -> Vec<u8> { | ||
| 256 | + self.buf | ||
| 257 | + } | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +/// LSB-first bit reader (Vorbis, and other Xiph-family bitstreams). | ||
| 261 | +#[derive(Debug, Clone)] | ||
| 262 | +pub struct BitReaderLsb<'a> { | ||
| 263 | + data: &'a [u8], | ||
| 264 | + pos: u64, | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +impl<'a> BitReaderLsb<'a> { | ||
| 268 | + /// A reader positioned at the first bit of `data`. | ||
| 269 | + pub fn new(data: &'a [u8]) -> BitReaderLsb<'a> { | ||
| 270 | + BitReaderLsb { data, pos: 0 } | ||
| 271 | + } | ||
| 272 | + | ||
| 273 | + /// Bits consumed so far. | ||
| 274 | + pub fn bit_position(&self) -> u64 { | ||
| 275 | + self.pos | ||
| 276 | + } | ||
| 277 | + | ||
| 278 | + /// Bits left in the buffer. | ||
| 279 | + pub fn bits_remaining(&self) -> u64 { | ||
| 280 | + (self.data.len() as u64 * 8).saturating_sub(self.pos) | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + /// True when the next bit starts a byte. | ||
| 284 | + pub fn is_byte_aligned(&self) -> bool { | ||
| 285 | + self.pos.is_multiple_of(8) | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + /// Skip to the next byte boundary; no-op when already aligned. | ||
| 289 | + pub fn align_to_byte(&mut self) { | ||
| 290 | + self.pos = self.pos.div_ceil(8) * 8; | ||
| 291 | + } | ||
| 292 | + | ||
| 293 | + /// Read `n` bits (`n <= 64`), least significant bit first. | ||
| 294 | + pub fn read_bits64(&mut self, n: u32) -> Result<u64> { | ||
| 295 | + assert!(n <= 64, "read_bits64: n = {n} > 64"); | ||
| 296 | + if self.bits_remaining() < n as u64 { | ||
| 297 | + return Err(Error::NeedMore); | ||
| 298 | + } | ||
| 299 | + let mut value = 0u64; | ||
| 300 | + let mut got = 0u32; | ||
| 301 | + while got < n { | ||
| 302 | + let byte = self.data[(self.pos >> 3) as usize]; | ||
| 303 | + let bit_off = (self.pos & 7) as u32; | ||
| 304 | + let take = (n - got).min(8 - bit_off); | ||
| 305 | + let mask = ((1u16 << take) - 1) as u8; | ||
| 306 | + let chunk = (byte >> bit_off) & mask; | ||
| 307 | + value |= (chunk as u64) << got; | ||
| 308 | + self.pos += take as u64; | ||
| 309 | + got += take; | ||
| 310 | + } | ||
| 311 | + Ok(value) | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + /// Read `n` bits (`n <= 32`), least significant bit first. | ||
| 315 | + pub fn read_bits(&mut self, n: u32) -> Result<u32> { | ||
| 316 | + assert!(n <= 32, "read_bits: n = {n} > 32"); | ||
| 317 | + Ok(self.read_bits64(n)? as u32) | ||
| 318 | + } | ||
| 319 | + | ||
| 320 | + /// Read one bit. | ||
| 321 | + pub fn read_bit(&mut self) -> Result<bool> { | ||
| 322 | + Ok(self.read_bits64(1)? != 0) | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + /// Skip `n` bits, or [`Error::NeedMore`] if fewer remain. | ||
| 326 | + pub fn skip_bits(&mut self, n: u64) -> Result<()> { | ||
| 327 | + if self.bits_remaining() < n { | ||
| 328 | + return Err(Error::NeedMore); | ||
| 329 | + } | ||
| 330 | + self.pos += n; | ||
| 331 | + Ok(()) | ||
| 332 | + } | ||
| 333 | +} | ||
| 334 | + | ||
| 335 | +/// LSB-first bit writer. | ||
| 336 | +#[derive(Debug, Clone, Default)] | ||
| 337 | +pub struct BitWriterLsb { | ||
| 338 | + buf: Vec<u8>, | ||
| 339 | + used: u32, | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +impl BitWriterLsb { | ||
| 343 | + /// An empty writer. | ||
| 344 | + pub fn new() -> BitWriterLsb { | ||
| 345 | + BitWriterLsb::default() | ||
| 346 | + } | ||
| 347 | + | ||
| 348 | + /// Bits written so far. | ||
| 349 | + pub fn bit_len(&self) -> u64 { | ||
| 350 | + if self.used == 0 { | ||
| 351 | + self.buf.len() as u64 * 8 | ||
| 352 | + } else { | ||
| 353 | + (self.buf.len() as u64 - 1) * 8 + self.used as u64 | ||
| 354 | + } | ||
| 355 | + } | ||
| 356 | + | ||
| 357 | + /// True when the next bit would start a byte. | ||
| 358 | + pub fn is_byte_aligned(&self) -> bool { | ||
| 359 | + self.used == 0 | ||
| 360 | + } | ||
| 361 | + | ||
| 362 | + /// Write the low `n` bits of `value` (`n <= 64`), least significant first. | ||
| 363 | + pub fn write_bits64(&mut self, value: u64, n: u32) { | ||
| 364 | + assert!(n <= 64, "write_bits64: n = {n} > 64"); | ||
| 365 | + for i in 0..n { | ||
| 366 | + self.write_bit(value >> i & 1 == 1); | ||
| 367 | + } | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + /// Write the low `n` bits of `value` (`n <= 32`), least significant first. | ||
| 371 | + pub fn write_bits(&mut self, value: u32, n: u32) { | ||
| 372 | + assert!(n <= 32, "write_bits: n = {n} > 32"); | ||
| 373 | + self.write_bits64(value as u64, n); | ||
| 374 | + } | ||
| 375 | + | ||
| 376 | + /// Write one bit. | ||
| 377 | + pub fn write_bit(&mut self, bit: bool) { | ||
| 378 | + if self.used == 0 { | ||
| 379 | + self.buf.push(0); | ||
| 380 | + } | ||
| 381 | + if bit { | ||
| 382 | + let last = self.buf.len() - 1; | ||
| 383 | + self.buf[last] |= 1 << self.used; | ||
| 384 | + } | ||
| 385 | + self.used = (self.used + 1) % 8; | ||
| 386 | + } | ||
| 387 | + | ||
| 388 | + /// Pad with zero bits up to the next byte boundary. | ||
| 389 | + pub fn align_to_byte(&mut self) { | ||
| 390 | + while self.used != 0 { | ||
| 391 | + self.write_bit(false); | ||
| 392 | + } | ||
| 393 | + } | ||
| 394 | + | ||
| 395 | + /// The bytes written so far; a trailing partial byte is zero padded. | ||
| 396 | + pub fn as_bytes(&self) -> &[u8] { | ||
| 397 | + &self.buf | ||
| 398 | + } | ||
| 399 | + | ||
| 400 | + /// Consume the writer, returning its bytes. | ||
| 401 | + pub fn into_bytes(self) -> Vec<u8> { | ||
| 402 | + self.buf | ||
| 403 | + } | ||
| 404 | +} | ||
| 405 | + | ||
| 406 | +#[cfg(test)] | ||
| 407 | +mod tests { | ||
| 408 | + use super::*; | ||
| 409 | + | ||
| 410 | + #[test] | ||
| 411 | + fn msb_round_trip_mixed_widths() { | ||
| 412 | + let widths = [1u32, 2, 3, 5, 7, 8, 9, 13, 16, 17, 24, 31, 32]; | ||
| 413 | + let mut w = BitWriter::new(); | ||
| 414 | + let mut values = Vec::new(); | ||
| 415 | + for (i, &n) in widths.iter().enumerate() { | ||
| 416 | + let v = if n == 32 { | ||
| 417 | + u32::MAX | ||
| 418 | + } else { | ||
| 419 | + ((0xDEAD_BEEFu64 >> i) as u32) & (u32::MAX >> (32 - n)) | ||
| 420 | + }; | ||
| 421 | + values.push(v); | ||
| 422 | + w.write_bits(v, n); | ||
| 423 | + } | ||
| 424 | + let bits = w.bit_len(); | ||
| 425 | + let bytes = w.into_bytes(); | ||
| 426 | + let mut r = BitReader::new(&bytes); | ||
| 427 | + for (&n, &v) in widths.iter().zip(&values) { | ||
| 428 | + assert_eq!(r.read_bits(n).unwrap(), v, "width {n}"); | ||
| 429 | + } | ||
| 430 | + assert_eq!(r.bit_position(), bits); | ||
| 431 | + } | ||
| 432 | + | ||
| 433 | + #[test] | ||
| 434 | + fn msb_bit_order_is_most_significant_first() { | ||
| 435 | + let mut w = BitWriter::new(); | ||
| 436 | + w.write_bits(0b101, 3); | ||
| 437 | + w.align_to_byte(); | ||
| 438 | + assert_eq!(w.as_bytes(), &[0b1010_0000]); | ||
| 439 | + let mut r = BitReader::new(&[0b1010_0000]); | ||
| 440 | + assert!(r.read_bit().unwrap()); | ||
| 441 | + assert!(!r.read_bit().unwrap()); | ||
| 442 | + assert!(r.read_bit().unwrap()); | ||
| 443 | + assert!(!r.is_byte_aligned()); | ||
| 444 | + r.align_to_byte(); | ||
| 445 | + assert!(r.is_byte_aligned()); | ||
| 446 | + assert_eq!(r.bits_remaining(), 0); | ||
| 447 | + } | ||
| 448 | + | ||
| 449 | + #[test] | ||
| 450 | + fn exp_golomb_round_trip_including_edges() { | ||
| 451 | + // 0 is a single '1' bit; the top of the range is 31 zeros + suffix. | ||
| 452 | + let values = [ | ||
| 453 | + 0u32, | ||
| 454 | + 1, | ||
| 455 | + 2, | ||
| 456 | + 3, | ||
| 457 | + 255, | ||
| 458 | + 256, | ||
| 459 | + 65_535, | ||
| 460 | + (1 << 31) - 2, | ||
| 461 | + (1 << 31) - 1, | ||
| 462 | + u32::MAX - 2, | ||
| 463 | + u32::MAX - 1, | ||
| 464 | + ]; | ||
| 465 | + for &v in &values { | ||
| 466 | + let mut w = BitWriter::new(); | ||
| 467 | + w.write_ue(v); | ||
| 468 | + let bits = w.bit_len(); | ||
| 469 | + let bytes = w.into_bytes(); | ||
| 470 | + let mut r = BitReader::new(&bytes); | ||
| 471 | + assert_eq!(r.read_ue().unwrap(), v, "ue({v})"); | ||
| 472 | + assert_eq!(r.bit_position(), bits, "ue({v}) length"); | ||
| 473 | + } | ||
| 474 | + let mut w = BitWriter::new(); | ||
| 475 | + w.write_ue(0); | ||
| 476 | + w.align_to_byte(); | ||
| 477 | + assert_eq!(w.as_bytes(), &[0b1000_0000]); | ||
| 478 | + } | ||
| 479 | + | ||
| 480 | + #[test] | ||
| 481 | + fn signed_exp_golomb_round_trip() { | ||
| 482 | + for v in [ | ||
| 483 | + 0i32, | ||
| 484 | + 1, | ||
| 485 | + -1, | ||
| 486 | + 2, | ||
| 487 | + -2, | ||
| 488 | + 1000, | ||
| 489 | + -1000, | ||
| 490 | + i32::MAX / 2, | ||
| 491 | + -(i32::MAX / 2), | ||
| 492 | + ] { | ||
| 493 | + let mut w = BitWriter::new(); | ||
| 494 | + w.write_se(v); | ||
| 495 | + let bytes = w.into_bytes(); | ||
| 496 | + assert_eq!(BitReader::new(&bytes).read_se().unwrap(), v, "se({v})"); | ||
| 497 | + } | ||
| 498 | + } | ||
| 499 | + | ||
| 500 | + #[test] | ||
| 501 | + fn truncation_is_need_more_never_panic() { | ||
| 502 | + let mut r = BitReader::new(&[0xFF, 0xFF]); | ||
| 503 | + assert!(r.read_bits(16).is_ok()); | ||
| 504 | + assert!(r.read_bits(1).unwrap_err().is_need_more()); | ||
| 505 | + assert!(BitReader::new(&[]).read_bit().unwrap_err().is_need_more()); | ||
| 506 | + assert!( | ||
| 507 | + BitReader::new(&[0x80]) | ||
| 508 | + .read_bits(9) | ||
| 509 | + .unwrap_err() | ||
| 510 | + .is_need_more() | ||
| 511 | + ); | ||
| 512 | + // A ue() whose suffix is cut off, and one with no terminating 1 bit. | ||
| 513 | + assert!( | ||
| 514 | + BitReader::new(&[0x01]) | ||
| 515 | + .read_ue() | ||
| 516 | + .unwrap_err() | ||
| 517 | + .is_need_more() | ||
| 518 | + ); | ||
| 519 | + assert!( | ||
| 520 | + BitReader::new(&[0x00, 0x00]) | ||
| 521 | + .read_ue() | ||
| 522 | + .unwrap_err() | ||
| 523 | + .is_need_more() | ||
| 524 | + ); | ||
| 525 | + // 32+ zero bits before the 1: corrupt, not an infinite scan. | ||
| 526 | + let long = [0u8, 0, 0, 0, 0x80]; | ||
| 527 | + let err = BitReader::new(&long).read_ue().unwrap_err(); | ||
| 528 | + assert!(matches!(err, Error::Corrupt { .. }), "{err}"); | ||
| 529 | + } | ||
| 530 | + | ||
| 531 | + #[test] | ||
| 532 | + fn signed_fixed_width_and_bytes() { | ||
| 533 | + let mut w = BitWriter::new(); | ||
| 534 | + w.write_signed(-3, 8); | ||
| 535 | + w.write_signed(7, 5); | ||
| 536 | + w.align_to_byte(); | ||
| 537 | + w.write_bytes(&[0xAB, 0xCD]); | ||
| 538 | + let bytes = w.into_bytes(); | ||
| 539 | + let mut r = BitReader::new(&bytes); | ||
| 540 | + assert_eq!(r.read_signed(8).unwrap(), -3); | ||
| 541 | + assert_eq!(r.read_signed(5).unwrap(), 7); | ||
| 542 | + r.align_to_byte(); | ||
| 543 | + assert_eq!(r.read_bytes(2).unwrap(), &[0xAB, 0xCD]); | ||
| 544 | + assert!(r.read_bytes(1).unwrap_err().is_need_more()); | ||
| 545 | + // Misaligned byte reads are refused rather than silently realigned. | ||
| 546 | + let mut r = BitReader::new(&bytes); | ||
| 547 | + r.read_bit().unwrap(); | ||
| 548 | + assert!(matches!(r.read_bytes(1), Err(Error::Corrupt { .. }))); | ||
| 549 | + } | ||
| 550 | + | ||
| 551 | + #[test] | ||
| 552 | + fn peek_and_skip_do_not_diverge() { | ||
| 553 | + let mut r = BitReader::new(&[0b1011_0010, 0xFF]); | ||
| 554 | + assert_eq!(r.peek_bits(4).unwrap(), 0b1011); | ||
| 555 | + assert_eq!(r.bit_position(), 0); | ||
| 556 | + r.skip_bits(4).unwrap(); | ||
| 557 | + assert_eq!(r.read_bits(4).unwrap(), 0b0010); | ||
| 558 | + assert!(r.skip_bits(9).is_err()); | ||
| 559 | + assert_eq!(r.bits_remaining(), 8); | ||
| 560 | + } | ||
| 561 | + | ||
| 562 | + #[test] | ||
| 563 | + fn lsb_round_trip_and_order() { | ||
| 564 | + let mut w = BitWriterLsb::new(); | ||
| 565 | + w.write_bits(0b101, 3); | ||
| 566 | + w.align_to_byte(); | ||
| 567 | + assert_eq!(w.as_bytes(), &[0b0000_0101]); | ||
| 568 | + | ||
| 569 | + let widths = [1u32, 4, 7, 11, 16, 32]; | ||
| 570 | + let mut w = BitWriterLsb::new(); | ||
| 571 | + let mut values = Vec::new(); | ||
| 572 | + for (i, &n) in widths.iter().enumerate() { | ||
| 573 | + let v = ((0xCAFE_F00Du64 >> i) as u32) & (u32::MAX >> (32 - n)); | ||
| 574 | + values.push(v); | ||
| 575 | + w.write_bits(v, n); | ||
| 576 | + } | ||
| 577 | + let bytes = w.into_bytes(); | ||
| 578 | + let mut r = BitReaderLsb::new(&bytes); | ||
| 579 | + for (&n, &v) in widths.iter().zip(&values) { | ||
| 580 | + assert_eq!(r.read_bits(n).unwrap(), v, "lsb width {n}"); | ||
| 581 | + } | ||
| 582 | + assert_eq!(r.bits_remaining(), 1); // 71 bits written, padded to 9 bytes | ||
| 583 | + } | ||
| 584 | + | ||
| 585 | + #[test] | ||
| 586 | + fn lsb_truncation_is_need_more() { | ||
| 587 | + let mut r = BitReaderLsb::new(&[0x0F]); | ||
| 588 | + assert_eq!(r.read_bits(4).unwrap(), 0x0F); | ||
| 589 | + assert!(r.read_bits(5).unwrap_err().is_need_more()); | ||
| 590 | + assert!(r.skip_bits(5).is_err()); | ||
| 591 | + r.align_to_byte(); | ||
| 592 | + assert_eq!(r.bits_remaining(), 0); | ||
| 593 | + } | ||
| 594 | +} | ||
crates/ec-core/src/error.rsadded+89 -0
| @@ -0,0 +1,89 @@ | |||
| 1 | +//! Family-wide error type. | ||
| 2 | + | ||
| 3 | +use std::fmt; | ||
| 4 | + | ||
| 5 | +/// Result alias used by every crate in the family. | ||
| 6 | +pub type Result<T> = std::result::Result<T, Error>; | ||
| 7 | + | ||
| 8 | +/// Everything that can go wrong in a demuxer, decoder, encoder or muxer. | ||
| 9 | +/// | ||
| 10 | +/// The taxonomy is deliberately small: callers branch on "give me more data" | ||
| 11 | +/// (`NeedMore`), "the stream ended" (`Eof`), "this input is broken" (`Corrupt`) | ||
| 12 | +/// and "we do not implement this" (`Unsupported`). Every `Unsupported` carries | ||
| 13 | +/// both *what* was refused and *why* — a refusal string without a reason is a | ||
| 14 | +/// bug report waiting to happen, not a diagnosis. | ||
| 15 | +#[derive(Debug)] | ||
| 16 | +pub enum Error { | ||
| 17 | + /// Not enough data buffered yet; feed more and retry the same call. | ||
| 18 | + NeedMore, | ||
| 19 | + /// End of stream reached; no further data will ever arrive. | ||
| 20 | + Eof, | ||
| 21 | + /// A capability this build genuinely does not have. | ||
| 22 | + Unsupported { | ||
| 23 | + /// The construct that was refused, e.g. "HE-AAC SBR". | ||
| 24 | + what: String, | ||
| 25 | + /// Why it is refused, e.g. "SBR resampler not implemented". | ||
| 26 | + why: String, | ||
| 27 | + }, | ||
| 28 | + /// The bitstream violates its own format rules. | ||
| 29 | + Corrupt { | ||
| 30 | + /// Where and how, e.g. "H.264 SPS: log2_max_frame_num_minus4 = 13". | ||
| 31 | + context: String, | ||
| 32 | + }, | ||
| 33 | + /// Underlying I/O failure. | ||
| 34 | + Io(std::io::Error), | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +impl Error { | ||
| 38 | + /// Build an [`Error::Unsupported`] from any two string-likes. | ||
| 39 | + pub fn unsupported(what: impl Into<String>, why: impl Into<String>) -> Self { | ||
| 40 | + Error::Unsupported { | ||
| 41 | + what: what.into(), | ||
| 42 | + why: why.into(), | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// Build an [`Error::Corrupt`] from any string-like. | ||
| 47 | + pub fn corrupt(context: impl Into<String>) -> Self { | ||
| 48 | + Error::Corrupt { | ||
| 49 | + context: context.into(), | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// True for [`Error::NeedMore`] — the streaming "try again later" contract. | ||
| 54 | + pub fn is_need_more(&self) -> bool { | ||
| 55 | + matches!(self, Error::NeedMore) | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// True for [`Error::Eof`]. | ||
| 59 | + pub fn is_eof(&self) -> bool { | ||
| 60 | + matches!(self, Error::Eof) | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +impl fmt::Display for Error { | ||
| 65 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 66 | + match self { | ||
| 67 | + Error::NeedMore => write!(f, "need more data"), | ||
| 68 | + Error::Eof => write!(f, "end of stream"), | ||
| 69 | + Error::Unsupported { what, why } => write!(f, "unsupported: {what} ({why})"), | ||
| 70 | + Error::Corrupt { context } => write!(f, "corrupt bitstream: {context}"), | ||
| 71 | + Error::Io(e) => write!(f, "io error: {e}"), | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +impl std::error::Error for Error { | ||
| 77 | + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | ||
| 78 | + match self { | ||
| 79 | + Error::Io(e) => Some(e), | ||
| 80 | + _ => None, | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +impl From<std::io::Error> for Error { | ||
| 86 | + fn from(e: std::io::Error) -> Self { | ||
| 87 | + Error::Io(e) | ||
| 88 | + } | ||
| 89 | +} | ||
crates/ec-core/src/frame.rsadded+603 -0
| @@ -0,0 +1,603 @@ | |||
| 1 | +//! Decoded units: pictures and audio blocks. | ||
| 2 | + | ||
| 3 | +use crate::error::{Error, Result}; | ||
| 4 | +use crate::packet::Buf; | ||
| 5 | +use crate::timebase::Timestamp; | ||
| 6 | + | ||
| 7 | +/// Pixel layout of a [`VideoFrame`]. | ||
| 8 | +/// | ||
| 9 | +/// Covers what the family actually moves: planar YUV 8/10/16-bit (software | ||
| 10 | +/// codecs), the semi-planar pairs hardware hands back (NV12, P010) and packed | ||
| 11 | +/// RGB for the display sink. | ||
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 13 | +pub enum PixelFormat { | ||
| 14 | + /// Planar Y/U/V 4:2:0, 8-bit. | ||
| 15 | + I420, | ||
| 16 | + /// Planar Y/U/V 4:2:2, 8-bit. | ||
| 17 | + I422, | ||
| 18 | + /// Planar Y/U/V 4:4:4, 8-bit. | ||
| 19 | + I444, | ||
| 20 | + /// Planar Y/U/V 4:2:0, 10-bit in 16-bit little-endian samples. | ||
| 21 | + I010, | ||
| 22 | + /// Planar Y/U/V 4:2:2, 10-bit in 16-bit little-endian samples. | ||
| 23 | + I210, | ||
| 24 | + /// Planar Y/U/V 4:4:4, 10-bit in 16-bit little-endian samples. | ||
| 25 | + I410, | ||
| 26 | + /// Y plane + interleaved U/V, 4:2:0, 8-bit. | ||
| 27 | + Nv12, | ||
| 28 | + /// Y plane + interleaved V/U, 4:2:0, 8-bit. | ||
| 29 | + Nv21, | ||
| 30 | + /// Y plane + interleaved U/V, 4:2:0, 10-bit in the high bits of 16. | ||
| 31 | + P010, | ||
| 32 | + /// Y plane + interleaved U/V, 4:2:0, 16-bit. | ||
| 33 | + P016, | ||
| 34 | + /// Single 8-bit luma plane. | ||
| 35 | + Gray8, | ||
| 36 | + /// Single 16-bit luma plane. | ||
| 37 | + Gray16, | ||
| 38 | + /// Packed 8-bit R,G,B. | ||
| 39 | + Rgb8, | ||
| 40 | + /// Packed 8-bit B,G,R. | ||
| 41 | + Bgr8, | ||
| 42 | + /// Packed 8-bit R,G,B,A. | ||
| 43 | + Rgba8, | ||
| 44 | + /// Packed 8-bit B,G,R,A — edith's display currency. | ||
| 45 | + Bgra8, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +impl PixelFormat { | ||
| 49 | + /// Number of planes the format stores. | ||
| 50 | + pub fn plane_count(&self) -> usize { | ||
| 51 | + use PixelFormat::*; | ||
| 52 | + match self { | ||
| 53 | + I420 | I422 | I444 | I010 | I210 | I410 => 3, | ||
| 54 | + Nv12 | Nv21 | P010 | P016 => 2, | ||
| 55 | + Gray8 | Gray16 | Rgb8 | Bgr8 | Rgba8 | Bgra8 => 1, | ||
| 56 | + } | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + /// True when chroma lives in its own plane(s) rather than packed with luma. | ||
| 60 | + pub fn is_planar(&self) -> bool { | ||
| 61 | + self.plane_count() > 1 | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + /// True for the YUV families (planar and semi-planar). | ||
| 65 | + pub fn is_yuv(&self) -> bool { | ||
| 66 | + use PixelFormat::*; | ||
| 67 | + matches!( | ||
| 68 | + self, | ||
| 69 | + I420 | I422 | I444 | I010 | I210 | I410 | Nv12 | Nv21 | P010 | P016 | ||
| 70 | + ) | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + /// True when the format carries an alpha channel. | ||
| 74 | + pub fn has_alpha(&self) -> bool { | ||
| 75 | + matches!(self, PixelFormat::Rgba8 | PixelFormat::Bgra8) | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// Significant bits per component (10 for P010 even though it stores 16). | ||
| 79 | + pub fn bits_per_component(&self) -> u32 { | ||
| 80 | + use PixelFormat::*; | ||
| 81 | + match self { | ||
| 82 | + I010 | I210 | I410 | P010 => 10, | ||
| 83 | + Gray16 | P016 => 16, | ||
| 84 | + _ => 8, | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + /// Storage bytes per component (2 for every 10- and 16-bit format). | ||
| 89 | + pub fn bytes_per_component(&self) -> usize { | ||
| 90 | + if self.bits_per_component() > 8 { 2 } else { 1 } | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + /// `(log2 horizontal, log2 vertical)` chroma subsampling; `(0, 0)` for | ||
| 94 | + /// non-subsampled and non-YUV formats. | ||
| 95 | + pub fn chroma_shift(&self) -> (u32, u32) { | ||
| 96 | + use PixelFormat::*; | ||
| 97 | + match self { | ||
| 98 | + I420 | I010 | Nv12 | Nv21 | P010 | P016 => (1, 1), | ||
| 99 | + I422 | I210 => (1, 0), | ||
| 100 | + _ => (0, 0), | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// Per plane: `(minimum bytes per row, number of rows)` for `width x height`. | ||
| 105 | + pub fn plane_geometry(&self, width: u32, height: u32) -> Vec<(usize, usize)> { | ||
| 106 | + use PixelFormat::*; | ||
| 107 | + let (w, h) = (width as usize, height as usize); | ||
| 108 | + let bpc = self.bytes_per_component(); | ||
| 109 | + let (sx, sy) = self.chroma_shift(); | ||
| 110 | + let cw = w.div_ceil(1 << sx); | ||
| 111 | + let ch = h.div_ceil(1 << sy); | ||
| 112 | + match self { | ||
| 113 | + I420 | I422 | I444 | I010 | I210 | I410 => { | ||
| 114 | + vec![(w * bpc, h), (cw * bpc, ch), (cw * bpc, ch)] | ||
| 115 | + } | ||
| 116 | + Nv12 | Nv21 | P010 | P016 => vec![(w * bpc, h), (cw * 2 * bpc, ch)], | ||
| 117 | + Gray8 | Gray16 => vec![(w * bpc, h)], | ||
| 118 | + Rgb8 | Bgr8 => vec![(w * 3, h)], | ||
| 119 | + Rgba8 | Bgra8 => vec![(w * 4, h)], | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// One image plane: bytes plus the distance between row starts. | ||
| 125 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 126 | +pub struct Plane { | ||
| 127 | + /// Plane bytes; may be a shared slice of a larger buffer. | ||
| 128 | + pub data: Buf, | ||
| 129 | + /// Bytes from the start of one row to the start of the next. | ||
| 130 | + pub stride: usize, | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +impl Plane { | ||
| 134 | + /// A plane over `data` with row pitch `stride`. | ||
| 135 | + pub fn new(data: impl Into<Buf>, stride: usize) -> Plane { | ||
| 136 | + Plane { | ||
| 137 | + data: data.into(), | ||
| 138 | + stride, | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + /// Row `y` of the plane, `len` bytes wide, or `None` when out of range. | ||
| 143 | + pub fn row(&self, y: usize, len: usize) -> Option<&[u8]> { | ||
| 144 | + let start = y.checked_mul(self.stride)?; | ||
| 145 | + self.data.get(start..start.checked_add(len)?) | ||
| 146 | + } | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// CICP (ITU-T H.273) colour code points, carried verbatim. | ||
| 150 | +/// | ||
| 151 | +/// Kept as raw code points here so the IR never loses a value it cannot name; | ||
| 152 | +/// the named tables (BT.709/2020, PQ, HLG, ...) live in the colour module built | ||
| 153 | +/// on top of this. | ||
| 154 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 155 | +pub struct ColorInfo { | ||
| 156 | + /// `colour_primaries` code point (1 = BT.709, 9 = BT.2020, 2 = unspecified). | ||
| 157 | + pub primaries: u8, | ||
| 158 | + /// `transfer_characteristics` code point (16 = PQ, 18 = HLG). | ||
| 159 | + pub transfer: u8, | ||
| 160 | + /// `matrix_coefficients` code point (1 = BT.709, 9 = BT.2020 NCL). | ||
| 161 | + pub matrix: u8, | ||
| 162 | + /// `video_full_range_flag`: false = limited (16-235), true = full. | ||
| 163 | + pub full_range: bool, | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +impl Default for ColorInfo { | ||
| 167 | + /// All three code points unspecified (2), limited range. | ||
| 168 | + fn default() -> Self { | ||
| 169 | + ColorInfo { | ||
| 170 | + primaries: 2, | ||
| 171 | + transfer: 2, | ||
| 172 | + matrix: 2, | ||
| 173 | + full_range: false, | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +/// A decoded picture. | ||
| 179 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 180 | +pub struct VideoFrame { | ||
| 181 | + /// Pixel layout of `planes`. | ||
| 182 | + pub format: PixelFormat, | ||
| 183 | + /// Visible width in pixels. | ||
| 184 | + pub width: u32, | ||
| 185 | + /// Visible height in pixels. | ||
| 186 | + pub height: u32, | ||
| 187 | + /// One entry per [`PixelFormat::plane_count`]. | ||
| 188 | + pub planes: Vec<Plane>, | ||
| 189 | + /// Colour description as signalled by the bitstream or container. | ||
| 190 | + pub color: ColorInfo, | ||
| 191 | + /// Presentation time, when the source provided one. | ||
| 192 | + pub pts: Option<Timestamp>, | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +impl VideoFrame { | ||
| 196 | + /// A frame over existing planes, validating plane count and plane sizes. | ||
| 197 | + /// | ||
| 198 | + /// This is the trust boundary between a decoder and everything that indexes | ||
| 199 | + /// planes afterwards; a short plane fails here rather than in a converter. | ||
| 200 | + pub fn try_new( | ||
| 201 | + format: PixelFormat, | ||
| 202 | + width: u32, | ||
| 203 | + height: u32, | ||
| 204 | + planes: Vec<Plane>, | ||
| 205 | + ) -> Result<VideoFrame> { | ||
| 206 | + let geometry = format.plane_geometry(width, height); | ||
| 207 | + if planes.len() != geometry.len() { | ||
| 208 | + return Err(Error::corrupt(format!( | ||
| 209 | + "{format:?} needs {} planes, got {}", | ||
| 210 | + geometry.len(), | ||
| 211 | + planes.len() | ||
| 212 | + ))); | ||
| 213 | + } | ||
| 214 | + for (i, (plane, (row_bytes, rows))) in planes.iter().zip(geometry).enumerate() { | ||
| 215 | + if plane.stride < row_bytes { | ||
| 216 | + return Err(Error::corrupt(format!( | ||
| 217 | + "plane {i}: stride {} < {row_bytes} bytes per row", | ||
| 218 | + plane.stride | ||
| 219 | + ))); | ||
| 220 | + } | ||
| 221 | + // The last row need only hold its visible bytes, not a full stride. | ||
| 222 | + let needed = rows.saturating_sub(1) * plane.stride + row_bytes; | ||
| 223 | + if plane.data.len() < needed { | ||
| 224 | + return Err(Error::corrupt(format!( | ||
| 225 | + "plane {i}: {} bytes for {rows} rows of stride {}", | ||
| 226 | + plane.data.len(), | ||
| 227 | + plane.stride | ||
| 228 | + ))); | ||
| 229 | + } | ||
| 230 | + } | ||
| 231 | + Ok(VideoFrame { | ||
| 232 | + format, | ||
| 233 | + width, | ||
| 234 | + height, | ||
| 235 | + planes, | ||
| 236 | + color: ColorInfo::default(), | ||
| 237 | + pts: None, | ||
| 238 | + }) | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + /// A zeroed frame with tightly packed planes. | ||
| 242 | + pub fn alloc(format: PixelFormat, width: u32, height: u32) -> VideoFrame { | ||
| 243 | + let planes = format | ||
| 244 | + .plane_geometry(width, height) | ||
| 245 | + .into_iter() | ||
| 246 | + .map(|(row_bytes, rows)| Plane::new(vec![0u8; row_bytes * rows], row_bytes)) | ||
| 247 | + .collect(); | ||
| 248 | + VideoFrame { | ||
| 249 | + format, | ||
| 250 | + width, | ||
| 251 | + height, | ||
| 252 | + planes, | ||
| 253 | + color: ColorInfo::default(), | ||
| 254 | + pts: None, | ||
| 255 | + } | ||
| 256 | + } | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +/// Sample storage of an [`AudioFrame`]. 24-bit sources decode into [`SampleFormat::S32`]. | ||
| 260 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 261 | +pub enum SampleFormat { | ||
| 262 | + /// Unsigned 8-bit. | ||
| 263 | + U8, | ||
| 264 | + /// Signed 16-bit native endian. | ||
| 265 | + S16, | ||
| 266 | + /// Signed 32-bit native endian. | ||
| 267 | + S32, | ||
| 268 | + /// 32-bit float, nominal range -1.0..=1.0 — the family's mixing currency. | ||
| 269 | + F32, | ||
| 270 | + /// 64-bit float. | ||
| 271 | + F64, | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +impl SampleFormat { | ||
| 275 | + /// Bytes one sample of one channel occupies. | ||
| 276 | + pub fn bytes_per_sample(&self) -> usize { | ||
| 277 | + match self { | ||
| 278 | + SampleFormat::U8 => 1, | ||
| 279 | + SampleFormat::S16 => 2, | ||
| 280 | + SampleFormat::S32 | SampleFormat::F32 => 4, | ||
| 281 | + SampleFormat::F64 => 8, | ||
| 282 | + } | ||
| 283 | + } | ||
| 284 | + | ||
| 285 | + /// True for the float formats. | ||
| 286 | + pub fn is_float(&self) -> bool { | ||
| 287 | + matches!(self, SampleFormat::F32 | SampleFormat::F64) | ||
| 288 | + } | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +/// A named speaker position. | ||
| 292 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 293 | +pub enum ChannelPosition { | ||
| 294 | + /// Front left. | ||
| 295 | + FrontLeft, | ||
| 296 | + /// Front right. | ||
| 297 | + FrontRight, | ||
| 298 | + /// Front centre. | ||
| 299 | + FrontCenter, | ||
| 300 | + /// Low frequency effects. | ||
| 301 | + Lfe, | ||
| 302 | + /// Back (surround) left. | ||
| 303 | + BackLeft, | ||
| 304 | + /// Back (surround) right. | ||
| 305 | + BackRight, | ||
| 306 | + /// Side left. | ||
| 307 | + SideLeft, | ||
| 308 | + /// Side right. | ||
| 309 | + SideRight, | ||
| 310 | + /// Back centre. | ||
| 311 | + BackCenter, | ||
| 312 | + /// Front left of centre. | ||
| 313 | + FrontLeftOfCenter, | ||
| 314 | + /// Front right of centre. | ||
| 315 | + FrontRightOfCenter, | ||
| 316 | +} | ||
| 317 | + | ||
| 318 | +use ChannelPosition::*; | ||
| 319 | + | ||
| 320 | +const MONO: &[ChannelPosition] = &[FrontCenter]; | ||
| 321 | +const STEREO: &[ChannelPosition] = &[FrontLeft, FrontRight]; | ||
| 322 | +const SURROUND_5_1: &[ChannelPosition] = | ||
| 323 | + &[FrontLeft, FrontRight, FrontCenter, Lfe, BackLeft, BackRight]; | ||
| 324 | +const SURROUND_7_1: &[ChannelPosition] = &[ | ||
| 325 | + FrontLeft, | ||
| 326 | + FrontRight, | ||
| 327 | + FrontCenter, | ||
| 328 | + Lfe, | ||
| 329 | + BackLeft, | ||
| 330 | + BackRight, | ||
| 331 | + SideLeft, | ||
| 332 | + SideRight, | ||
| 333 | +]; | ||
| 334 | + | ||
| 335 | +/// Channel count plus the meaning and order of each channel. | ||
| 336 | +/// | ||
| 337 | +/// The named layouts fix the interleaving order the family decodes and encodes | ||
| 338 | +/// in; 5.1 is FL, FR, FC, LFE, BL, BR. | ||
| 339 | +#[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
| 340 | +pub enum ChannelLayout { | ||
| 341 | + /// One channel, front centre. | ||
| 342 | + Mono, | ||
| 343 | + /// FL, FR. | ||
| 344 | + Stereo, | ||
| 345 | + /// FL, FR, FC, LFE, BL, BR. | ||
| 346 | + Surround5_1, | ||
| 347 | + /// FL, FR, FC, LFE, BL, BR, SL, SR. | ||
| 348 | + Surround7_1, | ||
| 349 | + /// Any other ordering a container states explicitly. | ||
| 350 | + Custom(Vec<ChannelPosition>), | ||
| 351 | +} | ||
| 352 | + | ||
| 353 | +impl ChannelLayout { | ||
| 354 | + /// Channel order, as interleaved and as planes are indexed. | ||
| 355 | + pub fn positions(&self) -> &[ChannelPosition] { | ||
| 356 | + match self { | ||
| 357 | + ChannelLayout::Mono => MONO, | ||
| 358 | + ChannelLayout::Stereo => STEREO, | ||
| 359 | + ChannelLayout::Surround5_1 => SURROUND_5_1, | ||
| 360 | + ChannelLayout::Surround7_1 => SURROUND_7_1, | ||
| 361 | + ChannelLayout::Custom(v) => v, | ||
| 362 | + } | ||
| 363 | + } | ||
| 364 | + | ||
| 365 | + /// Number of channels. | ||
| 366 | + pub fn channel_count(&self) -> usize { | ||
| 367 | + self.positions().len() | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + /// The default layout for a bare channel count, as containers that state | ||
| 371 | + /// only a count intend it. | ||
| 372 | + pub fn from_count(n: usize) -> ChannelLayout { | ||
| 373 | + match n { | ||
| 374 | + 1 => ChannelLayout::Mono, | ||
| 375 | + 2 => ChannelLayout::Stereo, | ||
| 376 | + 6 => ChannelLayout::Surround5_1, | ||
| 377 | + 8 => ChannelLayout::Surround7_1, | ||
| 378 | + _ => ChannelLayout::Custom(vec![FrontCenter; n]), | ||
| 379 | + } | ||
| 380 | + } | ||
| 381 | +} | ||
| 382 | + | ||
| 383 | +/// A decoded block of audio. | ||
| 384 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 385 | +pub struct AudioFrame { | ||
| 386 | + /// Sample storage format. | ||
| 387 | + pub format: SampleFormat, | ||
| 388 | + /// True when `data` holds one plane per channel, false when interleaved. | ||
| 389 | + pub planar: bool, | ||
| 390 | + /// Channel count, order and meaning. | ||
| 391 | + pub layout: ChannelLayout, | ||
| 392 | + /// Sample rate in Hz. | ||
| 393 | + pub rate: u32, | ||
| 394 | + /// Samples per channel in this frame. | ||
| 395 | + pub samples: usize, | ||
| 396 | + /// One plane when interleaved, one per channel when planar. | ||
| 397 | + pub data: Vec<Buf>, | ||
| 398 | + /// Presentation time, when the source provided one. | ||
| 399 | + pub pts: Option<Timestamp>, | ||
| 400 | +} | ||
| 401 | + | ||
| 402 | +impl AudioFrame { | ||
| 403 | + /// An audio frame over existing planes, validating plane count and length. | ||
| 404 | + pub fn try_new( | ||
| 405 | + format: SampleFormat, | ||
| 406 | + planar: bool, | ||
| 407 | + layout: ChannelLayout, | ||
| 408 | + rate: u32, | ||
| 409 | + samples: usize, | ||
| 410 | + data: Vec<Buf>, | ||
| 411 | + ) -> Result<AudioFrame> { | ||
| 412 | + let channels = layout.channel_count(); | ||
| 413 | + let wanted_planes = if planar { channels } else { 1 }; | ||
| 414 | + if data.len() != wanted_planes { | ||
| 415 | + return Err(Error::corrupt(format!( | ||
| 416 | + "{layout:?} {} needs {wanted_planes} planes, got {}", | ||
| 417 | + if planar { "planar" } else { "interleaved" }, | ||
| 418 | + data.len() | ||
| 419 | + ))); | ||
| 420 | + } | ||
| 421 | + let per_plane = if planar { 1 } else { channels }; | ||
| 422 | + let needed = samples * per_plane * format.bytes_per_sample(); | ||
| 423 | + for (i, plane) in data.iter().enumerate() { | ||
| 424 | + if plane.len() < needed { | ||
| 425 | + return Err(Error::corrupt(format!( | ||
| 426 | + "audio plane {i}: {} bytes, {needed} needed for {samples} samples", | ||
| 427 | + plane.len() | ||
| 428 | + ))); | ||
| 429 | + } | ||
| 430 | + } | ||
| 431 | + Ok(AudioFrame { | ||
| 432 | + format, | ||
| 433 | + planar, | ||
| 434 | + layout, | ||
| 435 | + rate, | ||
| 436 | + samples, | ||
| 437 | + data, | ||
| 438 | + pts: None, | ||
| 439 | + }) | ||
| 440 | + } | ||
| 441 | + | ||
| 442 | + /// Channel count of the layout. | ||
| 443 | + pub fn channels(&self) -> usize { | ||
| 444 | + self.layout.channel_count() | ||
| 445 | + } | ||
| 446 | +} | ||
| 447 | + | ||
| 448 | +/// What a decoder produces. | ||
| 449 | +/// | ||
| 450 | +/// Subtitles are deliberately absent: a decoded subtitle is a cue list or a | ||
| 451 | +/// bitmap region set, not a sample grid, so subtitle streams travel as | ||
| 452 | +/// [`crate::packet::Packet`]s and are parsed by the subtitle crate into its own | ||
| 453 | +/// IR. | ||
| 454 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 455 | +pub enum Frame { | ||
| 456 | + /// A decoded picture. | ||
| 457 | + Video(VideoFrame), | ||
| 458 | + /// A decoded audio block. | ||
| 459 | + Audio(AudioFrame), | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +impl Frame { | ||
| 463 | + /// Presentation time of either variant. | ||
| 464 | + pub fn pts(&self) -> Option<Timestamp> { | ||
| 465 | + match self { | ||
| 466 | + Frame::Video(v) => v.pts, | ||
| 467 | + Frame::Audio(a) => a.pts, | ||
| 468 | + } | ||
| 469 | + } | ||
| 470 | +} | ||
| 471 | + | ||
| 472 | +#[cfg(test)] | ||
| 473 | +mod tests { | ||
| 474 | + use super::*; | ||
| 475 | + use crate::timebase::TimeBase; | ||
| 476 | + | ||
| 477 | + #[test] | ||
| 478 | + fn plane_geometry_matches_formats() { | ||
| 479 | + // Odd dimensions round chroma up, never down. | ||
| 480 | + assert_eq!( | ||
| 481 | + PixelFormat::I420.plane_geometry(1921, 1081), | ||
| 482 | + vec![(1921, 1081), (961, 541), (961, 541)] | ||
| 483 | + ); | ||
| 484 | + assert_eq!( | ||
| 485 | + PixelFormat::Nv12.plane_geometry(1920, 1080), | ||
| 486 | + vec![(1920, 1080), (1920, 540)] | ||
| 487 | + ); | ||
| 488 | + // P010: 2 bytes per component, interleaved chroma pair. | ||
| 489 | + assert_eq!( | ||
| 490 | + PixelFormat::P010.plane_geometry(1920, 1080), | ||
| 491 | + vec![(3840, 1080), (3840, 540)] | ||
| 492 | + ); | ||
| 493 | + assert_eq!(PixelFormat::Bgra8.plane_geometry(64, 4), vec![(256, 4)]); | ||
| 494 | + assert_eq!(PixelFormat::I444.plane_geometry(16, 16).len(), 3); | ||
| 495 | + assert_eq!(PixelFormat::P010.bits_per_component(), 10); | ||
| 496 | + assert_eq!(PixelFormat::P010.bytes_per_component(), 2); | ||
| 497 | + assert!(PixelFormat::Bgra8.has_alpha()); | ||
| 498 | + assert!(!PixelFormat::Nv12.has_alpha()); | ||
| 499 | + assert!(PixelFormat::Nv12.is_yuv()); | ||
| 500 | + } | ||
| 501 | + | ||
| 502 | + #[test] | ||
| 503 | + fn video_frame_validates_planes() { | ||
| 504 | + let f = VideoFrame::alloc(PixelFormat::I420, 64, 32); | ||
| 505 | + assert_eq!(f.planes.len(), 3); | ||
| 506 | + assert_eq!(f.planes[0].stride, 64); | ||
| 507 | + assert_eq!(f.planes[1].data.len(), 32 * 16); | ||
| 508 | + assert_eq!(f.planes[0].row(31, 64).unwrap().len(), 64); | ||
| 509 | + assert!(f.planes[0].row(32, 64).is_none()); | ||
| 510 | + | ||
| 511 | + // Padded strides are legal; short planes and short strides are not. | ||
| 512 | + let padded = VideoFrame::try_new( | ||
| 513 | + PixelFormat::Gray8, | ||
| 514 | + 4, | ||
| 515 | + 2, | ||
| 516 | + vec![Plane::new(vec![0u8; 8 + 4], 8)], | ||
| 517 | + ); | ||
| 518 | + assert!(padded.is_ok()); | ||
| 519 | + assert!( | ||
| 520 | + VideoFrame::try_new(PixelFormat::Gray8, 4, 2, vec![Plane::new(vec![0u8; 8], 2)]) | ||
| 521 | + .is_err() | ||
| 522 | + ); | ||
| 523 | + assert!( | ||
| 524 | + VideoFrame::try_new(PixelFormat::I420, 4, 2, vec![Plane::new(vec![0u8; 8], 4)]) | ||
| 525 | + .is_err() | ||
| 526 | + ); | ||
| 527 | + } | ||
| 528 | + | ||
| 529 | + #[test] | ||
| 530 | + fn channel_layouts_are_named_and_ordered() { | ||
| 531 | + assert_eq!( | ||
| 532 | + ChannelLayout::Surround5_1.positions(), | ||
| 533 | + &[ | ||
| 534 | + ChannelPosition::FrontLeft, | ||
| 535 | + ChannelPosition::FrontRight, | ||
| 536 | + ChannelPosition::FrontCenter, | ||
| 537 | + ChannelPosition::Lfe, | ||
| 538 | + ChannelPosition::BackLeft, | ||
| 539 | + ChannelPosition::BackRight | ||
| 540 | + ] | ||
| 541 | + ); | ||
| 542 | + assert_eq!(ChannelLayout::Surround7_1.channel_count(), 8); | ||
| 543 | + assert_eq!(ChannelLayout::from_count(6), ChannelLayout::Surround5_1); | ||
| 544 | + assert_eq!(ChannelLayout::from_count(3).channel_count(), 3); | ||
| 545 | + } | ||
| 546 | + | ||
| 547 | + #[test] | ||
| 548 | + fn audio_frame_validates_planes() { | ||
| 549 | + let interleaved = AudioFrame::try_new( | ||
| 550 | + SampleFormat::F32, | ||
| 551 | + false, | ||
| 552 | + ChannelLayout::Surround5_1, | ||
| 553 | + 48_000, | ||
| 554 | + 1024, | ||
| 555 | + vec![Buf::from_vec(vec![0u8; 1024 * 6 * 4])], | ||
| 556 | + ) | ||
| 557 | + .unwrap(); | ||
| 558 | + assert_eq!(interleaved.channels(), 6); | ||
| 559 | + | ||
| 560 | + let planar = AudioFrame::try_new( | ||
| 561 | + SampleFormat::S16, | ||
| 562 | + true, | ||
| 563 | + ChannelLayout::Stereo, | ||
| 564 | + 44_100, | ||
| 565 | + 512, | ||
| 566 | + vec![Buf::from_vec(vec![0u8; 1024]); 2], | ||
| 567 | + ) | ||
| 568 | + .unwrap(); | ||
| 569 | + assert_eq!(planar.data.len(), 2); | ||
| 570 | + | ||
| 571 | + // Wrong plane count and short planes are rejected, not truncated. | ||
| 572 | + assert!( | ||
| 573 | + AudioFrame::try_new( | ||
| 574 | + SampleFormat::F32, | ||
| 575 | + true, | ||
| 576 | + ChannelLayout::Stereo, | ||
| 577 | + 48_000, | ||
| 578 | + 64, | ||
| 579 | + vec![Buf::from_vec(vec![0u8; 256])] | ||
| 580 | + ) | ||
| 581 | + .is_err() | ||
| 582 | + ); | ||
| 583 | + assert!( | ||
| 584 | + AudioFrame::try_new( | ||
| 585 | + SampleFormat::F32, | ||
| 586 | + false, | ||
| 587 | + ChannelLayout::Stereo, | ||
| 588 | + 48_000, | ||
| 589 | + 64, | ||
| 590 | + vec![Buf::from_vec(vec![0u8; 4])] | ||
| 591 | + ) | ||
| 592 | + .is_err() | ||
| 593 | + ); | ||
| 594 | + } | ||
| 595 | + | ||
| 596 | + #[test] | ||
| 597 | + fn frame_pts_passthrough() { | ||
| 598 | + let mut v = VideoFrame::alloc(PixelFormat::Nv12, 16, 16); | ||
| 599 | + v.pts = Some(Timestamp::new(1001, TimeBase::new(1, 24_000))); | ||
| 600 | + let f = Frame::Video(v); | ||
| 601 | + assert_eq!(f.pts().unwrap().ticks, 1001); | ||
| 602 | + } | ||
| 603 | +} | ||
crates/ec-core/src/lib.rsadded+44 -0
| @@ -0,0 +1,44 @@ | |||
| 1 | +//! The intermediate representation every edith_codecs crate is built on. | ||
| 2 | +//! | ||
| 3 | +//! One vocabulary spans demux, decode, encode and mux: a [`Packet`] of | ||
| 4 | +//! compressed bytes, a [`Frame`] of decoded samples, a [`CodecId`] naming what | ||
| 5 | +//! turns one into the other, [`CodecParameters`] describing a stream before its | ||
| 6 | +//! first packet, and a rational [`TimeBase`] that keeps `24000/1001` exact from | ||
| 7 | +//! the container to the muxer. [`bitio`] holds the one bit reader/writer pair | ||
| 8 | +//! the parsers share. | ||
| 9 | +//! | ||
| 10 | +//! Contracts worth knowing before implementing against this crate: | ||
| 11 | +//! | ||
| 12 | +//! - Timing is integer. `f64` appears only in `as_secs_f64` helpers, for | ||
| 13 | +//! display, and never flows back into a timestamp. | ||
| 14 | +//! - Truncated input is [`Error::NeedMore`], not a panic; a refusal is | ||
| 15 | +//! [`Error::Unsupported`] and always names *what* and *why*. | ||
| 16 | +//! - Codecs are push/pull ([`Decoder::send_packet`] / [`Decoder::receive_frame`]), | ||
| 17 | +//! because packets and frames do not correspond one to one. | ||
| 18 | +//! - Payloads are [`Buf`], a refcounted byte range: cloning a packet or sharing | ||
| 19 | +//! a plane is a refcount bump, not a copy. | ||
| 20 | +//! | ||
| 21 | +//! No async, no unsafe, no external dependencies. | ||
| 22 | + | ||
| 23 | +#![forbid(unsafe_code)] | ||
| 24 | +#![warn(missing_docs)] | ||
| 25 | + | ||
| 26 | +pub mod bitio; | ||
| 27 | +pub mod error; | ||
| 28 | +pub mod frame; | ||
| 29 | +pub mod packet; | ||
| 30 | +pub mod registry; | ||
| 31 | +pub mod timebase; | ||
| 32 | + | ||
| 33 | +pub use bitio::{BitReader, BitReaderLsb, BitWriter, BitWriterLsb}; | ||
| 34 | +pub use error::{Error, Result}; | ||
| 35 | +pub use frame::{ | ||
| 36 | + AudioFrame, ChannelLayout, ChannelPosition, ColorInfo, Frame, PixelFormat, Plane, SampleFormat, | ||
| 37 | + VideoFrame, | ||
| 38 | +}; | ||
| 39 | +pub use packet::{Buf, Packet, PacketFlags, SideData}; | ||
| 40 | +pub use registry::{ | ||
| 41 | + AudioParameters, CodecId, CodecParameters, Decoder, Demuxer, Encoder, MediaParameters, | ||
| 42 | + MediaType, Muxer, SeekMode, StreamInfo, VideoParameters, | ||
| 43 | +}; | ||
| 44 | +pub use timebase::{Rounding, TimeBase, Timestamp}; | ||
crates/ec-core/src/packet.rsadded+238 -0
| @@ -0,0 +1,238 @@ | |||
| 1 | +//! Compressed data units and the shared cheap-clone byte buffer. | ||
| 2 | + | ||
| 3 | +use std::ops::{Bound, Deref, RangeBounds}; | ||
| 4 | +use std::sync::Arc; | ||
| 5 | + | ||
| 6 | +use crate::timebase::TimeBase; | ||
| 7 | + | ||
| 8 | +/// Reference-counted byte range: clone is a refcount bump, `slice` is free. | ||
| 9 | +/// | ||
| 10 | +/// This is what keeps demuxed packets and decoded planes zero-copy — a | ||
| 11 | +/// container reads one cluster into a `Vec<u8>`, wraps it once, and hands out | ||
| 12 | +/// packets that borrow into it without copying or borrowing a lifetime (so the | ||
| 13 | +/// result stays `Send + 'static`). | ||
| 14 | +#[derive(Clone, Default)] | ||
| 15 | +pub struct Buf { | ||
| 16 | + data: Arc<[u8]>, | ||
| 17 | + off: usize, | ||
| 18 | + len: usize, | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +impl Buf { | ||
| 22 | + /// Empty buffer, no allocation beyond the empty `Arc`. | ||
| 23 | + pub fn new() -> Buf { | ||
| 24 | + Buf::default() | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + /// Take ownership of a `Vec` without copying its bytes. | ||
| 28 | + pub fn from_vec(v: Vec<u8>) -> Buf { | ||
| 29 | + let len = v.len(); | ||
| 30 | + Buf { | ||
| 31 | + data: Arc::from(v), | ||
| 32 | + off: 0, | ||
| 33 | + len, | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + /// Copy a slice into a new buffer. | ||
| 38 | + pub fn copy_from_slice(s: &[u8]) -> Buf { | ||
| 39 | + Buf::from_vec(s.to_vec()) | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + /// Length in bytes. | ||
| 43 | + pub fn len(&self) -> usize { | ||
| 44 | + self.len | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /// True when the buffer holds no bytes. | ||
| 48 | + pub fn is_empty(&self) -> bool { | ||
| 49 | + self.len == 0 | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + /// A sub-range of this buffer, sharing the same allocation. | ||
| 53 | + /// | ||
| 54 | + /// Panics on an out-of-bounds range, exactly like slicing a `&[u8]`. | ||
| 55 | + pub fn slice(&self, range: impl RangeBounds<usize>) -> Buf { | ||
| 56 | + let start = match range.start_bound() { | ||
| 57 | + Bound::Included(&n) => n, | ||
| 58 | + Bound::Excluded(&n) => n + 1, | ||
| 59 | + Bound::Unbounded => 0, | ||
| 60 | + }; | ||
| 61 | + let end = match range.end_bound() { | ||
| 62 | + Bound::Included(&n) => n + 1, | ||
| 63 | + Bound::Excluded(&n) => n, | ||
| 64 | + Bound::Unbounded => self.len, | ||
| 65 | + }; | ||
| 66 | + assert!(start <= end && end <= self.len, "Buf::slice out of bounds"); | ||
| 67 | + Buf { | ||
| 68 | + data: Arc::clone(&self.data), | ||
| 69 | + off: self.off + start, | ||
| 70 | + len: end - start, | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +impl Deref for Buf { | ||
| 76 | + type Target = [u8]; | ||
| 77 | + | ||
| 78 | + fn deref(&self) -> &[u8] { | ||
| 79 | + &self.data[self.off..self.off + self.len] | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +impl AsRef<[u8]> for Buf { | ||
| 84 | + fn as_ref(&self) -> &[u8] { | ||
| 85 | + self | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +impl From<Vec<u8>> for Buf { | ||
| 90 | + fn from(v: Vec<u8>) -> Buf { | ||
| 91 | + Buf::from_vec(v) | ||
| 92 | + } | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +impl From<&[u8]> for Buf { | ||
| 96 | + fn from(s: &[u8]) -> Buf { | ||
| 97 | + Buf::copy_from_slice(s) | ||
| 98 | + } | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +impl PartialEq for Buf { | ||
| 102 | + fn eq(&self, other: &Buf) -> bool { | ||
| 103 | + **self == **other | ||
| 104 | + } | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +impl Eq for Buf {} | ||
| 108 | + | ||
| 109 | +impl std::fmt::Debug for Buf { | ||
| 110 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 111 | + write!(f, "Buf({} bytes)", self.len) | ||
| 112 | + } | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +/// Out-of-band data attached to a packet. | ||
| 116 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 117 | +pub enum SideData { | ||
| 118 | + /// Codec configuration in the codec's own form (avcC, hvcC, av1C, | ||
| 119 | + /// AudioSpecificConfig, ...) when it arrives in band rather than in | ||
| 120 | + /// [`crate::registry::CodecParameters::extradata`]. | ||
| 121 | + CodecConfig(Buf), | ||
| 122 | + /// Palette for palettised subtitle/image codecs. | ||
| 123 | + Palette(Buf), | ||
| 124 | + /// ISO 14496-12 3x3 display matrix (rotation/flip). | ||
| 125 | + DisplayMatrix(Buf), | ||
| 126 | + /// Anything a single container needs and nothing else understands. | ||
| 127 | + Custom { | ||
| 128 | + /// Container-defined discriminator. | ||
| 129 | + kind: u32, | ||
| 130 | + /// Raw payload. | ||
| 131 | + data: Buf, | ||
| 132 | + }, | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// Per-packet booleans. All default to false. | ||
| 136 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | ||
| 137 | +pub struct PacketFlags { | ||
| 138 | + /// Decoding may start here (IDR, audio sync frame, subtitle cue start). | ||
| 139 | + pub keyframe: bool, | ||
| 140 | + /// Carries headers/config only, no presentable sample. | ||
| 141 | + pub header: bool, | ||
| 142 | + /// Known-damaged payload; decoders may attempt it and must not panic. | ||
| 143 | + pub corrupt: bool, | ||
| 144 | + /// Decode for state but do not present (post-seek pre-roll). | ||
| 145 | + pub discard: bool, | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// One compressed access unit of one stream. | ||
| 149 | +/// | ||
| 150 | +/// Fields are public: containers and codecs assemble packets field by field, | ||
| 151 | +/// and a builder chain would only hide that. | ||
| 152 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 153 | +pub struct Packet { | ||
| 154 | + /// Index of the stream in [`crate::registry::Demuxer::streams`]. | ||
| 155 | + pub stream: u32, | ||
| 156 | + /// Base of `pts`, `dts` and `duration`. | ||
| 157 | + pub time_base: TimeBase, | ||
| 158 | + /// Presentation timestamp, when the container states one. | ||
| 159 | + pub pts: Option<i64>, | ||
| 160 | + /// Decode timestamp, when it differs from `pts` (B-frames). | ||
| 161 | + pub dts: Option<i64>, | ||
| 162 | + /// Duration in `time_base` ticks, when known. | ||
| 163 | + pub duration: Option<i64>, | ||
| 164 | + /// Per-packet flags. | ||
| 165 | + pub flags: PacketFlags, | ||
| 166 | + /// Out-of-band extras; empty for almost every packet. | ||
| 167 | + pub side_data: Vec<SideData>, | ||
| 168 | + /// Compressed payload. | ||
| 169 | + pub data: Buf, | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +impl Packet { | ||
| 173 | + /// A packet with no timestamps and no flags set. | ||
| 174 | + pub fn new(stream: u32, time_base: TimeBase, data: impl Into<Buf>) -> Packet { | ||
| 175 | + Packet { | ||
| 176 | + stream, | ||
| 177 | + time_base, | ||
| 178 | + pts: None, | ||
| 179 | + dts: None, | ||
| 180 | + duration: None, | ||
| 181 | + flags: PacketFlags::default(), | ||
| 182 | + side_data: Vec::new(), | ||
| 183 | + data: data.into(), | ||
| 184 | + } | ||
| 185 | + } | ||
| 186 | + | ||
| 187 | + /// `pts + duration`, when both are known. | ||
| 188 | + pub fn end_pts(&self) -> Option<i64> { | ||
| 189 | + self.pts?.checked_add(self.duration?) | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + /// True when decoding may start at this packet. | ||
| 193 | + pub fn is_keyframe(&self) -> bool { | ||
| 194 | + self.flags.keyframe | ||
| 195 | + } | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +#[cfg(test)] | ||
| 199 | +mod tests { | ||
| 200 | + use super::*; | ||
| 201 | + | ||
| 202 | + #[test] | ||
| 203 | + fn buf_slices_share_one_allocation() { | ||
| 204 | + let buf = Buf::from_vec(vec![0, 1, 2, 3, 4, 5]); | ||
| 205 | + let mid = buf.slice(2..5); | ||
| 206 | + assert_eq!(&*mid, &[2, 3, 4]); | ||
| 207 | + assert_eq!(&*mid.slice(1..), &[3, 4]); | ||
| 208 | + assert_eq!(mid.len(), 3); | ||
| 209 | + assert!(Buf::new().is_empty()); | ||
| 210 | + // Clone is a refcount bump, not a copy: same bytes, no reallocation. | ||
| 211 | + let clone = mid.clone(); | ||
| 212 | + assert_eq!(clone, mid); | ||
| 213 | + assert_eq!(&*buf.slice(..), &[0, 1, 2, 3, 4, 5]); | ||
| 214 | + } | ||
| 215 | + | ||
| 216 | + #[test] | ||
| 217 | + #[should_panic(expected = "out of bounds")] | ||
| 218 | + fn buf_slice_rejects_out_of_range() { | ||
| 219 | + Buf::from_vec(vec![0, 1]).slice(0..3); | ||
| 220 | + } | ||
| 221 | + | ||
| 222 | + #[test] | ||
| 223 | + fn packet_construction() { | ||
| 224 | + let tb = TimeBase::from_rate(48_000); | ||
| 225 | + let mut p = Packet::new(0, tb, vec![0xff; 4]); | ||
| 226 | + assert!(!p.is_keyframe()); | ||
| 227 | + assert_eq!(p.end_pts(), None); | ||
| 228 | + p.pts = Some(1024); | ||
| 229 | + p.duration = Some(1024); | ||
| 230 | + p.flags.keyframe = true; | ||
| 231 | + p.side_data | ||
| 232 | + .push(SideData::CodecConfig(Buf::copy_from_slice(&[0x12, 0x10]))); | ||
| 233 | + assert_eq!(p.end_pts(), Some(2048)); | ||
| 234 | + assert!(p.is_keyframe()); | ||
| 235 | + assert_eq!(p.data.len(), 4); | ||
| 236 | + assert_eq!(p.time_base, TimeBase::new(1, 48_000)); | ||
| 237 | + } | ||
| 238 | +} | ||
crates/ec-core/src/registry.rsadded+432 -0
| @@ -0,0 +1,432 @@ | |||
| 1 | +//! Codec identities, stream descriptions and the four trait contracts every | ||
| 2 | +//! container and codec crate in the family implements. | ||
| 3 | + | ||
| 4 | +use crate::error::Result; | ||
| 5 | +use crate::frame::{ChannelLayout, ColorInfo, Frame, PixelFormat, SampleFormat}; | ||
| 6 | +use crate::packet::{Buf, Packet}; | ||
| 7 | +use crate::timebase::{TimeBase, Timestamp}; | ||
| 8 | + | ||
| 9 | +/// Which kind of stream something belongs to. | ||
| 10 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 11 | +pub enum MediaType { | ||
| 12 | + /// Pictures. | ||
| 13 | + Video, | ||
| 14 | + /// Sound. | ||
| 15 | + Audio, | ||
| 16 | + /// Timed text or bitmap overlays. | ||
| 17 | + Subtitle, | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// Every codec the family carries. | ||
| 21 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 22 | +#[non_exhaustive] | ||
| 23 | +pub enum CodecId { | ||
| 24 | + /// ITU-T H.264 / MPEG-4 AVC. | ||
| 25 | + H264, | ||
| 26 | + /// ITU-T H.265 / MPEG-H HEVC. | ||
| 27 | + H265, | ||
| 28 | + /// Google VP8 (also the lossy half of WebP). | ||
| 29 | + Vp8, | ||
| 30 | + /// Google VP9. | ||
| 31 | + Vp9, | ||
| 32 | + /// AOMedia AV1. | ||
| 33 | + Av1, | ||
| 34 | + /// MPEG-4 AAC (LC and friends). | ||
| 35 | + Aac, | ||
| 36 | + /// Dolby AC-3. | ||
| 37 | + Ac3, | ||
| 38 | + /// Dolby Digital Plus (E-AC-3). | ||
| 39 | + EAc3, | ||
| 40 | + /// Apple Lossless. | ||
| 41 | + Alac, | ||
| 42 | + /// Xiph FLAC. | ||
| 43 | + Flac, | ||
| 44 | + /// MPEG-1/2 Layer III. | ||
| 45 | + Mp3, | ||
| 46 | + /// Xiph Opus. | ||
| 47 | + Opus, | ||
| 48 | + /// Xiph Vorbis. | ||
| 49 | + Vorbis, | ||
| 50 | + /// Unsigned 8-bit PCM. | ||
| 51 | + PcmU8, | ||
| 52 | + /// Signed 16-bit little-endian PCM. | ||
| 53 | + PcmS16Le, | ||
| 54 | + /// Signed 16-bit big-endian PCM. | ||
| 55 | + PcmS16Be, | ||
| 56 | + /// Signed 24-bit little-endian packed PCM. | ||
| 57 | + PcmS24Le, | ||
| 58 | + /// Signed 32-bit little-endian PCM. | ||
| 59 | + PcmS32Le, | ||
| 60 | + /// 32-bit float little-endian PCM. | ||
| 61 | + PcmF32Le, | ||
| 62 | + /// SubRip text. | ||
| 63 | + Srt, | ||
| 64 | + /// WebVTT text. | ||
| 65 | + WebVtt, | ||
| 66 | + /// Advanced SubStation Alpha (and SSA). | ||
| 67 | + Ass, | ||
| 68 | + /// Blu-ray Presentation Graphic Stream bitmaps. | ||
| 69 | + Pgs, | ||
| 70 | + /// MPEG-4 timed text (3GPP `tx3g`). | ||
| 71 | + Tx3g, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +impl CodecId { | ||
| 75 | + /// The media type this codec produces. | ||
| 76 | + pub fn media_type(&self) -> MediaType { | ||
| 77 | + use CodecId::*; | ||
| 78 | + match self { | ||
| 79 | + H264 | H265 | Vp8 | Vp9 | Av1 => MediaType::Video, | ||
| 80 | + Aac | Ac3 | EAc3 | Alac | Flac | Mp3 | Opus | Vorbis | PcmU8 | PcmS16Le | PcmS16Be | ||
| 81 | + | PcmS24Le | PcmS32Le | PcmF32Le => MediaType::Audio, | ||
| 82 | + Srt | WebVtt | Ass | Pgs | Tx3g => MediaType::Subtitle, | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + /// Short lowercase name, stable enough for logs and capability tables. | ||
| 87 | + pub fn name(&self) -> &'static str { | ||
| 88 | + use CodecId::*; | ||
| 89 | + match self { | ||
| 90 | + H264 => "h264", | ||
| 91 | + H265 => "h265", | ||
| 92 | + Vp8 => "vp8", | ||
| 93 | + Vp9 => "vp9", | ||
| 94 | + Av1 => "av1", | ||
| 95 | + Aac => "aac", | ||
| 96 | + Ac3 => "ac3", | ||
| 97 | + EAc3 => "eac3", | ||
| 98 | + Alac => "alac", | ||
| 99 | + Flac => "flac", | ||
| 100 | + Mp3 => "mp3", | ||
| 101 | + Opus => "opus", | ||
| 102 | + Vorbis => "vorbis", | ||
| 103 | + PcmU8 => "pcm_u8", | ||
| 104 | + PcmS16Le => "pcm_s16le", | ||
| 105 | + PcmS16Be => "pcm_s16be", | ||
| 106 | + PcmS24Le => "pcm_s24le", | ||
| 107 | + PcmS32Le => "pcm_s32le", | ||
| 108 | + PcmF32Le => "pcm_f32le", | ||
| 109 | + Srt => "srt", | ||
| 110 | + WebVtt => "webvtt", | ||
| 111 | + Ass => "ass", | ||
| 112 | + Pgs => "pgs", | ||
| 113 | + Tx3g => "tx3g", | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// Video half of [`CodecParameters`]. | ||
| 119 | +#[derive(Debug, Clone, PartialEq, Eq, Default)] | ||
| 120 | +pub struct VideoParameters { | ||
| 121 | + /// Coded width in pixels. | ||
| 122 | + pub width: u32, | ||
| 123 | + /// Coded height in pixels. | ||
| 124 | + pub height: u32, | ||
| 125 | + /// Decoded pixel layout, when the container or headers state one. | ||
| 126 | + pub format: Option<PixelFormat>, | ||
| 127 | + /// Frame rate *as a rate*: `num/den` is frames per second, so NTSC film is | ||
| 128 | + /// `24000/1001`. Invert it with [`TimeBase::inverse`] for a tick duration. | ||
| 129 | + pub frame_rate: Option<TimeBase>, | ||
| 130 | + /// Sample aspect ratio (`num/den`), when not square. | ||
| 131 | + pub sample_aspect_ratio: Option<TimeBase>, | ||
| 132 | + /// H.273 colour description. | ||
| 133 | + pub color: ColorInfo, | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// Audio half of [`CodecParameters`]. | ||
| 137 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 138 | +pub struct AudioParameters { | ||
| 139 | + /// Sample rate in Hz. | ||
| 140 | + pub sample_rate: u32, | ||
| 141 | + /// Channel count, order and meaning. | ||
| 142 | + pub layout: ChannelLayout, | ||
| 143 | + /// Decoded sample format, when known before the first frame. | ||
| 144 | + pub format: Option<SampleFormat>, | ||
| 145 | + /// Coded bit depth, when the codec has one (FLAC 24, ALAC 16/24). | ||
| 146 | + pub bits_per_sample: Option<u32>, | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +impl Default for AudioParameters { | ||
| 150 | + fn default() -> Self { | ||
| 151 | + AudioParameters { | ||
| 152 | + sample_rate: 0, | ||
| 153 | + layout: ChannelLayout::Stereo, | ||
| 154 | + format: None, | ||
| 155 | + bits_per_sample: None, | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// Per-media-type parameters. | ||
| 161 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 162 | +pub enum MediaParameters { | ||
| 163 | + /// Video stream parameters. | ||
| 164 | + Video(VideoParameters), | ||
| 165 | + /// Audio stream parameters. | ||
| 166 | + Audio(AudioParameters), | ||
| 167 | + /// Subtitle streams carry no dimensions; their setup lives in `extradata` | ||
| 168 | + /// (the ASS header, the PGS palette, ...). | ||
| 169 | + Subtitle, | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// Everything a decoder needs before it sees its first packet. | ||
| 173 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 174 | +pub struct CodecParameters { | ||
| 175 | + /// Which codec. | ||
| 176 | + pub codec: CodecId, | ||
| 177 | + /// Codec-defined setup bytes: avcC, hvcC, av1C, AudioSpecificConfig, the | ||
| 178 | + /// FLAC STREAMINFO block, the Vorbis header triplet, and so on. | ||
| 179 | + pub extradata: Option<Buf>, | ||
| 180 | + /// Media-type-specific parameters. | ||
| 181 | + pub media: MediaParameters, | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +impl CodecParameters { | ||
| 185 | + /// Parameters for `codec` with defaults for its media type and no extradata. | ||
| 186 | + pub fn new(codec: CodecId) -> CodecParameters { | ||
| 187 | + let media = match codec.media_type() { | ||
| 188 | + MediaType::Video => MediaParameters::Video(VideoParameters::default()), | ||
| 189 | + MediaType::Audio => MediaParameters::Audio(AudioParameters::default()), | ||
| 190 | + MediaType::Subtitle => MediaParameters::Subtitle, | ||
| 191 | + }; | ||
| 192 | + CodecParameters { | ||
| 193 | + codec, | ||
| 194 | + extradata: None, | ||
| 195 | + media, | ||
| 196 | + } | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + /// Video parameters, when this is a video stream. | ||
| 200 | + pub fn video(&self) -> Option<&VideoParameters> { | ||
| 201 | + match &self.media { | ||
| 202 | + MediaParameters::Video(v) => Some(v), | ||
| 203 | + _ => None, | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + /// Audio parameters, when this is an audio stream. | ||
| 208 | + pub fn audio(&self) -> Option<&AudioParameters> { | ||
| 209 | + match &self.media { | ||
| 210 | + MediaParameters::Audio(a) => Some(a), | ||
| 211 | + _ => None, | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +/// One stream of a container, as a demuxer reports it. | ||
| 217 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 218 | +pub struct StreamInfo { | ||
| 219 | + /// Index matching [`Packet::stream`]. | ||
| 220 | + pub index: u32, | ||
| 221 | + /// Base of every timestamp on this stream's packets. | ||
| 222 | + pub time_base: TimeBase, | ||
| 223 | + /// Codec and setup data. | ||
| 224 | + pub params: CodecParameters, | ||
| 225 | + /// First presentation timestamp, in `time_base` ticks, when known. | ||
| 226 | + pub start_time: Option<i64>, | ||
| 227 | + /// Duration in `time_base` ticks, when the container states one. | ||
| 228 | + pub duration: Option<i64>, | ||
| 229 | + /// ISO 639-2 language tag, when the container carries one. | ||
| 230 | + pub language: Option<String>, | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +impl StreamInfo { | ||
| 234 | + /// A stream with no timing hints and no language. | ||
| 235 | + pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo { | ||
| 236 | + StreamInfo { | ||
| 237 | + index, | ||
| 238 | + time_base, | ||
| 239 | + params, | ||
| 240 | + start_time: None, | ||
| 241 | + duration: None, | ||
| 242 | + language: None, | ||
| 243 | + } | ||
| 244 | + } | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +/// Where a seek is allowed to land relative to the requested instant. | ||
| 248 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 249 | +pub enum SeekMode { | ||
| 250 | + /// Nearest random access point at or before the target. The default: it is | ||
| 251 | + /// the only mode that lets a decoder reach the target frame exactly, by | ||
| 252 | + /// decoding forward and discarding. | ||
| 253 | + #[default] | ||
| 254 | + SyncBefore, | ||
| 255 | + /// Nearest random access point at or after the target. | ||
| 256 | + SyncAfter, | ||
| 257 | + /// Exact instant, whether or not a random access point sits there; the | ||
| 258 | + /// caller handles the pre-roll. | ||
| 259 | + Exact, | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +/// A container reader: streams in, packets out. | ||
| 263 | +pub trait Demuxer: Send { | ||
| 264 | + /// The streams found while opening the container. | ||
| 265 | + fn streams(&self) -> &[StreamInfo]; | ||
| 266 | + | ||
| 267 | + /// Next packet in storage order, or [`crate::Error::Eof`] at the end. | ||
| 268 | + fn next_packet(&mut self) -> Result<Packet>; | ||
| 269 | + | ||
| 270 | + /// Position so that reading resumes near `to` on `stream`. | ||
| 271 | + /// | ||
| 272 | + /// `to` carries its own [`TimeBase`], so callers never have to know the | ||
| 273 | + /// stream's base to seek by wall-clock instant. | ||
| 274 | + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()>; | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +/// A container writer: streams declared, then packets, then a finish. | ||
| 278 | +pub trait Muxer: Send { | ||
| 279 | + /// Declare a stream; returns the index that its packets must carry. | ||
| 280 | + /// | ||
| 281 | + /// All streams are declared before the first [`Muxer::write_packet`]. | ||
| 282 | + fn add_stream(&mut self, info: StreamInfo) -> Result<u32>; | ||
| 283 | + | ||
| 284 | + /// Write one packet. Its `stream` must be an index from | ||
| 285 | + /// [`Muxer::add_stream`] and its timestamps are rescaled by the muxer. | ||
| 286 | + fn write_packet(&mut self, packet: &Packet) -> Result<()>; | ||
| 287 | + | ||
| 288 | + /// Flush indices and trailers. Takes `&mut self` rather than `self` so a | ||
| 289 | + /// muxer stays usable behind `Box<dyn Muxer>`. | ||
| 290 | + fn finish(&mut self) -> Result<()>; | ||
| 291 | +} | ||
| 292 | + | ||
| 293 | +/// A decoder: packets in, frames out. | ||
| 294 | +/// | ||
| 295 | +/// Push/pull rather than `decode(&Packet) -> Vec<Frame>` because the mapping is | ||
| 296 | +/// genuinely not one to one — a parameter-set packet yields nothing, a | ||
| 297 | +/// reordering decoder yields nothing until its DPB fills, an audio packet can | ||
| 298 | +/// yield several blocks — and because end of stream has to be expressible: | ||
| 299 | +/// [`Decoder::flush`] then drains what reorder delay is still holding. The | ||
| 300 | +/// `Vec` shape would allocate per packet and still need a second entry point | ||
| 301 | +/// for the drain. | ||
| 302 | +pub trait Decoder: Send { | ||
| 303 | + /// The parameters this decoder was configured with, updated in place when | ||
| 304 | + /// in-band headers change them. | ||
| 305 | + fn codec_parameters(&self) -> &CodecParameters; | ||
| 306 | + | ||
| 307 | + /// Submit one packet. Call [`Decoder::receive_frame`] until it answers | ||
| 308 | + /// [`crate::Error::NeedMore`] before submitting the next. | ||
| 309 | + fn send_packet(&mut self, packet: &Packet) -> Result<()>; | ||
| 310 | + | ||
| 311 | + /// Take one decoded frame; [`crate::Error::NeedMore`] when none is ready, | ||
| 312 | + /// [`crate::Error::Eof`] once a flushed decoder is drained. | ||
| 313 | + fn receive_frame(&mut self) -> Result<Frame>; | ||
| 314 | + | ||
| 315 | + /// Signal end of stream: after this, `receive_frame` returns the delayed | ||
| 316 | + /// frames and then [`crate::Error::Eof`]. | ||
| 317 | + fn flush(&mut self) -> Result<()>; | ||
| 318 | + | ||
| 319 | + /// Drop all buffered state after a seek. Timestamps and references from | ||
| 320 | + /// before the seek are discarded. | ||
| 321 | + fn reset(&mut self); | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +/// An encoder: frames in, packets out — the mirror of [`Decoder`]. | ||
| 325 | +pub trait Encoder: Send { | ||
| 326 | + /// Parameters describing the encoder's output, including the `extradata` | ||
| 327 | + /// a muxer needs. For codecs whose setup data is derived while encoding | ||
| 328 | + /// (AAC ASC, avcC), this is final after the first | ||
| 329 | + /// [`Encoder::receive_packet`]. | ||
| 330 | + fn codec_parameters(&self) -> &CodecParameters; | ||
| 331 | + | ||
| 332 | + /// Submit one frame. | ||
| 333 | + fn send_frame(&mut self, frame: &Frame) -> Result<()>; | ||
| 334 | + | ||
| 335 | + /// Take one encoded packet; [`crate::Error::NeedMore`] when none is ready, | ||
| 336 | + /// [`crate::Error::Eof`] once a flushed encoder is drained. | ||
| 337 | + fn receive_packet(&mut self) -> Result<Packet>; | ||
| 338 | + | ||
| 339 | + /// Signal end of input and drain the lookahead. | ||
| 340 | + fn flush(&mut self) -> Result<()>; | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +#[cfg(test)] | ||
| 344 | +mod tests { | ||
| 345 | + use super::*; | ||
| 346 | + | ||
| 347 | + #[test] | ||
| 348 | + fn every_codec_id_has_a_media_type_and_name() { | ||
| 349 | + // The set the family must express, spelled out so a later crate cannot | ||
| 350 | + // quietly lose one (subtitle packets included: they are Packets, not | ||
| 351 | + // Frames). | ||
| 352 | + let all = [ | ||
| 353 | + CodecId::H264, | ||
| 354 | + CodecId::H265, | ||
| 355 | + CodecId::Vp8, | ||
| 356 | + CodecId::Vp9, | ||
| 357 | + CodecId::Av1, | ||
| 358 | + CodecId::Aac, | ||
| 359 | + CodecId::Ac3, | ||
| 360 | + CodecId::EAc3, | ||
| 361 | + CodecId::Alac, | ||
| 362 | + CodecId::Flac, | ||
| 363 | + CodecId::Mp3, | ||
| 364 | + CodecId::Opus, | ||
| 365 | + CodecId::Vorbis, | ||
| 366 | + CodecId::PcmU8, | ||
| 367 | + CodecId::PcmS16Le, | ||
| 368 | + CodecId::PcmS16Be, | ||
| 369 | + CodecId::PcmS24Le, | ||
| 370 | + CodecId::PcmS32Le, | ||
| 371 | + CodecId::PcmF32Le, | ||
| 372 | + CodecId::Srt, | ||
| 373 | + CodecId::WebVtt, | ||
| 374 | + CodecId::Ass, | ||
| 375 | + CodecId::Pgs, | ||
| 376 | + CodecId::Tx3g, | ||
| 377 | + ]; | ||
| 378 | + assert_eq!(all.len(), 24); | ||
| 379 | + let mut names: Vec<&str> = all.iter().map(|c| c.name()).collect(); | ||
| 380 | + names.sort_unstable(); | ||
| 381 | + names.dedup(); | ||
| 382 | + assert_eq!(names.len(), all.len(), "codec names must be unique"); | ||
| 383 | + assert_eq!(CodecId::Av1.media_type(), MediaType::Video); | ||
| 384 | + assert_eq!(CodecId::Opus.media_type(), MediaType::Audio); | ||
| 385 | + assert_eq!(CodecId::Pgs.media_type(), MediaType::Subtitle); | ||
| 386 | + } | ||
| 387 | + | ||
| 388 | + #[test] | ||
| 389 | + fn parameters_default_per_media_type() { | ||
| 390 | + let v = CodecParameters::new(CodecId::H265); | ||
| 391 | + assert!(v.video().is_some() && v.audio().is_none()); | ||
| 392 | + let a = CodecParameters::new(CodecId::Opus); | ||
| 393 | + assert_eq!(a.audio().unwrap().layout, ChannelLayout::Stereo); | ||
| 394 | + assert!(matches!( | ||
| 395 | + CodecParameters::new(CodecId::Pgs).media, | ||
| 396 | + MediaParameters::Subtitle | ||
| 397 | + )); | ||
| 398 | + | ||
| 399 | + // NTSC frame rate survives as a rate and inverts into a tick duration. | ||
| 400 | + let mut p = CodecParameters::new(CodecId::H264); | ||
| 401 | + if let MediaParameters::Video(v) = &mut p.media { | ||
| 402 | + v.width = 1920; | ||
| 403 | + v.height = 1080; | ||
| 404 | + v.frame_rate = Some(TimeBase::new(24_000, 1001)); | ||
| 405 | + v.format = Some(PixelFormat::I420); | ||
| 406 | + } | ||
| 407 | + let fr = p.video().unwrap().frame_rate.unwrap(); | ||
| 408 | + assert_eq!(fr.num(), 24_000); | ||
| 409 | + assert_eq!(fr.inverse(), TimeBase::NTSC_FILM); | ||
| 410 | + } | ||
| 411 | + | ||
| 412 | + #[test] | ||
| 413 | + fn stream_info_carries_language_and_timing() { | ||
| 414 | + let mut s = StreamInfo::new(2, TimeBase::MILLIS, CodecParameters::new(CodecId::Srt)); | ||
| 415 | + s.language = Some("tur".into()); | ||
| 416 | + s.duration = Some(3_600_000); | ||
| 417 | + assert_eq!(s.params.codec.media_type(), MediaType::Subtitle); | ||
| 418 | + assert_eq!(s.index, 2); | ||
| 419 | + assert_eq!(s.language.as_deref(), Some("tur")); | ||
| 420 | + } | ||
| 421 | + | ||
| 422 | + #[test] | ||
| 423 | + fn trait_objects_are_send() { | ||
| 424 | + fn assert_send<T: Send + ?Sized>() {} | ||
| 425 | + assert_send::<dyn Demuxer>(); | ||
| 426 | + assert_send::<dyn Muxer>(); | ||
| 427 | + assert_send::<dyn Decoder>(); | ||
| 428 | + assert_send::<dyn Encoder>(); | ||
| 429 | + assert_send::<Packet>(); | ||
| 430 | + assert_send::<Frame>(); | ||
| 431 | + } | ||
| 432 | +} | ||
crates/ec-core/src/timebase.rsadded+345 -0
| @@ -0,0 +1,345 @@ | |||
| 1 | +//! Exact rational time. No `f64` anywhere on a timing path. | ||
| 2 | +//! | ||
| 3 | +//! Every timestamp in the family is an integer tick count plus the [`TimeBase`] | ||
| 4 | +//! that gives the tick its duration in seconds. NTSC rates are exactly | ||
| 5 | +//! representable (`24000/1001`, `30000/1001`, `60000/1001`) and stay exact | ||
| 6 | +//! through rescaling, which is why `23.976` can never decay into `23.0` here. | ||
| 7 | + | ||
| 8 | +use std::cmp::Ordering; | ||
| 9 | + | ||
| 10 | +use crate::error::{Error, Result}; | ||
| 11 | + | ||
| 12 | +/// A positive rational number of seconds per tick, stored reduced. | ||
| 13 | +/// | ||
| 14 | +/// Also used as a *rate* (frames per second) where a rate is what is meant; | ||
| 15 | +/// [`TimeBase::inverse`] converts between the two readings. | ||
| 16 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 17 | +pub struct TimeBase { | ||
| 18 | + num: i64, | ||
| 19 | + den: i64, | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +const fn gcd(mut a: i64, mut b: i64) -> i64 { | ||
| 23 | + while b != 0 { | ||
| 24 | + let t = a % b; | ||
| 25 | + a = b; | ||
| 26 | + b = t; | ||
| 27 | + } | ||
| 28 | + a | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl TimeBase { | ||
| 32 | + /// Reduced `num/den`. Panics if either part is not positive — for literals; | ||
| 33 | + /// use [`TimeBase::try_new`] for values parsed out of a container. | ||
| 34 | + pub const fn new(num: i64, den: i64) -> TimeBase { | ||
| 35 | + assert!(num > 0 && den > 0, "time base parts must be positive"); | ||
| 36 | + let g = gcd(num, den); | ||
| 37 | + TimeBase { | ||
| 38 | + num: num / g, | ||
| 39 | + den: den / g, | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + /// Reduced `num/den`, or [`Error::Corrupt`] if either part is not positive. | ||
| 44 | + pub fn try_new(num: i64, den: i64) -> Result<TimeBase> { | ||
| 45 | + if num <= 0 || den <= 0 { | ||
| 46 | + return Err(Error::corrupt(format!( | ||
| 47 | + "time base {num}/{den} not positive" | ||
| 48 | + ))); | ||
| 49 | + } | ||
| 50 | + Ok(TimeBase::new(num, den)) | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// Tick duration of a sample rate, i.e. `1/rate` (48 kHz audio: `1/48000`). | ||
| 54 | + pub const fn from_rate(rate: u32) -> TimeBase { | ||
| 55 | + TimeBase::new(1, rate as i64) | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// Numerator of the reduced fraction. | ||
| 59 | + pub const fn num(&self) -> i64 { | ||
| 60 | + self.num | ||
| 61 | + } | ||
| 62 | + | ||
| 63 | + /// Denominator of the reduced fraction. | ||
| 64 | + pub const fn den(&self) -> i64 { | ||
| 65 | + self.den | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + /// `den/num` — a tick duration read as a rate, or a rate as a duration. | ||
| 69 | + pub const fn inverse(&self) -> TimeBase { | ||
| 70 | + TimeBase { | ||
| 71 | + num: self.den, | ||
| 72 | + den: self.num, | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + /// Convert `ticks` from this base into `to`, saturating at [`i64`] bounds. | ||
| 77 | + /// | ||
| 78 | + /// Saturation is unreachable for real media (i64 nanoseconds is 292 years); | ||
| 79 | + /// use [`TimeBase::checked_rescale`] when the input is attacker-controlled | ||
| 80 | + /// and the difference must be observed. | ||
| 81 | + pub fn rescale(&self, ticks: i64, to: TimeBase, rounding: Rounding) -> i64 { | ||
| 82 | + match self.checked_rescale(ticks, to, rounding) { | ||
| 83 | + Some(v) => v, | ||
| 84 | + None if ticks >= 0 => i64::MAX, | ||
| 85 | + None => i64::MIN, | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + /// Convert `ticks` from this base into `to`, or `None` on [`i64`] overflow. | ||
| 90 | + /// | ||
| 91 | + /// Exact: the whole computation runs in [`i128`] and rounds exactly once. | ||
| 92 | + pub fn checked_rescale(&self, ticks: i64, to: TimeBase, rounding: Rounding) -> Option<i64> { | ||
| 93 | + let n = ticks as i128 * self.num as i128 * to.den as i128; | ||
| 94 | + let d = self.den as i128 * to.num as i128; | ||
| 95 | + i64::try_from(rounding.div(n, d)).ok() | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + /// Seconds as a float. Display and logging only — never feed this back into | ||
| 99 | + /// a timestamp. | ||
| 100 | + pub fn as_secs_f64(&self) -> f64 { | ||
| 101 | + self.num as f64 / self.den as f64 | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// Seconds per tick: 1/1. | ||
| 105 | + pub const SECONDS: TimeBase = TimeBase::new(1, 1); | ||
| 106 | + /// Milliseconds: 1/1000 (Matroska default TimestampScale territory). | ||
| 107 | + pub const MILLIS: TimeBase = TimeBase::new(1, 1_000); | ||
| 108 | + /// Microseconds: 1/1_000_000. | ||
| 109 | + pub const MICROS: TimeBase = TimeBase::new(1, 1_000_000); | ||
| 110 | + /// Nanoseconds: 1/1_000_000_000 (Matroska timestamps). | ||
| 111 | + pub const NANOS: TimeBase = TimeBase::new(1, 1_000_000_000); | ||
| 112 | + /// MPEG transport/program stream clock: 1/90000. | ||
| 113 | + pub const MPEG_TS: TimeBase = TimeBase::new(1, 90_000); | ||
| 114 | + /// NTSC film frame duration: 1001/24000 (23.976 fps, exactly). | ||
| 115 | + pub const NTSC_FILM: TimeBase = TimeBase::new(1001, 24_000); | ||
| 116 | + /// NTSC video frame duration: 1001/30000 (29.97 fps, exactly). | ||
| 117 | + pub const NTSC_VIDEO: TimeBase = TimeBase::new(1001, 30_000); | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// How a rescale that does not divide evenly picks its integer result. | ||
| 121 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] | ||
| 122 | +pub enum Rounding { | ||
| 123 | + /// Toward negative infinity. | ||
| 124 | + Down, | ||
| 125 | + /// Toward positive infinity. | ||
| 126 | + Up, | ||
| 127 | + /// Toward zero (truncate). | ||
| 128 | + Zero, | ||
| 129 | + /// To the nearest, halves away from zero. The default: it is what seek and | ||
| 130 | + /// container timestamp conversion want. | ||
| 131 | + #[default] | ||
| 132 | + Nearest, | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +impl Rounding { | ||
| 136 | + /// Divide `n` by a positive `d` under this rounding mode. | ||
| 137 | + fn div(self, n: i128, d: i128) -> i128 { | ||
| 138 | + debug_assert!(d > 0, "time base denominators are positive by construction"); | ||
| 139 | + let q = n / d; | ||
| 140 | + let r = n % d; | ||
| 141 | + match self { | ||
| 142 | + Rounding::Zero => q, | ||
| 143 | + Rounding::Down => { | ||
| 144 | + if r < 0 { | ||
| 145 | + q - 1 | ||
| 146 | + } else { | ||
| 147 | + q | ||
| 148 | + } | ||
| 149 | + } | ||
| 150 | + Rounding::Up => { | ||
| 151 | + if r > 0 { | ||
| 152 | + q + 1 | ||
| 153 | + } else { | ||
| 154 | + q | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + Rounding::Nearest => { | ||
| 158 | + if r.abs() * 2 >= d { | ||
| 159 | + if n >= 0 { q + 1 } else { q - 1 } | ||
| 160 | + } else { | ||
| 161 | + q | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// A tick count carrying its own [`TimeBase`]. | ||
| 169 | +/// | ||
| 170 | +/// Ordering and equality compare *instants*, exactly, across different bases. | ||
| 171 | +#[derive(Debug, Clone, Copy)] | ||
| 172 | +pub struct Timestamp { | ||
| 173 | + /// Tick count in `base`. | ||
| 174 | + pub ticks: i64, | ||
| 175 | + /// Duration of one tick. | ||
| 176 | + pub base: TimeBase, | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +impl Timestamp { | ||
| 180 | + /// A timestamp of `ticks` in `base`. | ||
| 181 | + pub const fn new(ticks: i64, base: TimeBase) -> Timestamp { | ||
| 182 | + Timestamp { ticks, base } | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + /// The same instant expressed in `base`, saturating at [`i64`] bounds. | ||
| 186 | + pub fn rescale(&self, base: TimeBase, rounding: Rounding) -> Timestamp { | ||
| 187 | + Timestamp::new(self.base.rescale(self.ticks, base, rounding), base) | ||
| 188 | + } | ||
| 189 | + | ||
| 190 | + /// The same instant expressed in `base`, or `None` on [`i64`] overflow. | ||
| 191 | + pub fn checked_rescale(&self, base: TimeBase, rounding: Rounding) -> Option<Timestamp> { | ||
| 192 | + self.base | ||
| 193 | + .checked_rescale(self.ticks, base, rounding) | ||
| 194 | + .map(|t| Timestamp::new(t, base)) | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + /// Advance by `ticks` of this timestamp's own base. | ||
| 198 | + pub fn checked_add_ticks(&self, ticks: i64) -> Option<Timestamp> { | ||
| 199 | + self.ticks | ||
| 200 | + .checked_add(ticks) | ||
| 201 | + .map(|t| Timestamp::new(t, self.base)) | ||
| 202 | + } | ||
| 203 | + | ||
| 204 | + /// `self - other`, in this timestamp's base, exact. | ||
| 205 | + pub fn checked_diff(&self, other: Timestamp) -> Option<i64> { | ||
| 206 | + let o = other.checked_rescale(self.base, Rounding::Nearest)?; | ||
| 207 | + self.ticks.checked_sub(o.ticks) | ||
| 208 | + } | ||
| 209 | + | ||
| 210 | + /// Seconds as a float. Display only. | ||
| 211 | + pub fn as_secs_f64(&self) -> f64 { | ||
| 212 | + self.ticks as f64 * self.base.as_secs_f64() | ||
| 213 | + } | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +impl PartialEq for Timestamp { | ||
| 217 | + fn eq(&self, other: &Self) -> bool { | ||
| 218 | + self.cmp(other) == Ordering::Equal | ||
| 219 | + } | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +impl Eq for Timestamp {} | ||
| 223 | + | ||
| 224 | +impl PartialOrd for Timestamp { | ||
| 225 | + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | ||
| 226 | + Some(self.cmp(other)) | ||
| 227 | + } | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +impl Ord for Timestamp { | ||
| 231 | + /// Exact cross-base comparison: both sides are put over the common | ||
| 232 | + /// denominator in [`i128`] rather than converted (and rounded) first. | ||
| 233 | + fn cmp(&self, other: &Self) -> Ordering { | ||
| 234 | + let a = self.ticks as i128 * self.base.num() as i128 * other.base.den() as i128; | ||
| 235 | + let b = other.ticks as i128 * other.base.num() as i128 * self.base.den() as i128; | ||
| 236 | + a.cmp(&b) | ||
| 237 | + } | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +#[cfg(test)] | ||
| 241 | +mod tests { | ||
| 242 | + use super::*; | ||
| 243 | + | ||
| 244 | + #[test] | ||
| 245 | + fn reduces_and_compares_equal() { | ||
| 246 | + assert_eq!(TimeBase::new(2, 4), TimeBase::new(1, 2)); | ||
| 247 | + // NTSC fractions are already reduced and must survive verbatim. | ||
| 248 | + assert_eq!(TimeBase::NTSC_FILM.num(), 1001); | ||
| 249 | + assert_eq!(TimeBase::NTSC_FILM.den(), 24_000); | ||
| 250 | + assert_eq!(TimeBase::NTSC_FILM.inverse(), TimeBase::new(24_000, 1001)); | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + #[test] | ||
| 254 | + fn rejects_non_positive_parts() { | ||
| 255 | + assert!(TimeBase::try_new(1, 0).is_err()); | ||
| 256 | + assert!(TimeBase::try_new(0, 1).is_err()); | ||
| 257 | + assert!(TimeBase::try_new(-1, 24_000).is_err()); | ||
| 258 | + } | ||
| 259 | + | ||
| 260 | + #[test] | ||
| 261 | + fn ntsc_ten_hours_zero_drift() { | ||
| 262 | + // 10 h of 24000/1001 film: frame index -> exact base and back. | ||
| 263 | + let frames = 863_136_i64; // 10 h at 23.976 fps | ||
| 264 | + let film = TimeBase::NTSC_FILM; | ||
| 265 | + let fine = TimeBase::new(1, 24_000_000); | ||
| 266 | + let ticks = film | ||
| 267 | + .checked_rescale(frames, fine, Rounding::Nearest) | ||
| 268 | + .unwrap(); | ||
| 269 | + assert_eq!(ticks, frames * 1001 * 1000); | ||
| 270 | + assert_eq!( | ||
| 271 | + fine.checked_rescale(ticks, film, Rounding::Nearest) | ||
| 272 | + .unwrap(), | ||
| 273 | + frames | ||
| 274 | + ); | ||
| 275 | + // Per-frame accumulation must equal the closed form: no drift. | ||
| 276 | + let mut acc = 0_i64; | ||
| 277 | + for _ in 0..frames { | ||
| 278 | + acc += 1001 * 1000; | ||
| 279 | + } | ||
| 280 | + assert_eq!(acc, ticks); | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + #[test] | ||
| 284 | + fn ntsc_never_becomes_integer_fps() { | ||
| 285 | + // 23.976 fps as a rate, one second of it, in the film base. | ||
| 286 | + let one_second = TimeBase::SECONDS | ||
| 287 | + .checked_rescale(1, TimeBase::NTSC_FILM, Rounding::Nearest) | ||
| 288 | + .unwrap(); | ||
| 289 | + assert_eq!(one_second, 24); // 23.976 frames rounds to 24 ticks, never 23 | ||
| 290 | + // A 24 fps base would be a different instant; prove the two differ. | ||
| 291 | + let film = Timestamp::new(24, TimeBase::NTSC_FILM); | ||
| 292 | + let flat = Timestamp::new(24, TimeBase::new(1, 24)); | ||
| 293 | + assert!(film > flat); | ||
| 294 | + } | ||
| 295 | + | ||
| 296 | + #[test] | ||
| 297 | + fn rounding_modes() { | ||
| 298 | + let ms = TimeBase::MILLIS; | ||
| 299 | + let s = TimeBase::SECONDS; | ||
| 300 | + // 1500 ms -> seconds under each mode. | ||
| 301 | + assert_eq!(ms.rescale(1500, s, Rounding::Down), 1); | ||
| 302 | + assert_eq!(ms.rescale(1500, s, Rounding::Up), 2); | ||
| 303 | + assert_eq!(ms.rescale(1500, s, Rounding::Zero), 1); | ||
| 304 | + assert_eq!(ms.rescale(1500, s, Rounding::Nearest), 2); | ||
| 305 | + // Negative timestamps (B-frame dts) round symmetrically. | ||
| 306 | + assert_eq!(ms.rescale(-1500, s, Rounding::Down), -2); | ||
| 307 | + assert_eq!(ms.rescale(-1500, s, Rounding::Up), -1); | ||
| 308 | + assert_eq!(ms.rescale(-1500, s, Rounding::Zero), -1); | ||
| 309 | + assert_eq!(ms.rescale(-1500, s, Rounding::Nearest), -2); | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + #[test] | ||
| 313 | + fn overflow_is_reported_not_wrapped() { | ||
| 314 | + // Seconds into nanoseconds: 2^63 seconds does not fit. | ||
| 315 | + let s = TimeBase::SECONDS; | ||
| 316 | + assert_eq!( | ||
| 317 | + s.checked_rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest), | ||
| 318 | + None | ||
| 319 | + ); | ||
| 320 | + assert_eq!( | ||
| 321 | + s.rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest), | ||
| 322 | + i64::MAX | ||
| 323 | + ); | ||
| 324 | + assert_eq!( | ||
| 325 | + s.rescale(i64::MIN, TimeBase::NANOS, Rounding::Nearest), | ||
| 326 | + i64::MIN | ||
| 327 | + ); | ||
| 328 | + // In range, nothing saturates. | ||
| 329 | + assert_eq!( | ||
| 330 | + s.checked_rescale(3, TimeBase::NANOS, Rounding::Nearest), | ||
| 331 | + Some(3_000_000_000) | ||
| 332 | + ); | ||
| 333 | + } | ||
| 334 | + | ||
| 335 | + #[test] | ||
| 336 | + fn timestamp_math() { | ||
| 337 | + let a = Timestamp::new(90_000, TimeBase::MPEG_TS); // 1 s | ||
| 338 | + let b = Timestamp::new(1_000, TimeBase::MILLIS); // 1 s | ||
| 339 | + assert_eq!(a, b); | ||
| 340 | + assert_eq!(a.checked_diff(b), Some(0)); | ||
| 341 | + assert_eq!(a.checked_add_ticks(90_000).unwrap().ticks, 180_000); | ||
| 342 | + assert_eq!(a.rescale(TimeBase::MILLIS, Rounding::Nearest).ticks, 1_000); | ||
| 343 | + assert!(Timestamp::new(0, TimeBase::MILLIS) < a); | ||
| 344 | + } | ||
| 345 | +} | ||
shims/.gitkeepadded+0 -0
tools/.gitkeepadded+0 -0