forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

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