forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1e4e107Tahinli2 months ago2830 commits

lib.rs308 lines, 10.3 KiBHistoryRawDownload
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
45use ec_core::Error as EcError;
46use ec_vorbis::{EncoderConfig, VorbisEncoder as EcEncoder};
47
48/// Short block size, as a power of two, that this encoder states.
49pub const BS0_LOG2: u8 = 11;
50/// Long block size, as a power of two.
51pub const BS1_LOG2: u8 = 11;
52/// The nominal bitrate the replica asks for.
53pub const BITRATE_NOMINAL: i32 = 128_000;
54
55/// Errors this encoder can answer.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub 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
70impl 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
82impl 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
94impl std::error::Error for Error {}
95
96/// This crate's result type.
97pub type Result<T> = std::result::Result<T, Error>;
98
99fn 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)]
110pub 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)]
123pub 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
130impl 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.
140pub 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.
149pub 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
157impl 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)]
275mod 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}