forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

decode.rs566 lines, 21.5 KiBHistoryRawDownload
1//! The decoder: header packets in, audio packets in, planar float out.
2
3use std::collections::VecDeque;
4
5use ec_core::frame::ChannelPosition::{self, *};
6use ec_core::{
7 AudioFrame, AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Decoder, Error,
8 Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase, Timestamp,
9};
10use ec_dsp::Mdct;
11
12use crate::bits::Bits;
13use crate::codebook::ilog;
14use crate::floor::{self, FloorState};
15use crate::residue;
16use crate::setup::{Comments, FloorConfig, Identification, Setup};
17use crate::trim::{GranuleTrim, granule_of};
18use crate::window::Windows;
19
20/// Vorbis I decoder.
21///
22/// Feed it the three header packets, then audio packets; every audio packet
23/// answers the samples that became final when its window closed, which is why
24/// the *first* audio packet of a stream answers none — its block only reaches
25/// halfway into the first sample the stream states.
26pub struct VorbisDecoder {
27 ident: Identification,
28 comments: Comments,
29 setup: Setup,
30 params: CodecParameters,
31 layout: ChannelLayout,
32 /// `to_ec[vorbis channel] = ec-core channel`.
33 to_ec: Vec<usize>,
34 windows: Windows,
35 mdct_short: Mdct<f32>,
36 mdct_long: Mdct<f32>,
37 /// Per channel, the overlap-add accumulator, in Vorbis channel order.
38 lap: Vec<Vec<f32>>,
39 /// Absolute sample position of `lap[..][0]`.
40 lap_start: i64,
41 /// Centre of the block decoded last, absolute; `None` before the first.
42 centre: Option<i64>,
43 /// Blocksize of the block decoded last.
44 previous_n: usize,
45 /// Samples handed out so far, for the frames' timestamps.
46 position: i64,
47 /// Timestamp the next frame carries, when the container stated one.
48 next_pts: Option<i64>,
49 frames: VecDeque<Frame>,
50 drained: bool,
51 /// Holds decoded samples until the page granules say which are the stream's.
52 trim: GranuleTrim,
53 /// Per-block captured decoded residue: (half, per-channel integer residue).
54 /// Populated only when `enable_residue_capture` is set.
55 residue_capture: Vec<(usize, Vec<Vec<i32>>)>,
56 /// Per-block bit split captured alongside: (floor bits, residue bits, packet bits).
57 bit_split: Vec<(u64, u64, u64)>,
58 /// When true, `decode_audio` copies each block's residue (after inverse
59 /// coupling, before floor multiply) into `residue_capture`.
60 enable_residue_capture: bool,
61}
62
63impl VorbisDecoder {
64 /// Build a decoder from the three header packets, in order.
65 pub fn new(headers: &[&[u8]]) -> Result<VorbisDecoder> {
66 let [ident, comment, setup] = headers else {
67 return Err(Error::corrupt(format!(
68 "Vorbis needs 3 header packets, got {}",
69 headers.len()
70 )));
71 };
72 let ident = Identification::parse(ident)?;
73 let comments = Comments::parse(comment)?;
74 let setup = Setup::parse(setup, &ident)?;
75 let channels = usize::from(ident.channels);
76 let (layout, to_ec) = channel_map(channels);
77 let params = CodecParameters {
78 codec: CodecId::Vorbis,
79 media: MediaParameters::Audio(AudioParameters {
80 sample_rate: ident.rate,
81 layout: layout.clone(),
82 format: Some(SampleFormat::F32),
83 bits_per_sample: None,
84 }),
85 extradata: None,
86 };
87 Ok(VorbisDecoder {
88 windows: Windows::new(ident.blocksize_0, ident.blocksize_1),
89 mdct_short: Mdct::new(ident.blocksize_0),
90 mdct_long: Mdct::new(ident.blocksize_1),
91 lap: vec![Vec::new(); channels],
92 lap_start: 0,
93 centre: None,
94 previous_n: ident.blocksize_1,
95 position: 0,
96 next_pts: None,
97 frames: VecDeque::new(),
98 drained: false,
99 trim: GranuleTrim::new(channels),
100 residue_capture: Vec::new(),
101 bit_split: Vec::new(),
102 enable_residue_capture: false,
103 ident,
104 comments,
105 setup,
106 params,
107 layout,
108 to_ec,
109 })
110 }
111
112 /// Build a decoder from Xiph-laced `extradata`, the form containers carry
113 /// the three headers in.
114 pub fn from_extradata(extradata: &[u8]) -> Result<VorbisDecoder> {
115 let packets = unlace(extradata)?;
116 let borrowed: Vec<&[u8]> = packets.iter().map(|p| &p[..]).collect();
117 VorbisDecoder::new(&borrowed)
118 }
119
120 /// The identification header's contents.
121 pub fn identification(&self) -> &Identification {
122 &self.ident
123 }
124
125 /// The comment header's contents.
126 pub fn comments(&self) -> &Comments {
127 &self.comments
128 }
129
130 /// Channel layout of the decoded frames.
131 pub fn layout(&self) -> &ChannelLayout {
132 &self.layout
133 }
134
135 /// The blocksize of one audio packet, read from its header alone: the mode
136 /// it names and that mode's block flag. A packet answers the previous
137 /// block's quarter plus this block's quarter (`previous / 4 + current / 4`)
138 /// samples after the first, so a reader that counts the blocks of a stream
139 /// can place every packet's samples exactly without decoding any of them.
140 /// Only the first byte of `packet` is read.
141 pub fn packet_blocksize(&self, packet: &[u8]) -> Result<usize> {
142 let mut bits = Bits::new(packet);
143 if bits.bit() {
144 return Err(Error::corrupt("audio packet flagged as a header"));
145 }
146 let mode_bits = ilog(self.setup.modes.len() as u32 - 1);
147 let mode_index = bits.read(mode_bits) as usize;
148 let Some(&mode) = self.setup.modes.get(mode_index) else {
149 return Err(Error::corrupt(
150 "audio packet names a mode that is not there",
151 ));
152 };
153 Ok(match mode.block_flag {
154 true => self.ident.blocksize_1,
155 false => self.ident.blocksize_0,
156 })
157 }
158
159 /// Decode one audio packet into per-channel samples in ec-core channel
160 /// order. The first packet of a stream answers empty vectors.
161 pub fn decode_audio(&mut self, data: &[u8]) -> Result<Vec<Vec<f32>>> {
162 let channels = usize::from(self.ident.channels);
163 let mut bits = Bits::new(data);
164 if bits.bit() {
165 return Err(Error::corrupt("audio packet flagged as a header"));
166 }
167 let mode_bits = ilog(self.setup.modes.len() as u32 - 1);
168 let mode_index = bits.read(mode_bits) as usize;
169 let Some(&mode) = self.setup.modes.get(mode_index) else {
170 return Err(Error::corrupt(
171 "audio packet names a mode that is not there",
172 ));
173 };
174 let n = match mode.block_flag {
175 true => self.ident.blocksize_1,
176 false => self.ident.blocksize_0,
177 };
178 let half = n / 2;
179 let (previous_long, next_long) = match mode.block_flag {
180 true => (bits.bit(), bits.bit()),
181 false => (true, true),
182 };
183 if bits.eop() {
184 return Err(Error::corrupt("audio packet header truncated"));
185 }
186
187 let mapping = &self.setup.mappings[mode.mapping];
188 let packet_bits = data.len() as u64 * 8;
189 let before_floors = bits.remaining();
190 let mut floors = Vec::with_capacity(channels);
191 let mut no_residue = Vec::with_capacity(channels);
192 for &submap in mapping.mux.iter().take(channels) {
193 let state = match &self.setup.floors[mapping.submaps[submap].0] {
194 FloorConfig::Zero(config) => {
195 floor::decode_floor0(config, &self.setup.codebooks, &mut bits)
196 }
197 FloorConfig::One(config) => {
198 floor::decode_floor1(config, &self.setup.codebooks, &mut bits)
199 }
200 };
201 no_residue.push(state.is_unused());
202 floors.push(state);
203 }
204 let after_floors = bits.remaining();
205 // A coupled pair shares its residue, so one live channel keeps both.
206 for &(magnitude, angle) in &mapping.coupling {
207 if !no_residue[magnitude] || !no_residue[angle] {
208 no_residue[magnitude] = false;
209 no_residue[angle] = false;
210 }
211 }
212
213 let mut spectra: Vec<Vec<f32>> = vec![vec![0.0; half]; channels];
214 for (index, &(_, residue_index)) in mapping.submaps.iter().enumerate() {
215 let members: Vec<usize> = (0..channels).filter(|&c| mapping.mux[c] == index).collect();
216 if members.is_empty() {
217 continue;
218 }
219 let config = &self.setup.residues[residue_index];
220 let skip: Vec<bool> = members.iter().map(|&c| no_residue[c]).collect();
221 let mut decoded: Vec<Vec<f32>> = vec![vec![0.0; half]; members.len()];
222 if config.kind == 2 {
223 // Type 2 codes the whole submap as one interleaved vector, so
224 // it is decoded whole and split afterwards.
225 let mut interleaved = vec![vec![0.0f32; half * members.len()]];
226 let all_skipped = [skip.iter().all(|&s| s)];
227 residue::decode(
228 config,
229 &self.setup.codebooks,
230 &mut bits,
231 &mut interleaved,
232 &all_skipped,
233 );
234 residue::deinterleave(&interleaved[0], members.len(), &mut decoded);
235 } else {
236 residue::decode(
237 config,
238 &self.setup.codebooks,
239 &mut bits,
240 &mut decoded,
241 &skip,
242 );
243 }
244 for (slot, &channel) in members.iter().enumerate() {
245 spectra[channel] = std::mem::take(&mut decoded[slot]);
246 }
247 }
248
249 // §9.4.2 inverse coupling, newest step first.
250 for &(magnitude, angle) in mapping.coupling.iter().rev() {
251 // Taken out and put back so the two vectors can be walked in step;
252 // a coupling step never names one channel twice.
253 let mut mags = std::mem::take(&mut spectra[magnitude]);
254 let mut angles = std::mem::take(&mut spectra[angle]);
255 for (m, a) in mags.iter_mut().zip(angles.iter_mut()) {
256 let (new_m, new_a) = match (*m > 0.0, *a > 0.0) {
257 (true, true) => (*m, *m - *a),
258 (true, false) => (*m + *a, *m),
259 (false, true) => (*m, *m + *a),
260 (false, false) => (*m - *a, *m),
261 };
262 *m = new_m;
263 *a = new_a;
264 }
265 spectra[magnitude] = mags;
266 spectra[angle] = angles;
267 }
268
269 if self.enable_residue_capture {
270 let after_residues = bits.remaining();
271 self.bit_split.push((
272 before_floors - after_floors,
273 after_floors - after_residues,
274 packet_bits,
275 ));
276 let captured: Vec<Vec<i32>> = spectra
277 .iter()
278 .map(|ch| ch.iter().map(|&v| v.round() as i32).collect())
279 .collect();
280 self.residue_capture.push((half, captured));
281 }
282
283 // Floor times residue, then out of the frequency domain.
284 let window = self.windows.get(mode.block_flag, previous_long, next_long);
285 let mdct = match mode.block_flag {
286 true => &mut self.mdct_long,
287 false => &mut self.mdct_short,
288 };
289 let mut curve = vec![0.0f32; half];
290 let mut block = vec![0.0f32; n];
291 let centre = match self.centre {
292 Some(previous) => previous + (self.previous_n + n) as i64 / 4,
293 None => {
294 self.lap_start = 0;
295 self.lap = vec![vec![0.0; n]; channels];
296 n as i64 / 2
297 }
298 };
299 let start = centre - n as i64 / 2;
300
301 for channel in 0..channels {
302 match &floors[channel] {
303 FloorState::Unused => spectra[channel].fill(0.0),
304 FloorState::One { y, step2 } => {
305 let submap = mapping.mux[channel];
306 let FloorConfig::One(config) = &self.setup.floors[mapping.submaps[submap].0]
307 else {
308 return Err(Error::corrupt("floor type changed between packets"));
309 };
310 floor::render_floor1(config, y, step2, &mut curve);
311 for (value, &gain) in spectra[channel].iter_mut().zip(curve.iter()) {
312 *value *= gain;
313 }
314 }
315 FloorState::Zero {
316 amplitude,
317 coefficients,
318 } => {
319 let submap = mapping.mux[channel];
320 let FloorConfig::Zero(config) = &self.setup.floors[mapping.submaps[submap].0]
321 else {
322 return Err(Error::corrupt("floor type changed between packets"));
323 };
324 floor::render_floor0(config, *amplitude, coefficients, &mut curve);
325 for (value, &gain) in spectra[channel].iter_mut().zip(curve.iter()) {
326 *value *= gain;
327 }
328 }
329 }
330 // Undo the codec-side normalisation ec-dsp's inverse applies: a
331 // Vorbis coefficient is already `2/N` of the raw transform, so the
332 // synthesis here is the plain sum.
333 for value in spectra[channel].iter_mut() {
334 *value *= (half / 2) as f32;
335 }
336 mdct.inverse_windowed(&spectra[channel], window, &mut block);
337 let lap = &mut self.lap[channel];
338 let offset = (start - self.lap_start).max(0) as usize;
339 if lap.len() < offset + n {
340 lap.resize(offset + n, 0.0);
341 }
342 // A block starting before what has already been handed out only
343 // ever reaches back into its own zero run (§4.3.1 puts the slope
344 // inside the block when the neighbour is shorter), so the skipped
345 // samples are zeroes by construction.
346 let skipped = (self.lap_start - start).max(0) as usize;
347 for i in skipped..n {
348 lap[offset + i - skipped] += block[i];
349 }
350 }
351
352 let emit = (centre - self.lap_start).max(0) as usize;
353 let first = self.centre.is_none();
354 let mut out = vec![Vec::new(); channels];
355 for (channel, lap) in self.lap.iter_mut().enumerate() {
356 let take = emit.min(lap.len());
357 let head: Vec<f32> = lap.drain(..take).collect();
358 if !first {
359 out[self.to_ec[channel]] = head;
360 }
361 }
362 self.lap_start = centre;
363 self.centre = Some(centre);
364 self.previous_n = n;
365 Ok(out)
366 }
367
368 /// Drop the lapping state after a seek; the next packet starts a new run.
369 pub fn reset_state(&mut self) {
370 self.centre = None;
371 self.lap_start = 0;
372 self.position = 0;
373 for lap in &mut self.lap {
374 lap.clear();
375 }
376 self.frames.clear();
377 self.drained = false;
378 self.trim.reset();
379 }
380
381 /// Enable per-block residue capture for offline histogram analysis.
382 pub fn enable_residue_capture(&mut self) {
383 self.enable_residue_capture = true;
384 }
385
386 /// Take the captured per-block residue: each entry is `(half, per-channel integer residue)`.
387 pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec<Vec<i32>>)> {
388 std::mem::take(&mut self.residue_capture)
389 }
390
391 /// Take the per-block (floor bits, residue bits, packet bits) captured with the residue.
392 pub fn take_bit_split(&mut self) -> Vec<(u64, u64, u64)> {
393 std::mem::take(&mut self.bit_split)
394 }
395
396}
397/// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order.
398///
399/// Vorbis orders a 5.1 stream FL, FC, FR, BL, BR, LFE and a 7.1 stream FL, FC,
400/// FR, SL, SR, BL, BR, LFE; this family orders both FL, FR, FC, LFE, ... So the
401/// two named surround layouts are permuted on the way out and everything else
402/// passes through in the order the stream states, carrying the positions Vorbis
403/// names for it.
404pub fn channel_map(channels: usize) -> (ChannelLayout, Vec<usize>) {
405 let positions: &[ChannelPosition] = match channels {
406 1 => &[FrontCenter],
407 2 => &[FrontLeft, FrontRight],
408 3 => &[FrontLeft, FrontCenter, FrontRight],
409 4 => &[FrontLeft, FrontRight, BackLeft, BackRight],
410 5 => &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight],
411 6 => &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe],
412 7 => &[
413 FrontLeft,
414 FrontCenter,
415 FrontRight,
416 SideLeft,
417 SideRight,
418 BackCenter,
419 Lfe,
420 ],
421 8 => &[
422 FrontLeft,
423 FrontCenter,
424 FrontRight,
425 SideLeft,
426 SideRight,
427 BackLeft,
428 BackRight,
429 Lfe,
430 ],
431 _ => &[],
432 };
433 match channels {
434 1 => (ChannelLayout::Mono, vec![0]),
435 2 => (ChannelLayout::Stereo, vec![0, 1]),
436 6 => (ChannelLayout::Surround5_1, vec![0, 2, 1, 4, 5, 3]),
437 8 => (ChannelLayout::Surround7_1, vec![0, 2, 1, 6, 7, 4, 5, 3]),
438 n if n <= 8 => (ChannelLayout::Custom(positions.to_vec()), (0..n).collect()),
439 n => (ChannelLayout::from_count(n), (0..n).collect()),
440 }
441}
442
443/// The Xiph lacing containers wrap the three headers in.
444fn unlace(data: &[u8]) -> Result<Vec<Vec<u8>>> {
445 let count = *data
446 .first()
447 .ok_or_else(|| Error::corrupt("empty Vorbis extradata"))? as usize;
448 if count != 2 {
449 return Err(Error::corrupt("Vorbis extradata does not hold 3 packets"));
450 }
451 let mut lengths = Vec::with_capacity(2);
452 let mut pos = 1usize;
453 for _ in 0..count {
454 let mut length = 0usize;
455 loop {
456 let byte = *data
457 .get(pos)
458 .ok_or_else(|| Error::corrupt("Vorbis extradata lacing"))?;
459 pos += 1;
460 length += usize::from(byte);
461 if byte != 255 {
462 break;
463 }
464 }
465 lengths.push(length);
466 }
467 let mut packets = Vec::with_capacity(3);
468 for length in lengths {
469 let end = pos
470 .checked_add(length)
471 .filter(|end| *end <= data.len())
472 .ok_or_else(|| Error::corrupt("Vorbis extradata is shorter than it states"))?;
473 packets.push(data[pos..end].to_vec());
474 pos = end;
475 }
476 packets.push(data[pos..].to_vec());
477 Ok(packets)
478}
479
480impl VorbisDecoder {
481 /// Wrap released per-channel samples in an audio frame and queue it. The
482 /// frame is stamped `pts`, or the running sample position when there is none.
483 fn queue(&mut self, out: Vec<Vec<f32>>, pts: Option<i64>) -> Result<()> {
484 let count = out.first().map_or(0, Vec::len);
485 let data: Vec<Buf> = out
486 .into_iter()
487 .map(|channel| {
488 let mut bytes = Vec::with_capacity(channel.len() * 4);
489 for value in channel {
490 bytes.extend_from_slice(&value.to_le_bytes());
491 }
492 Buf::from_vec(bytes)
493 })
494 .collect();
495 let mut frame = AudioFrame::try_new(
496 SampleFormat::F32,
497 true,
498 self.layout.clone(),
499 self.ident.rate,
500 count,
501 data,
502 )?;
503 let base = TimeBase::new(1, i64::from(self.ident.rate));
504 frame.pts = Some(Timestamp::new(pts.unwrap_or(self.position), base));
505 self.position += count as i64;
506 self.frames.push_back(Frame::Audio(frame));
507 Ok(())
508 }
509}
510
511impl Decoder for VorbisDecoder {
512 fn codec_parameters(&self) -> &CodecParameters {
513 &self.params
514 }
515
516 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
517 let samples = self.decode_audio(&packet.data)?;
518 let before = self.trim.decoded();
519 self.trim.push(samples);
520 if let Some(granule) = granule_of(packet) {
521 self.trim.granule(granule, before);
522 }
523 let out = self.trim.release(false);
524 if out.first().is_none_or(Vec::is_empty) {
525 // The first packet of a run: its block only reaches the first
526 // sample the stream states, so there is nothing final yet.
527 self.next_pts = packet.pts;
528 return Ok(());
529 }
530 let pts = self.next_pts.take();
531 self.queue(out, pts)
532 }
533
534 fn receive_frame(&mut self) -> Result<Frame> {
535 match self.frames.pop_front() {
536 Some(frame) => Ok(frame),
537 None if self.drained => Err(Error::Eof),
538 None => Err(Error::NeedMore),
539 }
540 }
541
542 fn flush(&mut self) -> Result<()> {
543 // §1.3.2: the terminal block's un-overlapped right half (everything
544 // past the last emitted centre) is still valid output up to the
545 // stream's final granule position; without this the decoder is
546 // always exactly one hop short at true EOS. The granule trim cuts
547 // whatever lies past that final position.
548 if self.centre.is_some() {
549 let mut tail = vec![Vec::new(); self.lap.len()];
550 for (channel, lap) in self.lap.iter_mut().enumerate() {
551 tail[self.to_ec[channel]] = std::mem::take(lap);
552 }
553 self.trim.push(tail);
554 }
555 let out = self.trim.release(true);
556 if out.first().is_some_and(|c| !c.is_empty()) {
557 self.queue(out, None)?;
558 }
559 self.drained = true;
560 Ok(())
561 }
562
563 fn reset(&mut self) {
564 self.reset_state();
565 }
566}