forge
Explore
Log in

Don't you dare go Hollow

U1: delete 19 unused compatibility shims and list workspace members explicitly; ec-image's image dev-dep now resolves to the registry crate, not the shadowing workspace shim (no codec code or output change)

Browse files at this commit

8d5f9039c9831bfca472bc17601f963ed191289cAhmet Kaan GümüşParent: 41510f0
Cargo.lockmodified+4 -160
@@ -607,7 +607,7 @@ dependencies = [
607607 "ec-core",
608608 "ec-inflate",
609609 "ec-testkit",
610- "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)",
610+ "image",
611611 "tracking-allocator",
612612 ]
613613
@@ -885,7 +885,7 @@ dependencies = [
885885 "bit_field",
886886 "half",
887887 "lebe",
888- "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)",
888+ "miniz_oxide",
889889 "num-complex",
890890 "pulp",
891891 "rayon-core",
@@ -914,13 +914,6 @@ version = "0.1.10"
914914 source = "registry+https://github.com/rust-lang/crates.io-index"
915915 checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de"
916916
917-[[package]]
918-name = "flacenc"
919-version = "0.5.1"
920-dependencies = [
921- "ec-flac",
922-]
923-
924917 [[package]]
925918 name = "flate2"
926919 version = "1.1.9"
@@ -928,7 +921,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
928921 checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
929922 dependencies = [
930923 "crc32fast",
931- "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)",
924+ "miniz_oxide",
932925 ]
933926
934927 [[package]]
@@ -1031,13 +1024,6 @@ dependencies = [
10311024 "zerocopy",
10321025 ]
10331026
1034-[[package]]
1035-name = "hound"
1036-version = "3.5.1"
1037-dependencies = [
1038- "ec-riff",
1039-]
1040-
10411027 [[package]]
10421028 name = "hybrid-array"
10431029 version = "0.4.15"
@@ -1047,13 +1033,6 @@ dependencies = [
10471033 "typenum",
10481034 ]
10491035
1050-[[package]]
1051-name = "image"
1052-version = "0.25.10"
1053-dependencies = [
1054- "ec-image",
1055-]
1056-
10571036 [[package]]
10581037 name = "image"
10591038 version = "0.25.10"
@@ -1208,13 +1187,6 @@ version = "0.2.1"
12081187 source = "registry+https://github.com/rust-lang/crates.io-index"
12091188 checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
12101189
1211-[[package]]
1212-name = "miniz_oxide"
1213-version = "0.8.9"
1214-dependencies = [
1215- "ec-inflate",
1216-]
1217-
12181190 [[package]]
12191191 name = "miniz_oxide"
12201192 version = "0.8.9"
@@ -1362,13 +1334,6 @@ version = "1.21.4"
13621334 source = "registry+https://github.com/rust-lang/crates.io-index"
13631335 checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
13641336
1365-[[package]]
1366-name = "opus-rs"
1367-version = "0.1.26"
1368-dependencies = [
1369- "ec-opus",
1370-]
1371-
13721337 [[package]]
13731338 name = "oracle"
13741339 version = "0.1.0"
@@ -1376,59 +1341,6 @@ dependencies = [
13761341 "ec-testkit",
13771342 ]
13781343
1379-[[package]]
1380-name = "oxideav-ac3"
1381-version = "0.0.10"
1382-dependencies = [
1383- "ec-ac3",
1384- "ec-core",
1385- "ec-testkit",
1386- "oxideav-core",
1387-]
1388-
1389-[[package]]
1390-name = "oxideav-ass"
1391-version = "0.0.9"
1392-dependencies = [
1393- "ec-ass",
1394- "ec-subs",
1395- "oxideav-core",
1396-]
1397-
1398-[[package]]
1399-name = "oxideav-core"
1400-version = "0.1.34"
1401-dependencies = [
1402- "ec-core",
1403-]
1404-
1405-[[package]]
1406-name = "oxideav-ogg"
1407-version = "0.1.8"
1408-dependencies = [
1409- "ec-core",
1410- "ec-ogg",
1411- "oxideav-core",
1412-]
1413-
1414-[[package]]
1415-name = "oxideav-sub-image"
1416-version = "0.0.7"
1417-dependencies = [
1418- "ec-pgs",
1419- "oxideav-ass",
1420- "oxideav-core",
1421- "oxideav-subtitle",
1422-]
1423-
1424-[[package]]
1425-name = "oxideav-subtitle"
1426-version = "0.1.2"
1427-dependencies = [
1428- "ec-subs",
1429- "oxideav-core",
1430-]
1431-
14321344 [[package]]
14331345 name = "paste"
14341346 version = "1.0.15"
@@ -1463,7 +1375,7 @@ dependencies = [
14631375 "crc32fast",
14641376 "fdeflate",
14651377 "flate2",
1466- "miniz_oxide 0.8.9 (registry+https://github.com/rust-lang/crates.io-index)",
1378+ "miniz_oxide",
14671379 ]
14681380
14691381 [[package]]
@@ -1736,13 +1648,6 @@ version = "0.8.53"
17361648 source = "registry+https://github.com/rust-lang/crates.io-index"
17371649 checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
17381650
1739-[[package]]
1740-name = "ruopus"
1741-version = "0.1.2"
1742-dependencies = [
1743- "ec-opus",
1744-]
1745-
17461651 [[package]]
17471652 name = "rustc-hash"
17481653 version = "1.1.0"
@@ -1769,38 +1674,6 @@ version = "1.0.23"
17691674 source = "registry+https://github.com/rust-lang/crates.io-index"
17701675 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
17711676
1772-[[package]]
1773-name = "rusty_aac"
1774-version = "0.5.0"
1775-dependencies = [
1776- "ec-aac",
1777-]
1778-
1779-[[package]]
1780-name = "rusty_h264"
1781-version = "0.9.1"
1782-dependencies = [
1783- "ec-h264",
1784- "ec-h264-syntax",
1785-]
1786-
1787-[[package]]
1788-name = "rusty_mp3"
1789-version = "0.6.1"
1790-dependencies = [
1791- "ec-core",
1792- "ec-mp3",
1793-]
1794-
1795-[[package]]
1796-name = "rusty_vorbis"
1797-version = "0.1.1"
1798-dependencies = [
1799- "ec-core",
1800- "ec-ogg",
1801- "ec-vorbis",
1802-]
1803-
18041677 [[package]]
18051678 name = "safe_arch"
18061679 version = "1.1.0"
@@ -1878,35 +1751,6 @@ version = "0.2.4"
18781751 source = "registry+https://github.com/rust-lang/crates.io-index"
18791752 checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
18801753
1881-[[package]]
1882-name = "symphonia"
1883-version = "0.6.0"
1884-dependencies = [
1885- "ec-core",
1886- "ec-ogg",
1887- "ec-probe",
1888- "ec-testkit",
1889- "ec-vorbis",
1890- "rusty_vorbis",
1891- "symphonia-codec-aac",
1892- "symphonia-core",
1893-]
1894-
1895-[[package]]
1896-name = "symphonia-codec-aac"
1897-version = "0.6.0"
1898-dependencies = [
1899- "ec-aac",
1900- "symphonia-core",
1901-]
1902-
1903-[[package]]
1904-name = "symphonia-core"
1905-version = "0.6.0"
1906-dependencies = [
1907- "ec-core",
1908-]
1909-
19101754 [[package]]
19111755 name = "syn"
19121756 version = "2.0.119"
Cargo.tomlmodified+1 -1
@@ -1,6 +1,6 @@
11 [workspace]
22 resolver = "3"
3-members = ["crates/*", "shims/*", "tools/*"]
3+members = ["crates/*", "shims/cros-libva", "shims/vk-video-ffi", "tools/ec-bench", "tools/golden", "tools/oracle"]
44 exclude = ["crates/*/fuzz"]
55
66 [workspace.package]
shims/flacenc/Cargo.tomldeleted+0 -11
@@ -1,11 +0,0 @@
1-[package]
2-name = "flacenc"
3-description = "Compatibility shim: the flacenc 0.5.1 surface edith consumes, served by ec-flac."
4-version = "0.5.1"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-flac = { path = "../../crates/ec-flac", version = "0.1.0" }
shims/flacenc/src/bitsink.rsdeleted+0 -71
@@ -1,71 +0,0 @@
1-//! `flacenc::bitsink`: where a written stream lands.
2-
3-use std::convert::Infallible;
4-
5-/// Somewhere bits can be written.
6-///
7-/// Only the part the replica needs: it constructs a [`ByteSink`], hands it to
8-/// `Stream::write` and reads the bytes back.
9-pub trait BitSink: Sized {
10- /// What writing can fail with.
11- type Error: std::error::Error;
12-
13- /// Append whole bytes.
14- fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
15-
16- /// Bits written so far.
17- fn bit_len(&self) -> usize;
18-}
19-
20-/// A `Vec<u8>` sink — `flacenc::bitsink::ByteSink`.
21-#[derive(Debug, Clone, Default, PartialEq, Eq)]
22-pub struct ByteSink {
23- storage: Vec<u8>,
24-}
25-
26-impl ByteSink {
27- /// An empty sink.
28- pub fn new() -> Self {
29- ByteSink::default()
30- }
31-
32- /// An empty sink with room for `bits`.
33- pub fn with_capacity(bits: usize) -> Self {
34- ByteSink {
35- storage: Vec::with_capacity(bits.div_ceil(8)),
36- }
37- }
38-
39- /// The bytes written so far.
40- pub fn as_slice(&self) -> &[u8] {
41- &self.storage
42- }
43-
44- /// Take the bytes.
45- pub fn into_inner(self) -> Vec<u8> {
46- self.storage
47- }
48-
49- /// Bytes written so far.
50- pub fn len(&self) -> usize {
51- self.storage.len()
52- }
53-
54- /// True when nothing has been written.
55- pub fn is_empty(&self) -> bool {
56- self.storage.is_empty()
57- }
58-}
59-
60-impl BitSink for ByteSink {
61- type Error = Infallible;
62-
63- fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Infallible> {
64- self.storage.extend_from_slice(bytes);
65- Ok(())
66- }
67-
68- fn bit_len(&self) -> usize {
69- self.storage.len() * 8
70- }
71-}
shims/flacenc/src/component.rsdeleted+0 -112
@@ -1,112 +0,0 @@
1-//! `flacenc::component`: the encoded stream and its `STREAMINFO`.
2-//!
3-//! The incumbent models every FLAC component as an addressable value and
4-//! writes them out on demand. Ours holds the encoded bytes and the header
5-//! fields a caller is allowed to correct afterwards — which is the whole of
6-//! what the replica does with the tree.
7-
8-use crate::bitsink::BitSink;
9-use crate::error::{OutputError, VerifyError};
10-
11-/// Something that can state its size and write itself to a [`BitSink`].
12-pub trait BitRepr {
13- /// Bits this component occupies.
14- fn count_bits(&self) -> usize;
15-
16- /// Write the component out.
17- ///
18- /// # Errors
19- /// When the sink fails, or the component holds a value FLAC cannot express.
20- fn write<S: BitSink>(&self, dest: &mut S) -> Result<(), OutputError<S>>;
21-}
22-
23-/// A complete encoded FLAC stream.
24-#[derive(Debug, Clone, PartialEq, Eq)]
25-pub struct Stream {
26- bytes: Vec<u8>,
27- stream_info: StreamInfo,
28-}
29-
30-/// Offset of the `STREAMINFO` payload: `fLaC` plus the 4-byte block header.
31-const STREAM_INFO_AT: usize = 8;
32-
33-impl Stream {
34- pub(crate) fn from_bytes(bytes: Vec<u8>) -> Stream {
35- let min = u16::from_be_bytes([bytes[STREAM_INFO_AT], bytes[STREAM_INFO_AT + 1]]);
36- let max = u16::from_be_bytes([bytes[STREAM_INFO_AT + 2], bytes[STREAM_INFO_AT + 3]]);
37- Stream {
38- bytes,
39- stream_info: StreamInfo {
40- min_block_size: min,
41- max_block_size: max,
42- },
43- }
44- }
45-
46- /// The stream's `STREAMINFO`, mutable.
47- pub fn stream_info_mut(&mut self) -> &mut StreamInfo {
48- &mut self.stream_info
49- }
50-
51- /// The stream's `STREAMINFO`.
52- pub fn stream_info(&self) -> &StreamInfo {
53- &self.stream_info
54- }
55-}
56-
57-impl BitRepr for Stream {
58- fn count_bits(&self) -> usize {
59- self.bytes.len() * 8
60- }
61-
62- fn write<S: BitSink>(&self, dest: &mut S) -> Result<(), OutputError<S>> {
63- // The declared block sizes are the one field a caller may have changed
64- // after encoding, so they are patched in on the way out.
65- let mut bytes = self.bytes.clone();
66- bytes[STREAM_INFO_AT..STREAM_INFO_AT + 2]
67- .copy_from_slice(&self.stream_info.min_block_size.to_be_bytes());
68- bytes[STREAM_INFO_AT + 2..STREAM_INFO_AT + 4]
69- .copy_from_slice(&self.stream_info.max_block_size.to_be_bytes());
70- dest.write_bytes(&bytes)
71- .map_err(|e| OutputError::new(e.to_string()))
72- }
73-}
74-
75-/// The `STREAMINFO` fields a caller may correct after encoding.
76-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77-pub struct StreamInfo {
78- min_block_size: u16,
79- max_block_size: u16,
80-}
81-
82-impl StreamInfo {
83- /// State the stream's block sizes.
84- ///
85- /// # Errors
86- /// When either value is not a legal block size.
87- pub fn set_block_sizes(
88- &mut self,
89- min_value: usize,
90- max_value: usize,
91- ) -> Result<(), VerifyError> {
92- self.min_block_size = u16::try_from(min_value)
93- .ok()
94- .filter(|&n| n >= 16)
95- .ok_or_else(|| VerifyError::new("min_block_size", "must be a valid block size."))?;
96- self.max_block_size = u16::try_from(max_value)
97- .ok()
98- .filter(|&n| n >= 16)
99- .ok_or_else(|| VerifyError::new("max_block_size", "must be a valid block size."))?;
100- Ok(())
101- }
102-
103- /// Smallest block size stated by the stream.
104- pub fn min_block_size(&self) -> usize {
105- usize::from(self.min_block_size)
106- }
107-
108- /// Largest block size stated by the stream.
109- pub fn max_block_size(&self) -> usize {
110- usize::from(self.max_block_size)
111- }
112-}
shims/flacenc/src/config.rsdeleted+0 -92
@@ -1,92 +0,0 @@
1-//! `flacenc::config`: the encoder configuration tree.
2-//!
3-//! The fields the replica reads (`block_size`) and the ones its `Default`
4-//! walks are kept; the knobs that only steer the incumbent's own search
5-//! (window functions, per-order caps) are not reproduced, because a value set
6-//! there would silently do nothing.
7-
8-use crate::error::{Verify, VerifyError};
9-
10-/// Encoder configuration — `flacenc::config::Encoder`.
11-#[derive(Clone, Debug, PartialEq, Eq)]
12-#[non_exhaustive]
13-pub struct Encoder {
14- /// Encoder block size.
15- pub block_size: usize,
16- /// Whether the encoder may use several threads.
17- pub multithread: bool,
18- /// Stereo coding switches.
19- pub stereo_coding: StereoCoding,
20- /// Per-channel coding switches.
21- pub subframe_coding: SubFrameCoding,
22-}
23-
24-impl Default for Encoder {
25- fn default() -> Self {
26- Encoder {
27- block_size: 4096,
28- multithread: false,
29- stereo_coding: StereoCoding::default(),
30- subframe_coding: SubFrameCoding::default(),
31- }
32- }
33-}
34-
35-impl Verify for Encoder {
36- fn verify(&self) -> Result<(), VerifyError> {
37- if !(16..=65535).contains(&self.block_size) {
38- return Err(VerifyError::new(
39- "block_size",
40- "must be in the range of 16..=65535.",
41- ));
42- }
43- Ok(())
44- }
45-}
46-
47-/// Stereo coding switches — `flacenc::config::StereoCoding`.
48-#[derive(Clone, Debug, PartialEq, Eq)]
49-#[non_exhaustive]
50-pub struct StereoCoding {
51- /// Allow left/side coding.
52- pub use_leftside: bool,
53- /// Allow right/side coding.
54- pub use_rightside: bool,
55- /// Allow mid/side coding.
56- pub use_midside: bool,
57-}
58-
59-impl Default for StereoCoding {
60- fn default() -> Self {
61- StereoCoding {
62- use_leftside: true,
63- use_rightside: true,
64- use_midside: true,
65- }
66- }
67-}
68-
69-/// Per-channel coding switches — `flacenc::config::SubFrameCoding`.
70-///
71-/// Verbatim coding is deliberately not switchable: it is the representation
72-/// that always exists, so turning it off could leave a signal unencodable.
73-#[derive(Clone, Debug, PartialEq, Eq)]
74-#[non_exhaustive]
75-pub struct SubFrameCoding {
76- /// Allow constant subframes.
77- pub use_constant: bool,
78- /// Allow fixed-predictor subframes.
79- pub use_fixed: bool,
80- /// Allow LPC subframes.
81- pub use_lpc: bool,
82-}
83-
84-impl Default for SubFrameCoding {
85- fn default() -> Self {
86- SubFrameCoding {
87- use_constant: true,
88- use_fixed: true,
89- use_lpc: true,
90- }
91- }
92-}
shims/flacenc/src/error.rsdeleted+0 -110
@@ -1,110 +0,0 @@
1-//! `flacenc::error`: verification wrappers and the error types the encoder
2-//! hands back.
3-
4-use std::fmt;
5-use std::marker::PhantomData;
6-
7-use crate::bitsink::BitSink;
8-
9-/// A value that has passed [`Verify::verify`].
10-///
11-/// Derefs to the value, which is how callers read `config.block_size` off a
12-/// verified config.
13-#[derive(Debug, Clone, PartialEq, Eq)]
14-pub struct Verified<T>(T);
15-
16-impl<T> std::ops::Deref for Verified<T> {
17- type Target = T;
18- fn deref(&self) -> &T {
19- &self.0
20- }
21-}
22-
23-/// Configuration structs that can check their own consistency.
24-pub trait Verify: Sized {
25- /// Check every field; [`VerifyError`] names the first bad one.
26- fn verify(&self) -> Result<(), VerifyError>;
27-
28- /// Wrap into [`Verified`], or hand the value back with the reason.
29- fn into_verified(self) -> Result<Verified<Self>, (Self, VerifyError)> {
30- match self.verify() {
31- Ok(()) => Ok(Verified(self)),
32- Err(e) => Err((self, e)),
33- }
34- }
35-}
36-
37-/// A configuration field that is out of range, with the path to it.
38-#[derive(Debug, Clone, PartialEq, Eq)]
39-pub struct VerifyError {
40- components: Vec<String>,
41- reason: String,
42-}
43-
44-impl VerifyError {
45- /// An error for an invalid field `component`.
46- pub fn new(component: &str, reason: &str) -> Self {
47- VerifyError {
48- components: vec![component.to_owned()],
49- reason: reason.to_owned(),
50- }
51- }
52-
53- /// Prefix the field path with an enclosing struct's field name.
54- pub fn within(mut self, component: &str) -> Self {
55- self.components.insert(0, component.to_owned());
56- self
57- }
58-}
59-
60-impl fmt::Display for VerifyError {
61- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62- write!(
63- f,
64- "verification error: `{}` is not valid. reason: {}",
65- self.components.join("."),
66- self.reason
67- )
68- }
69-}
70-
71-impl std::error::Error for VerifyError {}
72-
73-/// Encoding failed: either the source or the configuration.
74-#[derive(Debug, Clone, PartialEq, Eq)]
75-pub struct EncodeError(pub(crate) String);
76-
77-impl fmt::Display for EncodeError {
78- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79- f.write_str(&self.0)
80- }
81-}
82-
83-impl std::error::Error for EncodeError {}
84-
85-/// Writing a component to a [`BitSink`] failed.
86-///
87-/// Generic over the sink, as the incumbent is, so `write` signatures match; our
88-/// only sink is infallible, so this is never constructed in practice.
89-#[derive(Debug, Clone, PartialEq, Eq)]
90-pub struct OutputError<S: BitSink> {
91- reason: String,
92- sink: PhantomData<fn() -> S>,
93-}
94-
95-impl<S: BitSink> OutputError<S> {
96- pub(crate) fn new(reason: impl Into<String>) -> Self {
97- OutputError {
98- reason: reason.into(),
99- sink: PhantomData,
100- }
101- }
102-}
103-
104-impl<S: BitSink> fmt::Display for OutputError<S> {
105- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106- f.write_str(&self.reason)
107- }
108-}
109-
110-impl<S: BitSink + fmt::Debug> std::error::Error for OutputError<S> {}
shims/flacenc/src/lib.rsdeleted+0 -135
@@ -1,135 +0,0 @@
1-//! Drop-in replacement for the `flacenc` 0.5.1 surface the replica consumes,
2-//! implemented over [`ec_flac`].
3-//!
4-//! It carries the incumbent's package name and version so the swap is a
5-//! `[patch.crates-io]` entry and nothing else. The scope is exactly the API
6-//! `engine/src/export.rs` calls (`export.rs:67-68,2930-2954`):
7-//!
8-//! ```no_run
9-//! use flacenc::component::BitRepr;
10-//! use flacenc::error::Verify;
11-//!
12-//! let config = flacenc::config::Encoder::default().into_verified().unwrap();
13-//! let source = flacenc::source::MemSource::from_samples(&[0i32; 32], 2, 16, 44100);
14-//! let mut stream =
15-//! flacenc::encode_with_fixed_block_size(&config, source, config.block_size).unwrap();
16-//! stream
17-//! .stream_info_mut()
18-//! .set_block_sizes(config.block_size, config.block_size)
19-//! .unwrap();
20-//! let mut sink = flacenc::bitsink::ByteSink::new();
21-//! stream.write(&mut sink).unwrap();
22-//! let _bytes: &[u8] = sink.as_slice();
23-//! ```
24-//!
25-//! Signatures match the incumbent's (types, argument order, error shapes) so
26-//! call sites compile unchanged; the implementation behind them is ours.
27-//! Deliberately *not* covered: the `par` feature knobs, `serde` config
28-//! round-tripping and the component tree (`Frame`/`SubFrame`/`Residual` as
29-//! addressable values) — the replica constructs none of them.
30-
31-#![forbid(unsafe_code)]
32-#![warn(missing_docs)]
33-
34-pub mod bitsink;
35-pub mod component;
36-pub mod config;
37-pub mod error;
38-pub mod source;
39-
40-pub use component::Stream;
41-pub use error::EncodeError;
42-
43-use error::Verified;
44-use source::Source;
45-
46-/// Encode `src` into a stream of fixed-size blocks.
47-///
48-/// Mirrors `flacenc::encode_with_fixed_block_size`: the verified config, a
49-/// source, and the block size (which the caller reads off the config).
50-pub fn encode_with_fixed_block_size<T: Source>(
51- config: &Verified<config::Encoder>,
52- src: T,
53- block_size: usize,
54-) -> Result<Stream, EncodeError> {
55- let encoder = ec_flac::EncoderConfig {
56- block_size,
57- stereo_decorrelation: config.stereo_coding.use_midside
58- || config.stereo_coding.use_leftside
59- || config.stereo_coding.use_rightside,
60- ..ec_flac::EncoderConfig::default()
61- };
62- let bytes = ec_flac::encode(
63- &encoder,
64- src.as_raw_slice(),
65- src.channels(),
66- src.bits_per_sample() as u32,
67- src.sample_rate() as u32,
68- )
69- .map_err(|e| EncodeError(e.to_string()))?;
70- Ok(Stream::from_bytes(bytes))
71-}
72-
73-#[cfg(test)]
74-mod tests {
75- use super::*;
76- use crate::component::BitRepr;
77- use crate::error::Verify;
78-
79- /// The replica's own call sequence, verbatim from `export.rs:2994-3025`,
80- /// with the result decoded back to prove it is a real FLAC stream.
81- #[test]
82- fn the_replica_call_sequence_produces_a_decodable_stream() {
83- let samples: Vec<i32> = (0..8192)
84- .map(|i| ((i as f64 * 0.07).sin() * 12000.0) as i32)
85- .collect();
86-
87- let config = config::Encoder::default()
88- .into_verified()
89- .map_err(|(_, e)| format!("flac encoder config: {e}"))
90- .unwrap();
91- let source = source::MemSource::from_samples(&samples, 2, 16, 44100);
92- let mut stream = encode_with_fixed_block_size(&config, source, config.block_size)
93- .map_err(|e| format!("flac encode: {e}"))
94- .unwrap();
95- stream
96- .stream_info_mut()
97- .set_block_sizes(config.block_size, config.block_size)
98- .map_err(|e| format!("flac block size: {e}"))
99- .unwrap();
100- let mut sink = bitsink::ByteSink::new();
101- stream
102- .write(&mut sink)
103- .map_err(|e| format!("flac write: {e}"))
104- .unwrap();
105-
106- let bytes = sink.as_slice();
107- assert_eq!(&bytes[..4], b"fLaC");
108- assert_eq!(stream.count_bits(), bytes.len() * 8);
109- let mut reader = ec_flac::FlacReader::new(bytes).expect("our own output opens");
110- let info = reader.stream_info().expect("streaminfo").clone();
111- assert_eq!(info.min_block_size, config.block_size as u16);
112- assert_eq!(info.max_block_size, config.block_size as u16);
113- let decoded = reader.decode_all().expect("decode");
114- assert_eq!(decoded.interleaved(), samples, "the shim must be lossless");
115- }
116-
117- #[test]
118- fn a_block_size_the_stream_cannot_hold_is_an_error_not_a_panic() {
119- let config = config::Encoder::default().into_verified().unwrap();
120- let source = source::MemSource::from_samples(&[0i32; 64], 2, 16, 44100);
121- let mut stream = encode_with_fixed_block_size(&config, source, 32).unwrap();
122- assert!(stream.stream_info_mut().set_block_sizes(0, 70000).is_err());
123- }
124-
125- #[test]
126- fn an_invalid_config_is_refused_with_its_original_value() {
127- let config = config::Encoder {
128- block_size: 4,
129- ..config::Encoder::default()
130- };
131- let (returned, error) = config.into_verified().unwrap_err();
132- assert_eq!(returned.block_size, 4);
133- assert!(format!("{error}").contains("block_size"));
134- }
135-}
shims/flacenc/src/source.rsdeleted+0 -79
@@ -1,79 +0,0 @@
1-//! `flacenc::source`: where samples come from.
2-
3-/// A signal the encoder can read.
4-///
5-/// The incumbent's trait is a pull interface with a reusable context; the
6-/// replica only ever hands over a [`MemSource`] it built from a `Vec`, so this
7-/// is the whole-buffer shape of the same thing.
8-pub trait Source {
9- /// Channel count.
10- fn channels(&self) -> usize;
11- /// Bits per sample.
12- fn bits_per_sample(&self) -> usize;
13- /// Sample rate in Hz.
14- fn sample_rate(&self) -> usize;
15- /// The interleaved samples.
16- fn as_raw_slice(&self) -> &[i32];
17-}
18-
19-/// Samples already in memory — `flacenc::source::MemSource`.
20-#[derive(Debug, Clone, PartialEq, Eq)]
21-pub struct MemSource {
22- channels: usize,
23- bits_per_sample: usize,
24- sample_rate: usize,
25- samples: Vec<i32>,
26-}
27-
28-impl MemSource {
29- /// Build from interleaved samples.
30- pub fn from_samples(
31- samples: &[i32],
32- channels: usize,
33- bits_per_sample: usize,
34- sample_rate: usize,
35- ) -> Self {
36- MemSource {
37- channels,
38- bits_per_sample,
39- sample_rate,
40- samples: samples.to_owned(),
41- }
42- }
43-
44- /// The samples, interleaved.
45- pub fn as_raw_slice(&self) -> &[i32] {
46- &self.samples
47- }
48-
49- /// Inter-channel samples held.
50- pub fn len(&self) -> usize {
51- match self.channels {
52- 0 => 0,
53- n => self.samples.len() / n,
54- }
55- }
56-
57- /// True when the source holds no samples.
58- pub fn is_empty(&self) -> bool {
59- self.samples.is_empty()
60- }
61-}
62-
63-impl Source for MemSource {
64- fn channels(&self) -> usize {
65- self.channels
66- }
67-
68- fn bits_per_sample(&self) -> usize {
69- self.bits_per_sample
70- }
71-
72- fn sample_rate(&self) -> usize {
73- self.sample_rate
74- }
75-
76- fn as_raw_slice(&self) -> &[i32] {
77- &self.samples
78- }
79-}
shims/hound/Cargo.tomldeleted+0 -10
@@ -1,10 +0,0 @@
1-[package]
2-name = "hound"
3-description = "Compatibility shim: the hound 3.5.1 WAV-writing surface, implemented over ec-riff."
4-version = "3.5.1"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-
9-[dependencies]
10-ec-riff = { path = "../../crates/ec-riff", version = "0.1.0" }
shims/hound/src/lib.rsdeleted+0 -344
@@ -1,344 +0,0 @@
1-//! `hound` 3.5.1's WAV surface, over [`ec_riff`].
2-//!
3-//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the
4-//! incumbent's name and version so a consumer's `use hound::…` compiles
5-//! unchanged. Only what edith consumes is here — `WavWriter::create`,
6-//! `write_sample`, `finalize`, `WavReader::open`, `spec`, `samples`,
7-//! [`WavSpec`], [`SampleFormat`] and an [`Error`] with the incumbent's variants
8-//! — because a shim that grows a surface nobody calls is a second
9-//! implementation to keep honest.
10-//!
11-//! Behaviour differences from the incumbent. Writing is stricter only: files
12-//! with more than two channels or more than 16 bits get a
13-//! `WAVE_FORMAT_EXTENSIBLE` header (hound writes one only above 16 bits), and
14-//! a `fact` chunk goes with it. Reading diverges in shape, not in verdict —
15-//! the refusals are hound's, the reporting is not:
16-//!
17-//! * [`WavReader::samples`] reads the `data` chunk whole before yielding, so a
18-//! file that ends early yields one [`Error::IoError`] and nothing else,
19-//! where hound yields the samples it did read and then the `UnexpectedEof`.
20-//! [`Error::TooWide`] and [`Error::InvalidSampleFormat`] are single-item for
21-//! the same reason; hound repeats them per sample.
22-//! * `bits_per_sample` outside 8/16/24/32 is [`Error::FormatError`] when it is
23-//! not a whole number of bytes and [`Error::Unsupported`] otherwise, which
24-//! splits hound's refusals along the same line but not with its wording.
25-
26-#![forbid(unsafe_code)]
27-#![warn(missing_docs)]
28-
29-use std::fmt;
30-use std::fs::File;
31-use std::io::{self, BufReader, BufWriter, Read, Seek, Write};
32-use std::path::Path;
33-
34-/// A sample type a [`WavWriter`] accepts and a [`WavReader`] yields.
35-///
36-/// The write half is [`ec_riff::Sample`]; the two constructors and the width
37-/// are what reading adds, and they are what makes hound's `TooWide` and
38-/// `InvalidSampleFormat` decidable before a single sample is converted.
39-pub trait Sample: ec_riff::Sample {
40- /// Bits this type carries. A file deeper than this is [`Error::TooWide`].
41- const BITS: u16;
42- /// Narrow the reader's integer carrier. Called for integer files only.
43- fn from_i32(v: i32) -> Self;
44- /// Take the reader's float carrier. Called for float files only.
45- fn from_f32(v: f32) -> Self;
46-}
47-
48-macro_rules! int_sample {
49- ($($t:ty => $bits:expr),*) => {$(
50- impl Sample for $t {
51- const BITS: u16 = $bits;
52- fn from_i32(v: i32) -> Self {
53- v as $t
54- }
55- fn from_f32(v: f32) -> Self {
56- v as $t
57- }
58- }
59- )*};
60-}
61-int_sample!(i8 => 8, i16 => 16, i32 => 32);
62-
63-impl Sample for f32 {
64- const BITS: u16 = 32;
65- fn from_i32(v: i32) -> Self {
66- v as f32
67- }
68- fn from_f32(v: f32) -> Self {
69- v
70- }
71-}
72-
73-/// Whether samples are stored as floats or integers.
74-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75-pub enum SampleFormat {
76- /// `WAVE_FORMAT_IEEE_FLOAT`, nominal range -1.0..=1.0.
77- Float,
78- /// `WAVE_FORMAT_PCM`.
79- Int,
80-}
81-
82-/// Properties of the audio data.
83-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84-pub struct WavSpec {
85- /// The number of channels.
86- pub channels: u16,
87- /// The number of samples per second.
88- pub sample_rate: u32,
89- /// The number of bits per sample.
90- pub bits_per_sample: u16,
91- /// Whether the samples are float or integer values.
92- pub sample_format: SampleFormat,
93-}
94-
95-impl From<WavSpec> for ec_riff::WavSpec {
96- fn from(s: WavSpec) -> ec_riff::WavSpec {
97- ec_riff::WavSpec {
98- channels: s.channels,
99- sample_rate: s.sample_rate,
100- bits_per_sample: s.bits_per_sample,
101- sample_format: match s.sample_format {
102- SampleFormat::Float => ec_riff::SampleType::Float,
103- SampleFormat::Int => ec_riff::SampleType::Int,
104- },
105- }
106- }
107-}
108-
109-/// The error type for operations on `WavWriter`.
110-#[derive(Debug)]
111-pub enum Error {
112- /// An IO error occured in the underlying writer.
113- IoError(io::Error),
114- /// Ill-formed WAVE data was encountered.
115- FormatError(&'static str),
116- /// The sample has more bits than the destination format allows.
117- TooWide,
118- /// The number of samples written is not a multiple of the number of channels.
119- UnfinishedSample,
120- /// The format is not supported.
121- Unsupported,
122- /// The sample format is different than the destination format.
123- InvalidSampleFormat,
124-}
125-
126-impl fmt::Display for Error {
127- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128- match self {
129- Error::IoError(e) => e.fmt(f),
130- Error::FormatError(reason) => write!(f, "Ill-formed WAVE file: {reason}"),
131- Error::TooWide => f.write_str("The sample has more bits than the destination type."),
132- Error::UnfinishedSample => f.write_str(
133- "The number of samples written is not a multiple of the number of channels.",
134- ),
135- Error::Unsupported => f.write_str("The wave format of the file is not supported."),
136- Error::InvalidSampleFormat => {
137- f.write_str("The sample format differs from the destination format.")
138- }
139- }
140- }
141-}
142-
143-impl std::error::Error for Error {
144- fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
145- match self {
146- Error::IoError(e) => Some(e),
147- _ => None,
148- }
149- }
150-}
151-
152-impl From<io::Error> for Error {
153- fn from(e: io::Error) -> Error {
154- Error::IoError(e)
155- }
156-}
157-
158-/// A type for results generated by this crate.
159-pub type Result<T> = std::result::Result<T, Error>;
160-
161-/// I/O failures keep their identity; everything else becomes `other`, which the
162-/// call site chooses, since the same `ec-riff` variant means different things
163-/// when writing a header, a sample, or the final sizes.
164-fn map(e: ec_riff::Error, corrupt_as: Error) -> Error {
165- match e {
166- ec_riff::Error::Io(e) => Error::IoError(e),
167- ec_riff::Error::Unsupported { .. } => Error::Unsupported,
168- _ => corrupt_as,
169- }
170-}
171-
172-/// Writes a WAVE file sample by sample.
173-pub struct WavWriter<W: Write + Seek> {
174- inner: ec_riff::WavWriter<W>,
175-}
176-
177-impl WavWriter<BufWriter<File>> {
178- /// Create a new wav file at `path` with the given spec.
179- pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> {
180- let file = File::create(path)?;
181- WavWriter::new(BufWriter::new(file), spec)
182- }
183-}
184-
185-impl<W: Write + Seek> WavWriter<W> {
186- /// Create a new writer over `writer`, writing the header immediately.
187- pub fn new(writer: W, spec: WavSpec) -> Result<Self> {
188- ec_riff::WavWriter::new(writer, spec.into())
189- .map(|inner| WavWriter { inner })
190- .map_err(|e| {
191- map(
192- e,
193- Error::FormatError("unusable channel count or sample rate"),
194- )
195- })
196- }
197-
198- /// Write a single sample for one channel.
199- pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> {
200- self.inner.write_sample(sample).map_err(|e| match e {
201- // A value the declared depth cannot hold, versus a sample type the
202- // declared format cannot hold: hound's TooWide and
203- // InvalidSampleFormat respectively.
204- ec_riff::Error::Io(e) => Error::IoError(e),
205- ec_riff::Error::Unsupported { .. } => Error::InvalidSampleFormat,
206- _ => Error::TooWide,
207- })
208- }
209-
210- /// Number of samples (per channel) written so far.
211- pub fn duration(&self) -> u32 {
212- self.inner.duration() as u32
213- }
214-
215- /// The spec the file was created with.
216- pub fn spec(&self) -> WavSpec {
217- let s = self.inner.spec();
218- WavSpec {
219- channels: s.channels,
220- sample_rate: s.sample_rate,
221- bits_per_sample: s.bits_per_sample,
222- sample_format: match s.sample_format {
223- ec_riff::SampleType::Float => SampleFormat::Float,
224- ec_riff::SampleType::Int => SampleFormat::Int,
225- },
226- }
227- }
228-
229- /// Update the header with the written length and flush.
230- ///
231- /// Failing here is the difference between a finished file and a truncated
232- /// one, which is why it is called instead of dropping the writer.
233- pub fn finalize(self) -> Result<()> {
234- self.inner
235- .finalize()
236- .map(|_| ())
237- .map_err(|e| map(e, Error::UnfinishedSample))
238- }
239-}
240-
241-/// Reads a WAVE file's header, then its samples.
242-pub struct WavReader<R: Read> {
243- inner: ec_riff::WavReader<R>,
244-}
245-
246-impl WavReader<BufReader<File>> {
247- /// Open `path` and parse its header.
248- pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
249- WavReader::new(BufReader::new(File::open(path)?))
250- }
251-}
252-
253-impl<R: Read> WavReader<R> {
254- /// Parse the header of an already-open stream.
255- pub fn new(reader: R) -> Result<Self> {
256- ec_riff::WavReader::new(reader)
257- .map(|inner| WavReader { inner })
258- .map_err(|e| map(e, Error::FormatError("not a WAVE file this reader accepts")))
259- }
260-
261- /// The `fmt ` chunk as parsed.
262- pub fn spec(&self) -> WavSpec {
263- let s = self.inner.spec();
264- WavSpec {
265- channels: s.channels,
266- sample_rate: s.sample_rate,
267- bits_per_sample: s.bits_per_sample,
268- sample_format: match s.sample_format {
269- ec_riff::SampleType::Float => SampleFormat::Float,
270- ec_riff::SampleType::Int => SampleFormat::Int,
271- },
272- }
273- }
274-
275- /// Every sample, interleaved in channel order, as the incumbent's fallible
276- /// iterator: a file whose format or depth `S` cannot carry yields one
277- /// [`Error::InvalidSampleFormat`] or [`Error::TooWide`] rather than a
278- /// converted value, which is where hound puts the same refusals.
279- ///
280- /// corner-cut: `ec-riff` reads the `data` chunk whole, so this buffers the
281- /// file where hound streams it — ~10 MB per minute of 48 kHz stereo, fine
282- /// for the export round-trips edith checks and wrong for an hour of audio.
283- /// Upgrade path is a streaming `read_samples` on `ec_riff::WavReader`,
284- /// which this then forwards to unchanged.
285- pub fn samples<S: Sample>(&mut self) -> WavSamples<S> {
286- let spec = self.inner.spec();
287- let float_file = spec.sample_format == ec_riff::SampleType::Float;
288- // What the `data` header promised. `ec-riff` stops at the end of the
289- // file without complaint; hound hands the caller the `UnexpectedEof`,
290- // so the promise is compared against what arrived.
291- let promised = self
292- .inner
293- .duration()
294- .map(|frames| frames as usize * usize::from(spec.channels));
295- let items = if float_file != S::FLOAT {
296- vec![Err(Error::InvalidSampleFormat)]
297- } else if spec.bits_per_sample > S::BITS {
298- vec![Err(Error::TooWide)]
299- } else if float_file {
300- match self.inner.read_all_f32() {
301- Ok(v) => match short_read(v.len(), promised) {
302- Some(e) => vec![Err(e)],
303- None => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(),
304- },
305- Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
306- }
307- } else {
308- match self.inner.read_all_i32() {
309- Ok(v) => match short_read(v.len(), promised) {
310- Some(e) => vec![Err(e)],
311- None => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(),
312- },
313- Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
314- }
315- };
316- WavSamples(items.into_iter())
317- }
318-}
319-
320-/// The `UnexpectedEof` hound reports when the `data` chunk ends before the
321-/// length its header declares, or `None` when the file kept its promise (or
322-/// made none: a streamed placeholder size leaves the file itself the bound).
323-fn short_read(got: usize, promised: Option<usize>) -> Option<Error> {
324- let want = promised.filter(|&n| got < n)?;
325- Some(Error::IoError(io::Error::new(
326- io::ErrorKind::UnexpectedEof,
327- format!("WAVE data chunk ends after {got} of {want} samples"),
328- )))
329-}
330-
331-/// The iterator [`WavReader::samples`] returns.
332-pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>);
333-
334-impl<S> Iterator for WavSamples<S> {
335- type Item = Result<S>;
336-
337- fn next(&mut self) -> Option<Self::Item> {
338- self.0.next()
339- }
340-
341- fn size_hint(&self) -> (usize, Option<usize>) {
342- self.0.size_hint()
343- }
344-}
shims/hound/tests/edith_surface.rsdeleted+0 -190
@@ -1,190 +0,0 @@
1-//! The call edith makes, verbatim in shape (engine/src/export.rs `write_wav`):
2-//! `WavWriter::create(path, WavSpec { .. sample_format: Int })`, a run of
3-//! `write_sample(x as i16)`, then `finalize()` — with the `?` conversion into
4-//! edith's `Box<dyn Error + Send + Sync>` exercised too.
5-
6-type EdithError = Box<dyn std::error::Error + Send + Sync>;
7-
8-fn write_wav(
9- out: &std::path::Path,
10- samples: &[i32],
11- channels: u16,
12- rate: u32,
13-) -> Result<(), EdithError> {
14- let mut writer = hound::WavWriter::create(
15- out,
16- hound::WavSpec {
17- channels,
18- sample_rate: rate,
19- bits_per_sample: 16,
20- sample_format: hound::SampleFormat::Int,
21- },
22- )?;
23- for &sample in samples {
24- writer.write_sample(sample as i16)?;
25- }
26- writer.finalize()?;
27- Ok(())
28-}
29-
30-#[test]
31-fn edith_write_wav_round_trips() {
32- let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
33- std::fs::create_dir_all(dir).unwrap();
34- for (channels, rate) in [(1u16, 44100u32), (2, 48000), (6, 48000)] {
35- let path = dir.join(format!("edith-{channels}ch-{rate}.wav"));
36- let samples: Vec<i32> = (0..usize::from(channels) * 512)
37- .map(|i| ((i as i32 * 733) % 65536) - 32768)
38- .collect();
39- write_wav(&path, &samples, channels, rate).unwrap();
40-
41- let mut r = ec_riff::WavReader::open(&path).unwrap();
42- let spec = r.spec();
43- assert_eq!(spec.channels, channels);
44- assert_eq!(spec.sample_rate, rate);
45- assert_eq!(spec.bits_per_sample, 16);
46- assert_eq!(spec.sample_format, ec_riff::SampleType::Int);
47- assert_eq!(r.read_all_i32().unwrap(), samples);
48- }
49-}
50-
51-/// The read half edith's tests make: `WavReader::open`, `spec()`, and
52-/// `samples::<i16>()` collected — plus the two refusals hound answers with
53-/// when the requested type cannot carry the file.
54-#[test]
55-fn edith_read_wav_round_trips() {
56- let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
57- std::fs::create_dir_all(dir).unwrap();
58- let path = dir.join("read-back.wav");
59- let samples: Vec<i32> = (0..2048).map(|i| ((i * 733) % 65536) - 32768).collect();
60- write_wav(&path, &samples, 2, 48000).unwrap();
61-
62- let mut r = hound::WavReader::open(&path).unwrap();
63- let spec = r.spec();
64- assert_eq!(spec.channels, 2);
65- assert_eq!(spec.sample_rate, 48000);
66- assert_eq!(spec.bits_per_sample, 16);
67- assert_eq!(spec.sample_format, hound::SampleFormat::Int);
68- let read: Vec<i32> = r
69- .samples::<i16>()
70- .map(|s| i32::from(s.expect("a sample")))
71- .collect();
72- assert_eq!(read, samples);
73-
74- // An integer file read as floats, and a 16-bit file read as 8: the two
75- // refusals, not silent conversions.
76- let mut r = hound::WavReader::open(&path).unwrap();
77- assert!(matches!(
78- r.samples::<f32>().next(),
79- Some(Err(hound::Error::InvalidSampleFormat))
80- ));
81- let mut r = hound::WavReader::open(&path).unwrap();
82- assert!(matches!(
83- r.samples::<i8>().next(),
84- Some(Err(hound::Error::TooWide))
85- ));
86-}
87-
88-/// A `data` chunk that ends before its header said is hound's `IoError`
89-/// (`UnexpectedEof`), never a short read the caller mistakes for the whole file.
90-#[test]
91-fn truncated_data_chunk_errors() {
92- let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
93- std::fs::create_dir_all(dir).unwrap();
94- let path = dir.join("truncated.wav");
95- let samples: Vec<i32> = (0..1024).map(|i| (i * 17) % 4096).collect();
96- write_wav(&path, &samples, 2, 48000).unwrap();
97-
98- // Half the samples away, the header still promising all of them.
99- let bytes = std::fs::read(&path).unwrap();
100- std::fs::write(&path, &bytes[..bytes.len() - 1024]).unwrap();
101-
102- let mut r = hound::WavReader::open(&path).unwrap();
103- let first = r.samples::<i16>().next();
104- assert!(
105- matches!(&first, Some(Err(hound::Error::IoError(e))) if e.kind() == std::io::ErrorKind::UnexpectedEof),
106- "expected UnexpectedEof, got {first:?}"
107- );
108-}
109-
110-/// A minimal PCM WAVE header with `block_align` and `bits_per_sample` stated
111-/// independently, so a padded container can be handed to the reader.
112-fn wav_bytes(channels: u16, bits: u16, block_align: u16, data: &[u8]) -> Vec<u8> {
113- let mut v = Vec::new();
114- v.extend_from_slice(b"RIFF");
115- v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
116- v.extend_from_slice(b"WAVEfmt ");
117- v.extend_from_slice(&16u32.to_le_bytes());
118- v.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM
119- v.extend_from_slice(&channels.to_le_bytes());
120- v.extend_from_slice(&48000u32.to_le_bytes());
121- v.extend_from_slice(&(48000 * u32::from(block_align)).to_le_bytes());
122- v.extend_from_slice(&block_align.to_le_bytes());
123- v.extend_from_slice(&bits.to_le_bytes());
124- v.extend_from_slice(b"data");
125- v.extend_from_slice(&(data.len() as u32).to_le_bytes());
126- v.extend_from_slice(data);
127- v
128-}
129-
130-/// The header pair the reader must not paper over: a container wider than the
131-/// depth (hound: `Unsupported`) and a depth that is not whole bytes (hound:
132-/// `FormatError`). Reading either as if it were packed would silently double
133-/// the sample count and halve the duration.
134-#[test]
135-fn container_width_and_odd_depths_are_refused() {
136- let padded = wav_bytes(1, 8, 2, &[0x80, 0x00, 0x90, 0x00]);
137- assert!(
138- matches!(
139- hound::WavReader::new(std::io::Cursor::new(padded)),
140- Err(hound::Error::Unsupported)
141- ),
142- "8-bit samples in a 2-byte container must be refused"
143- );
144-
145- for bits in [12u16, 20] {
146- let odd = wav_bytes(1, bits, bits.div_ceil(8), &[0; 8]);
147- assert!(
148- matches!(
149- hound::WavReader::new(std::io::Cursor::new(odd)),
150- Err(hound::Error::FormatError(_))
151- ),
152- "{bits}-bit must be a FormatError"
153- );
154- }
155-
156- // The well-formed shape of the same helper still opens, so the refusals
157- // above are about the fields under test and not about the fixture.
158- let ok = wav_bytes(2, 16, 4, &[0; 16]);
159- let r = hound::WavReader::new(std::io::Cursor::new(ok)).expect("a packed 16-bit stereo header");
160- assert_eq!(r.spec().bits_per_sample, 16);
161-}
162-
163-#[test]
164-fn errors_carry_the_incumbent_variants() {
165- let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
166- let spec = hound::WavSpec {
167- channels: 2,
168- sample_rate: 48000,
169- bits_per_sample: 16,
170- sample_format: hound::SampleFormat::Int,
171- };
172- let mut w = hound::WavWriter::create(dir.join("errors.wav"), spec).unwrap();
173- // Wider than the declared depth, and the wrong sample family: the two
174- // failures callers of hound match on.
175- assert!(matches!(
176- w.write_sample(40_000i32),
177- Err(hound::Error::TooWide)
178- ));
179- assert!(matches!(
180- w.write_sample(0.5f32),
181- Err(hound::Error::InvalidSampleFormat)
182- ));
183- w.write_sample(1i16).unwrap();
184- assert!(matches!(w.finalize(), Err(hound::Error::UnfinishedSample)));
185- // A directory is not a file: I/O keeps its identity through the shim.
186- assert!(matches!(
187- hound::WavWriter::create(dir, spec),
188- Err(hound::Error::IoError(_))
189- ));
190-}
shims/image/Cargo.tomldeleted+0 -26
@@ -1,26 +0,0 @@
1-[package]
2-name = "image"
3-description = "Compatibility shim: the image surface edith's engine consumes, served by ec-image."
4-version = "0.25.10"
5-edition.workspace = true
6-license.workspace = true
7-authors.workspace = true
8-publish = false
9-
10-[dependencies]
11-ec-image = { path = "../../crates/ec-image", version = "0.1.0" }
12-
13-# The format switches the incumbent gates its decoders behind. Every format this
14-# shim serves is compiled unconditionally, so these select nothing -- they exist
15-# because a consumer naming a feature the replacement lacks fails to *resolve*,
16-# and edith's engine asks for exactly these three.
17-[features]
18-png = []
19-jpeg = []
20-webp = []
21-
22-# The surface that exists only because gpui consumes it: animation frames,
23-# their delays, and the per-format decoder types under `image::codecs`. It is
24-# not part of decoding a still picture, so a build that draws no windows does
25-# not compile it -- the way `chrono` keeps its `serde` impls behind a feature.
26-gpui = []
shims/image/src/gpui.rsdeleted+0 -438
@@ -1,438 +0,0 @@
1-//! The half of the `image` surface that exists only because gpui consumes it.
2-//!
3-//! edith's window toolkit decodes pictures through the same `image` crate the
4-//! engine does, and it reaches for animation: `Frame`, `Delay`, the
5-//! `AnimationDecoder` trait, and the per-format decoder types under
6-//! `image::codecs`. None of that belongs to a still-image decoder — it is a
7-//! consumer's shape — so it lives behind the `gpui` cargo feature, the way
8-//! `chrono` keeps its `serde` impls behind one. A build that does not draw
9-//! windows never compiles a line of it.
10-//!
11-//! Everything here is served by [`ec_image`]; nothing decodes twice.
12-
13-use std::io::Read;
14-use std::time::Duration;
15-
16-use crate::{DynamicImage, ImageError, ImageFormat, ImageResult, RgbaImage};
17-
18-/// How long one frame of an animation is shown, as a rational number of
19-/// milliseconds — upstream's `image::Delay`.
20-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21-pub struct Delay {
22- numer: u32,
23- denom: u32,
24-}
25-
26-impl Delay {
27- /// A delay of `numer / denom` milliseconds.
28- pub fn from_numer_denom_ms(numer: u32, denom: u32) -> Delay {
29- Delay { numer, denom }
30- }
31-
32- /// The delay as the pair it was built from.
33- pub fn numer_denom_ms(self) -> (u32, u32) {
34- (self.numer, self.denom)
35- }
36-}
37-
38-impl From<Delay> for Duration {
39- fn from(delay: Delay) -> Duration {
40- if delay.denom == 0 {
41- return Duration::ZERO;
42- }
43- Duration::from_nanos(u64::from(delay.numer) * 1_000_000 / u64::from(delay.denom))
44- }
45-}
46-
47-/// One picture of an animation: the whole canvas at that point, and how long
48-/// it is shown.
49-#[derive(Debug, Clone, PartialEq, Eq)]
50-pub struct Frame {
51- buffer: RgbaImage,
52- delay: Delay,
53-}
54-
55-impl Frame {
56- /// A single frame shown for no particular length of time — what a still
57- /// picture becomes when a caller wants frames.
58- pub fn new(buffer: RgbaImage) -> Frame {
59- Frame {
60- buffer,
61- delay: Delay::from_numer_denom_ms(0, 1),
62- }
63- }
64-
65- /// A frame with its own delay.
66- pub fn from_parts(buffer: RgbaImage, delay: Delay) -> Frame {
67- Frame { buffer, delay }
68- }
69-
70- /// The samples.
71- pub fn buffer(&self) -> &RgbaImage {
72- &self.buffer
73- }
74-
75- /// The samples, to be edited in place — callers swap R and B here.
76- pub fn buffer_mut(&mut self) -> &mut RgbaImage {
77- &mut self.buffer
78- }
79-
80- /// How long this frame is shown.
81- pub fn delay(&self) -> Delay {
82- self.delay
83- }
84-}
85-
86-/// The frames of an animation, as an iterator — upstream's `image::Frames`.
87-///
88-/// Upstream streams them; these decoders composite the whole animation before
89-/// the first frame is handed out, because every format we serve carries frames
90-/// that reference their predecessors anyway.
91-pub struct Frames {
92- frames: std::vec::IntoIter<ImageResult<Frame>>,
93-}
94-
95-impl Iterator for Frames {
96- type Item = ImageResult<Frame>;
97-
98- fn next(&mut self) -> Option<ImageResult<Frame>> {
99- self.frames.next()
100- }
101-}
102-
103-impl Frames {
104- fn of(frames: Vec<ImageResult<Frame>>) -> Frames {
105- Frames {
106- frames: frames.into_iter(),
107- }
108- }
109-}
110-
111-/// A decoder that can yield more than one picture.
112-pub trait AnimationDecoder {
113- /// Every frame, composited.
114- fn into_frames(self) -> Frames;
115-}
116-
117-/// A decoder of one still picture, as far as [`DynamicImage::from_decoder`] is
118-/// concerned.
119-pub trait ImageDecoder {
120- /// Decode the whole picture.
121- fn into_image(self) -> ImageResult<DynamicImage>;
122-}
123-
124-impl DynamicImage {
125- /// The picture a decoder holds.
126- pub fn from_decoder(decoder: impl ImageDecoder) -> ImageResult<DynamicImage> {
127- decoder.into_image()
128- }
129-
130- /// The image as 8-bit RGBA, by value.
131- pub fn into_rgba8(self) -> RgbaImage {
132- match self {
133- DynamicImage::ImageRgba8(buffer) => buffer,
134- other => other.to_rgba8(),
135- }
136- }
137-}
138-
139-/// The format `data` starts with, as `image::guess_format`.
140-///
141-/// Upstream errors on unrecognised bytes rather than returning `None`, and
142-/// gpui branches on that error, so this keeps the shape.
143-pub fn guess_format(data: &[u8]) -> ImageResult<ImageFormat> {
144- crate::format_of(data).ok_or_else(|| ImageError::Unsupported("unrecognised signature".into()))
145-}
146-
147-/// Decode bytes whose format the caller already knows.
148-///
149-/// The format argument only *asserts* what the bytes are; every decoder here
150-/// is chosen by signature, so a mismatch surfaces as a decode error rather
151-/// than as a wrong picture.
152-pub fn load_from_memory_with_format(data: &[u8], format: ImageFormat) -> ImageResult<DynamicImage> {
153- match crate::format_of(data) {
154- Some(found) if found == format => crate::load_from_memory(data),
155- Some(found) => Err(ImageError::Decoding(format!(
156- "asked for {format:?}, the bytes are {found:?}"
157- ))),
158- None => Err(ImageError::Unsupported("unrecognised signature".into())),
159- }
160-}
161-
162-/// Read a decoder's whole input, the way upstream's decoders do before they
163-/// parse anything.
164-fn slurp(mut reader: impl Read) -> ImageResult<Vec<u8>> {
165- let mut data = Vec::new();
166- reader.read_to_end(&mut data)?;
167- Ok(data)
168-}
169-
170-/// Every frame of an animation, as [`Frame`]s.
171-fn frames_of(data: &[u8]) -> Vec<ImageResult<Frame>> {
172- match ec_image::decode_animation(data) {
173- Err(e) => vec![Err(e.into())],
174- Ok(frames) => frames
175- .into_iter()
176- .map(|frame| {
177- let (w, h) = (frame.image.width, frame.image.height);
178- let buffer = RgbaImage::from_raw(w, h, frame.image.to_rgba8())
179- .ok_or_else(|| ImageError::Decoding("frame plane is short".into()))?;
180- // `Delay` counts milliseconds; the decoder counts seconds.
181- Ok(Frame::from_parts(
182- buffer,
183- Delay::from_numer_denom_ms(
184- frame.delay_num.saturating_mul(1000),
185- frame.delay_den.max(1),
186- ),
187- ))
188- })
189- .collect(),
190- }
191-}
192-
193-/// The per-format decoder types, under the path upstream puts them.
194-pub mod codecs {
195- /// GIF.
196- pub mod gif {
197- use super::super::{AnimationDecoder, Frames, ImageDecoder, frames_of, slurp};
198- use crate::{DynamicImage, ImageResult};
199-
200- /// A GIF decoder over bytes, as `image::codecs::gif::GifDecoder`.
201- pub struct GifDecoder {
202- data: Vec<u8>,
203- }
204-
205- impl GifDecoder {
206- /// Take the bytes; nothing is parsed until a picture is asked for.
207- pub fn new(reader: impl std::io::Read) -> ImageResult<GifDecoder> {
208- Ok(GifDecoder {
209- data: slurp(reader)?,
210- })
211- }
212- }
213-
214- impl AnimationDecoder for GifDecoder {
215- fn into_frames(self) -> Frames {
216- Frames::of(frames_of(&self.data))
217- }
218- }
219-
220- impl ImageDecoder for GifDecoder {
221- fn into_image(self) -> ImageResult<DynamicImage> {
222- crate::load_from_memory(&self.data)
223- }
224- }
225- }
226-
227- /// WebP.
228- pub mod webp {
229- use super::super::{AnimationDecoder, Frames, ImageDecoder, frames_of, slurp};
230- use crate::{DynamicImage, ImageResult, Rgba};
231-
232- /// A WebP decoder over bytes, as `image::codecs::webp::WebPDecoder`.
233- pub struct WebPDecoder {
234- data: Vec<u8>,
235- }
236-
237- impl WebPDecoder {
238- /// Take the bytes; nothing is parsed until a picture is asked for.
239- pub fn new(reader: impl std::io::Read) -> ImageResult<WebPDecoder> {
240- Ok(WebPDecoder {
241- data: slurp(reader)?,
242- })
243- }
244-
245- /// Whether the file carries more than one picture.
246- pub fn has_animation(&self) -> bool {
247- ec_image::webp::is_animated(&self.data)
248- }
249-
250- /// The colour an animation's transparent areas are composited
251- /// over.
252- ///
253- /// Frames come out with their own alpha rather than flattened
254- /// onto a colour, which is what a caller asking for a fully
255- /// transparent background wants; any other colour is refused
256- /// rather than silently ignored.
257- pub fn set_background_color(&mut self, colour: Rgba) -> ImageResult<()> {
258- match colour.0 {
259- [_, _, _, 0] => Ok(()),
260- _ => Err(crate::ImageError::Unsupported(
261- "compositing animation frames onto an opaque background".into(),
262- )),
263- }
264- }
265- }
266-
267- impl AnimationDecoder for WebPDecoder {
268- fn into_frames(self) -> Frames {
269- Frames::of(frames_of(&self.data))
270- }
271- }
272-
273- impl ImageDecoder for WebPDecoder {
274- fn into_image(self) -> ImageResult<DynamicImage> {
275- crate::load_from_memory(&self.data)
276- }
277- }
278- }
279-}
280-
281-#[cfg(test)]
282-mod tests {
283- use super::*;
284- use crate::{ImageBuffer, Rgba};
285- use std::io::Cursor;
286- use std::path::{Path, PathBuf};
287-
288- fn fixtures() -> PathBuf {
289- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
290- }
291-
292- fn bytes(name: &str) -> Option<Vec<u8>> {
293- let path = fixtures().join(name);
294- if !path.exists() {
295- eprintln!("skipped: {name} not generated; run scripts/gen-still-fixtures.sh");
296- return None;
297- }
298- Some(std::fs::read(path).expect("read fixture"))
299- }
300-
301- /// A delay is milliseconds, whatever it is written over.
302- #[test]
303- fn a_delay_converts_to_the_duration_it_names() {
304- let tenth = Delay::from_numer_denom_ms(100, 1);
305- assert_eq!(Duration::from(tenth), Duration::from_millis(100));
306- // A 1/100 s GIF tick, written as 10/1 ms.
307- let tick = Delay::from_numer_denom_ms(10, 1);
308- assert_eq!(Duration::from(tick), Duration::from_millis(10));
309- // Thirds of a millisecond survive as nanoseconds rather than rounding
310- // to zero, which is what a 30 fps animation needs.
311- let third = Delay::from_numer_denom_ms(1, 3);
312- assert_eq!(Duration::from(third), Duration::from_nanos(333_333));
313- assert_eq!(
314- Duration::from(Delay::from_numer_denom_ms(1, 0)),
315- Duration::ZERO
316- );
317- }
318-
319- /// gpui's animated-GIF path, verbatim: guess the format, take the frames,
320- /// swap each frame's red and blue in place, and read the delays back.
321- #[test]
322- fn the_gpui_gif_sequence_works() {
323- let Some(data) = bytes("animated.gif") else {
324- return;
325- };
326- assert_eq!(
327- guess_format(&data).expect("a GIF signature"),
328- ImageFormat::Gif
329- );
330-
331- let decoder = codecs::gif::GifDecoder::new(Cursor::new(&data)).expect("decoder");
332- let mut frames = Vec::new();
333- for frame in decoder.into_frames() {
334- let mut frame = frame.expect("frame");
335- for pixel in frame.buffer_mut().chunks_exact_mut(4) {
336- pixel.swap(0, 2);
337- }
338- frames.push(frame);
339- }
340- assert!(
341- frames.len() > 1,
342- "an animation decoded to {} frame(s)",
343- frames.len()
344- );
345- let (width, height) = frames[0].buffer().dimensions();
346- for frame in &frames {
347- assert_eq!(
348- frame.buffer().dimensions(),
349- (width, height),
350- "frames are composited onto one canvas"
351- );
352- assert_eq!(
353- frame.buffer().as_raw().len(),
354- (width as usize) * (height as usize) * 4
355- );
356- assert!(
357- Duration::from(frame.delay()) > Duration::ZERO,
358- "a frame with no delay would never advance"
359- );
360- }
361- }
362-
363- /// gpui's WebP path: a still goes through the decoder as one picture, an
364- /// animation through the frame iterator.
365- #[test]
366- fn the_gpui_webp_sequence_works() {
367- let Some(still) = bytes("lossless-alpha.webp") else {
368- return;
369- };
370- let mut decoder = codecs::webp::WebPDecoder::new(Cursor::new(&still)).expect("decoder");
371- assert!(!decoder.has_animation());
372- assert!(decoder.set_background_color(Rgba([0, 0, 0, 0])).is_ok());
373- let mut data = DynamicImage::from_decoder(decoder)
374- .expect("decode")
375- .into_rgba8();
376- for pixel in data.chunks_exact_mut(4) {
377- pixel.swap(0, 2);
378- }
379- let frames = [Frame::new(data)];
380- assert_eq!(
381- Duration::from(frames[0].delay()),
382- Duration::ZERO,
383- "a still has no delay"
384- );
385-
386- let Some(animated) = bytes("animated.webp") else {
387- return;
388- };
389- let decoder = codecs::webp::WebPDecoder::new(Cursor::new(&animated)).expect("decoder");
390- assert!(decoder.has_animation(), "an ANIM file read as a still");
391- let frames: Vec<Frame> = decoder
392- .into_frames()
393- .map(|frame| frame.expect("frame"))
394- .collect();
395- assert!(
396- frames.len() > 1,
397- "an animation decoded to {} frame(s)",
398- frames.len()
399- );
400- }
401-
402- /// gpui's still path for everything else, and the buffer it builds by hand
403- /// for rendered SVGs.
404- #[test]
405- fn the_gpui_still_and_svg_paths_work() {
406- let Some(data) = bytes("rgb8.png") else {
407- return;
408- };
409- let format = guess_format(&data).expect("a PNG signature");
410- assert_eq!(format, ImageFormat::Png);
411- let picture = load_from_memory_with_format(&data, format)
412- .expect("decode")
413- .into_rgba8();
414- assert_eq!(picture.dimensions(), (320, 240));
415-
416- // The SVG renderer hands over its own samples; gpui wraps them and
417- // swaps the channel order in place.
418- let mut buffer = ImageBuffer::from_raw(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]).expect("buffer");
419- for pixel in buffer.chunks_exact_mut(4) {
420- pixel.swap(0, 2);
421- }
422- assert_eq!(buffer.as_raw(), &vec![3, 2, 1, 4, 7, 6, 5, 8]);
423- let frame = Frame::new(buffer);
424- assert_eq!(frame.buffer().dimensions(), (2, 1));
425- }
426-
427- /// Bytes of no known format are an error here, not a `None` -- gpui
428- /// branches on the error to try its SVG renderer instead.
429- #[test]
430- fn unknown_bytes_are_an_error_so_the_caller_can_fall_through() {
431- assert!(guess_format(b"<svg xmlns=...>").is_err());
432- let Some(data) = bytes("rgb8.png") else {
433- return;
434- };
435- // Asserting the wrong format is a decode error, never a wrong picture.
436- assert!(load_from_memory_with_format(&data, ImageFormat::Jpeg).is_err());
437- }
438-}
shims/image/src/lib.rsdeleted+0 -488
@@ -1,488 +0,0 @@
1-//! Compatibility shim carrying the `image` name and version, over
2-//! [`ec_image`].
3-//!
4-//! Only the surface a caller in this family actually consumes is here. edith's
5-//! engine uses exactly:
6-//!
7-//! ```text
8-//! image::ImageReader::open(path)?.with_guessed_format()?.decode()?.to_rgb8()
9-//! image::ImageReader::open(path)?.with_guessed_format()?.into_dimensions()?
10-//! image::open(path)?.to_rgb8().get_pixel(x, y).0 (engine test suite)
11-//! ```
12-//!
13-//! so `ImageReader`, `DynamicImage` and the three 8-bit buffer types are the
14-//! whole shim. Anything else the upstream crate exposes is deliberately
15-//! absent, so a new use shows up as a compile error rather than as silently
16-//! different behaviour.
17-//!
18-//! **Not covered, deliberately:** the *app* crate's `RgbaImage::from_raw` /
19-//! `Frame::new` pair feeds `gpui::RenderImage`, which is typed against the
20-//! real `image` crate gpui itself depends on. Those two call sites cannot be
21-//! served by a shim — a `[patch.crates-io]` swap would retype gpui's own
22-//! dependency as well. The engine must therefore take this crate by rename
23-//! (`image = { package = "ec-image-shim", path = ... }`) or the app must keep
24-//! the real crate; the swap is not a blanket patch. See the S40 report.
25-//!
26-//! Behaviour differences from `image` 0.25.10, all consequences of the decoder
27-//! underneath and none of them reached by the surface above:
28-//!
29-//! - Only PNG, JPEG and WebP decode — the formats edith's `is_image` admits.
30-//! - EXIF orientation is parsed and exposed, not applied, exactly as upstream.
31-//! - JPEG samples may differ from upstream's by up to 4 counts of 255, an
32-//! IDCT-rounding difference the format explicitly permits; PNG and lossless
33-//! WebP are pixel-exact.
34-
35-#![forbid(unsafe_code)]
36-#![warn(missing_docs)]
37-
38-use std::fmt;
39-use std::path::Path;
40-
41-#[cfg(feature = "gpui")]
42-pub mod gpui;
43-// The names gpui writes as `image::...`; upstream has them at the crate root,
44-// so the feature's module is flattened into it.
45-#[cfg(feature = "gpui")]
46-pub use gpui::{
47- AnimationDecoder, Delay, Frame, Frames, ImageDecoder, codecs, guess_format,
48- load_from_memory_with_format,
49-};
50-/// Upstream's one generic buffer type. Every caller behind the `gpui` feature
51-/// instantiates it at RGBA8, so that is what the name means here.
52-#[cfg(feature = "gpui")]
53-pub type ImageBuffer = RgbaImage;
54-
55-/// Failure of a decode, as `image::ImageError`.
56-#[derive(Debug)]
57-pub enum ImageError {
58- /// The bytes are not a valid image of their format.
59- Decoding(String),
60- /// The format, or something in it, is not supported.
61- Unsupported(String),
62- /// Underlying I/O failure.
63- IoError(std::io::Error),
64-}
65-
66-impl fmt::Display for ImageError {
67- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68- match self {
69- ImageError::Decoding(m) => write!(f, "Format error decoding image: {m}"),
70- ImageError::Unsupported(m) => write!(f, "The image format is not supported: {m}"),
71- ImageError::IoError(e) => write!(f, "{e}"),
72- }
73- }
74-}
75-
76-impl std::error::Error for ImageError {
77- fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
78- match self {
79- ImageError::IoError(e) => Some(e),
80- _ => None,
81- }
82- }
83-}
84-
85-impl From<std::io::Error> for ImageError {
86- fn from(e: std::io::Error) -> ImageError {
87- ImageError::IoError(e)
88- }
89-}
90-
91-impl From<ec_image::Error> for ImageError {
92- fn from(e: ec_image::Error) -> ImageError {
93- match e {
94- ec_image::Error::Io(e) => ImageError::IoError(e),
95- ec_image::Error::Unsupported { what, why } => {
96- ImageError::Unsupported(format!("{what}: {why}"))
97- }
98- other => ImageError::Decoding(other.to_string()),
99- }
100- }
101-}
102-
103-/// The result of a decode, as `image::ImageResult`.
104-pub type ImageResult<T> = Result<T, ImageError>;
105-
106-/// The formats this build decodes.
107-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108-pub enum ImageFormat {
109- /// PNG.
110- Png,
111- /// JPEG.
112- Jpeg,
113- /// WebP.
114- WebP,
115- /// GIF.
116- #[cfg(feature = "gpui")]
117- Gif,
118- /// Windows bitmap.
119- #[cfg(feature = "gpui")]
120- Bmp,
121- /// TIFF.
122- #[cfg(feature = "gpui")]
123- Tiff,
124-}
125-
126-/// One 8-bit greyscale pixel.
127-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128-pub struct Luma(pub [u8; 1]);
129-/// One 8-bit R,G,B pixel.
130-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131-pub struct Rgb(pub [u8; 3]);
132-/// One 8-bit R,G,B,A pixel.
133-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134-pub struct Rgba(pub [u8; 4]);
135-
136-/// Generates the three concrete buffer types the surface uses. Upstream has
137-/// one generic `ImageBuffer`; three concrete types cover every consumed call
138-/// without dragging a pixel-trait hierarchy in behind them.
139-macro_rules! buffer {
140- ($name:ident, $pixel:ident, $channels:expr, $doc:literal) => {
141- #[doc = $doc]
142- #[derive(Debug, Clone, PartialEq, Eq)]
143- pub struct $name {
144- width: u32,
145- height: u32,
146- data: Vec<u8>,
147- }
148-
149- impl $name {
150- /// A buffer over `data`, or `None` when it is not
151- #[doc = concat!(stringify!($channels), " bytes per pixel.")]
152- pub fn from_raw(width: u32, height: u32, data: Vec<u8>) -> Option<$name> {
153- let needed = (width as usize)
154- .checked_mul(height as usize)?
155- .checked_mul($channels)?;
156- (data.len() >= needed).then_some($name {
157- width,
158- height,
159- data,
160- })
161- }
162-
163- /// `(width, height)`.
164- pub fn dimensions(&self) -> (u32, u32) {
165- (self.width, self.height)
166- }
167-
168- /// Width in pixels.
169- pub fn width(&self) -> u32 {
170- self.width
171- }
172-
173- /// Height in pixels.
174- pub fn height(&self) -> u32 {
175- self.height
176- }
177-
178- /// The pixel at `(x, y)`; panics when it is outside the image, as
179- /// upstream's does.
180- pub fn get_pixel(&self, x: u32, y: u32) -> $pixel {
181- assert!(
182- x < self.width && y < self.height,
183- "({x}, {y}) is outside a {}x{} image",
184- self.width,
185- self.height
186- );
187- let at = ((y as usize) * (self.width as usize) + x as usize) * $channels;
188- let mut pixel = [0u8; $channels];
189- pixel.copy_from_slice(&self.data[at..at + $channels]);
190- $pixel(pixel)
191- }
192-
193- /// The samples, packed.
194- pub fn as_raw(&self) -> &Vec<u8> {
195- &self.data
196- }
197-
198- /// The samples, taken by value.
199- pub fn into_raw(self) -> Vec<u8> {
200- self.data
201- }
202-
203- /// The samples as a slice.
204- pub fn into_vec(self) -> Vec<u8> {
205- self.data
206- }
207- }
208-
209- impl std::ops::Deref for $name {
210- type Target = [u8];
211- fn deref(&self) -> &[u8] {
212- &self.data
213- }
214- }
215-
216- impl std::ops::DerefMut for $name {
217- fn deref_mut(&mut self) -> &mut [u8] {
218- &mut self.data
219- }
220- }
221- };
222-}
223-
224-buffer!(GrayImage, Luma, 1, "An 8-bit greyscale image buffer.");
225-buffer!(RgbImage, Rgb, 3, "An 8-bit RGB image buffer.");
226-buffer!(RgbaImage, Rgba, 4, "An 8-bit RGBA image buffer.");
227-
228-/// A decoded image of whichever colour form its file carried.
229-#[derive(Debug, Clone, PartialEq)]
230-pub enum DynamicImage {
231- /// 8-bit greyscale.
232- ImageLuma8(GrayImage),
233- /// 8-bit RGB.
234- ImageRgb8(RgbImage),
235- /// 8-bit RGBA.
236- ImageRgba8(RgbaImage),
237-}
238-
239-impl DynamicImage {
240- fn from_decoded(image: ec_image::Image) -> DynamicImage {
241- let (w, h) = (image.width, image.height);
242- match &image.pixels {
243- ec_image::Pixels::L8(data) => DynamicImage::ImageLuma8(
244- GrayImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"),
245- ),
246- ec_image::Pixels::Rgb8(data) => DynamicImage::ImageRgb8(
247- RgbImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"),
248- ),
249- _ if image.pixels.has_alpha() => DynamicImage::ImageRgba8(
250- RgbaImage::from_raw(w, h, image.to_rgba8()).expect("plane sized by the decoder"),
251- ),
252- _ => DynamicImage::ImageRgb8(
253- RgbImage::from_raw(w, h, image.to_rgb8()).expect("plane sized by the decoder"),
254- ),
255- }
256- }
257-
258- /// `(width, height)`.
259- pub fn dimensions(&self) -> (u32, u32) {
260- match self {
261- DynamicImage::ImageLuma8(b) => b.dimensions(),
262- DynamicImage::ImageRgb8(b) => b.dimensions(),
263- DynamicImage::ImageRgba8(b) => b.dimensions(),
264- }
265- }
266-
267- /// Width in pixels.
268- pub fn width(&self) -> u32 {
269- self.dimensions().0
270- }
271-
272- /// Height in pixels.
273- pub fn height(&self) -> u32 {
274- self.dimensions().1
275- }
276-
277- /// The image as 8-bit RGB, dropping any alpha channel.
278- pub fn to_rgb8(&self) -> RgbImage {
279- let (w, h) = self.dimensions();
280- let data = match self {
281- DynamicImage::ImageRgb8(b) => return b.clone(),
282- DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l]).collect(),
283- DynamicImage::ImageRgba8(b) => b
284- .data
285- .as_chunks::<4>().0.iter()
286- .flat_map(|p| p[..3].to_vec())
287- .collect(),
288- };
289- RgbImage::from_raw(w, h, data).expect("converted plane")
290- }
291-
292- /// The image as 8-bit RGBA; opaque where the source had no alpha.
293- pub fn to_rgba8(&self) -> RgbaImage {
294- let (w, h) = self.dimensions();
295- let data = match self {
296- DynamicImage::ImageRgba8(b) => return b.clone(),
297- DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l, 255]).collect(),
298- DynamicImage::ImageRgb8(b) => b
299- .data
300- .as_chunks::<3>().0.iter()
301- .flat_map(|p| [p[0], p[1], p[2], 255])
302- .collect(),
303- };
304- RgbaImage::from_raw(w, h, data).expect("converted plane")
305- }
306-
307- /// The image as 8-bit greyscale, by the same luma weights upstream uses.
308- pub fn to_luma8(&self) -> GrayImage {
309- let (w, h) = self.dimensions();
310- let data = match self {
311- DynamicImage::ImageLuma8(b) => return b.clone(),
312- _ => self
313- .to_rgb8()
314- .data
315- .as_chunks::<3>().0.iter()
316- .map(|p| {
317- let luma =
318- 2126 * u32::from(p[0]) + 7152 * u32::from(p[1]) + 722 * u32::from(p[2]);
319- ((luma + 5000) / 10000).min(255) as u8
320- })
321- .collect(),
322- };
323- GrayImage::from_raw(w, h, data).expect("converted plane")
324- }
325-}
326-
327-/// A decoder that guesses its format from the bytes, as `image::ImageReader`.
328-///
329-/// Upstream is generic over any `BufRead + Seek`; this reads the whole file
330-/// once, because every caller in this family hands it a path and then decodes
331-/// the whole picture anyway.
332-#[derive(Debug)]
333-pub struct ImageReader {
334- data: Vec<u8>,
335- format: Option<ImageFormat>,
336-}
337-
338-impl ImageReader {
339- /// Open `path` for decoding. The format is not guessed yet.
340- pub fn open(path: impl AsRef<Path>) -> std::io::Result<ImageReader> {
341- Ok(ImageReader {
342- data: std::fs::read(path)?,
343- format: None,
344- })
345- }
346-
347- /// A reader over bytes already in memory.
348- pub fn new(data: Vec<u8>) -> ImageReader {
349- ImageReader { data, format: None }
350- }
351-
352- /// Guess the format from the leading bytes.
353- ///
354- /// Upstream returns an I/O error here because it may have to read; an
355- /// unrecognised signature is not an error at this point in either crate —
356- /// it surfaces at `decode`.
357- pub fn with_guessed_format(mut self) -> std::io::Result<ImageReader> {
358- self.format = format_of(&self.data);
359- Ok(self)
360- }
361-
362- /// The format, once guessed or set.
363- pub fn format(&self) -> Option<ImageFormat> {
364- self.format
365- }
366-
367- /// Decode the whole picture.
368- pub fn decode(self) -> ImageResult<DynamicImage> {
369- Ok(DynamicImage::from_decoded(ec_image::decode(&self.data)?))
370- }
371-
372- /// The dimensions from the header alone, without decoding the pixels.
373- pub fn into_dimensions(self) -> ImageResult<(u32, u32)> {
374- let info = ec_image::info(&self.data)?;
375- Ok((info.width, info.height))
376- }
377-}
378-
379-/// The format `data`'s leading bytes name, if this build decodes it.
380-fn format_of(data: &[u8]) -> Option<ImageFormat> {
381- match ec_image::ImageFormat::guess(data)? {
382- ec_image::ImageFormat::Png => Some(ImageFormat::Png),
383- ec_image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
384- ec_image::ImageFormat::WebP => Some(ImageFormat::WebP),
385- // Only the gpui half of this shim names the formats gpui asks for; a
386- // build without it has no variant to answer with.
387- #[cfg(feature = "gpui")]
388- ec_image::ImageFormat::Gif => Some(ImageFormat::Gif),
389- #[cfg(not(feature = "gpui"))]
390- ec_image::ImageFormat::Gif => None,
391- #[cfg(feature = "gpui")]
392- ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
393- #[cfg(not(feature = "gpui"))]
394- ec_image::ImageFormat::Bmp => None,
395- #[cfg(feature = "gpui")]
396- ec_image::ImageFormat::Tiff => Some(ImageFormat::Tiff),
397- #[cfg(not(feature = "gpui"))]
398- ec_image::ImageFormat::Tiff => None,
399- }
400-}
401-
402-/// Decode the file at `path`.
403-pub fn open(path: impl AsRef<Path>) -> ImageResult<DynamicImage> {
404- let data = std::fs::read(path)?;
405- load_from_memory(&data)
406-}
407-
408-/// Decode bytes already in memory.
409-pub fn load_from_memory(data: &[u8]) -> ImageResult<DynamicImage> {
410- Ok(DynamicImage::from_decoded(ec_image::decode(data)?))
411-}
412-
413-#[cfg(test)]
414-mod tests {
415- use super::*;
416- use std::path::PathBuf;
417-
418- fn fixtures() -> PathBuf {
419- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
420- }
421-
422- /// The exact sequence edith's engine performs, start to finish.
423- #[test]
424- fn the_engine_call_sequence_works() {
425- let path = fixtures().join("rgb8.png");
426- if !path.exists() {
427- eprintln!("skipped: fixtures/stills not generated");
428- return;
429- }
430- let reader = ImageReader::open(&path).expect("open");
431- let rgb = reader
432- .with_guessed_format()
433- .expect("guess")
434- .decode()
435- .map_err(|e| format!("{}: {e}", path.display()))
436- .expect("decode")
437- .to_rgb8();
438- let (width, height) = rgb.dimensions();
439- assert_eq!((width, height), (320, 240));
440- assert_eq!(rgb.len(), 320 * 240 * 3, "Deref reaches the samples");
441-
442- let dimensions = ImageReader::open(&path)
443- .unwrap()
444- .with_guessed_format()
445- .unwrap()
446- .into_dimensions()
447- .expect("dimensions");
448- assert_eq!(dimensions, (320, 240));
449-
450- let pixel = open(&path).expect("open").to_rgb8().get_pixel(7, 9).0;
451- assert_eq!(pixel.len(), 3);
452- }
453-
454- #[test]
455- fn a_missing_file_is_an_io_error_the_caller_can_propagate() {
456- let err = ImageReader::open(fixtures().join("nope.png")).unwrap_err();
457- assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
458- let err: ImageError = err.into();
459- assert!(matches!(err, ImageError::IoError(_)), "{err}");
460- }
461-
462- #[test]
463- fn a_file_that_is_not_an_image_fails_at_decode_not_at_guess() {
464- let reader = ImageReader::new(b"not a picture at all".to_vec())
465- .with_guessed_format()
466- .expect("guessing never fails on unknown bytes");
467- assert_eq!(reader.format(), None);
468- assert!(matches!(reader.decode(), Err(ImageError::Unsupported(_))));
469- }
470-
471- #[test]
472- fn alpha_survives_and_grey_stays_grey() {
473- let dir = fixtures();
474- if !dir.join("rgba8.png").exists() {
475- eprintln!("skipped: fixtures/stills not generated");
476- return;
477- }
478- let rgba = open(dir.join("rgba8.png")).unwrap();
479- assert!(matches!(rgba, DynamicImage::ImageRgba8(_)));
480- let grey = open(dir.join("gray8.png")).unwrap();
481- assert!(matches!(grey, DynamicImage::ImageLuma8(_)));
482- // to_rgb8 of a grey image repeats the luma into all three channels.
483- let rgb = grey.to_rgb8();
484- let p = rgb.get_pixel(3, 3).0;
485- assert_eq!(p[0], p[1]);
486- assert_eq!(p[1], p[2]);
487- }
488-}
shims/miniz_oxide/Cargo.tomldeleted+0 -11
@@ -1,11 +0,0 @@
1-[package]
2-name = "miniz_oxide"
3-description = "Compatibility shim: the miniz_oxide surface edith consumes, served by ec-inflate."
4-version = "0.8.9"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-inflate = { path = "../../crates/ec-inflate", version = "0.1.0" }
shims/miniz_oxide/src/lib.rsdeleted+0 -134
@@ -1,134 +0,0 @@
1-//! Compatibility shim carrying the `miniz_oxide` name and version, over
2-//! [`ec_inflate`].
3-//!
4-//! Only the surface a caller in this family actually consumes is here — edith's
5-//! Matroska `ContentEncodings` path uses exactly
6-//! [`inflate::decompress_to_vec_zlib_with_limit`] and the `Display` of the error
7-//! it returns. Field names, statuses and message strings match miniz_oxide
8-//! 0.8.9 so a `[patch.crates-io]` swap needs no source change; anything else the
9-//! upstream crate exposes is deliberately absent, so a new use shows up as a
10-//! compile error rather than as silently different behaviour.
11-
12-#![forbid(unsafe_code)]
13-#![warn(missing_docs)]
14-
15-/// Decompression, as `miniz_oxide::inflate`.
16-pub mod inflate {
17- use ec_inflate::Error;
18-
19- /// Return status codes, as miniz_oxide spells them.
20- #[repr(i8)]
21- #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
22- pub enum TINFLStatus {
23- /// More input was expected but the caller said there is no more.
24- FailedCannotMakeProgress = -4,
25- /// The output buffer is an invalid size.
26- BadParam = -3,
27- /// Decompression went fine but the Adler-32 did not match.
28- Adler32Mismatch = -2,
29- /// Failed to decompress due to invalid data.
30- Failed = -1,
31- /// Finished decompression without issues.
32- Done = 0,
33- /// The decompressor needs more input data to continue.
34- NeedsMoreInput = 1,
35- /// There is still pending data that did not fit in the output buffer.
36- HasMoreOutput = 2,
37- }
38-
39- /// Failure of a `decompress_to_vec*` call, with the data decoded so far.
40- #[derive(Debug)]
41- pub struct DecompressError {
42- /// Decompressor status on failure.
43- pub status: TINFLStatus,
44- /// The currently decompressed data, if any.
45- pub output: Vec<u8>,
46- }
47-
48- impl core::fmt::Display for DecompressError {
49- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50- f.write_str(match self.status {
51- TINFLStatus::FailedCannotMakeProgress => "Truncated input stream",
52- TINFLStatus::BadParam => "Invalid output buffer size",
53- TINFLStatus::Adler32Mismatch => "Adler32 checksum mismatch",
54- TINFLStatus::Failed => "Invalid input data",
55- TINFLStatus::Done => "",
56- TINFLStatus::NeedsMoreInput => "Truncated input stream",
57- TINFLStatus::HasMoreOutput => "Output size exceeded the specified limit",
58- })
59- }
60- }
61-
62- impl std::error::Error for DecompressError {}
63-
64- /// Decompress zlib-wrapped data, growing the output to at most `max_size`.
65- ///
66- /// Over the limit the error carries [`TINFLStatus::HasMoreOutput`] and the
67- /// bytes decompressed so far, as upstream does.
68- pub fn decompress_to_vec_zlib_with_limit(
69- input: &[u8],
70- max_size: usize,
71- ) -> Result<Vec<u8>, DecompressError> {
72- let mut output = Vec::new();
73- match ec_inflate::inflate_into(input, &mut output, max_size, ec_inflate::Format::Zlib) {
74- Ok(()) => Ok(output),
75- Err(error) => Err(DecompressError {
76- status: match error {
77- Error::Truncated => TINFLStatus::FailedCannotMakeProgress,
78- Error::LimitExceeded { .. } => TINFLStatus::HasMoreOutput,
79- Error::Adler32Mismatch { .. } => TINFLStatus::Adler32Mismatch,
80- Error::Corrupt { .. } | Error::Unsupported { .. } => TINFLStatus::Failed,
81- },
82- output,
83- }),
84- }
85- }
86-
87- #[cfg(test)]
88- mod tests {
89- use super::*;
90-
91- /// `zlib.compress(b"edith reads this out of a Matroska ContentEncodings block" * 4, 9)`.
92- const STREAM: [u8; 66] = [
93- 0x78, 0xda, 0xd5, 0xcb, 0xc1, 0x0d, 0x80, 0x30, 0x0c, 0x03, 0xc0, 0x55, 0xbc, 0x0b,
94- 0xe2, 0xc9, 0x10, 0xa1, 0x09, 0xb4, 0x2a, 0x8a, 0xa5, 0xc6, 0xec, 0xcf, 0x1c, 0xdc,
95- 0xff, 0xc2, 0x87, 0x3a, 0x56, 0x98, 0x17, 0xd4, 0x47, 0x81, 0xaf, 0xc0, 0x0b, 0x86,
96- 0xc3, 0xb4, 0x58, 0xd3, 0xb0, 0x31, 0x15, 0xa9, 0x3d, 0x1b, 0x7d, 0xe4, 0x5d, 0x38,
97- 0x1f, 0xb6, 0x19, 0xff, 0x89, 0x1f, 0xb5, 0xdd, 0x54, 0x95,
98- ];
99- const PLAIN: &[u8] = b"edith reads this out of a Matroska ContentEncodings block";
100-
101- /// The call site: engine/src/demux.rs, `Unpack::Zlib`.
102- #[test]
103- fn decompresses_under_the_limit() {
104- let out = decompress_to_vec_zlib_with_limit(&STREAM, 64 << 20).unwrap();
105- assert_eq!(out.len(), PLAIN.len() * 4);
106- assert_eq!(&out[..PLAIN.len()], PLAIN);
107- }
108-
109- #[test]
110- fn over_the_limit_reports_has_more_output_with_partial_data() {
111- let error = decompress_to_vec_zlib_with_limit(&STREAM, 64).unwrap_err();
112- assert_eq!(error.status, TINFLStatus::HasMoreOutput);
113- assert!(error.output.len() <= 64);
114- assert_eq!(
115- error.to_string(),
116- "Output size exceeded the specified limit"
117- );
118- }
119-
120- #[test]
121- fn a_broken_stream_reports_its_status() {
122- let mut broken = STREAM;
123- let last = broken.len() - 1;
124- broken[last] ^= 0xff;
125- let error = decompress_to_vec_zlib_with_limit(&broken, 64 << 20).unwrap_err();
126- assert_eq!(error.status, TINFLStatus::Adler32Mismatch);
127- assert_eq!(error.to_string(), "Adler32 checksum mismatch");
128-
129- let error = decompress_to_vec_zlib_with_limit(&STREAM[..20], 64 << 20).unwrap_err();
130- assert_eq!(error.status, TINFLStatus::FailedCannotMakeProgress);
131- assert_eq!(error.to_string(), "Truncated input stream");
132- }
133- }
134-}
shims/opus-rs/Cargo.tomldeleted+0 -14
@@ -1,14 +0,0 @@
1-[package]
2-name = "opus-rs"
3-description = "Compatibility shim: the opus-rs 0.1.26 surface edith consumes, served by ec-opus."
4-version = "0.1.26"
5-edition.workspace = true
6-license.workspace = true
7-authors.workspace = true
8-publish = false
9-
10-[lib]
11-name = "opus_rs"
12-
13-[dependencies]
14-ec-opus = { path = "../../crates/ec-opus", version = "0.1.0" }
shims/opus-rs/src/lib.rsdeleted+0 -462
@@ -1,462 +0,0 @@
1-//! Compatibility shim: the `opus-rs` 0.1.26 surface edith consumes, served by
2-//! [`ec_opus`].
3-//!
4-//! The incumbent this replaces encoded packets that only its own decoder read
5-//! back above ~128-165 kbps (correlation 0.06 against the reference decoder at 256 kbps on
6-//! the same signal that round-tripped internally at 0.999), and mono was
7-//! broken at every rate. This shim serves the same three-call surface —
8-//! `OpusEncoder::new(rate, channels, Application)`, the public `bitrate_bps`
9-//! and `complexity` fields, `.encode(&pcm, frame_size, &mut out)` — from the
10-//! `ec-opus` CELT encoder, which is range-exact against the family's
11-//! RFC-vector-verified decoder and the reference decoder-verified at every rate up to
12-//! 510 kbps, mono and stereo alike. The measured envelope that capped the
13-//! incumbent (`OPUS_MAX_KBPS = 128`) is obsolete behind this crate.
14-//!
15-//! `complexity` is accepted for drop-in compatibility and ignored: this
16-//! encoder has one (fast) analysis path, not a ladder.
17-//!
18-//! [`Application::Voip`] below 20 kbps, mono, 20 ms frames picks the SILK
19-//! layer, as the reference does; every other combination stays CELT. Stereo
20-//! SILK and SILK at other frame sizes fall back to CELT rather than
21-//! silently approximating it.
22-
23-#![forbid(unsafe_code)]
24-#![warn(missing_docs)]
25-
26-use std::fmt;
27-
28-/// What the encoded stream is optimised for. This CELT-only encoder spends the
29-/// setting on the coded bandwidth, not on a different coding layer.
30-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31-pub enum Application {
32- /// Speech-optimised (SILK in the reference decoder; served by CELT here).
33- Voip,
34- /// Music and general audio.
35- Audio,
36- /// Lowest-latency mode.
37- RestrictedLowdelay,
38-}
39-
40-impl From<Application> for ec_opus::Application {
41- fn from(a: Application) -> ec_opus::Application {
42- match a {
43- Application::Voip => ec_opus::Application::Voip,
44- Application::Audio => ec_opus::Application::Audio,
45- Application::RestrictedLowdelay => ec_opus::Application::LowDelay,
46- }
47- }
48-}
49-
50-/// Coded audio bandwidth, with the C API's discriminants.
51-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52-pub enum Bandwidth {
53- /// Chosen from the bitrate, the application and the input rate.
54- Auto = -1000,
55- /// 4 kHz.
56- Narrowband = 1101,
57- /// 6 kHz. CELT has no mediumband configuration; this codes as wideband.
58- Mediumband = 1102,
59- /// 8 kHz.
60- Wideband = 1103,
61- /// 12 kHz.
62- SuperWideband = 1104,
63- /// 20 kHz.
64- Fullband = 1105,
65-}
66-
67-/// The error type of this shim: a message, as the incumbent's was.
68-#[derive(Debug, Clone)]
69-pub struct OpusError(String);
70-
71-impl fmt::Display for OpusError {
72- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73- f.write_str(&self.0)
74- }
75-}
76-
77-impl std::error::Error for OpusError {}
78-
79-/// An Opus encoder with the incumbent's field-configured surface.
80-#[derive(Debug)]
81-pub struct OpusEncoder {
82- /// Target bitrate in bits per second, applied at the next
83- /// [`OpusEncoder::encode`] call.
84- pub bitrate_bps: i32,
85- /// Accepted for compatibility; this encoder has a single analysis path.
86- pub complexity: i32,
87- /// Coded bandwidth; [`Bandwidth::Auto`] follows the bitrate.
88- pub bandwidth: Bandwidth,
89- /// Constrained VBR. Off by default, as the incumbent's was.
90- pub vbr: bool,
91- inner: ec_opus::Encoder,
92- channels: usize,
93- applied_bandwidth: Bandwidth,
94- applied_vbr: bool,
95-}
96-
97-impl OpusEncoder {
98- /// An encoder at `sample_rate` (8000, 12000, 16000, 24000 or 48000) for
99- /// `channels` channels (1 or 2).
100- pub fn new(
101- sample_rate: i32,
102- channels: i32,
103- application: Application,
104- ) -> Result<OpusEncoder, OpusError> {
105- if sample_rate < 0 || channels < 0 {
106- return Err(OpusError(format!(
107- "invalid encoder arguments: {sample_rate} Hz, {channels} channels"
108- )));
109- }
110- let inner =
111- ec_opus::Encoder::new(sample_rate as u32, channels as usize, application.into())
112- .map_err(|e| OpusError(e.to_string()))?;
113- Ok(OpusEncoder {
114- bitrate_bps: 64_000 * channels,
115- complexity: 10,
116- bandwidth: Bandwidth::Auto,
117- vbr: false,
118- inner,
119- channels: channels as usize,
120- applied_bandwidth: Bandwidth::Auto,
121- applied_vbr: false,
122- })
123- }
124-
125- /// Samples of encoder delay, at the input rate: the decoded stream lags
126- /// the input by this much, and an Ogg-Opus pre-skip of it (scaled to
127- /// 48 kHz) cancels the lag exactly. Reported for the canonical 20 ms
128- /// frame (SILK and Hybrid, which shift the delay, only run at 20 ms
129- /// anyway) — like the incumbent's `OPUS_GET_LOOKAHEAD`, which doesn't
130- /// take a frame size either.
131- pub fn look_ahead(&self) -> usize {
132- self.inner.look_ahead(self.inner.sample_rate() as usize / 50)
133- }
134-
135- /// The range coder state after the last packet — the RFC 6716 Section 6
136- /// conformance hook, which a conformant decoder reproduces exactly.
137- pub fn final_range(&self) -> u32 {
138- self.inner.final_range()
139- }
140-
141- /// Encodes `frame_size` samples per channel of interleaved `f32` into
142- /// `out`, returning the packet length in bytes.
143- pub fn encode(
144- &mut self,
145- pcm: &[f32],
146- frame_size: usize,
147- out: &mut [u8],
148- ) -> Result<usize, OpusError> {
149- if pcm.len() < frame_size * self.channels {
150- return Err(OpusError(format!(
151- "{} samples is short of {} channels x {frame_size}",
152- pcm.len(),
153- self.channels
154- )));
155- }
156- self.sync_settings();
157- self.inner
158- .encode_float(pcm, frame_size, out)
159- .map_err(|e| OpusError(e.to_string()))
160- }
161-
162- /// [`OpusEncoder::encode`] from 16-bit samples.
163- pub fn encode_i16(
164- &mut self,
165- pcm: &[i16],
166- frame_size: usize,
167- out: &mut [u8],
168- ) -> Result<usize, OpusError> {
169- if pcm.len() < frame_size * self.channels {
170- return Err(OpusError(format!(
171- "{} samples is short of {} channels x {frame_size}",
172- pcm.len(),
173- self.channels
174- )));
175- }
176- self.sync_settings();
177- self.inner
178- .encode(pcm, frame_size, out)
179- .map_err(|e| OpusError(e.to_string()))
180- }
181-
182- /// Drops all inter-frame state; the next packet starts a fresh stream.
183- pub fn reset(&mut self) {
184- self.inner.reset();
185- }
186-
187- /// Pushes the public fields into the encoder before a frame.
188- fn sync_settings(&mut self) {
189- self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
190- if self.bandwidth != self.applied_bandwidth {
191- self.inner.set_bandwidth(match self.bandwidth {
192- Bandwidth::Auto => None,
193- Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow),
194- Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide),
195- Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide),
196- Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full),
197- });
198- self.applied_bandwidth = self.bandwidth;
199- }
200- if self.vbr != self.applied_vbr {
201- self.inner.set_vbr_constrained(self.vbr);
202- self.applied_vbr = self.vbr;
203- }
204- }
205-}
206-
207-/// An Opus decoder, mono or stereo.
208-#[derive(Debug)]
209-pub struct OpusDecoder {
210- inner: ec_opus::Decoder,
211-}
212-
213-impl OpusDecoder {
214- /// A decoder for `channels` channels at `sample_rate` Hz.
215- pub fn new(sample_rate: i32, channels: i32) -> Result<OpusDecoder, OpusError> {
216- if sample_rate < 0 || channels < 0 {
217- return Err(OpusError(format!(
218- "invalid decoder arguments: {sample_rate} Hz, {channels} channels"
219- )));
220- }
221- Ok(OpusDecoder {
222- inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize)
223- .map_err(|e| OpusError(e.to_string()))?,
224- })
225- }
226-
227- /// Decodes one packet into interleaved `f32`, returning samples per
228- /// channel. `frame_size` bounds the output, as the incumbent's did.
229- pub fn decode(
230- &mut self,
231- packet: &[u8],
232- frame_size: usize,
233- out: &mut [f32],
234- ) -> Result<usize, OpusError> {
235- let _ = frame_size;
236- self.inner
237- .decode_float(packet, out)
238- .map_err(|e| OpusError(e.to_string()))
239- }
240-
241- /// The range coder state after the last packet.
242- pub fn final_range(&self) -> u32 {
243- self.inner.final_range()
244- }
245-}
246-
247-/// A multichannel encoder, for the 5.1 and 7.1 exports the incumbent could not
248-/// do at all — the replica's surround Opus path today is stereo only.
249-#[derive(Debug)]
250-pub struct MultistreamEncoder {
251- /// Target bitrate in bits per second, across all streams.
252- pub bitrate_bps: i32,
253- inner: ec_opus::MultistreamEncoder,
254- channels: usize,
255-}
256-
257-impl MultistreamEncoder {
258- /// An encoder for the RFC 7845 family-1 layout of `channels` channels (1
259- /// to 8). Input is in the mapping's channel order, which for 5.1 is Vorbis
260- /// order: left, centre, right, back left, back right, LFE.
261- pub fn surround(
262- sample_rate: i32,
263- channels: usize,
264- application: Application,
265- ) -> Result<MultistreamEncoder, OpusError> {
266- if sample_rate < 0 {
267- return Err(OpusError(format!("invalid sample rate {sample_rate}")));
268- }
269- let inner =
270- ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into())
271- .map_err(|e| OpusError(e.to_string()))?;
272- Ok(MultistreamEncoder {
273- bitrate_bps: 96_000 * channels as i32 / 2,
274- inner,
275- channels,
276- })
277- }
278-
279- /// The channel mapping table the `OpusHead` for this encoder needs.
280- pub fn mapping(&self) -> &[u8] {
281- self.inner.layout().2
282- }
283-
284- /// Elementary streams, and how many of them are coupled.
285- pub fn stream_counts(&self) -> (usize, usize) {
286- let (streams, coupled, _) = self.inner.layout();
287- (streams, coupled)
288- }
289-
290- /// Encodes one frame of interleaved `f32`, returning the packet length.
291- pub fn encode(
292- &mut self,
293- pcm: &[f32],
294- frame_size: usize,
295- out: &mut [u8],
296- ) -> Result<usize, OpusError> {
297- if pcm.len() < frame_size * self.channels {
298- return Err(OpusError(format!(
299- "{} samples is short of {} channels x {frame_size}",
300- pcm.len(),
301- self.channels
302- )));
303- }
304- self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
305- self.inner
306- .encode_float(pcm, frame_size, out)
307- .map_err(|e| OpusError(e.to_string()))
308- }
309-}
310-
311-#[cfg(test)]
312-mod tests {
313- use super::*;
314-
315- /// The exact call shape edith's export path uses (export.rs:1863-1896).
316- #[test]
317- fn edith_call_shape_compiles_and_encodes() {
318- let mut encoder = OpusEncoder::new(48000, 2, Application::Audio)
319- .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))
320- .unwrap();
321- encoder.bitrate_bps = 256_000;
322- encoder.complexity = 10;
323- let frame = vec![0.1f32; 960 * 2];
324- let mut out = vec![0u8; 1500];
325- let len = encoder
326- .encode(&frame, 960, &mut out)
327- .map_err(|e| format!("Opus encode failed: {e}"))
328- .unwrap();
329- assert!(len > 2 && len <= 1276);
330- // Mono — broken at every rate in the incumbent — encodes too.
331- let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap();
332- mono.bitrate_bps = 96_000;
333- let frame = vec![0.1f32; 960];
334- let len = mono.encode(&frame, 960, &mut out).unwrap();
335- assert!(len > 2);
336- }
337-
338- fn tone(n: usize, channels: usize) -> Vec<f32> {
339- (0..n * channels)
340- .map(|i| {
341- let t = (i / channels) as f32;
342- 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin()
343- })
344- .collect()
345- }
346-
347- /// The decoder half of the surface, and the conformance hook that says the
348- /// two agree: the decoder's range state must equal the encoder's after
349- /// every packet.
350- #[test]
351- fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() {
352- const FRAME: usize = 960;
353- let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap();
354- enc.bitrate_bps = 256_000;
355- let mut dec = OpusDecoder::new(48_000, 2).unwrap();
356- let pcm = tone(FRAME * 8, 2);
357- let mut out = vec![0u8; 1500];
358- let mut back = vec![0.0f32; FRAME * 2];
359- let mut total = 0;
360- for block in pcm.as_chunks::<{ FRAME * 2 }>().0.iter() {
361- let len = enc.encode(block, FRAME, &mut out).unwrap();
362- assert!(len > 1 && len <= 1276, "packet of {len} bytes");
363- total += len;
364- assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME);
365- assert_eq!(dec.final_range(), enc.final_range());
366- }
367- // 256 kbps over 8 frames of 20 ms: the incumbent's 165 kbps ceiling is
368- // what this number exists to refute.
369- let want = 256_000 / 8 / 50 * 8;
370- assert!(
371- (total as f64 - want as f64).abs() < 0.2 * want as f64,
372- "{total} bytes vs {want} at 256 kbps"
373- );
374- }
375-
376- /// Input below 48 kHz, which the shim used to refuse outright, and the
377- /// `look_ahead` that goes with it: libopus's `OPUS_GET_LOOKAHEAD`,
378- /// `Fs/400 + Fs/250` (120 + 192 at 48 kHz), in the input rate's samples.
379- /// ffmpeg's libopus encoder runs at 48 kHz and reports 312 for every rate.
380- #[test]
381- fn slower_input_rates_encode_and_report_their_own_delay() {
382- for &(rate, frame, look) in &[
383- (48_000i32, 960usize, 312usize),
384- (24_000, 480, 156),
385- (16_000, 320, 104),
386- (12_000, 240, 78),
387- (8_000, 160, 52),
388- ] {
389- let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap();
390- enc.bitrate_bps = 32_000;
391- assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead");
392- let pcm = tone(frame * 4, 1);
393- let mut out = vec![0u8; 1500];
394- // Everything a 48 kHz decoder gets back is 48 kHz, whatever went in.
395- let mut dec = OpusDecoder::new(48_000, 1).unwrap();
396- let mut back = vec![0.0f32; 960];
397- for block in pcm.chunks_exact(frame) {
398- let len = enc.encode(block, frame, &mut out).unwrap();
399- assert!(len > 2, "{rate} Hz packet of {len} bytes");
400- assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960);
401- assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range");
402- }
403- }
404- assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err());
405- }
406-
407- /// A narrower band is a smaller top-band cost, not a refusal: forcing the
408- /// bandwidth must still produce packets a decoder reads.
409- #[test]
410- fn forced_bandwidth_and_i16_input_round_trip() {
411- const FRAME: usize = 960;
412- let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap();
413- enc.bitrate_bps = 64_000;
414- enc.bandwidth = Bandwidth::Wideband;
415- enc.vbr = true;
416- let pcm: Vec<i16> = tone(FRAME * 4, 1)
417- .iter()
418- .map(|v| (v * 16_000.0) as i16)
419- .collect();
420- let mut out = vec![0u8; 1500];
421- let mut dec = OpusDecoder::new(48_000, 1).unwrap();
422- let mut back = vec![0.0f32; FRAME];
423- for block in pcm.as_chunks::<FRAME>().0.iter() {
424- let len = enc.encode_i16(block, FRAME, &mut out).unwrap();
425- // TOC config 20..23 is wideband CELT (RFC 6716 Table 2).
426- assert_eq!(out[0] >> 3, 23, "wideband CELT config");
427- assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME);
428- assert_eq!(dec.final_range(), enc.final_range());
429- }
430- }
431-
432- /// 5.1, which the incumbent could not encode at all.
433- #[test]
434- fn surround_encodes_five_one() {
435- const FRAME: usize = 960;
436- let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap();
437- e.bitrate_bps = 384_000;
438- assert_eq!(e.stream_counts(), (4, 2));
439- assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]);
440- let pcm = tone(FRAME * 3, 6);
441- let mut out = vec![0u8; 8 * 1500];
442- for block in pcm.as_chunks::<{ FRAME * 6 }>().0.iter() {
443- assert!(e.encode(block, FRAME, &mut out).unwrap() > 8);
444- }
445- assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err());
446- }
447-
448- /// `Application::Voip` under 20 kbps, mono, 20 ms frames reaches the
449- /// SILK layer through this shim's existing surface — no new API, just
450- /// the application and bitrate the incumbent already exposed. TOC
451- /// configs 0..=11 are SILK (RFC 6716 Table 2).
452- #[test]
453- fn voip_below_20kbps_reaches_silk() {
454- let mut enc = OpusEncoder::new(48_000, 1, Application::Voip).unwrap();
455- enc.bitrate_bps = 12_000;
456- let pcm = tone(960, 1);
457- let mut out = vec![0u8; 1500];
458- let len = enc.encode(&pcm, 960, &mut out).unwrap();
459- assert!(len > 1);
460- assert!(out[0] >> 3 <= 11, "TOC config {} is not SILK", out[0] >> 3);
461- }
462-}
shims/oxideav-ac3/Cargo.tomldeleted+0 -16
@@ -1,16 +0,0 @@
1-[package]
2-name = "oxideav-ac3"
3-description = "Compatibility shim: the oxideav-ac3 surface edith consumes, over ec-ac3."
4-version = "0.0.10"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-ac3 = { path = "../../crates/ec-ac3", version = "0.1.0" }
12-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
13-oxideav-core = { path = "../oxideav-core", version = "0.1.34" }
14-
15-[dev-dependencies]
16-ec-testkit.workspace = true
shims/oxideav-ac3/src/lib.rsdeleted+0 -250
@@ -1,250 +0,0 @@
1-//! `oxideav-ac3` as edith consumes it, over [`ec_ac3`].
2-//!
3-//! A shim, not a port: it carries the incumbent's package name and version so
4-//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the
5-//! replica names — the header surface it reads a track's rate and layout out of
6-//! ([`syncinfo::parse`], [`bsi::parse`], [`eac3::bsi::parse`], `audio.rs:1954`,
7-//! `2063`) and [`register_codecs`], which is how it gets a decoder at all
8-//! (`audio.rs:2132`). The header modules are `ec_ac3`'s own: their signatures,
9-//! their entry offsets (`bsi` after the five `syncinfo()` bytes, `eac3::bsi`
10-//! after the 16-bit sync word) and their fields already match what the replica
11-//! writes, so a re-export is the whole adapter.
12-//!
13-//! Two differences are owned here rather than at the call site:
14-//!
15-//! * **Sample format.** The incumbent hands out S16 little-endian and the
16-//! replica reads it as such (`audio.rs:2160`, `chunks_exact(2)` over
17-//! `/32768.0`); `ec_ac3` decodes to `f32`. The conversion is
18-//! [`Ac3Decoder::receive_frame`], once, for every caller — which is why this
19-//! shim writes its own [`oxideav_core::Decoder`] instead of wrapping
20-//! `oxideav_core::EcDecoder`, whose job is the frames that need no
21-//! conversion.
22-//! * **Downmix request.** The incumbent takes the wanted channel count on
23-//! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the
24-//! factory translates. `Some(2)` is the A/52 §7.8 stereo fold the replica
25-//! asks for on anything wider than mono, `None` the stream's own layout.
26-//!
27-//! Encoding is not on the incumbent's own surface, so [`Ac3Encoder`] is
28-//! shaped after this family's other software encoder shim instead —
29-//! `rusty_aac::AacEncoder`'s `new`/`push_pcm_f32`/`next_packet`/
30-//! `encoder_delay` — so an export path already wired to one SW audio
31-//! encoder here can add this one the same way.
32-
33-#![forbid(unsafe_code)]
34-
35-pub use ec_ac3::{bsi, eac3, syncinfo};
36-
37-use ec_ac3::{Downmix, Options};
38-use oxideav_core::{
39- AudioFrame, CodecId, CodecInfo, CodecParameters, CodecRegistry, Decoder, Frame, Packet, Result,
40-};
41-
42-/// Register this crate's codecs — `ac3` and `eac3` — into `registry`.
43-///
44-/// Both ids reach the same decoder: it dispatches per packet on `bsid`, so the
45-/// id picks the capability set and not the syntax.
46-pub fn register_codecs(registry: &mut CodecRegistry) {
47- for id in ["ac3", "eac3"] {
48- registry.register(CodecInfo::new(CodecId::new(id)).decoder(open));
49- }
50-}
51-
52-/// A decoder for `params`, folded down to `params.channels`.
53-fn open(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
54- let options = Options {
55- downmix: match params.channels {
56- Some(1) => Downmix::Mono,
57- Some(2) => Downmix::Stereo,
58- _ => Downmix::Native,
59- },
60- ..Options::default()
61- };
62- Ok(Box::new(Ac3Decoder {
63- id: params.codec_id.clone(),
64- inner: ec_ac3::Ac3Decoder::with_options(options),
65- }))
66-}
67-
68-/// The family's AC-3 decoder: one syncframe in, one S16 little-endian frame
69-/// out.
70-struct Ac3Decoder {
71- id: CodecId,
72- inner: ec_ac3::Ac3Decoder,
73-}
74-
75-impl Decoder for Ac3Decoder {
76- fn codec_id(&self) -> &CodecId {
77- &self.id
78- }
79-
80- fn send_packet(&mut self, packet: &Packet) -> Result<()> {
81- Ok(ec_core::Decoder::send_packet(&mut self.inner, packet)?)
82- }
83-
84- fn receive_frame(&mut self) -> Result<Frame> {
85- match ec_core::Decoder::receive_frame(&mut self.inner)? {
86- ec_core::Frame::Audio(audio) => Ok(Frame::Audio(AudioFrame {
87- samples: audio.samples as u32,
88- pts: audio.pts.map(|ts| ts.ticks),
89- data: audio.data.iter().map(|plane| s16le(plane)).collect(),
90- })),
91- other => Ok(other.into()),
92- }
93- }
94-}
95-
96-/// Interleaved `f32` bytes as S16 little-endian, which is what the incumbent
97-/// speaks. Full scale is 32768 in both directions, saturating: the replica's
98-/// inverse is `/32768.0`, and a sample at or past `+1.0` has to land on
99-/// `i16::MAX` rather than wrap to silence.
100-fn s16le(samples: &[u8]) -> Vec<u8> {
101- let mut out = Vec::with_capacity(samples.len() / 2);
102- for chunk in samples.as_chunks::<4>().0 {
103- let v = f32::from_le_bytes(*chunk);
104- let scaled = (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
105- out.extend_from_slice(&scaled.to_le_bytes());
106- }
107- out
108-}
109-
110-/// How [`Ac3Encoder::new`] is configured.
111-pub struct EncoderConfig {
112- pub sample_rate: u32,
113- pub channels: u16,
114- pub bitrate_kbps: u32,
115-}
116-
117-/// An AC-3 encoder: PCM in, syncframes out.
118-pub struct Ac3Encoder(ec_ac3::Ac3Encoder);
119-
120-impl Ac3Encoder {
121- pub fn new(sample_rate: u32, channels: u16, bitrate_kbps: u32) -> Result<Ac3Encoder> {
122- Ok(Ac3Encoder(ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig {
123- sample_rate,
124- channels,
125- bitrate_kbps,
126- })?))
127- }
128-
129- /// Samples of priming delay before the first audible one; a muxer states
130- /// this on the track's edit list / codec delay.
131- pub fn encoder_delay(&self) -> usize {
132- self.0.encoder_delay()
133- }
134-
135- /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs).
136- pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> {
137- Ok(self.0.push_pcm_f32(interleaved)?)
138- }
139-
140- /// Ends the stream, padding and flushing the last frame.
141- pub fn finish(&mut self) {
142- self.0.finish();
143- }
144-
145- /// The next encoded syncframe; [`oxideav_core::Error`] with the
146- /// underlying `Eof`/`NeedMore` distinction once drained after
147- /// [`Ac3Encoder::finish`] or before enough PCM has arrived.
148- pub fn next_packet(&mut self) -> Result<Vec<u8>> {
149- Ok(self.0.next_packet()?)
150- }
151-}
152-
153-#[cfg(test)]
154-mod tests {
155- use super::*;
156-
157- #[test]
158- fn full_scale_saturates_instead_of_wrapping() {
159- let pcm: Vec<u8> = [-1.5f32, -1.0, 0.0, 0.5, 1.0, 1.5]
160- .iter()
161- .flat_map(|v| v.to_le_bytes())
162- .collect();
163- let got: Vec<i16> = s16le(&pcm)
164- .as_chunks::<2>()
165- .0
166- .iter()
167- .map(|s| i16::from_le_bytes(*s))
168- .collect();
169- assert_eq!(got, [-32768, -32768, 0, 16384, 32767, 32767]);
170- }
171-
172- #[test]
173- fn both_ids_are_registered_and_a_third_is_not() {
174- let mut registry = CodecRegistry::new();
175- register_codecs(&mut registry);
176- assert!(registry.has_decoder(&CodecId::new("ac3")));
177- assert!(registry.has_decoder(&CodecId::new("eac3")));
178- assert!(!registry.has_decoder(&CodecId::new("truehd")));
179- }
180-
181- /// One second of stereo through [`Ac3Encoder`], then back through this
182- /// shim's own decoder: after dropping the encoder's priming delay, the
183- /// two channels should still correlate almost perfectly with the source.
184- #[test]
185- fn encode_then_decode_round_trips() {
186- let sample_rate = 48000u32;
187- let seconds = 1.0f32;
188- let n = (sample_rate as f32 * seconds) as usize;
189- let mut pcm = vec![0.0f32; n * 2];
190- for i in 0..n {
191- let t = i as f32 / sample_rate as f32;
192- pcm[2 * i] = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
193- pcm[2 * i + 1] = 0.4 * (2.0 * std::f32::consts::PI * 660.0 * t).sin();
194- }
195-
196- let mut enc = Ac3Encoder::new(sample_rate, 2, 192).unwrap();
197- enc.push_pcm_f32(&pcm).unwrap();
198- enc.finish();
199- let mut bitstream = Vec::new();
200- while let Ok(packet) = enc.next_packet() {
201- bitstream.extend_from_slice(&packet);
202- }
203-
204- let mut registry = CodecRegistry::new();
205- register_codecs(&mut registry);
206- let params = CodecParameters {
207- channels: Some(2),
208- ..CodecParameters::audio(CodecId::new("ac3"))
209- };
210- let mut dec = registry.first_decoder(&params).unwrap();
211-
212- let mut decoded_s16: Vec<i16> = Vec::new();
213- let mut offset = 0;
214- while offset < bitstream.len() {
215- let len = ec_ac3::frame_size(&bitstream[offset..]).unwrap();
216- let packet = oxideav_core::Packet::new(
217- 0,
218- oxideav_core::TimeBase::new(1, sample_rate.into()),
219- bitstream[offset..offset + len].to_vec(),
220- );
221- dec.send_packet(&packet).unwrap();
222- offset += len;
223- while let Ok(Frame::Audio(frame)) = dec.receive_frame() {
224- for plane in &frame.data {
225- decoded_s16.extend(plane.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)));
226- }
227- }
228- }
229- let decoded: Vec<f32> = decoded_s16.iter().map(|&s| s as f32 / 32768.0).collect();
230-
231- // Drop the encoder's priming delay (one block, both channels).
232- let delay = enc.encoder_delay() * 2;
233- let decoded = &decoded[delay.min(decoded.len())..];
234- let source = &pcm[..decoded.len().min(pcm.len())];
235- let decoded = &decoded[..source.len()];
236-
237- let mean_s = source.iter().sum::<f32>() / source.len() as f32;
238- let mean_d = decoded.iter().sum::<f32>() / decoded.len() as f32;
239- let mut num = 0.0f64;
240- let (mut den_s, mut den_d) = (0.0f64, 0.0f64);
241- for (&s, &d) in source.iter().zip(decoded.iter()) {
242- let (s, d) = ((s - mean_s) as f64, (d - mean_d) as f64);
243- num += s * d;
244- den_s += s * s;
245- den_d += d * d;
246- }
247- let corr = num / (den_s.sqrt() * den_d.sqrt());
248- assert!(corr >= 0.99, "round-trip correlation too low: {corr}");
249- }
250-}
shims/oxideav-ac3/tests/edith_surface.rsdeleted+0 -137
@@ -1,137 +0,0 @@
1-//! The AC-3 path exactly as the replica drives it: read the rate and the
2-//! layout out of the first syncframe's headers, ask the registry for a decoder
3-//! folded to that layout, decode, and read the frame back as S16 little-endian
4-//! (`engine/src/audio.rs:1954-2170`).
5-
6-use oxideav_ac3::{bsi, eac3, register_codecs, syncinfo};
7-use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Error, Frame, Packet, TimeBase};
8-
9-fn fixture(name: &str) -> Vec<u8> {
10- std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture")
11-}
12-
13-/// `engine/src/audio.rs:2130` — a fresh decoder out of a fresh registry.
14-fn ac3_decoder(codec: &str, channels: Option<u16>) -> Box<dyn Decoder> {
15- let mut registry = CodecRegistry::new();
16- register_codecs(&mut registry);
17- let mut params = CodecParameters::audio(CodecId::new(codec));
18- params.channels = channels;
19- registry.first_decoder(&params).expect("no AC-3 decoder")
20-}
21-
22-/// `engine/src/audio.rs:2150` — one syncframe in, interleaved `f32` and the
23-/// frames per channel out; `None` when the decoder wants more input.
24-fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> Option<(Vec<f32>, u64)> {
25- let packet = Packet::new(0, TimeBase::new(1, 48_000), bytes.to_vec());
26- decoder.send_packet(&packet).expect("AC-3 decode failed");
27- match decoder.receive_frame() {
28- Ok(Frame::Audio(audio)) => Some((
29- audio.data[0]
30- .as_chunks::<2>()
31- .0
32- .iter()
33- .map(|s| f32::from(i16::from_le_bytes(*s)) / 32768.0)
34- .collect(),
35- u64::from(audio.samples),
36- )),
37- Ok(other) => panic!("AC-3 decoder handed back {other:?}"),
38- Err(Error::NeedMore) => None,
39- Err(e) => panic!("AC-3 decode failed: {e:?}"),
40- }
41-}
42-
43-/// `engine/src/audio.rs:2061` — rate and `nfchans` out of the bit stream,
44-/// whichever syntax it is.
45-fn header(codec: &str, frame: &[u8]) -> (u32, usize) {
46- if codec == "eac3" {
47- let bsi = eac3::bsi::parse(frame.get(2..).unwrap_or_default()).expect("E-AC-3 bsi");
48- (bsi.sample_rate, bsi.nfchans)
49- } else {
50- let sync = syncinfo::parse(frame).expect("AC-3 syncinfo");
51- let bsi = bsi::parse(frame.get(5..).unwrap_or_default()).expect("AC-3 bsi");
52- (sync.sample_rate, bsi.nfchans)
53- }
54-}
55-
56-fn rms(pcm: &[f32]) -> f64 {
57- (pcm.iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>() / pcm.len().max(1) as f64).sqrt()
58-}
59-
60-/// Every generated layout, opened the way a timeline source is opened: wider
61-/// than mono folds to stereo, mono stays mono, and neither decodes to silence
62-/// (the replica's mono `corner-cut` exists because the incumbent did).
63-#[test]
64-fn the_replicas_open_path_lands_on_audible_pcm() {
65- let cases = [
66- ("ac3-5.1-48000.ac3", "ac3", 48_000, 5, 2),
67- ("ac3-stereo-48000.ac3", "ac3", 48_000, 2, 2),
68- ("ac3-mono-44100.ac3", "ac3", 44_100, 1, 1),
69- ("eac3-5.1-48000.eac3", "eac3", 48_000, 5, 2),
70- ("eac3-mono-48000.eac3", "eac3", 48_000, 1, 1),
71- ];
72- for (name, codec, rate, nfchans_want, channels_want) in cases {
73- let data = fixture(name);
74-
75- let (sample_rate, nfchans) = header(codec, &data);
76- assert_eq!(sample_rate, rate, "{name}: sample rate");
77- assert_eq!(nfchans, nfchans_want, "{name}: nfchans");
78-
79- let requested = (nfchans > 1).then_some(2);
80- let mut decoder = ac3_decoder(codec, requested);
81- let (pcm, samples) = decode_ac3(&mut decoder, &data).expect("the first syncframe decoded");
82- let channels = (pcm.len() as u64 / samples.max(1)) as u16;
83- assert_eq!(channels, channels_want, "{name}: decoded channels");
84- assert!(samples > 0, "{name}: no samples");
85- assert!(rms(&pcm) > 1e-3, "{name}: decoded to silence, rms {}", rms(&pcm));
86-
87- // The replica then feeds the rest of the stream frame by frame; a
88- // second frame proves the packet walk does not desync on the shim's
89- // conversion.
90- let size = ec_ac3::frame_size(&data).expect("frame size");
91- if let Some(next) = data.get(size..).filter(|rest| rest.len() > size) {
92- let (pcm, samples) = decode_ac3(&mut decoder, next).expect("the second syncframe");
93- assert_eq!((pcm.len() as u64 / samples.max(1)) as u16, channels_want);
94- }
95- }
96-}
97-
98-/// A packet holding two or three syncframes, handed over the registry's
99-/// decoder the way the replica hands it packets: one call, one output frame.
100-/// The samples are the frames decoded one at a time, back to back.
101-#[test]
102-fn a_packet_of_two_and_three_syncframes_decodes_to_its_frames() {
103- let cases = [
104- ("ac3-5.1-48000.ac3", "ac3", Some(2)),
105- ("eac3-5.1-48000.eac3", "eac3", Some(2)),
106- ];
107- for (name, codec, requested) in cases {
108- let data = fixture(name);
109- let mut frames = Vec::new();
110- let mut pos = 0;
111- while let Ok(len) = ec_ac3::frame_size(&data[pos..]) {
112- frames.push(&data[pos..pos + len]);
113- pos += len;
114- if frames.len() == 3 {
115- break;
116- }
117- }
118- assert_eq!(frames.len(), 3, "{name}: three syncframes");
119-
120- let mut single = ac3_decoder(codec, requested);
121- let mut reference = Vec::new();
122- let mut reference_samples = 0;
123- for frame in &frames {
124- let (pcm, samples) = decode_ac3(&mut single, frame).expect("one frame");
125- reference.extend(pcm);
126- reference_samples += samples;
127- }
128-
129- for n in [2usize, 3] {
130- let mut decoder = ac3_decoder(codec, requested);
131- let packet: Vec<u8> = frames[..n].concat();
132- let (pcm, samples) = decode_ac3(&mut decoder, &packet).expect("the packet decodes");
133- assert_eq!(samples, reference_samples / 3 * n as u64, "{name}: {n} frames, samples");
134- assert_eq!(pcm, reference[..pcm.len()], "{name}: {n} frames, PCM");
135- }
136- }
137-}
shims/oxideav-ass/Cargo.tomldeleted+0 -13
@@ -1,13 +0,0 @@
1-[package]
2-name = "oxideav-ass"
3-description = "Compatibility shim: the oxideav-ass surface edith consumes, over ec-ass."
4-version = "0.0.9"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-ass = { path = "../../crates/ec-ass", version = "0.1.0" }
12-ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" }
13-oxideav-core = { path = "../oxideav-core", version = "0.1.34" }
shims/oxideav-ass/src/lib.rsdeleted+0 -37
@@ -1,37 +0,0 @@
1-//! `oxideav-ass` as edith consumes it, over [`ec_ass`].
2-//!
3-//! One item: `parse`, answering the same [`SubtitleTrack`] the SubRip and
4-//! WebVTT parsers do — the replica hands all three around as one function
5-//! pointer type and reads `cues`, `segments` and `plain_text` off the result.
6-
7-#![forbid(unsafe_code)]
8-
9-use oxideav_core::Result;
10-
11-pub use ec_subs::ir::{
12- CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign,
13-};
14-
15-/// Parse an ASS or SSA script.
16-pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
17- Ok(ec_ass::parse(bytes)?)
18-}
19-
20-#[cfg(test)]
21-mod tests {
22- use super::*;
23-
24- #[test]
25- fn a_script_parses_through_the_shim() {
26- type Parse = fn(&[u8]) -> Result<SubtitleTrack>;
27- let parse: Parse = parse;
28- let doc = "[Events]\n\
29- Format: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\
30- Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi{\\i0}\\Nthere\n";
31- let track = parse(doc.as_bytes()).unwrap();
32- assert_eq!(track.cues.len(), 1);
33- assert_eq!(track.cues[0].start_us, 1_000_000);
34- assert_eq!(ec_subs::plain_text(&track.cues[0].segments), "hi\nthere");
35- assert!(!parse(b"not a script").unwrap_err().to_string().is_empty());
36- }
37-}
shims/oxideav-core/Cargo.tomldeleted+0 -11
@@ -1,11 +0,0 @@
1-[package]
2-name = "oxideav-core"
3-description = "Compatibility shim: the oxideav-core surface edith consumes, over ec-core."
4-version = "0.1.34"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
shims/oxideav-core/src/lib.rsdeleted+0 -503
@@ -1,503 +0,0 @@
1-//! `oxideav-core` as edith consumes it, over [`ec_core`].
2-//!
3-//! A shim, not a port: it carries the incumbent's package name and version so a
4-//! swap is a `[patch.crates-io]` line and nothing else, and it exposes exactly
5-//! the items the replica names — no more, because an item nobody calls is an
6-//! item nobody can check. The list, and where each is called from, is in the
7-//! subtitle and export paths of the engine: `Packet::new`, `TimeBase::new`,
8-//! `Error::NeedMore`, `CodecId`, `CodecParameters::{audio,subtitle}`,
9-//! `CodecRegistry`, `Decoder`, `Frame`, `Muxer`, `StreamInfo`, `Result`.
10-//!
11-//! Where the two IRs differ in *shape* the shim owns the difference:
12-//! `oxideav`'s codec id is a string and `ec_core`'s is an enum, its frames own
13-//! their bytes and `ec_core`'s share a refcounted buffer. Those are converted
14-//! here, once, rather than at every call site of the replica.
15-//!
16-//! [`Packet`] and [`TimeBase`] are `ec_core`'s own: their signatures already
17-//! match what the replica writes, so a re-export is the whole adapter.
18-
19-#![forbid(unsafe_code)]
20-
21-use std::collections::HashMap;
22-use std::fmt;
23-
24-pub use ec_core::{Packet, TimeBase};
25-
26-/// What a call into this family can go wrong with.
27-///
28-/// `NeedMore` is load-bearing: the replica's AC-3 path treats it as "not an
29-/// error, feed me another packet" and everything else as a failure.
30-#[derive(Debug)]
31-#[non_exhaustive]
32-pub enum Error {
33- /// The decoder wants another packet before it can hand back a frame.
34- NeedMore,
35- /// End of stream.
36- Eof,
37- /// Well-formed but not supported.
38- Unsupported(String),
39- /// Malformed input.
40- InvalidData(String),
41- /// No codec in the registry claims these parameters.
42- CodecNotFound(String),
43- /// Underlying I/O.
44- Io(std::io::Error),
45- /// Anything else.
46- Other(String),
47-}
48-
49-impl fmt::Display for Error {
50- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51- match self {
52- Error::NeedMore => write!(f, "more input needed"),
53- Error::Eof => write!(f, "end of stream"),
54- Error::Unsupported(what) => write!(f, "unsupported: {what}"),
55- Error::InvalidData(what) => write!(f, "invalid data: {what}"),
56- Error::CodecNotFound(id) => write!(f, "no codec {id}"),
57- Error::Io(e) => write!(f, "{e}"),
58- Error::Other(what) => write!(f, "{what}"),
59- }
60- }
61-}
62-
63-impl std::error::Error for Error {}
64-
65-impl From<std::io::Error> for Error {
66- fn from(e: std::io::Error) -> Error {
67- Error::Io(e)
68- }
69-}
70-
71-impl From<ec_core::Error> for Error {
72- fn from(e: ec_core::Error) -> Error {
73- match e {
74- ec_core::Error::NeedMore => Error::NeedMore,
75- ec_core::Error::Eof => Error::Eof,
76- ec_core::Error::Unsupported { what, why } => {
77- Error::Unsupported(format!("{what}: {why}"))
78- }
79- ec_core::Error::Corrupt { context } => Error::InvalidData(context),
80- ec_core::Error::Io(e) => Error::Io(e),
81- }
82- }
83-}
84-
85-/// This family's result.
86-pub type Result<T> = std::result::Result<T, Error>;
87-
88-/// A codec's identifier, as a string: `"ac3"`, `"pgs"`, `"vorbis"`.
89-#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
90-pub struct CodecId(pub String);
91-
92-impl CodecId {
93- /// The id named by `s`.
94- pub fn new(s: impl Into<String>) -> CodecId {
95- CodecId(s.into())
96- }
97-
98- /// The name itself.
99- pub fn as_str(&self) -> &str {
100- &self.0
101- }
102-
103- /// The `ec_core` codec this names, when the family carries it.
104- pub fn to_ec(&self) -> Option<ec_core::CodecId> {
105- use ec_core::CodecId::*;
106- Some(match self.0.as_str() {
107- "h264" | "avc1" => H264,
108- "h265" | "hevc" => H265,
109- "vp8" => Vp8,
110- "vp9" => Vp9,
111- "av1" => Av1,
112- "aac" => Aac,
113- "ac3" => Ac3,
114- "eac3" => EAc3,
115- "alac" => Alac,
116- "flac" => Flac,
117- "mp3" => Mp3,
118- "opus" => Opus,
119- "vorbis" => Vorbis,
120- "srt" | "subrip" => Srt,
121- "webvtt" | "vtt" => WebVtt,
122- "ass" | "ssa" => Ass,
123- "pgs" => Pgs,
124- "tx3g" => Tx3g,
125- _ => return None,
126- })
127- }
128-}
129-
130-impl fmt::Display for CodecId {
131- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132- f.write_str(&self.0)
133- }
134-}
135-
136-impl From<&str> for CodecId {
137- fn from(s: &str) -> CodecId {
138- CodecId(s.to_owned())
139- }
140-}
141-
142-impl From<String> for CodecId {
143- fn from(s: String) -> CodecId {
144- CodecId(s)
145- }
146-}
147-
148-/// What kind of stream a set of parameters describes.
149-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
150-pub enum MediaType {
151- /// Audio samples.
152- Audio,
153- /// Video pictures.
154- Video,
155- /// Timed text or subtitle bitmaps.
156- Subtitle,
157- /// Opaque payload.
158- Data,
159- /// Not yet determined.
160- #[default]
161- Unknown,
162-}
163-
164-/// Everything a decoder is told before its first packet.
165-#[derive(Clone, Debug, Default, PartialEq, Eq)]
166-pub struct CodecParameters {
167- /// Which codec.
168- pub codec_id: CodecId,
169- /// Which kind of stream.
170- pub media_type: MediaType,
171- /// Audio sample rate.
172- pub sample_rate: Option<u32>,
173- /// Audio channel count — the replica asks for `Some(2)` to get a downmix.
174- pub channels: Option<u16>,
175- /// Coded width.
176- pub width: Option<u32>,
177- /// Coded height.
178- pub height: Option<u32>,
179- /// Codec setup bytes.
180- pub extradata: Vec<u8>,
181-}
182-
183-impl CodecParameters {
184- /// Audio parameters for `codec_id`.
185- pub fn audio(codec_id: CodecId) -> CodecParameters {
186- CodecParameters {
187- codec_id,
188- media_type: MediaType::Audio,
189- ..CodecParameters::default()
190- }
191- }
192-
193- /// Video parameters for `codec_id`.
194- pub fn video(codec_id: CodecId) -> CodecParameters {
195- CodecParameters {
196- codec_id,
197- media_type: MediaType::Video,
198- ..CodecParameters::default()
199- }
200- }
201-
202- /// Subtitle parameters for `codec_id`.
203- pub fn subtitle(codec_id: CodecId) -> CodecParameters {
204- CodecParameters {
205- codec_id,
206- media_type: MediaType::Subtitle,
207- ..CodecParameters::default()
208- }
209- }
210-
211- /// Data-stream parameters for `codec_id`.
212- pub fn data(codec_id: CodecId) -> CodecParameters {
213- CodecParameters {
214- codec_id,
215- media_type: MediaType::Data,
216- ..CodecParameters::default()
217- }
218- }
219-}
220-
221-/// One stream of a container, as a muxer is told about it.
222-#[derive(Clone, Debug, PartialEq, Eq)]
223-pub struct StreamInfo {
224- /// Index the stream's packets carry.
225- pub index: u32,
226- /// The unit its timestamps are in.
227- pub time_base: TimeBase,
228- /// Duration in `time_base` ticks.
229- pub duration: Option<i64>,
230- /// First timestamp in `time_base` ticks.
231- pub start_time: Option<i64>,
232- /// What is in it.
233- pub params: CodecParameters,
234-}
235-
236-/// One decoded picture.
237-///
238-/// No dimensions: the incumbent states them on the stream's
239-/// [`CodecParameters`] and puts only the row stride on the plane, and a codec
240-/// crate outside this workspace writes the literal (`oxideav-h265`'s decoder
241-/// does), so the field list is the incumbent's and not ours to improve.
242-#[derive(Clone, Debug, Default, PartialEq, Eq)]
243-pub struct VideoFrame {
244- /// Presentation time in the stream's time base.
245- pub pts: Option<i64>,
246- /// One plane per component group; packed formats have exactly one.
247- pub planes: Vec<VideoPlane>,
248-}
249-
250-/// One plane of a [`VideoFrame`].
251-#[derive(Clone, Debug, Default, PartialEq, Eq)]
252-pub struct VideoPlane {
253- /// Bytes between the starts of two rows.
254- pub stride: usize,
255- /// The plane's bytes.
256- pub data: Vec<u8>,
257-}
258-
259-/// One decoded block of audio.
260-#[derive(Clone, Debug, Default, PartialEq, Eq)]
261-pub struct AudioFrame {
262- /// Frames per channel in this block.
263- pub samples: u32,
264- /// Presentation time in the stream's time base.
265- pub pts: Option<i64>,
266- /// Interleaved (one entry) or planar (one entry per channel) bytes.
267- pub data: Vec<Vec<u8>>,
268-}
269-
270-/// What a decoder hands back.
271-#[derive(Clone, Debug, PartialEq, Eq)]
272-pub enum Frame {
273- /// A picture.
274- Video(VideoFrame),
275- /// An audio block.
276- Audio(AudioFrame),
277-}
278-
279-impl From<ec_core::Frame> for Frame {
280- fn from(frame: ec_core::Frame) -> Frame {
281- match frame {
282- ec_core::Frame::Video(video) => Frame::Video(VideoFrame {
283- pts: video.pts.map(|t| t.ticks),
284- planes: video
285- .planes
286- .into_iter()
287- .map(|plane| VideoPlane {
288- stride: plane.stride,
289- data: plane.data.to_vec(),
290- })
291- .collect(),
292- }),
293- ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame {
294- samples: audio.samples as u32,
295- pts: audio.pts.map(|t| t.ticks),
296- data: audio.data.iter().map(|buf| buf.to_vec()).collect(),
297- }),
298- }
299- }
300-}
301-
302-/// A decoder: packets in, frames out.
303-pub trait Decoder: Send {
304- /// The codec this decodes.
305- fn codec_id(&self) -> &CodecId;
306-
307- /// Feed one packet.
308- fn send_packet(&mut self, packet: &Packet) -> Result<()>;
309-
310- /// Take one frame, or [`Error::NeedMore`] when the decoder wants another
311- /// packet first.
312- fn receive_frame(&mut self) -> Result<Frame>;
313-
314- /// Signal end of input, so whatever is held back becomes available through
315- /// [`receive_frame`](Decoder::receive_frame) and then [`Error::Eof`].
316- ///
317- /// The default is for a decoder that holds nothing back — one packet in,
318- /// one frame out, which is what the AC-3 path is.
319- fn flush(&mut self) -> Result<()> {
320- Ok(())
321- }
322-}
323-
324-/// A container writer.
325-pub trait Muxer: Send {
326- /// The format's short name.
327- fn format_name(&self) -> &str;
328-
329- /// Write whatever precedes the first packet.
330- fn write_header(&mut self) -> Result<()>;
331-
332- /// Write one packet.
333- fn write_packet(&mut self, packet: &Packet) -> Result<()>;
334-
335- /// Write whatever follows the last one.
336- fn write_trailer(&mut self) -> Result<()>;
337-}
338-
339-/// How a codec crate hands out decoders.
340-pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>;
341-
342-/// One codec's registration.
343-#[derive(Clone)]
344-pub struct CodecInfo {
345- /// The id this claims.
346- pub id: CodecId,
347- /// How to build a decoder for it.
348- pub decoder_factory: Option<DecoderFactory>,
349-}
350-
351-impl CodecInfo {
352- /// An empty registration for `id`.
353- pub fn new(id: CodecId) -> CodecInfo {
354- CodecInfo {
355- id,
356- decoder_factory: None,
357- }
358- }
359-
360- /// The same registration, with a decoder.
361- pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo {
362- self.decoder_factory = Some(factory);
363- self
364- }
365-}
366-
367-/// The codecs a caller has registered, in registration order per id.
368-///
369-/// The replica builds one of these per AC-3 segment, registers that crate's
370-/// codecs into it and asks for the first decoder that claims the parameters.
371-#[derive(Clone, Default)]
372-pub struct CodecRegistry {
373- by_id: HashMap<CodecId, Vec<CodecInfo>>,
374-}
375-
376-impl CodecRegistry {
377- /// An empty registry.
378- pub fn new() -> CodecRegistry {
379- CodecRegistry::default()
380- }
381-
382- /// Add one codec.
383- pub fn register(&mut self, info: CodecInfo) {
384- self.by_id.entry(info.id.clone()).or_default().push(info);
385- }
386-
387- /// True when something registered can decode `id`.
388- pub fn has_decoder(&self, id: &CodecId) -> bool {
389- self.by_id
390- .get(id)
391- .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some()))
392- }
393-
394- /// A decoder from the first registration that offers one.
395- pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> {
396- let factory = self
397- .by_id
398- .get(&params.codec_id)
399- .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory))
400- .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?;
401- factory(params)
402- }
403-}
404-
405-/// A [`Decoder`] over one of the family's own, converting the frames on the way
406-/// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap.
407-pub struct EcDecoder {
408- id: CodecId,
409- inner: Box<dyn ec_core::Decoder>,
410-}
411-
412-impl EcDecoder {
413- /// Wrap `inner`, which decodes the codec named `id`.
414- pub fn new(id: CodecId, inner: Box<dyn ec_core::Decoder>) -> EcDecoder {
415- EcDecoder { id, inner }
416- }
417-}
418-
419-impl Decoder for EcDecoder {
420- fn codec_id(&self) -> &CodecId {
421- &self.id
422- }
423-
424- fn send_packet(&mut self, packet: &Packet) -> Result<()> {
425- Ok(self.inner.send_packet(packet)?)
426- }
427-
428- fn receive_frame(&mut self) -> Result<Frame> {
429- Ok(self.inner.receive_frame()?.into())
430- }
431-}
432-
433-#[cfg(test)]
434-mod tests {
435- use super::*;
436-
437- /// A decoder that answers one frame per packet, for the registry test.
438- struct Stub(CodecId);
439-
440- impl Decoder for Stub {
441- fn codec_id(&self) -> &CodecId {
442- &self.0
443- }
444-
445- fn send_packet(&mut self, _packet: &Packet) -> Result<()> {
446- Ok(())
447- }
448-
449- fn receive_frame(&mut self) -> Result<Frame> {
450- Err(Error::NeedMore)
451- }
452- }
453-
454- fn stub(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
455- Ok(Box::new(Stub(params.codec_id.clone())))
456- }
457-
458- #[test]
459- fn the_registry_hands_back_what_was_registered_and_names_what_was_not() {
460- let mut registry = CodecRegistry::new();
461- registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub));
462- let params = CodecParameters::audio(CodecId::new("ac3"));
463- let mut decoder = registry.first_decoder(&params).unwrap();
464- assert_eq!(decoder.codec_id().as_str(), "ac3");
465- assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore)));
466- assert!(registry.has_decoder(&CodecId::new("ac3")));
467-
468- let missing = CodecParameters::audio(CodecId::new("truehd"));
469- assert!(matches!(
470- registry.first_decoder(&missing),
471- Err(Error::CodecNotFound(id)) if id == "truehd"
472- ));
473- }
474-
475- #[test]
476- fn frames_and_errors_cross_the_boundary_intact() {
477- let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4);
478- let video =
479- ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap();
480- let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else {
481- panic!("a video frame stays a video frame");
482- };
483- assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]);
484- assert_eq!(frame.planes[0].stride, 4);
485-
486- // The one error the replica matches on by name.
487- assert!(matches!(
488- Error::from(ec_core::Error::NeedMore),
489- Error::NeedMore
490- ));
491- assert_eq!(
492- Error::from(ec_core::Error::corrupt("torn")).to_string(),
493- "invalid data: torn"
494- );
495- }
496-
497- #[test]
498- fn a_packet_is_written_the_way_the_replica_writes_one() {
499- let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]);
500- assert_eq!(packet.data.len(), 8);
501- assert_eq!(packet.time_base, TimeBase::new(1, 90_000));
502- }
503-}
shims/oxideav-ogg/Cargo.tomldeleted+0 -13
@@ -1,13 +0,0 @@
1-[package]
2-name = "oxideav-ogg"
3-description = "Compatibility shim: the oxideav-ogg mux surface edith consumes, over ec-ogg."
4-version = "0.1.8"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
12-ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" }
13-oxideav-core = { path = "../oxideav-core", version = "0.1.34" }
shims/oxideav-ogg/src/lib.rsdeleted+0 -28
@@ -1,28 +0,0 @@
1-//! `oxideav-ogg` as edith consumes it, over [`ec_ogg`].
2-//!
3-//! A shim, not a port: it carries the incumbent's package name and version so
4-//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the
5-//! replica names — `mux::xiph_lace`, `mux::open_concrete`, and the concrete
6-//! muxer's `set_page_target_bytes` beside the `oxideav_core::Muxer` methods
7-//! (`export.rs:2942,2957,2961`).
8-//!
9-//! One semantic difference is owned here rather than at the call site. The
10-//! replica states a packet's *granule position* — where it ends — in the
11-//! packet's `pts`, because that is what the incumbent's muxer wrote onto the
12-//! page; `ec_ogg` keeps `pts` meaning presentation start and carries granule
13-//! positions in side data ([`ec_ogg::granule_side_data`]). The translation is
14-//! [`mux::OggMuxer::write_packet`], once, for every caller.
15-
16-#![forbid(unsafe_code)]
17-
18-use std::io::{Seek, Write};
19-
20-/// A sink an Ogg file can be written to. The incumbent puts this trait in
21-/// `oxideav-core`; nothing in the replica names it directly (it only ever
22-/// passes a `Box::new(File::create(..)?)`), so it lives here until the atomic
23-/// oxideav swap decides where the family keeps it.
24-pub trait WriteSeek: Write + Seek + Send {}
25-
26-impl<T: Write + Seek + Send> WriteSeek for T {}
27-
28-pub mod mux;
shims/oxideav-ogg/src/mux.rsdeleted+0 -90
@@ -1,90 +0,0 @@
1-//! The muxing half — the only half the replica calls.
2-
3-use ec_core::Muxer as _;
4-use ec_ogg::granule_side_data;
5-use oxideav_core::{Error, Muxer, Packet, Result, StreamInfo};
6-
7-use crate::WriteSeek;
8-
9-/// Lace header packets into the `extradata` form Vorbis setup data travels in:
10-/// [`None`] when they cannot be described that way.
11-pub fn xiph_lace(packets: &[&[u8]]) -> Option<Vec<u8>> {
12- ec_ogg::xiph_lace(packets)
13-}
14-
15-/// Open a writer over `output` with `streams` already declared.
16-pub fn open_concrete(output: Box<dyn WriteSeek>, streams: &[StreamInfo]) -> Result<OggMuxer> {
17- let mut inner = ec_ogg::OggMuxer::new(output);
18- for stream in streams {
19- inner.add_stream(to_ec_stream(stream)?)?;
20- }
21- Ok(OggMuxer { inner })
22-}
23-
24-/// The concrete muxer, so callers reach [`OggMuxer::set_page_target_bytes`]
25-/// without a downcast.
26-pub struct OggMuxer {
27- inner: ec_ogg::OggMuxer<Box<dyn WriteSeek>>,
28-}
29-
30-impl OggMuxer {
31- /// Aim for `bytes` of body per page; [`None`] restores the default.
32- pub fn set_page_target_bytes(&mut self, bytes: Option<usize>) {
33- self.inner.set_page_target_bytes(bytes);
34- }
35-}
36-
37-impl Muxer for OggMuxer {
38- fn format_name(&self) -> &str {
39- "ogg"
40- }
41-
42- fn write_header(&mut self) -> Result<()> {
43- Ok(self.inner.write_headers()?)
44- }
45-
46- /// The caller's `pts` *is* the granule position — where this packet ends —
47- /// which is the convention the incumbent muxer wrote onto its pages. It is
48- /// moved into the side data `ec_ogg` reads positions from, and the packet
49- /// keeps no start timestamp, because Ogg does not carry one.
50- fn write_packet(&mut self, packet: &Packet) -> Result<()> {
51- let mut out = packet.clone();
52- if let Some(granule) = packet.pts {
53- out.side_data.push(granule_side_data(granule));
54- }
55- out.pts = None;
56- out.dts = None;
57- Ok(self.inner.write_packet(&out)?)
58- }
59-
60- fn write_trailer(&mut self) -> Result<()> {
61- Ok(self.inner.finish()?)
62- }
63-}
64-
65-/// The replica's stream description, in family terms.
66-fn to_ec_stream(stream: &StreamInfo) -> Result<ec_core::StreamInfo> {
67- let params = &stream.params;
68- let codec = params.codec_id.to_ec().ok_or_else(|| {
69- Error::Unsupported(format!(
70- "Ogg mux: codec {} is not one this family carries",
71- params.codec_id
72- ))
73- })?;
74- let mut out = ec_core::CodecParameters::new(codec);
75- if let ec_core::MediaParameters::Audio(audio) = &mut out.media {
76- if let Some(rate) = params.sample_rate {
77- audio.sample_rate = rate;
78- }
79- if let Some(channels) = params.channels {
80- audio.layout = ec_core::ChannelLayout::from_count(usize::from(channels).max(1));
81- }
82- }
83- if !params.extradata.is_empty() {
84- out.extradata = Some(ec_core::Buf::copy_from_slice(&params.extradata));
85- }
86- let mut info = ec_core::StreamInfo::new(stream.index, stream.time_base, out);
87- info.duration = stream.duration;
88- info.start_time = stream.start_time;
89- Ok(info)
90-}
shims/oxideav-ogg/tests/edith_surface.rsdeleted+0 -123
@@ -1,123 +0,0 @@
1-//! The replica's own call sequence, run against the shim.
2-//!
3-//! `export.rs:2942-2982` laces three Vorbis headers, describes one stream,
4-//! opens a concrete muxer, sets the page target, then writes header, packets
5-//! and trailer — with each packet's *granule* in its `pts`. This drives exactly
6-//! that, with real Vorbis packets taken out of a fixture, and asks ffmpeg
7-//! whether the result is the same audio.
8-
9-use std::path::{Path, PathBuf};
10-use std::process::Command;
11-
12-use ec_core::Demuxer as _;
13-use oxideav_core::{CodecId, CodecParameters, Muxer as _, Packet, StreamInfo, TimeBase};
14-
15-fn fixture() -> PathBuf {
16- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio/vorbis-ogg-stereo-44100.ogg")
17-}
18-
19-fn decode_pcm(path: &Path) -> Vec<u8> {
20- let out = Command::new("ffmpeg")
21- .args(["-v", "error", "-i"])
22- .arg(path)
23- .args(["-f", "f32le", "-"])
24- .output()
25- .expect("ffmpeg");
26- assert!(
27- out.status.success(),
28- "ffmpeg failed on {}: {}",
29- path.display(),
30- String::from_utf8_lossy(&out.stderr)
31- );
32- out.stdout
33-}
34-
35-#[test]
36-fn writes_a_vorbis_file_the_way_the_replica_does() {
37- let source = fixture();
38- if !source.exists() {
39- eprintln!("fixtures/audio absent (gitignored) — skipping");
40- return;
41- }
42-
43- // Packets and setup data out of a real file, standing in for the encoder
44- // the replica feeds this from.
45- let mut demuxer = ec_ogg::OggDemuxer::open(std::fs::File::open(&source).unwrap()).unwrap();
46- let info = demuxer.streams()[0].clone();
47- let extradata = info.params.extradata.clone().unwrap();
48- let headers = ec_ogg::xiph_unlace(&extradata).unwrap();
49- let mut packets = Vec::new();
50- while let Ok(packet) = demuxer.next_packet() {
51- packets.push(packet);
52- }
53- assert_eq!(headers.len(), 3, "a Vorbis stream is three headers");
54-
55- // From here on, the replica's code, line for line.
56- let laced = super_xiph_lace(&headers).expect("the three headers would not lace");
57- assert_eq!(&laced[..], &extradata[..], "lacing must round-trip");
58-
59- let rate = 44_100u32;
60- let time_base = TimeBase::new(1, i64::from(rate));
61- let mut params = CodecParameters::audio(CodecId::new("vorbis"));
62- params.sample_rate = Some(rate);
63- params.channels = Some(2);
64- params.extradata = laced;
65- let stream = StreamInfo {
66- index: 0,
67- time_base,
68- duration: info.duration,
69- start_time: Some(0),
70- params,
71- };
72-
73- let out_path =
74- std::env::temp_dir().join(format!("oxideav-ogg-shim-{}.ogg", std::process::id()));
75- let file = std::fs::File::create(&out_path).unwrap();
76- let mut muxer = oxideav_ogg::mux::open_concrete(Box::new(file), &[stream]).unwrap();
77- muxer.set_page_target_bytes(Some(4096));
78- muxer.write_header().unwrap();
79- for packet in &packets {
80- // The replica states the granule position in `pts`; the shim is what
81- // knows that is what it means.
82- let mut out = Packet::new(0, time_base, packet.data.to_vec());
83- out.pts = ec_ogg::granule_of(packet);
84- out.duration = packet.duration;
85- muxer.write_packet(&out).unwrap();
86- }
87- muxer.write_trailer().unwrap();
88-
89- // ffprobe reads it without complaint, and it is the same audio.
90- let probe = Command::new("ffprobe")
91- .args([
92- "-v",
93- "error",
94- "-select_streams",
95- "a:0",
96- "-count_packets",
97- "-show_entries",
98- "stream=codec_name,sample_rate,channels,nb_read_packets",
99- "-of",
100- "csv=p=0",
101- ])
102- .arg(&out_path)
103- .output()
104- .expect("ffprobe");
105- let stderr = String::from_utf8_lossy(&probe.stderr);
106- assert!(stderr.trim().is_empty(), "ffprobe complained: {stderr}");
107- assert_eq!(
108- String::from_utf8_lossy(&probe.stdout).trim(),
109- format!("vorbis,{rate},2,{}", packets.len()),
110- "ffprobe must see the stream the replica described"
111- );
112- assert_eq!(
113- decode_pcm(&out_path),
114- decode_pcm(&source),
115- "the shim's file must decode to the samples that went into it"
116- );
117- let _ = std::fs::remove_file(&out_path);
118-}
119-
120-/// Named apart so the call above reads like the replica's line.
121-fn super_xiph_lace(headers: &[&[u8]]) -> Option<Vec<u8>> {
122- oxideav_ogg::mux::xiph_lace(headers)
123-}
shims/oxideav-sub-image/Cargo.tomldeleted+0 -16
@@ -1,16 +0,0 @@
1-[package]
2-name = "oxideav-sub-image"
3-description = "Compatibility shim: the oxideav-sub-image PGS surface edith consumes, over ec-pgs."
4-version = "0.0.7"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-pgs = { path = "../../crates/ec-pgs", version = "0.1.0" }
12-oxideav-core = { path = "../oxideav-core", version = "0.1.34" }
13-
14-[dev-dependencies]
15-oxideav-subtitle = { path = "../oxideav-subtitle", version = "0.1.2" }
16-oxideav-ass = { path = "../oxideav-ass", version = "0.0.9" }
shims/oxideav-sub-image/src/lib.rsdeleted+0 -83
@@ -1,83 +0,0 @@
1-//! `oxideav-sub-image` as edith consumes it, over [`ec_pgs`].
2-//!
3-//! Four items: [`PGS_CODEC_ID`], [`pgs::make_decoder`], [`pgs::SEG_PCS`] and
4-//! [`pgs::SEG_END`] — the replica reads a Matroska block's segments, puts the
5-//! `.sup` framing back on and stops at the `END` that closes the first set
6-//! which composes something, then decodes that through the trait.
7-
8-#![forbid(unsafe_code)]
9-
10-/// The codec id a PGS track is named by.
11-pub const PGS_CODEC_ID: &str = "pgs";
12-
13-/// Presentation Graphic Stream.
14-pub mod pgs {
15- use oxideav_core::{CodecId, CodecParameters, Decoder, EcDecoder, Result};
16-
17- pub use ec_pgs::{SEG_END, SEG_ODS, SEG_PCS, SEG_PDS, SEG_WDS};
18-
19- /// A PGS decoder: `.sup`-framed segments in, one RGBA canvas per display
20- /// set out. The parameters say nothing a PGS stream does not state itself.
21- pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
22- Ok(Box::new(EcDecoder::new(
23- CodecId::new(crate::PGS_CODEC_ID),
24- Box::new(ec_pgs::PgsDecoder::new()),
25- )))
26- }
27-}
28-
29-#[cfg(test)]
30-mod tests {
31- use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase};
32-
33- use super::*;
34-
35- /// The `.sup` framing the replica rebuilds around a Matroska block.
36- fn segment(kind: u8, body: &[u8]) -> Vec<u8> {
37- let mut out = Vec::new();
38- out.extend_from_slice(b"PG");
39- out.extend_from_slice(&[0; 8]);
40- out.push(kind);
41- out.extend_from_slice(&(body.len() as u16).to_be_bytes());
42- out.extend_from_slice(body);
43- out
44- }
45-
46- #[test]
47- fn a_display_set_decodes_through_the_replica_s_own_call_shape() {
48- let params = CodecParameters::subtitle(CodecId::new(PGS_CODEC_ID));
49- let mut decoder = pgs::make_decoder(&params).unwrap();
50-
51- // A 4x2 canvas with one 2x1 opaque-white object at (1, 0).
52- let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1];
53- pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]);
54- let pds = vec![0, 0, 1, 235, 128, 128, 255];
55- let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00];
56- let mut ods = vec![0, 0, 0, 0xC0];
57- ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]);
58- ods.extend_from_slice(&[0, 2, 0, 1]);
59- ods.extend_from_slice(&rle);
60- let mut sup = segment(pgs::SEG_PCS, &pcs);
61- // The composition object count is where the replica reads whether the
62- // set shows anything.
63- assert_eq!(pcs[10], 1);
64- sup.extend(segment(pgs::SEG_PDS, &pds));
65- sup.extend(segment(pgs::SEG_ODS, &ods));
66- sup.extend(segment(pgs::SEG_END, &[]));
67-
68- decoder
69- .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup))
70- .unwrap();
71- let Ok(Frame::Video(frame)) = decoder.receive_frame() else {
72- panic!("a display set is a picture");
73- };
74- // A 4x2 canvas: no dimensions on the frame, so the row stride and the
75- // byte count are what state them.
76- assert_eq!(frame.planes[0].stride, 4 * 4);
77- let data = frame.planes.into_iter().next().unwrap().data;
78- assert_eq!(data.len(), 4 * 2 * 4);
79- // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`).
80- assert_eq!(&data[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]);
81- assert_eq!(&data[0..4], &[0, 0, 0, 0]);
82- }
83-}
shims/oxideav-sub-image/tests/replica_call_shapes.rsdeleted+0 -158
@@ -1,158 +0,0 @@
1-//! The replica's own call shapes, transcribed, so a swap is proven at compile
2-//! time and not at the first PGS track a user opens.
3-//!
4-//! Every block below is the engine's code with its surroundings removed:
5-//! `subtitle.rs:33` (`plain_text`), `:90-125` (`CueImage::rgba` — the `.sup`
6-//! framing rebuilt around a Matroska block and decoded), `:518` (`srt::parse`
7-//! around a synthetic timing line), `:555` (`oxideav_ass::parse`) and
8-//! `:603-607` (the four parsers as one function-pointer type). If any of them
9-//! stops compiling against these shims, the swap has broken, whatever the
10-//! crates' own tests say.
11-
12-use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase};
13-use oxideav_subtitle::ir::plain_text;
14-
15-/// `subtitle.rs:604-607` — the extension-to-parser table, as one `fn` type.
16-type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>;
17-
18-fn parser_for(ext: &str) -> Option<Parse> {
19- match ext {
20- "srt" => Some(oxideav_subtitle::srt::parse),
21- "vtt" | "webvtt" => Some(oxideav_subtitle::webvtt::parse),
22- "ass" | "ssa" => Some(oxideav_ass::parse),
23- _ => None,
24- }
25-}
26-
27-#[test]
28-fn the_parser_table_and_the_cue_fields_the_replica_reads() {
29- for (ext, doc) in [
30- ("srt", "1\n00:00:01,000 --> 00:00:02,000\n<i>hi</i>\n"),
31- (
32- "vtt",
33- "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n<i>hi</i>\n",
34- ),
35- (
36- "ass",
37- "[Events]\nFormat: Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text\n\
38- Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}hi\n",
39- ),
40- ] {
41- let parse = parser_for(ext).expect("the replica routes these four extensions");
42- let track = parse(doc.as_bytes()).unwrap();
43- // `subtitle.rs:623-632`: cues mapped onto the engine's own `Cue`.
44- let cues: Vec<(i64, i64, String)> = track
45- .cues
46- .iter()
47- .map(|c| (c.start_us, c.end_us, plain_text(&c.segments)))
48- .collect();
49- assert_eq!(cues, vec![(1_000_000, 2_000_000, "hi".to_owned())], "{ext}");
50- }
51- assert!(parser_for("txt").is_none());
52-}
53-
54-/// `subtitle.rs:516-527` — an `S_TEXT/UTF8` block's markup resolved by wrapping
55-/// it in a synthetic SRT.
56-#[test]
57-fn a_matroska_text_block_is_resolved_through_the_srt_parser() {
58- let text = "<i>tilted</i> and plain";
59- let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end());
60- let resolved = match oxideav_subtitle::srt::parse(doc.as_bytes()) {
61- Ok(track) => track
62- .cues
63- .first()
64- .map(|c| plain_text(&c.segments))
65- .unwrap_or_default(),
66- Err(_) => text.trim_end().to_owned(),
67- };
68- assert_eq!(resolved, "tilted and plain");
69-}
70-
71-/// `subtitle.rs:89-125` — a Matroska PGS block, framed back into a `.sup` and
72-/// decoded to straight RGBA the size of the disc's own canvas.
73-#[test]
74-fn a_matroska_pgs_block_decodes_the_way_the_replica_decodes_one() {
75- let set = matroska_block();
76- let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID));
77- let mut decoder = oxideav_sub_image::pgs::make_decoder(&params).unwrap();
78- let mut sup = Vec::with_capacity(set.len() + 64);
79- let mut shows = false;
80- for (kind, body) in segments(&set).unwrap() {
81- sup.extend_from_slice(b"PG");
82- sup.extend_from_slice(&[0; 8]);
83- sup.push(kind);
84- sup.extend_from_slice(&(body.len() as u16).to_be_bytes());
85- sup.extend_from_slice(body);
86- match kind {
87- oxideav_sub_image::pgs::SEG_PCS => {
88- shows = body.get(10).is_some_and(|&n| n > 0);
89- }
90- oxideav_sub_image::pgs::SEG_END if shows => break,
91- _ => {}
92- }
93- }
94- decoder
95- .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup))
96- .unwrap();
97- let rgba = match decoder.receive_frame().unwrap() {
98- Frame::Video(frame) => frame.planes.into_iter().next().map(|p| p.data),
99- _ => None,
100- }
101- .expect("a display set is a picture");
102- // The whole canvas, transparent where the cue paints nothing.
103- assert_eq!(rgba.len(), 4 * 2 * 4);
104- assert_eq!(&rgba[0..4], &[0, 0, 0, 0]);
105- // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`).
106- assert_eq!(&rgba[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]);
107-
108- // The erase set after the composition must not be what gets decoded: the
109- // loop above stops at the `END` that closes the showing set.
110- let all: Vec<u8> = set.clone();
111- assert!(
112- segments(&all).unwrap().len() > 5,
113- "the block holds both sets"
114- );
115-}
116-
117-/// `subtitle.rs:131-140` — the segments of a display set as a Matroska block
118-/// holds them: type, big-endian size, body.
119-fn segments(set: &[u8]) -> Option<Vec<(u8, &[u8])>> {
120- let mut out = Vec::new();
121- let mut at = 0;
122- while at < set.len() {
123- let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize;
124- out.push((set[at], set.get(at + 3..at + 3 + size)?));
125- at += 3 + size;
126- }
127- Some(out)
128-}
129-
130-/// A block holding a composition *and* the erase that follows it — the packing
131-/// the replica's comment warns about.
132-fn matroska_block() -> Vec<u8> {
133- let block = |kind: u8, body: &[u8]| {
134- let mut out = vec![kind];
135- out.extend_from_slice(&(body.len() as u16).to_be_bytes());
136- out.extend_from_slice(body);
137- out
138- };
139- let mut pcs = vec![0, 4, 0, 2, 0x10, 0, 0, 0x80, 0, 0, 1];
140- pcs.extend_from_slice(&[0, 0, 0, 0, 0, 1, 0, 0]);
141- let pds = vec![0, 0, 1, 235, 128, 128, 255];
142- let rle = vec![0x00, 0x82, 0x01, 0x00, 0x00];
143- let mut ods = vec![0, 0, 0, 0xC0];
144- ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]);
145- ods.extend_from_slice(&[0, 2, 0, 1]);
146- ods.extend_from_slice(&rle);
147- // The erase: a composition with no objects at all.
148- let erase = vec![0, 4, 0, 2, 0x10, 0, 1, 0, 0, 0, 0];
149- [
150- block(oxideav_sub_image::pgs::SEG_PCS, &pcs),
151- block(oxideav_sub_image::pgs::SEG_PDS, &pds),
152- block(oxideav_sub_image::pgs::SEG_ODS, &ods),
153- block(oxideav_sub_image::pgs::SEG_END, &[]),
154- block(oxideav_sub_image::pgs::SEG_PCS, &erase),
155- block(oxideav_sub_image::pgs::SEG_END, &[]),
156- ]
157- .concat()
158-}
shims/oxideav-subtitle/Cargo.tomldeleted+0 -12
@@ -1,12 +0,0 @@
1-[package]
2-name = "oxideav-subtitle"
3-description = "Compatibility shim: the oxideav-subtitle surface edith consumes, over ec-subs."
4-version = "0.1.2"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-subs = { path = "../../crates/ec-subs", version = "0.1.0" }
12-oxideav-core = { path = "../oxideav-core", version = "0.1.34" }
shims/oxideav-subtitle/src/lib.rsdeleted+0 -64
@@ -1,64 +0,0 @@
1-//! `oxideav-subtitle` as edith consumes it, over [`ec_subs`].
2-//!
3-//! Three items and their types: `ir::plain_text`, `ir::SubtitleTrack`,
4-//! `srt::parse` and `webvtt::parse`. The IR is `ec_subs`'s own — the field
5-//! names were chosen to match, so this is a re-export and not a conversion —
6-//! and the only adapter is the error type, because the replica writes the parse
7-//! functions as `fn(&[u8]) -> oxideav_core::Result<SubtitleTrack>` and takes
8-//! their address.
9-
10-#![forbid(unsafe_code)]
11-
12-/// The cue IR, which is [`ec_subs::ir`] under its incumbent name.
13-pub mod ir {
14- pub use ec_subs::ir::{
15- CuePosition, Segment, SourceFormat, SubtitleCue, SubtitleStyle, SubtitleTrack, TextAlign,
16- plain_text,
17- };
18-}
19-
20-pub use ir::{SourceFormat, SubtitleTrack};
21-
22-/// SubRip.
23-pub mod srt {
24- use oxideav_core::Result;
25-
26- use crate::ir::SubtitleTrack;
27-
28- /// Parse a SubRip document.
29- pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
30- Ok(ec_subs::srt::parse(bytes)?)
31- }
32-}
33-
34-/// WebVTT.
35-pub mod webvtt {
36- use oxideav_core::Result;
37-
38- use crate::ir::SubtitleTrack;
39-
40- /// Parse a WebVTT document.
41- pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
42- Ok(ec_subs::webvtt::parse(bytes)?)
43- }
44-}
45-
46-#[cfg(test)]
47-mod tests {
48- use super::*;
49-
50- /// The replica takes these as function pointers of one type and calls
51- /// `plain_text` on whatever comes back; that is the whole contract.
52- #[test]
53- fn the_parsers_are_interchangeable_function_pointers() {
54- type Parse = fn(&[u8]) -> oxideav_core::Result<ir::SubtitleTrack>;
55- for parse in [srt::parse as Parse, webvtt::parse as Parse] {
56- let track = parse(b"1\n00:00:01,000 --> 00:00:02,000\n<i>hi</i>\n").unwrap();
57- assert_eq!(ir::plain_text(&track.cues[0].segments), "hi");
58- assert_eq!(track.cues[0].start_us, 1_000_000);
59- }
60- // A file of the wrong kind is an error the replica can print.
61- let error = srt::parse(b"prose, not subtitles").unwrap_err();
62- assert!(!error.to_string().is_empty());
63- }
64-}
shims/ruopus/Cargo.tomldeleted+0 -22
@@ -1,22 +0,0 @@
1-[package]
2-name = "ruopus"
3-description = "Compatibility shim: the ruopus 0.1.2 surface edith consumes, served by ec-opus."
4-version = "0.1.2"
5-edition.workspace = true
6-license.workspace = true
7-authors.workspace = true
8-publish = false
9-
10-[dependencies]
11-ec-opus = { path = "../../crates/ec-opus", version = "0.1.0" }
12-
13-# The incumbent's feature names, all no-ops here. A `[patch.crates-io]` consumer
14-# that names a feature the patch lacks fails to *resolve*, so the swap needs
15-# them declared even though nothing behind them is optional in this crate:
16-# `spectrograms` bought the incumbent an FFT-backed MDCT (fifteen crates), and
17-# `ec-opus` has that path unconditionally through `ec-dsp`.
18-[features]
19-default = ["std", "spectrograms"]
20-std = []
21-spectrograms = ["std"]
22-libm = []
shims/ruopus/src/lib.rsdeleted+0 -31
@@ -1,31 +0,0 @@
1-//! `ruopus` as edith consumes it, over [`ec_opus`].
2-//!
3-//! A shim, not a port: it carries the incumbent's package name and version so
4-//! the swap is a `[patch.crates-io]` line, and it exposes exactly the one item
5-//! the replica names — [`MultistreamDecoder`], built with `with_rate` and fed
6-//! one packet at a time with `decode_packet` (`audio.rs:1575`, `1694`;
7-//! `export.rs:1950`, the fidelity gate's own decoder).
8-//!
9-//! A re-export is the whole adapter, and that is a claim about two things
10-//! rather than about the names:
11-//!
12-//! * **Layout arguments.** `with_rate(rate, streams, coupled, &mapping)` means
13-//! the same thing in both: the first `coupled` elementary streams are stereo,
14-//! `mapping[c]` names the decoded channel output channel `c` reads (255 =
15-//! silent), and an impossible layout panics rather than returning — which is
16-//! why the replica checks the `OpusHead` it read from a file before it gets
17-//! here (`audio.rs:opus_layout`).
18-//! * **Channel order.** Both decoders emit the *mapping's* order, which for RFC
19-//! 7845 family 1 is Vorbis order (FL, FC, FR, BL, BR, LFE for 5.1) and not
20-//! the product's FL/FR/FC/LFE/BL/BR. The permutation stays where the
21-//! incumbent's behaviour already put it, at the call site
22-//! (`audio.rs:vorbis_to_film_order`); a shim that permuted here would fold
23-//! surround twice.
24-//!
25-//! Errors differ in type and not in use: `ec_core::Error` where the incumbent
26-//! had `PacketError`, both `Display` and both consumed as `{e}` or as a
27-//! refused packet.
28-
29-#![forbid(unsafe_code)]
30-
31-pub use ec_opus::MultistreamDecoder;
shims/rusty_aac/Cargo.tomldeleted+0 -11
@@ -1,11 +0,0 @@
1-[package]
2-name = "rusty_aac"
3-description = "Compatibility shim: the rusty_aac 0.5 surface edith consumes, served by ec-aac."
4-version = "0.5.0"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-aac = { path = "../../crates/ec-aac", version = "0.1.0" }
shims/rusty_aac/src/lib.rsdeleted+0 -233
@@ -1,233 +0,0 @@
1-//! The `rusty_aac` 0.5 surface, served by `ec-aac`.
2-//!
3-//! Only what edith consumes is here, at the incumbent's signatures:
4-//! `AacDecoder::with_config_bytes` (audio.rs:1731), `AacEncoder::new` with
5-//! `AacEncoderConfig` (mux.rs:2116, export.rs:1756) and `sf_index_for_rate`
6-//! (export.rs:1678). The encoder's tool flags are kept as fields so a caller
7-//! written against the incumbent still compiles; each one names what it maps to.
8-
9-#![forbid(unsafe_code)]
10-
11-pub use ec_aac::{
12- AdtsHeader, AudioSpecificConfig, SAMPLE_RATES, audio_specific_config_bytes, is_adts,
13- parse_adts, parse_audio_specific_config, sample_rate_for_index, sf_index_for_rate,
14- write_adts_header, write_audio_specific_config,
15-};
16-
17-/// The incumbent's error type: one variant per refusal reason, `Eof` included
18-/// so `while let Ok(p) = next_packet()` still terminates.
19-#[derive(Debug)]
20-pub enum Error {
21- Eof,
22- NeedMore,
23- Invalid(String),
24- Unsupported(String),
25-}
26-
27-impl std::fmt::Display for Error {
28- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29- match self {
30- Error::Eof => write!(f, "end of stream"),
31- Error::NeedMore => write!(f, "need more data"),
32- Error::Invalid(m) => write!(f, "invalid: {m}"),
33- Error::Unsupported(m) => write!(f, "unsupported: {m}"),
34- }
35- }
36-}
37-
38-impl std::error::Error for Error {}
39-
40-impl Error {
41- pub fn invalid(msg: impl Into<String>) -> Error {
42- Error::Invalid(msg.into())
43- }
44-
45- pub fn unsupported(msg: impl Into<String>) -> Error {
46- Error::Unsupported(msg.into())
47- }
48-}
49-
50-impl From<ec_aac::Error> for Error {
51- fn from(e: ec_aac::Error) -> Error {
52- match e {
53- ec_aac::Error::Eof => Error::Eof,
54- ec_aac::Error::NeedMore => Error::NeedMore,
55- ec_aac::Error::Unsupported { .. } => Error::Unsupported(e.to_string()),
56- other => Error::Invalid(other.to_string()),
57- }
58- }
59-}
60-
61-pub type Result<T> = std::result::Result<T, Error>;
62-
63-/// One decoded frame, interleaved, in film channel order.
64-#[derive(Clone, Debug, Default)]
65-pub struct DecodedAudio {
66- pub sample_rate: u32,
67- pub channels: u16,
68- pub samples: Vec<f32>,
69- pub pts: Option<i64>,
70-}
71-
72-impl DecodedAudio {
73- pub fn frames(&self) -> usize {
74- if self.channels == 0 {
75- 0
76- } else {
77- self.samples.len() / usize::from(self.channels)
78- }
79- }
80-}
81-
82-/// What the decoder does with a High Efficiency stream.
83-pub use ec_aac::SbrSupport;
84-
85-/// An AAC-LC decoder.
86-pub struct AacDecoder(ec_aac::AacDecoder);
87-
88-impl AacDecoder {
89- pub fn new() -> AacDecoder {
90- AacDecoder(ec_aac::AacDecoder::new())
91- }
92-
93- pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
94- AacDecoder(ec_aac::AacDecoder::with_config(cfg))
95- }
96-
97- pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
98- Ok(AacDecoder(ec_aac::AacDecoder::with_config_bytes(data)?))
99- }
100-
101- pub fn sbr_support(&self) -> SbrSupport {
102- self.0.sbr_support()
103- }
104-
105- pub fn output_sample_rate(&self) -> Option<u32> {
106- self.0.output_sample_rate()
107- }
108-
109- pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
110- let d = self.0.decode(packet, pts)?;
111- Ok(DecodedAudio {
112- sample_rate: d.sample_rate,
113- channels: d.channels,
114- samples: d.samples,
115- pts: d.pts,
116- })
117- }
118-}
119-
120-impl Default for AacDecoder {
121- fn default() -> AacDecoder {
122- AacDecoder::new()
123- }
124-}
125-
126-/// Window-shape policy.
127-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128-pub enum WindowShape {
129- #[default]
130- Sine,
131- Kbd,
132- /// Per-frame dispatch on content tonality; served here as [`WindowShape::Sine`].
133- Auto,
134-}
135-
136-/// Encoder options, at the incumbent's field set.
137-#[derive(Debug, Clone, Copy)]
138-pub struct AacEncoderConfig {
139- /// Target bitrate in bits per second.
140- pub bitrate_bps: u32,
141- /// Window-shape policy.
142- pub window_shape: WindowShape,
143- /// The `Auto` gate's threshold; unused here, `Auto` codes as sine.
144- pub shape_tonality_pct: f32,
145- /// Run the psychoacoustic model on short blocks: always on here.
146- pub short_block_psy: bool,
147- /// Make the signal-to-mask ratio a function of band tonality: always on here.
148- pub tonality_smr: bool,
149- /// Emit TNS on long blocks; not emitted by this encoder (decoding it is
150- /// complete either way).
151- pub tns: bool,
152- /// Level-invariant transient detector: always on here.
153- pub relative_transients: bool,
154- /// Perceptual noise substitution; not emitted by this encoder.
155- pub pns: bool,
156- /// Intensity stereo; not emitted by this encoder.
157- pub intensity: bool,
158- /// Split a pair's bit budget by perceptual demand: always on here, the rate
159- /// loop is joint over the whole frame.
160- pub stereo_bit_split: bool,
161-}
162-
163-impl Default for AacEncoderConfig {
164- fn default() -> AacEncoderConfig {
165- AacEncoderConfig {
166- bitrate_bps: 128_000,
167- window_shape: WindowShape::Sine,
168- shape_tonality_pct: 0.5,
169- short_block_psy: true,
170- tonality_smr: true,
171- tns: false,
172- relative_transients: true,
173- pns: false,
174- intensity: false,
175- stereo_bit_split: true,
176- }
177- }
178-}
179-
180-/// One encoded raw access unit (a `raw_data_block`, no ADTS framing).
181-#[derive(Debug, Clone)]
182-pub struct EncodedPacket {
183- pub data: Vec<u8>,
184- pub pts: i64,
185- pub duration: u32,
186-}
187-
188-/// An AAC-LC encoder.
189-pub struct AacEncoder(ec_aac::AacEncoder);
190-
191-impl AacEncoder {
192- pub fn new(config: AacEncoderConfig) -> AacEncoder {
193- AacEncoder(ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig {
194- bitrate_bps: config.bitrate_bps.max(1),
195- window_shape: match config.window_shape {
196- WindowShape::Kbd => ec_aac::WindowShape::Kbd,
197- _ => ec_aac::WindowShape::Sine,
198- },
199- adts: false,
200- mid_side: true,
201- window_switching: true,
202- }))
203- }
204-
205- pub fn sample_rate(&self) -> u32 {
206- self.0.sample_rate()
207- }
208-
209- pub fn channels(&self) -> u16 {
210- self.0.channels()
211- }
212-
213- pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
214- Ok(self.0.push_pcm(interleaved, channels, sample_rate)?)
215- }
216-
217- pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
218- Ok(self.0.push_pcm_planar(planes, sample_rate)?)
219- }
220-
221- pub fn finish(&mut self) {
222- self.0.finish();
223- }
224-
225- pub fn next_packet(&mut self) -> Result<EncodedPacket> {
226- let p = self.0.next_packet()?;
227- Ok(EncodedPacket {
228- data: p.data,
229- pts: p.pts,
230- duration: p.duration,
231- })
232- }
233-}
shims/rusty_aac/tests/edith_surface.rsdeleted+0 -73
@@ -1,73 +0,0 @@
1-//! The call sites edith actually has, compiled and run against the shim.
2-//!
3-//! Each one mirrors a line in the replica: `audio.rs:1731` builds the decoder
4-//! for a multichannel track from its AudioSpecificConfig, `export.rs:1678`
5-//! turns a sample rate into a `samplingFrequencyIndex`, and `export.rs:1756`
6-//! plus `mux.rs:2116` drive the encoder over a mix.
7-
8-#[test]
9-fn sf_index_for_rate_covers_the_rates_the_exporter_offers() {
10- assert_eq!(rusty_aac::sf_index_for_rate(48_000), Some(3));
11- assert_eq!(rusty_aac::sf_index_for_rate(44_100), Some(4));
12- assert_eq!(rusty_aac::sf_index_for_rate(96_000), Some(0));
13- assert_eq!(rusty_aac::sf_index_for_rate(8_000), Some(11));
14- // The exporter's own error path: a rate AAC cannot carry.
15- assert_eq!(rusty_aac::sf_index_for_rate(37_000), None);
16-}
17-
18-#[test]
19-fn a_multichannel_track_builds_from_its_audio_specific_config() {
20- // 5.1 at 48 kHz, which is what a film's mkv hands over as CodecPrivate.
21- let asc = rusty_aac::audio_specific_config_bytes(48_000, 6);
22- let decoder = rusty_aac::AacDecoder::with_config_bytes(&asc).expect("decoder builds");
23- assert_eq!(decoder.output_sample_rate(), Some(48_000));
24- assert_eq!(decoder.sbr_support(), rusty_aac::SbrSupport::NotSignalled);
25-}
26-
27-/// `export.rs:1756`: the caller's bitrate over the config's defaults, PCM in,
28-/// packets out until `Eof`.
29-#[test]
30-fn the_export_encoder_loop_runs_to_eof() {
31- let rate = 48_000u32;
32- let channels = 2u16;
33- let frames = rate as usize;
34- let mut pcm = Vec::with_capacity(frames * usize::from(channels));
35- for i in 0..frames {
36- let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5;
37- for _ in 0..channels {
38- pcm.push(s);
39- }
40- }
41- let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {
42- bitrate_bps: 256 * 1_000,
43- ..Default::default()
44- });
45- encoder
46- .push_pcm(&pcm, channels, rate)
47- .expect("pcm accepted");
48- encoder.finish();
49- let mut packets = Vec::new();
50- while let Ok(packet) = encoder.next_packet() {
51- assert_eq!(packet.duration, 1024, "one AAC frame per packet");
52- assert!(!packet.data.is_empty(), "a packet with no payload");
53- packets.push(packet);
54- }
55- assert!(
56- packets.len() > 10,
57- "a second of audio is many packets, got {}",
58- packets.len()
59- );
60- assert_eq!(encoder.sample_rate(), rate);
61- assert_eq!(encoder.channels(), channels);
62-
63- // And the packets are a stream this family's own decoder reads back.
64- let asc = rusty_aac::audio_specific_config_bytes(rate, channels);
65- let mut decoder = rusty_aac::AacDecoder::with_config_bytes(&asc).expect("decoder builds");
66- let mut decoded = 0usize;
67- for packet in &packets {
68- let audio = decoder.decode(&packet.data, None).expect("packet decodes");
69- assert_eq!(audio.channels, channels);
70- decoded += audio.frames();
71- }
72- assert_eq!(decoded, packets.len() * 1024);
73-}
shims/rusty_h264/Cargo.tomldeleted+0 -12
@@ -1,12 +0,0 @@
1-[package]
2-name = "rusty_h264"
3-description = "Compatibility shim: the rusty_h264 0.9.1 surface edith consumes, served by ec-h264."
4-version = "0.9.1"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-h264 = { workspace = true }
12-ec-h264-syntax = { workspace = true }
shims/rusty_h264/src/lib.rsdeleted+0 -328
@@ -1,328 +0,0 @@
1-//! The `rusty_h264` 0.9.1 surface, served by `ec-h264`.
2-//!
3-//! Only what edith consumes is here, at the incumbent's signatures:
4-//! `Decoder::new` + `decode` over whole access units (decode.rs:1478-1500,
5-//! export.rs:4200), and `EncoderConfig` + `Encoder::new` + `try_encode` +
6-//! `try_flush` with `YuvFrame` and `Preset` (export.rs:3407-3422, 3640-3650,
7-//! 3727-3736).
8-//!
9-//! Two differences from the incumbent, both deliberate and both visible only
10-//! as *absences*:
11-//!
12-//! - No `#[global_allocator]`. The incumbent's `common` crate installed one
13-//! process-wide and had to be vendored out; there is nothing to vendor here.
14-//! - No lookahead buffering. `try_encode` returns the access unit of the
15-//! picture it was handed, every time, so `try_flush` has nothing left to
16-//! give and the caller's per-picture timing is exact whatever the rate
17-//! control mode.
18-//!
19-//! Pictures come out in decode order, which is what the incumbent did and what
20-//! edith's decode loop assumes. [`Decoder::in_display_order`] is the same
21-//! decoder with the reordering the incumbent never had.
22-
23-#![forbid(unsafe_code)]
24-
25-use ec_h264::{NalOutcome, OutputOrder, PictureView};
26-
27-/// The incumbent's error type: one variant per refusal reason.
28-#[derive(Debug)]
29-pub enum Error {
30- NeedMore,
31- Invalid(String),
32- Unsupported(String),
33-}
34-
35-impl std::fmt::Display for Error {
36- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37- match self {
38- Error::NeedMore => write!(f, "need more data"),
39- Error::Invalid(m) => write!(f, "invalid: {m}"),
40- Error::Unsupported(m) => write!(f, "unsupported: {m}"),
41- }
42- }
43-}
44-
45-impl std::error::Error for Error {}
46-
47-impl From<ec_h264::Error> for Error {
48- fn from(e: ec_h264::Error) -> Error {
49- match e {
50- ec_h264::Error::NeedMore => Error::NeedMore,
51- ec_h264::Error::Unsupported { .. } => Error::Unsupported(e.to_string()),
52- other => Error::Invalid(other.to_string()),
53- }
54- }
55-}
56-
57-/// A decoded — or about to be encoded — I420 picture, planes owned.
58-#[derive(Debug, Clone, Default, PartialEq, Eq)]
59-pub struct YuvFrame {
60- pub width: usize,
61- pub height: usize,
62- pub y: Vec<u8>,
63- pub u: Vec<u8>,
64- pub v: Vec<u8>,
65-}
66-
67-/// Speed/quality ladder.
68-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69-pub enum Preset {
70- #[default]
71- Fast,
72- Balanced,
73-}
74-
75-impl From<Preset> for ec_h264::Preset {
76- fn from(p: Preset) -> ec_h264::Preset {
77- match p {
78- Preset::Fast => ec_h264::Preset::Fast,
79- Preset::Balanced => ec_h264::Preset::Balanced,
80- }
81- }
82-}
83-
84-/// The H.264 software decoder.
85-pub struct Decoder {
86- inner: ec_h264::Decoder,
87-}
88-
89-impl Default for Decoder {
90- fn default() -> Decoder {
91- Decoder::new()
92- }
93-}
94-
95-impl Decoder {
96- /// A decoder that emits pictures in decode order.
97- pub fn new() -> Decoder {
98- let mut inner = ec_h264::Decoder::new();
99- inner.set_output_order(OutputOrder::Decode);
100- Decoder { inner }
101- }
102-
103- /// A decoder that emits pictures in *display* order, which a stream with
104- /// B pictures needs and the incumbent could not do. Pictures then come out
105- /// with the stream's own reordering delay, so a caller that stops feeding
106- /// must call [`Decoder::flush`] to collect the tail.
107- pub fn in_display_order() -> Decoder {
108- let mut inner = ec_h264::Decoder::new();
109- inner.set_output_order(OutputOrder::Display);
110- Decoder { inner }
111- }
112-
113- /// Decode one access unit (Annex B, one coded picture), returning the
114- /// picture it completed if any.
115- pub fn decode(&mut self, au: &[u8]) -> Result<Option<YuvFrame>, Error> {
116- self.feed(au)?;
117- if self.inner.picture_open() {
118- self.inner.end_picture()?;
119- }
120- Ok(self.take())
121- }
122-
123- /// Decode a whole Annex B stream at once, returning every picture in it —
124- /// what a test that holds an encoder's output in memory asks for, where
125- /// [`Decoder::decode`] serves a demuxer handing over one unit at a time.
126- pub fn decode_stream(&mut self, stream: &[u8]) -> Result<Vec<YuvFrame>, Error> {
127- let mut out = Vec::new();
128- self.feed(stream)?;
129- // The tail: whatever the last picture and the reordering delay hold.
130- self.inner.flush()?;
131- while let Some(frame) = self.take() {
132- out.push(frame);
133- }
134- Ok(out)
135- }
136-
137- /// Push every NAL in `bytes`, closing a picture wherever one ends.
138- fn feed(&mut self, bytes: &[u8]) -> Result<(), Error> {
139- for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
140- if self.inner.push_nal(nal)? == NalOutcome::PictureBoundary {
141- // The next picture starts here: close the one before it.
142- self.inner.end_picture()?;
143- self.inner.push_nal(nal)?;
144- }
145- }
146- Ok(())
147- }
148-
149- /// Collect a picture the reordering delay is still holding, at end of
150- /// stream.
151- pub fn flush(&mut self) -> Result<Option<YuvFrame>, Error> {
152- self.inner.flush()?;
153- Ok(self.take())
154- }
155-
156- fn take(&mut self) -> Option<YuvFrame> {
157- let frame = self.inner.next_frame()?;
158- let (w, h) = (frame.width as usize, frame.height as usize);
159- let plane = |i: usize, pw: usize, ph: usize| -> Vec<u8> {
160- let p = &frame.planes[i];
161- let mut out = Vec::with_capacity(pw * ph);
162- for row in 0..ph {
163- out.extend_from_slice(&p.data[row * p.stride..row * p.stride + pw]);
164- }
165- out
166- };
167- Some(YuvFrame {
168- width: w,
169- height: h,
170- y: plane(0, w, h),
171- u: plane(1, w / 2, h / 2),
172- v: plane(2, w / 2, h / 2),
173- })
174- }
175-}
176-
177-/// Encoder settings, at the incumbent's field names.
178-#[derive(Debug, Clone)]
179-pub struct EncoderConfig {
180- pub width: usize,
181- pub height: usize,
182- pub framerate: f32,
183- /// Bits per second; zero codes at a constant quantiser instead.
184- pub bitrate: u32,
185- pub gop_size: u32,
186- /// Consecutive B pictures. Accepted at any value and coded as zero: this
187- /// encoder has no B pictures yet, and refusing the field would break a
188- /// caller that sets it.
189- pub bframes: u32,
190- pub preset: Preset,
191-}
192-
193-impl EncoderConfig {
194- /// The incumbent's constructor: geometry now, everything else by field.
195- pub fn new(width: usize, height: usize) -> EncoderConfig {
196- EncoderConfig {
197- width,
198- height,
199- framerate: 30.0,
200- bitrate: 0,
201- gop_size: 250,
202- bframes: 0,
203- preset: Preset::Fast,
204- }
205- }
206-}
207-
208-/// The H.264 software encoder.
209-pub struct Encoder {
210- inner: ec_h264::Encoder,
211- width: usize,
212- height: usize,
213-}
214-
215-impl Encoder {
216- pub fn new(cfg: EncoderConfig) -> Result<Encoder, Error> {
217- let mut inner_cfg = ec_h264::EncoderConfig::new(cfg.width as u32, cfg.height as u32);
218- inner_cfg.framerate = cfg.framerate;
219- inner_cfg.bitrate = cfg.bitrate;
220- inner_cfg.gop_size = cfg.gop_size;
221- inner_cfg.bframes = cfg.bframes;
222- inner_cfg.preset = cfg.preset.into();
223- let inner = ec_h264::Encoder::new(inner_cfg)?;
224- Ok(Encoder {
225- inner,
226- width: cfg.width,
227- height: cfg.height,
228- })
229- }
230-
231- /// One picture in, its access unit out — always, with no lookahead delay.
232- pub fn try_encode(&mut self, frame: &YuvFrame) -> Result<Vec<u8>, Error> {
233- if frame.width != self.width || frame.height != self.height {
234- return Err(Error::Invalid(format!(
235- "frame is {}x{}, encoder is {}x{}",
236- frame.width, frame.height, self.width, self.height
237- )));
238- }
239- let view = PictureView::i420(
240- self.width as u32,
241- self.height as u32,
242- &frame.y,
243- &frame.u,
244- &frame.v,
245- );
246- Ok(self.inner.encode(&view)?.au)
247- }
248-
249- /// Nothing is ever held back, so this is always empty; it exists because
250- /// the caller's drain path calls it.
251- pub fn try_flush(&mut self) -> Result<Vec<u8>, Error> {
252- Ok(Vec::new())
253- }
254-}
255-
256-#[cfg(test)]
257-mod tests {
258- use super::*;
259-
260- fn frame(w: usize, h: usize, t: usize) -> YuvFrame {
261- YuvFrame {
262- width: w,
263- height: h,
264- y: (0..w * h)
265- .map(|i| ((i / w + i % w + t * 4) % 256) as u8)
266- .collect(),
267- u: vec![110; w / 2 * h / 2],
268- v: vec![150; w / 2 * h / 2],
269- }
270- }
271-
272- /// The whole surface edith calls, in the order edith calls it: configure,
273- /// encode picture by picture, drain, then decode what came out.
274- #[test]
275- fn the_edith_call_sequence_round_trips() {
276- let (w, h) = (176usize, 144usize);
277- let mut cfg = EncoderConfig::new(w, h);
278- cfg.framerate = 25.0;
279- cfg.bitrate = 600_000;
280- cfg.gop_size = 5;
281- cfg.bframes = 0;
282- cfg.preset = Preset::Fast;
283- let mut enc = Encoder::new(cfg).expect("encoder");
284- let mut units = Vec::new();
285- for t in 0..6 {
286- let au = enc.try_encode(&frame(w, h, t)).expect("encode");
287- assert!(!au.is_empty(), "picture {t} produced no access unit");
288- units.push(au);
289- }
290- assert!(enc.try_flush().expect("flush").is_empty());
291-
292- let mut dec = Decoder::new();
293- for (t, au) in units.iter().enumerate() {
294- let got = dec.decode(au).expect("decode").expect("a picture");
295- assert_eq!((got.width, got.height), (w, h), "picture {t} geometry");
296- assert_eq!(got.y.len(), w * h);
297- assert_eq!(got.u.len(), w / 2 * h / 2);
298- // A coded picture is close to its source; this is the shim's own
299- // proof that the two halves are wired to each other.
300- let src = frame(w, h, t);
301- let mse: f64 = got
302- .y
303- .iter()
304- .zip(&src.y)
305- .map(|(&a, &b)| {
306- let d = f64::from(a) - f64::from(b);
307- d * d
308- })
309- .sum::<f64>()
310- / (w * h) as f64;
311- assert!(mse < 25.0, "picture {t}: mean squared error {mse:.1}");
312- }
313-
314- // And the same units as one stream, which is how a test that kept the
315- // encoder's output in a `Vec` decodes it back.
316- let whole: Vec<u8> = units.concat();
317- let frames = Decoder::new().decode_stream(&whole).expect("decode stream");
318- assert_eq!(frames.len(), units.len(), "one picture per access unit");
319- }
320-
321- /// A frame whose geometry does not match the encoder is refused by name.
322- #[test]
323- fn geometry_mismatch_is_refused() {
324- let mut enc = Encoder::new(EncoderConfig::new(64, 64)).expect("encoder");
325- let err = enc.try_encode(&frame(32, 32, 0)).unwrap_err();
326- assert!(matches!(err, Error::Invalid(_)), "{err}");
327- }
328-}
shims/rusty_mp3/Cargo.tomldeleted+0 -11
@@ -1,11 +0,0 @@
1-[package]
2-name = "rusty_mp3"
3-description = "Compatibility shim: the rusty_mp3 0.6.1 surface, implemented over ec-mp3."
4-version = "0.6.1"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-
9-[dependencies]
10-ec-mp3 = { path = "../../crates/ec-mp3", version = "0.1.0" }
11-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
shims/rusty_mp3/src/lib.rsdeleted+0 -217
@@ -1,217 +0,0 @@
1-//! `rusty_mp3` 0.6.1's surface, over [`ec_mp3`].
2-//!
3-//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the
4-//! incumbent's name and version so a consumer's `use rusty_mp3::…` compiles
5-//! unchanged. Only what edith consumes plus the streaming decoder beside it is
6-//! here — [`Mp3Encoder`] with [`Mp3EncoderConfig`], [`Mp3Decoder`] with
7-//! [`DecodedAudio`], and an [`Error`] carrying the incumbent's `Eof`/`Again`
8-//! contract — because a shim that grows a surface nobody calls is a second
9-//! implementation to keep honest.
10-//!
11-//! Behaviour difference from the incumbent, stated: the encoder writes the
12-//! `Xing`/`Info` header frame first, and `vbr_quality` runs true variable
13-//! bitrate — per-frame bitrate indices chosen to carry the coded granules
14-//! (see [`ec_mp3::encode::Mp3EncoderConfig`]).
15-
16-#![forbid(unsafe_code)]
17-#![warn(missing_docs)]
18-
19-use std::collections::VecDeque;
20-use std::fmt;
21-
22-/// The incumbent's error type.
23-#[derive(Debug)]
24-pub enum Error {
25- /// No more frames will arrive.
26- Eof,
27- /// Not enough data buffered yet; push more and retry.
28- Again,
29- /// The bitstream is malformed, or the configuration is not codable.
30- Format(String),
31-}
32-
33-impl fmt::Display for Error {
34- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35- match self {
36- Error::Eof => write!(f, "end of stream"),
37- Error::Again => write!(f, "need more data"),
38- Error::Format(why) => write!(f, "mp3: {why}"),
39- }
40- }
41-}
42-
43-impl std::error::Error for Error {}
44-
45-impl From<ec_core::error::Error> for Error {
46- fn from(error: ec_core::error::Error) -> Error {
47- match error {
48- ec_core::error::Error::Eof => Error::Eof,
49- ec_core::error::Error::NeedMore => Error::Again,
50- other => Error::Format(other.to_string()),
51- }
52- }
53-}
54-
55-/// The incumbent's result alias.
56-pub type Result<T> = std::result::Result<T, Error>;
57-
58-/// One decoded frame of audio.
59-#[derive(Debug, Clone)]
60-pub struct DecodedAudio {
61- /// Sample rate in Hz.
62- pub sample_rate: u32,
63- /// Channel count.
64- pub channels: u16,
65- /// Interleaved samples in `[-1, 1]`.
66- pub samples: Vec<f32>,
67-}
68-
69-/// A streaming MP3 decoder.
70-#[derive(Debug, Default)]
71-pub struct Mp3Decoder {
72- reader: ec_mp3::Mp3Reader,
73- queue: VecDeque<DecodedAudio>,
74- eof: bool,
75-}
76-
77-impl Mp3Decoder {
78- /// A decoder with nothing buffered.
79- pub fn new() -> Mp3Decoder {
80- Mp3Decoder::default()
81- }
82-
83- /// Buffers bytes and decodes whatever whole frames they complete.
84- pub fn push(&mut self, bytes: &[u8]) {
85- self.reader.push(bytes);
86- while let Ok(frame) = self.reader.next_frame() {
87- self.queue.push_back(DecodedAudio {
88- sample_rate: frame.sample_rate,
89- channels: frame.channels as u16,
90- samples: frame.samples,
91- });
92- }
93- }
94-
95- /// The next decoded frame, [`Error::Again`] until one is complete and
96- /// [`Error::Eof`] once [`Mp3Decoder::flush`] has been called and drained.
97- pub fn next_frame(&mut self) -> Result<DecodedAudio> {
98- match self.queue.pop_front() {
99- Some(frame) => Ok(frame),
100- None if self.eof => Err(Error::Eof),
101- None => Err(Error::Again),
102- }
103- }
104-
105- /// Marks the end of input.
106- pub fn flush(&mut self) {
107- self.eof = true;
108- }
109-}
110-
111-/// Encoder settings, field for field as the incumbent declares them.
112-#[derive(Debug, Clone, Default)]
113-pub struct Mp3EncoderConfig {
114- /// Constant bitrate in kbit/s.
115- pub bitrate_kbps: u32,
116- /// Quality on a normalised `[0, 1]` scale instead of a bitrate.
117- pub vbr_quality: Option<f32>,
118-}
119-
120-/// The incumbent's quality-to-bitrate curve, in kbit/s.
121-pub fn vbr_quality_index(q: f32) -> f32 {
122- ec_mp3::encode::bitrate_for_quality(q) as f32
123-}
124-
125-/// A streaming MP3 encoder.
126-#[derive(Debug)]
127-pub struct Mp3Encoder {
128- inner: ec_mp3::Mp3Encoder,
129-}
130-
131-impl Mp3Encoder {
132- /// An encoder that configures itself from the first PCM it is given.
133- pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder {
134- Mp3Encoder {
135- inner: ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig {
136- bitrate_kbps: config.bitrate_kbps,
137- vbr_quality: config.vbr_quality,
138- }),
139- }
140- }
141-
142- /// Feeds interleaved `f32` samples.
143- pub fn push_pcm_f32(
144- &mut self,
145- interleaved: &[f32],
146- channels: u16,
147- sample_rate: u32,
148- ) -> Result<()> {
149- Ok(self
150- .inner
151- .push_pcm_f32(interleaved, channels, sample_rate)?)
152- }
153-
154- /// Feeds interleaved 16-bit samples.
155- pub fn push_pcm_s16(
156- &mut self,
157- interleaved: &[i16],
158- channels: u16,
159- sample_rate: u32,
160- ) -> Result<()> {
161- Ok(self
162- .inner
163- .push_pcm_s16(interleaved, channels, sample_rate)?)
164- }
165-
166- /// Ends the stream and flushes the tail.
167- pub fn finish(&mut self) {
168- self.inner.finish();
169- }
170-
171- /// The next complete frame; [`Error::Eof`] once drained after
172- /// [`Mp3Encoder::finish`].
173- pub fn next_packet(&mut self) -> Result<Vec<u8>> {
174- Ok(self.inner.next_packet()?)
175- }
176-}
177-
178-#[cfg(test)]
179-mod tests {
180- use super::*;
181-
182- /// The call shape edith uses, end to end: config in, frames out, and our
183- /// own decoder reads them back.
184- #[test]
185- fn encodes_and_decodes_through_the_incumbent_surface() {
186- let rate = 44100;
187- let pcm: Vec<i16> = (0..rate * 2 / 4)
188- .map(|i| ((i as f32 * 0.05).sin() * 8000.0) as i16)
189- .collect();
190- let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
191- bitrate_kbps: 192,
192- vbr_quality: None,
193- });
194- encoder.push_pcm_s16(&pcm, 2, rate as u32).unwrap();
195- encoder.finish();
196- let mut bytes = Vec::new();
197- while let Ok(frame) = encoder.next_packet() {
198- bytes.extend_from_slice(&frame);
199- }
200- assert!(bytes.len() > 1000, "wrote {} bytes", bytes.len());
201-
202- let mut decoder = Mp3Decoder::new();
203- decoder.push(&bytes);
204- decoder.flush();
205- let mut frames = 0;
206- let mut samples = 0;
207- while let Ok(frame) = decoder.next_frame() {
208- assert_eq!(frame.sample_rate, rate as u32);
209- assert_eq!(frame.channels, 2);
210- frames += 1;
211- samples += frame.samples.len();
212- }
213- assert!(frames > 5, "decoded {frames} frames");
214- assert!(samples >= pcm.len() / 2, "decoded {samples} samples");
215- assert!(matches!(decoder.next_frame(), Err(Error::Eof)));
216- }
217-}
shims/rusty_vorbis/Cargo.tomldeleted+0 -15
@@ -1,15 +0,0 @@
1-[package]
2-name = "rusty_vorbis"
3-description = "Compatibility shim: the rusty_vorbis 0.1.1 surface edith consumes, served by ec-vorbis."
4-version = "0.1.1"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
12-ec-vorbis = { path = "../../crates/ec-vorbis", version = "0.1.0" }
13-
14-[dev-dependencies]
15-ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" }
shims/rusty_vorbis/src/lib.rsdeleted+0 -308
@@ -1,308 +0,0 @@
1-//! Drop-in replacement for the `rusty_vorbis` 0.1.1 surface the replica
2-//! consumes, implemented over [`ec_vorbis`].
3-//!
4-//! It carries the incumbent's package name and version so the swap is a
5-//! `[patch.crates-io]` entry and nothing else. The scope is the API
6-//! `engine/src/export.rs` calls (`export.rs:2850-2862`):
7-//!
8-//! ```no_run
9-//! let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig {
10-//! bitrate_bps: rusty_vorbis::BITRATE_NOMINAL,
11-//! quality: 0.85,
12-//! });
13-//! encoder.push_pcm_s16(&[0i16; 2048], 2, 48_000).unwrap();
14-//! encoder.finish();
15-//! loop {
16-//! match encoder.next_packet() {
17-//! Ok(packet) => { let _ = (&packet.data, packet.pts, packet.duration); }
18-//! Err(rusty_vorbis::Error::Eof) => break,
19-//! Err(e) => panic!("{e}"),
20-//! }
21-//! }
22-//! ```
23-//!
24-//! Two of the incumbent's behaviours are deliberately *not* reproduced, because
25-//! they are the defects this replacement exists to remove — both are corrections
26-//! the replica currently applies by hand at `export.rs:2762-2815` and can delete:
27-//!
28-//! * **No pre-roll hop.** The incumbent's first audio packet advanced the
29-//! granule by a full block hop while decoding to nothing, so every caller had
30-//! to feed a hop of silence and subtract a hop from every granule. Here the
31-//! first block is centred on input sample 0 and [`EncodedPacket::pts`] is the
32-//! true granule, so a caller writes what it is given.
33-//! * **No stereo-only setup header.** The incumbent shipped one embedded stereo
34-//! profile and refused mono ("bad coupling channels") and anything wider. Here
35-//! the setup header is written per stream for whatever channel count is
36-//! pushed, so mono stays mono and 5.1 stays 5.1.
37-//!
38-//! The last packet's `pts` is the input's own sample count, so a file decodes to
39-//! exactly as many samples as went in; the caller does not have to state the
40-//! tail granule itself either.
41-
42-#![forbid(unsafe_code)]
43-#![warn(missing_docs)]
44-
45-use ec_core::Error as EcError;
46-use ec_vorbis::{EncoderConfig, VorbisEncoder as EcEncoder};
47-
48-/// Short block size, as a power of two, that this encoder states.
49-pub const BS0_LOG2: u8 = 11;
50-/// Long block size, as a power of two.
51-pub const BS1_LOG2: u8 = 11;
52-/// The nominal bitrate the replica asks for.
53-pub const BITRATE_NOMINAL: i32 = 128_000;
54-
55-/// Errors this encoder can answer.
56-#[derive(Debug, Clone, PartialEq, Eq)]
57-pub enum Error {
58- /// Something is not implemented.
59- Unimplemented(String),
60- /// No further packet: the encoder is finished and drained.
61- Eof,
62- /// More input is needed before another packet exists.
63- Again,
64- /// The input or the state does not make sense.
65- InvalidData(String),
66- /// A legal request this encoder does not serve.
67- Unsupported(String),
68-}
69-
70-impl Error {
71- /// An [`Error::InvalidData`] with a message.
72- pub fn invalid(msg: impl Into<String>) -> Self {
73- Error::InvalidData(msg.into())
74- }
75-
76- /// An [`Error::Unsupported`] with a message.
77- pub fn unsupported(msg: impl Into<String>) -> Self {
78- Error::Unsupported(msg.into())
79- }
80-}
81-
82-impl std::fmt::Display for Error {
83- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84- match self {
85- Error::Unimplemented(what) => write!(f, "not yet implemented: {what}"),
86- Error::Eof => write!(f, "end of stream"),
87- Error::Again => write!(f, "more input required"),
88- Error::InvalidData(msg) => write!(f, "invalid data: {msg}"),
89- Error::Unsupported(msg) => write!(f, "unsupported: {msg}"),
90- }
91- }
92-}
93-
94-impl std::error::Error for Error {}
95-
96-/// This crate's result type.
97-pub type Result<T> = std::result::Result<T, Error>;
98-
99-fn map(error: EcError) -> Error {
100- match error {
101- EcError::Eof => Error::Eof,
102- EcError::NeedMore => Error::Again,
103- EcError::Unsupported { what, why } => Error::Unsupported(format!("{what} ({why})")),
104- other => Error::InvalidData(other.to_string()),
105- }
106-}
107-
108-/// One packet out of the encoder.
109-#[derive(Debug, Clone, PartialEq, Eq)]
110-pub struct EncodedPacket {
111- /// Packet payload, ready to page.
112- pub data: Vec<u8>,
113- /// Granule position this packet ends at: the number of input samples that
114- /// are decodable once it has been decoded. Zero for the three headers and
115- /// for the first audio packet, which decodes to no samples at all.
116- pub pts: i64,
117- /// Samples this packet finalises.
118- pub duration: i64,
119-}
120-
121-/// How the encoder is set up.
122-#[derive(Debug, Clone, Copy, PartialEq)]
123-pub struct VorbisEncoderConfig {
124- /// Target bitrate in bits per second.
125- pub bitrate_bps: i32,
126- /// Quality on `[0, 1]`.
127- pub quality: f32,
128-}
129-
130-impl Default for VorbisEncoderConfig {
131- fn default() -> VorbisEncoderConfig {
132- VorbisEncoderConfig {
133- bitrate_bps: BITRATE_NOMINAL,
134- quality: 0.5,
135- }
136- }
137-}
138-
139-/// The incumbent's `[0, 1]` quality scale from Vorbis's own `-q` scale.
140-pub fn quality01_from_vorbis_q(q: f64) -> f32 {
141- (((q + 1.0) / 11.0).clamp(0.0, 1.0)) as f32
142-}
143-
144-/// Vorbis encoder over [`ec_vorbis`].
145-///
146-/// Channel count and sample rate arrive with the first push, exactly as they do
147-/// in the incumbent, so the encoder is built lazily and the setup header is
148-/// written for the layout that actually turns up.
149-pub struct VorbisEncoder {
150- config: VorbisEncoderConfig,
151- inner: Option<EcEncoder>,
152- /// Header packets not yet handed out.
153- headers: std::collections::VecDeque<Vec<u8>>,
154- finished: bool,
155-}
156-
157-impl VorbisEncoder {
158- /// A new encoder; nothing is written until the first push states a layout.
159- pub fn new(config: VorbisEncoderConfig) -> Self {
160- VorbisEncoder {
161- config,
162- inner: None,
163- headers: std::collections::VecDeque::new(),
164- finished: false,
165- }
166- }
167-
168- /// Change the quality; takes effect on the next stream.
169- pub fn set_quality(&mut self, quality: f32) {
170- self.config.quality = quality;
171- }
172-
173- /// Change the target bitrate; takes effect on the next stream.
174- pub fn set_bitrate_bps(&mut self, bps: i32) {
175- self.config.bitrate_bps = bps;
176- }
177-
178- /// The three header packets, once a push has stated the layout.
179- pub fn headers(&self) -> Vec<Vec<u8>> {
180- self.inner
181- .as_ref()
182- .map(|encoder| encoder.headers().into_iter().map(<[u8]>::to_vec).collect())
183- .unwrap_or_default()
184- }
185-
186- /// The three headers Xiph-laced, the form a container carries them in.
187- pub fn extradata(&self) -> Vec<u8> {
188- self.inner
189- .as_ref()
190- .map(EcEncoder::extradata)
191- .unwrap_or_default()
192- }
193-
194- /// Push interleaved float samples.
195- pub fn push_pcm_f32(
196- &mut self,
197- interleaved: &[f32],
198- channels: u16,
199- sample_rate: u32,
200- ) -> Result<()> {
201- self.start(channels, sample_rate)?;
202- let encoder = self.inner.as_mut().expect("started");
203- encoder.push_interleaved(interleaved).map_err(map)
204- }
205-
206- /// Push interleaved 16-bit samples, scaled by 1/32768 as every decoder in
207- /// this family scales them.
208- pub fn push_pcm_s16(
209- &mut self,
210- interleaved: &[i16],
211- channels: u16,
212- sample_rate: u32,
213- ) -> Result<()> {
214- let floats: Vec<f32> = interleaved
215- .iter()
216- .map(|&sample| f32::from(sample) / 32_768.0)
217- .collect();
218- self.push_pcm_f32(&floats, channels, sample_rate)
219- }
220-
221- /// No more input; the tail is encoded and the last granule is the input's
222- /// own sample count.
223- pub fn finish(&mut self) {
224- self.finished = true;
225- if let Some(encoder) = self.inner.as_mut() {
226- encoder.finish();
227- }
228- }
229-
230- /// Next packet: the three headers first, then audio, then [`Error::Eof`].
231- pub fn next_packet(&mut self) -> Result<EncodedPacket> {
232- if let Some(data) = self.headers.pop_front() {
233- return Ok(EncodedPacket {
234- data,
235- pts: 0,
236- duration: 0,
237- });
238- }
239- let Some(encoder) = self.inner.as_mut() else {
240- return Err(match self.finished {
241- true => Error::Eof,
242- false => Error::Again,
243- });
244- };
245- let packet = encoder.next_packet().map_err(map)?;
246- Ok(EncodedPacket {
247- data: packet.data,
248- pts: packet.granule,
249- duration: packet.samples,
250- })
251- }
252-
253- /// Build the encoder on the first push and queue its headers.
254- fn start(&mut self, channels: u16, sample_rate: u32) -> Result<()> {
255- if self.inner.is_some() {
256- return Ok(());
257- }
258- if self.finished {
259- return Err(Error::invalid("push after finish"));
260- }
261- let encoder = EcEncoder::new(EncoderConfig {
262- sample_rate,
263- channels,
264- bitrate_bps: self.config.bitrate_bps,
265- quality: self.config.quality,
266- })
267- .map_err(map)?;
268- self.headers = encoder.headers().into_iter().map(<[u8]>::to_vec).collect();
269- self.inner = Some(encoder);
270- Ok(())
271- }
272-}
273-
274-#[cfg(test)]
275-mod tests {
276- use super::*;
277-
278- #[test]
279- fn the_incumbents_call_sequence_yields_headers_then_audio() {
280- let mut encoder = VorbisEncoder::new(VorbisEncoderConfig {
281- bitrate_bps: BITRATE_NOMINAL,
282- quality: 0.85,
283- });
284- // Mono, which the incumbent refused outright.
285- let pcm: Vec<i16> = (0..8_000)
286- .map(|i| ((f64::from(i) * 0.05).sin() * 12_000.0) as i16)
287- .collect();
288- encoder.push_pcm_s16(&pcm, 1, 48_000).unwrap();
289- encoder.finish();
290- let mut packets = Vec::new();
291- loop {
292- match encoder.next_packet() {
293- Ok(packet) => packets.push(packet),
294- Err(Error::Eof) => break,
295- Err(e) => panic!("{e}"),
296- }
297- }
298- assert!(packets.len() > 4, "{} packets", packets.len());
299- assert_eq!(packets[0].data[0], 1, "identification header first");
300- assert_eq!(packets[1].data[0], 3, "comment header second");
301- assert_eq!(packets[2].data[0], 5, "setup header third");
302- // No pre-roll: the first audio packet ends at granule zero, and the
303- // last states the input's own length.
304- assert_eq!(packets[3].pts, 0);
305- assert_eq!(packets.last().unwrap().pts, 8_000);
306- assert_eq!(quality01_from_vorbis_q(-1.0), 0.0);
307- }
308-}
shims/rusty_vorbis/tests/edith_surface.rsdeleted+0 -172
@@ -1,172 +0,0 @@
1-//! The replica's `write_ogg` (`export.rs:2895-2985`) with both of its
2-//! corrections deleted, run end to end.
3-//!
4-//! That deletion *is* the test: no hop of silence in front of the mix, no hop
5-//! subtracted from every granule, no hand-written tail granule, and a mono mix
6-//! written as mono rather than widened to dual mono. What comes out has to
7-//! decode in ffmpeg without a word of complaint and be exactly as long as the
8-//! timeline it came from — which is the promise the replica makes for every
9-//! other audio format.
10-
11-use std::fs::File;
12-use std::path::{Path, PathBuf};
13-use std::process::Command;
14-
15-use ec_core::{
16- AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, Packet,
17- StreamInfo, TimeBase,
18-};
19-
20-fn scratch(name: &str) -> PathBuf {
21- let dir = std::env::temp_dir().join(format!("rusty-vorbis-shim-{}", std::process::id()));
22- std::fs::create_dir_all(&dir).expect("scratch dir");
23- dir.join(name)
24-}
25-
26-/// The replica's own mix, as 16-bit samples: a tone per channel so a channel
27-/// that came out of the wrong hole is visible rather than subtle.
28-fn mix(channels: u16, rate: u32, frames: usize) -> Vec<i16> {
29- let mut samples = Vec::with_capacity(frames * usize::from(channels));
30- for i in 0..frames {
31- for channel in 0..channels {
32- let hz = 220.0 * f64::from(channel + 1);
33- let t = i as f64 / f64::from(rate);
34- let value = (2.0 * std::f64::consts::PI * hz * t).sin() * 0.6;
35- samples.push((value * f64::from(i16::MAX)) as i16);
36- }
37- }
38- samples
39-}
40-
41-/// `write_ogg`, shorn of the workarounds.
42-fn write_ogg(out: &Path, samples: &[i16], channels: u16, rate: u32) {
43- let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig {
44- bitrate_bps: rusty_vorbis::BITRATE_NOMINAL,
45- quality: 0.85,
46- });
47- encoder
48- .push_pcm_s16(samples, channels, rate)
49- .expect("vorbis encode");
50- encoder.finish();
51- let mut packets = Vec::new();
52- loop {
53- match encoder.next_packet() {
54- Ok(packet) => packets.push(packet),
55- Err(rusty_vorbis::Error::Eof) => break,
56- Err(e) => panic!("vorbis encode: {e}"),
57- }
58- }
59- assert!(
60- packets.len() >= 4,
61- "{} packets is not a stream",
62- packets.len()
63- );
64-
65- let extradata = ec_ogg::xiph_lace(&[
66- &packets[0].data[..],
67- &packets[1].data[..],
68- &packets[2].data[..],
69- ])
70- .expect("the three headers lace");
71-
72- let time_base = TimeBase::new(1, i64::from(rate));
73- let mut params = CodecParameters::new(CodecId::Vorbis);
74- params.media = MediaParameters::Audio(AudioParameters {
75- sample_rate: rate,
76- layout: ChannelLayout::from_count(usize::from(channels)),
77- format: None,
78- bits_per_sample: None,
79- });
80- params.extradata = Some(Buf::from_vec(extradata));
81- let mut muxer = ec_ogg::OggMuxer::new(File::create(out).expect("create"));
82- muxer
83- .add_stream(StreamInfo::new(0, time_base, params))
84- .expect("stream");
85- muxer.write_headers().expect("headers");
86- for packet in &packets[3..] {
87- // The granule the encoder states, written through: no hop subtracted,
88- // and no special case for the last packet.
89- let mut out = Packet::new(0, time_base, packet.data.clone());
90- out.side_data.push(ec_ogg::granule_side_data(packet.pts));
91- out.duration = Some(packet.duration);
92- muxer.write_packet(&out).expect("packet");
93- }
94- muxer.finish().expect("trailer");
95-}
96-
97-fn probe(path: &Path, field: &str) -> String {
98- let out = Command::new("ffprobe")
99- .args([
100- "-v",
101- "error",
102- "-select_streams",
103- "a:0",
104- "-show_entries",
105- &format!("stream={field}"),
106- "-of",
107- "default=noprint_wrappers=1:nokey=1",
108- ])
109- .arg(path)
110- .output()
111- .expect("ffprobe");
112- String::from_utf8_lossy(&out.stdout).trim().to_string()
113-}
114-
115-#[test]
116-fn writes_an_ogg_44100_mono_widened_to_stereo() {
117- let path = scratch("write-ogg-44100-widened.ogg");
118- let rate = 44_100u32;
119- let frames = 44_100usize;
120- let mono = mix(1, rate, frames);
121- let widened: Vec<i16> = mono.iter().flat_map(|&s| [s, s]).collect();
122- write_ogg(&path, &widened, 2, rate);
123- let decode = Command::new("ffmpeg")
124- .args(["-v", "error", "-i"])
125- .arg(&path)
126- .args(["-f", "f32le", "-"])
127- .output()
128- .expect("ffmpeg");
129- assert!(decode.stderr.is_empty(), "ffmpeg said {}", String::from_utf8_lossy(&decode.stderr));
130- println!("duration_ts={}", probe(&path, "duration_ts"));
131- let decoded = decode.stdout.len() / 4 / 2;
132- assert_eq!(decoded, frames, "decoded sample count");
133-}
134-
135-#[test]
136-fn writes_an_ogg_the_way_the_replica_would_without_its_corrections() {
137- let rate = 48_000u32;
138- // Deliberately not a whole number of blocks: the grid has to close over it
139- // and the granule has to trim the overshoot back off.
140- let frames = 33_333usize;
141- for channels in [1u16, 2, 6] {
142- let path = scratch(&format!("write-ogg-{channels}ch.ogg"));
143- write_ogg(&path, &mix(channels, rate, frames), channels, rate);
144-
145- // ffmpeg decodes it silently...
146- let decode = Command::new("ffmpeg")
147- .args(["-v", "error", "-i"])
148- .arg(&path)
149- .args(["-f", "f32le", "-"])
150- .output()
151- .expect("ffmpeg");
152- assert!(
153- decode.stderr.is_empty(),
154- "{channels} ch: ffmpeg said {}",
155- String::from_utf8_lossy(&decode.stderr)
156- );
157- // ...for exactly the timeline's own length...
158- assert_eq!(
159- probe(&path, "duration_ts"),
160- frames.to_string(),
161- "{channels} ch: duration"
162- );
163- // ...at the channel count that was pushed, mono included.
164- assert_eq!(
165- probe(&path, "channels"),
166- channels.to_string(),
167- "{channels} ch: channel count"
168- );
169- let decoded = decode.stdout.len() / 4 / usize::from(channels);
170- assert_eq!(decoded, frames, "{channels} ch: decoded sample count");
171- }
172-}
shims/symphonia-codec-aac/Cargo.tomldeleted+0 -12
@@ -1,12 +0,0 @@
1-[package]
2-name = "symphonia-codec-aac"
3-description = "Compatibility shim: the symphonia-codec-aac 0.6 surface edith consumes, served by ec-aac."
4-version = "0.6.0"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-aac = { path = "../../crates/ec-aac", version = "0.1.0" }
12-symphonia-core = { path = "../symphonia-core", version = "0.6.0" }
shims/symphonia-codec-aac/src/lib.rsdeleted+0 -81
@@ -1,81 +0,0 @@
1-//! Compatibility shim: the `symphonia-codec-aac` 0.6 surface edith consumes,
2-//! served by [`ec_aac`].
3-//!
4-//! One difference from the incumbent, and it is the reason this exists:
5-//! **multichannel decodes**. The incumbent refuses anything wider than stereo
6-//! outright (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1
7-//! and 7.1 tracks of a film — edith routes those to a second AAC crate to get
8-//! around it. [`ec_aac`] decodes mono through 7.1 in film channel order, so
9-//! there is nothing to route around.
10-//!
11-//! Written from the signatures edith calls (`AacDecoder::try_new`, then the
12-//! `AudioDecoder` trait) and the crate's published documentation; no symphonia
13-//! source was read.
14-
15-#![forbid(unsafe_code)]
16-
17-use symphonia_core::codecs::audio::{
18- AudioCodecParameters, AudioDecoder, AudioDecoderOptions, GenericAudioBufferRef,
19- well_known::CODEC_ID_AAC,
20-};
21-use symphonia_core::packet::Packet;
22-use symphonia_core::{Error, Result};
23-
24-/// An AAC-LC decoder for one track.
25-pub struct AacDecoder {
26- inner: ec_aac::AacDecoder,
27- params: AudioCodecParameters,
28- out: Vec<f32>,
29- channels: usize,
30-}
31-
32-impl AacDecoder {
33- /// A decoder for the track `params` describes.
34- ///
35- /// The `extra_data` is the `AudioSpecificConfig`; a track with none (raw
36- /// ADTS, which states its configuration in every frame) is accepted and
37- /// configures itself from the first frame.
38- pub fn try_new(
39- params: &AudioCodecParameters,
40- _options: &AudioDecoderOptions,
41- ) -> Result<AacDecoder> {
42- if params.codec != CODEC_ID_AAC {
43- return Err(Error::Unsupported(format!(
44- "codec id {} is not AAC",
45- params.codec.0
46- )));
47- }
48- let inner = match params.extra_data.as_deref() {
49- Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?,
50- None => ec_aac::AacDecoder::new(),
51- };
52- let channels = params.channels.map_or(2, |c| c.count()).max(1) as usize;
53- Ok(AacDecoder {
54- inner,
55- params: params.clone(),
56- out: Vec::new(),
57- channels,
58- })
59- }
60-}
61-
62-impl AudioDecoder for AacDecoder {
63- fn decode(&mut self, packet: &Packet) -> Result<GenericAudioBufferRef<'_>> {
64- let audio = self.inner.decode(&packet.data, Some(packet.pts.value()))?;
65- self.channels = usize::from(audio.channels).max(1);
66- self.out.clear();
67- self.out.extend_from_slice(&audio.samples);
68- Ok(GenericAudioBufferRef::new(&self.out, self.channels))
69- }
70-
71- fn codec_params(&self) -> &AudioCodecParameters {
72- &self.params
73- }
74-
75- fn reset(&mut self) {
76- self.inner = match self.params.extra_data.as_deref() {
77- Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc).unwrap_or_default(),
78- None => ec_aac::AacDecoder::new(),
79- };
80- }
81-}
shims/symphonia-core/Cargo.tomldeleted+0 -11
@@ -1,11 +0,0 @@
1-[package]
2-name = "symphonia-core"
3-description = "Compatibility shim: the symphonia-core 0.6 surface edith consumes, over ec-core."
4-version = "0.6.0"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
shims/symphonia-core/src/codecs.rsdeleted+0 -373
@@ -1,373 +0,0 @@
1-//! Codec identities, stream parameters and the decoder trait.
2-
3-use crate::Result;
4-use crate::packet::Packet;
5-
6-/// Per-media-type parameters, as a track carries them.
7-#[derive(Debug, Clone, PartialEq)]
8-pub enum CodecParameters {
9- /// An audio track.
10- Audio(audio::AudioCodecParameters),
11- /// A video track. Nothing in this family decodes picture through the
12- /// symphonia surface, so it carries only what a listing needs.
13- Video(VideoCodecParameters),
14- /// A subtitle track.
15- Subtitle(SubtitleCodecParameters),
16-}
17-
18-/// What a video track states about itself.
19-#[derive(Debug, Clone, Default, PartialEq)]
20-pub struct VideoCodecParameters {
21- /// Codec identity, in this shim's own numbering.
22- pub codec: u32,
23- /// Coded width.
24- pub width: Option<u16>,
25- /// Coded height.
26- pub height: Option<u16>,
27-}
28-
29-/// What a subtitle track states about itself.
30-#[derive(Debug, Clone, Default, PartialEq)]
31-pub struct SubtitleCodecParameters {
32- /// Codec identity, in this shim's own numbering.
33- pub codec: u32,
34- /// Setup bytes (the ASS header, for instance).
35- pub extra_data: Option<Box<[u8]>>,
36-}
37-
38-/// A codec's name, as a registry reports it.
39-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40-pub struct CodecInfo {
41- /// Short lowercase name, e.g. `"aac"`.
42- pub short_name: &'static str,
43- /// Human-readable name.
44- pub long_name: &'static str,
45-}
46-
47-/// One entry of a codec registry.
48-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49-pub struct CodecDescriptor {
50- /// The identity this entry serves.
51- pub id: audio::AudioCodecId,
52- /// Its names.
53- pub info: CodecInfo,
54-}
55-
56-/// A registry's answer for one audio codec.
57-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58-pub struct AudioDecoderRegistration {
59- /// The codec this registration decodes.
60- pub codec: CodecDescriptor,
61-}
62-
63-/// Audio codecs, parameters and decoders.
64-pub mod audio {
65- use super::*;
66-
67- /// A codec identity. The numbering is this shim's own; only equality
68- /// against the [`well_known`] constants is meaningful.
69- #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
70- pub struct AudioCodecId(pub u32);
71-
72- /// The identities edith names.
73- pub mod well_known {
74- use super::AudioCodecId;
75-
76- /// MPEG-4 AAC.
77- pub const CODEC_ID_AAC: AudioCodecId = AudioCodecId(0x1000);
78- /// Xiph Opus.
79- pub const CODEC_ID_OPUS: AudioCodecId = AudioCodecId(0x1001);
80- /// Xiph Vorbis.
81- pub const CODEC_ID_VORBIS: AudioCodecId = AudioCodecId(0x1002);
82- /// Xiph FLAC.
83- pub const CODEC_ID_FLAC: AudioCodecId = AudioCodecId(0x1003);
84- /// MPEG-1/2 Layer III.
85- pub const CODEC_ID_MP3: AudioCodecId = AudioCodecId(0x1004);
86- /// ALAC.
87- pub const CODEC_ID_ALAC: AudioCodecId = AudioCodecId(0x1005);
88- /// Dolby AC-3.
89- pub const CODEC_ID_AC3: AudioCodecId = AudioCodecId(0x1006);
90- /// Dolby Digital Plus.
91- pub const CODEC_ID_EAC3: AudioCodecId = AudioCodecId(0x1007);
92- /// Dolby TrueHD. No decoder is registered for it, which is how a
93- /// caller learns the track cannot be played.
94- pub const CODEC_ID_TRUEHD: AudioCodecId = AudioCodecId(0x1008);
95- /// DTS and its extensions. No decoder is registered for it either.
96- pub const CODEC_ID_DTS: AudioCodecId = AudioCodecId(0x1009);
97- /// Unsigned 8-bit PCM.
98- pub const CODEC_ID_PCM_U8: AudioCodecId = AudioCodecId(0x1010);
99- /// Signed 16-bit little-endian PCM.
100- pub const CODEC_ID_PCM_S16LE: AudioCodecId = AudioCodecId(0x1011);
101- /// Signed 16-bit big-endian PCM.
102- pub const CODEC_ID_PCM_S16BE: AudioCodecId = AudioCodecId(0x1012);
103- /// Signed 24-bit little-endian PCM.
104- pub const CODEC_ID_PCM_S24LE: AudioCodecId = AudioCodecId(0x1013);
105- /// Signed 32-bit little-endian PCM.
106- pub const CODEC_ID_PCM_S32LE: AudioCodecId = AudioCodecId(0x1014);
107- /// 32-bit float little-endian PCM.
108- pub const CODEC_ID_PCM_F32LE: AudioCodecId = AudioCodecId(0x1015);
109- /// Anything with no identity of its own here.
110- pub const CODEC_ID_NULL: AudioCodecId = AudioCodecId(0);
111- }
112-
113- /// A channel layout, as far as anything here asks: how many there are.
114- #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115- pub struct Channels(pub u32);
116-
117- impl Channels {
118- /// Channels in the layout.
119- pub fn count(&self) -> u32 {
120- self.0
121- }
122- }
123-
124- /// Everything an audio decoder needs before its first packet.
125- #[derive(Debug, Clone, Default, PartialEq)]
126- pub struct AudioCodecParameters {
127- /// Which codec.
128- pub codec: AudioCodecId,
129- /// Sample rate in Hz.
130- pub sample_rate: Option<u32>,
131- /// Channel layout.
132- pub channels: Option<Channels>,
133- /// Coded bit depth, when the container states one.
134- pub bits_per_sample: Option<u32>,
135- /// Codec setup bytes: the AudioSpecificConfig, `OpusHead`, STREAMINFO.
136- pub extra_data: Option<Box<[u8]>>,
137- }
138-
139- impl AudioCodecParameters {
140- /// Empty parameters, filled in by the `with_*` builders.
141- pub fn new() -> AudioCodecParameters {
142- AudioCodecParameters::default()
143- }
144-
145- /// Name the codec.
146- pub fn for_codec(&mut self, codec: AudioCodecId) -> &mut AudioCodecParameters {
147- self.codec = codec;
148- self
149- }
150-
151- /// State the sample rate.
152- pub fn with_sample_rate(&mut self, rate: u32) -> &mut AudioCodecParameters {
153- self.sample_rate = Some(rate);
154- self
155- }
156-
157- /// State the channel layout.
158- pub fn with_channels(&mut self, channels: Channels) -> &mut AudioCodecParameters {
159- self.channels = Some(channels);
160- self
161- }
162-
163- /// State the bit depth.
164- pub fn with_bits_per_sample(&mut self, bits: u32) -> &mut AudioCodecParameters {
165- self.bits_per_sample = Some(bits);
166- self
167- }
168-
169- /// State the codec setup bytes.
170- pub fn with_extra_data(&mut self, data: Box<[u8]>) -> &mut AudioCodecParameters {
171- self.extra_data = Some(data);
172- self
173- }
174- }
175-
176- /// Options a decoder is built with. Nothing here has any, which is what
177- /// `Default` means for it.
178- #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
179- pub struct AudioDecoderOptions {
180- /// Verify the decoded audio against a checksum where the format has
181- /// one. Not implemented by any decoder in this family.
182- pub verify: bool,
183- }
184-
185- /// A decoded block, borrowed from the decoder until its next call.
186- #[derive(Debug, Clone, Copy)]
187- pub struct GenericAudioBufferRef<'a> {
188- samples: &'a [f32],
189- channels: usize,
190- }
191-
192- impl<'a> GenericAudioBufferRef<'a> {
193- /// Wrap interleaved samples.
194- pub fn new(samples: &'a [f32], channels: usize) -> GenericAudioBufferRef<'a> {
195- GenericAudioBufferRef { samples, channels }
196- }
197-
198- /// Channels in the block.
199- pub fn spec_channels(&self) -> usize {
200- self.channels
201- }
202-
203- /// Sample frames in the block.
204- pub fn frames(&self) -> usize {
205- match self.channels {
206- 0 => 0,
207- n => self.samples.len() / n,
208- }
209- }
210-
211- /// Copy the block into `out`, interleaved, replacing what was there.
212- pub fn copy_to_vec_interleaved<S: FromSample>(&self, out: &mut Vec<S>) {
213- out.clear();
214- out.extend(self.samples.iter().map(|&s| S::from_sample(s)));
215- }
216- }
217-
218- /// A sample type [`GenericAudioBufferRef::copy_to_vec_interleaved`] can
219- /// convert to.
220- pub trait FromSample {
221- /// Convert one normalised `f32` sample.
222- fn from_sample(s: f32) -> Self;
223- }
224-
225- impl FromSample for f32 {
226- fn from_sample(s: f32) -> f32 {
227- s
228- }
229- }
230-
231- impl FromSample for i16 {
232- fn from_sample(s: f32) -> i16 {
233- (s.clamp(-1.0, 1.0) * 32767.0) as i16
234- }
235- }
236-
237- impl FromSample for i32 {
238- fn from_sample(s: f32) -> i32 {
239- (f64::from(s.clamp(-1.0, 1.0)) * 2147483647.0) as i32
240- }
241- }
242-
243- /// A decoder: packets in, one block out per packet.
244- pub trait AudioDecoder: Send {
245- /// Decode one packet.
246- fn decode(&mut self, packet: &Packet) -> Result<GenericAudioBufferRef<'_>>;
247-
248- /// The parameters this decoder was built with.
249- fn codec_params(&self) -> &AudioCodecParameters;
250-
251- /// Drop state left over from before a seek.
252- fn reset(&mut self);
253- }
254-}
255-
256-impl CodecParameters {
257- /// The audio half, when this is an audio track.
258- pub fn audio(&self) -> Option<&audio::AudioCodecParameters> {
259- match self {
260- CodecParameters::Audio(p) => Some(p),
261- _ => None,
262- }
263- }
264-}
265-
266-/// The identity a family [`ec_core::CodecId`] answers to here.
267-pub fn audio_codec_id(codec: ec_core::CodecId) -> audio::AudioCodecId {
268- use audio::well_known::*;
269- use ec_core::CodecId;
270- match codec {
271- CodecId::Aac => CODEC_ID_AAC,
272- CodecId::Opus => CODEC_ID_OPUS,
273- CodecId::Vorbis => CODEC_ID_VORBIS,
274- CodecId::Flac => CODEC_ID_FLAC,
275- CodecId::Mp3 => CODEC_ID_MP3,
276- CodecId::Alac => CODEC_ID_ALAC,
277- CodecId::Ac3 => CODEC_ID_AC3,
278- CodecId::EAc3 => CODEC_ID_EAC3,
279- CodecId::TrueHd => CODEC_ID_TRUEHD,
280- CodecId::Dts => CODEC_ID_DTS,
281- // Each PCM width keeps its own identity: mapping them all to one and
282- // back would decode a 24-bit WAVE as 16-bit.
283- CodecId::PcmU8 => CODEC_ID_PCM_U8,
284- CodecId::PcmS16Le => CODEC_ID_PCM_S16LE,
285- CodecId::PcmS16Be => CODEC_ID_PCM_S16BE,
286- CodecId::PcmS24Le => CODEC_ID_PCM_S24LE,
287- CodecId::PcmS32Le => CODEC_ID_PCM_S32LE,
288- CodecId::PcmF32Le => CODEC_ID_PCM_F32LE,
289- _ => CODEC_ID_NULL,
290- }
291-}
292-
293-/// The family codec an identity names, or [`None`] for one nothing here
294-/// decodes.
295-pub fn ec_codec_id(id: audio::AudioCodecId) -> Option<ec_core::CodecId> {
296- use audio::well_known::*;
297- use ec_core::CodecId;
298- Some(match id {
299- CODEC_ID_AAC => CodecId::Aac,
300- CODEC_ID_OPUS => CodecId::Opus,
301- CODEC_ID_VORBIS => CodecId::Vorbis,
302- CODEC_ID_FLAC => CodecId::Flac,
303- CODEC_ID_MP3 => CodecId::Mp3,
304- CODEC_ID_ALAC => CodecId::Alac,
305- CODEC_ID_AC3 => CodecId::Ac3,
306- CODEC_ID_EAC3 => CodecId::EAc3,
307- CODEC_ID_TRUEHD => CodecId::TrueHd,
308- CODEC_ID_DTS => CodecId::Dts,
309- CODEC_ID_PCM_U8 => CodecId::PcmU8,
310- CODEC_ID_PCM_S16LE => CodecId::PcmS16Le,
311- CODEC_ID_PCM_S16BE => CodecId::PcmS16Be,
312- CODEC_ID_PCM_S24LE => CodecId::PcmS24Le,
313- CODEC_ID_PCM_S32LE => CodecId::PcmS32Le,
314- CODEC_ID_PCM_F32LE => CodecId::PcmF32Le,
315- _ => return None,
316- })
317-}
318-
319-/// Family parameters for what a track states, for handing to a family decoder.
320-pub fn ec_parameters(
321- params: &audio::AudioCodecParameters,
322-) -> crate::Result<ec_core::CodecParameters> {
323- let codec = ec_codec_id(params.codec).ok_or_else(|| {
324- crate::Error::Unsupported(format!("no decoder for codec id {}", params.codec.0))
325- })?;
326- let mut out = ec_core::CodecParameters::new(codec);
327- out.extradata = params
328- .extra_data
329- .as_deref()
330- .map(ec_core::packet::Buf::copy_from_slice);
331- out.media = ec_core::registry::MediaParameters::Audio(ec_core::registry::AudioParameters {
332- sample_rate: params.sample_rate.unwrap_or(48_000),
333- layout: ec_core::ChannelLayout::from_count(
334- params.channels.map_or(2, |c| c.count()).max(1) as usize
335- ),
336- format: None,
337- bits_per_sample: params.bits_per_sample,
338- });
339- Ok(out)
340-}
341-
342-/// What a track states, from the family's own description of it.
343-pub fn from_ec_parameters(params: &ec_core::CodecParameters) -> CodecParameters {
344- match params.audio() {
345- Some(audio) => {
346- let mut out = audio::AudioCodecParameters::new();
347- out.for_codec(audio_codec_id(params.codec))
348- .with_sample_rate(audio.sample_rate)
349- .with_channels(audio::Channels(audio.layout.channel_count() as u32));
350- if let Some(bits) = audio.bits_per_sample {
351- out.with_bits_per_sample(bits);
352- }
353- if let Some(extra) = &params.extradata {
354- out.with_extra_data(extra.as_ref().to_vec().into_boxed_slice());
355- }
356- CodecParameters::Audio(out)
357- }
358- None => match params.video() {
359- Some(video) => CodecParameters::Video(VideoCodecParameters {
360- codec: audio_codec_id(params.codec).0,
361- width: Some(video.width as u16),
362- height: Some(video.height as u16),
363- }),
364- None => CodecParameters::Subtitle(SubtitleCodecParameters {
365- codec: audio_codec_id(params.codec).0,
366- extra_data: params
367- .extradata
368- .as_ref()
369- .map(|b| b.as_ref().to_vec().into_boxed_slice()),
370- }),
371- },
372- }
373-}
shims/symphonia-core/src/formats.rsdeleted+0 -141
@@ -1,141 +0,0 @@
1-//! Tracks, the reader trait, and seeking.
2-
3-use crate::Result;
4-use crate::codecs::CodecParameters;
5-use crate::packet::Packet;
6-use crate::units::{Time, TimeBase, Timestamp};
7-
8-/// What kind of stream a track carries.
9-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10-pub enum TrackType {
11- /// Sound.
12- Audio,
13- /// Pictures.
14- Video,
15- /// Timed text or bitmaps.
16- Subtitle,
17-}
18-
19-/// One track of a container.
20-#[derive(Debug, Clone, PartialEq)]
21-pub struct Track {
22- /// The container's own id for the track — a Matroska `TrackNumber`, which
23- /// is what names one language of a dual-audio file.
24- pub id: u32,
25- /// Which kind of stream it is.
26- pub track_type: TrackType,
27- /// Base of this track's timestamps.
28- pub time_base: Option<TimeBase>,
29- /// Sample frames the track holds, when the container states one.
30- pub num_frames: Option<u64>,
31- /// First timestamp.
32- pub start_ts: u64,
33- /// Samples the decoder emits before the first audible one -- an MP3's gapless
34- /// encoder delay, an Opus stream's pre-skip. **Not** dropped by the reader:
35- /// [`num_frames`](Self::num_frames) counts them, so a caller that wants the
36- /// audible stream skips them and takes `num_frames - delay` samples.
37- pub delay: Option<u64>,
38- /// Codec and setup data.
39- pub codec_params: Option<CodecParameters>,
40- /// ISO 639 language tag, when the container carries one.
41- pub language: Option<String>,
42-}
43-
44-/// Options a reader is built with; nothing here has any.
45-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
46-pub struct FormatOptions {
47- /// Build a seek index even when the container carries none.
48- pub enable_gapless: bool,
49-}
50-
51-/// How exactly a seek must land.
52-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53-pub enum SeekMode {
54- /// The nearest random access point at or before the target, from which a
55- /// decoder reaches the target exactly by decoding forward.
56- #[default]
57- Accurate,
58- /// Whatever is cheapest.
59- Coarse,
60-}
61-
62-/// Where to seek to.
63-#[derive(Debug, Clone, Copy, PartialEq)]
64-pub enum SeekTo {
65- /// An instant, on `track_id` or on the default track.
66- Time {
67- /// The instant.
68- time: Time,
69- /// Which track's timeline it is on.
70- track_id: Option<u32>,
71- },
72- /// A timestamp in a track's own base.
73- TimeStamp {
74- /// The timestamp.
75- ts: Timestamp,
76- /// Which track it belongs to.
77- track_id: u32,
78- },
79-}
80-
81-/// Where a seek actually landed.
82-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83-pub struct SeekedTo {
84- /// Track the landing is on.
85- pub track_id: u32,
86- /// What was asked for.
87- pub required_ts: Timestamp,
88- /// What was reached — at or before `required_ts` in [`SeekMode::Accurate`].
89- pub actual_ts: Timestamp,
90-}
91-
92-/// A container reader.
93-pub trait FormatReader: Send {
94- /// Every track the container declares.
95- fn tracks(&self) -> &[Track];
96-
97- /// The first track of `kind`.
98- fn default_track(&self, kind: TrackType) -> Option<&Track>;
99-
100- /// Seek, answering where it landed.
101- fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result<SeekedTo>;
102-
103- /// The next packet, or `Ok(None)` at the end of the stream.
104- fn next_packet(&mut self) -> Result<Option<Packet>>;
105-}
106-
107-/// Format hints from outside the bytes.
108-pub mod probe {
109- /// What the caller knows that the content does not say: a file extension,
110- /// a MIME type. Advisory — every reader in this family sniffs the content
111- /// first and is free to disagree.
112- #[derive(Debug, Clone, Default, PartialEq, Eq)]
113- pub struct Hint {
114- extension: Option<String>,
115- mime_type: Option<String>,
116- }
117-
118- impl Hint {
119- /// A hint that says nothing.
120- pub fn new() -> Hint {
121- Hint::default()
122- }
123-
124- /// Name the file extension, without its dot.
125- pub fn with_extension(&mut self, extension: &str) -> &mut Hint {
126- self.extension = Some(extension.to_string());
127- self
128- }
129-
130- /// Name the MIME type.
131- pub fn mime_type(&mut self, mime: &str) -> &mut Hint {
132- self.mime_type = Some(mime.to_string());
133- self
134- }
135-
136- /// The extension, if one was given.
137- pub fn extension(&self) -> Option<&str> {
138- self.extension.as_deref()
139- }
140- }
141-}
shims/symphonia-core/src/io.rsdeleted+0 -50
@@ -1,50 +0,0 @@
1-//! The source a reader reads from.
2-
3-use std::io::{Read, Seek};
4-
5-/// Anything a reader can be built over: seekable, readable, and movable to the
6-/// thread that will do the reading.
7-pub trait MediaSource: Read + Seek + Send {}
8-
9-impl<T: Read + Seek + Send> MediaSource for T {}
10-
11-/// Options a stream is built with; nothing here has any.
12-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13-pub struct MediaSourceStreamOptions {
14- /// Buffer size a caller would like. This shim buffers in the demuxers
15- /// themselves, so it is advisory.
16- pub buffer_len: usize,
17-}
18-
19-/// A source with a buffer in front of it.
20-pub struct MediaSourceStream {
21- inner: Box<dyn MediaSource>,
22-}
23-
24-impl MediaSourceStream {
25- /// Wrap a source.
26- pub fn new(
27- source: Box<dyn MediaSource>,
28- _options: MediaSourceStreamOptions,
29- ) -> MediaSourceStream {
30- MediaSourceStream { inner: source }
31- }
32-
33- /// Take the source back out, which is how a reader in this family is
34- /// handed the file it will read.
35- pub fn into_inner(self) -> Box<dyn MediaSource> {
36- self.inner
37- }
38-}
39-
40-impl Read for MediaSourceStream {
41- fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
42- self.inner.read(buf)
43- }
44-}
45-
46-impl Seek for MediaSourceStream {
47- fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
48- self.inner.seek(pos)
49- }
50-}
shims/symphonia-core/src/lib.rsdeleted+0 -77
@@ -1,77 +0,0 @@
1-//! Compatibility shim: the `symphonia-core` 0.6 surface edith consumes, over
2-//! [`ec_core`] and (through the `symphonia` shim) [`ec_probe`].
3-//!
4-//! This is the vocabulary half — parameters, packets, units, the reader and
5-//! decoder traits. The registries that build them live in the `symphonia`
6-//! shim, and the AAC decoder seat in `symphonia-codec-aac`, exactly as the
7-//! incumbent splits them.
8-//!
9-//! Written from the signatures edith calls (`crates/engine/src/audio.rs`
10-//! lines 36-53 and their call sites) and the crate's published documentation.
11-//! No symphonia source was read: the incumbent is MPL-2.0 and this family is
12-//! MIT OR Apache-2.0.
13-//!
14-//! **Not the whole crate.** What edith does not call is not here: metadata
15-//! revisions, the sample-buffer zoo, `Signal`/`AudioBuffer` generics, the
16-//! `CodecRegistry` builder API. Each is a small addition when something needs
17-//! it; none is a silent omission.
18-
19-#![forbid(unsafe_code)]
20-
21-pub mod codecs;
22-pub mod formats;
23-pub mod io;
24-pub mod meta;
25-pub mod packet;
26-pub mod units;
27-
28-use std::fmt;
29-
30-/// The incumbent's error type, in the shape callers match on.
31-#[derive(Debug)]
32-pub enum Error {
33- /// Underlying I/O failure.
34- IoError(std::io::Error),
35- /// The bitstream is malformed.
36- DecodeError(String),
37- /// A capability this build does not have, naming what and why.
38- Unsupported(String),
39- /// A seek that could not be served.
40- SeekError(String),
41- /// End of stream.
42- ResetRequired,
43-}
44-
45-/// `Result` with this crate's [`Error`].
46-pub type Result<T> = std::result::Result<T, Error>;
47-
48-impl fmt::Display for Error {
49- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50- match self {
51- Error::IoError(e) => write!(f, "io error: {e}"),
52- Error::DecodeError(e) => write!(f, "decode error: {e}"),
53- Error::Unsupported(e) => write!(f, "unsupported: {e}"),
54- Error::SeekError(e) => write!(f, "seek error: {e}"),
55- Error::ResetRequired => write!(f, "decoder reset required"),
56- }
57- }
58-}
59-
60-impl std::error::Error for Error {}
61-
62-impl From<std::io::Error> for Error {
63- fn from(e: std::io::Error) -> Error {
64- Error::IoError(e)
65- }
66-}
67-
68-impl From<ec_core::Error> for Error {
69- fn from(e: ec_core::Error) -> Error {
70- match e {
71- ec_core::Error::Io(io) => Error::IoError(io),
72- ec_core::Error::Eof | ec_core::Error::NeedMore => Error::ResetRequired,
73- ec_core::Error::Unsupported { .. } => Error::Unsupported(e.to_string()),
74- ec_core::Error::Corrupt { .. } => Error::DecodeError(e.to_string()),
75- }
76- }
77-}
shims/symphonia-core/src/meta.rsdeleted+0 -12
@@ -1,12 +0,0 @@
1-//! Metadata options.
2-//!
3-//! edith passes `MetadataOptions::default()` and never reads a revision back,
4-//! so the tags a file carries are read by `ec_probe::Tags` and surfaced there
5-//! rather than through this type.
6-
7-/// Options metadata is read with.
8-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
9-pub struct MetadataOptions {
10- /// Read cover art as well as text. Nothing here does.
11- pub read_visuals: bool,
12-}
shims/symphonia-core/src/packet.rsdeleted+0 -44
@@ -1,44 +0,0 @@
1-//! One packet of coded bytes.
2-
3-use crate::units::{Duration, Timestamp};
4-
5-/// A packet as a reader hands it out.
6-#[derive(Debug, Clone, PartialEq, Eq)]
7-pub struct Packet {
8- /// Track this packet belongs to.
9- pub track_id: u32,
10- /// Presentation timestamp, in the track's own time base.
11- pub pts: Timestamp,
12- /// How long it plays for.
13- pub dur: Duration,
14- /// The coded bytes.
15- pub data: Box<[u8]>,
16- /// The container's own end-of-packet position, in the track's time base,
17- /// when it states one — an Ogg page's granule above all, which is the
18- /// only way a Vorbis (or FLAC-in-Ogg) stream's true, un-rounded length
19- /// ever reaches the decoder: the codec's own bitstream never states it.
20- pub granule: Option<i64>,
21-}
22-
23-impl Packet {
24- /// A packet over `data`.
25- pub fn new(track_id: u32, pts: Timestamp, dur: Duration, data: &[u8]) -> Packet {
26- Packet {
27- track_id,
28- pts,
29- dur,
30- data: data.to_vec().into_boxed_slice(),
31- granule: None,
32- }
33- }
34-
35- /// The presentation timestamp.
36- pub fn pts(&self) -> Timestamp {
37- self.pts
38- }
39-
40- /// The coded bytes.
41- pub fn buf(&self) -> &[u8] {
42- &self.data
43- }
44-}
shims/symphonia-core/src/units.rsdeleted+0 -134
@@ -1,134 +0,0 @@
1-//! Time, timestamps and the rational base between them.
2-
3-/// A media timestamp, in [`TimeBase`] ticks.
4-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
5-pub struct Timestamp(pub i64);
6-
7-impl Timestamp {
8- /// A timestamp of `ticks`.
9- pub fn new(ticks: i64) -> Timestamp {
10- Timestamp(ticks)
11- }
12-
13- /// The tick count.
14- pub fn value(&self) -> i64 {
15- self.0
16- }
17-}
18-
19-/// A duration in [`TimeBase`] ticks.
20-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
21-pub struct Duration(pub u64);
22-
23-impl Duration {
24- /// A duration of `ticks`.
25- pub fn new(ticks: u64) -> Duration {
26- Duration(ticks)
27- }
28-
29- /// The tick count.
30- pub fn value(&self) -> u64 {
31- self.0
32- }
33-}
34-
35-/// Wall-clock time, split so that no fraction is lost to a float.
36-#[derive(Debug, Clone, Copy, PartialEq, Default)]
37-pub struct Time {
38- /// Whole seconds.
39- pub seconds: u64,
40- /// Fraction of a second, 0.0..1.0.
41- pub frac: f64,
42-}
43-
44-impl Time {
45- /// A time from whole seconds and a fraction.
46- pub fn new(seconds: u64, frac: f64) -> Time {
47- Time { seconds, frac }
48- }
49-
50- /// A time from seconds, or [`None`] for a negative or non-finite input —
51- /// which is what makes a caller check before seeking to it.
52- pub fn try_from_secs_f64(secs: f64) -> Option<Time> {
53- if !secs.is_finite() || secs < 0.0 {
54- return None;
55- }
56- let seconds = secs.trunc() as u64;
57- Some(Time {
58- seconds,
59- frac: secs - secs.trunc(),
60- })
61- }
62-
63- /// This time in seconds.
64- pub fn as_secs_f64(&self) -> f64 {
65- self.seconds as f64 + self.frac
66- }
67-}
68-
69-/// A rational tick duration: `numer / denom` seconds.
70-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71-pub struct TimeBase {
72- /// Numerator, in seconds.
73- pub numer: u32,
74- /// Denominator.
75- pub denom: u32,
76-}
77-
78-impl TimeBase {
79- /// A time base of `numer / denom` seconds per tick.
80- pub fn new(numer: u32, denom: u32) -> TimeBase {
81- TimeBase { numer, denom }
82- }
83-
84- /// `ts` as wall-clock time; a base with a zero denominator answers zero
85- /// rather than dividing by it.
86- pub fn calc_time_saturating(&self, ts: Timestamp) -> Time {
87- if self.denom == 0 {
88- return Time::default();
89- }
90- let secs = ts.0 as f64 * f64::from(self.numer) / f64::from(self.denom);
91- Time::try_from_secs_f64(secs).unwrap_or_default()
92- }
93-
94- /// The timestamp `time` falls on in this base.
95- pub fn calc_timestamp(&self, time: Time) -> Timestamp {
96- if self.numer == 0 {
97- return Timestamp::default();
98- }
99- Timestamp((time.as_secs_f64() * f64::from(self.denom) / f64::from(self.numer)) as i64)
100- }
101-}
102-
103-impl From<ec_core::TimeBase> for TimeBase {
104- fn from(tb: ec_core::TimeBase) -> TimeBase {
105- TimeBase::new(tb.num().max(0) as u32, tb.den().max(1) as u32)
106- }
107-}
108-
109-impl From<TimeBase> for ec_core::TimeBase {
110- fn from(tb: TimeBase) -> ec_core::TimeBase {
111- ec_core::TimeBase::new(i64::from(tb.numer.max(1)), i64::from(tb.denom.max(1)))
112- }
113-}
114-
115-#[cfg(test)]
116-mod tests {
117- use super::*;
118-
119- #[test]
120- fn a_timestamp_round_trips_through_its_base() {
121- let base = TimeBase::new(1, 48_000);
122- let time = base.calc_time_saturating(Timestamp::new(96_000));
123- assert_eq!(time.as_secs_f64(), 2.0);
124- assert_eq!(base.calc_timestamp(time), Timestamp::new(96_000));
125- // A negative instant is not a time, and says so rather than wrapping.
126- assert_eq!(Time::try_from_secs_f64(-1.0), None);
127- assert_eq!(
128- TimeBase::new(1, 0)
129- .calc_time_saturating(Timestamp::new(5))
130- .as_secs_f64(),
131- 0.0
132- );
133- }
134-}
shims/symphonia/Cargo.tomldeleted+0 -40
@@ -1,40 +0,0 @@
1-[package]
2-name = "symphonia"
3-description = "Compatibility shim: the symphonia 0.6 umbrella surface edith consumes, served by ec-probe."
4-version = "0.6.0"
5-edition = "2024"
6-license = "MIT OR Apache-2.0"
7-authors = ["Ahmet Kaan Gümüş"]
8-publish = false
9-
10-[dependencies]
11-ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
12-ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" }
13-ec-probe = { path = "../../crates/ec-probe", version = "0.1.0" }
14-symphonia-core = { path = "../symphonia-core", version = "0.6.0" }
15-
16-[dev-dependencies]
17-ec-testkit.workspace = true
18-symphonia-codec-aac = { path = "../symphonia-codec-aac", version = "0.6.0" }
19-ec-vorbis = { path = "../../crates/ec-vorbis", version = "0.1.0" }
20-rusty_vorbis = { path = "../rusty_vorbis", version = "0.1.1" }
21-
22-# The incumbent's feature names, every one of them a no-op: a caller selects
23-# codecs and containers there, and here `ec_probe` serves all of them
24-# unconditionally. They are declared because a feature list is part of the
25-# surface a `[patch.crates-io]` entry has to answer — a consumer naming
26-# `features = ["mkv"]` fails to resolve otherwise, which is not a difference
27-# worth making it edit its manifest for.
28-[features]
29-aac = []
30-alac = []
31-flac = []
32-id3v1 = []
33-id3v2 = []
34-isomp4 = []
35-mkv = []
36-mp3 = []
37-ogg = []
38-pcm = []
39-vorbis = []
40-wav = []
shims/symphonia/src/lib.rsdeleted+0 -137
@@ -1,137 +0,0 @@
1-//! Compatibility shim: the `symphonia` 0.6 umbrella surface edith consumes,
2-//! served by [`ec_probe`].
3-//!
4-//! Two registries, exactly as the incumbent has them:
5-//! [`default::get_probe`] opens a file and [`default::get_codecs`] builds a
6-//! decoder for one of its tracks. Underneath, both are `ec_probe`: one sniffing
7-//! reader over WAV, MP3, FLAC, ADTS, Ogg, mp4 and Matroska, and one decoder
8-//! seat over the family's codecs.
9-//!
10-//! Two behaviours differ from the incumbent, deliberately, because they are
11-//! defects edith works around today:
12-//!
13-//! - **A seek is reliable more than once per reader.** The incumbent's mkv
14-//! seek neither clears its queued frames nor recovers its element iterator,
15-//! so edith opens a *new reader per seek attempt*
16-//! (`crates/engine/src/audio.rs`, `SymTrack::seek_to`). Here every seek is
17-//! served on the one reader the file was opened with, and the landing it
18-//! reports is the next packet's own timestamp.
19-//! - **A multichannel AAC track decodes.** The incumbent refuses anything
20-//! wider than stereo (`aac: aac too complex`), which is exactly a film's 5.1;
21-//! [`ec_aac`] decodes to 7.1, so `make_audio_decoder` does not refuse it.
22-//!
23-//! Written from the signatures edith calls and the crate's published
24-//! documentation; no symphonia source was read (it is MPL-2.0, this family is
25-//! MIT OR Apache-2.0).
26-
27-#![forbid(unsafe_code)]
28-
29-pub use symphonia_core as core;
30-
31-mod reader;
32-
33-use symphonia_core::codecs::audio::{
34- AudioCodecId, AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::*,
35-};
36-use symphonia_core::codecs::{
37- AudioDecoderRegistration, CodecDescriptor, CodecInfo, ec_codec_id, ec_parameters,
38-};
39-use symphonia_core::formats::{FormatOptions, FormatReader, probe::Hint};
40-use symphonia_core::io::MediaSourceStream;
41-use symphonia_core::meta::MetadataOptions;
42-use symphonia_core::{Error, Result};
43-
44-pub use reader::ProbeReader;
45-
46-/// The registries, as the incumbent hands them out.
47-pub mod default {
48- use super::{CodecRegistry, Probe};
49-
50- /// The format probe: content-sniffing, extension-hinted.
51- pub fn get_probe() -> &'static Probe {
52- &Probe
53- }
54-
55- /// The codec registry.
56- pub fn get_codecs() -> &'static CodecRegistry {
57- &CodecRegistry
58- }
59-}
60-
61-/// Opens a media source as whatever it turns out to be.
62-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63-pub struct Probe;
64-
65-impl Probe {
66- /// Open `source`, using `hint` only where the content says nothing.
67- pub fn probe(
68- &self,
69- hint: &Hint,
70- source: MediaSourceStream,
71- _format: FormatOptions,
72- _metadata: MetadataOptions,
73- ) -> Result<Box<dyn FormatReader>> {
74- let reader = ec_probe::Reader::new(source.into_inner(), hint.extension())?;
75- Ok(Box::new(ProbeReader::new(reader)))
76- }
77-}
78-
79-/// Which codecs have a decoder behind them.
80-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81-pub struct CodecRegistry;
82-
83-/// Every codec this registry serves, with the name it reports.
84-const REGISTERED: &[(AudioCodecId, &str, &str)] = &[
85- (CODEC_ID_AAC, "aac", "Advanced Audio Coding"),
86- (CODEC_ID_OPUS, "opus", "Opus"),
87- (CODEC_ID_VORBIS, "vorbis", "Vorbis"),
88- (CODEC_ID_FLAC, "flac", "Free Lossless Audio Codec"),
89- (CODEC_ID_MP3, "mp3", "MPEG-1/2 Audio Layer III"),
90- (CODEC_ID_ALAC, "alac", "ALAC"),
91- (CODEC_ID_AC3, "ac3", "Dolby Digital"),
92- (CODEC_ID_EAC3, "eac3", "Dolby Digital Plus"),
93- (CODEC_ID_PCM_U8, "pcm_u8", "PCM unsigned 8-bit"),
94- (CODEC_ID_PCM_S16LE, "pcm_s16le", "PCM signed 16-bit LE"),
95- (CODEC_ID_PCM_S16BE, "pcm_s16be", "PCM signed 16-bit BE"),
96- (CODEC_ID_PCM_S24LE, "pcm_s24le", "PCM signed 24-bit LE"),
97- (CODEC_ID_PCM_S32LE, "pcm_s32le", "PCM signed 32-bit LE"),
98- (CODEC_ID_PCM_F32LE, "pcm_f32le", "PCM float 32-bit LE"),
99- // TrueHD and DTS are deliberately absent: nothing in this family decodes
100- // them, so a caller asking gets `None` and can say so.
101-];
102-
103-impl CodecRegistry {
104- /// The registration for `codec`, or [`None`] when nothing decodes it.
105- pub fn get_audio_decoder(&self, codec: AudioCodecId) -> Option<AudioDecoderRegistration> {
106- REGISTERED
107- .iter()
108- .find(|(id, ..)| *id == codec)
109- .map(|&(id, short_name, long_name)| AudioDecoderRegistration {
110- codec: CodecDescriptor {
111- id,
112- info: CodecInfo {
113- short_name,
114- long_name,
115- },
116- },
117- })
118- }
119-
120- /// Build a decoder for `params`.
121- pub fn make_audio_decoder(
122- &self,
123- params: &AudioCodecParameters,
124- _options: &AudioDecoderOptions,
125- ) -> Result<Box<dyn AudioDecoder>> {
126- if self.get_audio_decoder(params.codec).is_none() {
127- let named = ec_codec_id(params.codec).map_or("this codec", |c| c.name());
128- return Err(Error::Unsupported(format!(
129- "{named}: no decoder for it exists in this family"
130- )));
131- }
132- Ok(Box::new(reader::EcAudioDecoder::new(
133- ec_probe::AudioDecoder::new(&ec_parameters(params)?)?,
134- params.clone(),
135- )))
136- }
137-}
shims/symphonia/src/reader.rsdeleted+0 -215
@@ -1,215 +0,0 @@
1-//! The reader and decoder seats: `ec_probe` behind the incumbent's traits.
2-
3-use symphonia_core::Result;
4-use symphonia_core::codecs::audio::{AudioCodecParameters, AudioDecoder, GenericAudioBufferRef};
5-use symphonia_core::codecs::from_ec_parameters;
6-use symphonia_core::formats::{FormatReader, SeekMode, SeekTo, SeekedTo, Track, TrackType};
7-use symphonia_core::packet::Packet;
8-use symphonia_core::units::{Duration, TimeBase, Timestamp};
9-
10-use ec_core::registry::MediaType;
11-
12-/// One open file: the tracks it declares, and its packets.
13-///
14-/// Track ids are the *container's* own — a Matroska `TrackNumber` — so a
15-/// caller that named one track by number gets that track back and not the one
16-/// that happened to be at the same index.
17-pub struct ProbeReader {
18- inner: ec_probe::Reader,
19- tracks: Vec<Track>,
20- /// Audio track ids still owed their terminal, empty-data packet once the
21- /// container itself has run out: `None` before that, then the queue,
22- /// draining to empty rather than back to `None` so a second real EOF read
23- /// hands out nothing more than once each.
24- eos_pending: Option<std::vec::IntoIter<u32>>,
25-}
26-
27-impl ProbeReader {
28- /// Wrap an open [`ec_probe::Reader`].
29- pub fn new(inner: ec_probe::Reader) -> ProbeReader {
30- let tracks = inner
31- .streams()
32- .iter()
33- .map(|s| Track {
34- id: inner.native_id(s.index) as u32,
35- track_type: match s.params.codec.media_type() {
36- MediaType::Audio => TrackType::Audio,
37- MediaType::Video => TrackType::Video,
38- MediaType::Subtitle => TrackType::Subtitle,
39- },
40- time_base: Some(TimeBase::from(s.time_base)),
41- num_frames: s.duration.map(|d| d.max(0) as u64),
42- start_ts: s.start_time.unwrap_or(0).max(0) as u64,
43- delay: Some(u64::from(s.initial_padding)).filter(|d| *d > 0),
44- codec_params: Some(from_ec_parameters(&s.params)),
45- language: s.language.clone(),
46- })
47- .collect();
48- ProbeReader {
49- inner,
50- tracks,
51- eos_pending: None,
52- }
53- }
54-
55- /// The stream index behind a track id.
56- fn stream_of(&self, id: u32) -> Option<u32> {
57- self.inner.stream_of_native(u64::from(id))
58- }
59-
60- /// The time base of a track id.
61- fn base_of(&self, id: u32) -> ec_core::TimeBase {
62- self.stream_of(id)
63- .and_then(|s| self.inner.streams().iter().find(|i| i.index == s))
64- .map(|s| s.time_base)
65- .unwrap_or(ec_core::TimeBase::MILLIS)
66- }
67-}
68-
69-impl FormatReader for ProbeReader {
70- fn tracks(&self) -> &[Track] {
71- &self.tracks
72- }
73-
74- fn default_track(&self, kind: TrackType) -> Option<&Track> {
75- // The container's flagged track, not merely the first one of its kind:
76- // a dual-audio remux that marked its second track default opens in that
77- // language, which is what a caller asking for "the audio" means by it.
78- let media = match kind {
79- TrackType::Audio => MediaType::Audio,
80- TrackType::Video => MediaType::Video,
81- TrackType::Subtitle => MediaType::Subtitle,
82- };
83- let index = self.inner.default_stream(media)?.index;
84- self.tracks.get(index as usize)
85- }
86-
87- fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result<SeekedTo> {
88- let (time, track_id) = match to {
89- SeekTo::Time { time, track_id } => (time.as_secs_f64(), track_id),
90- SeekTo::TimeStamp { ts, track_id } => {
91- let base = self.base_of(track_id);
92- (ts.value() as f64 * base.as_secs_f64(), Some(track_id))
93- }
94- };
95- let id = track_id
96- .or_else(|| self.default_track(TrackType::Audio).map(|t| t.id))
97- .unwrap_or(0);
98- let stream = self.stream_of(id).unwrap_or(0);
99- let base = self.base_of(id);
100- let ticks = (time / base.as_secs_f64()) as i64;
101- let landed = self.inner.seek(
102- stream,
103- ec_core::Timestamp::new(ticks, base),
104- match mode {
105- // Both modes land at or before the target: it is the only
106- // landing a decoder can reach the exact sample from.
107- SeekMode::Accurate | SeekMode::Coarse => ec_core::SeekMode::SyncBefore,
108- },
109- )?;
110- Ok(SeekedTo {
111- track_id: id,
112- required_ts: Timestamp::new(ticks),
113- actual_ts: Timestamp::new(landed.ticks),
114- })
115- }
116-
117- fn next_packet(&mut self) -> Result<Option<Packet>> {
118- if let Some(pending) = &mut self.eos_pending {
119- // Empty data is the flush signal `EcAudioDecoder::decode` reads:
120- // a real packet is never zero bytes for any codec this family
121- // decodes.
122- return Ok(pending
123- .next()
124- .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[])));
125- }
126- match self.inner.next_packet() {
127- Ok(packet) => {
128- let id = self.inner.native_id(packet.stream) as u32;
129- let granule = ec_ogg::granule_of(&packet);
130- let mut out = Packet::new(
131- id,
132- Timestamp::new(packet.pts.unwrap_or(0)),
133- Duration::new(packet.duration.unwrap_or(0).max(0) as u64),
134- &packet.data,
135- );
136- out.granule = granule;
137- Ok(Some(out))
138- }
139- Err(e) if e.is_eof() => {
140- // The container itself is exhausted: give every audio track
141- // one last, empty packet so its decoder is told to flush the
142- // hop it has been holding back, then report real EOF.
143- let ids: Vec<u32> = self
144- .tracks
145- .iter()
146- .filter(|t| t.track_type == TrackType::Audio)
147- .map(|t| t.id)
148- .collect();
149- let mut ids = ids.into_iter();
150- let first = ids
151- .next()
152- .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[]));
153- self.eos_pending = Some(ids);
154- Ok(first)
155- }
156- Err(e) => Err(e.into()),
157- }
158- }
159-}
160-
161-/// One decoder seat over [`ec_probe::AudioDecoder`].
162-pub(crate) struct EcAudioDecoder {
163- inner: ec_probe::AudioDecoder,
164- params: AudioCodecParameters,
165- out: Vec<f32>,
166-}
167-
168-impl EcAudioDecoder {
169- pub(crate) fn new(
170- inner: ec_probe::AudioDecoder,
171- params: AudioCodecParameters,
172- ) -> EcAudioDecoder {
173- EcAudioDecoder {
174- inner,
175- params,
176- out: Vec::new(),
177- }
178- }
179-}
180-
181-impl AudioDecoder for EcAudioDecoder {
182- fn decode(&mut self, packet: &Packet) -> Result<GenericAudioBufferRef<'_>> {
183- if packet.data.is_empty() {
184- // `ProbeReader::next_packet`'s terminal, empty packet: the file
185- // has run out, and this is the signal to release whatever the
186- // decoder was holding back rather than decode nothing.
187- self.inner.flush(&mut self.out)?;
188- } else {
189- let rate = self.inner.sample_rate().max(1);
190- let mut ec = ec_core::Packet::new(
191- packet.track_id,
192- ec_core::TimeBase::from_rate(rate),
193- packet.data.as_ref(),
194- );
195- ec.pts = Some(packet.pts.value());
196- ec.duration = Some(packet.dur.value() as i64);
197- if let Some(granule) = packet.granule {
198- ec.side_data.push(ec_ogg::granule_side_data(granule));
199- }
200- self.inner.decode(&ec, &mut self.out)?;
201- }
202- Ok(GenericAudioBufferRef::new(
203- &self.out,
204- self.inner.channels().max(1),
205- ))
206- }
207-
208- fn codec_params(&self) -> &AudioCodecParameters {
209- &self.params
210- }
211-
212- fn reset(&mut self) {
213- self.inner.reset();
214- }
215-}
shims/symphonia/tests/edith_surface.rsdeleted+0 -458
@@ -1,458 +0,0 @@
1-//! The shim driven exactly as edith drives symphonia.
2-//!
3-//! Every call here is copied in shape from `edith/crates/engine/src/audio.rs`
4-//! (the `SymTrack` reader at 1461-1668 and the `SymDecoder` at 1692-1740), so a
5-//! green run means the replica's audio path compiles and *works* against this
6-//! shim rather than merely type-checking against it.
7-
8-use std::fs::File;
9-use std::path::Path;
10-
11-use symphonia_codec_aac::AacDecoder;
12-use symphonia_core::codecs::CodecParameters;
13-use symphonia_core::codecs::audio::{
14- AudioCodecParameters, AudioDecoder, AudioDecoderOptions,
15- well_known::{CODEC_ID_AAC, CODEC_ID_OPUS},
16-};
17-use symphonia_core::formats::probe::Hint;
18-use symphonia_core::formats::{
19- FormatOptions, FormatReader, SeekMode, SeekTo, TrackType as SymKind,
20-};
21-use symphonia_core::io::MediaSourceStream;
22-use symphonia_core::meta::MetadataOptions;
23-use symphonia_core::units::{Time, TimeBase, Timestamp};
24-
25-fn fixture(name: &str) -> std::path::PathBuf {
26- ec_testkit::fixture(&format!("audio/{name}"))
27-}
28-
29-/// edith's `sym_reader`, verbatim in shape.
30-fn sym_reader(path: &Path) -> Box<dyn FormatReader> {
31- let mss = MediaSourceStream::new(
32- Box::new(File::open(path).expect("open")),
33- Default::default(),
34- );
35- let mut hint = Hint::new();
36- if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
37- hint.with_extension(ext);
38- }
39- symphonia::default::get_probe()
40- .probe(
41- &hint,
42- mss,
43- FormatOptions::default(),
44- MetadataOptions::default(),
45- )
46- .expect("probe")
47-}
48-
49-/// edith's `SymTrack::open_inner`, verbatim in shape.
50-struct SymTrack {
51- reader: Box<dyn FormatReader>,
52- track_id: u32,
53- sample_rate: u32,
54- channels: u16,
55- total_samples: Option<u64>,
56- time_base: TimeBase,
57- params: AudioCodecParameters,
58- codec: &'static str,
59-}
60-
61-impl SymTrack {
62- fn open(path: &Path) -> Option<SymTrack> {
63- let reader = sym_reader(path);
64- let track = reader.default_track(SymKind::Audio)?;
65- let (track_id, num_frames) = (track.id, track.num_frames);
66- let time_base = track.time_base.expect("a time base");
67- let Some(CodecParameters::Audio(params)) = track.codec_params.clone() else {
68- panic!("no audio codec parameters");
69- };
70- let sample_rate = params.sample_rate.expect("a sample rate");
71- let channels = params
72- .channels
73- .as_ref()
74- .map(|c| c.count() as u16)
75- .expect("a layout");
76- let codec = symphonia::default::get_codecs()
77- .get_audio_decoder(params.codec)
78- .map_or("an unsupported format", |d| d.codec.info.short_name);
79- Some(SymTrack {
80- reader,
81- track_id,
82- sample_rate,
83- channels,
84- total_samples: num_frames,
85- time_base,
86- params,
87- codec,
88- })
89- }
90-
91- /// edith's `SymTrack::decoder`, minus the two routes it takes away from
92- /// symphonia (multichannel AAC and Opus) — which is the point: this shim
93- /// serves them itself.
94- fn decoder(&self) -> Box<dyn AudioDecoder> {
95- if self.params.codec == CODEC_ID_AAC {
96- return Box::new(
97- AacDecoder::try_new(&self.params, &AudioDecoderOptions::default()).expect("aac"),
98- );
99- }
100- symphonia::default::get_codecs()
101- .make_audio_decoder(&self.params, &AudioDecoderOptions::default())
102- .expect("decoder")
103- }
104-
105- /// edith's `samples_at`.
106- fn samples_at(&self, ts: Timestamp) -> u64 {
107- let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
108- (secs.max(0.0) * f64::from(self.sample_rate)) as u64
109- }
110-
111- /// edith's `seek_to`, on **one** reader — the loop that reopens the file
112- /// per attempt exists because the incumbent's mkv seek works once.
113- fn seek_to(&mut self, secs: f64) -> f64 {
114- let time = Time::try_from_secs_f64(secs).expect("a time");
115- let to = SeekTo::Time {
116- time,
117- track_id: Some(self.track_id),
118- };
119- let landed = self.reader.seek(SeekMode::Accurate, to).expect("seek");
120- self.time_base
121- .calc_time_saturating(landed.actual_ts)
122- .as_secs_f64()
123- }
124-}
125-
126-/// Open, describe, decode: what edith does for every standalone audio file and
127-/// for the sound of a Matroska one.
128-#[test]
129-fn every_file_opens_describes_and_decodes_through_the_shim() {
130- let files = [
131- ("wav16-stereo-48000.wav", "pcm_s16le", 2),
132- ("flac-5.1-44100.flac", "flac", 6),
133- ("mp3-stereo-48000.mp3", "mp3", 2),
134- ("aac-adts-stereo-48000.aac", "aac", 2),
135- ("alac-mp4-stereo-44100.m4a", "alac", 2),
136- ("vorbis-ogg-stereo-48000.ogg", "vorbis", 2),
137- ("opus-ogg-5.1-48000.opus", "opus", 6),
138- ("aac-mka-stereo-48000.mka", "aac", 2),
139- ("av-h264-aac-stereo-48000.mkv", "aac", 2),
140- ];
141- for (name, codec, channels) in files {
142- let path = fixture(name);
143- let mut track = SymTrack::open(&path).unwrap_or_else(|| panic!("{name}: no audio track"));
144- assert_eq!(track.codec, codec, "{name}: codec name");
145- assert_eq!(track.channels, channels, "{name}: channels");
146- assert!(track.total_samples.unwrap_or(0) > 0, "{name}: no duration");
147-
148- let mut decoder = track.decoder();
149- let mut out = Vec::new();
150- let mut frames = 0u64;
151- let mut first_pts = None;
152- while let Some(packet) = track.reader.next_packet().expect("demux") {
153- if packet.track_id != track.track_id {
154- continue;
155- }
156- first_pts.get_or_insert_with(|| track.samples_at(packet.pts));
157- decoder
158- .decode(&packet)
159- .expect("decode")
160- .copy_to_vec_interleaved::<f32>(&mut out);
161- frames += (out.len() / usize::from(track.channels)) as u64;
162- }
163- assert_eq!(first_pts, Some(0), "{name}: first packet is not at zero");
164- let want = track.total_samples.unwrap_or(0);
165- assert!(
166- frames * 20 > want * 19,
167- "{name}: decoded {frames} of {want} frames"
168- );
169- }
170- eprintln!("edith's symphonia surface: {} files opened and decoded", files.len());
171-}
172-
173-/// The defect this shim exists to fix: the incumbent's Matroska seek is
174-/// reliable exactly once per reader, so edith opens a new reader per attempt.
175-/// Here twenty seeks in a row are served on one reader, each landing at or
176-/// before its target, and the audio still decodes from every landing.
177-#[test]
178-fn twenty_seeks_on_one_reader_all_land() {
179- for name in ["av-h264-aac-stereo-48000.mkv", "aac-mka-stereo-48000.mka"] {
180- let path = fixture(name);
181- let mut track = SymTrack::open(&path).expect("track");
182- let mut decoder = track.decoder();
183- let mut out = Vec::new();
184- for i in 0..20 {
185- let target = 0.1 + (i as f64 * 0.13) % 2.5;
186- let landed = track.seek_to(target);
187- assert!(
188- landed <= target + 0.001,
189- "{name}: seek {i} to {target:.3}s landed at {landed:.3}s"
190- );
191- let mut decoded = 0;
192- for _ in 0..8 {
193- let Some(packet) = track.reader.next_packet().expect("demux") else {
194- break;
195- };
196- if packet.track_id != track.track_id {
197- continue;
198- }
199- decoder
200- .decode(&packet)
201- .expect("decode after a seek")
202- .copy_to_vec_interleaved::<f32>(&mut out);
203- decoded += out.len();
204- }
205- assert!(decoded > 0, "{name}: nothing decoded after seek {i}");
206- }
207- eprintln!("{name}: 20 seeks, one reader, every landing at or before its target");
208- }
209-}
210-
211-/// The other incumbent defect: `aac: aac too complex` for anything wider than
212-/// stereo. A 5.1 AAC track decodes here, through the AAC shim, as 6 channels.
213-#[test]
214-fn multichannel_aac_decodes_rather_than_being_refused() {
215- let path = fixture("aac-mp4-5.1-44100.mp4");
216- let mut track = SymTrack::open(&path).expect("track");
217- assert_eq!(track.channels, 6);
218- let mut decoder = track.decoder();
219- let mut out = Vec::new();
220- let packet = loop {
221- let packet = track
222- .reader
223- .next_packet()
224- .expect("demux")
225- .expect("a packet");
226- if packet.track_id == track.track_id {
227- break packet;
228- }
229- };
230- decoder
231- .decode(&packet)
232- .expect("5.1 AAC decodes")
233- .copy_to_vec_interleaved::<f32>(&mut out);
234- assert_eq!(out.len() % 6, 0);
235- assert!(out.len() >= 6 * 1024, "a 5.1 frame is 1024 samples wide");
236-}
237-
238-/// Opus: the incumbent has no decoder for it at any version, and edith carries
239-/// a second crate for that alone. Here the registry answers.
240-#[test]
241-fn opus_has_a_decoder_in_the_registry() {
242- let registration = symphonia::default::get_codecs().get_audio_decoder(CODEC_ID_OPUS);
243- assert_eq!(
244- registration.map(|r| r.codec.info.short_name),
245- Some("opus"),
246- "the registry must name an Opus decoder"
247- );
248- // ...and a TrueHD track has none, which is how a caller learns to say so.
249- let truehd = symphonia_core::codecs::audio::well_known::CODEC_ID_TRUEHD;
250- assert!(
251- symphonia::default::get_codecs()
252- .get_audio_decoder(truehd)
253- .is_none()
254- );
255- let params = {
256- let mut p = AudioCodecParameters::new();
257- p.for_codec(truehd).with_sample_rate(48_000);
258- p
259- };
260- let refusal = match symphonia::default::get_codecs()
261- .make_audio_decoder(&params, &AudioDecoderOptions::default())
262- {
263- Ok(_) => panic!("a TrueHD decoder was built out of nothing"),
264- Err(e) => e.to_string(),
265- };
266- assert!(
267- refusal.contains("truehd"),
268- "the refusal names the codec: {refusal}"
269- );
270-}
271-
272-/// Regression for `open: NeedMore` on a real mp3 whose ID3v2 header carries a
273-/// large APIC cover-art picture and whose tail carries an ID3v1 `TAG` block:
274-/// the probe must skip both rather than reading a bounded head short of the
275-/// first mp3 frame sync, or getting confused reading a 128-byte tail as audio.
276-/// Built out of a plain mp3 fixture wrapped in a synthetic 2 MB ID3v2 APIC
277-/// header and an ID3v1 tail, so this needs no real file on disk.
278-#[test]
279-fn cover_art_and_id3v1_tail_do_not_stop_the_probe() {
280- let raw = std::fs::read(fixture("mp3-stereo-48000.mp3")).expect("fixture mp3");
281- // A 2 MB ID3v2.3 tag: one oversized `APIC` frame of filler bytes. The
282- // probe only needs to skip past the tag's declared size, so the frame
283- // body's content does not matter.
284- let apic_body_len = 2_000_000usize;
285- let mut id3 = Vec::new();
286- id3.extend_from_slice(b"ID3");
287- id3.extend_from_slice(&[3, 0, 0]); // version 2.3.0, no flags
288- let frame_len = apic_body_len as u32;
289- let tag_size = 10 + apic_body_len as u32; // one frame header (10) + body
290- id3.extend_from_slice(&syncsafe(tag_size));
291- id3.extend_from_slice(b"APIC");
292- id3.extend_from_slice(&frame_len.to_be_bytes());
293- id3.extend_from_slice(&[0, 0]); // frame flags
294- id3.extend(std::iter::repeat_n(0u8, apic_body_len));
295-
296- let mut id3v1 = vec![0u8; 128];
297- id3v1[0..3].copy_from_slice(b"TAG");
298-
299- let mut bytes = id3;
300- bytes.extend_from_slice(&raw);
301- bytes.extend_from_slice(&id3v1);
302-
303- let path = std::env::temp_dir().join("edith-cover-art-id3v1-tail.mp3");
304- std::fs::write(&path, &bytes).expect("write synthetic mp3");
305-
306- let mut track = SymTrack::open(&path).expect("open past the ID3v2 APIC and ID3v1 tail");
307- assert_eq!(track.codec, "mp3");
308- let mut decoder = track.decoder();
309- let mut out = Vec::new();
310- let mut decoded_packets = 0;
311- let mut total_samples = 0;
312- while let Some(packet) = track.reader.next_packet().expect("demux") {
313- if packet.track_id != track.track_id {
314- continue;
315- }
316- decoder
317- .decode(&packet)
318- .expect("decode")
319- .copy_to_vec_interleaved::<f32>(&mut out);
320- // The reader's terminal, empty flush packet legitimately decodes to
321- // nothing for mp3 (nothing is held back across EOS), and it is always
322- // the last one seen — `out` alone, checked only after the loop, would
323- // read that packet's empty result rather than the file's real audio.
324- total_samples += out.len();
325- decoded_packets += 1;
326- }
327- assert!(decoded_packets > 0, "no audio packets decoded");
328- assert!(total_samples > 0, "no samples decoded");
329- let _ = std::fs::remove_file(&path);
330-}
331-
332-/// Write `source` (one `Vec<f32>` per channel, all the same length) as an Ogg
333-/// Vorbis file through `ec_vorbis`/`ec_ogg` — the same two crates
334-/// `edith_replica::export::write_ogg` writes through — at scratch/`name`.
335-fn encode_ogg(source: &[Vec<f32>], rate: u32, path: &Path) {
336- use ec_core::{
337- AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer,
338- Packet, StreamInfo, TimeBase,
339- };
340- use ec_vorbis::{EncoderConfig, VorbisEncoder};
341-
342- let channels = source.len() as u16;
343- let mut encoder = VorbisEncoder::new(EncoderConfig {
344- sample_rate: rate,
345- channels,
346- bitrate_bps: 128_000,
347- quality: 0.6,
348- })
349- .expect("vorbis encoder");
350- let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
351- encoder.push_planar(&borrowed).expect("push");
352- encoder.finish();
353- let mut packets = Vec::new();
354- loop {
355- match encoder.next_packet() {
356- Ok(p) => packets.push((p.data, p.granule)),
357- Err(e) if e.is_eof() => break,
358- Err(e) => panic!("encode: {e}"),
359- }
360- }
361- eprintln!(
362- "encode_ogg: {} packets, last granule {}",
363- packets.len(),
364- packets.last().map_or(0, |(_, g)| *g)
365- );
366-
367- let base = TimeBase::new(1, i64::from(rate));
368- let mut params = CodecParameters::new(CodecId::Vorbis);
369- params.media = MediaParameters::Audio(AudioParameters {
370- sample_rate: rate,
371- layout: ChannelLayout::from_count(usize::from(channels)),
372- format: None,
373- bits_per_sample: None,
374- });
375- params.extradata = Some(Buf::from_vec(encoder.extradata()));
376- let file = File::create(path).expect("create");
377- let mut muxer = ec_ogg::OggMuxer::new(file);
378- muxer
379- .add_stream(StreamInfo::new(0, base, params))
380- .expect("add stream");
381- muxer.write_headers().expect("headers");
382- for (data, granule) in &packets {
383- let mut packet = Packet::new(0, base, data.clone());
384- packet.side_data.push(ec_ogg::granule_side_data(*granule));
385- muxer.write_packet(&packet).expect("packet");
386- }
387- muxer.finish().expect("finish");
388-}
389-
390-/// The engine's own read door (`SymTrack` above, mirroring
391-/// `edith_replica::engine::audio::run_sym`): open, decode every packet to
392-/// EOF, count frames. This is what the export tests' `decode()` helper
393-/// measures against.
394-fn decode_all(path: &Path) -> u64 {
395- let mut track = SymTrack::open(path).expect("track");
396- let mut decoder = track.decoder();
397- let mut out = Vec::new();
398- let mut frames = 0u64;
399- let mut n = 0;
400- while let Some(packet) = track.reader.next_packet().expect("demux") {
401- if packet.track_id != track.track_id {
402- continue;
403- }
404- let before = frames;
405- decoder
406- .decode(&packet)
407- .expect("decode")
408- .copy_to_vec_interleaved::<f32>(&mut out);
409- frames += (out.len() / usize::from(track.channels)) as u64;
410- n += 1;
411- eprintln!(
412- "packet {n}: {} bytes in, {} frames out (running {frames})",
413- packet.data.len(),
414- frames - before
415- );
416- }
417- frames
418-}
419-
420-/// The exact shape of `audio_export::exports_the_timeline_as_an_ogg_vorbis`
421-/// and `a_mono_timeline_exports_as_dual_mono_ogg` in `edith_replica`: write N
422-/// samples through the family's own Ogg Vorbis encoder, read them back
423-/// through this shim exactly as the engine's `SymTrack`/`run_sym` do, and the
424-/// count must come back to N — the terminal hop `VorbisDecoder::flush`
425-/// delivers has to actually reach the reader at EOS.
426-#[test]
427-fn ogg_vorbis_round_trip_reads_back_every_sample_written() {
428- let rate = 44_100u32;
429- for (name, channels, n) in [
430- ("surface-mono-44100.ogg", 2usize, 44_100usize),
431- ("surface-stereo-264600.ogg", 2, 264_600),
432- ] {
433- let source: Vec<Vec<f32>> = (0..channels)
434- .map(|_| {
435- (0..n)
436- .map(|i| 0.2 * (i as f32 * 0.05).sin())
437- .collect::<Vec<f32>>()
438- })
439- .collect();
440- let path = std::env::temp_dir().join(format!("edith-surface-{}-{name}", std::process::id()));
441- encode_ogg(&source, rate, &path);
442- let frames = decode_all(&path);
443- eprintln!("{name}: wrote {n} frames, read back {frames}");
444- assert_eq!(frames, n as u64, "{name}: round trip sample count");
445- let _ = std::fs::remove_file(&path);
446- }
447-}
448-
449-/// ID3v2's syncsafe integer: 4 bytes, 7 significant bits each (top bit clear),
450-/// big-endian.
451-fn syncsafe(mut n: u32) -> [u8; 4] {
452- let mut out = [0u8; 4];
453- for b in out.iter_mut().rev() {
454- *b = (n & 0x7f) as u8;
455- n >>= 7;
456- }
457- out
458-}
shims/symphonia/tests/vorbis_timing.rsdeleted+0 -429
@@ -1,429 +0,0 @@
1-use std::fs::File;
2-use std::path::{Path, PathBuf};
3-use std::process::Command;
4-
5-use ec_core::{
6- AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer,
7- Packet, StreamInfo, TimeBase,
8-};
9-use symphonia_core::codecs::audio::{AudioCodecParameters, AudioDecoderOptions};
10-use symphonia_core::formats::probe::Hint;
11-use symphonia_core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo, TrackType};
12-use symphonia_core::io::MediaSourceStream;
13-use symphonia_core::meta::MetadataOptions;
14-
15-const CHANNELS: u16 = 2;
16-const FIRST_PACKET_FRAMES: usize = 1024;
17-
18-fn scratch(name: &str) -> PathBuf {
19- let dir = std::env::temp_dir().join(format!("symphonia-timing-{}", std::process::id()));
20- std::fs::create_dir_all(&dir).expect("scratch dir");
21- dir.join(name)
22-}
23-
24-fn samples(rate: u32) -> Vec<i16> {
25- let tone = (rate / 2) as usize;
26- let gap = rate as usize;
27- let frames = tone + gap + tone;
28- let mut out = Vec::with_capacity(frames * usize::from(CHANNELS));
29- for frame in 0..frames {
30- let active = frame < tone || frame >= tone + gap;
31- for ch in 0..CHANNELS {
32- let hz = if ch == 0 { 440.0 } else { 660.0 };
33- let v = if active {
34- (2.0 * std::f64::consts::PI * hz * frame as f64 / f64::from(rate)).sin() * 0.45
35- } else {
36- 0.0
37- };
38- out.push((v * f64::from(i16::MAX)) as i16);
39- }
40- }
41- out
42-}
43-
44-fn write_ogg(out: &Path, samples: &[i16], rate: u32) {
45- let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig {
46- bitrate_bps: rusty_vorbis::BITRATE_NOMINAL,
47- quality: 0.85,
48- });
49- encoder
50- .push_pcm_s16(samples, CHANNELS, rate)
51- .expect("encode");
52- encoder.finish();
53- let mut packets = Vec::new();
54- loop {
55- match encoder.next_packet() {
56- Ok(packet) => packets.push(packet),
57- Err(rusty_vorbis::Error::Eof) => break,
58- Err(e) => panic!("encode: {e}"),
59- }
60- }
61-
62- let extradata = ec_ogg::xiph_lace(&[
63- &packets[0].data[..],
64- &packets[1].data[..],
65- &packets[2].data[..],
66- ])
67- .expect("headers lace");
68- let time_base = TimeBase::new(1, i64::from(rate));
69- let mut params = CodecParameters::new(CodecId::Vorbis);
70- params.media = MediaParameters::Audio(AudioParameters {
71- sample_rate: rate,
72- layout: ChannelLayout::from_count(usize::from(CHANNELS)),
73- format: None,
74- bits_per_sample: None,
75- });
76- params.extradata = Some(Buf::from_vec(extradata));
77- let mut muxer = ec_ogg::OggMuxer::new(File::create(out).expect("create"));
78- muxer
79- .add_stream(StreamInfo::new(0, time_base, params))
80- .expect("stream");
81- muxer.write_headers().expect("headers");
82- for packet in &packets[3..] {
83- let mut out = Packet::new(0, time_base, packet.data.clone());
84- out.side_data.push(ec_ogg::granule_side_data(packet.pts));
85- out.duration = Some(packet.duration);
86- muxer.write_packet(&out).expect("packet");
87- }
88- muxer.finish().expect("trailer");
89-}
90-
91-fn ffmpeg_decode(path: &Path) -> Vec<f32> {
92- let out = Command::new("ffmpeg")
93- .args(["-nostdin", "-v", "error", "-i"])
94- .arg(path)
95- .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
96- .output()
97- .expect("ffmpeg");
98- assert!(
99- out.status.success(),
100- "{}",
101- String::from_utf8_lossy(&out.stderr)
102- );
103- out.stdout
104- .as_chunks::<4>().0.iter()
105- .map(|c| f32::from_le_bytes(*c))
106- .collect()
107-}
108-
109-fn probe_decode(path: &Path) -> Vec<f32> {
110- let mut demuxer = ec_ogg::OggDemuxer::open(File::open(path).expect("open")).expect("demux");
111- let params = demuxer.streams()[0].params.clone();
112- let mut decoder = ec_probe::AudioDecoder::new(&params).expect("decoder");
113- let mut out = Vec::new();
114- let mut chunk = Vec::new();
115- loop {
116- match demuxer.next_packet() {
117- Ok(packet) => {
118- decoder.decode(&packet, &mut chunk).expect("decode");
119- out.extend_from_slice(&chunk);
120- }
121- Err(e) if e.is_eof() => break,
122- Err(e) => panic!("demux: {e}"),
123- }
124- }
125- decoder.flush(&mut chunk).expect("flush");
126- out.extend_from_slice(&chunk);
127- out
128-}
129-
130-fn shim_reader(path: &Path) -> Box<dyn FormatReader> {
131- let mss = MediaSourceStream::new(
132- Box::new(File::open(path).expect("open")),
133- Default::default(),
134- );
135- let mut hint = Hint::new();
136- hint.with_extension("ogg");
137- symphonia::default::get_probe()
138- .probe(
139- &hint,
140- mss,
141- FormatOptions::default(),
142- MetadataOptions::default(),
143- )
144- .expect("probe")
145-}
146-
147-fn audio_track(reader: &dyn FormatReader) -> (u32, AudioCodecParameters) {
148- let track = reader.default_track(TrackType::Audio).expect("track");
149- let track_id = track.id;
150- let params = match track.codec_params.clone().expect("params") {
151- symphonia_core::codecs::CodecParameters::Audio(params) => params,
152- _ => panic!("audio params"),
153- };
154- (track_id, params)
155-}
156-
157-fn decode_from_reader(
158- reader: &mut dyn FormatReader,
159- track_id: u32,
160- params: &AudioCodecParameters,
161-) -> Vec<f32> {
162- let mut decoder = symphonia::default::get_codecs()
163- .make_audio_decoder(params, &AudioDecoderOptions::default())
164- .expect("decoder");
165- let mut out = Vec::new();
166- let mut chunk = Vec::new();
167- while let Some(packet) = reader.next_packet().expect("packet") {
168- if packet.track_id != track_id {
169- continue;
170- }
171- decoder
172- .decode(&packet)
173- .expect("decode")
174- .copy_to_vec_interleaved::<f32>(&mut chunk);
175- out.extend_from_slice(&chunk);
176- }
177- out
178-}
179-
180-#[derive(Debug, Clone, PartialEq, Eq)]
181-struct PacketTiming {
182- data: Vec<u8>,
183- ts: i64,
184- granule: Option<i64>,
185-}
186-
187-fn packet_prefix(reader: &mut dyn FormatReader, track_id: u32, n: usize) -> Vec<PacketTiming> {
188- let mut out = Vec::new();
189- while out.len() < n {
190- let packet = reader
191- .next_packet()
192- .expect("packet")
193- .expect("enough packets");
194- if packet.track_id == track_id && !packet.data.is_empty() {
195- out.push(PacketTiming {
196- data: packet.data.as_ref().to_vec(),
197- ts: packet.pts.value(),
198- granule: packet.granule,
199- });
200- }
201- }
202- out
203-}
204-
205-fn probe_packet_prefix(path: &Path, n: usize) -> Vec<PacketTiming> {
206- let mut demuxer = ec_ogg::OggDemuxer::open(File::open(path).expect("open")).expect("demux");
207- let mut out = Vec::new();
208- while out.len() < n {
209- match demuxer.next_packet() {
210- Ok(packet) => {
211- if packet.stream == 0 {
212- out.push(PacketTiming {
213- data: packet.data.as_ref().to_vec(),
214- ts: packet.pts.unwrap_or(0),
215- granule: ec_ogg::granule_of(&packet),
216- });
217- }
218- }
219- Err(e) if e.is_eof() => panic!("enough packets"),
220- Err(e) => panic!("demux: {e}"),
221- }
222- }
223- out
224-}
225-
226-fn assert_packet_timing(rate: u32, label: &str, left: &[PacketTiming], right: &[PacketTiming]) {
227- assert_eq!(left.len(), right.len(), "{rate}: {label} packet count");
228- for (i, (left, right)) in left.iter().zip(right).enumerate() {
229- assert_eq!(left.ts, right.ts, "{rate}: {label} packet {i} ts");
230- assert_eq!(
231- left.granule, right.granule,
232- "{rate}: {label} packet {i} granule"
233- );
234- assert_eq!(left.data, right.data, "{rate}: {label} packet {i} payload");
235- }
236-}
237-
238-fn seek_to_start(reader: &mut dyn FormatReader, track_id: u32) {
239- reader
240- .seek(
241- SeekMode::Accurate,
242- SeekTo::TimeStamp {
243- ts: symphonia_core::units::Timestamp::new(0),
244- track_id,
245- },
246- )
247- .expect("seek");
248-}
249-
250-fn shim_decode(path: &Path) -> Vec<f32> {
251- let mut reader = shim_reader(path);
252- let (track_id, params) = audio_track(&*reader);
253- decode_from_reader(&mut *reader, track_id, &params)
254-}
255-
256-fn rms(window: &[f32]) -> f64 {
257- (window
258- .iter()
259- .map(|&v| f64::from(v) * f64::from(v))
260- .sum::<f64>()
261- / window.len() as f64)
262- .sqrt()
263-}
264-
265-fn tone_rms(samples: &[f32], rate: u32) -> f64 {
266- let channels = usize::from(CHANNELS);
267- let start = FIRST_PACKET_FRAMES * channels;
268- let end = (rate / 2) as usize * channels;
269- rms(&samples[start..end.min(samples.len())])
270-}
271-
272-fn gap_rms(samples: &[f32], rate: u32) -> f64 {
273- let channels = usize::from(CHANNELS);
274- let onset = ((rate / 2 + rate) as usize) * channels;
275- let start = onset - ((rate / 20) as usize) * channels;
276- rms(&samples[start..onset.min(samples.len())])
277-}
278-
279-fn first_tone_onset(samples: &[f32], rate: u32) -> usize {
280- let channels = usize::from(CHANNELS);
281- let threshold = (tone_rms(samples, rate) * 0.25) as f32;
282- let search = rate as usize * channels;
283- samples[search..]
284- .chunks_exact(channels)
285- .position(|frame| frame.iter().any(|v| v.abs() >= threshold))
286- .map(|frame| frame + search / channels)
287- .expect("tone onset")
288-}
289-
290-fn max_abs_after_first_packet(a: &[f32], b: &[f32]) -> f32 {
291- let skip = FIRST_PACKET_FRAMES * usize::from(CHANNELS);
292- a[skip..]
293- .iter()
294- .zip(&b[skip..])
295- .map(|(x, y)| (x - y).abs())
296- .fold(0.0, f32::max)
297-}
298-
299-#[test]
300-fn ogg_timing_matches_reference_decoder() {
301- if Command::new("ffmpeg").arg("-version").output().is_err() {
302- eprintln!("skip: ffmpeg not on PATH");
303- return;
304- }
305-
306- for rate in [44_100, 48_000] {
307- let path = scratch(&format!("timing-{rate}.ogg"));
308- write_ogg(&path, &samples(rate), rate);
309- let shim = shim_decode(&path);
310- let probe = probe_decode(&path);
311- let reference = ffmpeg_decode(&path);
312-
313- let shim_gap = gap_rms(&shim, rate);
314- let probe_gap = gap_rms(&probe, rate);
315- let reference_gap = gap_rms(&reference, rate);
316- let shim_tone = tone_rms(&shim, rate);
317- let probe_tone = tone_rms(&probe, rate);
318- let reference_tone = tone_rms(&reference, rate);
319- let gap_bound = reference_tone * 0.001;
320- let shim_onset = first_tone_onset(&shim, rate);
321- let probe_onset = first_tone_onset(&probe, rate);
322- let reference_onset = first_tone_onset(&reference, rate);
323- let shim_max = max_abs_after_first_packet(&shim, &reference);
324- let probe_max = max_abs_after_first_packet(&probe, &reference);
325- eprintln!(
326- "rate={rate} frames shim={} probe={} ref={} tone shim={shim_tone:.8} probe={probe_tone:.8} ref={reference_tone:.8} gap_bound={gap_bound:.8} gap shim={shim_gap:.8} probe={probe_gap:.8} ref={reference_gap:.8} onset shim={shim_onset} probe={probe_onset} ref={reference_onset} max shim={shim_max:.8} probe={probe_max:.8}",
327- shim.len() / usize::from(CHANNELS),
328- probe.len() / usize::from(CHANNELS),
329- reference.len() / usize::from(CHANNELS),
330- );
331-
332- assert_eq!(shim.len(), reference.len(), "{rate}: shim length");
333- assert_eq!(probe.len(), reference.len(), "{rate}: probe length");
334- assert!(
335- shim_gap <= gap_bound,
336- "{rate}: shim gap RMS {shim_gap:.8} exceeds 60 dB-down absolute bound {gap_bound:.8}; tone RMS {shim_tone:.8}"
337- );
338- assert!(
339- probe_gap <= gap_bound,
340- "{rate}: probe gap RMS {probe_gap:.8} exceeds 60 dB-down absolute bound {gap_bound:.8}; tone RMS {probe_tone:.8}"
341- );
342- assert!(
343- reference_gap <= gap_bound,
344- "{rate}: reference gap RMS {reference_gap:.8} exceeds 60 dB-down absolute bound {gap_bound:.8}; tone RMS {reference_tone:.8}"
345- );
346- assert!(
347- shim_onset.abs_diff(probe_onset) <= 1,
348- "{rate}: shim onset {shim_onset} vs probe onset {probe_onset}"
349- );
350- assert!(
351- shim_onset.abs_diff(reference_onset) <= 1,
352- "{rate}: shim onset {shim_onset} vs reference onset {reference_onset}"
353- );
354- assert!(shim_max <= 1e-6, "{rate}: shim differs by {shim_max}");
355- assert!(probe_max <= 1e-6, "{rate}: probe differs by {probe_max}");
356- }
357-}
358-
359-#[test]
360-fn seek_to_start_replays_fresh_packet_timing() {
361- for rate in [44_100, 48_000] {
362- let path = scratch(&format!("seek-start-{rate}.ogg"));
363- write_ogg(&path, &samples(rate), rate);
364-
365- let mut fresh_reader = shim_reader(&path);
366- let (track_id, params) = audio_track(&*fresh_reader);
367- let fresh_packets = packet_prefix(&mut *fresh_reader, track_id, 8);
368- let probe_packets = probe_packet_prefix(&path, 8);
369- assert_packet_timing(rate, "shim vs probe", &fresh_packets, &probe_packets);
370-
371- let mut seeked_reader = shim_reader(&path);
372- let (seeked_track, seeked_params) = audio_track(&*seeked_reader);
373- assert_eq!(seeked_track, track_id);
374- assert_eq!(seeked_params.sample_rate, params.sample_rate);
375- let _ = packet_prefix(&mut *seeked_reader, seeked_track, 5);
376- seek_to_start(&mut *seeked_reader, seeked_track);
377- let seeked_packets = packet_prefix(&mut *seeked_reader, seeked_track, 8);
378- assert_packet_timing(rate, "seek(0) vs probe", &seeked_packets, &probe_packets);
379-
380- eprintln!(
381- "rate={rate} fresh_first_granule={:?} seek_first_granule={:?}",
382- fresh_packets[0].granule, seeked_packets[0].granule
383- );
384- assert_packet_timing(rate, "seek(0) vs fresh", &seeked_packets, &fresh_packets);
385-
386- let fresh_pcm = shim_decode(&path);
387- let mut decode_reader = shim_reader(&path);
388- let (decode_track, decode_params) = audio_track(&*decode_reader);
389- let _ = packet_prefix(&mut *decode_reader, decode_track, 5);
390- seek_to_start(&mut *decode_reader, decode_track);
391- let seeked_pcm = decode_from_reader(&mut *decode_reader, decode_track, &decode_params);
392- assert_eq!(seeked_pcm, fresh_pcm, "{rate}: decoded PCM after seek(0)");
393- let fresh_onset = first_tone_onset(&fresh_pcm, rate);
394- let seeked_onset = first_tone_onset(&seeked_pcm, rate);
395- assert!(
396- seeked_onset.abs_diff(fresh_onset) <= 1,
397- "{rate}: seek(0) onset {seeked_onset} vs fresh onset {fresh_onset}"
398- );
399-
400- let mut mid_reader = shim_reader(&path);
401- let (mid_track, mid_params) = audio_track(&*mid_reader);
402- let target = i64::from(rate);
403- let landed = mid_reader
404- .seek(
405- SeekMode::Accurate,
406- SeekTo::TimeStamp {
407- ts: symphonia_core::units::Timestamp::new(target),
408- track_id: mid_track,
409- },
410- )
411- .expect("mid seek")
412- .actual_ts
413- .value();
414- let mid_pcm = decode_from_reader(&mut *mid_reader, mid_track, &mid_params);
415- let channels = usize::from(CHANNELS);
416- let start = landed.max(0) as usize * channels;
417- let suffix = &fresh_pcm[start..];
418- let trim = mid_pcm.len().saturating_sub(suffix.len());
419- eprintln!(
420- "rate={rate} mid_landed={landed} mid_trim_frames={}",
421- trim / channels
422- );
423- assert!(
424- trim <= FIRST_PACKET_FRAMES * channels,
425- "{rate}: mid-stream trim too large: {} samples",
426- trim
427- );
428- }
429-}