diff --git a/Cargo.lock b/Cargo.lock index 14b61940..c3f09064 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -607,7 +607,7 @@ dependencies = [ "ec-core", "ec-inflate", "ec-testkit", - "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)", + "image", "tracking-allocator", ] @@ -885,7 +885,7 @@ dependencies = [ "bit_field", "half", "lebe", - "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)", + "miniz_oxide", "num-complex", "pulp", "rayon-core", @@ -914,13 +914,6 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" -[[package]] -name = "flacenc" -version = "0.5.1" -dependencies = [ - "ec-flac", -] - [[package]] name = "flate2" version = "1.1.9" @@ -928,7 +921,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", - "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)", + "miniz_oxide", ] [[package]] @@ -1031,13 +1024,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "hound" -version = "3.5.1" -dependencies = [ - "ec-riff", -] - [[package]] name = "hybrid-array" version = "0.4.15" @@ -1047,13 +1033,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "image" -version = "0.25.10" -dependencies = [ - "ec-image", -] - [[package]] name = "image" version = "0.25.10" @@ -1208,13 +1187,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.8.9" -dependencies = [ - "ec-inflate", -] - [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1362,13 +1334,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "opus-rs" -version = "0.1.26" -dependencies = [ - "ec-opus", -] - [[package]] name = "oracle" version = "0.1.0" @@ -1376,59 +1341,6 @@ dependencies = [ "ec-testkit", ] -[[package]] -name = "oxideav-ac3" -version = "0.0.10" -dependencies = [ - "ec-ac3", - "ec-core", - "ec-testkit", - "oxideav-core", -] - -[[package]] -name = "oxideav-ass" -version = "0.0.9" -dependencies = [ - "ec-ass", - "ec-subs", - "oxideav-core", -] - -[[package]] -name = "oxideav-core" -version = "0.1.34" -dependencies = [ - "ec-core", -] - -[[package]] -name = "oxideav-ogg" -version = "0.1.8" -dependencies = [ - "ec-core", - "ec-ogg", - "oxideav-core", -] - -[[package]] -name = "oxideav-sub-image" -version = "0.0.7" -dependencies = [ - "ec-pgs", - "oxideav-ass", - "oxideav-core", - "oxideav-subtitle", -] - -[[package]] -name = "oxideav-subtitle" -version = "0.1.2" -dependencies = [ - "ec-subs", - "oxideav-core", -] - [[package]] name = "paste" version = "1.0.15" @@ -1463,7 +1375,7 @@ dependencies = [ "crc32fast", "fdeflate", "flate2", - "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)", + "miniz_oxide", ] [[package]] @@ -1736,13 +1648,6 @@ version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" -[[package]] -name = "ruopus" -version = "0.1.2" -dependencies = [ - "ec-opus", -] - [[package]] name = "rustc-hash" version = "1.1.0" @@ -1769,38 +1674,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" -[[package]] -name = "rusty_aac" -version = "0.5.0" -dependencies = [ - "ec-aac", -] - -[[package]] -name = "rusty_h264" -version = "0.9.1" -dependencies = [ - "ec-h264", - "ec-h264-syntax", -] - -[[package]] -name = "rusty_mp3" -version = "0.6.1" -dependencies = [ - "ec-core", - "ec-mp3", -] - -[[package]] -name = "rusty_vorbis" -version = "0.1.1" -dependencies = [ - "ec-core", - "ec-ogg", - "ec-vorbis", -] - [[package]] name = "safe_arch" version = "1.1.0" @@ -1878,35 +1751,6 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" -[[package]] -name = "symphonia" -version = "0.6.0" -dependencies = [ - "ec-core", - "ec-ogg", - "ec-probe", - "ec-testkit", - "ec-vorbis", - "rusty_vorbis", - "symphonia-codec-aac", - "symphonia-core", -] - -[[package]] -name = "symphonia-codec-aac" -version = "0.6.0" -dependencies = [ - "ec-aac", - "symphonia-core", -] - -[[package]] -name = "symphonia-core" -version = "0.6.0" -dependencies = [ - "ec-core", -] - [[package]] name = "syn" version = "2.0.119" diff --git a/Cargo.toml b/Cargo.toml index 9bcb6768..53c642ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/*", "shims/*", "tools/*"] +members = ["crates/*", "shims/cros-libva", "shims/vk-video-ffi", "tools/ec-bench", "tools/golden", "tools/oracle"] exclude = ["crates/*/fuzz"] [workspace.package] diff --git a/shims/flacenc/Cargo.toml b/shims/flacenc/Cargo.toml deleted file mode 100644 index 390891ab..00000000 --- a/shims/flacenc/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "flacenc" -description = "Compatibility shim: the flacenc 0.5.1 surface edith consumes, served by ec-flac." -version = "0.5.1" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-flac = { path = "../../crates/ec-flac", version = "0.1.0" } diff --git a/shims/flacenc/src/bitsink.rs b/shims/flacenc/src/bitsink.rs deleted file mode 100644 index ab5160dc..00000000 --- a/shims/flacenc/src/bitsink.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! `flacenc::bitsink`: where a written stream lands. - -use std::convert::Infallible; - -/// Somewhere bits can be written. -/// -/// Only the part the replica needs: it constructs a [`ByteSink`], hands it to -/// `Stream::write` and reads the bytes back. -pub trait BitSink: Sized { - /// What writing can fail with. - type Error: std::error::Error; - - /// Append whole bytes. - fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error>; - - /// Bits written so far. - fn bit_len(&self) -> usize; -} - -/// A `Vec` sink — `flacenc::bitsink::ByteSink`. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct ByteSink { - storage: Vec, -} - -impl ByteSink { - /// An empty sink. - pub fn new() -> Self { - ByteSink::default() - } - - /// An empty sink with room for `bits`. - pub fn with_capacity(bits: usize) -> Self { - ByteSink { - storage: Vec::with_capacity(bits.div_ceil(8)), - } - } - - /// The bytes written so far. - pub fn as_slice(&self) -> &[u8] { - &self.storage - } - - /// Take the bytes. - pub fn into_inner(self) -> Vec { - self.storage - } - - /// Bytes written so far. - pub fn len(&self) -> usize { - self.storage.len() - } - - /// True when nothing has been written. - pub fn is_empty(&self) -> bool { - self.storage.is_empty() - } -} - -impl BitSink for ByteSink { - type Error = Infallible; - - fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Infallible> { - self.storage.extend_from_slice(bytes); - Ok(()) - } - - fn bit_len(&self) -> usize { - self.storage.len() * 8 - } -} diff --git a/shims/flacenc/src/component.rs b/shims/flacenc/src/component.rs deleted file mode 100644 index deff23a6..00000000 --- a/shims/flacenc/src/component.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! `flacenc::component`: the encoded stream and its `STREAMINFO`. -//! -//! The incumbent models every FLAC component as an addressable value and -//! writes them out on demand. Ours holds the encoded bytes and the header -//! fields a caller is allowed to correct afterwards — which is the whole of -//! what the replica does with the tree. - -use crate::bitsink::BitSink; -use crate::error::{OutputError, VerifyError}; - -/// Something that can state its size and write itself to a [`BitSink`]. -pub trait BitRepr { - /// Bits this component occupies. - fn count_bits(&self) -> usize; - - /// Write the component out. - /// - /// # Errors - /// When the sink fails, or the component holds a value FLAC cannot express. - fn write(&self, dest: &mut S) -> Result<(), OutputError>; -} - -/// A complete encoded FLAC stream. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Stream { - bytes: Vec, - stream_info: StreamInfo, -} - -/// Offset of the `STREAMINFO` payload: `fLaC` plus the 4-byte block header. -const STREAM_INFO_AT: usize = 8; - -impl Stream { - pub(crate) fn from_bytes(bytes: Vec) -> Stream { - let min = u16::from_be_bytes([bytes[STREAM_INFO_AT], bytes[STREAM_INFO_AT + 1]]); - let max = u16::from_be_bytes([bytes[STREAM_INFO_AT + 2], bytes[STREAM_INFO_AT + 3]]); - Stream { - bytes, - stream_info: StreamInfo { - min_block_size: min, - max_block_size: max, - }, - } - } - - /// The stream's `STREAMINFO`, mutable. - pub fn stream_info_mut(&mut self) -> &mut StreamInfo { - &mut self.stream_info - } - - /// The stream's `STREAMINFO`. - pub fn stream_info(&self) -> &StreamInfo { - &self.stream_info - } -} - -impl BitRepr for Stream { - fn count_bits(&self) -> usize { - self.bytes.len() * 8 - } - - fn write(&self, dest: &mut S) -> Result<(), OutputError> { - // The declared block sizes are the one field a caller may have changed - // after encoding, so they are patched in on the way out. - let mut bytes = self.bytes.clone(); - bytes[STREAM_INFO_AT..STREAM_INFO_AT + 2] - .copy_from_slice(&self.stream_info.min_block_size.to_be_bytes()); - bytes[STREAM_INFO_AT + 2..STREAM_INFO_AT + 4] - .copy_from_slice(&self.stream_info.max_block_size.to_be_bytes()); - dest.write_bytes(&bytes) - .map_err(|e| OutputError::new(e.to_string())) - } -} - -/// The `STREAMINFO` fields a caller may correct after encoding. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct StreamInfo { - min_block_size: u16, - max_block_size: u16, -} - -impl StreamInfo { - /// State the stream's block sizes. - /// - /// # Errors - /// When either value is not a legal block size. - pub fn set_block_sizes( - &mut self, - min_value: usize, - max_value: usize, - ) -> Result<(), VerifyError> { - self.min_block_size = u16::try_from(min_value) - .ok() - .filter(|&n| n >= 16) - .ok_or_else(|| VerifyError::new("min_block_size", "must be a valid block size."))?; - self.max_block_size = u16::try_from(max_value) - .ok() - .filter(|&n| n >= 16) - .ok_or_else(|| VerifyError::new("max_block_size", "must be a valid block size."))?; - Ok(()) - } - - /// Smallest block size stated by the stream. - pub fn min_block_size(&self) -> usize { - usize::from(self.min_block_size) - } - - /// Largest block size stated by the stream. - pub fn max_block_size(&self) -> usize { - usize::from(self.max_block_size) - } -} diff --git a/shims/flacenc/src/config.rs b/shims/flacenc/src/config.rs deleted file mode 100644 index c539d68e..00000000 --- a/shims/flacenc/src/config.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! `flacenc::config`: the encoder configuration tree. -//! -//! The fields the replica reads (`block_size`) and the ones its `Default` -//! walks are kept; the knobs that only steer the incumbent's own search -//! (window functions, per-order caps) are not reproduced, because a value set -//! there would silently do nothing. - -use crate::error::{Verify, VerifyError}; - -/// Encoder configuration — `flacenc::config::Encoder`. -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub struct Encoder { - /// Encoder block size. - pub block_size: usize, - /// Whether the encoder may use several threads. - pub multithread: bool, - /// Stereo coding switches. - pub stereo_coding: StereoCoding, - /// Per-channel coding switches. - pub subframe_coding: SubFrameCoding, -} - -impl Default for Encoder { - fn default() -> Self { - Encoder { - block_size: 4096, - multithread: false, - stereo_coding: StereoCoding::default(), - subframe_coding: SubFrameCoding::default(), - } - } -} - -impl Verify for Encoder { - fn verify(&self) -> Result<(), VerifyError> { - if !(16..=65535).contains(&self.block_size) { - return Err(VerifyError::new( - "block_size", - "must be in the range of 16..=65535.", - )); - } - Ok(()) - } -} - -/// Stereo coding switches — `flacenc::config::StereoCoding`. -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub struct StereoCoding { - /// Allow left/side coding. - pub use_leftside: bool, - /// Allow right/side coding. - pub use_rightside: bool, - /// Allow mid/side coding. - pub use_midside: bool, -} - -impl Default for StereoCoding { - fn default() -> Self { - StereoCoding { - use_leftside: true, - use_rightside: true, - use_midside: true, - } - } -} - -/// Per-channel coding switches — `flacenc::config::SubFrameCoding`. -/// -/// Verbatim coding is deliberately not switchable: it is the representation -/// that always exists, so turning it off could leave a signal unencodable. -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub struct SubFrameCoding { - /// Allow constant subframes. - pub use_constant: bool, - /// Allow fixed-predictor subframes. - pub use_fixed: bool, - /// Allow LPC subframes. - pub use_lpc: bool, -} - -impl Default for SubFrameCoding { - fn default() -> Self { - SubFrameCoding { - use_constant: true, - use_fixed: true, - use_lpc: true, - } - } -} diff --git a/shims/flacenc/src/error.rs b/shims/flacenc/src/error.rs deleted file mode 100644 index e73ecdba..00000000 --- a/shims/flacenc/src/error.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! `flacenc::error`: verification wrappers and the error types the encoder -//! hands back. - -use std::fmt; -use std::marker::PhantomData; - -use crate::bitsink::BitSink; - -/// A value that has passed [`Verify::verify`]. -/// -/// Derefs to the value, which is how callers read `config.block_size` off a -/// verified config. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Verified(T); - -impl std::ops::Deref for Verified { - type Target = T; - fn deref(&self) -> &T { - &self.0 - } -} - -/// Configuration structs that can check their own consistency. -pub trait Verify: Sized { - /// Check every field; [`VerifyError`] names the first bad one. - fn verify(&self) -> Result<(), VerifyError>; - - /// Wrap into [`Verified`], or hand the value back with the reason. - fn into_verified(self) -> Result, (Self, VerifyError)> { - match self.verify() { - Ok(()) => Ok(Verified(self)), - Err(e) => Err((self, e)), - } - } -} - -/// A configuration field that is out of range, with the path to it. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct VerifyError { - components: Vec, - reason: String, -} - -impl VerifyError { - /// An error for an invalid field `component`. - pub fn new(component: &str, reason: &str) -> Self { - VerifyError { - components: vec![component.to_owned()], - reason: reason.to_owned(), - } - } - - /// Prefix the field path with an enclosing struct's field name. - pub fn within(mut self, component: &str) -> Self { - self.components.insert(0, component.to_owned()); - self - } -} - -impl fmt::Display for VerifyError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "verification error: `{}` is not valid. reason: {}", - self.components.join("."), - self.reason - ) - } -} - -impl std::error::Error for VerifyError {} - -/// Encoding failed: either the source or the configuration. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct EncodeError(pub(crate) String); - -impl fmt::Display for EncodeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -impl std::error::Error for EncodeError {} - -/// Writing a component to a [`BitSink`] failed. -/// -/// Generic over the sink, as the incumbent is, so `write` signatures match; our -/// only sink is infallible, so this is never constructed in practice. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct OutputError { - reason: String, - sink: PhantomData S>, -} - -impl OutputError { - pub(crate) fn new(reason: impl Into) -> Self { - OutputError { - reason: reason.into(), - sink: PhantomData, - } - } -} - -impl fmt::Display for OutputError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.reason) - } -} - -impl std::error::Error for OutputError {} diff --git a/shims/flacenc/src/lib.rs b/shims/flacenc/src/lib.rs deleted file mode 100644 index dc49964c..00000000 --- a/shims/flacenc/src/lib.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! Drop-in replacement for the `flacenc` 0.5.1 surface the replica consumes, -//! implemented over [`ec_flac`]. -//! -//! It carries the incumbent's package name and version so the swap is a -//! `[patch.crates-io]` entry and nothing else. The scope is exactly the API -//! `engine/src/export.rs` calls (`export.rs:67-68,2930-2954`): -//! -//! ```no_run -//! use flacenc::component::BitRepr; -//! use flacenc::error::Verify; -//! -//! let config = flacenc::config::Encoder::default().into_verified().unwrap(); -//! let source = flacenc::source::MemSource::from_samples(&[0i32; 32], 2, 16, 44100); -//! let mut stream = -//! flacenc::encode_with_fixed_block_size(&config, source, config.block_size).unwrap(); -//! stream -//! .stream_info_mut() -//! .set_block_sizes(config.block_size, config.block_size) -//! .unwrap(); -//! let mut sink = flacenc::bitsink::ByteSink::new(); -//! stream.write(&mut sink).unwrap(); -//! let _bytes: &[u8] = sink.as_slice(); -//! ``` -//! -//! Signatures match the incumbent's (types, argument order, error shapes) so -//! call sites compile unchanged; the implementation behind them is ours. -//! Deliberately *not* covered: the `par` feature knobs, `serde` config -//! round-tripping and the component tree (`Frame`/`SubFrame`/`Residual` as -//! addressable values) — the replica constructs none of them. - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -pub mod bitsink; -pub mod component; -pub mod config; -pub mod error; -pub mod source; - -pub use component::Stream; -pub use error::EncodeError; - -use error::Verified; -use source::Source; - -/// Encode `src` into a stream of fixed-size blocks. -/// -/// Mirrors `flacenc::encode_with_fixed_block_size`: the verified config, a -/// source, and the block size (which the caller reads off the config). -pub fn encode_with_fixed_block_size( - config: &Verified, - src: T, - block_size: usize, -) -> Result { - let encoder = ec_flac::EncoderConfig { - block_size, - stereo_decorrelation: config.stereo_coding.use_midside - || config.stereo_coding.use_leftside - || config.stereo_coding.use_rightside, - ..ec_flac::EncoderConfig::default() - }; - let bytes = ec_flac::encode( - &encoder, - src.as_raw_slice(), - src.channels(), - src.bits_per_sample() as u32, - src.sample_rate() as u32, - ) - .map_err(|e| EncodeError(e.to_string()))?; - Ok(Stream::from_bytes(bytes)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::component::BitRepr; - use crate::error::Verify; - - /// The replica's own call sequence, verbatim from `export.rs:2994-3025`, - /// with the result decoded back to prove it is a real FLAC stream. - #[test] - fn the_replica_call_sequence_produces_a_decodable_stream() { - let samples: Vec = (0..8192) - .map(|i| ((i as f64 * 0.07).sin() * 12000.0) as i32) - .collect(); - - let config = config::Encoder::default() - .into_verified() - .map_err(|(_, e)| format!("flac encoder config: {e}")) - .unwrap(); - let source = source::MemSource::from_samples(&samples, 2, 16, 44100); - let mut stream = encode_with_fixed_block_size(&config, source, config.block_size) - .map_err(|e| format!("flac encode: {e}")) - .unwrap(); - stream - .stream_info_mut() - .set_block_sizes(config.block_size, config.block_size) - .map_err(|e| format!("flac block size: {e}")) - .unwrap(); - let mut sink = bitsink::ByteSink::new(); - stream - .write(&mut sink) - .map_err(|e| format!("flac write: {e}")) - .unwrap(); - - let bytes = sink.as_slice(); - assert_eq!(&bytes[..4], b"fLaC"); - assert_eq!(stream.count_bits(), bytes.len() * 8); - let mut reader = ec_flac::FlacReader::new(bytes).expect("our own output opens"); - let info = reader.stream_info().expect("streaminfo").clone(); - assert_eq!(info.min_block_size, config.block_size as u16); - assert_eq!(info.max_block_size, config.block_size as u16); - let decoded = reader.decode_all().expect("decode"); - assert_eq!(decoded.interleaved(), samples, "the shim must be lossless"); - } - - #[test] - fn a_block_size_the_stream_cannot_hold_is_an_error_not_a_panic() { - let config = config::Encoder::default().into_verified().unwrap(); - let source = source::MemSource::from_samples(&[0i32; 64], 2, 16, 44100); - let mut stream = encode_with_fixed_block_size(&config, source, 32).unwrap(); - assert!(stream.stream_info_mut().set_block_sizes(0, 70000).is_err()); - } - - #[test] - fn an_invalid_config_is_refused_with_its_original_value() { - let config = config::Encoder { - block_size: 4, - ..config::Encoder::default() - }; - let (returned, error) = config.into_verified().unwrap_err(); - assert_eq!(returned.block_size, 4); - assert!(format!("{error}").contains("block_size")); - } -} diff --git a/shims/flacenc/src/source.rs b/shims/flacenc/src/source.rs deleted file mode 100644 index d364ca54..00000000 --- a/shims/flacenc/src/source.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! `flacenc::source`: where samples come from. - -/// A signal the encoder can read. -/// -/// The incumbent's trait is a pull interface with a reusable context; the -/// replica only ever hands over a [`MemSource`] it built from a `Vec`, so this -/// is the whole-buffer shape of the same thing. -pub trait Source { - /// Channel count. - fn channels(&self) -> usize; - /// Bits per sample. - fn bits_per_sample(&self) -> usize; - /// Sample rate in Hz. - fn sample_rate(&self) -> usize; - /// The interleaved samples. - fn as_raw_slice(&self) -> &[i32]; -} - -/// Samples already in memory — `flacenc::source::MemSource`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MemSource { - channels: usize, - bits_per_sample: usize, - sample_rate: usize, - samples: Vec, -} - -impl MemSource { - /// Build from interleaved samples. - pub fn from_samples( - samples: &[i32], - channels: usize, - bits_per_sample: usize, - sample_rate: usize, - ) -> Self { - MemSource { - channels, - bits_per_sample, - sample_rate, - samples: samples.to_owned(), - } - } - - /// The samples, interleaved. - pub fn as_raw_slice(&self) -> &[i32] { - &self.samples - } - - /// Inter-channel samples held. - pub fn len(&self) -> usize { - match self.channels { - 0 => 0, - n => self.samples.len() / n, - } - } - - /// True when the source holds no samples. - pub fn is_empty(&self) -> bool { - self.samples.is_empty() - } -} - -impl Source for MemSource { - fn channels(&self) -> usize { - self.channels - } - - fn bits_per_sample(&self) -> usize { - self.bits_per_sample - } - - fn sample_rate(&self) -> usize { - self.sample_rate - } - - fn as_raw_slice(&self) -> &[i32] { - &self.samples - } -} diff --git a/shims/hound/Cargo.toml b/shims/hound/Cargo.toml deleted file mode 100644 index a3454092..00000000 --- a/shims/hound/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "hound" -description = "Compatibility shim: the hound 3.5.1 WAV-writing surface, implemented over ec-riff." -version = "3.5.1" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] - -[dependencies] -ec-riff = { path = "../../crates/ec-riff", version = "0.1.0" } diff --git a/shims/hound/src/lib.rs b/shims/hound/src/lib.rs deleted file mode 100644 index 84d02d2e..00000000 --- a/shims/hound/src/lib.rs +++ /dev/null @@ -1,344 +0,0 @@ -//! `hound` 3.5.1's WAV surface, over [`ec_riff`]. -//! -//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the -//! incumbent's name and version so a consumer's `use hound::…` compiles -//! unchanged. Only what edith consumes is here — `WavWriter::create`, -//! `write_sample`, `finalize`, `WavReader::open`, `spec`, `samples`, -//! [`WavSpec`], [`SampleFormat`] and an [`Error`] with the incumbent's variants -//! — because a shim that grows a surface nobody calls is a second -//! implementation to keep honest. -//! -//! Behaviour differences from the incumbent. Writing is stricter only: files -//! with more than two channels or more than 16 bits get a -//! `WAVE_FORMAT_EXTENSIBLE` header (hound writes one only above 16 bits), and -//! a `fact` chunk goes with it. Reading diverges in shape, not in verdict — -//! the refusals are hound's, the reporting is not: -//! -//! * [`WavReader::samples`] reads the `data` chunk whole before yielding, so a -//! file that ends early yields one [`Error::IoError`] and nothing else, -//! where hound yields the samples it did read and then the `UnexpectedEof`. -//! [`Error::TooWide`] and [`Error::InvalidSampleFormat`] are single-item for -//! the same reason; hound repeats them per sample. -//! * `bits_per_sample` outside 8/16/24/32 is [`Error::FormatError`] when it is -//! not a whole number of bytes and [`Error::Unsupported`] otherwise, which -//! splits hound's refusals along the same line but not with its wording. - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -use std::fmt; -use std::fs::File; -use std::io::{self, BufReader, BufWriter, Read, Seek, Write}; -use std::path::Path; - -/// A sample type a [`WavWriter`] accepts and a [`WavReader`] yields. -/// -/// The write half is [`ec_riff::Sample`]; the two constructors and the width -/// are what reading adds, and they are what makes hound's `TooWide` and -/// `InvalidSampleFormat` decidable before a single sample is converted. -pub trait Sample: ec_riff::Sample { - /// Bits this type carries. A file deeper than this is [`Error::TooWide`]. - const BITS: u16; - /// Narrow the reader's integer carrier. Called for integer files only. - fn from_i32(v: i32) -> Self; - /// Take the reader's float carrier. Called for float files only. - fn from_f32(v: f32) -> Self; -} - -macro_rules! int_sample { - ($($t:ty => $bits:expr),*) => {$( - impl Sample for $t { - const BITS: u16 = $bits; - fn from_i32(v: i32) -> Self { - v as $t - } - fn from_f32(v: f32) -> Self { - v as $t - } - } - )*}; -} -int_sample!(i8 => 8, i16 => 16, i32 => 32); - -impl Sample for f32 { - const BITS: u16 = 32; - fn from_i32(v: i32) -> Self { - v as f32 - } - fn from_f32(v: f32) -> Self { - v - } -} - -/// Whether samples are stored as floats or integers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SampleFormat { - /// `WAVE_FORMAT_IEEE_FLOAT`, nominal range -1.0..=1.0. - Float, - /// `WAVE_FORMAT_PCM`. - Int, -} - -/// Properties of the audio data. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct WavSpec { - /// The number of channels. - pub channels: u16, - /// The number of samples per second. - pub sample_rate: u32, - /// The number of bits per sample. - pub bits_per_sample: u16, - /// Whether the samples are float or integer values. - pub sample_format: SampleFormat, -} - -impl From for ec_riff::WavSpec { - fn from(s: WavSpec) -> ec_riff::WavSpec { - ec_riff::WavSpec { - channels: s.channels, - sample_rate: s.sample_rate, - bits_per_sample: s.bits_per_sample, - sample_format: match s.sample_format { - SampleFormat::Float => ec_riff::SampleType::Float, - SampleFormat::Int => ec_riff::SampleType::Int, - }, - } - } -} - -/// The error type for operations on `WavWriter`. -#[derive(Debug)] -pub enum Error { - /// An IO error occured in the underlying writer. - IoError(io::Error), - /// Ill-formed WAVE data was encountered. - FormatError(&'static str), - /// The sample has more bits than the destination format allows. - TooWide, - /// The number of samples written is not a multiple of the number of channels. - UnfinishedSample, - /// The format is not supported. - Unsupported, - /// The sample format is different than the destination format. - InvalidSampleFormat, -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::IoError(e) => e.fmt(f), - Error::FormatError(reason) => write!(f, "Ill-formed WAVE file: {reason}"), - Error::TooWide => f.write_str("The sample has more bits than the destination type."), - Error::UnfinishedSample => f.write_str( - "The number of samples written is not a multiple of the number of channels.", - ), - Error::Unsupported => f.write_str("The wave format of the file is not supported."), - Error::InvalidSampleFormat => { - f.write_str("The sample format differs from the destination format.") - } - } - } -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::IoError(e) => Some(e), - _ => None, - } - } -} - -impl From for Error { - fn from(e: io::Error) -> Error { - Error::IoError(e) - } -} - -/// A type for results generated by this crate. -pub type Result = std::result::Result; - -/// I/O failures keep their identity; everything else becomes `other`, which the -/// call site chooses, since the same `ec-riff` variant means different things -/// when writing a header, a sample, or the final sizes. -fn map(e: ec_riff::Error, corrupt_as: Error) -> Error { - match e { - ec_riff::Error::Io(e) => Error::IoError(e), - ec_riff::Error::Unsupported { .. } => Error::Unsupported, - _ => corrupt_as, - } -} - -/// Writes a WAVE file sample by sample. -pub struct WavWriter { - inner: ec_riff::WavWriter, -} - -impl WavWriter> { - /// Create a new wav file at `path` with the given spec. - pub fn create>(path: P, spec: WavSpec) -> Result { - let file = File::create(path)?; - WavWriter::new(BufWriter::new(file), spec) - } -} - -impl WavWriter { - /// Create a new writer over `writer`, writing the header immediately. - pub fn new(writer: W, spec: WavSpec) -> Result { - ec_riff::WavWriter::new(writer, spec.into()) - .map(|inner| WavWriter { inner }) - .map_err(|e| { - map( - e, - Error::FormatError("unusable channel count or sample rate"), - ) - }) - } - - /// Write a single sample for one channel. - pub fn write_sample(&mut self, sample: S) -> Result<()> { - self.inner.write_sample(sample).map_err(|e| match e { - // A value the declared depth cannot hold, versus a sample type the - // declared format cannot hold: hound's TooWide and - // InvalidSampleFormat respectively. - ec_riff::Error::Io(e) => Error::IoError(e), - ec_riff::Error::Unsupported { .. } => Error::InvalidSampleFormat, - _ => Error::TooWide, - }) - } - - /// Number of samples (per channel) written so far. - pub fn duration(&self) -> u32 { - self.inner.duration() as u32 - } - - /// The spec the file was created with. - pub fn spec(&self) -> WavSpec { - let s = self.inner.spec(); - WavSpec { - channels: s.channels, - sample_rate: s.sample_rate, - bits_per_sample: s.bits_per_sample, - sample_format: match s.sample_format { - ec_riff::SampleType::Float => SampleFormat::Float, - ec_riff::SampleType::Int => SampleFormat::Int, - }, - } - } - - /// Update the header with the written length and flush. - /// - /// Failing here is the difference between a finished file and a truncated - /// one, which is why it is called instead of dropping the writer. - pub fn finalize(self) -> Result<()> { - self.inner - .finalize() - .map(|_| ()) - .map_err(|e| map(e, Error::UnfinishedSample)) - } -} - -/// Reads a WAVE file's header, then its samples. -pub struct WavReader { - inner: ec_riff::WavReader, -} - -impl WavReader> { - /// Open `path` and parse its header. - pub fn open>(path: P) -> Result { - WavReader::new(BufReader::new(File::open(path)?)) - } -} - -impl WavReader { - /// Parse the header of an already-open stream. - pub fn new(reader: R) -> Result { - ec_riff::WavReader::new(reader) - .map(|inner| WavReader { inner }) - .map_err(|e| map(e, Error::FormatError("not a WAVE file this reader accepts"))) - } - - /// The `fmt ` chunk as parsed. - pub fn spec(&self) -> WavSpec { - let s = self.inner.spec(); - WavSpec { - channels: s.channels, - sample_rate: s.sample_rate, - bits_per_sample: s.bits_per_sample, - sample_format: match s.sample_format { - ec_riff::SampleType::Float => SampleFormat::Float, - ec_riff::SampleType::Int => SampleFormat::Int, - }, - } - } - - /// Every sample, interleaved in channel order, as the incumbent's fallible - /// iterator: a file whose format or depth `S` cannot carry yields one - /// [`Error::InvalidSampleFormat`] or [`Error::TooWide`] rather than a - /// converted value, which is where hound puts the same refusals. - /// - /// corner-cut: `ec-riff` reads the `data` chunk whole, so this buffers the - /// file where hound streams it — ~10 MB per minute of 48 kHz stereo, fine - /// for the export round-trips edith checks and wrong for an hour of audio. - /// Upgrade path is a streaming `read_samples` on `ec_riff::WavReader`, - /// which this then forwards to unchanged. - pub fn samples(&mut self) -> WavSamples { - let spec = self.inner.spec(); - let float_file = spec.sample_format == ec_riff::SampleType::Float; - // What the `data` header promised. `ec-riff` stops at the end of the - // file without complaint; hound hands the caller the `UnexpectedEof`, - // so the promise is compared against what arrived. - let promised = self - .inner - .duration() - .map(|frames| frames as usize * usize::from(spec.channels)); - let items = if float_file != S::FLOAT { - vec![Err(Error::InvalidSampleFormat)] - } else if spec.bits_per_sample > S::BITS { - vec![Err(Error::TooWide)] - } else if float_file { - match self.inner.read_all_f32() { - Ok(v) => match short_read(v.len(), promised) { - Some(e) => vec![Err(e)], - None => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(), - }, - Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], - } - } else { - match self.inner.read_all_i32() { - Ok(v) => match short_read(v.len(), promised) { - Some(e) => vec![Err(e)], - None => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(), - }, - Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))], - } - }; - WavSamples(items.into_iter()) - } -} - -/// The `UnexpectedEof` hound reports when the `data` chunk ends before the -/// length its header declares, or `None` when the file kept its promise (or -/// made none: a streamed placeholder size leaves the file itself the bound). -fn short_read(got: usize, promised: Option) -> Option { - let want = promised.filter(|&n| got < n)?; - Some(Error::IoError(io::Error::new( - io::ErrorKind::UnexpectedEof, - format!("WAVE data chunk ends after {got} of {want} samples"), - ))) -} - -/// The iterator [`WavReader::samples`] returns. -pub struct WavSamples(std::vec::IntoIter>); - -impl Iterator for WavSamples { - type Item = Result; - - fn next(&mut self) -> Option { - self.0.next() - } - - fn size_hint(&self) -> (usize, Option) { - self.0.size_hint() - } -} diff --git a/shims/hound/tests/edith_surface.rs b/shims/hound/tests/edith_surface.rs deleted file mode 100644 index d8a846e1..00000000 --- a/shims/hound/tests/edith_surface.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! The call edith makes, verbatim in shape (engine/src/export.rs `write_wav`): -//! `WavWriter::create(path, WavSpec { .. sample_format: Int })`, a run of -//! `write_sample(x as i16)`, then `finalize()` — with the `?` conversion into -//! edith's `Box` exercised too. - -type EdithError = Box; - -fn write_wav( - out: &std::path::Path, - samples: &[i32], - channels: u16, - rate: u32, -) -> Result<(), EdithError> { - let mut writer = hound::WavWriter::create( - out, - hound::WavSpec { - channels, - sample_rate: rate, - bits_per_sample: 16, - sample_format: hound::SampleFormat::Int, - }, - )?; - for &sample in samples { - writer.write_sample(sample as i16)?; - } - writer.finalize()?; - Ok(()) -} - -#[test] -fn edith_write_wav_round_trips() { - let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); - std::fs::create_dir_all(dir).unwrap(); - for (channels, rate) in [(1u16, 44100u32), (2, 48000), (6, 48000)] { - let path = dir.join(format!("edith-{channels}ch-{rate}.wav")); - let samples: Vec = (0..usize::from(channels) * 512) - .map(|i| ((i as i32 * 733) % 65536) - 32768) - .collect(); - write_wav(&path, &samples, channels, rate).unwrap(); - - let mut r = ec_riff::WavReader::open(&path).unwrap(); - let spec = r.spec(); - assert_eq!(spec.channels, channels); - assert_eq!(spec.sample_rate, rate); - assert_eq!(spec.bits_per_sample, 16); - assert_eq!(spec.sample_format, ec_riff::SampleType::Int); - assert_eq!(r.read_all_i32().unwrap(), samples); - } -} - -/// The read half edith's tests make: `WavReader::open`, `spec()`, and -/// `samples::()` collected — plus the two refusals hound answers with -/// when the requested type cannot carry the file. -#[test] -fn edith_read_wav_round_trips() { - let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); - std::fs::create_dir_all(dir).unwrap(); - let path = dir.join("read-back.wav"); - let samples: Vec = (0..2048).map(|i| ((i * 733) % 65536) - 32768).collect(); - write_wav(&path, &samples, 2, 48000).unwrap(); - - let mut r = hound::WavReader::open(&path).unwrap(); - let spec = r.spec(); - assert_eq!(spec.channels, 2); - assert_eq!(spec.sample_rate, 48000); - assert_eq!(spec.bits_per_sample, 16); - assert_eq!(spec.sample_format, hound::SampleFormat::Int); - let read: Vec = r - .samples::() - .map(|s| i32::from(s.expect("a sample"))) - .collect(); - assert_eq!(read, samples); - - // An integer file read as floats, and a 16-bit file read as 8: the two - // refusals, not silent conversions. - let mut r = hound::WavReader::open(&path).unwrap(); - assert!(matches!( - r.samples::().next(), - Some(Err(hound::Error::InvalidSampleFormat)) - )); - let mut r = hound::WavReader::open(&path).unwrap(); - assert!(matches!( - r.samples::().next(), - Some(Err(hound::Error::TooWide)) - )); -} - -/// A `data` chunk that ends before its header said is hound's `IoError` -/// (`UnexpectedEof`), never a short read the caller mistakes for the whole file. -#[test] -fn truncated_data_chunk_errors() { - let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); - std::fs::create_dir_all(dir).unwrap(); - let path = dir.join("truncated.wav"); - let samples: Vec = (0..1024).map(|i| (i * 17) % 4096).collect(); - write_wav(&path, &samples, 2, 48000).unwrap(); - - // Half the samples away, the header still promising all of them. - let bytes = std::fs::read(&path).unwrap(); - std::fs::write(&path, &bytes[..bytes.len() - 1024]).unwrap(); - - let mut r = hound::WavReader::open(&path).unwrap(); - let first = r.samples::().next(); - assert!( - matches!(&first, Some(Err(hound::Error::IoError(e))) if e.kind() == std::io::ErrorKind::UnexpectedEof), - "expected UnexpectedEof, got {first:?}" - ); -} - -/// A minimal PCM WAVE header with `block_align` and `bits_per_sample` stated -/// independently, so a padded container can be handed to the reader. -fn wav_bytes(channels: u16, bits: u16, block_align: u16, data: &[u8]) -> Vec { - let mut v = Vec::new(); - v.extend_from_slice(b"RIFF"); - v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); - v.extend_from_slice(b"WAVEfmt "); - v.extend_from_slice(&16u32.to_le_bytes()); - v.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM - v.extend_from_slice(&channels.to_le_bytes()); - v.extend_from_slice(&48000u32.to_le_bytes()); - v.extend_from_slice(&(48000 * u32::from(block_align)).to_le_bytes()); - v.extend_from_slice(&block_align.to_le_bytes()); - v.extend_from_slice(&bits.to_le_bytes()); - v.extend_from_slice(b"data"); - v.extend_from_slice(&(data.len() as u32).to_le_bytes()); - v.extend_from_slice(data); - v -} - -/// The header pair the reader must not paper over: a container wider than the -/// depth (hound: `Unsupported`) and a depth that is not whole bytes (hound: -/// `FormatError`). Reading either as if it were packed would silently double -/// the sample count and halve the duration. -#[test] -fn container_width_and_odd_depths_are_refused() { - let padded = wav_bytes(1, 8, 2, &[0x80, 0x00, 0x90, 0x00]); - assert!( - matches!( - hound::WavReader::new(std::io::Cursor::new(padded)), - Err(hound::Error::Unsupported) - ), - "8-bit samples in a 2-byte container must be refused" - ); - - for bits in [12u16, 20] { - let odd = wav_bytes(1, bits, bits.div_ceil(8), &[0; 8]); - assert!( - matches!( - hound::WavReader::new(std::io::Cursor::new(odd)), - Err(hound::Error::FormatError(_)) - ), - "{bits}-bit must be a FormatError" - ); - } - - // The well-formed shape of the same helper still opens, so the refusals - // above are about the fields under test and not about the fixture. - let ok = wav_bytes(2, 16, 4, &[0; 16]); - let r = hound::WavReader::new(std::io::Cursor::new(ok)).expect("a packed 16-bit stereo header"); - assert_eq!(r.spec().bits_per_sample, 16); -} - -#[test] -fn errors_carry_the_incumbent_variants() { - let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")); - let spec = hound::WavSpec { - channels: 2, - sample_rate: 48000, - bits_per_sample: 16, - sample_format: hound::SampleFormat::Int, - }; - let mut w = hound::WavWriter::create(dir.join("errors.wav"), spec).unwrap(); - // Wider than the declared depth, and the wrong sample family: the two - // failures callers of hound match on. - assert!(matches!( - w.write_sample(40_000i32), - Err(hound::Error::TooWide) - )); - assert!(matches!( - w.write_sample(0.5f32), - Err(hound::Error::InvalidSampleFormat) - )); - w.write_sample(1i16).unwrap(); - assert!(matches!(w.finalize(), Err(hound::Error::UnfinishedSample))); - // A directory is not a file: I/O keeps its identity through the shim. - assert!(matches!( - hound::WavWriter::create(dir, spec), - Err(hound::Error::IoError(_)) - )); -} diff --git a/shims/image/Cargo.toml b/shims/image/Cargo.toml deleted file mode 100644 index 70772b3b..00000000 --- a/shims/image/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "image" -description = "Compatibility shim: the image surface edith's engine consumes, served by ec-image." -version = "0.25.10" -edition.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[dependencies] -ec-image = { path = "../../crates/ec-image", version = "0.1.0" } - -# The format switches the incumbent gates its decoders behind. Every format this -# shim serves is compiled unconditionally, so these select nothing -- they exist -# because a consumer naming a feature the replacement lacks fails to *resolve*, -# and edith's engine asks for exactly these three. -[features] -png = [] -jpeg = [] -webp = [] - -# The surface that exists only because gpui consumes it: animation frames, -# their delays, and the per-format decoder types under `image::codecs`. It is -# not part of decoding a still picture, so a build that draws no windows does -# not compile it -- the way `chrono` keeps its `serde` impls behind a feature. -gpui = [] diff --git a/shims/image/src/gpui.rs b/shims/image/src/gpui.rs deleted file mode 100644 index 1652db52..00000000 --- a/shims/image/src/gpui.rs +++ /dev/null @@ -1,438 +0,0 @@ -//! The half of the `image` surface that exists only because gpui consumes it. -//! -//! edith's window toolkit decodes pictures through the same `image` crate the -//! engine does, and it reaches for animation: `Frame`, `Delay`, the -//! `AnimationDecoder` trait, and the per-format decoder types under -//! `image::codecs`. None of that belongs to a still-image decoder — it is a -//! consumer's shape — so it lives behind the `gpui` cargo feature, the way -//! `chrono` keeps its `serde` impls behind one. A build that does not draw -//! windows never compiles a line of it. -//! -//! Everything here is served by [`ec_image`]; nothing decodes twice. - -use std::io::Read; -use std::time::Duration; - -use crate::{DynamicImage, ImageError, ImageFormat, ImageResult, RgbaImage}; - -/// How long one frame of an animation is shown, as a rational number of -/// milliseconds — upstream's `image::Delay`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Delay { - numer: u32, - denom: u32, -} - -impl Delay { - /// A delay of `numer / denom` milliseconds. - pub fn from_numer_denom_ms(numer: u32, denom: u32) -> Delay { - Delay { numer, denom } - } - - /// The delay as the pair it was built from. - pub fn numer_denom_ms(self) -> (u32, u32) { - (self.numer, self.denom) - } -} - -impl From for Duration { - fn from(delay: Delay) -> Duration { - if delay.denom == 0 { - return Duration::ZERO; - } - Duration::from_nanos(u64::from(delay.numer) * 1_000_000 / u64::from(delay.denom)) - } -} - -/// One picture of an animation: the whole canvas at that point, and how long -/// it is shown. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Frame { - buffer: RgbaImage, - delay: Delay, -} - -impl Frame { - /// A single frame shown for no particular length of time — what a still - /// picture becomes when a caller wants frames. - pub fn new(buffer: RgbaImage) -> Frame { - Frame { - buffer, - delay: Delay::from_numer_denom_ms(0, 1), - } - } - - /// A frame with its own delay. - pub fn from_parts(buffer: RgbaImage, delay: Delay) -> Frame { - Frame { buffer, delay } - } - - /// The samples. - pub fn buffer(&self) -> &RgbaImage { - &self.buffer - } - - /// The samples, to be edited in place — callers swap R and B here. - pub fn buffer_mut(&mut self) -> &mut RgbaImage { - &mut self.buffer - } - - /// How long this frame is shown. - pub fn delay(&self) -> Delay { - self.delay - } -} - -/// The frames of an animation, as an iterator — upstream's `image::Frames`. -/// -/// Upstream streams them; these decoders composite the whole animation before -/// the first frame is handed out, because every format we serve carries frames -/// that reference their predecessors anyway. -pub struct Frames { - frames: std::vec::IntoIter>, -} - -impl Iterator for Frames { - type Item = ImageResult; - - fn next(&mut self) -> Option> { - self.frames.next() - } -} - -impl Frames { - fn of(frames: Vec>) -> Frames { - Frames { - frames: frames.into_iter(), - } - } -} - -/// A decoder that can yield more than one picture. -pub trait AnimationDecoder { - /// Every frame, composited. - fn into_frames(self) -> Frames; -} - -/// A decoder of one still picture, as far as [`DynamicImage::from_decoder`] is -/// concerned. -pub trait ImageDecoder { - /// Decode the whole picture. - fn into_image(self) -> ImageResult; -} - -impl DynamicImage { - /// The picture a decoder holds. - pub fn from_decoder(decoder: impl ImageDecoder) -> ImageResult { - decoder.into_image() - } - - /// The image as 8-bit RGBA, by value. - pub fn into_rgba8(self) -> RgbaImage { - match self { - DynamicImage::ImageRgba8(buffer) => buffer, - other => other.to_rgba8(), - } - } -} - -/// The format `data` starts with, as `image::guess_format`. -/// -/// Upstream errors on unrecognised bytes rather than returning `None`, and -/// gpui branches on that error, so this keeps the shape. -pub fn guess_format(data: &[u8]) -> ImageResult { - crate::format_of(data).ok_or_else(|| ImageError::Unsupported("unrecognised signature".into())) -} - -/// Decode bytes whose format the caller already knows. -/// -/// The format argument only *asserts* what the bytes are; every decoder here -/// is chosen by signature, so a mismatch surfaces as a decode error rather -/// than as a wrong picture. -pub fn load_from_memory_with_format(data: &[u8], format: ImageFormat) -> ImageResult { - match crate::format_of(data) { - Some(found) if found == format => crate::load_from_memory(data), - Some(found) => Err(ImageError::Decoding(format!( - "asked for {format:?}, the bytes are {found:?}" - ))), - None => Err(ImageError::Unsupported("unrecognised signature".into())), - } -} - -/// Read a decoder's whole input, the way upstream's decoders do before they -/// parse anything. -fn slurp(mut reader: impl Read) -> ImageResult> { - let mut data = Vec::new(); - reader.read_to_end(&mut data)?; - Ok(data) -} - -/// Every frame of an animation, as [`Frame`]s. -fn frames_of(data: &[u8]) -> Vec> { - match ec_image::decode_animation(data) { - Err(e) => vec![Err(e.into())], - Ok(frames) => frames - .into_iter() - .map(|frame| { - let (w, h) = (frame.image.width, frame.image.height); - let buffer = RgbaImage::from_raw(w, h, frame.image.to_rgba8()) - .ok_or_else(|| ImageError::Decoding("frame plane is short".into()))?; - // `Delay` counts milliseconds; the decoder counts seconds. - Ok(Frame::from_parts( - buffer, - Delay::from_numer_denom_ms( - frame.delay_num.saturating_mul(1000), - frame.delay_den.max(1), - ), - )) - }) - .collect(), - } -} - -/// The per-format decoder types, under the path upstream puts them. -pub mod codecs { - /// GIF. - pub mod gif { - use super::super::{AnimationDecoder, Frames, ImageDecoder, frames_of, slurp}; - use crate::{DynamicImage, ImageResult}; - - /// A GIF decoder over bytes, as `image::codecs::gif::GifDecoder`. - pub struct GifDecoder { - data: Vec, - } - - impl GifDecoder { - /// Take the bytes; nothing is parsed until a picture is asked for. - pub fn new(reader: impl std::io::Read) -> ImageResult { - Ok(GifDecoder { - data: slurp(reader)?, - }) - } - } - - impl AnimationDecoder for GifDecoder { - fn into_frames(self) -> Frames { - Frames::of(frames_of(&self.data)) - } - } - - impl ImageDecoder for GifDecoder { - fn into_image(self) -> ImageResult { - crate::load_from_memory(&self.data) - } - } - } - - /// WebP. - pub mod webp { - use super::super::{AnimationDecoder, Frames, ImageDecoder, frames_of, slurp}; - use crate::{DynamicImage, ImageResult, Rgba}; - - /// A WebP decoder over bytes, as `image::codecs::webp::WebPDecoder`. - pub struct WebPDecoder { - data: Vec, - } - - impl WebPDecoder { - /// Take the bytes; nothing is parsed until a picture is asked for. - pub fn new(reader: impl std::io::Read) -> ImageResult { - Ok(WebPDecoder { - data: slurp(reader)?, - }) - } - - /// Whether the file carries more than one picture. - pub fn has_animation(&self) -> bool { - ec_image::webp::is_animated(&self.data) - } - - /// The colour an animation's transparent areas are composited - /// over. - /// - /// Frames come out with their own alpha rather than flattened - /// onto a colour, which is what a caller asking for a fully - /// transparent background wants; any other colour is refused - /// rather than silently ignored. - pub fn set_background_color(&mut self, colour: Rgba) -> ImageResult<()> { - match colour.0 { - [_, _, _, 0] => Ok(()), - _ => Err(crate::ImageError::Unsupported( - "compositing animation frames onto an opaque background".into(), - )), - } - } - } - - impl AnimationDecoder for WebPDecoder { - fn into_frames(self) -> Frames { - Frames::of(frames_of(&self.data)) - } - } - - impl ImageDecoder for WebPDecoder { - fn into_image(self) -> ImageResult { - crate::load_from_memory(&self.data) - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ImageBuffer, Rgba}; - use std::io::Cursor; - use std::path::{Path, PathBuf}; - - fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills") - } - - fn bytes(name: &str) -> Option> { - let path = fixtures().join(name); - if !path.exists() { - eprintln!("skipped: {name} not generated; run scripts/gen-still-fixtures.sh"); - return None; - } - Some(std::fs::read(path).expect("read fixture")) - } - - /// A delay is milliseconds, whatever it is written over. - #[test] - fn a_delay_converts_to_the_duration_it_names() { - let tenth = Delay::from_numer_denom_ms(100, 1); - assert_eq!(Duration::from(tenth), Duration::from_millis(100)); - // A 1/100 s GIF tick, written as 10/1 ms. - let tick = Delay::from_numer_denom_ms(10, 1); - assert_eq!(Duration::from(tick), Duration::from_millis(10)); - // Thirds of a millisecond survive as nanoseconds rather than rounding - // to zero, which is what a 30 fps animation needs. - let third = Delay::from_numer_denom_ms(1, 3); - assert_eq!(Duration::from(third), Duration::from_nanos(333_333)); - assert_eq!( - Duration::from(Delay::from_numer_denom_ms(1, 0)), - Duration::ZERO - ); - } - - /// gpui's animated-GIF path, verbatim: guess the format, take the frames, - /// swap each frame's red and blue in place, and read the delays back. - #[test] - fn the_gpui_gif_sequence_works() { - let Some(data) = bytes("animated.gif") else { - return; - }; - assert_eq!( - guess_format(&data).expect("a GIF signature"), - ImageFormat::Gif - ); - - let decoder = codecs::gif::GifDecoder::new(Cursor::new(&data)).expect("decoder"); - let mut frames = Vec::new(); - for frame in decoder.into_frames() { - let mut frame = frame.expect("frame"); - for pixel in frame.buffer_mut().chunks_exact_mut(4) { - pixel.swap(0, 2); - } - frames.push(frame); - } - assert!( - frames.len() > 1, - "an animation decoded to {} frame(s)", - frames.len() - ); - let (width, height) = frames[0].buffer().dimensions(); - for frame in &frames { - assert_eq!( - frame.buffer().dimensions(), - (width, height), - "frames are composited onto one canvas" - ); - assert_eq!( - frame.buffer().as_raw().len(), - (width as usize) * (height as usize) * 4 - ); - assert!( - Duration::from(frame.delay()) > Duration::ZERO, - "a frame with no delay would never advance" - ); - } - } - - /// gpui's WebP path: a still goes through the decoder as one picture, an - /// animation through the frame iterator. - #[test] - fn the_gpui_webp_sequence_works() { - let Some(still) = bytes("lossless-alpha.webp") else { - return; - }; - let mut decoder = codecs::webp::WebPDecoder::new(Cursor::new(&still)).expect("decoder"); - assert!(!decoder.has_animation()); - assert!(decoder.set_background_color(Rgba([0, 0, 0, 0])).is_ok()); - let mut data = DynamicImage::from_decoder(decoder) - .expect("decode") - .into_rgba8(); - for pixel in data.chunks_exact_mut(4) { - pixel.swap(0, 2); - } - let frames = [Frame::new(data)]; - assert_eq!( - Duration::from(frames[0].delay()), - Duration::ZERO, - "a still has no delay" - ); - - let Some(animated) = bytes("animated.webp") else { - return; - }; - let decoder = codecs::webp::WebPDecoder::new(Cursor::new(&animated)).expect("decoder"); - assert!(decoder.has_animation(), "an ANIM file read as a still"); - let frames: Vec = decoder - .into_frames() - .map(|frame| frame.expect("frame")) - .collect(); - assert!( - frames.len() > 1, - "an animation decoded to {} frame(s)", - frames.len() - ); - } - - /// gpui's still path for everything else, and the buffer it builds by hand - /// for rendered SVGs. - #[test] - fn the_gpui_still_and_svg_paths_work() { - let Some(data) = bytes("rgb8.png") else { - return; - }; - let format = guess_format(&data).expect("a PNG signature"); - assert_eq!(format, ImageFormat::Png); - let picture = load_from_memory_with_format(&data, format) - .expect("decode") - .into_rgba8(); - assert_eq!(picture.dimensions(), (320, 240)); - - // The SVG renderer hands over its own samples; gpui wraps them and - // swaps the channel order in place. - let mut buffer = ImageBuffer::from_raw(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]).expect("buffer"); - for pixel in buffer.chunks_exact_mut(4) { - pixel.swap(0, 2); - } - assert_eq!(buffer.as_raw(), &vec![3, 2, 1, 4, 7, 6, 5, 8]); - let frame = Frame::new(buffer); - assert_eq!(frame.buffer().dimensions(), (2, 1)); - } - - /// Bytes of no known format are an error here, not a `None` -- gpui - /// branches on the error to try its SVG renderer instead. - #[test] - fn unknown_bytes_are_an_error_so_the_caller_can_fall_through() { - assert!(guess_format(b"").is_err()); - let Some(data) = bytes("rgb8.png") else { - return; - }; - // Asserting the wrong format is a decode error, never a wrong picture. - assert!(load_from_memory_with_format(&data, ImageFormat::Jpeg).is_err()); - } -} diff --git a/shims/image/src/lib.rs b/shims/image/src/lib.rs deleted file mode 100644 index 72618927..00000000 --- a/shims/image/src/lib.rs +++ /dev/null @@ -1,488 +0,0 @@ -//! Compatibility shim carrying the `image` name and version, over -//! [`ec_image`]. -//! -//! Only the surface a caller in this family actually consumes is here. edith's -//! engine uses exactly: -//! -//! ```text -//! image::ImageReader::open(path)?.with_guessed_format()?.decode()?.to_rgb8() -//! image::ImageReader::open(path)?.with_guessed_format()?.into_dimensions()? -//! image::open(path)?.to_rgb8().get_pixel(x, y).0 (engine test suite) -//! ``` -//! -//! so `ImageReader`, `DynamicImage` and the three 8-bit buffer types are the -//! whole shim. Anything else the upstream crate exposes is deliberately -//! absent, so a new use shows up as a compile error rather than as silently -//! different behaviour. -//! -//! **Not covered, deliberately:** the *app* crate's `RgbaImage::from_raw` / -//! `Frame::new` pair feeds `gpui::RenderImage`, which is typed against the -//! real `image` crate gpui itself depends on. Those two call sites cannot be -//! served by a shim — a `[patch.crates-io]` swap would retype gpui's own -//! dependency as well. The engine must therefore take this crate by rename -//! (`image = { package = "ec-image-shim", path = ... }`) or the app must keep -//! the real crate; the swap is not a blanket patch. See the S40 report. -//! -//! Behaviour differences from `image` 0.25.10, all consequences of the decoder -//! underneath and none of them reached by the surface above: -//! -//! - Only PNG, JPEG and WebP decode — the formats edith's `is_image` admits. -//! - EXIF orientation is parsed and exposed, not applied, exactly as upstream. -//! - JPEG samples may differ from upstream's by up to 4 counts of 255, an -//! IDCT-rounding difference the format explicitly permits; PNG and lossless -//! WebP are pixel-exact. - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -use std::fmt; -use std::path::Path; - -#[cfg(feature = "gpui")] -pub mod gpui; -// The names gpui writes as `image::...`; upstream has them at the crate root, -// so the feature's module is flattened into it. -#[cfg(feature = "gpui")] -pub use gpui::{ - AnimationDecoder, Delay, Frame, Frames, ImageDecoder, codecs, guess_format, - load_from_memory_with_format, -}; -/// Upstream's one generic buffer type. Every caller behind the `gpui` feature -/// instantiates it at RGBA8, so that is what the name means here. -#[cfg(feature = "gpui")] -pub type ImageBuffer = RgbaImage; - -/// Failure of a decode, as `image::ImageError`. -#[derive(Debug)] -pub enum ImageError { - /// The bytes are not a valid image of their format. - Decoding(String), - /// The format, or something in it, is not supported. - Unsupported(String), - /// Underlying I/O failure. - IoError(std::io::Error), -} - -impl fmt::Display for ImageError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ImageError::Decoding(m) => write!(f, "Format error decoding image: {m}"), - ImageError::Unsupported(m) => write!(f, "The image format is not supported: {m}"), - ImageError::IoError(e) => write!(f, "{e}"), - } - } -} - -impl std::error::Error for ImageError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - ImageError::IoError(e) => Some(e), - _ => None, - } - } -} - -impl From for ImageError { - fn from(e: std::io::Error) -> ImageError { - ImageError::IoError(e) - } -} - -impl From for ImageError { - fn from(e: ec_image::Error) -> ImageError { - match e { - ec_image::Error::Io(e) => ImageError::IoError(e), - ec_image::Error::Unsupported { what, why } => { - ImageError::Unsupported(format!("{what}: {why}")) - } - other => ImageError::Decoding(other.to_string()), - } - } -} - -/// The result of a decode, as `image::ImageResult`. -pub type ImageResult = Result; - -/// The formats this build decodes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ImageFormat { - /// PNG. - Png, - /// JPEG. - Jpeg, - /// WebP. - WebP, - /// GIF. - #[cfg(feature = "gpui")] - Gif, - /// Windows bitmap. - #[cfg(feature = "gpui")] - Bmp, - /// TIFF. - #[cfg(feature = "gpui")] - Tiff, -} - -/// One 8-bit greyscale pixel. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Luma(pub [u8; 1]); -/// One 8-bit R,G,B pixel. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Rgb(pub [u8; 3]); -/// One 8-bit R,G,B,A pixel. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Rgba(pub [u8; 4]); - -/// Generates the three concrete buffer types the surface uses. Upstream has -/// one generic `ImageBuffer`; three concrete types cover every consumed call -/// without dragging a pixel-trait hierarchy in behind them. -macro_rules! buffer { - ($name:ident, $pixel:ident, $channels:expr, $doc:literal) => { - #[doc = $doc] - #[derive(Debug, Clone, PartialEq, Eq)] - pub struct $name { - width: u32, - height: u32, - data: Vec, - } - - impl $name { - /// A buffer over `data`, or `None` when it is not - #[doc = concat!(stringify!($channels), " bytes per pixel.")] - pub fn from_raw(width: u32, height: u32, data: Vec) -> Option<$name> { - let needed = (width as usize) - .checked_mul(height as usize)? - .checked_mul($channels)?; - (data.len() >= needed).then_some($name { - width, - height, - data, - }) - } - - /// `(width, height)`. - pub fn dimensions(&self) -> (u32, u32) { - (self.width, self.height) - } - - /// Width in pixels. - pub fn width(&self) -> u32 { - self.width - } - - /// Height in pixels. - pub fn height(&self) -> u32 { - self.height - } - - /// The pixel at `(x, y)`; panics when it is outside the image, as - /// upstream's does. - pub fn get_pixel(&self, x: u32, y: u32) -> $pixel { - assert!( - x < self.width && y < self.height, - "({x}, {y}) is outside a {}x{} image", - self.width, - self.height - ); - let at = ((y as usize) * (self.width as usize) + x as usize) * $channels; - let mut pixel = [0u8; $channels]; - pixel.copy_from_slice(&self.data[at..at + $channels]); - $pixel(pixel) - } - - /// The samples, packed. - pub fn as_raw(&self) -> &Vec { - &self.data - } - - /// The samples, taken by value. - pub fn into_raw(self) -> Vec { - self.data - } - - /// The samples as a slice. - pub fn into_vec(self) -> Vec { - self.data - } - } - - impl std::ops::Deref for $name { - type Target = [u8]; - fn deref(&self) -> &[u8] { - &self.data - } - } - - impl std::ops::DerefMut for $name { - fn deref_mut(&mut self) -> &mut [u8] { - &mut self.data - } - } - }; -} - -buffer!(GrayImage, Luma, 1, "An 8-bit greyscale image buffer."); -buffer!(RgbImage, Rgb, 3, "An 8-bit RGB image buffer."); -buffer!(RgbaImage, Rgba, 4, "An 8-bit RGBA image buffer."); - -/// A decoded image of whichever colour form its file carried. -#[derive(Debug, Clone, PartialEq)] -pub enum DynamicImage { - /// 8-bit greyscale. - ImageLuma8(GrayImage), - /// 8-bit RGB. - ImageRgb8(RgbImage), - /// 8-bit RGBA. - ImageRgba8(RgbaImage), -} - -impl DynamicImage { - fn from_decoded(image: ec_image::Image) -> DynamicImage { - let (w, h) = (image.width, image.height); - match &image.pixels { - ec_image::Pixels::L8(data) => DynamicImage::ImageLuma8( - GrayImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"), - ), - ec_image::Pixels::Rgb8(data) => DynamicImage::ImageRgb8( - RgbImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"), - ), - _ if image.pixels.has_alpha() => DynamicImage::ImageRgba8( - RgbaImage::from_raw(w, h, image.to_rgba8()).expect("plane sized by the decoder"), - ), - _ => DynamicImage::ImageRgb8( - RgbImage::from_raw(w, h, image.to_rgb8()).expect("plane sized by the decoder"), - ), - } - } - - /// `(width, height)`. - pub fn dimensions(&self) -> (u32, u32) { - match self { - DynamicImage::ImageLuma8(b) => b.dimensions(), - DynamicImage::ImageRgb8(b) => b.dimensions(), - DynamicImage::ImageRgba8(b) => b.dimensions(), - } - } - - /// Width in pixels. - pub fn width(&self) -> u32 { - self.dimensions().0 - } - - /// Height in pixels. - pub fn height(&self) -> u32 { - self.dimensions().1 - } - - /// The image as 8-bit RGB, dropping any alpha channel. - pub fn to_rgb8(&self) -> RgbImage { - let (w, h) = self.dimensions(); - let data = match self { - DynamicImage::ImageRgb8(b) => return b.clone(), - DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l]).collect(), - DynamicImage::ImageRgba8(b) => b - .data - .as_chunks::<4>().0.iter() - .flat_map(|p| p[..3].to_vec()) - .collect(), - }; - RgbImage::from_raw(w, h, data).expect("converted plane") - } - - /// The image as 8-bit RGBA; opaque where the source had no alpha. - pub fn to_rgba8(&self) -> RgbaImage { - let (w, h) = self.dimensions(); - let data = match self { - DynamicImage::ImageRgba8(b) => return b.clone(), - DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l, 255]).collect(), - DynamicImage::ImageRgb8(b) => b - .data - .as_chunks::<3>().0.iter() - .flat_map(|p| [p[0], p[1], p[2], 255]) - .collect(), - }; - RgbaImage::from_raw(w, h, data).expect("converted plane") - } - - /// The image as 8-bit greyscale, by the same luma weights upstream uses. - pub fn to_luma8(&self) -> GrayImage { - let (w, h) = self.dimensions(); - let data = match self { - DynamicImage::ImageLuma8(b) => return b.clone(), - _ => self - .to_rgb8() - .data - .as_chunks::<3>().0.iter() - .map(|p| { - let luma = - 2126 * u32::from(p[0]) + 7152 * u32::from(p[1]) + 722 * u32::from(p[2]); - ((luma + 5000) / 10000).min(255) as u8 - }) - .collect(), - }; - GrayImage::from_raw(w, h, data).expect("converted plane") - } -} - -/// A decoder that guesses its format from the bytes, as `image::ImageReader`. -/// -/// Upstream is generic over any `BufRead + Seek`; this reads the whole file -/// once, because every caller in this family hands it a path and then decodes -/// the whole picture anyway. -#[derive(Debug)] -pub struct ImageReader { - data: Vec, - format: Option, -} - -impl ImageReader { - /// Open `path` for decoding. The format is not guessed yet. - pub fn open(path: impl AsRef) -> std::io::Result { - Ok(ImageReader { - data: std::fs::read(path)?, - format: None, - }) - } - - /// A reader over bytes already in memory. - pub fn new(data: Vec) -> ImageReader { - ImageReader { data, format: None } - } - - /// Guess the format from the leading bytes. - /// - /// Upstream returns an I/O error here because it may have to read; an - /// unrecognised signature is not an error at this point in either crate — - /// it surfaces at `decode`. - pub fn with_guessed_format(mut self) -> std::io::Result { - self.format = format_of(&self.data); - Ok(self) - } - - /// The format, once guessed or set. - pub fn format(&self) -> Option { - self.format - } - - /// Decode the whole picture. - pub fn decode(self) -> ImageResult { - Ok(DynamicImage::from_decoded(ec_image::decode(&self.data)?)) - } - - /// The dimensions from the header alone, without decoding the pixels. - pub fn into_dimensions(self) -> ImageResult<(u32, u32)> { - let info = ec_image::info(&self.data)?; - Ok((info.width, info.height)) - } -} - -/// The format `data`'s leading bytes name, if this build decodes it. -fn format_of(data: &[u8]) -> Option { - match ec_image::ImageFormat::guess(data)? { - ec_image::ImageFormat::Png => Some(ImageFormat::Png), - ec_image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg), - ec_image::ImageFormat::WebP => Some(ImageFormat::WebP), - // Only the gpui half of this shim names the formats gpui asks for; a - // build without it has no variant to answer with. - #[cfg(feature = "gpui")] - ec_image::ImageFormat::Gif => Some(ImageFormat::Gif), - #[cfg(not(feature = "gpui"))] - ec_image::ImageFormat::Gif => None, - #[cfg(feature = "gpui")] - ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp), - #[cfg(not(feature = "gpui"))] - ec_image::ImageFormat::Bmp => None, - #[cfg(feature = "gpui")] - ec_image::ImageFormat::Tiff => Some(ImageFormat::Tiff), - #[cfg(not(feature = "gpui"))] - ec_image::ImageFormat::Tiff => None, - } -} - -/// Decode the file at `path`. -pub fn open(path: impl AsRef) -> ImageResult { - let data = std::fs::read(path)?; - load_from_memory(&data) -} - -/// Decode bytes already in memory. -pub fn load_from_memory(data: &[u8]) -> ImageResult { - Ok(DynamicImage::from_decoded(ec_image::decode(data)?)) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - - fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills") - } - - /// The exact sequence edith's engine performs, start to finish. - #[test] - fn the_engine_call_sequence_works() { - let path = fixtures().join("rgb8.png"); - if !path.exists() { - eprintln!("skipped: fixtures/stills not generated"); - return; - } - let reader = ImageReader::open(&path).expect("open"); - let rgb = reader - .with_guessed_format() - .expect("guess") - .decode() - .map_err(|e| format!("{}: {e}", path.display())) - .expect("decode") - .to_rgb8(); - let (width, height) = rgb.dimensions(); - assert_eq!((width, height), (320, 240)); - assert_eq!(rgb.len(), 320 * 240 * 3, "Deref reaches the samples"); - - let dimensions = ImageReader::open(&path) - .unwrap() - .with_guessed_format() - .unwrap() - .into_dimensions() - .expect("dimensions"); - assert_eq!(dimensions, (320, 240)); - - let pixel = open(&path).expect("open").to_rgb8().get_pixel(7, 9).0; - assert_eq!(pixel.len(), 3); - } - - #[test] - fn a_missing_file_is_an_io_error_the_caller_can_propagate() { - let err = ImageReader::open(fixtures().join("nope.png")).unwrap_err(); - assert_eq!(err.kind(), std::io::ErrorKind::NotFound); - let err: ImageError = err.into(); - assert!(matches!(err, ImageError::IoError(_)), "{err}"); - } - - #[test] - fn a_file_that_is_not_an_image_fails_at_decode_not_at_guess() { - let reader = ImageReader::new(b"not a picture at all".to_vec()) - .with_guessed_format() - .expect("guessing never fails on unknown bytes"); - assert_eq!(reader.format(), None); - assert!(matches!(reader.decode(), Err(ImageError::Unsupported(_)))); - } - - #[test] - fn alpha_survives_and_grey_stays_grey() { - let dir = fixtures(); - if !dir.join("rgba8.png").exists() { - eprintln!("skipped: fixtures/stills not generated"); - return; - } - let rgba = open(dir.join("rgba8.png")).unwrap(); - assert!(matches!(rgba, DynamicImage::ImageRgba8(_))); - let grey = open(dir.join("gray8.png")).unwrap(); - assert!(matches!(grey, DynamicImage::ImageLuma8(_))); - // to_rgb8 of a grey image repeats the luma into all three channels. - let rgb = grey.to_rgb8(); - let p = rgb.get_pixel(3, 3).0; - assert_eq!(p[0], p[1]); - assert_eq!(p[1], p[2]); - } -} diff --git a/shims/miniz_oxide/Cargo.toml b/shims/miniz_oxide/Cargo.toml deleted file mode 100644 index 9e213a2c..00000000 --- a/shims/miniz_oxide/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "miniz_oxide" -description = "Compatibility shim: the miniz_oxide surface edith consumes, served by ec-inflate." -version = "0.8.9" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-inflate = { path = "../../crates/ec-inflate", version = "0.1.0" } diff --git a/shims/miniz_oxide/src/lib.rs b/shims/miniz_oxide/src/lib.rs deleted file mode 100644 index d673786f..00000000 --- a/shims/miniz_oxide/src/lib.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! Compatibility shim carrying the `miniz_oxide` name and version, over -//! [`ec_inflate`]. -//! -//! Only the surface a caller in this family actually consumes is here — edith's -//! Matroska `ContentEncodings` path uses exactly -//! [`inflate::decompress_to_vec_zlib_with_limit`] and the `Display` of the error -//! it returns. Field names, statuses and message strings match miniz_oxide -//! 0.8.9 so a `[patch.crates-io]` swap needs no source change; anything else the -//! upstream crate exposes is deliberately absent, so a new use shows up as a -//! compile error rather than as silently different behaviour. - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -/// Decompression, as `miniz_oxide::inflate`. -pub mod inflate { - use ec_inflate::Error; - - /// Return status codes, as miniz_oxide spells them. - #[repr(i8)] - #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] - pub enum TINFLStatus { - /// More input was expected but the caller said there is no more. - FailedCannotMakeProgress = -4, - /// The output buffer is an invalid size. - BadParam = -3, - /// Decompression went fine but the Adler-32 did not match. - Adler32Mismatch = -2, - /// Failed to decompress due to invalid data. - Failed = -1, - /// Finished decompression without issues. - Done = 0, - /// The decompressor needs more input data to continue. - NeedsMoreInput = 1, - /// There is still pending data that did not fit in the output buffer. - HasMoreOutput = 2, - } - - /// Failure of a `decompress_to_vec*` call, with the data decoded so far. - #[derive(Debug)] - pub struct DecompressError { - /// Decompressor status on failure. - pub status: TINFLStatus, - /// The currently decompressed data, if any. - pub output: Vec, - } - - impl core::fmt::Display for DecompressError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(match self.status { - TINFLStatus::FailedCannotMakeProgress => "Truncated input stream", - TINFLStatus::BadParam => "Invalid output buffer size", - TINFLStatus::Adler32Mismatch => "Adler32 checksum mismatch", - TINFLStatus::Failed => "Invalid input data", - TINFLStatus::Done => "", - TINFLStatus::NeedsMoreInput => "Truncated input stream", - TINFLStatus::HasMoreOutput => "Output size exceeded the specified limit", - }) - } - } - - impl std::error::Error for DecompressError {} - - /// Decompress zlib-wrapped data, growing the output to at most `max_size`. - /// - /// Over the limit the error carries [`TINFLStatus::HasMoreOutput`] and the - /// bytes decompressed so far, as upstream does. - pub fn decompress_to_vec_zlib_with_limit( - input: &[u8], - max_size: usize, - ) -> Result, DecompressError> { - let mut output = Vec::new(); - match ec_inflate::inflate_into(input, &mut output, max_size, ec_inflate::Format::Zlib) { - Ok(()) => Ok(output), - Err(error) => Err(DecompressError { - status: match error { - Error::Truncated => TINFLStatus::FailedCannotMakeProgress, - Error::LimitExceeded { .. } => TINFLStatus::HasMoreOutput, - Error::Adler32Mismatch { .. } => TINFLStatus::Adler32Mismatch, - Error::Corrupt { .. } | Error::Unsupported { .. } => TINFLStatus::Failed, - }, - output, - }), - } - } - - #[cfg(test)] - mod tests { - use super::*; - - /// `zlib.compress(b"edith reads this out of a Matroska ContentEncodings block" * 4, 9)`. - const STREAM: [u8; 66] = [ - 0x78, 0xda, 0xd5, 0xcb, 0xc1, 0x0d, 0x80, 0x30, 0x0c, 0x03, 0xc0, 0x55, 0xbc, 0x0b, - 0xe2, 0xc9, 0x10, 0xa1, 0x09, 0xb4, 0x2a, 0x8a, 0xa5, 0xc6, 0xec, 0xcf, 0x1c, 0xdc, - 0xff, 0xc2, 0x87, 0x3a, 0x56, 0x98, 0x17, 0xd4, 0x47, 0x81, 0xaf, 0xc0, 0x0b, 0x86, - 0xc3, 0xb4, 0x58, 0xd3, 0xb0, 0x31, 0x15, 0xa9, 0x3d, 0x1b, 0x7d, 0xe4, 0x5d, 0x38, - 0x1f, 0xb6, 0x19, 0xff, 0x89, 0x1f, 0xb5, 0xdd, 0x54, 0x95, - ]; - const PLAIN: &[u8] = b"edith reads this out of a Matroska ContentEncodings block"; - - /// The call site: engine/src/demux.rs, `Unpack::Zlib`. - #[test] - fn decompresses_under_the_limit() { - let out = decompress_to_vec_zlib_with_limit(&STREAM, 64 << 20).unwrap(); - assert_eq!(out.len(), PLAIN.len() * 4); - assert_eq!(&out[..PLAIN.len()], PLAIN); - } - - #[test] - fn over_the_limit_reports_has_more_output_with_partial_data() { - let error = decompress_to_vec_zlib_with_limit(&STREAM, 64).unwrap_err(); - assert_eq!(error.status, TINFLStatus::HasMoreOutput); - assert!(error.output.len() <= 64); - assert_eq!( - error.to_string(), - "Output size exceeded the specified limit" - ); - } - - #[test] - fn a_broken_stream_reports_its_status() { - let mut broken = STREAM; - let last = broken.len() - 1; - broken[last] ^= 0xff; - let error = decompress_to_vec_zlib_with_limit(&broken, 64 << 20).unwrap_err(); - assert_eq!(error.status, TINFLStatus::Adler32Mismatch); - assert_eq!(error.to_string(), "Adler32 checksum mismatch"); - - let error = decompress_to_vec_zlib_with_limit(&STREAM[..20], 64 << 20).unwrap_err(); - assert_eq!(error.status, TINFLStatus::FailedCannotMakeProgress); - assert_eq!(error.to_string(), "Truncated input stream"); - } - } -} diff --git a/shims/opus-rs/Cargo.toml b/shims/opus-rs/Cargo.toml deleted file mode 100644 index 79495bf2..00000000 --- a/shims/opus-rs/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "opus-rs" -description = "Compatibility shim: the opus-rs 0.1.26 surface edith consumes, served by ec-opus." -version = "0.1.26" -edition.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[lib] -name = "opus_rs" - -[dependencies] -ec-opus = { path = "../../crates/ec-opus", version = "0.1.0" } diff --git a/shims/opus-rs/src/lib.rs b/shims/opus-rs/src/lib.rs deleted file mode 100644 index e879b82e..00000000 --- a/shims/opus-rs/src/lib.rs +++ /dev/null @@ -1,462 +0,0 @@ -//! Compatibility shim: the `opus-rs` 0.1.26 surface edith consumes, served by -//! [`ec_opus`]. -//! -//! The incumbent this replaces encoded packets that only its own decoder read -//! back above ~128-165 kbps (correlation 0.06 against the reference decoder at 256 kbps on -//! the same signal that round-tripped internally at 0.999), and mono was -//! broken at every rate. This shim serves the same three-call surface — -//! `OpusEncoder::new(rate, channels, Application)`, the public `bitrate_bps` -//! and `complexity` fields, `.encode(&pcm, frame_size, &mut out)` — from the -//! `ec-opus` CELT encoder, which is range-exact against the family's -//! RFC-vector-verified decoder and the reference decoder-verified at every rate up to -//! 510 kbps, mono and stereo alike. The measured envelope that capped the -//! incumbent (`OPUS_MAX_KBPS = 128`) is obsolete behind this crate. -//! -//! `complexity` is accepted for drop-in compatibility and ignored: this -//! encoder has one (fast) analysis path, not a ladder. -//! -//! [`Application::Voip`] below 20 kbps, mono, 20 ms frames picks the SILK -//! layer, as the reference does; every other combination stays CELT. Stereo -//! SILK and SILK at other frame sizes fall back to CELT rather than -//! silently approximating it. - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -use std::fmt; - -/// What the encoded stream is optimised for. This CELT-only encoder spends the -/// setting on the coded bandwidth, not on a different coding layer. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Application { - /// Speech-optimised (SILK in the reference decoder; served by CELT here). - Voip, - /// Music and general audio. - Audio, - /// Lowest-latency mode. - RestrictedLowdelay, -} - -impl From for ec_opus::Application { - fn from(a: Application) -> ec_opus::Application { - match a { - Application::Voip => ec_opus::Application::Voip, - Application::Audio => ec_opus::Application::Audio, - Application::RestrictedLowdelay => ec_opus::Application::LowDelay, - } - } -} - -/// Coded audio bandwidth, with the C API's discriminants. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Bandwidth { - /// Chosen from the bitrate, the application and the input rate. - Auto = -1000, - /// 4 kHz. - Narrowband = 1101, - /// 6 kHz. CELT has no mediumband configuration; this codes as wideband. - Mediumband = 1102, - /// 8 kHz. - Wideband = 1103, - /// 12 kHz. - SuperWideband = 1104, - /// 20 kHz. - Fullband = 1105, -} - -/// The error type of this shim: a message, as the incumbent's was. -#[derive(Debug, Clone)] -pub struct OpusError(String); - -impl fmt::Display for OpusError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -impl std::error::Error for OpusError {} - -/// An Opus encoder with the incumbent's field-configured surface. -#[derive(Debug)] -pub struct OpusEncoder { - /// Target bitrate in bits per second, applied at the next - /// [`OpusEncoder::encode`] call. - pub bitrate_bps: i32, - /// Accepted for compatibility; this encoder has a single analysis path. - pub complexity: i32, - /// Coded bandwidth; [`Bandwidth::Auto`] follows the bitrate. - pub bandwidth: Bandwidth, - /// Constrained VBR. Off by default, as the incumbent's was. - pub vbr: bool, - inner: ec_opus::Encoder, - channels: usize, - applied_bandwidth: Bandwidth, - applied_vbr: bool, -} - -impl OpusEncoder { - /// An encoder at `sample_rate` (8000, 12000, 16000, 24000 or 48000) for - /// `channels` channels (1 or 2). - pub fn new( - sample_rate: i32, - channels: i32, - application: Application, - ) -> Result { - if sample_rate < 0 || channels < 0 { - return Err(OpusError(format!( - "invalid encoder arguments: {sample_rate} Hz, {channels} channels" - ))); - } - let inner = - ec_opus::Encoder::new(sample_rate as u32, channels as usize, application.into()) - .map_err(|e| OpusError(e.to_string()))?; - Ok(OpusEncoder { - bitrate_bps: 64_000 * channels, - complexity: 10, - bandwidth: Bandwidth::Auto, - vbr: false, - inner, - channels: channels as usize, - applied_bandwidth: Bandwidth::Auto, - applied_vbr: false, - }) - } - - /// Samples of encoder delay, at the input rate: the decoded stream lags - /// the input by this much, and an Ogg-Opus pre-skip of it (scaled to - /// 48 kHz) cancels the lag exactly. Reported for the canonical 20 ms - /// frame (SILK and Hybrid, which shift the delay, only run at 20 ms - /// anyway) — like the incumbent's `OPUS_GET_LOOKAHEAD`, which doesn't - /// take a frame size either. - pub fn look_ahead(&self) -> usize { - self.inner.look_ahead(self.inner.sample_rate() as usize / 50) - } - - /// The range coder state after the last packet — the RFC 6716 Section 6 - /// conformance hook, which a conformant decoder reproduces exactly. - pub fn final_range(&self) -> u32 { - self.inner.final_range() - } - - /// Encodes `frame_size` samples per channel of interleaved `f32` into - /// `out`, returning the packet length in bytes. - pub fn encode( - &mut self, - pcm: &[f32], - frame_size: usize, - out: &mut [u8], - ) -> Result { - if pcm.len() < frame_size * self.channels { - return Err(OpusError(format!( - "{} samples is short of {} channels x {frame_size}", - pcm.len(), - self.channels - ))); - } - self.sync_settings(); - self.inner - .encode_float(pcm, frame_size, out) - .map_err(|e| OpusError(e.to_string())) - } - - /// [`OpusEncoder::encode`] from 16-bit samples. - pub fn encode_i16( - &mut self, - pcm: &[i16], - frame_size: usize, - out: &mut [u8], - ) -> Result { - if pcm.len() < frame_size * self.channels { - return Err(OpusError(format!( - "{} samples is short of {} channels x {frame_size}", - pcm.len(), - self.channels - ))); - } - self.sync_settings(); - self.inner - .encode(pcm, frame_size, out) - .map_err(|e| OpusError(e.to_string())) - } - - /// Drops all inter-frame state; the next packet starts a fresh stream. - pub fn reset(&mut self) { - self.inner.reset(); - } - - /// Pushes the public fields into the encoder before a frame. - fn sync_settings(&mut self) { - self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); - if self.bandwidth != self.applied_bandwidth { - self.inner.set_bandwidth(match self.bandwidth { - Bandwidth::Auto => None, - Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow), - Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide), - Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide), - Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full), - }); - self.applied_bandwidth = self.bandwidth; - } - if self.vbr != self.applied_vbr { - self.inner.set_vbr_constrained(self.vbr); - self.applied_vbr = self.vbr; - } - } -} - -/// An Opus decoder, mono or stereo. -#[derive(Debug)] -pub struct OpusDecoder { - inner: ec_opus::Decoder, -} - -impl OpusDecoder { - /// A decoder for `channels` channels at `sample_rate` Hz. - pub fn new(sample_rate: i32, channels: i32) -> Result { - if sample_rate < 0 || channels < 0 { - return Err(OpusError(format!( - "invalid decoder arguments: {sample_rate} Hz, {channels} channels" - ))); - } - Ok(OpusDecoder { - inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize) - .map_err(|e| OpusError(e.to_string()))?, - }) - } - - /// Decodes one packet into interleaved `f32`, returning samples per - /// channel. `frame_size` bounds the output, as the incumbent's did. - pub fn decode( - &mut self, - packet: &[u8], - frame_size: usize, - out: &mut [f32], - ) -> Result { - let _ = frame_size; - self.inner - .decode_float(packet, out) - .map_err(|e| OpusError(e.to_string())) - } - - /// The range coder state after the last packet. - pub fn final_range(&self) -> u32 { - self.inner.final_range() - } -} - -/// A multichannel encoder, for the 5.1 and 7.1 exports the incumbent could not -/// do at all — the replica's surround Opus path today is stereo only. -#[derive(Debug)] -pub struct MultistreamEncoder { - /// Target bitrate in bits per second, across all streams. - pub bitrate_bps: i32, - inner: ec_opus::MultistreamEncoder, - channels: usize, -} - -impl MultistreamEncoder { - /// An encoder for the RFC 7845 family-1 layout of `channels` channels (1 - /// to 8). Input is in the mapping's channel order, which for 5.1 is Vorbis - /// order: left, centre, right, back left, back right, LFE. - pub fn surround( - sample_rate: i32, - channels: usize, - application: Application, - ) -> Result { - if sample_rate < 0 { - return Err(OpusError(format!("invalid sample rate {sample_rate}"))); - } - let inner = - ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into()) - .map_err(|e| OpusError(e.to_string()))?; - Ok(MultistreamEncoder { - bitrate_bps: 96_000 * channels as i32 / 2, - inner, - channels, - }) - } - - /// The channel mapping table the `OpusHead` for this encoder needs. - pub fn mapping(&self) -> &[u8] { - self.inner.layout().2 - } - - /// Elementary streams, and how many of them are coupled. - pub fn stream_counts(&self) -> (usize, usize) { - let (streams, coupled, _) = self.inner.layout(); - (streams, coupled) - } - - /// Encodes one frame of interleaved `f32`, returning the packet length. - pub fn encode( - &mut self, - pcm: &[f32], - frame_size: usize, - out: &mut [u8], - ) -> Result { - if pcm.len() < frame_size * self.channels { - return Err(OpusError(format!( - "{} samples is short of {} channels x {frame_size}", - pcm.len(), - self.channels - ))); - } - self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); - self.inner - .encode_float(pcm, frame_size, out) - .map_err(|e| OpusError(e.to_string())) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The exact call shape edith's export path uses (export.rs:1863-1896). - #[test] - fn edith_call_shape_compiles_and_encodes() { - let mut encoder = OpusEncoder::new(48000, 2, Application::Audio) - .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}")) - .unwrap(); - encoder.bitrate_bps = 256_000; - encoder.complexity = 10; - let frame = vec![0.1f32; 960 * 2]; - let mut out = vec![0u8; 1500]; - let len = encoder - .encode(&frame, 960, &mut out) - .map_err(|e| format!("Opus encode failed: {e}")) - .unwrap(); - assert!(len > 2 && len <= 1276); - // Mono — broken at every rate in the incumbent — encodes too. - let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap(); - mono.bitrate_bps = 96_000; - let frame = vec![0.1f32; 960]; - let len = mono.encode(&frame, 960, &mut out).unwrap(); - assert!(len > 2); - } - - fn tone(n: usize, channels: usize) -> Vec { - (0..n * channels) - .map(|i| { - let t = (i / channels) as f32; - 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin() - }) - .collect() - } - - /// The decoder half of the surface, and the conformance hook that says the - /// two agree: the decoder's range state must equal the encoder's after - /// every packet. - #[test] - fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() { - const FRAME: usize = 960; - let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); - enc.bitrate_bps = 256_000; - let mut dec = OpusDecoder::new(48_000, 2).unwrap(); - let pcm = tone(FRAME * 8, 2); - let mut out = vec![0u8; 1500]; - let mut back = vec![0.0f32; FRAME * 2]; - let mut total = 0; - for block in pcm.as_chunks::<{ FRAME * 2 }>().0.iter() { - let len = enc.encode(block, FRAME, &mut out).unwrap(); - assert!(len > 1 && len <= 1276, "packet of {len} bytes"); - total += len; - assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); - assert_eq!(dec.final_range(), enc.final_range()); - } - // 256 kbps over 8 frames of 20 ms: the incumbent's 165 kbps ceiling is - // what this number exists to refute. - let want = 256_000 / 8 / 50 * 8; - assert!( - (total as f64 - want as f64).abs() < 0.2 * want as f64, - "{total} bytes vs {want} at 256 kbps" - ); - } - - /// Input below 48 kHz, which the shim used to refuse outright, and the - /// `look_ahead` that goes with it: libopus's `OPUS_GET_LOOKAHEAD`, - /// `Fs/400 + Fs/250` (120 + 192 at 48 kHz), in the input rate's samples. - /// ffmpeg's libopus encoder runs at 48 kHz and reports 312 for every rate. - #[test] - fn slower_input_rates_encode_and_report_their_own_delay() { - for &(rate, frame, look) in &[ - (48_000i32, 960usize, 312usize), - (24_000, 480, 156), - (16_000, 320, 104), - (12_000, 240, 78), - (8_000, 160, 52), - ] { - let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap(); - enc.bitrate_bps = 32_000; - assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead"); - let pcm = tone(frame * 4, 1); - let mut out = vec![0u8; 1500]; - // Everything a 48 kHz decoder gets back is 48 kHz, whatever went in. - let mut dec = OpusDecoder::new(48_000, 1).unwrap(); - let mut back = vec![0.0f32; 960]; - for block in pcm.chunks_exact(frame) { - let len = enc.encode(block, frame, &mut out).unwrap(); - assert!(len > 2, "{rate} Hz packet of {len} bytes"); - assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960); - assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range"); - } - } - assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err()); - } - - /// A narrower band is a smaller top-band cost, not a refusal: forcing the - /// bandwidth must still produce packets a decoder reads. - #[test] - fn forced_bandwidth_and_i16_input_round_trip() { - const FRAME: usize = 960; - let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap(); - enc.bitrate_bps = 64_000; - enc.bandwidth = Bandwidth::Wideband; - enc.vbr = true; - let pcm: Vec = tone(FRAME * 4, 1) - .iter() - .map(|v| (v * 16_000.0) as i16) - .collect(); - let mut out = vec![0u8; 1500]; - let mut dec = OpusDecoder::new(48_000, 1).unwrap(); - let mut back = vec![0.0f32; FRAME]; - for block in pcm.as_chunks::hi\n"), - ( - "vtt", - "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nhi\n", - ), - ( - "ass", - "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\ - Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi\n", - ), - ] { - let parse = parser_for(ext).expect("the replica routes these four extensions"); - let track = parse(doc.as_bytes()).unwrap(); - // `subtitle.rs:623-632`: cues mapped onto the engine's own `Cue`. - let cues: Vec<(i64, i64, String)> = track - .cues - .iter() - .map(|c| (c.start_us, c.end_us, plain_text(&c.segments))) - .collect(); - assert_eq!(cues, vec![(1_000_000, 2_000_000, "hi".to_owned())], "{ext}"); - } - assert!(parser_for("txt").is_none()); -} - -/// `subtitle.rs:516-527` — an `S_TEXT/UTF8` block's markup resolved by wrapping -/// it in a synthetic SRT. -#[test] -fn a_matroska_text_block_is_resolved_through_the_srt_parser() { - let text = "tilted and plain"; - let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end()); - let resolved = match oxideav_subtitle::srt::parse(doc.as_bytes()) { - Ok(track) => track - .cues - .first() - .map(|c| plain_text(&c.segments)) - .unwrap_or_default(), - Err(_) => text.trim_end().to_owned(), - }; - assert_eq!(resolved, "tilted and plain"); -} - -/// `subtitle.rs:89-125` — a Matroska PGS block, framed back into a `.sup` and -/// decoded to straight RGBA the size of the disc's own canvas. -#[test] -fn a_matroska_pgs_block_decodes_the_way_the_replica_decodes_one() { - let set = matroska_block(); - let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID)); - let mut decoder = oxideav_sub_image::pgs::make_decoder(¶ms).unwrap(); - let mut sup = Vec::with_capacity(set.len() + 64); - let mut shows = false; - for (kind, body) in segments(&set).unwrap() { - sup.extend_from_slice(b"PG"); - sup.extend_from_slice(&[0; 8]); - sup.push(kind); - sup.extend_from_slice(&(body.len() as u16).to_be_bytes()); - sup.extend_from_slice(body); - match kind { - oxideav_sub_image::pgs::SEG_PCS => { - shows = body.get(10).is_some_and(|&n| n > 0); - } - oxideav_sub_image::pgs::SEG_END if shows => break, - _ => {} - } - } - decoder - .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) - .unwrap(); - let rgba = match decoder.receive_frame().unwrap() { - Frame::Video(frame) => frame.planes.into_iter().next().map(|p| p.data), - _ => None, - } - .expect("a display set is a picture"); - // The whole canvas, transparent where the cue paints nothing. - assert_eq!(rgba.len(), 4 * 2 * 4); - assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); - // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`). - assert_eq!(&rgba[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]); - - // The erase set after the composition must not be what gets decoded: the - // loop above stops at the `END` that closes the showing set. - let all: Vec = set.clone(); - assert!( - segments(&all).unwrap().len() > 5, - "the block holds both sets" - ); -} - -/// `subtitle.rs:131-140` — the segments of a display set as a Matroska block -/// holds them: type, big-endian size, body. -fn segments(set: &[u8]) -> Option> { - let mut out = Vec::new(); - let mut at = 0; - while at < set.len() { - let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize; - out.push((set[at], set.get(at + 3..at + 3 + size)?)); - at += 3 + size; - } - Some(out) -} - -/// A block holding a composition *and* the erase that follows it — the packing -/// the replica's comment warns about. -fn matroska_block() -> Vec { - let block = |kind: u8, body: &[u8]| { - let mut out = vec![kind]; - out.extend_from_slice(&(body.len() as u16).to_be_bytes()); - out.extend_from_slice(body); - out - }; - let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1]; - pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]); - let pds = vec![0, 0, 1, 235, 128, 128, 255]; - let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00]; - let mut ods = vec![0, 0, 0, 0xC0]; - ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); - ods.extend_from_slice(&[0, 2, 0, 1]); - ods.extend_from_slice(&rle); - // The erase: a composition with no objects at all. - let erase = vec![0, 4, 0, 2, 0x10, 0, 1, 0, 0, 0, 0]; - [ - block(oxideav_sub_image::pgs::SEG_PCS, &pcs), - block(oxideav_sub_image::pgs::SEG_PDS, &pds), - block(oxideav_sub_image::pgs::SEG_ODS, &ods), - block(oxideav_sub_image::pgs::SEG_END, &[]), - block(oxideav_sub_image::pgs::SEG_PCS, &erase), - block(oxideav_sub_image::pgs::SEG_END, &[]), - ] - .concat() -} diff --git a/shims/oxideav-subtitle/Cargo.toml b/shims/oxideav-subtitle/Cargo.toml deleted file mode 100644 index d1ff504a..00000000 --- a/shims/oxideav-subtitle/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "oxideav-subtitle" -description = "Compatibility shim: the oxideav-subtitle surface edith consumes, over ec-subs." -version = "0.1.2" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" } -oxideav-core = { path = "../oxideav-core", version = "0.1.34" } diff --git a/shims/oxideav-subtitle/src/lib.rs b/shims/oxideav-subtitle/src/lib.rs deleted file mode 100644 index b060cb7f..00000000 --- a/shims/oxideav-subtitle/src/lib.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! `oxideav-subtitle` as edith consumes it, over [`ec_subs`]. -//! -//! Three items and their types: `ir::plain_text`, `ir::SubtitleTrack`, -//! `srt::parse` and `webvtt::parse`. The IR is `ec_subs`'s own — the field -//! names were chosen to match, so this is a re-export and not a conversion — -//! and the only adapter is the error type, because the replica writes the parse -//! functions as `fn(&[u8]) -> oxideav_core::Result` and takes -//! their address. - -#![forbid(unsafe_code)] - -/// The cue IR, which is [`ec_subs::ir`] under its incumbent name. -pub mod ir { - pub use ec_subs::ir::{ - CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign, - plain_text, - }; -} - -pub use ir::{SourceFormat, SubtitleTrack}; - -/// SubRip. -pub mod srt { - use oxideav_core::Result; - - use crate::ir::SubtitleTrack; - - /// Parse a SubRip document. - pub fn parse(bytes: &[u8]) -> Result { - Ok(ec_subs::srt::parse(bytes)?) - } -} - -/// WebVTT. -pub mod webvtt { - use oxideav_core::Result; - - use crate::ir::SubtitleTrack; - - /// Parse a WebVTT document. - pub fn parse(bytes: &[u8]) -> Result { - Ok(ec_subs::webvtt::parse(bytes)?) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The replica takes these as function pointers of one type and calls - /// `plain_text` on whatever comes back; that is the whole contract. - #[test] - fn the_parsers_are_interchangeable_function_pointers() { - type Parse = fn(&[u8]) -> oxideav_core::Result; - for parse in [srt::parse as Parse, webvtt::parse as Parse] { - let track = parse(b"1\n00:00:01,000 --> 00:00:02,000\nhi\n").unwrap(); - assert_eq!(ir::plain_text(&track.cues[0].segments), "hi"); - assert_eq!(track.cues[0].start_us, 1_000_000); - } - // A file of the wrong kind is an error the replica can print. - let error = srt::parse(b"prose, not subtitles").unwrap_err(); - assert!(!error.to_string().is_empty()); - } -} diff --git a/shims/ruopus/Cargo.toml b/shims/ruopus/Cargo.toml deleted file mode 100644 index a43aee23..00000000 --- a/shims/ruopus/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "ruopus" -description = "Compatibility shim: the ruopus 0.1.2 surface edith consumes, served by ec-opus." -version = "0.1.2" -edition.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[dependencies] -ec-opus = { path = "../../crates/ec-opus", version = "0.1.0" } - -# The incumbent's feature names, all no-ops here. A `[patch.crates-io]` consumer -# that names a feature the patch lacks fails to *resolve*, so the swap needs -# them declared even though nothing behind them is optional in this crate: -# `spectrograms` bought the incumbent an FFT-backed MDCT (fifteen crates), and -# `ec-opus` has that path unconditionally through `ec-dsp`. -[features] -default = ["std", "spectrograms"] -std = [] -spectrograms = ["std"] -libm = [] diff --git a/shims/ruopus/src/lib.rs b/shims/ruopus/src/lib.rs deleted file mode 100644 index faffbbb3..00000000 --- a/shims/ruopus/src/lib.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! `ruopus` as edith consumes it, over [`ec_opus`]. -//! -//! A shim, not a port: it carries the incumbent's package name and version so -//! the swap is a `[patch.crates-io]` line, and it exposes exactly the one item -//! the replica names — [`MultistreamDecoder`], built with `with_rate` and fed -//! one packet at a time with `decode_packet` (`audio.rs:1575`, `1694`; -//! `export.rs:1950`, the fidelity gate's own decoder). -//! -//! A re-export is the whole adapter, and that is a claim about two things -//! rather than about the names: -//! -//! * **Layout arguments.** `with_rate(rate, streams, coupled, &mapping)` means -//! the same thing in both: the first `coupled` elementary streams are stereo, -//! `mapping[c]` names the decoded channel output channel `c` reads (255 = -//! silent), and an impossible layout panics rather than returning — which is -//! why the replica checks the `OpusHead` it read from a file before it gets -//! here (`audio.rs:opus_layout`). -//! * **Channel order.** Both decoders emit the *mapping's* order, which for RFC -//! 7845 family 1 is Vorbis order (FL, FC, FR, BL, BR, LFE for 5.1) and not -//! the product's FL/FR/FC/LFE/BL/BR. The permutation stays where the -//! incumbent's behaviour already put it, at the call site -//! (`audio.rs:vorbis_to_film_order`); a shim that permuted here would fold -//! surround twice. -//! -//! Errors differ in type and not in use: `ec_core::Error` where the incumbent -//! had `PacketError`, both `Display` and both consumed as `{e}` or as a -//! refused packet. - -#![forbid(unsafe_code)] - -pub use ec_opus::MultistreamDecoder; diff --git a/shims/rusty_aac/Cargo.toml b/shims/rusty_aac/Cargo.toml deleted file mode 100644 index 24a1fb19..00000000 --- a/shims/rusty_aac/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "rusty_aac" -description = "Compatibility shim: the rusty_aac 0.5 surface edith consumes, served by ec-aac." -version = "0.5.0" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-aac = { path = "../../crates/ec-aac", version = "0.1.0" } diff --git a/shims/rusty_aac/src/lib.rs b/shims/rusty_aac/src/lib.rs deleted file mode 100644 index 360ac82b..00000000 --- a/shims/rusty_aac/src/lib.rs +++ /dev/null @@ -1,233 +0,0 @@ -//! The `rusty_aac` 0.5 surface, served by `ec-aac`. -//! -//! Only what edith consumes is here, at the incumbent's signatures: -//! `AacDecoder::with_config_bytes` (audio.rs:1731), `AacEncoder::new` with -//! `AacEncoderConfig` (mux.rs:2116, export.rs:1756) and `sf_index_for_rate` -//! (export.rs:1678). The encoder's tool flags are kept as fields so a caller -//! written against the incumbent still compiles; each one names what it maps to. - -#![forbid(unsafe_code)] - -pub use ec_aac::{ - AdtsHeader, AudioSpecificConfig, SAMPLE_RATES, audio_specific_config_bytes, is_adts, - parse_adts, parse_audio_specific_config, sample_rate_for_index, sf_index_for_rate, - write_adts_header, write_audio_specific_config, -}; - -/// The incumbent's error type: one variant per refusal reason, `Eof` included -/// so `while let Ok(p) = next_packet()` still terminates. -#[derive(Debug)] -pub enum Error { - Eof, - NeedMore, - Invalid(String), - Unsupported(String), -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Eof => write!(f, "end of stream"), - Error::NeedMore => write!(f, "need more data"), - Error::Invalid(m) => write!(f, "invalid: {m}"), - Error::Unsupported(m) => write!(f, "unsupported: {m}"), - } - } -} - -impl std::error::Error for Error {} - -impl Error { - pub fn invalid(msg: impl Into) -> Error { - Error::Invalid(msg.into()) - } - - pub fn unsupported(msg: impl Into) -> Error { - Error::Unsupported(msg.into()) - } -} - -impl From for Error { - fn from(e: ec_aac::Error) -> Error { - match e { - ec_aac::Error::Eof => Error::Eof, - ec_aac::Error::NeedMore => Error::NeedMore, - ec_aac::Error::Unsupported { .. } => Error::Unsupported(e.to_string()), - other => Error::Invalid(other.to_string()), - } - } -} - -pub type Result = std::result::Result; - -/// One decoded frame, interleaved, in film channel order. -#[derive(Clone, Debug, Default)] -pub struct DecodedAudio { - pub sample_rate: u32, - pub channels: u16, - pub samples: Vec, - pub pts: Option, -} - -impl DecodedAudio { - pub fn frames(&self) -> usize { - if self.channels == 0 { - 0 - } else { - self.samples.len() / usize::from(self.channels) - } - } -} - -/// What the decoder does with a High Efficiency stream. -pub use ec_aac::SbrSupport; - -/// An AAC-LC decoder. -pub struct AacDecoder(ec_aac::AacDecoder); - -impl AacDecoder { - pub fn new() -> AacDecoder { - AacDecoder(ec_aac::AacDecoder::new()) - } - - pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder { - AacDecoder(ec_aac::AacDecoder::with_config(cfg)) - } - - pub fn with_config_bytes(data: &[u8]) -> Result { - Ok(AacDecoder(ec_aac::AacDecoder::with_config_bytes(data)?)) - } - - pub fn sbr_support(&self) -> SbrSupport { - self.0.sbr_support() - } - - pub fn output_sample_rate(&self) -> Option { - self.0.output_sample_rate() - } - - pub fn decode(&mut self, packet: &[u8], pts: Option) -> Result { - let d = self.0.decode(packet, pts)?; - Ok(DecodedAudio { - sample_rate: d.sample_rate, - channels: d.channels, - samples: d.samples, - pts: d.pts, - }) - } -} - -impl Default for AacDecoder { - fn default() -> AacDecoder { - AacDecoder::new() - } -} - -/// Window-shape policy. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum WindowShape { - #[default] - Sine, - Kbd, - /// Per-frame dispatch on content tonality; served here as [`WindowShape::Sine`]. - Auto, -} - -/// Encoder options, at the incumbent's field set. -#[derive(Debug, Clone, Copy)] -pub struct AacEncoderConfig { - /// Target bitrate in bits per second. - pub bitrate_bps: u32, - /// Window-shape policy. - pub window_shape: WindowShape, - /// The `Auto` gate's threshold; unused here, `Auto` codes as sine. - pub shape_tonality_pct: f32, - /// Run the psychoacoustic model on short blocks: always on here. - pub short_block_psy: bool, - /// Make the signal-to-mask ratio a function of band tonality: always on here. - pub tonality_smr: bool, - /// Emit TNS on long blocks; not emitted by this encoder (decoding it is - /// complete either way). - pub tns: bool, - /// Level-invariant transient detector: always on here. - pub relative_transients: bool, - /// Perceptual noise substitution; not emitted by this encoder. - pub pns: bool, - /// Intensity stereo; not emitted by this encoder. - pub intensity: bool, - /// Split a pair's bit budget by perceptual demand: always on here, the rate - /// loop is joint over the whole frame. - pub stereo_bit_split: bool, -} - -impl Default for AacEncoderConfig { - fn default() -> AacEncoderConfig { - AacEncoderConfig { - bitrate_bps: 128_000, - window_shape: WindowShape::Sine, - shape_tonality_pct: 0.5, - short_block_psy: true, - tonality_smr: true, - tns: false, - relative_transients: true, - pns: false, - intensity: false, - stereo_bit_split: true, - } - } -} - -/// One encoded raw access unit (a `raw_data_block`, no ADTS framing). -#[derive(Debug, Clone)] -pub struct EncodedPacket { - pub data: Vec, - pub pts: i64, - pub duration: u32, -} - -/// An AAC-LC encoder. -pub struct AacEncoder(ec_aac::AacEncoder); - -impl AacEncoder { - pub fn new(config: AacEncoderConfig) -> AacEncoder { - AacEncoder(ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig { - bitrate_bps: config.bitrate_bps.max(1), - window_shape: match config.window_shape { - WindowShape::Kbd => ec_aac::WindowShape::Kbd, - _ => ec_aac::WindowShape::Sine, - }, - adts: false, - mid_side: true, - window_switching: true, - })) - } - - pub fn sample_rate(&self) -> u32 { - self.0.sample_rate() - } - - pub fn channels(&self) -> u16 { - self.0.channels() - } - - pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> { - Ok(self.0.push_pcm(interleaved, channels, sample_rate)?) - } - - pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> { - Ok(self.0.push_pcm_planar(planes, sample_rate)?) - } - - pub fn finish(&mut self) { - self.0.finish(); - } - - pub fn next_packet(&mut self) -> Result { - let p = self.0.next_packet()?; - Ok(EncodedPacket { - data: p.data, - pts: p.pts, - duration: p.duration, - }) - } -} diff --git a/shims/rusty_aac/tests/edith_surface.rs b/shims/rusty_aac/tests/edith_surface.rs deleted file mode 100644 index 908c651b..00000000 --- a/shims/rusty_aac/tests/edith_surface.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! The call sites edith actually has, compiled and run against the shim. -//! -//! Each one mirrors a line in the replica: `audio.rs:1731` builds the decoder -//! for a multichannel track from its AudioSpecificConfig, `export.rs:1678` -//! turns a sample rate into a `samplingFrequencyIndex`, and `export.rs:1756` -//! plus `mux.rs:2116` drive the encoder over a mix. - -#[test] -fn sf_index_for_rate_covers_the_rates_the_exporter_offers() { - assert_eq!(rusty_aac::sf_index_for_rate(48_000), Some(3)); - assert_eq!(rusty_aac::sf_index_for_rate(44_100), Some(4)); - assert_eq!(rusty_aac::sf_index_for_rate(96_000), Some(0)); - assert_eq!(rusty_aac::sf_index_for_rate(8_000), Some(11)); - // The exporter's own error path: a rate AAC cannot carry. - assert_eq!(rusty_aac::sf_index_for_rate(37_000), None); -} - -#[test] -fn a_multichannel_track_builds_from_its_audio_specific_config() { - // 5.1 at 48 kHz, which is what a film's mkv hands over as CodecPrivate. - let asc = rusty_aac::audio_specific_config_bytes(48_000, 6); - let decoder = rusty_aac::AacDecoder::with_config_bytes(&asc).expect("decoder builds"); - assert_eq!(decoder.output_sample_rate(), Some(48_000)); - assert_eq!(decoder.sbr_support(), rusty_aac::SbrSupport::NotSignalled); -} - -/// `export.rs:1756`: the caller's bitrate over the config's defaults, PCM in, -/// packets out until `Eof`. -#[test] -fn the_export_encoder_loop_runs_to_eof() { - let rate = 48_000u32; - let channels = 2u16; - let frames = rate as usize; - let mut pcm = Vec::with_capacity(frames * usize::from(channels)); - for i in 0..frames { - let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5; - for _ in 0..channels { - pcm.push(s); - } - } - let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig { - bitrate_bps: 256 * 1_000, - ..Default::default() - }); - encoder - .push_pcm(&pcm, channels, rate) - .expect("pcm accepted"); - encoder.finish(); - let mut packets = Vec::new(); - while let Ok(packet) = encoder.next_packet() { - assert_eq!(packet.duration, 1024, "one AAC frame per packet"); - assert!(!packet.data.is_empty(), "a packet with no payload"); - packets.push(packet); - } - assert!( - packets.len() > 10, - "a second of audio is many packets, got {}", - packets.len() - ); - assert_eq!(encoder.sample_rate(), rate); - assert_eq!(encoder.channels(), channels); - - // And the packets are a stream this family's own decoder reads back. - let asc = rusty_aac::audio_specific_config_bytes(rate, channels); - let mut decoder = rusty_aac::AacDecoder::with_config_bytes(&asc).expect("decoder builds"); - let mut decoded = 0usize; - for packet in &packets { - let audio = decoder.decode(&packet.data, None).expect("packet decodes"); - assert_eq!(audio.channels, channels); - decoded += audio.frames(); - } - assert_eq!(decoded, packets.len() * 1024); -} diff --git a/shims/rusty_h264/Cargo.toml b/shims/rusty_h264/Cargo.toml deleted file mode 100644 index fb762503..00000000 --- a/shims/rusty_h264/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "rusty_h264" -description = "Compatibility shim: the rusty_h264 0.9.1 surface edith consumes, served by ec-h264." -version = "0.9.1" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-h264 = { workspace = true } -ec-h264-syntax = { workspace = true } diff --git a/shims/rusty_h264/src/lib.rs b/shims/rusty_h264/src/lib.rs deleted file mode 100644 index bb85095f..00000000 --- a/shims/rusty_h264/src/lib.rs +++ /dev/null @@ -1,328 +0,0 @@ -//! The `rusty_h264` 0.9.1 surface, served by `ec-h264`. -//! -//! Only what edith consumes is here, at the incumbent's signatures: -//! `Decoder::new` + `decode` over whole access units (decode.rs:1478-1500, -//! export.rs:4200), and `EncoderConfig` + `Encoder::new` + `try_encode` + -//! `try_flush` with `YuvFrame` and `Preset` (export.rs:3407-3422, 3640-3650, -//! 3727-3736). -//! -//! Two differences from the incumbent, both deliberate and both visible only -//! as *absences*: -//! -//! - No `#[global_allocator]`. The incumbent's `common` crate installed one -//! process-wide and had to be vendored out; there is nothing to vendor here. -//! - No lookahead buffering. `try_encode` returns the access unit of the -//! picture it was handed, every time, so `try_flush` has nothing left to -//! give and the caller's per-picture timing is exact whatever the rate -//! control mode. -//! -//! Pictures come out in decode order, which is what the incumbent did and what -//! edith's decode loop assumes. [`Decoder::in_display_order`] is the same -//! decoder with the reordering the incumbent never had. - -#![forbid(unsafe_code)] - -use ec_h264::{NalOutcome, OutputOrder, PictureView}; - -/// The incumbent's error type: one variant per refusal reason. -#[derive(Debug)] -pub enum Error { - NeedMore, - Invalid(String), - Unsupported(String), -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::NeedMore => write!(f, "need more data"), - Error::Invalid(m) => write!(f, "invalid: {m}"), - Error::Unsupported(m) => write!(f, "unsupported: {m}"), - } - } -} - -impl std::error::Error for Error {} - -impl From for Error { - fn from(e: ec_h264::Error) -> Error { - match e { - ec_h264::Error::NeedMore => Error::NeedMore, - ec_h264::Error::Unsupported { .. } => Error::Unsupported(e.to_string()), - other => Error::Invalid(other.to_string()), - } - } -} - -/// A decoded — or about to be encoded — I420 picture, planes owned. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct YuvFrame { - pub width: usize, - pub height: usize, - pub y: Vec, - pub u: Vec, - pub v: Vec, -} - -/// Speed/quality ladder. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Preset { - #[default] - Fast, - Balanced, -} - -impl From for ec_h264::Preset { - fn from(p: Preset) -> ec_h264::Preset { - match p { - Preset::Fast => ec_h264::Preset::Fast, - Preset::Balanced => ec_h264::Preset::Balanced, - } - } -} - -/// The H.264 software decoder. -pub struct Decoder { - inner: ec_h264::Decoder, -} - -impl Default for Decoder { - fn default() -> Decoder { - Decoder::new() - } -} - -impl Decoder { - /// A decoder that emits pictures in decode order. - pub fn new() -> Decoder { - let mut inner = ec_h264::Decoder::new(); - inner.set_output_order(OutputOrder::Decode); - Decoder { inner } - } - - /// A decoder that emits pictures in *display* order, which a stream with - /// B pictures needs and the incumbent could not do. Pictures then come out - /// with the stream's own reordering delay, so a caller that stops feeding - /// must call [`Decoder::flush`] to collect the tail. - pub fn in_display_order() -> Decoder { - let mut inner = ec_h264::Decoder::new(); - inner.set_output_order(OutputOrder::Display); - Decoder { inner } - } - - /// Decode one access unit (Annex B, one coded picture), returning the - /// picture it completed if any. - pub fn decode(&mut self, au: &[u8]) -> Result, Error> { - self.feed(au)?; - if self.inner.picture_open() { - self.inner.end_picture()?; - } - Ok(self.take()) - } - - /// Decode a whole Annex B stream at once, returning every picture in it — - /// what a test that holds an encoder's output in memory asks for, where - /// [`Decoder::decode`] serves a demuxer handing over one unit at a time. - pub fn decode_stream(&mut self, stream: &[u8]) -> Result, Error> { - let mut out = Vec::new(); - self.feed(stream)?; - // The tail: whatever the last picture and the reordering delay hold. - self.inner.flush()?; - while let Some(frame) = self.take() { - out.push(frame); - } - Ok(out) - } - - /// Push every NAL in `bytes`, closing a picture wherever one ends. - fn feed(&mut self, bytes: &[u8]) -> Result<(), Error> { - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { - if self.inner.push_nal(nal)? == NalOutcome::PictureBoundary { - // The next picture starts here: close the one before it. - self.inner.end_picture()?; - self.inner.push_nal(nal)?; - } - } - Ok(()) - } - - /// Collect a picture the reordering delay is still holding, at end of - /// stream. - pub fn flush(&mut self) -> Result, Error> { - self.inner.flush()?; - Ok(self.take()) - } - - fn take(&mut self) -> Option { - let frame = self.inner.next_frame()?; - let (w, h) = (frame.width as usize, frame.height as usize); - let plane = |i: usize, pw: usize, ph: usize| -> Vec { - let p = &frame.planes[i]; - let mut out = Vec::with_capacity(pw * ph); - for row in 0..ph { - out.extend_from_slice(&p.data[row * p.stride..row * p.stride + pw]); - } - out - }; - Some(YuvFrame { - width: w, - height: h, - y: plane(0, w, h), - u: plane(1, w / 2, h / 2), - v: plane(2, w / 2, h / 2), - }) - } -} - -/// Encoder settings, at the incumbent's field names. -#[derive(Debug, Clone)] -pub struct EncoderConfig { - pub width: usize, - pub height: usize, - pub framerate: f32, - /// Bits per second; zero codes at a constant quantiser instead. - pub bitrate: u32, - pub gop_size: u32, - /// Consecutive B pictures. Accepted at any value and coded as zero: this - /// encoder has no B pictures yet, and refusing the field would break a - /// caller that sets it. - pub bframes: u32, - pub preset: Preset, -} - -impl EncoderConfig { - /// The incumbent's constructor: geometry now, everything else by field. - pub fn new(width: usize, height: usize) -> EncoderConfig { - EncoderConfig { - width, - height, - framerate: 30.0, - bitrate: 0, - gop_size: 250, - bframes: 0, - preset: Preset::Fast, - } - } -} - -/// The H.264 software encoder. -pub struct Encoder { - inner: ec_h264::Encoder, - width: usize, - height: usize, -} - -impl Encoder { - pub fn new(cfg: EncoderConfig) -> Result { - let mut inner_cfg = ec_h264::EncoderConfig::new(cfg.width as u32, cfg.height as u32); - inner_cfg.framerate = cfg.framerate; - inner_cfg.bitrate = cfg.bitrate; - inner_cfg.gop_size = cfg.gop_size; - inner_cfg.bframes = cfg.bframes; - inner_cfg.preset = cfg.preset.into(); - let inner = ec_h264::Encoder::new(inner_cfg)?; - Ok(Encoder { - inner, - width: cfg.width, - height: cfg.height, - }) - } - - /// One picture in, its access unit out — always, with no lookahead delay. - pub fn try_encode(&mut self, frame: &YuvFrame) -> Result, Error> { - if frame.width != self.width || frame.height != self.height { - return Err(Error::Invalid(format!( - "frame is {}x{}, encoder is {}x{}", - frame.width, frame.height, self.width, self.height - ))); - } - let view = PictureView::i420( - self.width as u32, - self.height as u32, - &frame.y, - &frame.u, - &frame.v, - ); - Ok(self.inner.encode(&view)?.au) - } - - /// Nothing is ever held back, so this is always empty; it exists because - /// the caller's drain path calls it. - pub fn try_flush(&mut self) -> Result, Error> { - Ok(Vec::new()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn frame(w: usize, h: usize, t: usize) -> YuvFrame { - YuvFrame { - width: w, - height: h, - y: (0..w * h) - .map(|i| ((i / w + i % w + t * 4) % 256) as u8) - .collect(), - u: vec![110; w / 2 * h / 2], - v: vec![150; w / 2 * h / 2], - } - } - - /// The whole surface edith calls, in the order edith calls it: configure, - /// encode picture by picture, drain, then decode what came out. - #[test] - fn the_edith_call_sequence_round_trips() { - let (w, h) = (176usize, 144usize); - let mut cfg = EncoderConfig::new(w, h); - cfg.framerate = 25.0; - cfg.bitrate = 600_000; - cfg.gop_size = 5; - cfg.bframes = 0; - cfg.preset = Preset::Fast; - let mut enc = Encoder::new(cfg).expect("encoder"); - let mut units = Vec::new(); - for t in 0..6 { - let au = enc.try_encode(&frame(w, h, t)).expect("encode"); - assert!(!au.is_empty(), "picture {t} produced no access unit"); - units.push(au); - } - assert!(enc.try_flush().expect("flush").is_empty()); - - let mut dec = Decoder::new(); - for (t, au) in units.iter().enumerate() { - let got = dec.decode(au).expect("decode").expect("a picture"); - assert_eq!((got.width, got.height), (w, h), "picture {t} geometry"); - assert_eq!(got.y.len(), w * h); - assert_eq!(got.u.len(), w / 2 * h / 2); - // A coded picture is close to its source; this is the shim's own - // proof that the two halves are wired to each other. - let src = frame(w, h, t); - let mse: f64 = got - .y - .iter() - .zip(&src.y) - .map(|(&a, &b)| { - let d = f64::from(a) - f64::from(b); - d * d - }) - .sum::() - / (w * h) as f64; - assert!(mse < 25.0, "picture {t}: mean squared error {mse:.1}"); - } - - // And the same units as one stream, which is how a test that kept the - // encoder's output in a `Vec` decodes it back. - let whole: Vec = units.concat(); - let frames = Decoder::new().decode_stream(&whole).expect("decode stream"); - assert_eq!(frames.len(), units.len(), "one picture per access unit"); - } - - /// A frame whose geometry does not match the encoder is refused by name. - #[test] - fn geometry_mismatch_is_refused() { - let mut enc = Encoder::new(EncoderConfig::new(64, 64)).expect("encoder"); - let err = enc.try_encode(&frame(32, 32, 0)).unwrap_err(); - assert!(matches!(err, Error::Invalid(_)), "{err}"); - } -} diff --git a/shims/rusty_mp3/Cargo.toml b/shims/rusty_mp3/Cargo.toml deleted file mode 100644 index 7686902c..00000000 --- a/shims/rusty_mp3/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "rusty_mp3" -description = "Compatibility shim: the rusty_mp3 0.6.1 surface, implemented over ec-mp3." -version = "0.6.1" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] - -[dependencies] -ec-mp3 = { path = "../../crates/ec-mp3", version = "0.1.0" } -ec-core = { path = "../../crates/ec-core", version = "0.1.0" } diff --git a/shims/rusty_mp3/src/lib.rs b/shims/rusty_mp3/src/lib.rs deleted file mode 100644 index ab4a429a..00000000 --- a/shims/rusty_mp3/src/lib.rs +++ /dev/null @@ -1,217 +0,0 @@ -//! `rusty_mp3` 0.6.1's surface, over [`ec_mp3`]. -//! -//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the -//! incumbent's name and version so a consumer's `use rusty_mp3::…` compiles -//! unchanged. Only what edith consumes plus the streaming decoder beside it is -//! here — [`Mp3Encoder`] with [`Mp3EncoderConfig`], [`Mp3Decoder`] with -//! [`DecodedAudio`], and an [`Error`] carrying the incumbent's `Eof`/`Again` -//! contract — because a shim that grows a surface nobody calls is a second -//! implementation to keep honest. -//! -//! Behaviour difference from the incumbent, stated: the encoder writes the -//! `Xing`/`Info` header frame first, and `vbr_quality` runs true variable -//! bitrate — per-frame bitrate indices chosen to carry the coded granules -//! (see [`ec_mp3::encode::Mp3EncoderConfig`]). - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -use std::collections::VecDeque; -use std::fmt; - -/// The incumbent's error type. -#[derive(Debug)] -pub enum Error { - /// No more frames will arrive. - Eof, - /// Not enough data buffered yet; push more and retry. - Again, - /// The bitstream is malformed, or the configuration is not codable. - Format(String), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::Eof => write!(f, "end of stream"), - Error::Again => write!(f, "need more data"), - Error::Format(why) => write!(f, "mp3: {why}"), - } - } -} - -impl std::error::Error for Error {} - -impl From for Error { - fn from(error: ec_core::error::Error) -> Error { - match error { - ec_core::error::Error::Eof => Error::Eof, - ec_core::error::Error::NeedMore => Error::Again, - other => Error::Format(other.to_string()), - } - } -} - -/// The incumbent's result alias. -pub type Result = std::result::Result; - -/// One decoded frame of audio. -#[derive(Debug, Clone)] -pub struct DecodedAudio { - /// Sample rate in Hz. - pub sample_rate: u32, - /// Channel count. - pub channels: u16, - /// Interleaved samples in `[-1, 1]`. - pub samples: Vec, -} - -/// A streaming MP3 decoder. -#[derive(Debug, Default)] -pub struct Mp3Decoder { - reader: ec_mp3::Mp3Reader, - queue: VecDeque, - eof: bool, -} - -impl Mp3Decoder { - /// A decoder with nothing buffered. - pub fn new() -> Mp3Decoder { - Mp3Decoder::default() - } - - /// Buffers bytes and decodes whatever whole frames they complete. - pub fn push(&mut self, bytes: &[u8]) { - self.reader.push(bytes); - while let Ok(frame) = self.reader.next_frame() { - self.queue.push_back(DecodedAudio { - sample_rate: frame.sample_rate, - channels: frame.channels as u16, - samples: frame.samples, - }); - } - } - - /// The next decoded frame, [`Error::Again`] until one is complete and - /// [`Error::Eof`] once [`Mp3Decoder::flush`] has been called and drained. - pub fn next_frame(&mut self) -> Result { - match self.queue.pop_front() { - Some(frame) => Ok(frame), - None if self.eof => Err(Error::Eof), - None => Err(Error::Again), - } - } - - /// Marks the end of input. - pub fn flush(&mut self) { - self.eof = true; - } -} - -/// Encoder settings, field for field as the incumbent declares them. -#[derive(Debug, Clone, Default)] -pub struct Mp3EncoderConfig { - /// Constant bitrate in kbit/s. - pub bitrate_kbps: u32, - /// Quality on a normalised `[0, 1]` scale instead of a bitrate. - pub vbr_quality: Option, -} - -/// The incumbent's quality-to-bitrate curve, in kbit/s. -pub fn vbr_quality_index(q: f32) -> f32 { - ec_mp3::encode::bitrate_for_quality(q) as f32 -} - -/// A streaming MP3 encoder. -#[derive(Debug)] -pub struct Mp3Encoder { - inner: ec_mp3::Mp3Encoder, -} - -impl Mp3Encoder { - /// An encoder that configures itself from the first PCM it is given. - pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder { - Mp3Encoder { - inner: ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig { - bitrate_kbps: config.bitrate_kbps, - vbr_quality: config.vbr_quality, - }), - } - } - - /// Feeds interleaved `f32` samples. - pub fn push_pcm_f32( - &mut self, - interleaved: &[f32], - channels: u16, - sample_rate: u32, - ) -> Result<()> { - Ok(self - .inner - .push_pcm_f32(interleaved, channels, sample_rate)?) - } - - /// Feeds interleaved 16-bit samples. - pub fn push_pcm_s16( - &mut self, - interleaved: &[i16], - channels: u16, - sample_rate: u32, - ) -> Result<()> { - Ok(self - .inner - .push_pcm_s16(interleaved, channels, sample_rate)?) - } - - /// Ends the stream and flushes the tail. - pub fn finish(&mut self) { - self.inner.finish(); - } - - /// The next complete frame; [`Error::Eof`] once drained after - /// [`Mp3Encoder::finish`]. - pub fn next_packet(&mut self) -> Result> { - Ok(self.inner.next_packet()?) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The call shape edith uses, end to end: config in, frames out, and our - /// own decoder reads them back. - #[test] - fn encodes_and_decodes_through_the_incumbent_surface() { - let rate = 44100; - let pcm: Vec = (0..rate * 2 / 4) - .map(|i| ((i as f32 * 0.05).sin() * 8000.0) as i16) - .collect(); - let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { - bitrate_kbps: 192, - vbr_quality: None, - }); - encoder.push_pcm_s16(&pcm, 2, rate as u32).unwrap(); - encoder.finish(); - let mut bytes = Vec::new(); - while let Ok(frame) = encoder.next_packet() { - bytes.extend_from_slice(&frame); - } - assert!(bytes.len() > 1000, "wrote {} bytes", bytes.len()); - - let mut decoder = Mp3Decoder::new(); - decoder.push(&bytes); - decoder.flush(); - let mut frames = 0; - let mut samples = 0; - while let Ok(frame) = decoder.next_frame() { - assert_eq!(frame.sample_rate, rate as u32); - assert_eq!(frame.channels, 2); - frames += 1; - samples += frame.samples.len(); - } - assert!(frames > 5, "decoded {frames} frames"); - assert!(samples >= pcm.len() / 2, "decoded {samples} samples"); - assert!(matches!(decoder.next_frame(), Err(Error::Eof))); - } -} diff --git a/shims/rusty_vorbis/Cargo.toml b/shims/rusty_vorbis/Cargo.toml deleted file mode 100644 index 6da2458b..00000000 --- a/shims/rusty_vorbis/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "rusty_vorbis" -description = "Compatibility shim: the rusty_vorbis 0.1.1 surface edith consumes, served by ec-vorbis." -version = "0.1.1" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-core = { path = "../../crates/ec-core", version = "0.1.0" } -ec-vorbis = { path = "../../crates/ec-vorbis", version = "0.1.0" } - -[dev-dependencies] -ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" } diff --git a/shims/rusty_vorbis/src/lib.rs b/shims/rusty_vorbis/src/lib.rs deleted file mode 100644 index 0ff00ccf..00000000 --- a/shims/rusty_vorbis/src/lib.rs +++ /dev/null @@ -1,308 +0,0 @@ -//! Drop-in replacement for the `rusty_vorbis` 0.1.1 surface the replica -//! consumes, implemented over [`ec_vorbis`]. -//! -//! It carries the incumbent's package name and version so the swap is a -//! `[patch.crates-io]` entry and nothing else. The scope is the API -//! `engine/src/export.rs` calls (`export.rs:2850-2862`): -//! -//! ```no_run -//! let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig { -//! bitrate_bps: rusty_vorbis::BITRATE_NOMINAL, -//! quality: 0.85, -//! }); -//! encoder.push_pcm_s16(&[0i16; 2048], 2, 48_000).unwrap(); -//! encoder.finish(); -//! loop { -//! match encoder.next_packet() { -//! Ok(packet) => { let _ = (&packet.data, packet.pts, packet.duration); } -//! Err(rusty_vorbis::Error::Eof) => break, -//! Err(e) => panic!("{e}"), -//! } -//! } -//! ``` -//! -//! Two of the incumbent's behaviours are deliberately *not* reproduced, because -//! they are the defects this replacement exists to remove — both are corrections -//! the replica currently applies by hand at `export.rs:2762-2815` and can delete: -//! -//! * **No pre-roll hop.** The incumbent's first audio packet advanced the -//! granule by a full block hop while decoding to nothing, so every caller had -//! to feed a hop of silence and subtract a hop from every granule. Here the -//! first block is centred on input sample 0 and [`EncodedPacket::pts`] is the -//! true granule, so a caller writes what it is given. -//! * **No stereo-only setup header.** The incumbent shipped one embedded stereo -//! profile and refused mono ("bad coupling channels") and anything wider. Here -//! the setup header is written per stream for whatever channel count is -//! pushed, so mono stays mono and 5.1 stays 5.1. -//! -//! The last packet's `pts` is the input's own sample count, so a file decodes to -//! exactly as many samples as went in; the caller does not have to state the -//! tail granule itself either. - -#![forbid(unsafe_code)] -#![warn(missing_docs)] - -use ec_core::Error as EcError; -use ec_vorbis::{EncoderConfig, VorbisEncoder as EcEncoder}; - -/// Short block size, as a power of two, that this encoder states. -pub const BS0_LOG2: u8 = 11; -/// Long block size, as a power of two. -pub const BS1_LOG2: u8 = 11; -/// The nominal bitrate the replica asks for. -pub const BITRATE_NOMINAL: i32 = 128_000; - -/// Errors this encoder can answer. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Error { - /// Something is not implemented. - Unimplemented(String), - /// No further packet: the encoder is finished and drained. - Eof, - /// More input is needed before another packet exists. - Again, - /// The input or the state does not make sense. - InvalidData(String), - /// A legal request this encoder does not serve. - Unsupported(String), -} - -impl Error { - /// An [`Error::InvalidData`] with a message. - pub fn invalid(msg: impl Into) -> Self { - Error::InvalidData(msg.into()) - } - - /// An [`Error::Unsupported`] with a message. - pub fn unsupported(msg: impl Into) -> Self { - Error::Unsupported(msg.into()) - } -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Unimplemented(what) => write!(f, "not yet implemented: {what}"), - Error::Eof => write!(f, "end of stream"), - Error::Again => write!(f, "more input required"), - Error::InvalidData(msg) => write!(f, "invalid data: {msg}"), - Error::Unsupported(msg) => write!(f, "unsupported: {msg}"), - } - } -} - -impl std::error::Error for Error {} - -/// This crate's result type. -pub type Result = std::result::Result; - -fn map(error: EcError) -> Error { - match error { - EcError::Eof => Error::Eof, - EcError::NeedMore => Error::Again, - EcError::Unsupported { what, why } => Error::Unsupported(format!("{what} ({why})")), - other => Error::InvalidData(other.to_string()), - } -} - -/// One packet out of the encoder. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct EncodedPacket { - /// Packet payload, ready to page. - pub data: Vec, - /// Granule position this packet ends at: the number of input samples that - /// are decodable once it has been decoded. Zero for the three headers and - /// for the first audio packet, which decodes to no samples at all. - pub pts: i64, - /// Samples this packet finalises. - pub duration: i64, -} - -/// How the encoder is set up. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct VorbisEncoderConfig { - /// Target bitrate in bits per second. - pub bitrate_bps: i32, - /// Quality on `[0, 1]`. - pub quality: f32, -} - -impl Default for VorbisEncoderConfig { - fn default() -> VorbisEncoderConfig { - VorbisEncoderConfig { - bitrate_bps: BITRATE_NOMINAL, - quality: 0.5, - } - } -} - -/// The incumbent's `[0, 1]` quality scale from Vorbis's own `-q` scale. -pub fn quality01_from_vorbis_q(q: f64) -> f32 { - (((q + 1.0) / 11.0).clamp(0.0, 1.0)) as f32 -} - -/// Vorbis encoder over [`ec_vorbis`]. -/// -/// Channel count and sample rate arrive with the first push, exactly as they do -/// in the incumbent, so the encoder is built lazily and the setup header is -/// written for the layout that actually turns up. -pub struct VorbisEncoder { - config: VorbisEncoderConfig, - inner: Option, - /// Header packets not yet handed out. - headers: std::collections::VecDeque>, - finished: bool, -} - -impl VorbisEncoder { - /// A new encoder; nothing is written until the first push states a layout. - pub fn new(config: VorbisEncoderConfig) -> Self { - VorbisEncoder { - config, - inner: None, - headers: std::collections::VecDeque::new(), - finished: false, - } - } - - /// Change the quality; takes effect on the next stream. - pub fn set_quality(&mut self, quality: f32) { - self.config.quality = quality; - } - - /// Change the target bitrate; takes effect on the next stream. - pub fn set_bitrate_bps(&mut self, bps: i32) { - self.config.bitrate_bps = bps; - } - - /// The three header packets, once a push has stated the layout. - pub fn headers(&self) -> Vec> { - self.inner - .as_ref() - .map(|encoder| encoder.headers().into_iter().map(<[u8]>::to_vec).collect()) - .unwrap_or_default() - } - - /// The three headers Xiph-laced, the form a container carries them in. - pub fn extradata(&self) -> Vec { - self.inner - .as_ref() - .map(EcEncoder::extradata) - .unwrap_or_default() - } - - /// Push interleaved float samples. - pub fn push_pcm_f32( - &mut self, - interleaved: &[f32], - channels: u16, - sample_rate: u32, - ) -> Result<()> { - self.start(channels, sample_rate)?; - let encoder = self.inner.as_mut().expect("started"); - encoder.push_interleaved(interleaved).map_err(map) - } - - /// Push interleaved 16-bit samples, scaled by 1/32768 as every decoder in - /// this family scales them. - pub fn push_pcm_s16( - &mut self, - interleaved: &[i16], - channels: u16, - sample_rate: u32, - ) -> Result<()> { - let floats: Vec = interleaved - .iter() - .map(|&sample| f32::from(sample) / 32_768.0) - .collect(); - self.push_pcm_f32(&floats, channels, sample_rate) - } - - /// No more input; the tail is encoded and the last granule is the input's - /// own sample count. - pub fn finish(&mut self) { - self.finished = true; - if let Some(encoder) = self.inner.as_mut() { - encoder.finish(); - } - } - - /// Next packet: the three headers first, then audio, then [`Error::Eof`]. - pub fn next_packet(&mut self) -> Result { - if let Some(data) = self.headers.pop_front() { - return Ok(EncodedPacket { - data, - pts: 0, - duration: 0, - }); - } - let Some(encoder) = self.inner.as_mut() else { - return Err(match self.finished { - true => Error::Eof, - false => Error::Again, - }); - }; - let packet = encoder.next_packet().map_err(map)?; - Ok(EncodedPacket { - data: packet.data, - pts: packet.granule, - duration: packet.samples, - }) - } - - /// Build the encoder on the first push and queue its headers. - fn start(&mut self, channels: u16, sample_rate: u32) -> Result<()> { - if self.inner.is_some() { - return Ok(()); - } - if self.finished { - return Err(Error::invalid("push after finish")); - } - let encoder = EcEncoder::new(EncoderConfig { - sample_rate, - channels, - bitrate_bps: self.config.bitrate_bps, - quality: self.config.quality, - }) - .map_err(map)?; - self.headers = encoder.headers().into_iter().map(<[u8]>::to_vec).collect(); - self.inner = Some(encoder); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_incumbents_call_sequence_yields_headers_then_audio() { - let mut encoder = VorbisEncoder::new(VorbisEncoderConfig { - bitrate_bps: BITRATE_NOMINAL, - quality: 0.85, - }); - // Mono, which the incumbent refused outright. - let pcm: Vec = (0..8_000) - .map(|i| ((f64::from(i) * 0.05).sin() * 12_000.0) as i16) - .collect(); - encoder.push_pcm_s16(&pcm, 1, 48_000).unwrap(); - encoder.finish(); - let mut packets = Vec::new(); - loop { - match encoder.next_packet() { - Ok(packet) => packets.push(packet), - Err(Error::Eof) => break, - Err(e) => panic!("{e}"), - } - } - assert!(packets.len() > 4, "{} packets", packets.len()); - assert_eq!(packets[0].data[0], 1, "identification header first"); - assert_eq!(packets[1].data[0], 3, "comment header second"); - assert_eq!(packets[2].data[0], 5, "setup header third"); - // No pre-roll: the first audio packet ends at granule zero, and the - // last states the input's own length. - assert_eq!(packets[3].pts, 0); - assert_eq!(packets.last().unwrap().pts, 8_000); - assert_eq!(quality01_from_vorbis_q(-1.0), 0.0); - } -} diff --git a/shims/rusty_vorbis/tests/edith_surface.rs b/shims/rusty_vorbis/tests/edith_surface.rs deleted file mode 100644 index dda4b081..00000000 --- a/shims/rusty_vorbis/tests/edith_surface.rs +++ /dev/null @@ -1,172 +0,0 @@ -//! The replica's `write_ogg` (`export.rs:2895-2985`) with both of its -//! corrections deleted, run end to end. -//! -//! That deletion *is* the test: no hop of silence in front of the mix, no hop -//! subtracted from every granule, no hand-written tail granule, and a mono mix -//! written as mono rather than widened to dual mono. What comes out has to -//! decode in ffmpeg without a word of complaint and be exactly as long as the -//! timeline it came from — which is the promise the replica makes for every -//! other audio format. - -use std::fs::File; -use std::path::{Path, PathBuf}; -use std::process::Command; - -use ec_core::{ - AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, Packet, - StreamInfo, TimeBase, -}; - -fn scratch(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("rusty-vorbis-shim-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir.join(name) -} - -/// The replica's own mix, as 16-bit samples: a tone per channel so a channel -/// that came out of the wrong hole is visible rather than subtle. -fn mix(channels: u16, rate: u32, frames: usize) -> Vec { - let mut samples = Vec::with_capacity(frames * usize::from(channels)); - for i in 0..frames { - for channel in 0..channels { - let hz = 220.0 * f64::from(channel + 1); - let t = i as f64 / f64::from(rate); - let value = (2.0 * std::f64::consts::PI * hz * t).sin() * 0.6; - samples.push((value * f64::from(i16::MAX)) as i16); - } - } - samples -} - -/// `write_ogg`, shorn of the workarounds. -fn write_ogg(out: &Path, samples: &[i16], channels: u16, rate: u32) { - let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig { - bitrate_bps: rusty_vorbis::BITRATE_NOMINAL, - quality: 0.85, - }); - encoder - .push_pcm_s16(samples, channels, rate) - .expect("vorbis encode"); - encoder.finish(); - let mut packets = Vec::new(); - loop { - match encoder.next_packet() { - Ok(packet) => packets.push(packet), - Err(rusty_vorbis::Error::Eof) => break, - Err(e) => panic!("vorbis encode: {e}"), - } - } - assert!( - packets.len() >= 4, - "{} packets is not a stream", - packets.len() - ); - - let extradata = ec_ogg::xiph_lace(&[ - &packets[0].data[..], - &packets[1].data[..], - &packets[2].data[..], - ]) - .expect("the three headers lace"); - - let time_base = TimeBase::new(1, i64::from(rate)); - let mut params = CodecParameters::new(CodecId::Vorbis); - params.media = MediaParameters::Audio(AudioParameters { - sample_rate: rate, - layout: ChannelLayout::from_count(usize::from(channels)), - format: None, - bits_per_sample: None, - }); - params.extradata = Some(Buf::from_vec(extradata)); - let mut muxer = ec_ogg::OggMuxer::new(File::create(out).expect("create")); - muxer - .add_stream(StreamInfo::new(0, time_base, params)) - .expect("stream"); - muxer.write_headers().expect("headers"); - for packet in &packets[3..] { - // The granule the encoder states, written through: no hop subtracted, - // and no special case for the last packet. - let mut out = Packet::new(0, time_base, packet.data.clone()); - out.side_data.push(ec_ogg::granule_side_data(packet.pts)); - out.duration = Some(packet.duration); - muxer.write_packet(&out).expect("packet"); - } - muxer.finish().expect("trailer"); -} - -fn probe(path: &Path, field: &str) -> String { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - &format!("stream={field}"), - "-of", - "default=noprint_wrappers=1:nokey=1", - ]) - .arg(path) - .output() - .expect("ffprobe"); - String::from_utf8_lossy(&out.stdout).trim().to_string() -} - -#[test] -fn writes_an_ogg_44100_mono_widened_to_stereo() { - let path = scratch("write-ogg-44100-widened.ogg"); - let rate = 44_100u32; - let frames = 44_100usize; - let mono = mix(1, rate, frames); - let widened: Vec = mono.iter().flat_map(|&s| [s, s]).collect(); - write_ogg(&path, &widened, 2, rate); - let decode = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(&path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - assert!(decode.stderr.is_empty(), "ffmpeg said {}", String::from_utf8_lossy(&decode.stderr)); - println!("duration_ts={}", probe(&path, "duration_ts")); - let decoded = decode.stdout.len() / 4 / 2; - assert_eq!(decoded, frames, "decoded sample count"); -} - -#[test] -fn writes_an_ogg_the_way_the_replica_would_without_its_corrections() { - let rate = 48_000u32; - // Deliberately not a whole number of blocks: the grid has to close over it - // and the granule has to trim the overshoot back off. - let frames = 33_333usize; - for channels in [1u16, 2, 6] { - let path = scratch(&format!("write-ogg-{channels}ch.ogg")); - write_ogg(&path, &mix(channels, rate, frames), channels, rate); - - // ffmpeg decodes it silently... - let decode = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(&path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - assert!( - decode.stderr.is_empty(), - "{channels} ch: ffmpeg said {}", - String::from_utf8_lossy(&decode.stderr) - ); - // ...for exactly the timeline's own length... - assert_eq!( - probe(&path, "duration_ts"), - frames.to_string(), - "{channels} ch: duration" - ); - // ...at the channel count that was pushed, mono included. - assert_eq!( - probe(&path, "channels"), - channels.to_string(), - "{channels} ch: channel count" - ); - let decoded = decode.stdout.len() / 4 / usize::from(channels); - assert_eq!(decoded, frames, "{channels} ch: decoded sample count"); - } -} diff --git a/shims/symphonia-codec-aac/Cargo.toml b/shims/symphonia-codec-aac/Cargo.toml deleted file mode 100644 index c9a815c1..00000000 --- a/shims/symphonia-codec-aac/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "symphonia-codec-aac" -description = "Compatibility shim: the symphonia-codec-aac 0.6 surface edith consumes, served by ec-aac." -version = "0.6.0" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-aac = { path = "../../crates/ec-aac", version = "0.1.0" } -symphonia-core = { path = "../symphonia-core", version = "0.6.0" } diff --git a/shims/symphonia-codec-aac/src/lib.rs b/shims/symphonia-codec-aac/src/lib.rs deleted file mode 100644 index ae6c58e6..00000000 --- a/shims/symphonia-codec-aac/src/lib.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Compatibility shim: the `symphonia-codec-aac` 0.6 surface edith consumes, -//! served by [`ec_aac`]. -//! -//! One difference from the incumbent, and it is the reason this exists: -//! **multichannel decodes**. The incumbent refuses anything wider than stereo -//! outright (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 -//! and 7.1 tracks of a film — edith routes those to a second AAC crate to get -//! around it. [`ec_aac`] decodes mono through 7.1 in film channel order, so -//! there is nothing to route around. -//! -//! Written from the signatures edith calls (`AacDecoder::try_new`, then the -//! `AudioDecoder` trait) and the crate's published documentation; no symphonia -//! source was read. - -#![forbid(unsafe_code)] - -use symphonia_core::codecs::audio::{ - AudioCodecParameters, AudioDecoder, AudioDecoderOptions, GenericAudioBufferRef, - well_known::CODEC_ID_AAC, -}; -use symphonia_core::packet::Packet; -use symphonia_core::{Error, Result}; - -/// An AAC-LC decoder for one track. -pub struct AacDecoder { - inner: ec_aac::AacDecoder, - params: AudioCodecParameters, - out: Vec, - channels: usize, -} - -impl AacDecoder { - /// A decoder for the track `params` describes. - /// - /// The `extra_data` is the `AudioSpecificConfig`; a track with none (raw - /// ADTS, which states its configuration in every frame) is accepted and - /// configures itself from the first frame. - pub fn try_new( - params: &AudioCodecParameters, - _options: &AudioDecoderOptions, - ) -> Result { - if params.codec != CODEC_ID_AAC { - return Err(Error::Unsupported(format!( - "codec id {} is not AAC", - params.codec.0 - ))); - } - let inner = match params.extra_data.as_deref() { - Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?, - None => ec_aac::AacDecoder::new(), - }; - let channels = params.channels.map_or(2, |c| c.count()).max(1) as usize; - Ok(AacDecoder { - inner, - params: params.clone(), - out: Vec::new(), - channels, - }) - } -} - -impl AudioDecoder for AacDecoder { - fn decode(&mut self, packet: &Packet) -> Result> { - let audio = self.inner.decode(&packet.data, Some(packet.pts.value()))?; - self.channels = usize::from(audio.channels).max(1); - self.out.clear(); - self.out.extend_from_slice(&audio.samples); - Ok(GenericAudioBufferRef::new(&self.out, self.channels)) - } - - fn codec_params(&self) -> &AudioCodecParameters { - &self.params - } - - fn reset(&mut self) { - self.inner = match self.params.extra_data.as_deref() { - Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc).unwrap_or_default(), - None => ec_aac::AacDecoder::new(), - }; - } -} diff --git a/shims/symphonia-core/Cargo.toml b/shims/symphonia-core/Cargo.toml deleted file mode 100644 index 31a340e3..00000000 --- a/shims/symphonia-core/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "symphonia-core" -description = "Compatibility shim: the symphonia-core 0.6 surface edith consumes, over ec-core." -version = "0.6.0" -edition = "2024" -license = "MIT OR Apache-2.0" -authors = ["Ahmet Kaan Gümüş"] -publish = false - -[dependencies] -ec-core = { path = "../../crates/ec-core", version = "0.1.0" } diff --git a/shims/symphonia-core/src/codecs.rs b/shims/symphonia-core/src/codecs.rs deleted file mode 100644 index a1a886a7..00000000 --- a/shims/symphonia-core/src/codecs.rs +++ /dev/null @@ -1,373 +0,0 @@ -//! Codec identities, stream parameters and the decoder trait. - -use crate::Result; -use crate::packet::Packet; - -/// Per-media-type parameters, as a track carries them. -#[derive(Debug, Clone, PartialEq)] -pub enum CodecParameters { - /// An audio track. - Audio(audio::AudioCodecParameters), - /// A video track. Nothing in this family decodes picture through the - /// symphonia surface, so it carries only what a listing needs. - Video(VideoCodecParameters), - /// A subtitle track. - Subtitle(SubtitleCodecParameters), -} - -/// What a video track states about itself. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct VideoCodecParameters { - /// Codec identity, in this shim's own numbering. - pub codec: u32, - /// Coded width. - pub width: Option, - /// Coded height. - pub height: Option, -} - -/// What a subtitle track states about itself. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct SubtitleCodecParameters { - /// Codec identity, in this shim's own numbering. - pub codec: u32, - /// Setup bytes (the ASS header, for instance). - pub extra_data: Option>, -} - -/// A codec's name, as a registry reports it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CodecInfo { - /// Short lowercase name, e.g. `"aac"`. - pub short_name: &'static str, - /// Human-readable name. - pub long_name: &'static str, -} - -/// One entry of a codec registry. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct CodecDescriptor { - /// The identity this entry serves. - pub id: audio::AudioCodecId, - /// Its names. - pub info: CodecInfo, -} - -/// A registry's answer for one audio codec. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct AudioDecoderRegistration { - /// The codec this registration decodes. - pub codec: CodecDescriptor, -} - -/// Audio codecs, parameters and decoders. -pub mod audio { - use super::*; - - /// A codec identity. The numbering is this shim's own; only equality - /// against the [`well_known`] constants is meaningful. - #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] - pub struct AudioCodecId(pub u32); - - /// The identities edith names. - pub mod well_known { - use super::AudioCodecId; - - /// MPEG-4 AAC. - pub const CODEC_ID_AAC: AudioCodecId = AudioCodecId(0x1000); - /// Xiph Opus. - pub const CODEC_ID_OPUS: AudioCodecId = AudioCodecId(0x1001); - /// Xiph Vorbis. - pub const CODEC_ID_VORBIS: AudioCodecId = AudioCodecId(0x1002); - /// Xiph FLAC. - pub const CODEC_ID_FLAC: AudioCodecId = AudioCodecId(0x1003); - /// MPEG-1/2 Layer III. - pub const CODEC_ID_MP3: AudioCodecId = AudioCodecId(0x1004); - /// ALAC. - pub const CODEC_ID_ALAC: AudioCodecId = AudioCodecId(0x1005); - /// Dolby AC-3. - pub const CODEC_ID_AC3: AudioCodecId = AudioCodecId(0x1006); - /// Dolby Digital Plus. - pub const CODEC_ID_EAC3: AudioCodecId = AudioCodecId(0x1007); - /// Dolby TrueHD. No decoder is registered for it, which is how a - /// caller learns the track cannot be played. - pub const CODEC_ID_TRUEHD: AudioCodecId = AudioCodecId(0x1008); - /// DTS and its extensions. No decoder is registered for it either. - pub const CODEC_ID_DTS: AudioCodecId = AudioCodecId(0x1009); - /// Unsigned 8-bit PCM. - pub const CODEC_ID_PCM_U8: AudioCodecId = AudioCodecId(0x1010); - /// Signed 16-bit little-endian PCM. - pub const CODEC_ID_PCM_S16LE: AudioCodecId = AudioCodecId(0x1011); - /// Signed 16-bit big-endian PCM. - pub const CODEC_ID_PCM_S16BE: AudioCodecId = AudioCodecId(0x1012); - /// Signed 24-bit little-endian PCM. - pub const CODEC_ID_PCM_S24LE: AudioCodecId = AudioCodecId(0x1013); - /// Signed 32-bit little-endian PCM. - pub const CODEC_ID_PCM_S32LE: AudioCodecId = AudioCodecId(0x1014); - /// 32-bit float little-endian PCM. - pub const CODEC_ID_PCM_F32LE: AudioCodecId = AudioCodecId(0x1015); - /// Anything with no identity of its own here. - pub const CODEC_ID_NULL: AudioCodecId = AudioCodecId(0); - } - - /// A channel layout, as far as anything here asks: how many there are. - #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] - pub struct Channels(pub u32); - - impl Channels { - /// Channels in the layout. - pub fn count(&self) -> u32 { - self.0 - } - } - - /// Everything an audio decoder needs before its first packet. - #[derive(Debug, Clone, Default, PartialEq)] - pub struct AudioCodecParameters { - /// Which codec. - pub codec: AudioCodecId, - /// Sample rate in Hz. - pub sample_rate: Option, - /// Channel layout. - pub channels: Option, - /// Coded bit depth, when the container states one. - pub bits_per_sample: Option, - /// Codec setup bytes: the AudioSpecificConfig, `OpusHead`, STREAMINFO. - pub extra_data: Option>, - } - - impl AudioCodecParameters { - /// Empty parameters, filled in by the `with_*` builders. - pub fn new() -> AudioCodecParameters { - AudioCodecParameters::default() - } - - /// Name the codec. - pub fn for_codec(&mut self, codec: AudioCodecId) -> &mut AudioCodecParameters { - self.codec = codec; - self - } - - /// State the sample rate. - pub fn with_sample_rate(&mut self, rate: u32) -> &mut AudioCodecParameters { - self.sample_rate = Some(rate); - self - } - - /// State the channel layout. - pub fn with_channels(&mut self, channels: Channels) -> &mut AudioCodecParameters { - self.channels = Some(channels); - self - } - - /// State the bit depth. - pub fn with_bits_per_sample(&mut self, bits: u32) -> &mut AudioCodecParameters { - self.bits_per_sample = Some(bits); - self - } - - /// State the codec setup bytes. - pub fn with_extra_data(&mut self, data: Box<[u8]>) -> &mut AudioCodecParameters { - self.extra_data = Some(data); - self - } - } - - /// Options a decoder is built with. Nothing here has any, which is what - /// `Default` means for it. - #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] - pub struct AudioDecoderOptions { - /// Verify the decoded audio against a checksum where the format has - /// one. Not implemented by any decoder in this family. - pub verify: bool, - } - - /// A decoded block, borrowed from the decoder until its next call. - #[derive(Debug, Clone, Copy)] - pub struct GenericAudioBufferRef<'a> { - samples: &'a [f32], - channels: usize, - } - - impl<'a> GenericAudioBufferRef<'a> { - /// Wrap interleaved samples. - pub fn new(samples: &'a [f32], channels: usize) -> GenericAudioBufferRef<'a> { - GenericAudioBufferRef { samples, channels } - } - - /// Channels in the block. - pub fn spec_channels(&self) -> usize { - self.channels - } - - /// Sample frames in the block. - pub fn frames(&self) -> usize { - match self.channels { - 0 => 0, - n => self.samples.len() / n, - } - } - - /// Copy the block into `out`, interleaved, replacing what was there. - pub fn copy_to_vec_interleaved(&self, out: &mut Vec) { - out.clear(); - out.extend(self.samples.iter().map(|&s| S::from_sample(s))); - } - } - - /// A sample type [`GenericAudioBufferRef::copy_to_vec_interleaved`] can - /// convert to. - pub trait FromSample { - /// Convert one normalised `f32` sample. - fn from_sample(s: f32) -> Self; - } - - impl FromSample for f32 { - fn from_sample(s: f32) -> f32 { - s - } - } - - impl FromSample for i16 { - fn from_sample(s: f32) -> i16 { - (s.clamp(-1.0, 1.0) * 32767.0) as i16 - } - } - - impl FromSample for i32 { - fn from_sample(s: f32) -> i32 { - (f64::from(s.clamp(-1.0, 1.0)) * 2147483647.0) as i32 - } - } - - /// A decoder: packets in, one block out per packet. - pub trait AudioDecoder: Send { - /// Decode one packet. - fn decode(&mut self, packet: &Packet) -> Result>; - - /// The parameters this decoder was built with. - fn codec_params(&self) -> &AudioCodecParameters; - - /// Drop state left over from before a seek. - fn reset(&mut self); - } -} - -impl CodecParameters { - /// The audio half, when this is an audio track. - pub fn audio(&self) -> Option<&audio::AudioCodecParameters> { - match self { - CodecParameters::Audio(p) => Some(p), - _ => None, - } - } -} - -/// The identity a family [`ec_core::CodecId`] answers to here. -pub fn audio_codec_id(codec: ec_core::CodecId) -> audio::AudioCodecId { - use audio::well_known::*; - use ec_core::CodecId; - match codec { - CodecId::Aac => CODEC_ID_AAC, - CodecId::Opus => CODEC_ID_OPUS, - CodecId::Vorbis => CODEC_ID_VORBIS, - CodecId::Flac => CODEC_ID_FLAC, - CodecId::Mp3 => CODEC_ID_MP3, - CodecId::Alac => CODEC_ID_ALAC, - CodecId::Ac3 => CODEC_ID_AC3, - CodecId::EAc3 => CODEC_ID_EAC3, - CodecId::TrueHd => CODEC_ID_TRUEHD, - CodecId::Dts => CODEC_ID_DTS, - // Each PCM width keeps its own identity: mapping them all to one and - // back would decode a 24-bit WAVE as 16-bit. - CodecId::PcmU8 => CODEC_ID_PCM_U8, - CodecId::PcmS16Le => CODEC_ID_PCM_S16LE, - CodecId::PcmS16Be => CODEC_ID_PCM_S16BE, - CodecId::PcmS24Le => CODEC_ID_PCM_S24LE, - CodecId::PcmS32Le => CODEC_ID_PCM_S32LE, - CodecId::PcmF32Le => CODEC_ID_PCM_F32LE, - _ => CODEC_ID_NULL, - } -} - -/// The family codec an identity names, or [`None`] for one nothing here -/// decodes. -pub fn ec_codec_id(id: audio::AudioCodecId) -> Option { - use audio::well_known::*; - use ec_core::CodecId; - Some(match id { - CODEC_ID_AAC => CodecId::Aac, - CODEC_ID_OPUS => CodecId::Opus, - CODEC_ID_VORBIS => CodecId::Vorbis, - CODEC_ID_FLAC => CodecId::Flac, - CODEC_ID_MP3 => CodecId::Mp3, - CODEC_ID_ALAC => CodecId::Alac, - CODEC_ID_AC3 => CodecId::Ac3, - CODEC_ID_EAC3 => CodecId::EAc3, - CODEC_ID_TRUEHD => CodecId::TrueHd, - CODEC_ID_DTS => CodecId::Dts, - CODEC_ID_PCM_U8 => CodecId::PcmU8, - CODEC_ID_PCM_S16LE => CodecId::PcmS16Le, - CODEC_ID_PCM_S16BE => CodecId::PcmS16Be, - CODEC_ID_PCM_S24LE => CodecId::PcmS24Le, - CODEC_ID_PCM_S32LE => CodecId::PcmS32Le, - CODEC_ID_PCM_F32LE => CodecId::PcmF32Le, - _ => return None, - }) -} - -/// Family parameters for what a track states, for handing to a family decoder. -pub fn ec_parameters( - params: &audio::AudioCodecParameters, -) -> crate::Result { - let codec = ec_codec_id(params.codec).ok_or_else(|| { - crate::Error::Unsupported(format!("no decoder for codec id {}", params.codec.0)) - })?; - let mut out = ec_core::CodecParameters::new(codec); - out.extradata = params - .extra_data - .as_deref() - .map(ec_core::packet::Buf::copy_from_slice); - out.media = ec_core::registry::MediaParameters::Audio(ec_core::registry::AudioParameters { - sample_rate: params.sample_rate.unwrap_or(48_000), - layout: ec_core::ChannelLayout::from_count( - params.channels.map_or(2, |c| c.count()).max(1) as usize - ), - format: None, - bits_per_sample: params.bits_per_sample, - }); - Ok(out) -} - -/// What a track states, from the family's own description of it. -pub fn from_ec_parameters(params: &ec_core::CodecParameters) -> CodecParameters { - match params.audio() { - Some(audio) => { - let mut out = audio::AudioCodecParameters::new(); - out.for_codec(audio_codec_id(params.codec)) - .with_sample_rate(audio.sample_rate) - .with_channels(audio::Channels(audio.layout.channel_count() as u32)); - if let Some(bits) = audio.bits_per_sample { - out.with_bits_per_sample(bits); - } - if let Some(extra) = ¶ms.extradata { - out.with_extra_data(extra.as_ref().to_vec().into_boxed_slice()); - } - CodecParameters::Audio(out) - } - None => match params.video() { - Some(video) => CodecParameters::Video(VideoCodecParameters { - codec: audio_codec_id(params.codec).0, - width: Some(video.width as u16), - height: Some(video.height as u16), - }), - None => CodecParameters::Subtitle(SubtitleCodecParameters { - codec: audio_codec_id(params.codec).0, - extra_data: params - .extradata - .as_ref() - .map(|b| b.as_ref().to_vec().into_boxed_slice()), - }), - }, - } -} diff --git a/shims/symphonia-core/src/formats.rs b/shims/symphonia-core/src/formats.rs deleted file mode 100644 index aaf841ec..00000000 --- a/shims/symphonia-core/src/formats.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! Tracks, the reader trait, and seeking. - -use crate::Result; -use crate::codecs::CodecParameters; -use crate::packet::Packet; -use crate::units::{Time, TimeBase, Timestamp}; - -/// What kind of stream a track carries. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum TrackType { - /// Sound. - Audio, - /// Pictures. - Video, - /// Timed text or bitmaps. - Subtitle, -} - -/// One track of a container. -#[derive(Debug, Clone, PartialEq)] -pub struct Track { - /// The container's own id for the track — a Matroska `TrackNumber`, which - /// is what names one language of a dual-audio file. - pub id: u32, - /// Which kind of stream it is. - pub track_type: TrackType, - /// Base of this track's timestamps. - pub time_base: Option, - /// Sample frames the track holds, when the container states one. - pub num_frames: Option, - /// First timestamp. - pub start_ts: u64, - /// Samples the decoder emits before the first audible one -- an MP3's gapless - /// encoder delay, an Opus stream's pre-skip. **Not** dropped by the reader: - /// [`num_frames`](Self::num_frames) counts them, so a caller that wants the - /// audible stream skips them and takes `num_frames - delay` samples. - pub delay: Option, - /// Codec and setup data. - pub codec_params: Option, - /// ISO 639 language tag, when the container carries one. - pub language: Option, -} - -/// Options a reader is built with; nothing here has any. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct FormatOptions { - /// Build a seek index even when the container carries none. - pub enable_gapless: bool, -} - -/// How exactly a seek must land. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum SeekMode { - /// The nearest random access point at or before the target, from which a - /// decoder reaches the target exactly by decoding forward. - #[default] - Accurate, - /// Whatever is cheapest. - Coarse, -} - -/// Where to seek to. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum SeekTo { - /// An instant, on `track_id` or on the default track. - Time { - /// The instant. - time: Time, - /// Which track's timeline it is on. - track_id: Option, - }, - /// A timestamp in a track's own base. - TimeStamp { - /// The timestamp. - ts: Timestamp, - /// Which track it belongs to. - track_id: u32, - }, -} - -/// Where a seek actually landed. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct SeekedTo { - /// Track the landing is on. - pub track_id: u32, - /// What was asked for. - pub required_ts: Timestamp, - /// What was reached — at or before `required_ts` in [`SeekMode::Accurate`]. - pub actual_ts: Timestamp, -} - -/// A container reader. -pub trait FormatReader: Send { - /// Every track the container declares. - fn tracks(&self) -> &[Track]; - - /// The first track of `kind`. - fn default_track(&self, kind: TrackType) -> Option<&Track>; - - /// Seek, answering where it landed. - fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result; - - /// The next packet, or `Ok(None)` at the end of the stream. - fn next_packet(&mut self) -> Result>; -} - -/// Format hints from outside the bytes. -pub mod probe { - /// What the caller knows that the content does not say: a file extension, - /// a MIME type. Advisory — every reader in this family sniffs the content - /// first and is free to disagree. - #[derive(Debug, Clone, Default, PartialEq, Eq)] - pub struct Hint { - extension: Option, - mime_type: Option, - } - - impl Hint { - /// A hint that says nothing. - pub fn new() -> Hint { - Hint::default() - } - - /// Name the file extension, without its dot. - pub fn with_extension(&mut self, extension: &str) -> &mut Hint { - self.extension = Some(extension.to_string()); - self - } - - /// Name the MIME type. - pub fn mime_type(&mut self, mime: &str) -> &mut Hint { - self.mime_type = Some(mime.to_string()); - self - } - - /// The extension, if one was given. - pub fn extension(&self) -> Option<&str> { - self.extension.as_deref() - } - } -} diff --git a/shims/symphonia-core/src/io.rs b/shims/symphonia-core/src/io.rs deleted file mode 100644 index 129081fc..00000000 --- a/shims/symphonia-core/src/io.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! The source a reader reads from. - -use std::io::{Read, Seek}; - -/// Anything a reader can be built over: seekable, readable, and movable to the -/// thread that will do the reading. -pub trait MediaSource: Read + Seek + Send {} - -impl MediaSource for T {} - -/// Options a stream is built with; nothing here has any. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct MediaSourceStreamOptions { - /// Buffer size a caller would like. This shim buffers in the demuxers - /// themselves, so it is advisory. - pub buffer_len: usize, -} - -/// A source with a buffer in front of it. -pub struct MediaSourceStream { - inner: Box, -} - -impl MediaSourceStream { - /// Wrap a source. - pub fn new( - source: Box, - _options: MediaSourceStreamOptions, - ) -> MediaSourceStream { - MediaSourceStream { inner: source } - } - - /// Take the source back out, which is how a reader in this family is - /// handed the file it will read. - pub fn into_inner(self) -> Box { - self.inner - } -} - -impl Read for MediaSourceStream { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - self.inner.read(buf) - } -} - -impl Seek for MediaSourceStream { - fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { - self.inner.seek(pos) - } -} diff --git a/shims/symphonia-core/src/lib.rs b/shims/symphonia-core/src/lib.rs deleted file mode 100644 index 825daab8..00000000 --- a/shims/symphonia-core/src/lib.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Compatibility shim: the `symphonia-core` 0.6 surface edith consumes, over -//! [`ec_core`] and (through the `symphonia` shim) [`ec_probe`]. -//! -//! This is the vocabulary half — parameters, packets, units, the reader and -//! decoder traits. The registries that build them live in the `symphonia` -//! shim, and the AAC decoder seat in `symphonia-codec-aac`, exactly as the -//! incumbent splits them. -//! -//! Written from the signatures edith calls (`crates/engine/src/audio.rs` -//! lines 36-53 and their call sites) and the crate's published documentation. -//! No symphonia source was read: the incumbent is MPL-2.0 and this family is -//! MIT OR Apache-2.0. -//! -//! **Not the whole crate.** What edith does not call is not here: metadata -//! revisions, the sample-buffer zoo, `Signal`/`AudioBuffer` generics, the -//! `CodecRegistry` builder API. Each is a small addition when something needs -//! it; none is a silent omission. - -#![forbid(unsafe_code)] - -pub mod codecs; -pub mod formats; -pub mod io; -pub mod meta; -pub mod packet; -pub mod units; - -use std::fmt; - -/// The incumbent's error type, in the shape callers match on. -#[derive(Debug)] -pub enum Error { - /// Underlying I/O failure. - IoError(std::io::Error), - /// The bitstream is malformed. - DecodeError(String), - /// A capability this build does not have, naming what and why. - Unsupported(String), - /// A seek that could not be served. - SeekError(String), - /// End of stream. - ResetRequired, -} - -/// `Result` with this crate's [`Error`]. -pub type Result = std::result::Result; - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::IoError(e) => write!(f, "io error: {e}"), - Error::DecodeError(e) => write!(f, "decode error: {e}"), - Error::Unsupported(e) => write!(f, "unsupported: {e}"), - Error::SeekError(e) => write!(f, "seek error: {e}"), - Error::ResetRequired => write!(f, "decoder reset required"), - } - } -} - -impl std::error::Error for Error {} - -impl From for Error { - fn from(e: std::io::Error) -> Error { - Error::IoError(e) - } -} - -impl From for Error { - fn from(e: ec_core::Error) -> Error { - match e { - ec_core::Error::Io(io) => Error::IoError(io), - ec_core::Error::Eof | ec_core::Error::NeedMore => Error::ResetRequired, - ec_core::Error::Unsupported { .. } => Error::Unsupported(e.to_string()), - ec_core::Error::Corrupt { .. } => Error::DecodeError(e.to_string()), - } - } -} diff --git a/shims/symphonia-core/src/meta.rs b/shims/symphonia-core/src/meta.rs deleted file mode 100644 index d1b4be09..00000000 --- a/shims/symphonia-core/src/meta.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! Metadata options. -//! -//! edith passes `MetadataOptions::default()` and never reads a revision back, -//! so the tags a file carries are read by `ec_probe::Tags` and surfaced there -//! rather than through this type. - -/// Options metadata is read with. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct MetadataOptions { - /// Read cover art as well as text. Nothing here does. - pub read_visuals: bool, -} diff --git a/shims/symphonia-core/src/packet.rs b/shims/symphonia-core/src/packet.rs deleted file mode 100644 index c15f4ca3..00000000 --- a/shims/symphonia-core/src/packet.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! One packet of coded bytes. - -use crate::units::{Duration, Timestamp}; - -/// A packet as a reader hands it out. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Packet { - /// Track this packet belongs to. - pub track_id: u32, - /// Presentation timestamp, in the track's own time base. - pub pts: Timestamp, - /// How long it plays for. - pub dur: Duration, - /// The coded bytes. - pub data: Box<[u8]>, - /// The container's own end-of-packet position, in the track's time base, - /// when it states one — an Ogg page's granule above all, which is the - /// only way a Vorbis (or FLAC-in-Ogg) stream's true, un-rounded length - /// ever reaches the decoder: the codec's own bitstream never states it. - pub granule: Option, -} - -impl Packet { - /// A packet over `data`. - pub fn new(track_id: u32, pts: Timestamp, dur: Duration, data: &[u8]) -> Packet { - Packet { - track_id, - pts, - dur, - data: data.to_vec().into_boxed_slice(), - granule: None, - } - } - - /// The presentation timestamp. - pub fn pts(&self) -> Timestamp { - self.pts - } - - /// The coded bytes. - pub fn buf(&self) -> &[u8] { - &self.data - } -} diff --git a/shims/symphonia-core/src/units.rs b/shims/symphonia-core/src/units.rs deleted file mode 100644 index 8e75b14e..00000000 --- a/shims/symphonia-core/src/units.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! Time, timestamps and the rational base between them. - -/// A media timestamp, in [`TimeBase`] ticks. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)] -pub struct Timestamp(pub i64); - -impl Timestamp { - /// A timestamp of `ticks`. - pub fn new(ticks: i64) -> Timestamp { - Timestamp(ticks) - } - - /// The tick count. - pub fn value(&self) -> i64 { - self.0 - } -} - -/// A duration in [`TimeBase`] ticks. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)] -pub struct Duration(pub u64); - -impl Duration { - /// A duration of `ticks`. - pub fn new(ticks: u64) -> Duration { - Duration(ticks) - } - - /// The tick count. - pub fn value(&self) -> u64 { - self.0 - } -} - -/// Wall-clock time, split so that no fraction is lost to a float. -#[derive(Debug, Clone, Copy, PartialEq, Default)] -pub struct Time { - /// Whole seconds. - pub seconds: u64, - /// Fraction of a second, 0.0..1.0. - pub frac: f64, -} - -impl Time { - /// A time from whole seconds and a fraction. - pub fn new(seconds: u64, frac: f64) -> Time { - Time { seconds, frac } - } - - /// A time from seconds, or [`None`] for a negative or non-finite input — - /// which is what makes a caller check before seeking to it. - pub fn try_from_secs_f64(secs: f64) -> Option