edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·576f72d·Tahinli·3 months ago·1275 commits
| 1 | //! FLAC decoding: metadata blocks, frame headers, all four subframe kinds and |
| 2 | //! the three stereo decorrelations, per RFC 9639. |
| 3 | //! |
| 4 | //! Every parse routine takes a borrowed buffer and answers with |
| 5 | //! [`ec_core::Error`]: truncated input is `NeedMore`, a stream that breaks its |
| 6 | //! own rules is `Corrupt`. Nothing here panics on input — the only asserts are |
| 7 | //! in `ec_core::bitio`, and they fire on API misuse (`n > 64`), never on bytes. |
| 8 | |
| 9 | use ec_core::bitio::BitReader; |
| 10 | use ec_core::error::{Error, Result}; |
| 11 | |
| 12 | use crate::checksum::{crc8, crc16}; |
| 13 | |
| 14 | /// The four bytes every FLAC stream starts with. |
| 15 | pub const MAGIC: [u8; 4] = *b"fLaC"; |
| 16 | |
| 17 | /// Largest block size RFC 9639 can express (16-bit `block_size - 1`). |
| 18 | pub const MAX_BLOCK_SIZE: usize = 65536; |
| 19 | |
| 20 | /// The `STREAMINFO` metadata block: everything a player needs before the first |
| 21 | /// frame. |
| 22 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 23 | pub struct StreamInfo { |
| 24 | /// Smallest block size in the stream, in inter-channel samples. |
| 25 | pub min_block_size: u16, |
| 26 | /// Largest block size in the stream. Equal to `min_block_size` for a |
| 27 | /// fixed-block-size stream. |
| 28 | pub max_block_size: u16, |
| 29 | /// Smallest frame size in bytes; 0 when the encoder did not state it. |
| 30 | pub min_frame_size: u32, |
| 31 | /// Largest frame size in bytes; 0 when the encoder did not state it. |
| 32 | pub max_frame_size: u32, |
| 33 | /// Sample rate in Hz. 0 means "non-audio stream" and is refused here. |
| 34 | pub sample_rate: u32, |
| 35 | /// Channel count, 1..=8. |
| 36 | pub channels: u8, |
| 37 | /// Bits per sample, 4..=32. |
| 38 | pub bits_per_sample: u8, |
| 39 | /// Total inter-channel samples, or 0 when unknown. |
| 40 | pub total_samples: u64, |
| 41 | /// MD5 of the unencoded audio; all zero when the encoder did not compute it. |
| 42 | pub md5: [u8; 16], |
| 43 | } |
| 44 | |
| 45 | impl StreamInfo { |
| 46 | /// Parse the 34-byte `STREAMINFO` payload. |
| 47 | pub fn parse(data: &[u8]) -> Result<StreamInfo> { |
| 48 | if data.len() < 34 { |
| 49 | return Err(Error::NeedMore); |
| 50 | } |
| 51 | let mut r = BitReader::new(data); |
| 52 | let info = StreamInfo { |
| 53 | min_block_size: r.read_bits(16)? as u16, |
| 54 | max_block_size: r.read_bits(16)? as u16, |
| 55 | min_frame_size: r.read_bits(24)?, |
| 56 | max_frame_size: r.read_bits(24)?, |
| 57 | sample_rate: r.read_bits(20)?, |
| 58 | channels: (r.read_bits(3)? + 1) as u8, |
| 59 | bits_per_sample: (r.read_bits(5)? + 1) as u8, |
| 60 | total_samples: r.read_bits64(36)?, |
| 61 | md5: data[18..34].try_into().expect("18..34 is 16 bytes"), |
| 62 | }; |
| 63 | if info.sample_rate == 0 { |
| 64 | return Err(Error::corrupt("STREAMINFO: sample rate 0")); |
| 65 | } |
| 66 | if info.bits_per_sample < 4 { |
| 67 | return Err(Error::corrupt(format!( |
| 68 | "STREAMINFO: {} bits per sample", |
| 69 | info.bits_per_sample |
| 70 | ))); |
| 71 | } |
| 72 | if info.min_block_size < 16 || info.max_block_size < 16 { |
| 73 | return Err(Error::corrupt(format!( |
| 74 | "STREAMINFO: block sizes {}..{}", |
| 75 | info.min_block_size, info.max_block_size |
| 76 | ))); |
| 77 | } |
| 78 | Ok(info) |
| 79 | } |
| 80 | |
| 81 | /// The 34-byte `STREAMINFO` payload. |
| 82 | pub fn to_bytes(&self) -> [u8; 34] { |
| 83 | let mut out = [0u8; 34]; |
| 84 | out[0..2].copy_from_slice(&self.min_block_size.to_be_bytes()); |
| 85 | out[2..4].copy_from_slice(&self.max_block_size.to_be_bytes()); |
| 86 | out[4..7].copy_from_slice(&self.min_frame_size.to_be_bytes()[1..]); |
| 87 | out[7..10].copy_from_slice(&self.max_frame_size.to_be_bytes()[1..]); |
| 88 | let packed = (u64::from(self.sample_rate) << 44) |
| 89 | | (u64::from(self.channels - 1) << 41) |
| 90 | | (u64::from(self.bits_per_sample - 1) << 36) |
| 91 | | (self.total_samples & 0xf_ffff_ffff); |
| 92 | out[10..18].copy_from_slice(&packed.to_be_bytes()); |
| 93 | out[18..34].copy_from_slice(&self.md5); |
| 94 | out |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// One entry of the `SEEKTABLE` block. |
| 99 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 100 | pub struct SeekPoint { |
| 101 | /// First sample of the target frame. |
| 102 | pub sample: u64, |
| 103 | /// Byte offset of that frame from the first byte of the first frame. |
| 104 | pub offset: u64, |
| 105 | /// Samples in the target frame. |
| 106 | pub frame_samples: u16, |
| 107 | } |
| 108 | |
| 109 | /// How the channels of one frame were decorrelated. |
| 110 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 111 | pub enum ChannelAssignment { |
| 112 | /// `n` channels, each coded on its own. |
| 113 | Independent(u8), |
| 114 | /// Channel 0 is left, channel 1 is `left - right`. |
| 115 | LeftSide, |
| 116 | /// Channel 0 is `left - right`, channel 1 is right. |
| 117 | RightSide, |
| 118 | /// Channel 0 is `(left + right) >> 1`, channel 1 is `left - right`. |
| 119 | MidSide, |
| 120 | } |
| 121 | |
| 122 | impl ChannelAssignment { |
| 123 | /// Channels coded in the frame. |
| 124 | pub fn channel_count(&self) -> usize { |
| 125 | match self { |
| 126 | ChannelAssignment::Independent(n) => *n as usize, |
| 127 | _ => 2, |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// A parsed frame header, with the `STREAMINFO` fallbacks already resolved. |
| 133 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 134 | pub struct FrameHeader { |
| 135 | /// Inter-channel samples in this frame. |
| 136 | pub block_size: usize, |
| 137 | /// Sample rate in Hz. |
| 138 | pub sample_rate: u32, |
| 139 | /// Channel coding of this frame. |
| 140 | pub channels: ChannelAssignment, |
| 141 | /// Bits per sample of the *decoded* audio. |
| 142 | pub bits_per_sample: u32, |
| 143 | /// Frame number for a fixed-block-size stream, first sample number for a |
| 144 | /// variable-block-size one. |
| 145 | pub number: u64, |
| 146 | /// True when the stream declares variable block sizes. |
| 147 | pub variable_block_size: bool, |
| 148 | } |
| 149 | |
| 150 | impl FrameHeader { |
| 151 | /// First inter-channel sample of this frame, when it can be known: a |
| 152 | /// variable-block-size stream states it, a fixed one implies it from the |
| 153 | /// frame number and the block size the stream was written with. |
| 154 | pub fn first_sample(&self, stream_block_size: Option<usize>) -> Option<u64> { |
| 155 | match self.variable_block_size { |
| 156 | true => Some(self.number), |
| 157 | false => stream_block_size.map(|bs| self.number * bs as u64), |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// A decoded block: one `Vec<i32>` per channel, samples at the frame's own |
| 163 | /// bit depth (not shifted). |
| 164 | #[derive(Debug, Clone, Default)] |
| 165 | pub struct Block { |
| 166 | /// The header the samples came from. |
| 167 | pub header: Option<FrameHeader>, |
| 168 | /// Per-channel samples, already un-decorrelated. |
| 169 | pub channels: Vec<Vec<i32>>, |
| 170 | } |
| 171 | |
| 172 | impl Block { |
| 173 | /// Samples per channel. |
| 174 | pub fn len(&self) -> usize { |
| 175 | self.channels.first().map_or(0, Vec::len) |
| 176 | } |
| 177 | |
| 178 | /// True when no samples are held. |
| 179 | pub fn is_empty(&self) -> bool { |
| 180 | self.len() == 0 |
| 181 | } |
| 182 | |
| 183 | /// The block interleaved into one buffer, samples shifted left so they fill |
| 184 | /// a 16- or 32-bit container the way the oracle and every mixer expect |
| 185 | /// (`s16` for depths up to 16, `s32` above). |
| 186 | pub fn to_interleaved(&self, shift: u32) -> Vec<i32> { |
| 187 | let channels = self.channels.len(); |
| 188 | let len = self.len(); |
| 189 | let mut out = vec![0i32; len * channels]; |
| 190 | for (c, plane) in self.channels.iter().enumerate() { |
| 191 | for (i, &s) in plane.iter().enumerate() { |
| 192 | out[i * channels + c] = s << shift; |
| 193 | } |
| 194 | } |
| 195 | out |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | /// Bits the samples of a `bits_per_sample` stream are shifted left by to fill |
| 200 | /// their PCM container — the convention the oracle's decoder uses, so raw output |
| 201 | /// compares byte for byte. |
| 202 | pub fn container_shift(bits_per_sample: u32) -> u32 { |
| 203 | match bits_per_sample <= 16 { |
| 204 | true => 16 - bits_per_sample, |
| 205 | false => 32 - bits_per_sample, |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /// A FLAC stream over a complete in-memory buffer. |
| 210 | /// |
| 211 | /// Metadata is parsed on construction; frames are decoded one call at a time so |
| 212 | /// a caller can stop, seek and resume without decoding what it will discard. |
| 213 | #[derive(Debug)] |
| 214 | pub struct FlacReader<'a> { |
| 215 | data: &'a [u8], |
| 216 | stream_info: Option<StreamInfo>, |
| 217 | seek_table: Vec<SeekPoint>, |
| 218 | first_frame: usize, |
| 219 | pos: usize, |
| 220 | residual: Vec<i32>, |
| 221 | } |
| 222 | |
| 223 | impl<'a> FlacReader<'a> { |
| 224 | /// Open a stream: read the magic and metadata blocks, then stop at the |
| 225 | /// first frame. |
| 226 | /// |
| 227 | /// A buffer that does not start with `fLaC` is scanned for a frame sync |
| 228 | /// instead — some tools hand out FLAC that starts mid-stream, and the frame |
| 229 | /// headers carry enough to decode without `STREAMINFO`. |
| 230 | pub fn new(data: &'a [u8]) -> Result<FlacReader<'a>> { |
| 231 | let mut reader = FlacReader { |
| 232 | data, |
| 233 | stream_info: None, |
| 234 | seek_table: Vec::new(), |
| 235 | first_frame: 0, |
| 236 | pos: 0, |
| 237 | residual: Vec::new(), |
| 238 | }; |
| 239 | if data.len() >= 4 && data[..4] == MAGIC { |
| 240 | reader.read_metadata(4)?; |
| 241 | } else { |
| 242 | reader.first_frame = find_frame_sync(data, 0, None) |
| 243 | .ok_or_else(|| Error::corrupt("no fLaC magic and no frame sync"))?; |
| 244 | reader.pos = reader.first_frame; |
| 245 | } |
| 246 | Ok(reader) |
| 247 | } |
| 248 | |
| 249 | /// A reader over bare frames — what a container hands out, one packet at a |
| 250 | /// time, with the `STREAMINFO` it carried in its own headers. |
| 251 | pub fn frames(data: &'a [u8], info: Option<StreamInfo>) -> Result<FlacReader<'a>> { |
| 252 | let first_frame = find_frame_sync(data, 0, info.as_ref()) |
| 253 | .ok_or_else(|| Error::corrupt("no FLAC frame sync in this packet"))?; |
| 254 | Ok(FlacReader { |
| 255 | data, |
| 256 | stream_info: info, |
| 257 | seek_table: Vec::new(), |
| 258 | first_frame, |
| 259 | pos: first_frame, |
| 260 | residual: Vec::new(), |
| 261 | }) |
| 262 | } |
| 263 | |
| 264 | fn read_metadata(&mut self, mut at: usize) -> Result<()> { |
| 265 | let mut first = true; |
| 266 | loop { |
| 267 | let header = self.data.get(at..at + 4).ok_or(Error::NeedMore)?; |
| 268 | let last = header[0] & 0x80 != 0; |
| 269 | let kind = header[0] & 0x7f; |
| 270 | let len = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize; |
| 271 | let body = self.data.get(at + 4..at + 4 + len).ok_or(Error::NeedMore)?; |
| 272 | if first && kind != 0 { |
| 273 | return Err(Error::corrupt(format!( |
| 274 | "first metadata block is type {kind}, not STREAMINFO" |
| 275 | ))); |
| 276 | } |
| 277 | match kind { |
| 278 | 0 => self.stream_info = Some(StreamInfo::parse(body)?), |
| 279 | 3 => { |
| 280 | self.seek_table = body |
| 281 | .chunks_exact(18) |
| 282 | .map(|p| SeekPoint { |
| 283 | sample: u64::from_be_bytes(p[0..8].try_into().expect("8 bytes")), |
| 284 | offset: u64::from_be_bytes(p[8..16].try_into().expect("8 bytes")), |
| 285 | frame_samples: u16::from_be_bytes( |
| 286 | p[16..18].try_into().expect("2 bytes"), |
| 287 | ), |
| 288 | }) |
| 289 | // A placeholder point (sample == u64::MAX) indexes nothing. |
| 290 | .filter(|p| p.sample != u64::MAX) |
| 291 | .collect(); |
| 292 | } |
| 293 | 127 => return Err(Error::corrupt("metadata block type 127 is invalid")), |
| 294 | _ => {} |
| 295 | } |
| 296 | first = false; |
| 297 | at += 4 + len; |
| 298 | if last { |
| 299 | break; |
| 300 | } |
| 301 | } |
| 302 | self.first_frame = at; |
| 303 | self.pos = at; |
| 304 | Ok(()) |
| 305 | } |
| 306 | |
| 307 | /// The `STREAMINFO` block, when the stream had one. |
| 308 | pub fn stream_info(&self) -> Option<&StreamInfo> { |
| 309 | self.stream_info.as_ref() |
| 310 | } |
| 311 | |
| 312 | /// The seek table, empty when the stream carries none. |
| 313 | pub fn seek_table(&self) -> &[SeekPoint] { |
| 314 | &self.seek_table |
| 315 | } |
| 316 | |
| 317 | /// Byte offset of the next frame to be decoded. |
| 318 | pub fn position(&self) -> usize { |
| 319 | self.pos |
| 320 | } |
| 321 | |
| 322 | /// Position the reader at the last indexed frame at or before `sample` and |
| 323 | /// answer that frame's first sample; the caller decodes forward and |
| 324 | /// discards the difference (`SeekMode::SyncBefore`). |
| 325 | /// |
| 326 | /// Without a seek table the answer is the start of the stream: FLAC frames |
| 327 | /// are not self-indexing, so a blind scan would cost the same as decoding. |
| 328 | pub fn seek_to_sample(&mut self, sample: u64) -> u64 { |
| 329 | let point = self |
| 330 | .seek_table |
| 331 | .iter() |
| 332 | .filter(|p| p.sample <= sample) |
| 333 | .max_by_key(|p| p.sample); |
| 334 | match point { |
| 335 | Some(p) if self.first_frame + p.offset as usize <= self.data.len() => { |
| 336 | self.pos = self.first_frame + p.offset as usize; |
| 337 | p.sample |
| 338 | } |
| 339 | _ => { |
| 340 | self.pos = self.first_frame; |
| 341 | 0 |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// Decode the next frame into `block`, reusing its buffers. |
| 347 | /// |
| 348 | /// Answers `false` at the end of the stream. Trailing bytes that are not a |
| 349 | /// frame (an ID3v1 tag, padding a container left) end the stream rather |
| 350 | /// than failing it; a frame that starts well and then breaks is `Corrupt`. |
| 351 | pub fn next_block(&mut self, block: &mut Block) -> Result<bool> { |
| 352 | if self.pos >= self.data.len() { |
| 353 | return Ok(false); |
| 354 | } |
| 355 | let start = match find_frame_sync(self.data, self.pos, self.stream_info.as_ref()) { |
| 356 | Some(at) => at, |
| 357 | None => { |
| 358 | self.pos = self.data.len(); |
| 359 | return Ok(false); |
| 360 | } |
| 361 | }; |
| 362 | self.pos = start; |
| 363 | let mut r = BitReader::new(&self.data[start..]); |
| 364 | let header = parse_frame_header(&mut r, self.stream_info.as_ref())?; |
| 365 | let header_bytes = (r.bit_position() / 8) as usize; |
| 366 | let want = crc8(&self.data[start..start + header_bytes - 1]); |
| 367 | if want != self.data[start + header_bytes - 1] { |
| 368 | return Err(Error::corrupt(format!( |
| 369 | "frame at {start}: header CRC-8 {:#04x}, expected {want:#04x}", |
| 370 | self.data[start + header_bytes - 1] |
| 371 | ))); |
| 372 | } |
| 373 | |
| 374 | let coded = header.channels.channel_count(); |
| 375 | block.channels.resize_with(coded, Vec::new); |
| 376 | for (c, plane) in block.channels.iter_mut().enumerate() { |
| 377 | let side = matches!( |
| 378 | (header.channels, c), |
| 379 | (ChannelAssignment::LeftSide, 1) |
| 380 | | (ChannelAssignment::MidSide, 1) |
| 381 | | (ChannelAssignment::RightSide, 0) |
| 382 | ); |
| 383 | let bps = header.bits_per_sample + u32::from(side); |
| 384 | decode_subframe(&mut r, bps, header.block_size, plane, &mut self.residual)?; |
| 385 | } |
| 386 | r.align_to_byte(); |
| 387 | let frame_bytes = (r.bit_position() / 8) as usize; |
| 388 | let stated = r.read_bits(16)? as u16; |
| 389 | let want = crc16(&self.data[start..start + frame_bytes]); |
| 390 | if stated != want { |
| 391 | return Err(Error::corrupt(format!( |
| 392 | "frame at {start}: CRC-16 {stated:#06x}, expected {want:#06x}" |
| 393 | ))); |
| 394 | } |
| 395 | undecorrelate(header.channels, &mut block.channels)?; |
| 396 | block.header = Some(header); |
| 397 | self.pos = start + frame_bytes + 2; |
| 398 | Ok(true) |
| 399 | } |
| 400 | |
| 401 | /// Decode the whole stream into per-channel planes, verifying the |
| 402 | /// `STREAMINFO` MD5 when the stream states one. |
| 403 | /// |
| 404 | /// Convenience over [`FlacReader::next_block`]: it holds the whole decoded |
| 405 | /// stream in memory, which is what a fixture test and a waveform pass want |
| 406 | /// and what a player does not. |
| 407 | pub fn decode_all(&mut self) -> Result<DecodedStream> { |
| 408 | let mut block = Block::default(); |
| 409 | let mut out: Vec<Vec<i32>> = Vec::new(); |
| 410 | let mut header: Option<FrameHeader> = None; |
| 411 | while self.next_block(&mut block)? { |
| 412 | let h = block.header.expect("a decoded block has a header"); |
| 413 | match header { |
| 414 | None => { |
| 415 | out.resize_with(block.channels.len(), Vec::new); |
| 416 | header = Some(h); |
| 417 | } |
| 418 | Some(prev) |
| 419 | if prev.bits_per_sample != h.bits_per_sample |
| 420 | || prev.sample_rate != h.sample_rate |
| 421 | || prev.channels.channel_count() != h.channels.channel_count() => |
| 422 | { |
| 423 | return Err(Error::unsupported( |
| 424 | "FLAC stream changing format mid-stream", |
| 425 | format!( |
| 426 | "{}ch/{}bit/{}Hz became {}ch/{}bit/{}Hz", |
| 427 | prev.channels.channel_count(), |
| 428 | prev.bits_per_sample, |
| 429 | prev.sample_rate, |
| 430 | h.channels.channel_count(), |
| 431 | h.bits_per_sample, |
| 432 | h.sample_rate |
| 433 | ), |
| 434 | )); |
| 435 | } |
| 436 | Some(_) => {} |
| 437 | } |
| 438 | for (dst, src) in out.iter_mut().zip(&block.channels) { |
| 439 | dst.extend_from_slice(src); |
| 440 | } |
| 441 | } |
| 442 | let header = header.ok_or(Error::Eof)?; |
| 443 | Ok(DecodedStream { |
| 444 | bits_per_sample: header.bits_per_sample, |
| 445 | sample_rate: header.sample_rate, |
| 446 | channels: out, |
| 447 | }) |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | /// The result of [`FlacReader::decode_all`]. |
| 452 | #[derive(Debug, Clone)] |
| 453 | pub struct DecodedStream { |
| 454 | /// Bit depth of the samples. |
| 455 | pub bits_per_sample: u32, |
| 456 | /// Sample rate in Hz. |
| 457 | pub sample_rate: u32, |
| 458 | /// One plane per channel, samples at the stream's own bit depth. |
| 459 | pub channels: Vec<Vec<i32>>, |
| 460 | } |
| 461 | |
| 462 | impl DecodedStream { |
| 463 | /// Samples per channel. |
| 464 | pub fn len(&self) -> usize { |
| 465 | self.channels.first().map_or(0, Vec::len) |
| 466 | } |
| 467 | |
| 468 | /// True when nothing decoded. |
| 469 | pub fn is_empty(&self) -> bool { |
| 470 | self.len() == 0 |
| 471 | } |
| 472 | |
| 473 | /// Interleaved samples at the stream's own bit depth. |
| 474 | pub fn interleaved(&self) -> Vec<i32> { |
| 475 | let channels = self.channels.len(); |
| 476 | let mut out = vec![0i32; self.len() * channels]; |
| 477 | for (c, plane) in self.channels.iter().enumerate() { |
| 478 | for (i, &s) in plane.iter().enumerate() { |
| 479 | out[i * channels + c] = s; |
| 480 | } |
| 481 | } |
| 482 | out |
| 483 | } |
| 484 | |
| 485 | /// Interleaved samples shifted into their PCM container, as raw bytes: |
| 486 | /// `s16le` for depths up to 16 bits, `s32le` above. This is exactly what |
| 487 | /// `the oracle -f s16le/-f s32le` writes for the same file. |
| 488 | pub fn to_pcm_bytes(&self) -> Vec<u8> { |
| 489 | let shift = container_shift(self.bits_per_sample); |
| 490 | let narrow = self.bits_per_sample <= 16; |
| 491 | let mut out = Vec::with_capacity(self.len() * self.channels.len() * 4); |
| 492 | for i in 0..self.len() { |
| 493 | for plane in &self.channels { |
| 494 | let v = plane[i] << shift; |
| 495 | match narrow { |
| 496 | true => out.extend_from_slice(&(v as i16).to_le_bytes()), |
| 497 | false => out.extend_from_slice(&v.to_le_bytes()), |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | out |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | /// Byte offset of the next plausible frame sync at or after `from`. |
| 506 | /// |
| 507 | /// "Plausible" is: the 14-bit sync code, a zero reserved bit, and a header that |
| 508 | /// both parses and matches its own CRC-8. That is what makes resynchronisation |
| 509 | /// after damage, and opening a buffer that starts mid-stream, safe. |
| 510 | pub fn find_frame_sync(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option<usize> { |
| 511 | let mut at = from; |
| 512 | while at + 2 <= data.len() { |
| 513 | if data[at] == 0xff && data[at + 1] & 0xfe == 0xf8 { |
| 514 | let mut r = BitReader::new(&data[at..]); |
| 515 | if let Ok(_header) = parse_frame_header(&mut r, info) { |
| 516 | let n = (r.bit_position() / 8) as usize; |
| 517 | if at + n <= data.len() && crc8(&data[at..at + n - 1]) == data[at + n - 1] { |
| 518 | return Some(at); |
| 519 | } |
| 520 | } |
| 521 | } |
| 522 | at += 1; |
| 523 | } |
| 524 | None |
| 525 | } |
| 526 | |
| 527 | /// Parse a frame header, resolving the "same as `STREAMINFO`" codes. |
| 528 | pub fn parse_frame_header(r: &mut BitReader<'_>, info: Option<&StreamInfo>) -> Result<FrameHeader> { |
| 529 | if r.read_bits(14)? != 0x3ffe { |
| 530 | return Err(Error::corrupt("frame header: bad sync code")); |
| 531 | } |
| 532 | if r.read_bit()? { |
| 533 | return Err(Error::corrupt("frame header: reserved bit set")); |
| 534 | } |
| 535 | let variable_block_size = r.read_bit()?; |
| 536 | let block_size_code = r.read_bits(4)?; |
| 537 | let sample_rate_code = r.read_bits(4)?; |
| 538 | let channel_code = r.read_bits(4)?; |
| 539 | let bps_code = r.read_bits(3)?; |
| 540 | if r.read_bit()? { |
| 541 | return Err(Error::corrupt("frame header: second reserved bit set")); |
| 542 | } |
| 543 | |
| 544 | let number = read_utf8_number(r, if variable_block_size { 36 } else { 31 })?; |
| 545 | |
| 546 | let block_size = match block_size_code { |
| 547 | 0 => return Err(Error::corrupt("frame header: block size code 0")), |
| 548 | 1 => 192, |
| 549 | 2..=5 => 576 << (block_size_code - 2), |
| 550 | 6 => r.read_bits(8)? as usize + 1, |
| 551 | 7 => r.read_bits(16)? as usize + 1, |
| 552 | _ => 256 << (block_size_code - 8), |
| 553 | }; |
| 554 | let sample_rate = match sample_rate_code { |
| 555 | 0 => info |
| 556 | .map(|i| i.sample_rate) |
| 557 | .ok_or_else(|| Error::corrupt("frame header: rate from a missing STREAMINFO"))?, |
| 558 | 1 => 88200, |
| 559 | 2 => 176_400, |
| 560 | 3 => 192_000, |
| 561 | 4 => 8000, |
| 562 | 5 => 16000, |
| 563 | 6 => 22050, |
| 564 | 7 => 24000, |
| 565 | 8 => 32000, |
| 566 | 9 => 44100, |
| 567 | 10 => 48000, |
| 568 | 11 => 96000, |
| 569 | 12 => r.read_bits(8)? * 1000, |
| 570 | 13 => r.read_bits(16)?, |
| 571 | 14 => r.read_bits(16)? * 10, |
| 572 | _ => return Err(Error::corrupt("frame header: sample rate code 15")), |
| 573 | }; |
| 574 | let channels = match channel_code { |
| 575 | 0..=7 => ChannelAssignment::Independent(channel_code as u8 + 1), |
| 576 | 8 => ChannelAssignment::LeftSide, |
| 577 | 9 => ChannelAssignment::RightSide, |
| 578 | 10 => ChannelAssignment::MidSide, |
| 579 | _ => { |
| 580 | return Err(Error::corrupt(format!( |
| 581 | "frame header: channel assignment {channel_code}" |
| 582 | ))); |
| 583 | } |
| 584 | }; |
| 585 | let bits_per_sample = match bps_code { |
| 586 | 0 => info |
| 587 | .map(|i| u32::from(i.bits_per_sample)) |
| 588 | .ok_or_else(|| Error::corrupt("frame header: depth from a missing STREAMINFO"))?, |
| 589 | 1 => 8, |
| 590 | 2 => 12, |
| 591 | 3 => return Err(Error::corrupt("frame header: bit depth code 3 is reserved")), |
| 592 | 4 => 16, |
| 593 | 5 => 20, |
| 594 | 6 => 24, |
| 595 | _ => 32, |
| 596 | }; |
| 597 | // The CRC-8 byte closes the header; callers check it against the bytes they |
| 598 | // hold, so it is only skipped here. |
| 599 | r.skip_bits(8)?; |
| 600 | Ok(FrameHeader { |
| 601 | block_size, |
| 602 | sample_rate, |
| 603 | channels, |
| 604 | bits_per_sample, |
| 605 | number, |
| 606 | variable_block_size, |
| 607 | }) |
| 608 | } |
| 609 | |
| 610 | /// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider |
| 611 | /// than real UTF-8). |
| 612 | pub(crate) fn read_utf8_number(r: &mut BitReader<'_>, max_bits: u32) -> Result<u64> { |
| 613 | let first = r.read_bits(8)?; |
| 614 | let extra = match first { |
| 615 | 0x00..=0x7f => 0, |
| 616 | 0xc0..=0xdf => 1, |
| 617 | 0xe0..=0xef => 2, |
| 618 | 0xf0..=0xf7 => 3, |
| 619 | 0xf8..=0xfb => 4, |
| 620 | 0xfc..=0xfd => 5, |
| 621 | 0xfe => 6, |
| 622 | _ => return Err(Error::corrupt("frame header: bad coded-number prefix")), |
| 623 | }; |
| 624 | // The lead byte carries `6 - extra` payload bits after its prefix. |
| 625 | let mut value = match extra { |
| 626 | 0 => u64::from(first), |
| 627 | _ => u64::from(first & ((1u32 << (6 - extra)) - 1)), |
| 628 | }; |
| 629 | for _ in 0..extra { |
| 630 | let byte = r.read_bits(8)?; |
| 631 | if byte & 0xc0 != 0x80 { |
| 632 | return Err(Error::corrupt( |
| 633 | "frame header: bad coded-number continuation", |
| 634 | )); |
| 635 | } |
| 636 | value = (value << 6) | u64::from(byte & 0x3f); |
| 637 | } |
| 638 | if max_bits < 64 && value >> max_bits != 0 { |
| 639 | return Err(Error::corrupt(format!( |
| 640 | "frame header: coded number {value} exceeds {max_bits} bits" |
| 641 | ))); |
| 642 | } |
| 643 | Ok(value) |
| 644 | } |
| 645 | |
| 646 | fn decode_subframe( |
| 647 | r: &mut BitReader<'_>, |
| 648 | bps: u32, |
| 649 | block_size: usize, |
| 650 | out: &mut Vec<i32>, |
| 651 | residual: &mut Vec<i32>, |
| 652 | ) -> Result<()> { |
| 653 | if r.read_bit()? { |
| 654 | return Err(Error::corrupt("subframe: padding bit set")); |
| 655 | } |
| 656 | let kind = r.read_bits(6)?; |
| 657 | let mut wasted = 0u32; |
| 658 | if r.read_bit()? { |
| 659 | wasted = 1; |
| 660 | while !r.read_bit()? { |
| 661 | wasted += 1; |
| 662 | if wasted >= bps { |
| 663 | break; |
| 664 | } |
| 665 | } |
| 666 | } |
| 667 | if wasted >= bps { |
| 668 | return Err(Error::corrupt(format!( |
| 669 | "subframe: {wasted} wasted bits of {bps}" |
| 670 | ))); |
| 671 | } |
| 672 | let bps = bps - wasted; |
| 673 | if bps > 32 { |
| 674 | // Only a 32-bit stream that also decorrelates its stereo pair gets |
| 675 | // here: its side channel needs 33 bits, which does not fit the i32 |
| 676 | // sample planes this decoder (and the oracle's, and the reference encoder's encoder) |
| 677 | // works in. Named rather than mangled. |
| 678 | return Err(Error::unsupported( |
| 679 | "33-bit side subframe", |
| 680 | "32-bit stereo decorrelation needs 33-bit sample planes", |
| 681 | )); |
| 682 | } |
| 683 | |
| 684 | out.clear(); |
| 685 | out.reserve(block_size); |
| 686 | match kind { |
| 687 | 0 => { |
| 688 | let value = r.read_signed(bps)?; |
| 689 | out.resize(block_size, value); |
| 690 | } |
| 691 | 1 => { |
| 692 | for _ in 0..block_size { |
| 693 | out.push(r.read_signed(bps)?); |
| 694 | } |
| 695 | } |
| 696 | 8..=12 => decode_fixed(r, (kind - 8) as usize, bps, block_size, out, residual)?, |
| 697 | 32..=63 => decode_lpc(r, (kind - 31) as usize, bps, block_size, out, residual)?, |
| 698 | _ => { |
| 699 | return Err(Error::corrupt(format!("subframe: type {kind} is reserved"))); |
| 700 | } |
| 701 | } |
| 702 | if wasted > 0 { |
| 703 | for s in out.iter_mut() { |
| 704 | *s <<= wasted; |
| 705 | } |
| 706 | } |
| 707 | Ok(()) |
| 708 | } |
| 709 | |
| 710 | fn decode_fixed( |
| 711 | r: &mut BitReader<'_>, |
| 712 | order: usize, |
| 713 | bps: u32, |
| 714 | block_size: usize, |
| 715 | out: &mut Vec<i32>, |
| 716 | residual: &mut Vec<i32>, |
| 717 | ) -> Result<()> { |
| 718 | if order > block_size { |
| 719 | return Err(Error::corrupt(format!( |
| 720 | "fixed subframe: order {order} over a {block_size}-sample block" |
| 721 | ))); |
| 722 | } |
| 723 | for _ in 0..order { |
| 724 | out.push(r.read_signed(bps)?); |
| 725 | } |
| 726 | decode_residual(r, block_size, order, residual)?; |
| 727 | for (i, &res) in residual.iter().enumerate() { |
| 728 | let n = order + i; |
| 729 | let p = &out[n - order..n]; |
| 730 | // Fixed predictors are the first four differences of the signal. |
| 731 | let predicted: i64 = match order { |
| 732 | 0 => 0, |
| 733 | 1 => i64::from(p[0]), |
| 734 | 2 => 2 * i64::from(p[1]) - i64::from(p[0]), |
| 735 | 3 => 3 * i64::from(p[2]) - 3 * i64::from(p[1]) + i64::from(p[0]), |
| 736 | _ => 4 * i64::from(p[3]) - 6 * i64::from(p[2]) + 4 * i64::from(p[1]) - i64::from(p[0]), |
| 737 | }; |
| 738 | out.push((predicted as i32).wrapping_add(res)); |
| 739 | } |
| 740 | Ok(()) |
| 741 | } |
| 742 | |
| 743 | fn decode_lpc( |
| 744 | r: &mut BitReader<'_>, |
| 745 | order: usize, |
| 746 | bps: u32, |
| 747 | block_size: usize, |
| 748 | out: &mut Vec<i32>, |
| 749 | residual: &mut Vec<i32>, |
| 750 | ) -> Result<()> { |
| 751 | if order > block_size { |
| 752 | return Err(Error::corrupt(format!( |
| 753 | "LPC subframe: order {order} over a {block_size}-sample block" |
| 754 | ))); |
| 755 | } |
| 756 | for _ in 0..order { |
| 757 | out.push(r.read_signed(bps)?); |
| 758 | } |
| 759 | let precision = r.read_bits(4)? + 1; |
| 760 | if precision == 16 { |
| 761 | return Err(Error::corrupt("LPC subframe: coefficient precision 15+1")); |
| 762 | } |
| 763 | let shift = r.read_signed(5)?; |
| 764 | if shift < 0 { |
| 765 | return Err(Error::corrupt(format!( |
| 766 | "LPC subframe: negative shift {shift}" |
| 767 | ))); |
| 768 | } |
| 769 | let mut coefs = [0i64; 32]; |
| 770 | for c in coefs.iter_mut().take(order) { |
| 771 | *c = i64::from(r.read_signed(precision)?); |
| 772 | } |
| 773 | decode_residual(r, block_size, order, residual)?; |
| 774 | let coefs = &coefs[..order]; |
| 775 | for (i, &res) in residual.iter().enumerate() { |
| 776 | let n = order + i; |
| 777 | let history = &out[n - order..n]; |
| 778 | // 64-bit accumulation: 32-bit samples with 15-bit coefficients at order |
| 779 | // 32 need 52 bits, and the "predictor overflow" streams exist to catch |
| 780 | // a decoder that accumulates narrower. |
| 781 | let mut sum = 0i64; |
| 782 | for (c, &s) in coefs.iter().zip(history.iter().rev()) { |
| 783 | sum += c * i64::from(s); |
| 784 | } |
| 785 | out.push(((sum >> shift) as i32).wrapping_add(res)); |
| 786 | } |
| 787 | Ok(()) |
| 788 | } |
| 789 | |
| 790 | fn decode_residual( |
| 791 | r: &mut BitReader<'_>, |
| 792 | block_size: usize, |
| 793 | order: usize, |
| 794 | out: &mut Vec<i32>, |
| 795 | ) -> Result<()> { |
| 796 | let method = r.read_bits(2)?; |
| 797 | let param_bits = match method { |
| 798 | 0 => 4, |
| 799 | 1 => 5, |
| 800 | _ => { |
| 801 | return Err(Error::corrupt(format!( |
| 802 | "residual: coding method {method} is reserved" |
| 803 | ))); |
| 804 | } |
| 805 | }; |
| 806 | let escape = (1u32 << param_bits) - 1; |
| 807 | let partition_order = r.read_bits(4)?; |
| 808 | let partitions = 1usize << partition_order; |
| 809 | if !block_size.is_multiple_of(partitions) { |
| 810 | return Err(Error::corrupt(format!( |
| 811 | "residual: {partitions} partitions over a {block_size}-sample block" |
| 812 | ))); |
| 813 | } |
| 814 | let partition_len = block_size / partitions; |
| 815 | if partition_len < order { |
| 816 | return Err(Error::corrupt(format!( |
| 817 | "residual: order {order} over {partition_len}-sample partitions" |
| 818 | ))); |
| 819 | } |
| 820 | out.clear(); |
| 821 | out.reserve(block_size - order); |
| 822 | for p in 0..partitions { |
| 823 | let count = partition_len - if p == 0 { order } else { 0 }; |
| 824 | let param = r.read_bits(param_bits)?; |
| 825 | if param == escape { |
| 826 | let raw = r.read_bits(5)?; |
| 827 | for _ in 0..count { |
| 828 | out.push(match raw { |
| 829 | 0 => 0, |
| 830 | n => r.read_signed(n)?, |
| 831 | }); |
| 832 | } |
| 833 | } else { |
| 834 | for _ in 0..count { |
| 835 | out.push(read_rice(r, param)?); |
| 836 | } |
| 837 | } |
| 838 | } |
| 839 | Ok(()) |
| 840 | } |
| 841 | |
| 842 | /// One Rice-coded, zig-zag folded residual. |
| 843 | fn read_rice(r: &mut BitReader<'_>, param: u32) -> Result<i32> { |
| 844 | let mut quotient = 0u32; |
| 845 | while !r.read_bit()? { |
| 846 | quotient += 1; |
| 847 | // A quotient wider than the sample container is damage, not data; the |
| 848 | // cap is what keeps a fuzzed stream from spinning to the end of the |
| 849 | // buffer one bit at a time. |
| 850 | if quotient > 1 << 20 { |
| 851 | return Err(Error::corrupt("residual: Rice quotient over 2^20")); |
| 852 | } |
| 853 | } |
| 854 | let folded = match param { |
| 855 | 0 => quotient, |
| 856 | n => (quotient << n) | r.read_bits(n)?, |
| 857 | }; |
| 858 | Ok(((folded >> 1) as i32) ^ -((folded & 1) as i32)) |
| 859 | } |
| 860 | |
| 861 | fn undecorrelate(assignment: ChannelAssignment, channels: &mut [Vec<i32>]) -> Result<()> { |
| 862 | if matches!(assignment, ChannelAssignment::Independent(_)) { |
| 863 | return Ok(()); |
| 864 | } |
| 865 | let (a, b) = channels.split_at_mut(1); |
| 866 | let (a, b) = (&mut a[0], &mut b[0]); |
| 867 | if a.len() != b.len() { |
| 868 | return Err(Error::corrupt("stereo decorrelation over unequal channels")); |
| 869 | } |
| 870 | match assignment { |
| 871 | ChannelAssignment::LeftSide => { |
| 872 | // a = left, b = left - right. |
| 873 | for (l, s) in a.iter().zip(b.iter_mut()) { |
| 874 | *s = l.wrapping_sub(*s); |
| 875 | } |
| 876 | } |
| 877 | ChannelAssignment::RightSide => { |
| 878 | // a = left - right, b = right. |
| 879 | for (s, r) in a.iter_mut().zip(b.iter()) { |
| 880 | *s = s.wrapping_add(*r); |
| 881 | } |
| 882 | } |
| 883 | ChannelAssignment::MidSide => { |
| 884 | for (m, s) in a.iter_mut().zip(b.iter_mut()) { |
| 885 | // The low bit of the difference is carried in the mid channel. |
| 886 | let mid = (*m << 1) | (*s & 1); |
| 887 | let side = *s; |
| 888 | *m = mid.wrapping_add(side) >> 1; |
| 889 | *s = mid.wrapping_sub(side) >> 1; |
| 890 | } |
| 891 | } |
| 892 | ChannelAssignment::Independent(_) => unreachable!("returned above"), |
| 893 | } |
| 894 | Ok(()) |
| 895 | } |
| 896 | |
| 897 | #[cfg(test)] |
| 898 | mod tests { |
| 899 | use super::*; |
| 900 | |
| 901 | #[test] |
| 902 | fn stream_info_round_trips() { |
| 903 | let info = StreamInfo { |
| 904 | min_block_size: 4096, |
| 905 | max_block_size: 4096, |
| 906 | min_frame_size: 14, |
| 907 | max_frame_size: 16384, |
| 908 | sample_rate: 44100, |
| 909 | channels: 2, |
| 910 | bits_per_sample: 16, |
| 911 | total_samples: 1_234_567, |
| 912 | md5: [7; 16], |
| 913 | }; |
| 914 | assert_eq!(StreamInfo::parse(&info.to_bytes()).unwrap(), info); |
| 915 | } |
| 916 | |
| 917 | #[test] |
| 918 | fn truncated_input_is_need_more_not_a_panic() { |
| 919 | let info = StreamInfo { |
| 920 | min_block_size: 16, |
| 921 | max_block_size: 16, |
| 922 | min_frame_size: 0, |
| 923 | max_frame_size: 0, |
| 924 | sample_rate: 8000, |
| 925 | channels: 1, |
| 926 | bits_per_sample: 8, |
| 927 | total_samples: 0, |
| 928 | md5: [0; 16], |
| 929 | }; |
| 930 | let bytes = info.to_bytes(); |
| 931 | for n in 0..34 { |
| 932 | assert!(StreamInfo::parse(&bytes[..n]).unwrap_err().is_need_more()); |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | #[test] |
| 937 | fn garbage_never_panics_and_never_opens() { |
| 938 | for seed in 0..64u32 { |
| 939 | let junk: Vec<u8> = (0..512).map(|i| (i * 37 + seed * 11) as u8).collect(); |
| 940 | let _ = FlacReader::new(&junk).map(|mut r| { |
| 941 | let mut b = Block::default(); |
| 942 | let _ = r.next_block(&mut b); |
| 943 | }); |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | #[test] |
| 948 | fn mid_side_inverts_the_encoder_transform() { |
| 949 | let left: Vec<i32> = (-8..8).collect(); |
| 950 | let right: Vec<i32> = (0..16).map(|i| i * 3 - 20).collect(); |
| 951 | let mid: Vec<i32> = left.iter().zip(&right).map(|(l, r)| (l + r) >> 1).collect(); |
| 952 | let side: Vec<i32> = left.iter().zip(&right).map(|(l, r)| l - r).collect(); |
| 953 | let mut planes = vec![mid, side]; |
| 954 | undecorrelate(ChannelAssignment::MidSide, &mut planes).unwrap(); |
| 955 | assert_eq!(planes[0], left); |
| 956 | assert_eq!(planes[1], right); |
| 957 | } |
| 958 | |
| 959 | #[test] |
| 960 | fn container_shift_matches_reference_layout() { |
| 961 | assert_eq!(container_shift(8), 8); |
| 962 | assert_eq!(container_shift(12), 4); |
| 963 | assert_eq!(container_shift(16), 0); |
| 964 | assert_eq!(container_shift(20), 12); |
| 965 | assert_eq!(container_shift(24), 8); |
| 966 | assert_eq!(container_shift(32), 0); |
| 967 | } |
| 968 | } |