forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

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