Gapless Info tag, and the region split a switched granule must use
Browse files at this commit09040ebdf398d4a7472f5320df69571f87402c6cParent: 6e48da7- fix
- gapless Info tag, and the region split a switched granule must use
3 changed files +531 -87
- crates/ec-mp3/src/encode.rs +504 -85
- crates/ec-mp3/src/lib.rs +4 -1
- crates/ec-mp3/tests/encode_matrix.rs +23 -1
crates/ec-mp3/src/encode.rsmodified+504 -85
| @@ -20,7 +20,7 @@ | |||
| 20 | use crate::filterbank::{Analysis, alias_expand}; | 20 | use crate::filterbank::{Analysis, alias_expand}; |
| 21 | use crate::header::{ChannelMode, FrameHeader, Version}; | 21 | use crate::header::{ChannelMode, FrameHeader, Version}; |
| 22 | use crate::huffman::{self, Table}; | 22 | use crate::huffman::{self, Table}; |
| 23 | -use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, windows}; | 23 | +use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, short_widths, windows}; |
| 24 | use ec_core::bitio::BitWriter; | 24 | use ec_core::bitio::BitWriter; |
| 25 | use ec_core::error::{Error, Result}; | 25 | use ec_core::error::{Error, Result}; |
| 26 | use ec_dsp::{RealFft, Window}; | 26 | use ec_dsp::{RealFft, Window}; |
| @@ -101,6 +101,9 @@ pub struct Mp3Encode { | |||
| 101 | history: Vec<[[f32; 32]; 18]>, | 101 | history: Vec<[[f32; 32]; 18]>, |
| 102 | /// Window type chosen for the granule we are holding back. | 102 | /// Window type chosen for the granule we are holding back. |
| 103 | pending: Vec<PendingGranule>, | 103 | pending: Vec<PendingGranule>, |
| 104 | + /// The block type each channel's previous granule used. Window switching | ||
| 105 | + /// is a sequence, and the sequence does not restart at a frame boundary. | ||
| 106 | + previous_block: Vec<u8>, | ||
| 104 | fft: RealFft<f32>, | 107 | fft: RealFft<f32>, |
| 105 | fft_window: Window<f32>, | 108 | fft_window: Window<f32>, |
| 106 | psy_history: Vec<Vec<f32>>, | 109 | psy_history: Vec<Vec<f32>>, |
| @@ -161,6 +164,7 @@ impl Mp3Encode { | |||
| 161 | slots: vec![Vec::new(); channels], | 164 | slots: vec![Vec::new(); channels], |
| 162 | history: vec![[[0.0; 32]; 18]; channels], | 165 | history: vec![[[0.0; 32]; 18]; channels], |
| 163 | pending: Vec::new(), | 166 | pending: Vec::new(), |
| 167 | + previous_block: vec![0; channels], | ||
| 164 | fft: RealFft::new(1024), | 168 | fft: RealFft::new(1024), |
| 165 | fft_window: Window::sine(1024), | 169 | fft_window: Window::sine(1024), |
| 166 | psy_history: vec![vec![0.0; 1024]; channels], | 170 | psy_history: vec![vec![0.0; 1024]; channels], |
| @@ -242,6 +246,7 @@ impl Mp3Encoder { | |||
| 242 | None => self.config.bitrate_kbps.max(8), | 246 | None => self.config.bitrate_kbps.max(8), |
| 243 | }; | 247 | }; |
| 244 | self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?); | 248 | self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?); |
| 249 | + self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0); | ||
| 245 | } | 250 | } |
| 246 | self.pcm.extend_from_slice(interleaved); | 251 | self.pcm.extend_from_slice(interleaved); |
| 247 | self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64; | 252 | self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64; |
| @@ -268,10 +273,11 @@ impl Mp3Encoder { | |||
| 268 | pub fn finish(&mut self) { | 273 | pub fn finish(&mut self) { |
| 269 | if let Some(core) = &self.core { | 274 | if let Some(core) = &self.core { |
| 270 | let channels = core.channels; | 275 | let channels = core.channels; |
| 271 | - // The filterbank runs fifteen slots behind, and the MDCT one | 276 | + // The filterbank runs fifteen slots behind, the MDCT one granule |
| 272 | - // granule behind that; feed silence so the last real samples come | 277 | + // behind that, and block switching holds one more granule back to |
| 273 | - // out the other end. | 278 | + // look ahead; feed silence so every real sample comes out the other |
| 274 | - let tail = vec![0.0f32; channels * (576 * 2 + 480)]; | 279 | + // end rather than being dropped with the pipeline. |
| 280 | + let tail = vec![0.0f32; channels * (576 * 3 + 480)]; | ||
| 275 | self.pcm.extend_from_slice(&tail); | 281 | self.pcm.extend_from_slice(&tail); |
| 276 | } | 282 | } |
| 277 | self.drain(true); | 283 | self.drain(true); |
| @@ -294,6 +300,7 @@ impl Mp3Encoder { | |||
| 294 | block.resize(need, 0.0); | 300 | block.resize(need, 0.0); |
| 295 | core.encode_block(&block); | 301 | core.encode_block(&block); |
| 296 | } | 302 | } |
| 303 | + core.flush_pending(); | ||
| 297 | core.flush_frames(); | 304 | core.flush_frames(); |
| 298 | } | 305 | } |
| 299 | while let Some(frame) = core.ready.pop_front() { | 306 | while let Some(frame) = core.ready.pop_front() { |
| @@ -307,7 +314,7 @@ impl Mp3Encoder { | |||
| 307 | if !self.header_written && (self.finished || !self.frames.is_empty()) { | 314 | if !self.header_written && (self.finished || !self.frames.is_empty()) { |
| 308 | self.header_written = true; | 315 | self.header_written = true; |
| 309 | if let Some(core) = &self.core { | 316 | if let Some(core) = &self.core { |
| 310 | - return Ok(info_frame(core, self.total_samples)); | 317 | + return Ok(info_frame(core, self.total_samples, self.finished)); |
| 311 | } | 318 | } |
| 312 | } | 319 | } |
| 313 | match self.frames.pop_front() { | 320 | match self.frames.pop_front() { |
| @@ -318,20 +325,102 @@ impl Mp3Encoder { | |||
| 318 | } | 325 | } |
| 319 | } | 326 | } |
| 320 | 327 | ||
| 328 | +/// Silence prepended to the first PCM the encoder is given. | ||
| 329 | +/// | ||
| 330 | +/// The first MDCT block has no predecessor to overlap with, so the frame it | ||
| 331 | +/// produces cannot reconstruct — the transform's startup, not a coding loss. | ||
| 332 | +/// Priming with a frame of silence puts that region before the audio instead | ||
| 333 | +/// of on top of it, and the delay field below tells a decoder to drop it. It | ||
| 334 | +/// is what makes the first frame of a gapless decode as good as the rest; | ||
| 335 | +/// without it that frame correlates 0.67 against its input while every other | ||
| 336 | +/// frame is above 0.999. | ||
| 337 | +const PRIMING: usize = 1152; | ||
| 338 | + | ||
| 339 | +/// Samples of PCM this encoder's pipeline runs ahead of its output: the | ||
| 340 | +/// [`PRIMING`] silence, plus the analysis bank running fifteen slots behind | ||
| 341 | +/// its input and the MDCT one granule behind that, less what the decoder's | ||
| 342 | +/// synthesis gives back. Measured end to end (encode, decode, | ||
| 343 | +/// cross-correlate) as 1728 samples of lag, of which 529 is the decoder delay | ||
| 344 | +/// every LAME-tag consumer adds for itself. | ||
| 345 | +/// | ||
| 346 | +/// `encoder_delay_is_what_the_tag_says` is that measurement as a test: change | ||
| 347 | +/// the pipeline and it fails rather than silently mis-stating the tag. | ||
| 348 | +pub(crate) const ENCODER_DELAY: u32 = PRIMING as u32 + 47; | ||
| 349 | + | ||
| 350 | +/// The decoder delay a LAME tag consumer adds to the encoder delay. Fixed by | ||
| 351 | +/// the tag's own convention, not by anything here, so nothing in the encoder | ||
| 352 | +/// spends it — `encoder_delay_is_what_the_tag_says` is what it is for. | ||
| 353 | +#[allow(dead_code)] | ||
| 354 | +const DECODER_DELAY: u32 = 529; | ||
| 355 | + | ||
| 356 | +/// The nine-byte encoder string in the LAME extension. | ||
| 357 | +/// | ||
| 358 | +/// It says `LAME3.100` and not `ec-mp3` on purpose, and this is the one place | ||
| 359 | +/// this crate writes something it is not: ffmpeg (and every player that copied | ||
| 360 | +/// its parser) only reads the delay and padding fields when those first four | ||
| 361 | +/// bytes are `LAME`, `Lavc` or `Lavf`. Writing our own name there produces a | ||
| 362 | +/// tag that parses and is then ignored, which is worse than useless — the | ||
| 363 | +/// gapless information would be present and unusable. The rest of the | ||
| 364 | +/// extension is filled honestly or zeroed. | ||
| 365 | +const LAME_VERSION: &[u8; 9] = b"LAME3.100"; | ||
| 366 | + | ||
| 321 | /// The Xing/Info header frame every player expects first: a silent frame whose | 367 | /// The Xing/Info header frame every player expects first: a silent frame whose |
| 322 | /// main data is the tag, so a decoder that does not know the tag still decodes | 368 | /// main data is the tag, so a decoder that does not know the tag still decodes |
| 323 | /// a legal (silent) frame rather than choking. | 369 | /// a legal (silent) frame rather than choking. |
| 324 | -fn info_frame(core: &Mp3Encode, samples: u64) -> Vec<u8> { | 370 | +/// |
| 371 | +/// Carries frame and byte counts and — the point of it — the encoder delay and | ||
| 372 | +/// padding, which is what lets a decoder hand back exactly the samples that | ||
| 373 | +/// went in. Those two are exact when the caller pushes all its PCM before | ||
| 374 | +/// pulling packets, which is the pattern the family's exporter uses; a caller | ||
| 375 | +/// that interleaves pushes and pulls gets the delay (a constant) right and the | ||
| 376 | +/// counts as of the first pull. | ||
| 377 | +fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { | ||
| 325 | let header = core.header(); | 378 | let header = core.header(); |
| 326 | let frame_len = header.frame_len().unwrap_or(417); | 379 | let frame_len = header.frame_len().unwrap_or(417); |
| 327 | let mut out = vec![0u8; frame_len]; | 380 | let mut out = vec![0u8; frame_len]; |
| 328 | out[..4].copy_from_slice(&header.to_bytes()); | 381 | out[..4].copy_from_slice(&header.to_bytes()); |
| 329 | let at = 4 + header.side_info_len(); | 382 | let at = 4 + header.side_info_len(); |
| 330 | - let tag: &[u8] = b"Info"; | 383 | + let spf = header.samples_per_frame() as u64; |
| 331 | - out[at..at + 4].copy_from_slice(tag); | 384 | + let (frames, padding) = if complete { |
| 332 | - out[at + 4..at + 8].copy_from_slice(&1u32.to_be_bytes()); // frames field present | 385 | + let frames = core.frames; |
| 333 | - let frames = samples.div_ceil(header.samples_per_frame() as u64) as u32; | 386 | + let coded = u64::from(frames) * spf; |
| 334 | - out[at + 8..at + 12].copy_from_slice(&frames.to_be_bytes()); | 387 | + let padding = coded.saturating_sub(samples + u64::from(ENCODER_DELAY)); |
| 388 | + (frames, padding.min(4095) as u32) | ||
| 389 | + } else { | ||
| 390 | + (0, 0) | ||
| 391 | + }; | ||
| 392 | + let bytes = if complete { | ||
| 393 | + (u64::from(frames) + 1) * frame_len as u64 | ||
| 394 | + } else { | ||
| 395 | + 0 | ||
| 396 | + }; | ||
| 397 | + | ||
| 398 | + let mut tag: Vec<u8> = Vec::with_capacity(64); | ||
| 399 | + tag.extend_from_slice(b"Info"); // constant bitrate; "Xing" is the VBR name | ||
| 400 | + tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present | ||
| 401 | + tag.extend_from_slice(&frames.to_be_bytes()); | ||
| 402 | + tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes()); | ||
| 403 | + tag.extend_from_slice(LAME_VERSION); | ||
| 404 | + tag.push(0); // tag revision and VBR method | ||
| 405 | + tag.push(0); // lowpass in 100 Hz units, unstated | ||
| 406 | + tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak | ||
| 407 | + tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain | ||
| 408 | + tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain | ||
| 409 | + tag.push(0); // encoding flags and ATH type | ||
| 410 | + tag.push(core.bitrate_kbps.min(255) as u8); | ||
| 411 | + let delay_padding = (ENCODER_DELAY << 12) | padding; | ||
| 412 | + tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each | ||
| 413 | + tag.push(0); // misc | ||
| 414 | + tag.push(0); // mp3gain | ||
| 415 | + tag.extend_from_slice(&0u16.to_be_bytes()); // preset and surround info | ||
| 416 | + tag.extend_from_slice(&0u32.to_be_bytes()); // music length | ||
| 417 | + tag.extend_from_slice(&0u16.to_be_bytes()); // music CRC | ||
| 418 | + tag.extend_from_slice(&0u16.to_be_bytes()); // tag CRC | ||
| 419 | + // A frame too small to hold the whole tag keeps the fields that fit, in | ||
| 420 | + // order, which is how the parsers read it anyway. | ||
| 421 | + let room = frame_len - at; | ||
| 422 | + let take = tag.len().min(room); | ||
| 423 | + out[at..at + take].copy_from_slice(&tag[..take]); | ||
| 335 | out | 424 | out |
| 336 | } | 425 | } |
| 337 | 426 | ||
| @@ -451,28 +540,36 @@ impl Mp3Encode { | |||
| 451 | let frame_len = header.frame_len().unwrap_or(0); | 540 | let frame_len = header.frame_len().unwrap_or(0); |
| 452 | let capacity = frame_len - 4 - header.side_info_len(); | 541 | let capacity = frame_len - 4 - header.side_info_len(); |
| 453 | 542 | ||
| 454 | - // Window types: a granule whose successor is much louder starts the | 543 | + // Window types. A granule whose successor is much louder starts the |
| 455 | - // switch, the loud one is short, and the one after stops it. | 544 | + // switch, the loud one is short, and the one after stops it — and the |
| 545 | + // sequence carries across frames, because a start window in the last | ||
| 546 | + // granule of one frame demands a short block in the first granule of | ||
| 547 | + // the next. Restarting it per frame is what leaves a start window | ||
| 548 | + // facing a normal one, whose overlap does not reconstruct. | ||
| 456 | let mut types = vec![0u8; granules * channels]; | 549 | let mut types = vec![0u8; granules * channels]; |
| 457 | for gr in 0..granules { | 550 | for gr in 0..granules { |
| 458 | for ch in 0..channels { | 551 | for ch in 0..channels { |
| 459 | let index = gr * channels + ch; | 552 | let index = gr * channels + ch; |
| 460 | - let next = index + channels; | ||
| 461 | let here = self.pending[index].energy; | 553 | let here = self.pending[index].energy; |
| 462 | - let there = self.pending.get(next).map_or(here, |g| g.energy); | 554 | + let next = self |
| 463 | - if there > here * 8.0 + 1e-6 { | 555 | + .pending |
| 464 | - types[index] = 1; // start | 556 | + .get(index + channels) |
| 465 | - } | 557 | + .map_or(here, |g| g.energy); |
| 466 | - } | 558 | + // Digital silence is not a transient to protect: switching on |
| 467 | - } | 559 | + // the way out of it (the priming, or a cut in a timeline) costs |
| 468 | - for gr in 0..granules { | 560 | + // the resolution a long block would have spent on the attack |
| 469 | - for ch in 0..channels { | 561 | + // itself, and there is no pre-echo to hide when nothing |
| 470 | - let index = gr * channels + ch; | 562 | + // precedes it. |
| 471 | - if index >= channels && types[index - channels] == 1 { | 563 | + let attack = here > 1e-9 && next > here * 8.0 + 1e-6; |
| 472 | - types[index] = 2; // short | 564 | + let block = match self.previous_block[ch] { |
| 473 | - } else if index >= 2 * channels && types[index - 2 * channels] == 2 { | 565 | + 1 => 2, |
| 474 | - types[index] = 3; // stop | 566 | + 2 if attack => 2, |
| 475 | - } | 567 | + 2 => 3, |
| 568 | + _ if attack => 1, | ||
| 569 | + _ => 0, | ||
| 570 | + }; | ||
| 571 | + types[index] = block; | ||
| 572 | + self.previous_block[ch] = block; | ||
| 476 | } | 573 | } |
| 477 | } | 574 | } |
| 478 | 575 | ||
| @@ -591,6 +688,14 @@ impl Mp3Encode { | |||
| 591 | } | 688 | } |
| 592 | } | 689 | } |
| 593 | 690 | ||
| 691 | + /// Encodes the granules still held back for block-switching lookahead. | ||
| 692 | + fn flush_pending(&mut self) { | ||
| 693 | + let per_frame = self.granules() * self.channels; | ||
| 694 | + while self.pending.len() >= per_frame { | ||
| 695 | + self.emit_frame(); | ||
| 696 | + } | ||
| 697 | + } | ||
| 698 | + | ||
| 594 | /// Writes out whatever frames are still queued, padding the stream so the | 699 | /// Writes out whatever frames are still queued, padding the stream so the |
| 595 | /// last frame is complete. | 700 | /// last frame is complete. |
| 596 | fn flush_frames(&mut self) { | 701 | fn flush_frames(&mut self) { |
| @@ -692,9 +797,12 @@ fn quantise_granule( | |||
| 692 | // Spending the bits matters as much as the threshold does — a granule that | 797 | // Spending the bits matters as much as the threshold does — a granule that |
| 693 | // stops early leaves the extra bitrate on the floor, which is what makes an | 798 | // stops early leaves the extra bitrate on the floor, which is what makes an |
| 694 | // encoder's quality flat across 128 and 320 kbit/s. | 799 | // encoder's quality flat across 128 and 320 kbit/s. |
| 800 | + // Short blocks carry twelve bands, long ones twenty-one. | ||
| 801 | + let bands = if block_type == 2 { 12 } else { SFB_LONG }; | ||
| 802 | + let threshold = band_thresholds(threshold, block_type, sample_rate); | ||
| 695 | for _round in 0..20 { | 803 | for _round in 0..20 { |
| 696 | let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate); | 804 | let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate); |
| 697 | - let ratios: Vec<f64> = (0..SFB_LONG) | 805 | + let ratios: Vec<f64> = (0..bands) |
| 698 | .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30)) | 806 | .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30)) |
| 699 | .collect(); | 807 | .collect(); |
| 700 | let score: f64 = ratios.iter().sum(); | 808 | let score: f64 = ratios.iter().sum(); |
| @@ -702,14 +810,13 @@ fn quantise_granule( | |||
| 702 | if best.as_ref().is_none_or(|(_, s)| score < *s) { | 810 | if best.as_ref().is_none_or(|(_, s)| score < *s) { |
| 703 | best = Some((granule, score)); | 811 | best = Some((granule, score)); |
| 704 | } | 812 | } |
| 705 | - if block_type == 2 { | ||
| 706 | - break; // short blocks carry no long scalefactors here | ||
| 707 | - } | ||
| 708 | if spent * 20 > target_bits * 19 { | 813 | if spent * 20 > target_bits * 19 { |
| 709 | break; // the budget is spent; amplifying now only coarsens | 814 | break; // the budget is spent; amplifying now only coarsens |
| 710 | } | 815 | } |
| 711 | // Amplify the bands that are worst against their threshold. | 816 | // Amplify the bands that are worst against their threshold. |
| 712 | - let mut order: Vec<usize> = (0..SFB_LONG).filter(|&b| scalefac[b] < 15).collect(); | 817 | + let mut order: Vec<usize> = (0..bands) |
| 818 | + .filter(|&b| scalefac[b] < max_scalefac(b, block_type)) | ||
| 819 | + .collect(); | ||
| 713 | order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a])); | 820 | order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a])); |
| 714 | let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect(); | 821 | let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect(); |
| 715 | let chosen: Vec<usize> = if over.is_empty() { | 822 | let chosen: Vec<usize> = if over.is_empty() { |
| @@ -727,6 +834,66 @@ fn quantise_granule( | |||
| 727 | best.expect("at least one round runs").0 | 834 | best.expect("at least one round runs").0 |
| 728 | } | 835 | } |
| 729 | 836 | ||
| 837 | +/// Bitstream order for a short block's spectrum. | ||
| 838 | +/// | ||
| 839 | +/// A short granule is coded band by band, window by window, line by line, | ||
| 840 | +/// while the spectrum the transform produces interleaves the three windows on | ||
| 841 | +/// every line — the decoder's reorder step. The encoder has to undo it before | ||
| 842 | +/// Huffman coding; writing spectral order instead costs exactly the same | ||
| 843 | +/// number of bits, lands exactly on `part2_3_length`, and hands the decoder a | ||
| 844 | +/// permuted granule, which comes back as noise. | ||
| 845 | +fn short_reorder(sample_rate: u32, spectral: &[i32]) -> Vec<i32> { | ||
| 846 | + let widths = short_widths(sample_rate); | ||
| 847 | + let starts = short_starts(sample_rate); | ||
| 848 | + let mut out = Vec::with_capacity(576); | ||
| 849 | + for sfb in 0..13 { | ||
| 850 | + let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb])); | ||
| 851 | + for window in 0..3 { | ||
| 852 | + for line in 0..width { | ||
| 853 | + let position = (start + line) * 3 + window; | ||
| 854 | + out.push(spectral.get(position).copied().unwrap_or(0)); | ||
| 855 | + } | ||
| 856 | + } | ||
| 857 | + } | ||
| 858 | + out.resize(576, 0); | ||
| 859 | + out | ||
| 860 | +} | ||
| 861 | + | ||
| 862 | +/// The largest scalefactor a band can actually carry. | ||
| 863 | +/// | ||
| 864 | +/// `scalefac_compress` names two lengths, and the second partition's is at most | ||
| 865 | +/// three bits — so a band above the split cannot hold more than 7 however much | ||
| 866 | +/// the distortion loop would like to amplify it. Ignoring that ceiling is not a | ||
| 867 | +/// rounding error: the quantiser uses the value it wanted, no length can encode | ||
| 868 | +/// it, and the decoder reconstructs the band with a scalefactor of zero, which | ||
| 869 | +/// turns the granule into noise. | ||
| 870 | +fn max_scalefac(band: usize, block_type: u8) -> u8 { | ||
| 871 | + let split = if block_type == 2 { 6 } else { 11 }; | ||
| 872 | + if band < split { 15 } else { 7 } | ||
| 873 | +} | ||
| 874 | + | ||
| 875 | +/// The masking model works in long bands; a short block's twelve bands are | ||
| 876 | +/// read off it at the same frequencies, so one model serves both. | ||
| 877 | +fn band_thresholds(threshold: &[f32], block_type: u8, sample_rate: u32) -> Vec<f32> { | ||
| 878 | + if block_type != 2 { | ||
| 879 | + return threshold.to_vec(); | ||
| 880 | + } | ||
| 881 | + let long = long_starts(sample_rate); | ||
| 882 | + let short = short_starts(sample_rate); | ||
| 883 | + (0..12) | ||
| 884 | + .map(|band| { | ||
| 885 | + // A short band's lines sit at three times its index in the spectrum. | ||
| 886 | + let line = usize::from(short[band]) * 3; | ||
| 887 | + let long_band = (0..SFB_LONG) | ||
| 888 | + .rev() | ||
| 889 | + .find(|&b| line >= usize::from(long[b])) | ||
| 890 | + .unwrap_or(0); | ||
| 891 | + // Three windows share the band, so each carries a third of it. | ||
| 892 | + threshold[long_band] / 3.0 | ||
| 893 | + }) | ||
| 894 | + .collect() | ||
| 895 | +} | ||
| 896 | + | ||
| 730 | /// Quantises with a fixed scalefactor set, running the rate loop on | 897 | /// Quantises with a fixed scalefactor set, running the rate loop on |
| 731 | /// `global_gain`, and reports the noise each band ends up with. | 898 | /// `global_gain`, and reports the noise each band ends up with. |
| 732 | fn code_with( | 899 | fn code_with( |
| @@ -736,10 +903,11 @@ fn code_with( | |||
| 736 | scalefac: &[u8; SFB_LONG], | 903 | scalefac: &[u8; SFB_LONG], |
| 737 | sample_rate: u32, | 904 | sample_rate: u32, |
| 738 | ) -> (CodedGranule, [f32; SFB_LONG]) { | 905 | ) -> (CodedGranule, [f32; SFB_LONG]) { |
| 739 | - let (slen1, slen2, compress) = scalefac_compress(scalefac); | 906 | + let (slen1, slen2, compress) = scalefac_compress(scalefac, block_type); |
| 740 | - // The scalefactors come out of the same budget as the spectrum does. | 907 | + // The scalefactors come out of the same budget as the spectrum does. A |
| 908 | + // short block transmits six bands of each length, once per window. | ||
| 741 | let scalefac_bits = if block_type == 2 { | 909 | let scalefac_bits = if block_type == 2 { |
| 742 | - 0 | 910 | + (slen1 + slen2) * 18 |
| 743 | } else { | 911 | } else { |
| 744 | slen1 * 11 + slen2 * 10 | 912 | slen1 * 11 + slen2 * 10 |
| 745 | }; | 913 | }; |
| @@ -759,13 +927,20 @@ fn code_with( | |||
| 759 | // while the granule is too big for them. A line that saturates the coding | 927 | // while the granule is too big for them. A line that saturates the coding |
| 760 | // range is not "cheap", it is clipped, so that check comes first. | 928 | // range is not "cheap", it is clipped, so that check comes first. |
| 761 | let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191); | 929 | let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191); |
| 930 | + let for_coding = |ix: &[i32]| -> Vec<i32> { | ||
| 931 | + if block_type == 2 { | ||
| 932 | + short_reorder(sample_rate, ix) | ||
| 933 | + } else { | ||
| 934 | + ix.to_vec() | ||
| 935 | + } | ||
| 936 | + }; | ||
| 762 | quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); | 937 | quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); |
| 763 | - coded = code_spectrum(&ix, block_type, sample_rate); | 938 | + coded = code_spectrum(&for_coding(&ix), block_type, sample_rate); |
| 764 | loop { | 939 | loop { |
| 765 | if (saturated(&ix) || coded.0 > target_bits) && gain < 255 { | 940 | if (saturated(&ix) || coded.0 > target_bits) && gain < 255 { |
| 766 | gain += 1; | 941 | gain += 1; |
| 767 | quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); | 942 | quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); |
| 768 | - coded = code_spectrum(&ix, block_type, sample_rate); | 943 | + coded = code_spectrum(&for_coding(&ix), block_type, sample_rate); |
| 769 | continue; | 944 | continue; |
| 770 | } | 945 | } |
| 771 | if saturated(&ix) || coded.0 > target_bits || gain == 0 { | 946 | if saturated(&ix) || coded.0 > target_bits || gain == 0 { |
| @@ -775,7 +950,7 @@ fn code_with( | |||
| 775 | // inside the coding range. | 950 | // inside the coding range. |
| 776 | let mut trial = ix.clone(); | 951 | let mut trial = ix.clone(); |
| 777 | quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial); | 952 | quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial); |
| 778 | - let trial_coded = code_spectrum(&trial, block_type, sample_rate); | 953 | + let trial_coded = code_spectrum(&for_coding(&trial), block_type, sample_rate); |
| 779 | if trial_coded.0 > target_bits || saturated(&trial) { | 954 | if trial_coded.0 > target_bits || saturated(&trial) { |
| 780 | break; | 955 | break; |
| 781 | } | 956 | } |
| @@ -793,27 +968,46 @@ fn code_with( | |||
| 793 | for slot in ix.iter_mut().skip(limit) { | 968 | for slot in ix.iter_mut().skip(limit) { |
| 794 | *slot = 0; | 969 | *slot = 0; |
| 795 | } | 970 | } |
| 796 | - coded = code_spectrum(&ix, block_type, sample_rate); | 971 | + coded = code_spectrum(&for_coding(&ix), block_type, sample_rate); |
| 797 | } | 972 | } |
| 798 | let (_, big_values, tables, region0, region1, count1_select, bits) = coded; | 973 | let (_, big_values, tables, region0, region1, count1_select, bits) = coded; |
| 799 | let mut noise = [0.0f32; SFB_LONG]; | 974 | let mut noise = [0.0f32; SFB_LONG]; |
| 800 | - let starts = long_starts(sample_rate); | ||
| 801 | let power = power43(); | 975 | let power = power43(); |
| 802 | - for band in 0..SFB_LONG { | 976 | + let residual = |i: usize, band: usize| -> f32 { |
| 803 | - let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); | ||
| 804 | let scale = band_gain(gain, scalefac[band], block_type); | 977 | let scale = band_gain(gain, scalefac[band], block_type); |
| 805 | - let mut sum = 0.0f32; | 978 | + let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale; |
| 806 | - for i in from..to.min(576) { | 979 | + let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude }; |
| 807 | - let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale; | 980 | + (xr[i] - reconstructed).powi(2) |
| 808 | - let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude }; | 981 | + }; |
| 809 | - sum += (xr[i] - reconstructed).powi(2); | 982 | + if block_type == 2 { |
| 983 | + for (i, _) in ix.iter().enumerate().take(576) { | ||
| 984 | + let band = short_band(i, sample_rate); | ||
| 985 | + noise[band.min(SFB_LONG - 1)] += residual(i, band); | ||
| 986 | + } | ||
| 987 | + } else { | ||
| 988 | + let starts = long_starts(sample_rate); | ||
| 989 | + for band in 0..SFB_LONG { | ||
| 990 | + let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); | ||
| 991 | + let mut sum = 0.0f32; | ||
| 992 | + for i in from..to.min(576) { | ||
| 993 | + sum += residual(i, band); | ||
| 994 | + } | ||
| 995 | + noise[band] = sum; | ||
| 810 | } | 996 | } |
| 811 | - noise[band] = sum; | ||
| 812 | } | 997 | } |
| 813 | let mut out = BitWriter::new(); | 998 | let mut out = BitWriter::new(); |
| 814 | - for (band, value) in scalefac.iter().enumerate() { | 999 | + if block_type == 2 { |
| 815 | - let slen = if band < 11 { slen1 } else { slen2 }; | 1000 | + // The decoder reads short scalefactors band-major, three windows at a |
| 816 | - if block_type != 2 { | 1001 | + // time; ours are one per band, so each is written three times. |
| 1002 | + for (band, value) in scalefac.iter().enumerate().take(12) { | ||
| 1003 | + let slen = if band < 6 { slen1 } else { slen2 }; | ||
| 1004 | + for _window in 0..3 { | ||
| 1005 | + out.write_bits(u32::from(*value), slen); | ||
| 1006 | + } | ||
| 1007 | + } | ||
| 1008 | + } else { | ||
| 1009 | + for (band, value) in scalefac.iter().enumerate() { | ||
| 1010 | + let slen = if band < 11 { slen1 } else { slen2 }; | ||
| 817 | out.write_bits(u32::from(*value), slen); | 1011 | out.write_bits(u32::from(*value), slen); |
| 818 | } | 1012 | } |
| 819 | } | 1013 | } |
| @@ -840,13 +1034,9 @@ fn code_with( | |||
| 840 | (granule, noise) | 1034 | (granule, noise) |
| 841 | } | 1035 | } |
| 842 | 1036 | ||
| 843 | -fn band_gain(gain: i32, scalefac: u8, block_type: u8) -> f32 { | 1037 | +fn band_gain(gain: i32, scalefac: u8, _block_type: u8) -> f32 { |
| 844 | let base = (gain as f32 - 210.0) * 0.25; | 1038 | let base = (gain as f32 - 210.0) * 0.25; |
| 845 | - if block_type == 2 { | 1039 | + (base - 0.5 * f32::from(scalefac)).exp2() |
| 846 | - base.exp2() | ||
| 847 | - } else { | ||
| 848 | - (base - 0.5 * f32::from(scalefac)).exp2() | ||
| 849 | - } | ||
| 850 | } | 1040 | } |
| 851 | 1041 | ||
| 852 | /// The spectrum as integers, per the decoder's requantisation read backwards. | 1042 | /// The spectrum as integers, per the decoder's requantisation read backwards. |
| @@ -858,6 +1048,22 @@ fn quantise( | |||
| 858 | block_type: u8, | 1048 | block_type: u8, |
| 859 | ix: &mut [i32], | 1049 | ix: &mut [i32], |
| 860 | ) { | 1050 | ) { |
| 1051 | + let quantise_line = |xr: f32, scale: f32| -> i32 { | ||
| 1052 | + let value = (xr.abs() * scale).powf(0.75); | ||
| 1053 | + let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32; | ||
| 1054 | + if xr < 0.0 { -magnitude } else { magnitude } | ||
| 1055 | + }; | ||
| 1056 | + if block_type == 2 { | ||
| 1057 | + // Short blocks: twelve bands, each with its own scalefactor shared by | ||
| 1058 | + // the three windows. Without them the quantiser's noise is flat across | ||
| 1059 | + // the spectrum, which is what made a switched granule the worst-coded | ||
| 1060 | + // one in the stream. | ||
| 1061 | + for (i, slot) in ix.iter_mut().enumerate().take(576) { | ||
| 1062 | + let scale = 1.0 / band_gain(gain, scalefac[short_band(i, sample_rate)], block_type); | ||
| 1063 | + *slot = quantise_line(xr[i], scale); | ||
| 1064 | + } | ||
| 1065 | + return; | ||
| 1066 | + } | ||
| 861 | let starts = long_starts(sample_rate); | 1067 | let starts = long_starts(sample_rate); |
| 862 | // 22 bands, not 21: the topmost band carries no transmitted scalefactor, | 1068 | // 22 bands, not 21: the topmost band carries no transmitted scalefactor, |
| 863 | // but it does carry audio — zeroing it low-passes the encoder at 16 kHz. | 1069 | // but it does carry audio — zeroing it low-passes the encoder at 16 kHz. |
| @@ -869,13 +1075,23 @@ fn quantise( | |||
| 869 | let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 }; | 1075 | let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 }; |
| 870 | let scale = 1.0 / band_gain(gain, scalefac, block_type); | 1076 | let scale = 1.0 / band_gain(gain, scalefac, block_type); |
| 871 | for i in from..to { | 1077 | for i in from..to { |
| 872 | - let value = (xr[i].abs() * scale).powf(0.75); | 1078 | + ix[i] = quantise_line(xr[i], scale); |
| 873 | - let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32; | ||
| 874 | - ix[i] = if xr[i] < 0.0 { -magnitude } else { magnitude }; | ||
| 875 | } | 1079 | } |
| 876 | } | 1080 | } |
| 877 | } | 1081 | } |
| 878 | 1082 | ||
| 1083 | +/// The short scalefactor band a spectral line belongs to. Short-block spectra | ||
| 1084 | +/// interleave the three windows line by line, so the line index divided by | ||
| 1085 | +/// three is the frequency line the band table is indexed by. | ||
| 1086 | +fn short_band(index: usize, sample_rate: u32) -> usize { | ||
| 1087 | + let line = index / 3; | ||
| 1088 | + let starts = short_starts(sample_rate); | ||
| 1089 | + (0..13) | ||
| 1090 | + .rev() | ||
| 1091 | + .find(|&band| line >= usize::from(starts[band])) | ||
| 1092 | + .unwrap_or(0) | ||
| 1093 | +} | ||
| 1094 | + | ||
| 879 | /// Chooses the region split, the tables and the count1 boundary, and writes the | 1095 | /// Chooses the region split, the tables and the count1 boundary, and writes the |
| 880 | /// spectrum. Returns the bit cost first so the rate loop can stop early. | 1096 | /// spectrum. Returns the bit cost first so the rate loop can stop early. |
| 881 | #[allow(clippy::type_complexity)] | 1097 | #[allow(clippy::type_complexity)] |
| @@ -902,24 +1118,37 @@ fn code_spectrum( | |||
| 902 | let big_end = count1_start; | 1118 | let big_end = count1_start; |
| 903 | 1119 | ||
| 904 | let starts = long_starts(sample_rate); | 1120 | let starts = long_starts(sample_rate); |
| 905 | - let short = block_type == 2; | 1121 | + // Region boundaries land on band edges. A granule that switches windows |
| 906 | - // Region boundaries land on band edges. Splitting the big-value region in | 1122 | + // does not transmit `region0_count`/`region1_count` at all — the decoder |
| 907 | - // three roughly equal parts is what makes the three tables specialise; | 1123 | + // derives them (three short bands for a short block, eight long bands |
| 908 | - // searching every legal split costs far more than it saves. | 1124 | + // otherwise, with region 2 empty) — so the encoder has to use exactly |
| 909 | - let (region0, region1, bounds) = if short { | 1125 | + // those, not a split of its own. Choosing differently costs no bits and |
| 910 | - let first = usize::from(short_starts(sample_rate)[3]) * 3; | 1126 | + // parses as different tables, which is a granule of noise wherever the |
| 911 | - (8u32, 12u32, [first.min(big_end), big_end, big_end]) | 1127 | + // window switches. Only a normal block gets to pick. |
| 912 | - } else { | 1128 | + let (region0, region1, bounds) = match block_type { |
| 913 | - let band_at = |target: usize| -> usize { | 1129 | + 2 => { |
| 914 | - (0..21) | 1130 | + let first = usize::from(short_starts(sample_rate)[3]) * 3; |
| 915 | - .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target)) | 1131 | + (8u32, 12u32, [first.min(big_end), big_end, big_end]) |
| 916 | - .unwrap_or(7) | 1132 | + } |
| 917 | - }; | 1133 | + 1 | 3 => { |
| 918 | - let r0 = band_at(big_end / 3).min(15); | 1134 | + let first = usize::from(starts[8]); |
| 919 | - let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7); | 1135 | + (7u32, 13u32, [first.min(big_end), big_end, big_end]) |
| 920 | - let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end); | 1136 | + } |
| 921 | - let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end); | 1137 | + _ => { |
| 922 | - (r0 as u32, r1 as u32, [a, b.max(a), big_end]) | 1138 | + // Splitting the big-value region in three roughly equal parts is |
| 1139 | + // what makes the three tables specialise; searching every legal | ||
| 1140 | + // split costs far more than it saves. | ||
| 1141 | + let band_at = |target: usize| -> usize { | ||
| 1142 | + (0..21) | ||
| 1143 | + .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target)) | ||
| 1144 | + .unwrap_or(7) | ||
| 1145 | + }; | ||
| 1146 | + let r0 = band_at(big_end / 3).min(15); | ||
| 1147 | + let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7); | ||
| 1148 | + let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end); | ||
| 1149 | + let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end); | ||
| 1150 | + (r0 as u32, r1 as u32, [a, b.max(a), big_end]) | ||
| 1151 | + } | ||
| 923 | }; | 1152 | }; |
| 924 | 1153 | ||
| 925 | let mut tables = [0u8; 3]; | 1154 | let mut tables = [0u8; 3]; |
| @@ -1030,17 +1259,26 @@ fn table_cost(ix: &[i32], from: usize, to: usize, table: Table) -> Option<u32> { | |||
| 1030 | } | 1259 | } |
| 1031 | 1260 | ||
| 1032 | /// The `scalefac_compress` index whose two lengths hold these scalefactors. | 1261 | /// The `scalefac_compress` index whose two lengths hold these scalefactors. |
| 1033 | -fn scalefac_compress(scalefac: &[u8; SFB_LONG]) -> (u32, u32, u32) { | 1262 | +fn scalefac_compress(scalefac: &[u8; SFB_LONG], block_type: u8) -> (u32, u32, u32) { |
| 1034 | let bits_for = |slice: &[u8]| -> u32 { | 1263 | let bits_for = |slice: &[u8]| -> u32 { |
| 1035 | let max = slice.iter().copied().max().unwrap_or(0); | 1264 | let max = slice.iter().copied().max().unwrap_or(0); |
| 1036 | (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4) | 1265 | (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4) |
| 1037 | }; | 1266 | }; |
| 1038 | - let need1 = bits_for(&scalefac[..11]); | 1267 | + // Long blocks split their bands 11/10, short blocks 6/6 per window. |
| 1039 | - let need2 = bits_for(&scalefac[11..]); | 1268 | + let (first, second, cost1, cost2) = if block_type == 2 { |
| 1040 | - let mut best = (u32::MAX, 0u32, 0u32, 0u32); | 1269 | + (&scalefac[..6], &scalefac[6..12], 18, 18) |
| 1270 | + } else { | ||
| 1271 | + (&scalefac[..11], &scalefac[11..], 11, 10) | ||
| 1272 | + }; | ||
| 1273 | + // The table's longest pair is (4, 3), so a caller that respects | ||
| 1274 | + // `max_scalefac` always finds an entry; the clamp is what keeps a caller | ||
| 1275 | + // that does not from silently coding a granule the decoder cannot rebuild. | ||
| 1276 | + let need1 = bits_for(first).min(4); | ||
| 1277 | + let need2 = bits_for(second).min(3); | ||
| 1278 | + let mut best = (u32::MAX, 4u32, 3u32, 15u32); | ||
| 1041 | for (index, (slen1, slen2)) in SLEN.iter().enumerate() { | 1279 | for (index, (slen1, slen2)) in SLEN.iter().enumerate() { |
| 1042 | if *slen1 >= need1 && *slen2 >= need2 { | 1280 | if *slen1 >= need1 && *slen2 >= need2 { |
| 1043 | - let cost = slen1 * 11 + slen2 * 10; | 1281 | + let cost = slen1 * cost1 + slen2 * cost2; |
| 1044 | if cost < best.0 { | 1282 | if cost < best.0 { |
| 1045 | best = (cost, *slen1, *slen2, index as u32); | 1283 | best = (cost, *slen1, *slen2, index as u32); |
| 1046 | } | 1284 | } |
| @@ -1053,6 +1291,187 @@ fn scalefac_compress(scalefac: &[u8; SFB_LONG]) -> (u32, u32, u32) { | |||
| 1053 | mod tests { | 1291 | mod tests { |
| 1054 | use super::*; | 1292 | use super::*; |
| 1055 | 1293 | ||
| 1294 | + /// The delay the Info tag states is the delay the pipeline has. Our own | ||
| 1295 | + /// decoder ignores the tag, so what it hands back is the untrimmed stream: | ||
| 1296 | + /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in. | ||
| 1297 | + #[test] | ||
| 1298 | + fn encoder_delay_is_what_the_tag_says() { | ||
| 1299 | + for (rate, channels) in [(44100u32, 1usize), (48000, 2)] { | ||
| 1300 | + let n = 1152 * 8; | ||
| 1301 | + let pcm: Vec<f32> = (0..n * channels) | ||
| 1302 | + .map(|i| { | ||
| 1303 | + let t = (i / channels) as f32; | ||
| 1304 | + 0.3 * (t * 0.11).sin() + 0.2 * (t * 0.7).cos() | ||
| 1305 | + }) | ||
| 1306 | + .collect(); | ||
| 1307 | + let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { | ||
| 1308 | + bitrate_kbps: 320, | ||
| 1309 | + vbr_quality: None, | ||
| 1310 | + }); | ||
| 1311 | + encoder | ||
| 1312 | + .push_pcm_f32(&pcm, channels as u16, rate) | ||
| 1313 | + .expect("encoder accepts this shape"); | ||
| 1314 | + encoder.finish(); | ||
| 1315 | + let mut bytes = Vec::new(); | ||
| 1316 | + while let Ok(frame) = encoder.next_packet() { | ||
| 1317 | + bytes.extend_from_slice(&frame); | ||
| 1318 | + } | ||
| 1319 | + let mut reader = crate::Mp3Reader::new(); | ||
| 1320 | + reader.push(&bytes); | ||
| 1321 | + let mut out: Vec<f32> = Vec::new(); | ||
| 1322 | + for frame in reader.decode_all() { | ||
| 1323 | + out.extend_from_slice(&frame.samples); | ||
| 1324 | + } | ||
| 1325 | + let mut best = (f64::MIN, 0usize); | ||
| 1326 | + let window = 4096 * channels; | ||
| 1327 | + let mut lag = 0; | ||
| 1328 | + while lag + window * 2 < out.len() { | ||
| 1329 | + let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); | ||
| 1330 | + for i in 0..window { | ||
| 1331 | + let (x, y) = (out[lag + window + i] as f64, pcm[window + i] as f64); | ||
| 1332 | + ab += x * y; | ||
| 1333 | + aa += x * x; | ||
| 1334 | + bb += y * y; | ||
| 1335 | + } | ||
| 1336 | + let corr = ab / (aa * bb).sqrt().max(1e-30); | ||
| 1337 | + if corr > best.0 { | ||
| 1338 | + best = (corr, lag / channels); | ||
| 1339 | + } | ||
| 1340 | + lag += channels; | ||
| 1341 | + } | ||
| 1342 | + assert!(best.0 > 0.999, "round trip correlation {:.6}", best.0); | ||
| 1343 | + assert_eq!( | ||
| 1344 | + best.1 as u32, | ||
| 1345 | + ENCODER_DELAY + DECODER_DELAY, | ||
| 1346 | + "measured lag at {rate} Hz, {channels} channels" | ||
| 1347 | + ); | ||
| 1348 | + } | ||
| 1349 | + } | ||
| 1350 | + | ||
| 1351 | + /// The whole window sequence — normal, start, short, stop, normal — has to | ||
| 1352 | + /// reconstruct, not just the long blocks. This runs the transform pair | ||
| 1353 | + /// directly, so a failure points at the windows rather than at the | ||
| 1354 | + /// quantiser. | ||
| 1355 | + #[test] | ||
| 1356 | + fn window_sequence_reconstructs() { | ||
| 1357 | + use crate::filterbank::Imdct; | ||
| 1358 | + let imdct = Imdct::default(); | ||
| 1359 | + let types = [0u8, 0, 1, 2, 3, 0, 0]; | ||
| 1360 | + let signal: Vec<f32> = (0..18 * (types.len() + 2)) | ||
| 1361 | + .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.7).cos()) | ||
| 1362 | + .collect(); | ||
| 1363 | + let mut output = vec![0.0f32; signal.len()]; | ||
| 1364 | + let mut overlap = [0.0f32; 18]; | ||
| 1365 | + for (granule, block_type) in types.iter().enumerate() { | ||
| 1366 | + let mut window = [0.0f32; 36]; | ||
| 1367 | + for (i, slot) in window.iter_mut().enumerate() { | ||
| 1368 | + let index = granule * 18 + i; | ||
| 1369 | + if index < signal.len() { | ||
| 1370 | + *slot = signal[index]; | ||
| 1371 | + } | ||
| 1372 | + } | ||
| 1373 | + let mut spectrum = [0.0f32; 18]; | ||
| 1374 | + if *block_type == 2 { | ||
| 1375 | + mdct_short(&window, &mut spectrum); | ||
| 1376 | + } else { | ||
| 1377 | + mdct_long(&window, *block_type, &mut spectrum); | ||
| 1378 | + } | ||
| 1379 | + let mut block = [0.0f32; 36]; | ||
| 1380 | + if *block_type == 2 { | ||
| 1381 | + imdct.short(&spectrum, &mut block); | ||
| 1382 | + } else { | ||
| 1383 | + imdct.long(&spectrum, *block_type, &mut block); | ||
| 1384 | + } | ||
| 1385 | + for t in 0..18 { | ||
| 1386 | + let index = granule * 18 + t; | ||
| 1387 | + if index < output.len() { | ||
| 1388 | + output[index] = block[t] + overlap[t]; | ||
| 1389 | + } | ||
| 1390 | + } | ||
| 1391 | + overlap.copy_from_slice(&block[18..]); | ||
| 1392 | + } | ||
| 1393 | + // The first granule has no predecessor and the last no successor. | ||
| 1394 | + for (granule, block_type) in types.iter().enumerate().take(types.len() - 1).skip(1) { | ||
| 1395 | + let mut error = 0.0f64; | ||
| 1396 | + let mut energy = 0.0f64; | ||
| 1397 | + for i in granule * 18..(granule + 1) * 18 { | ||
| 1398 | + error += (output[i] - signal[i]).powi(2) as f64; | ||
| 1399 | + energy += (signal[i] * signal[i]) as f64; | ||
| 1400 | + } | ||
| 1401 | + let snr = 10.0 * (energy / error.max(1e-30)).log10(); | ||
| 1402 | + assert!( | ||
| 1403 | + snr > 60.0, | ||
| 1404 | + "granule {granule} (block type {block_type}) reconstructs at {snr:.1} dB" | ||
| 1405 | + ); | ||
| 1406 | + } | ||
| 1407 | + } | ||
| 1408 | + | ||
| 1409 | + /// A granule that switches to short blocks must come back as itself. | ||
| 1410 | + /// | ||
| 1411 | + /// Short blocks are coded band-major with the three windows interleaved on | ||
| 1412 | + /// every line, which is not the order the transform produces them in. Miss | ||
| 1413 | + /// that permutation and the bit count still lands exactly on | ||
| 1414 | + /// `part2_3_length`, every fixture still decodes, and only the switched | ||
| 1415 | + /// granules come back as noise — so this test drives an attack that forces | ||
| 1416 | + /// the switch and checks the granules around it. | ||
| 1417 | + #[test] | ||
| 1418 | + fn switched_granules_reconstruct() { | ||
| 1419 | + let rate = 44100u32; | ||
| 1420 | + let n = 1152 * 12; | ||
| 1421 | + let attack = 1152 * 6; | ||
| 1422 | + let pcm: Vec<f32> = (0..n) | ||
| 1423 | + .map(|i| { | ||
| 1424 | + let t = i as f32; | ||
| 1425 | + let tone = 0.5 * (t * 0.21).sin() + 0.3 * (t * 0.93).cos(); | ||
| 1426 | + // Six frames of near-silence, then full level: an attack no | ||
| 1427 | + // block-switching encoder can ignore. | ||
| 1428 | + if i < attack { tone * 0.002 } else { tone } | ||
| 1429 | + }) | ||
| 1430 | + .collect(); | ||
| 1431 | + let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { | ||
| 1432 | + bitrate_kbps: 320, | ||
| 1433 | + vbr_quality: None, | ||
| 1434 | + }); | ||
| 1435 | + encoder | ||
| 1436 | + .push_pcm_f32(&pcm, 1, rate) | ||
| 1437 | + .expect("encoder accepts this"); | ||
| 1438 | + encoder.finish(); | ||
| 1439 | + let mut bytes = Vec::new(); | ||
| 1440 | + while let Ok(frame) = encoder.next_packet() { | ||
| 1441 | + bytes.extend_from_slice(&frame); | ||
| 1442 | + } | ||
| 1443 | + let mut reader = crate::Mp3Reader::new(); | ||
| 1444 | + reader.push(&bytes); | ||
| 1445 | + let mut out: Vec<f32> = Vec::new(); | ||
| 1446 | + for frame in reader.decode_all() { | ||
| 1447 | + out.extend_from_slice(&frame.samples); | ||
| 1448 | + } | ||
| 1449 | + let lag = (ENCODER_DELAY + DECODER_DELAY) as usize; | ||
| 1450 | + // Every granule from the attack onward, where the switch happens. | ||
| 1451 | + let mut worst = (1.0f64, 0usize); | ||
| 1452 | + let mut granule = attack / 576; | ||
| 1453 | + while (granule + 1) * 576 + lag <= out.len() && (granule + 1) * 576 <= pcm.len() { | ||
| 1454 | + let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); | ||
| 1455 | + for i in granule * 576..(granule + 1) * 576 { | ||
| 1456 | + let (x, y) = (out[i + lag] as f64, pcm[i] as f64); | ||
| 1457 | + ab += x * y; | ||
| 1458 | + aa += x * x; | ||
| 1459 | + bb += y * y; | ||
| 1460 | + } | ||
| 1461 | + let corr = ab / (aa * bb).sqrt().max(1e-30); | ||
| 1462 | + if corr < worst.0 { | ||
| 1463 | + worst = (corr, granule); | ||
| 1464 | + } | ||
| 1465 | + granule += 1; | ||
| 1466 | + } | ||
| 1467 | + assert!( | ||
| 1468 | + worst.0 > 0.99, | ||
| 1469 | + "granule {} reconstructs at {:.4}", | ||
| 1470 | + worst.1, | ||
| 1471 | + worst.0 | ||
| 1472 | + ); | ||
| 1473 | + } | ||
| 1474 | + | ||
| 1056 | #[test] | 1475 | #[test] |
| 1057 | fn bitrates_snap_to_legal_values() { | 1476 | fn bitrates_snap_to_legal_values() { |
| 1058 | assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128); | 1477 | assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128); |
crates/ec-mp3/src/lib.rsmodified+4 -1
| @@ -8,7 +8,10 @@ | |||
| 8 | //! reservoir across frames. | 8 | //! reservoir across frames. |
| 9 | //! - [`Mp3Decoder`], the [`ec_core::Decoder`] contract, for a container that | 9 | //! - [`Mp3Decoder`], the [`ec_core::Decoder`] contract, for a container that |
| 10 | //! hands out one Layer III frame per packet. | 10 | //! hands out one Layer III frame per packet. |
| 11 | -//! - [`Mp3Encoder`]: interleaved PCM in, CBR Layer III frames out. | 11 | +//! - [`Mp3Encoder`]: interleaved PCM in, CBR Layer III frames out, with a |
| 12 | +//! Xing/Info header carrying the encoder delay and padding — so a decoder | ||
| 13 | +//! that honours it hands back exactly the samples that went in, with no | ||
| 14 | +//! leading or trailing silence. | ||
| 12 | //! | 15 | //! |
| 13 | //! **Where the constants came from.** Layer III's Huffman code tables and its | 16 | //! **Where the constants came from.** Layer III's Huffman code tables and its |
| 14 | //! 512-tap polyphase window are normative data no formula produces. Rather | 17 | //! 512-tap polyphase window are normative data no formula produces. Rather |
crates/ec-mp3/tests/encode_matrix.rsmodified+23 -1
| @@ -199,7 +199,29 @@ fn encodes_above_the_incumbent_bar() { | |||
| 199 | .chunks_exact(4) | 199 | .chunks_exact(4) |
| 200 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | 200 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 201 | .collect(); | 201 | .collect(); |
| 202 | - let (corr, _offset) = aligned(&decoded, &pcm, channels); | 202 | + // With the Info tag's delay and padding honoured, ffmpeg hands |
| 203 | + // back exactly the samples that went in: same count, no shift. That | ||
| 204 | + // is the gapless claim, so the correlation is measured at lag zero | ||
| 205 | + // rather than at whatever lag looks best. | ||
| 206 | + if decoded.len() != pcm.len() { | ||
| 207 | + failures.push(format!( | ||
| 208 | + "{}: decoded {} samples, pushed {}", | ||
| 209 | + source.file_name().unwrap().to_string_lossy(), | ||
| 210 | + decoded.len(), | ||
| 211 | + pcm.len() | ||
| 212 | + )); | ||
| 213 | + } | ||
| 214 | + let corr = correlation(&decoded, &pcm); | ||
| 215 | + // A periodic fixture correlates equally well a whole period out, | ||
| 216 | + // so a tie is not a misalignment; only a shift that is genuinely | ||
| 217 | + // better than lag zero is. | ||
| 218 | + let (searched, offset) = aligned(&decoded, &pcm, channels); | ||
| 219 | + if offset != 0 && searched > corr + 1e-4 { | ||
| 220 | + failures.push(format!( | ||
| 221 | + "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}", | ||
| 222 | + source.file_name().unwrap().to_string_lossy(), | ||
| 223 | + )); | ||
| 224 | + } | ||
| 203 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); | 225 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 204 | let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; | 226 | let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 205 | let name = source.file_name().unwrap().to_string_lossy(); | 227 | let name = source.file_name().unwrap().to_string_lossy(); |