claxon/frame.rs
1// Claxon -- A FLAC decoding library in Rust
2// Copyright 2014 Ruud van Asseldonk
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// A copy of the License has been included in the root of the repository.
7
8//! The `frame` module deals with the frames that make up a FLAC stream.
9
10use std::i32;
11
12use crc::{Crc8Reader, Crc16Reader};
13use error::{Error, Result, fmt_err};
14use input::{Bitstream, ReadBytes};
15use subframe;
16
17#[derive(Clone, Copy)]
18enum BlockingStrategy {
19 Fixed,
20 Variable,
21}
22
23#[derive(Clone, Copy)]
24enum BlockTime {
25 FrameNumber(u32),
26 SampleNumber(u64),
27}
28
29#[derive(Clone, Copy, Debug)]
30enum ChannelAssignment {
31 /// The `n: u8` channels are coded as-is.
32 Independent(u8),
33 /// Channel 0 is the left channel, channel 1 is the side channel.
34 LeftSideStereo,
35 /// Channel 0 is the side channel, channel 1 is the right channel.
36 RightSideStereo,
37 /// Channel 0 is the mid channel, channel 1 is the side channel.
38 MidSideStereo,
39}
40
41#[derive(Clone, Copy)]
42struct FrameHeader {
43 pub block_time: BlockTime,
44 pub block_size: u16,
45 pub sample_rate: Option<u32>,
46 pub channel_assignment: ChannelAssignment,
47 pub bits_per_sample: Option<u32>,
48}
49
50impl FrameHeader {
51 pub fn channels(&self) -> u8 {
52 match self.channel_assignment {
53 ChannelAssignment::Independent(n) => n,
54 ChannelAssignment::LeftSideStereo => 2,
55 ChannelAssignment::RightSideStereo => 2,
56 ChannelAssignment::MidSideStereo => 2,
57 }
58 }
59}
60
61/// Reads a variable-length integer encoded as what is called "UTF-8" coding
62/// in the specification. (It is not real UTF-8.) This function can read
63/// integers encoded in this way up to 36-bit integers.
64fn read_var_length_int<R: ReadBytes>(input: &mut R) -> Result<u64> {
65 // The number of consecutive 1s followed by a 0 is the number of additional
66 // bytes to read.
67 let first = try!(input.read_u8());
68 let mut read_additional = 0u8;
69 let mut mask_data = 0b0111_1111u8;
70 let mut mask_mark = 0b1000_0000u8;
71
72 // Determine the number of leading 1s.
73 while first & mask_mark != 0 {
74 read_additional = read_additional + 1;
75 mask_data = mask_data >> 1;
76 mask_mark = mask_mark >> 1;
77 }
78
79 // A single leading 1 is a follow-up byte and thus invalid.
80 if read_additional > 0 {
81 if read_additional == 1 {
82 return fmt_err("invalid variable-length integer");
83 } else {
84 // The number of 1s (if > 1) is the total number of bytes, not the
85 // number of additional bytes.
86 read_additional = read_additional - 1;
87 }
88 }
89
90 // Each additional byte will yield 6 extra bits, so shift the most
91 // significant bits into the correct position.
92 let mut result = ((first & mask_data) as u64) << (6 * read_additional);
93 for i in (0..read_additional as i16).rev() {
94 let byte = try!(input.read_u8());
95
96 // The two most significant bits _must_ be 10.
97 if byte & 0b1100_0000 != 0b1000_0000 {
98 return fmt_err("invalid variable-length integer");
99 }
100
101 result = result | (((byte & 0b0011_1111) as u64) << (6 * i as usize));
102 }
103
104 Ok(result)
105}
106
107#[test]
108fn verify_read_var_length_int() {
109 use std::io;
110 use error::Error;
111 use input::BufferedReader;
112
113 let mut reader = BufferedReader::new(
114 io::Cursor::new(vec![0x24, 0xc2, 0xa2, 0xe2, 0x82, 0xac, 0xf0, 0x90, 0x8d,
115 0x88, 0xc2, 0x00, 0x80]));
116
117 assert_eq!(read_var_length_int(&mut reader).unwrap(), 0x24);
118 assert_eq!(read_var_length_int(&mut reader).unwrap(), 0xa2);
119 assert_eq!(read_var_length_int(&mut reader).unwrap(), 0x20ac);
120 assert_eq!(read_var_length_int(&mut reader).unwrap(), 0x010348);
121
122 // Two-byte integer with invalid continuation byte should fail.
123 assert_eq!(read_var_length_int(&mut reader).err().unwrap(),
124 Error::FormatError("invalid variable-length integer"));
125
126 // Continuation byte can never be the first byte.
127 assert_eq!(read_var_length_int(&mut reader).err().unwrap(),
128 Error::FormatError("invalid variable-length integer"));
129}
130
131fn read_frame_header_or_eof<R: ReadBytes>(input: &mut R) -> Result<Option<FrameHeader>> {
132 // The frame header includes a CRC-8 at the end. It can be computed
133 // automatically while reading, by wrapping the input reader in a reader
134 // that computes the CRC.
135 let mut crc_input = Crc8Reader::new(input);
136
137 // First are 14 bits frame sync code, a reserved bit, and blocking stategy.
138 // If instead of the two bytes we find the end of the stream, return
139 // `Nothing`, indicating EOF.
140 let sync_res_block = match try!(crc_input.read_be_u16_or_eof()) {
141 None => return Ok(None),
142 Some(x) => x,
143 };
144
145 // The first 14 bits must be 11111111111110.
146 let sync_code = sync_res_block & 0b1111_1111_1111_1100;
147 if sync_code != 0b1111_1111_1111_1000 {
148 return fmt_err("frame sync code missing");
149 }
150
151 // The next bit has a mandatory value of 0 at the moment of writing. The
152 // spec says "0: mandatory value, 1: reserved for future use". As it is
153 // unlikely that the FLAC format will every change, we treat features in
154 // the spec that are not implemented as `Error::Unsupported`, and this is
155 // a format error.
156 if sync_res_block & 0b0000_0000_0000_0010 != 0 {
157 return fmt_err("invalid frame header, encountered reserved value");
158 }
159
160 // The final bit determines the blocking strategy.
161 let blocking_strategy = if sync_res_block & 0b0000_0000_0000_0001 == 0 {
162 BlockingStrategy::Fixed
163 } else {
164 BlockingStrategy::Variable
165 };
166
167 // Next are 4 bits block size and 4 bits sample rate.
168 let bs_sr = try!(crc_input.read_u8());
169 let mut block_size = 0u16;
170 let mut read_8bit_bs = false;
171 let mut read_16bit_bs = false;
172
173 // There are some pre-defined bit patterns. Some mean 'get from end of
174 // header instead'.
175 match bs_sr >> 4 {
176 // The value 0000 is reserved.
177 0b0000 => return fmt_err("invalid frame header, encountered reserved value"),
178 0b0001 => block_size = 192,
179 n if 0b0010 <= n && n <= 0b0101 => block_size = 576 * (1 << (n - 2) as usize),
180 0b0110 => read_8bit_bs = true,
181 0b0111 => read_16bit_bs = true,
182 n => block_size = 256 * (1 << (n - 8) as usize),
183 }
184
185 // For the sample rate there is a number of pre-defined bit patterns as
186 // well. Again, some mean 'get from end of header instead'.
187 let mut sample_rate = None;
188 let mut read_8bit_sr = false;
189 let mut read_16bit_sr = false;
190 let mut read_16bit_sr_ten = false;
191
192 match bs_sr & 0b0000_1111 {
193 0b0000 => sample_rate = None, // 0000 means 'get from streaminfo block'.
194 0b0001 => sample_rate = Some(88_200),
195 0b0010 => sample_rate = Some(176_400),
196 0b0011 => sample_rate = Some(192_000),
197 0b0100 => sample_rate = Some(8_000),
198 0b0101 => sample_rate = Some(16_000),
199 0b0110 => sample_rate = Some(22_050),
200 0b0111 => sample_rate = Some(24_000),
201 0b1000 => sample_rate = Some(32_000),
202 0b1001 => sample_rate = Some(44_100),
203 0b1010 => sample_rate = Some(48_000),
204 0b1011 => sample_rate = Some(96_000),
205 0b1100 => read_8bit_sr = true, // Read Hz from end of header.
206 0b1101 => read_16bit_sr = true, // Read Hz from end of header.
207 0b1110 => read_16bit_sr_ten = true, // Read tens of Hz from end of header.
208 // 1111 is invalid to prevent sync-fooling.
209 // Other values are impossible at this point.
210 _ => return fmt_err("invalid frame header"),
211 }
212
213 // Next are 4 bits channel assignment, 3 bits sample size, and 1 reserved bit.
214 let chan_bps_res = try!(crc_input.read_u8());
215
216 // The most significant 4 bits determine channel assignment.
217 let channel_assignment = match chan_bps_res >> 4 {
218 // Values 0 through 7 indicate n + 1 channels without mixing.
219 n if n < 8 => ChannelAssignment::Independent(n + 1),
220 0b1000 => ChannelAssignment::LeftSideStereo,
221 0b1001 => ChannelAssignment::RightSideStereo,
222 0b1010 => ChannelAssignment::MidSideStereo,
223 // Values 1011 through 1111 are reserved and thus invalid.
224 _ => return fmt_err("invalid frame header, encountered reserved value"),
225 };
226
227 // The next three bits indicate bits per sample.
228 let bits_per_sample = match (chan_bps_res & 0b0000_1110) >> 1 {
229 0b000 => None, // 000 means 'get from streaminfo block'.
230 0b001 => Some(8),
231 0b010 => Some(12),
232 0b100 => Some(16),
233 0b101 => Some(20),
234 0b110 => Some(24),
235 // Values 011 and 111 are reserved. Other values are impossible.
236 _ => return fmt_err("invalid frame header, encountered reserved value"),
237 };
238
239 // The final bit has a mandatory value of 0, it is a reserved bit.
240 if chan_bps_res & 0b0000_0001 != 0 {
241 return fmt_err("invalid frame header, encountered reserved value");
242 }
243
244 let block_time = match blocking_strategy {
245 BlockingStrategy::Variable => {
246 // The sample number is encoded in 8-56 bits, at most a 36-bit int.
247 let sample = try!(read_var_length_int(&mut crc_input));
248 BlockTime::SampleNumber(sample)
249 }
250 BlockingStrategy::Fixed => {
251 // The frame number is encoded in 8-48 bits, at most a 31-bit int.
252 let frame = try!(read_var_length_int(&mut crc_input));
253 // A frame number larger than 31 bits is therefore invalid.
254 if frame > 0x7fffffff {
255 return fmt_err("invalid frame header, frame number too large");
256 }
257 BlockTime::FrameNumber(frame as u32)
258 }
259 };
260
261 if read_8bit_bs {
262 // 8 bit block size - 1 is stored.
263 let bs = try!(crc_input.read_u8());
264 block_size = bs as u16 + 1;
265 }
266 if read_16bit_bs {
267 // 16-bit block size - 1 is stored. Note that the max block size that
268 // can be indicated in the streaminfo block is a 16-bit number, so a
269 // value of 0xffff would be invalid because it exceeds the max block
270 // size, though this is not mentioned explicitly in the specification.
271 let bs = try!(crc_input.read_be_u16());
272 if bs == 0xffff {
273 return fmt_err("invalid block size, exceeds 65535");
274 }
275 block_size = bs + 1;
276 }
277
278 if read_8bit_sr {
279 let sr = try!(crc_input.read_u8());
280 sample_rate = Some(sr as u32);
281 }
282 if read_16bit_sr {
283 let sr = try!(crc_input.read_be_u16());
284 sample_rate = Some(sr as u32);
285 }
286 if read_16bit_sr_ten {
287 let sr_ten = try!(crc_input.read_be_u16());
288 sample_rate = Some(sr_ten as u32 * 10);
289 }
290
291 // Next is an 8-bit CRC that is computed over the entire header so far.
292 let computed_crc = crc_input.crc();
293 let presumed_crc = try!(crc_input.read_u8());
294
295 // Do not verify checksum during fuzzing, otherwise malformed input from
296 // fuzzer won't reach the actually interesting code.
297 #[cfg(not(fuzzing))]
298 {
299 if computed_crc != presumed_crc {
300 return fmt_err("frame header CRC mismatch");
301 }
302 }
303
304 // Silence unused variable warnings.
305 #[cfg(fuzzing)]
306 let _ = computed_crc == presumed_crc;
307
308 let frame_header = FrameHeader {
309 block_time: block_time,
310 block_size: block_size,
311 sample_rate: sample_rate,
312 channel_assignment: channel_assignment,
313 bits_per_sample: bits_per_sample,
314 };
315 Ok(Some(frame_header))
316}
317
318/// Converts a buffer with left samples and a side channel in-place to left ++ right.
319fn decode_left_side(buffer: &mut [i32]) {
320 let block_size = buffer.len() / 2;
321 let (mids, sides) = buffer.split_at_mut(block_size);
322 for (fst, snd) in mids.iter_mut().zip(sides) {
323 let left = *fst;
324 let side = *snd;
325
326 // Left is correct already, only the right channel needs to be decoded.
327 // side = left - right => right = left - side. A valid FLAC file will
328 // never overflow here. If we do have an overflow then we decode
329 // garbage, but at least Rust does not panic in debug mode due to
330 // overflow.
331 let right = left.wrapping_sub(side);
332 *snd = right;
333 }
334}
335
336#[test]
337fn verify_decode_left_side() {
338 let mut buffer = vec![2, 5, 83, 113, 127, -63, -45, -15, 7, 38, 142, 238, 0, -152, -52, -18];
339 let result = vec![2, 5, 83, 113, 127, -63, -45, -15, -5, -33, -59, -125, 127, 89, 7, 3];
340 decode_left_side(&mut buffer);
341 assert_eq!(buffer, result);
342}
343
344/// Converts a buffer with right samples and a side channel in-place to left ++ right.
345fn decode_right_side(buffer: &mut [i32]) {
346 let block_size = buffer.len() / 2;
347 let (mids, sides) = buffer.split_at_mut(block_size);
348 for (fst, snd) in mids.iter_mut().zip(sides) {
349 let side = *fst;
350 let right = *snd;
351
352 // Right is correct already, only the left channel needs to be decoded.
353 // side = left - right => left = side + right. A valid FLAC file will
354 // never overflow here. If we do have an overflow then we decode
355 // garbage, but at least Rust does not panic in debug mode due to
356 // overflow.
357 let left = side.wrapping_add(right);
358 *fst = left;
359 }
360}
361
362#[test]
363fn verify_decode_right_side() {
364 let mut buffer = vec![7, 38, 142, 238, 0, -152, -52, -18, -5, -33, -59, -125, 127, 89, 7, 3];
365 let result = vec![2, 5, 83, 113, 127, -63, -45, -15, -5, -33, -59, -125, 127, 89, 7, 3];
366 decode_right_side(&mut buffer);
367 assert_eq!(buffer, result);
368}
369
370/// Converts a buffer with mid samples and a side channel in-place to left ++ right.
371fn decode_mid_side(buffer: &mut [i32]) {
372 let block_size = buffer.len() / 2;
373 let (mids, sides) = buffer.split_at_mut(block_size);
374 for (fst, snd) in mids.iter_mut().zip(sides) {
375 let mid = *fst;
376 let side = *snd;
377
378 // Double mid first, and then correct for truncated rounding that
379 // will have occured if side is odd. Note that samples are never
380 // expected to exceed 25 bits, so the wrapping multiplication does not
381 // actually wrap for valid files.
382 let mid = mid.wrapping_mul(2) | (side & 1);
383 let left = mid.wrapping_add(side) / 2;
384 let right = mid.wrapping_sub(side) / 2;
385
386 *fst = left;
387 *snd = right;
388 }
389}
390
391#[test]
392fn verify_decode_mid_side() {
393 let mut buffer = vec!(-2, -14, 12, -6, 127, 13, -19, -6,
394 7, 38, 142, 238, 0, -152, -52, -18);
395 let result = vec!(2, 5, 83, 113, 127, -63, -45, -15,
396 -5, -33, -59, -125, 127, 89, 7, 3);
397 decode_mid_side(&mut buffer);
398 assert_eq!(buffer, result);
399}
400
401/// A block of raw audio samples.
402pub struct Block {
403 /// The sample number of the first sample in the this block.
404 first_sample_number: u64,
405 /// The number of samples in the block.
406 block_size: u32,
407 /// The number of channels in the block.
408 channels: u32,
409 /// The decoded samples, the channels stored consecutively.
410 buffer: Vec<i32>,
411}
412
413impl Block {
414 fn new(time: u64, bs: u32, buffer: Vec<i32>) -> Block {
415 Block {
416 first_sample_number: time,
417 block_size: bs,
418 channels: buffer.len() as u32 / bs,
419 buffer: buffer,
420 }
421 }
422
423 /// Returns a block with 0 channels and 0 samples.
424 pub fn empty() -> Block {
425 Block {
426 first_sample_number: 0,
427 block_size: 0,
428 channels: 0,
429 buffer: Vec::with_capacity(0),
430 }
431 }
432
433 /// Returns the inter-channel sample number of the first sample in the block.
434 ///
435 /// The time is independent of the number of channels. To get the start time
436 /// of the block in seconds, divide this number by the sample rate in the
437 /// streaminfo.
438 pub fn time(&self) -> u64 {
439 self.first_sample_number
440 }
441
442 /// Returns the total number of samples in this block.
443 ///
444 /// Samples in different channels are counted as distinct samples.
445 #[inline(always)]
446 pub fn len(&self) -> u32 {
447 // Note: this cannot overflow, because the block size fits in 16 bits,
448 // and the number of channels is at most 8.
449 self.block_size * self.channels
450 }
451
452 /// Returns the number of inter-channel samples in the block.
453 ///
454 /// The duration is independent of the number of channels. The returned
455 /// value is also referred to as the *block size*. To get the duration of
456 /// the block in seconds, divide this number by the sample rate in the
457 /// streaminfo.
458 #[inline(always)]
459 pub fn duration(&self) -> u32 {
460 self.block_size
461 }
462
463 /// Returns the number of channels in the block.
464 // TODO: Should a frame know this? #channels must be constant throughout the stream anyway ...
465 // TODO: Rename to `num_channels` for clarity.
466 #[inline(always)]
467 pub fn channels(&self) -> u32 {
468 self.channels
469 }
470
471 /// Returns the (zero-based) `ch`-th channel as a slice.
472 ///
473 /// # Panics
474 ///
475 /// Panics if `ch >= channels()`.
476 #[inline(always)]
477 pub fn channel(&self, ch: u32) -> &[i32] {
478 let bsz = self.block_size as usize;
479 let ch_usz = ch as usize;
480 &self.buffer[ch_usz * bsz..(ch_usz + 1) * bsz]
481 }
482
483 /// Returns a sample in this block.
484 ///
485 /// The value returned is for the zero-based `ch`-th channel of the
486 /// inter-channel sample with index `sample` in this block (so this is not
487 /// the global sample number).
488 ///
489 /// # Panics
490 ///
491 /// Panics if `ch >= channels()` or if `sample >= len()` for the last
492 /// channel.
493 #[inline(always)]
494 pub fn sample(&self, ch: u32, sample: u32) -> i32 {
495 let bsz = self.block_size as usize;
496 return self.buffer[ch as usize * bsz + sample as usize];
497 }
498
499 /// Returns the underlying buffer that stores the samples in this block.
500 ///
501 /// This allows the buffer to be reused to decode the next frame. The
502 /// capacity of the buffer may be bigger than `len()` times `channels()`.
503 pub fn into_buffer(self) -> Vec<i32> {
504 return self.buffer;
505 }
506
507 /// Returns an iterator that produces left and right channel samples.
508 ///
509 /// This iterator can be more efficient than requesting a sample directly,
510 /// because it avoids a bounds check.
511 ///
512 /// # Panics
513 ///
514 /// Panics if the number of channels in the block is not 2.
515 #[inline]
516 pub fn stereo_samples<'a>(&'a self) -> StereoSamples<'a> {
517 if self.channels != 2 {
518 panic!("stereo_samples() must only be called for blocks with two channels.");
519 }
520
521 assert!(self.buffer.len() >= self.block_size as usize * 2);
522
523 StereoSamples {
524 buffer: &self.buffer,
525 block_duration: self.block_size,
526 current_sample: 0,
527 }
528 }
529}
530
531#[test]
532fn verify_block_sample() {
533 let block = Block {
534 first_sample_number: 0,
535 block_size: 5,
536 channels: 3,
537 buffer: vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47],
538 };
539
540 assert_eq!(block.sample(0, 2), 5);
541 assert_eq!(block.sample(1, 3), 23);
542 assert_eq!(block.sample(2, 4), 47);
543}
544
545/// An iterator over the stereo sample pairs in a block.
546///
547/// This iterator is produced by `Block::stereo_samples()`.
548pub struct StereoSamples<'a> {
549 buffer: &'a [i32],
550 block_duration: u32,
551 current_sample: u32,
552}
553
554impl<'a> Iterator for StereoSamples<'a> {
555 type Item = (i32, i32);
556
557 #[inline(always)]
558 fn next(&mut self) -> Option<(i32, i32)> {
559 if self.current_sample == self.block_duration {
560 None
561 } else {
562 let ch_offset = self.block_duration as usize;
563 let idx = self.current_sample as usize;
564
565 // Indexing without bounds check is safe here, because the current
566 // sample is less than the block duration, and the buffer size is at
567 // least twice the block duration. (There is an assertion for that
568 // too when the iterator is constructed.)
569 let samples = unsafe {
570 let left = *self.buffer.get_unchecked(idx);
571 let right = *self.buffer.get_unchecked(idx + ch_offset);
572 (left, right)
573 };
574
575 self.current_sample += 1;
576
577 Some(samples)
578 }
579 }
580}
581
582#[test]
583fn verify_block_stereo_samples_iterator() {
584 let block = Block {
585 first_sample_number: 0,
586 block_size: 3,
587 channels: 2,
588 buffer: vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47],
589 };
590
591 let mut iter = block.stereo_samples();
592
593 assert_eq!(iter.next(), Some((2, 7)));
594 assert_eq!(iter.next(), Some((3, 11)));
595 assert_eq!(iter.next(), Some((5, 13)));
596 assert_eq!(iter.next(), None);
597}
598
599/// Reads frames from a stream and exposes decoded blocks as an iterator.
600///
601/// TODO: for now, it is assumes that the reader starts at a frame header;
602/// no searching for a sync code is performed at the moment.
603pub struct FrameReader<R: ReadBytes> {
604 input: R,
605}
606
607/// Either a `Block` or an `Error`.
608// TODO: The option should not be part of FrameResult.
609pub type FrameResult = Result<Option<Block>>;
610
611/// A function to expand the length of a buffer, or replace the buffer altogether,
612/// so it can hold at least `new_len` elements. The contents of the buffer can
613/// be anything, it is assumed they will be overwritten anyway.
614///
615/// To use this function safely, the caller must overwrite all `new_len` bytes.
616fn ensure_buffer_len(mut buffer: Vec<i32>, new_len: usize) -> Vec<i32> {
617 if buffer.len() < new_len {
618 // Previous data will be overwritten, so instead of resizing the
619 // vector if it is too small, we might as well allocate a new one.
620 // NOTE: In the past we allocated a vector with Vec::with_capacity here,
621 // setting it to the right length without zeroing (and also setting the
622 // right length if the capacity was sufficient). However, the
623 // performance impact of zeroing turned out to be negligible (a 0.2%
624 // increase in decode times in an adversarial scenario, but a 0.03%
625 // increase on real-world files when the buffer is recycled). We still
626 // don't zero out previous contents of the buffer as it was passed in,
627 // zeroing only happens on resize or for new allocations.
628 if buffer.capacity() < new_len {
629 buffer = vec![0; new_len];
630 } else {
631 buffer.resize(new_len, 0);
632 }
633 } else {
634 buffer.truncate(new_len);
635 }
636 buffer
637}
638
639#[test]
640fn ensure_buffer_len_returns_buffer_with_new_len() {
641 for capacity in 0..10 {
642 for new_len in 0..10 {
643 let buffer = Vec::with_capacity(capacity);
644 let resized = ensure_buffer_len(buffer, new_len);
645 assert_eq!(resized.len(), new_len);
646 }
647 }
648}
649
650impl<R: ReadBytes> FrameReader<R> {
651 /// Creates a new frame reader that will yield at least one element.
652 pub fn new(input: R) -> FrameReader<R> {
653 FrameReader {
654 input: input,
655 }
656 }
657
658 /// Decodes the next frame or returns an error if the data was invalid.
659 ///
660 /// The buffer is moved into the returned block, so that the same buffer may
661 /// be reused to decode multiple blocks, avoiding a heap allocation every
662 /// time. It can be retrieved again with `block.into_buffer()`. If the
663 /// buffer is not large enough to hold all samples, a larger buffer is
664 /// allocated automatically.
665 ///
666 /// TODO: I should really be consistent with 'read' and 'decode'.
667 pub fn read_next_or_eof(&mut self, mut buffer: Vec<i32>) -> FrameResult {
668 // The frame includes a CRC-16 at the end. It can be computed
669 // automatically while reading, by wrapping the input reader in a reader
670 // that computes the CRC. If the stream ended before the the frame
671 // header (so not in the middle of the frame header), return `None`,
672 // indicating EOF.
673 let mut crc_input = Crc16Reader::new(&mut self.input);
674 let header = match try!(read_frame_header_or_eof(&mut crc_input)) {
675 None => return Ok(None),
676 Some(h) => h,
677 };
678
679 // We must allocate enough space for all channels in the block to be
680 // decoded.
681 let total_samples = header.channels() as usize * header.block_size as usize;
682
683 // Ensure the buffer is the right size to hold all samples. For
684 // correctness, we must be careful to overwrite each byte in the buffer.
685 buffer = ensure_buffer_len(buffer, total_samples);
686
687 let bps = match header.bits_per_sample {
688 Some(x) => x,
689 // TODO: if the bps is missing from the header, we must get it from
690 // the streaminfo block.
691 None => return Err(Error::Unsupported("header without bits per sample info")),
692 };
693
694 // The number of bits per sample must not exceed 32, for we decode into
695 // an i32. TODO: Turn this into an error instead of panic? Or is it
696 // enforced elsewhere?
697 debug_assert!(bps as usize <= 32);
698
699 // In the next part of the stream, nothing is byte-aligned any more,
700 // we need a bitstream. Then we can decode subframes from the bitstream.
701 {
702 let mut bitstream = Bitstream::new(&mut crc_input);
703 let bs = header.block_size as usize;
704
705 match header.channel_assignment {
706 ChannelAssignment::Independent(n_ch) => {
707 for ch in 0..n_ch as usize {
708 try!(subframe::decode(&mut bitstream,
709 bps,
710 &mut buffer[ch * bs..(ch + 1) * bs]));
711 }
712 }
713 ChannelAssignment::LeftSideStereo => {
714 // The side channel has one extra bit per sample.
715 try!(subframe::decode(&mut bitstream, bps, &mut buffer[..bs]));
716 try!(subframe::decode(&mut bitstream,
717 bps + 1,
718 &mut buffer[bs..bs * 2]));
719
720 // Then decode the side channel into the right channel.
721 decode_left_side(&mut buffer[..bs * 2]);
722 }
723 ChannelAssignment::RightSideStereo => {
724 // The side channel has one extra bit per sample.
725 try!(subframe::decode(&mut bitstream, bps + 1, &mut buffer[..bs]));
726 try!(subframe::decode(&mut bitstream, bps, &mut buffer[bs..bs * 2]));
727
728 // Then decode the side channel into the left channel.
729 decode_right_side(&mut buffer[..bs * 2]);
730 }
731 ChannelAssignment::MidSideStereo => {
732 // Decode mid as the first channel, then side with one
733 // extra bitp per sample.
734 try!(subframe::decode(&mut bitstream, bps, &mut buffer[..bs]));
735 try!(subframe::decode(&mut bitstream,
736 bps + 1,
737 &mut buffer[bs..bs * 2]));
738
739 // Then decode mid-side channel into left-right.
740 decode_mid_side(&mut buffer[..bs * 2]);
741 }
742 }
743
744 // When the bitstream goes out of scope, we can use the `input`
745 // reader again, which will be byte-aligned. The specification
746 // dictates that padding should consist of zero bits, but we do not
747 // enforce this here.
748 // TODO: It could be enforced by having a read_to_byte_aligned
749 // method on the bit reader; it'd be a simple comparison.
750 }
751
752 // The frame footer is a 16-bit CRC.
753 let computed_crc = crc_input.crc();
754 let presumed_crc = try!(crc_input.read_be_u16());
755
756 // Do not verify checksum during fuzzing, otherwise malformed input from
757 // the fuzzer won't reach the actually interesting code.
758 #[cfg(not(fuzzing))]
759 {
760 if computed_crc != presumed_crc {
761 return fmt_err("frame CRC mismatch");
762 }
763 }
764
765 // Silence unused variable warnings.
766 #[cfg(fuzzing)]
767 let _ = computed_crc == presumed_crc;
768
769 // TODO: constant block size should be verified if a frame number is
770 // encountered.
771 let time = match header.block_time {
772 BlockTime::FrameNumber(fnr) => header.block_size as u64 * fnr as u64,
773 BlockTime::SampleNumber(snr) => snr,
774 };
775
776 let block = Block::new(time, header.block_size as u32, buffer);
777
778 Ok(Some(block))
779 }
780
781 /// Destroy the frame reader, returning the wrapped reader.
782 pub fn into_inner(self) -> R {
783 self.input
784 }
785}
786
787// TODO: implement Iterator<Item = FrameResult> for FrameReader, with an
788// accurate size hint.