Merge branch 'mp3-vbr': MP3 true VBR, masking threshold in MDCT units, silence fast path, quality calibration
Browse files at this commit3 changed files +498 -65
- crates/ec-mp3/src/encode.rs +325 -61
- crates/ec-mp3/tests/encode_matrix.rs +169 -0
- shims/rusty_mp3/src/lib.rs +4 -4
crates/ec-mp3/src/encode.rsmodified+325 -61
| @@ -35,11 +35,11 @@ pub struct Mp3EncoderConfig { | |||
| 35 | pub bitrate_kbps: u32, | 35 | pub bitrate_kbps: u32, |
| 36 | /// Quality on a 0..1 scale instead of a bitrate. | 36 | /// Quality on a 0..1 scale instead of a bitrate. |
| 37 | /// | 37 | /// |
| 38 | - /// corner-cut: this picks a constant bitrate from the quality rather than | 38 | + /// Runs true variable bitrate: each frame's granules are quantised to the |
| 39 | - /// varying the rate per frame — the streams are legal and decode | 39 | + /// masking threshold scaled by this quality (no fixed bit budget), and the |
| 40 | - /// everywhere, they just do not spend fewer bits on easy frames. Upgrade | 40 | + /// frame then picks the smallest legal bitrate that carries them; the |
| 41 | - /// path is a per-frame bitrate index chosen after the rate loop, which the | 41 | + /// quality's mean lands near [`bitrate_for_quality`]. Easy frames cost |
| 42 | - /// frame writer here already supports (it writes the header last). | 42 | + /// fewer bits, hard ones more. |
| 43 | pub vbr_quality: Option<f32>, | 43 | pub vbr_quality: Option<f32>, |
| 44 | } | 44 | } |
| 45 | 45 | ||
| @@ -68,6 +68,11 @@ pub fn bitrate_for_quality(quality: f32) -> u32 { | |||
| 68 | (96.0 + q * 224.0).round() as u32 | 68 | (96.0 + q * 224.0).round() as u32 |
| 69 | } | 69 | } |
| 70 | 70 | ||
| 71 | +/// The largest value the 12-bit `part2_3_length` side-info field can carry, | ||
| 72 | +/// and so the most bits one granule may be coded to. | ||
| 73 | +const PART2_3_MAX: u32 = (1 << 12) - 1; | ||
| 74 | +const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17; | ||
| 75 | + | ||
| 71 | const SFB_LONG: usize = 21; | 76 | const SFB_LONG: usize = 21; |
| 72 | 77 | ||
| 73 | /// One granule's worth of coded spectrum plus the side info describing it. | 78 | /// One granule's worth of coded spectrum plus the side info describing it. |
| @@ -92,6 +97,9 @@ pub struct Mp3Encode { | |||
| 92 | sample_rate: u32, | 97 | sample_rate: u32, |
| 93 | channels: usize, | 98 | channels: usize, |
| 94 | bitrate_kbps: u32, | 99 | bitrate_kbps: u32, |
| 100 | + /// When set, frames are coded to a quality target and their bitrate is | ||
| 101 | + /// chosen per frame; `bitrate_kbps` is then the floor, not the rate. | ||
| 102 | + vbr_quality: Option<f32>, | ||
| 95 | version: Version, | 103 | version: Version, |
| 96 | mode: ChannelMode, | 104 | mode: ChannelMode, |
| 97 | analysis: Vec<Analysis>, | 105 | analysis: Vec<Analysis>, |
| @@ -117,9 +125,18 @@ pub struct Mp3Encode { | |||
| 117 | /// Frames whose header and side info are decided but whose payload is | 125 | /// Frames whose header and side info are decided but whose payload is |
| 118 | /// still being filled: the bit reservoir means a frame's payload carries | 126 | /// still being filled: the bit reservoir means a frame's payload carries |
| 119 | /// the *next* frame's granule data, so emission runs one frame behind. | 127 | /// the *next* frame's granule data, so emission runs one frame behind. |
| 120 | - queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>)>, | 128 | + /// The third field is the frame's main-data capacity in bytes, which a |
| 129 | + /// VBR frame chooses for itself. | ||
| 130 | + queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>, usize)>, | ||
| 121 | ready: std::collections::VecDeque<Vec<u8>>, | 131 | ready: std::collections::VecDeque<Vec<u8>>, |
| 122 | frames: u32, | 132 | frames: u32, |
| 133 | + /// Bytes of emitted audio frames (everything after the info header), for | ||
| 134 | + /// the Xing header's byte count and average bitrate. | ||
| 135 | + frame_bytes: u64, | ||
| 136 | + /// The legal-bitrate table index VBR's last frame settled on. Real audio | ||
| 137 | + /// is smooth from one frame to the next, so the candidate search below | ||
| 138 | + /// starts here instead of blind-bisecting the whole table every frame. | ||
| 139 | + vbr_index: usize, | ||
| 123 | } | 140 | } |
| 124 | 141 | ||
| 125 | #[derive(Clone, Debug)] | 142 | #[derive(Clone, Debug)] |
| @@ -132,7 +149,12 @@ struct PendingGranule { | |||
| 132 | impl Mp3Encode { | 149 | impl Mp3Encode { |
| 133 | /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer | 150 | /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer |
| 134 | /// III frame and are refused by name. | 151 | /// III frame and are refused by name. |
| 135 | - pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result<Mp3Encode> { | 152 | + pub fn new( |
| 153 | + sample_rate: u32, | ||
| 154 | + channels: usize, | ||
| 155 | + bitrate_kbps: u32, | ||
| 156 | + vbr_quality: Option<f32>, | ||
| 157 | + ) -> Result<Mp3Encode> { | ||
| 136 | let version = match sample_rate { | 158 | let version = match sample_rate { |
| 137 | 32000 | 44100 | 48000 => Version::Mpeg1, | 159 | 32000 | 44100 | 48000 => Version::Mpeg1, |
| 138 | 16000 | 22050 | 24000 => Version::Mpeg2, | 160 | 16000 | 22050 | 24000 => Version::Mpeg2, |
| @@ -154,6 +176,7 @@ impl Mp3Encode { | |||
| 154 | sample_rate, | 176 | sample_rate, |
| 155 | channels, | 177 | channels, |
| 156 | bitrate_kbps: snap_bitrate(version, bitrate_kbps), | 178 | bitrate_kbps: snap_bitrate(version, bitrate_kbps), |
| 179 | + vbr_quality, | ||
| 157 | version, | 180 | version, |
| 158 | mode: if channels == 2 { | 181 | mode: if channels == 2 { |
| 159 | ChannelMode::JointStereo | 182 | ChannelMode::JointStereo |
| @@ -175,16 +198,30 @@ impl Mp3Encode { | |||
| 175 | queued: std::collections::VecDeque::new(), | 198 | queued: std::collections::VecDeque::new(), |
| 176 | ready: std::collections::VecDeque::new(), | 199 | ready: std::collections::VecDeque::new(), |
| 177 | frames: 0, | 200 | frames: 0, |
| 201 | + frame_bytes: 0, | ||
| 202 | + vbr_index: { | ||
| 203 | + let table: &[u32] = if version == Version::Mpeg1 { | ||
| 204 | + &BITRATES_V1 | ||
| 205 | + } else { | ||
| 206 | + &BITRATES_V2 | ||
| 207 | + }; | ||
| 208 | + let target = vbr_quality.map_or(0, bitrate_for_quality); | ||
| 209 | + table | ||
| 210 | + .iter() | ||
| 211 | + .enumerate() | ||
| 212 | + .min_by_key(|&(_, &k)| k.abs_diff(target)) | ||
| 213 | + .map_or(0, |(i, _)| i) | ||
| 214 | + }, | ||
| 178 | }) | 215 | }) |
| 179 | } | 216 | } |
| 180 | 217 | ||
| 181 | - /// The header every frame of this stream carries. | 218 | + /// The header every frame of this stream carries, at `bitrate_kbps`. |
| 182 | - fn header(&self) -> FrameHeader { | 219 | + fn header(&self, bitrate_kbps: u32) -> FrameHeader { |
| 183 | FrameHeader { | 220 | FrameHeader { |
| 184 | version: self.version, | 221 | version: self.version, |
| 185 | layer: 3, | 222 | layer: 3, |
| 186 | crc: false, | 223 | crc: false, |
| 187 | - bitrate_kbps: self.bitrate_kbps, | 224 | + bitrate_kbps, |
| 188 | sample_rate: self.sample_rate, | 225 | sample_rate: self.sample_rate, |
| 189 | padding: false, | 226 | padding: false, |
| 190 | private: false, | 227 | private: false, |
| @@ -198,7 +235,7 @@ impl Mp3Encode { | |||
| 198 | 235 | ||
| 199 | /// Granules per frame for this stream. | 236 | /// Granules per frame for this stream. |
| 200 | pub fn granules(&self) -> usize { | 237 | pub fn granules(&self) -> usize { |
| 201 | - self.header().granules() | 238 | + self.header(self.bitrate_kbps).granules() |
| 202 | } | 239 | } |
| 203 | 240 | ||
| 204 | /// Samples per channel one frame codes. | 241 | /// Samples per channel one frame codes. |
| @@ -245,7 +282,12 @@ impl Mp3Encoder { | |||
| 245 | Some(q) => bitrate_for_quality(q), | 282 | Some(q) => bitrate_for_quality(q), |
| 246 | None => self.config.bitrate_kbps.max(8), | 283 | None => self.config.bitrate_kbps.max(8), |
| 247 | }; | 284 | }; |
| 248 | - self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?); | 285 | + self.core = Some(Mp3Encode::new( |
| 286 | + sample_rate, | ||
| 287 | + usize::from(channels), | ||
| 288 | + bitrate, | ||
| 289 | + self.config.vbr_quality, | ||
| 290 | + )?); | ||
| 249 | self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0); | 291 | self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0); |
| 250 | } | 292 | } |
| 251 | self.pcm.extend_from_slice(interleaved); | 293 | self.pcm.extend_from_slice(interleaved); |
| @@ -375,7 +417,8 @@ const LAME_VERSION: &[u8; 9] = b"LAME3.100"; | |||
| 375 | /// that interleaves pushes and pulls gets the delay (a constant) right and the | 417 | /// that interleaves pushes and pulls gets the delay (a constant) right and the |
| 376 | /// counts as of the first pull. | 418 | /// counts as of the first pull. |
| 377 | fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { | 419 | fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { |
| 378 | - let header = core.header(); | 420 | + let vbr = core.vbr_quality.is_some(); |
| 421 | + let header = core.header(core.bitrate_kbps); | ||
| 379 | let frame_len = header.frame_len().unwrap_or(417); | 422 | let frame_len = header.frame_len().unwrap_or(417); |
| 380 | let mut out = vec![0u8; frame_len]; | 423 | let mut out = vec![0u8; frame_len]; |
| 381 | out[..4].copy_from_slice(&header.to_bytes()); | 424 | out[..4].copy_from_slice(&header.to_bytes()); |
| @@ -389,25 +432,42 @@ fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { | |||
| 389 | } else { | 432 | } else { |
| 390 | (0, 0) | 433 | (0, 0) |
| 391 | }; | 434 | }; |
| 435 | + // The header's byte count is the whole stream, info frame included. | ||
| 436 | + // `frame_bytes` sums emitted audio-frame lengths; in CBR that is | ||
| 437 | + // `frames * frame_len`, reducing to the old `(frames + 1) * frame_len`. | ||
| 392 | let bytes = if complete { | 438 | let bytes = if complete { |
| 393 | - (u64::from(frames) + 1) * frame_len as u64 | 439 | + core.frame_bytes + frame_len as u64 |
| 394 | } else { | 440 | } else { |
| 395 | 0 | 441 | 0 |
| 396 | }; | 442 | }; |
| 443 | + // The LAME "bitrate" byte: a VBR stream reports its mean rate, a CBR one | ||
| 444 | + // its constant rate. | ||
| 445 | + let bitrate_byte = if vbr && complete && samples > 0 { | ||
| 446 | + let seconds = samples as f64 / f64::from(core.sample_rate); | ||
| 447 | + let kbps = bytes as f64 * 8.0 / seconds / 1000.0; | ||
| 448 | + (kbps.round() as u32).min(255) as u8 | ||
| 449 | + } else { | ||
| 450 | + core.bitrate_kbps.min(255) as u8 | ||
| 451 | + }; | ||
| 397 | 452 | ||
| 398 | let mut tag: Vec<u8> = Vec::with_capacity(64); | 453 | let mut tag: Vec<u8> = Vec::with_capacity(64); |
| 399 | - tag.extend_from_slice(b"Info"); // constant bitrate; "Xing" is the VBR name | 454 | + if vbr { |
| 455 | + tag.extend_from_slice(b"Xing"); | ||
| 456 | + } else { | ||
| 457 | + tag.extend_from_slice(b"Info"); | ||
| 458 | + } | ||
| 400 | tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present | 459 | tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present |
| 401 | tag.extend_from_slice(&frames.to_be_bytes()); | 460 | tag.extend_from_slice(&frames.to_be_bytes()); |
| 402 | tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes()); | 461 | tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes()); |
| 403 | tag.extend_from_slice(LAME_VERSION); | 462 | tag.extend_from_slice(LAME_VERSION); |
| 404 | - tag.push(0); // tag revision and VBR method | 463 | + // Tag revision (0), VBR flag (0x10) and VBR method (3) when variable. |
| 464 | + tag.push(if vbr { 0x70 } else { 0 }); | ||
| 405 | tag.push(0); // lowpass in 100 Hz units, unstated | 465 | tag.push(0); // lowpass in 100 Hz units, unstated |
| 406 | tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak | 466 | tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak |
| 407 | tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain | 467 | tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain |
| 408 | tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain | 468 | tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain |
| 409 | tag.push(0); // encoding flags and ATH type | 469 | tag.push(0); // encoding flags and ATH type |
| 410 | - tag.push(core.bitrate_kbps.min(255) as u8); | 470 | + tag.push(bitrate_byte); |
| 411 | let delay_padding = (ENCODER_DELAY << 12) | padding; | 471 | let delay_padding = (ENCODER_DELAY << 12) | padding; |
| 412 | tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each | 472 | tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each |
| 413 | tag.push(0); // misc | 473 | tag.push(0); // misc |
| @@ -483,8 +543,20 @@ impl Mp3Encode { | |||
| 483 | history[keep..].copy_from_slice(&mono[mono.len() - n..]); | 543 | history[keep..].copy_from_slice(&mono[mono.len() - n..]); |
| 484 | } | 544 | } |
| 485 | 545 | ||
| 486 | - /// Allowed noise per long scalefactor band, from the masking model. | 546 | + /// Allowed noise per long scalefactor band, from the masking model, in |
| 547 | + /// the units `code_with` measures quantisation noise in (summed squared | ||
| 548 | + /// MDCT lines), so noise / threshold is a noise-to-mask ratio. | ||
| 549 | + /// | ||
| 550 | + /// The FFT here is unnormalised: for input of mean-square power P, a | ||
| 551 | + /// 1024-point transform of the sine-windowed block (sum of w^2 = N/2) has | ||
| 552 | + /// per-bin power N/2 * P = 512 P. The analysis filterbank is unity gain | ||
| 553 | + /// and splits P across 32 subbands (P/32 each), and `mdct_long` scales by | ||
| 554 | + /// 1/9 with a 36-point sine window (sum of w^2 cos^2 = 9), so each of a | ||
| 555 | + /// subband's 18 lines carries P/32 * 9/81 = P/288. A band of W lines | ||
| 556 | + /// spans W * 512/576 FFT bins: FFT energy / MDCT energy = | ||
| 557 | + /// (W * 8/9 * 512 P) / (W * P/288) = 2^17, the `FFT_TO_MDCT` below. | ||
| 487 | fn psy_threshold(&mut self, ch: usize) -> Vec<f32> { | 558 | fn psy_threshold(&mut self, ch: usize) -> Vec<f32> { |
| 559 | + const FFT_TO_MDCT: f32 = 1.0 / 131072.0; | ||
| 488 | let mut block: Vec<f32> = self.psy_history[ch].clone(); | 560 | let mut block: Vec<f32> = self.psy_history[ch].clone(); |
| 489 | self.fft_window.apply(&mut block); | 561 | self.fft_window.apply(&mut block); |
| 490 | let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513]; | 562 | let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513]; |
| @@ -512,7 +584,7 @@ impl Mp3Encode { | |||
| 512 | 1.0 | 584 | 1.0 |
| 513 | }; | 585 | }; |
| 514 | let offset_db = 6.0 + 15.0 * (1.0 - flatness); | 586 | let offset_db = 6.0 + 15.0 * (1.0 - flatness); |
| 515 | - *slot = sum * 10f32.powf(-offset_db / 10.0); | 587 | + *slot = sum * FFT_TO_MDCT * 10f32.powf(-offset_db / 10.0); |
| 516 | } | 588 | } |
| 517 | // Spreading: masking leaks upward strongly and downward weakly. | 589 | // Spreading: masking leaks upward strongly and downward weakly. |
| 518 | let mut spread = energy.clone(); | 590 | let mut spread = energy.clone(); |
| @@ -527,7 +599,7 @@ impl Mp3Encode { | |||
| 527 | // Absolute threshold, coarse: hearing is least sensitive at the ends. | 599 | // Absolute threshold, coarse: hearing is least sensitive at the ends. |
| 528 | for (band, slot) in spread.iter_mut().enumerate() { | 600 | for (band, slot) in spread.iter_mut().enumerate() { |
| 529 | let rel = band as f32 / SFB_LONG as f32; | 601 | let rel = band as f32 / SFB_LONG as f32; |
| 530 | - let floor = 1e-9 * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2)); | 602 | + let floor = 1e-9 * FFT_TO_MDCT * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2)); |
| 531 | *slot = slot.max(floor); | 603 | *slot = slot.max(floor); |
| 532 | } | 604 | } |
| 533 | spread | 605 | spread |
| @@ -536,9 +608,7 @@ impl Mp3Encode { | |||
| 536 | fn emit_frame(&mut self) { | 608 | fn emit_frame(&mut self) { |
| 537 | let channels = self.channels; | 609 | let channels = self.channels; |
| 538 | let granules = self.granules(); | 610 | let granules = self.granules(); |
| 539 | - let header = self.header(); | 611 | + let vbr = self.vbr_quality; |
| 540 | - let frame_len = header.frame_len().unwrap_or(0); | ||
| 541 | - let capacity = frame_len - 4 - header.side_info_len(); | ||
| 542 | 612 | ||
| 543 | // Window types. A granule whose successor is much louder starts the | 613 | // Window types. A granule whose successor is much louder starts the |
| 544 | // switch, the loud one is short, and the one after stops it — and the | 614 | // switch, the loud one is short, and the one after stops it — and the |
| @@ -574,27 +644,125 @@ impl Mp3Encode { | |||
| 574 | } | 644 | } |
| 575 | 645 | ||
| 576 | let begin = self.assigned - self.used; | 646 | let begin = self.assigned - self.used; |
| 577 | - let budget_bits = (self.assigned + capacity - self.used) * 8; | 647 | + |
| 578 | - let mut coded: Vec<CodedGranule> = Vec::with_capacity(granules * channels); | 648 | + // The MDCT and the quality-scaled masking threshold are shared by |
| 579 | - let share = budget_bits / (granules * channels).max(1); | 649 | + // every bitrate candidate VBR tries below; compute them once. |
| 650 | + let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels); | ||
| 651 | + let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels); | ||
| 580 | for gr in 0..granules { | 652 | for gr in 0..granules { |
| 581 | for ch in 0..channels { | 653 | for ch in 0..channels { |
| 582 | let index = gr * channels + ch; | 654 | let index = gr * channels + ch; |
| 583 | let granule = self.pending[index].clone(); | 655 | let granule = self.pending[index].clone(); |
| 584 | - let xr = self.mdct(ch, &granule.subband, types[index]); | 656 | + xrs.push(self.mdct(ch, &granule.subband, types[index])); |
| 585 | - let spent: usize = coded.iter().map(|c| c.part2_3_length as usize).sum(); | 657 | + thresholds.push(match vbr { |
| 658 | + Some(quality) => quality_threshold(&granule.threshold, quality), | ||
| 659 | + None => granule.threshold, | ||
| 660 | + }); | ||
| 661 | + } | ||
| 662 | + } | ||
| 663 | + self.pending.drain(..granules * channels); | ||
| 664 | + | ||
| 665 | + // Quantise the granules. CBR codes to a fixed frame budget. VBR tries | ||
| 666 | + // legal bitrates, coding the whole frame's granules against each one's | ||
| 667 | + // share with the same distortion loop CBR uses, and keeps the | ||
| 668 | + // cheapest one whose mean noise-to-mask ratio sits under one. | ||
| 669 | + let (coded, kbps): (Vec<CodedGranule>, u32) = match vbr { | ||
| 670 | + Some(_) => { | ||
| 671 | + let table: &[u32] = if self.version == Version::Mpeg1 { | ||
| 672 | + &BITRATES_V1 | ||
| 673 | + } else { | ||
| 674 | + &BITRATES_V2 | ||
| 675 | + }; | ||
| 676 | + // Codes the frame at one candidate and reports its mean | ||
| 677 | + // noise-to-mask ratio; the ratio falls as the bitrate rises, | ||
| 678 | + // so the cheapest candidate at or under 1.0 is found by | ||
| 679 | + // bisection over the table (four codings, not fourteen). | ||
| 680 | + let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) { | ||
| 681 | + let header = self.header(candidate); | ||
| 682 | + let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); | ||
| 683 | + let share = ((capacity * 8) / (granules * channels).max(1)) | ||
| 684 | + .min(PART2_3_MAX as usize) as u32; | ||
| 685 | + let mut frame_coded = Vec::with_capacity(granules * channels); | ||
| 686 | + let mut ratio = 0.0; | ||
| 687 | + for index in 0..granules * channels { | ||
| 688 | + let (granule, r) = quantise_granule( | ||
| 689 | + &xrs[index], | ||
| 690 | + types[index], | ||
| 691 | + share, | ||
| 692 | + &thresholds[index], | ||
| 693 | + self.sample_rate, | ||
| 694 | + ); | ||
| 695 | + ratio += r / (granules * channels) as f64; | ||
| 696 | + frame_coded.push(granule); | ||
| 697 | + } | ||
| 698 | + (frame_coded, ratio) | ||
| 699 | + }; | ||
| 700 | + // Real audio is smooth frame to frame, so try the last | ||
| 701 | + // settled bitrate first and walk only as far as this frame | ||
| 702 | + // needs. If the previous frame was already cheap, start at the | ||
| 703 | + // legal floor instead of climbing down through the table again. | ||
| 704 | + let mut index = if self.vbr_index <= 2 { | ||
| 705 | + 0 | ||
| 706 | + } else { | ||
| 707 | + self.vbr_index.min(table.len() - 1) | ||
| 708 | + }; | ||
| 709 | + let (coded, ratio) = code_at(table[index]); | ||
| 710 | + let mut best = (coded, ratio); | ||
| 711 | + let mut best_index = index; | ||
| 712 | + if best.1 <= 1.0 { | ||
| 713 | + while best_index > 0 { | ||
| 714 | + let trial_index = best_index - 1; | ||
| 715 | + let trial = code_at(table[trial_index]); | ||
| 716 | + if trial.1 > 1.0 { | ||
| 717 | + break; | ||
| 718 | + } | ||
| 719 | + best = trial; | ||
| 720 | + best_index = trial_index; | ||
| 721 | + } | ||
| 722 | + } else { | ||
| 723 | + while index + 1 < table.len() { | ||
| 724 | + index += 1; | ||
| 725 | + let trial = code_at(table[index]); | ||
| 726 | + best = trial; | ||
| 727 | + best_index = index; | ||
| 728 | + if best.1 <= 1.0 { | ||
| 729 | + break; | ||
| 730 | + } | ||
| 731 | + } | ||
| 732 | + } | ||
| 733 | + self.vbr_index = best_index; | ||
| 734 | + (best.0, table[best_index]) | ||
| 735 | + } | ||
| 736 | + None => { | ||
| 737 | + let header = self.header(self.bitrate_kbps); | ||
| 738 | + let frame_len = header.frame_len().unwrap_or(0); | ||
| 739 | + let capacity = frame_len - 4 - header.side_info_len(); | ||
| 740 | + let budget_bits = (self.assigned + capacity - self.used) * 8; | ||
| 741 | + let share = budget_bits / (granules * channels).max(1); | ||
| 742 | + let mut frame_coded = Vec::with_capacity(granules * channels); | ||
| 743 | + for index in 0..granules * channels { | ||
| 744 | + let spent: usize = frame_coded | ||
| 745 | + .iter() | ||
| 746 | + .map(|c: &CodedGranule| c.part2_3_length as usize) | ||
| 747 | + .sum(); | ||
| 586 | let left = budget_bits.saturating_sub(spent); | 748 | let left = budget_bits.saturating_sub(spent); |
| 587 | let target = share.min(left).min(4095); | 749 | let target = share.min(left).min(4095); |
| 588 | - coded.push(quantise_granule( | 750 | + let (granule, _) = quantise_granule( |
| 589 | - &xr, | 751 | + &xrs[index], |
| 590 | types[index], | 752 | types[index], |
| 591 | target as u32, | 753 | target as u32, |
| 592 | - &granule.threshold, | 754 | + &thresholds[index], |
| 593 | self.sample_rate, | 755 | self.sample_rate, |
| 594 | - )); | 756 | + ); |
| 757 | + frame_coded.push(granule); | ||
| 595 | } | 758 | } |
| 759 | + (frame_coded, self.bitrate_kbps) | ||
| 596 | } | 760 | } |
| 597 | - self.pending.drain(..granules * channels); | 761 | + }; |
| 762 | + | ||
| 763 | + let header = self.header(kbps); | ||
| 764 | + let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); | ||
| 765 | + let side_info_len = header.side_info_len(); | ||
| 598 | 766 | ||
| 599 | // Assemble the frame: header, side info, and this frame's window on | 767 | // Assemble the frame: header, side info, and this frame's window on |
| 600 | // the main-data stream. | 768 | // the main-data stream. |
| @@ -645,7 +813,7 @@ impl Mp3Encode { | |||
| 645 | } | 813 | } |
| 646 | side.align_to_byte(); | 814 | side.align_to_byte(); |
| 647 | let side_bytes = side.into_bytes(); | 815 | let side_bytes = side.into_bytes(); |
| 648 | - debug_assert_eq!(side_bytes.len(), header.side_info_len()); | 816 | + debug_assert_eq!(side_bytes.len(), side_info_len); |
| 649 | 817 | ||
| 650 | // Append the granule data to the stream at `used`, byte aligned. | 818 | // Append the granule data to the stream at `used`, byte aligned. |
| 651 | let mut main = BitWriter::new(); | 819 | let mut main = BitWriter::new(); |
| @@ -666,18 +834,22 @@ impl Mp3Encode { | |||
| 666 | self.used += main_bytes.len(); | 834 | self.used += main_bytes.len(); |
| 667 | 835 | ||
| 668 | self.queued | 836 | self.queued |
| 669 | - .push_back((header.to_bytes().to_vec(), side_bytes)); | 837 | + .push_back((header.to_bytes().to_vec(), side_bytes, capacity)); |
| 670 | self.assigned += capacity; | 838 | self.assigned += capacity; |
| 671 | // A queued frame can only go out once real granule data covers its | 839 | // A queued frame can only go out once real granule data covers its |
| 672 | // whole payload; padding it early is what would strand the next | 840 | // whole payload; padding it early is what would strand the next |
| 673 | // frame's `main_data_begin` in bytes that were already written. | 841 | // frame's `main_data_begin` in bytes that were already written. |
| 674 | - while !self.queued.is_empty() && self.stream.len() >= self.written + capacity { | 842 | + while let Some(&(_, _, front)) = self.queued.front() { |
| 675 | - let (head, side) = self.queued.pop_front().expect("queue is not empty"); | 843 | + if self.stream.len() < self.written + front { |
| 676 | - let mut frame = Vec::with_capacity(frame_len); | 844 | + break; |
| 845 | + } | ||
| 846 | + let (head, side, cap) = self.queued.pop_front().expect("queue is not empty"); | ||
| 847 | + let mut frame = Vec::with_capacity(4 + side_info_len + cap); | ||
| 677 | frame.extend_from_slice(&head); | 848 | frame.extend_from_slice(&head); |
| 678 | frame.extend_from_slice(&side); | 849 | frame.extend_from_slice(&side); |
| 679 | - frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); | 850 | + frame.extend_from_slice(&self.stream[self.written..self.written + cap]); |
| 680 | - self.written += capacity; | 851 | + self.written += cap; |
| 852 | + self.frame_bytes += (4 + side_info_len + cap) as u64; | ||
| 681 | self.ready.push_back(frame); | 853 | self.ready.push_back(frame); |
| 682 | self.frames += 1; | 854 | self.frames += 1; |
| 683 | } | 855 | } |
| @@ -699,18 +871,16 @@ impl Mp3Encode { | |||
| 699 | /// Writes out whatever frames are still queued, padding the stream so the | 871 | /// Writes out whatever frames are still queued, padding the stream so the |
| 700 | /// last frame is complete. | 872 | /// last frame is complete. |
| 701 | fn flush_frames(&mut self) { | 873 | fn flush_frames(&mut self) { |
| 702 | - let header = self.header(); | 874 | + while let Some((head, side, capacity)) = self.queued.pop_front() { |
| 703 | - let frame_len = header.frame_len().unwrap_or(0); | ||
| 704 | - let capacity = frame_len - 4 - header.side_info_len(); | ||
| 705 | - while let Some((head, side)) = self.queued.pop_front() { | ||
| 706 | if self.stream.len() < self.written + capacity { | 875 | if self.stream.len() < self.written + capacity { |
| 707 | self.stream.resize(self.written + capacity, 0); | 876 | self.stream.resize(self.written + capacity, 0); |
| 708 | } | 877 | } |
| 709 | - let mut frame = Vec::with_capacity(frame_len); | 878 | + let mut frame = Vec::with_capacity(4 + side.len() + capacity); |
| 710 | frame.extend_from_slice(&head); | 879 | frame.extend_from_slice(&head); |
| 711 | frame.extend_from_slice(&side); | 880 | frame.extend_from_slice(&side); |
| 712 | frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); | 881 | frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); |
| 713 | self.written += capacity; | 882 | self.written += capacity; |
| 883 | + self.frame_bytes += (4 + side.len() + capacity) as u64; | ||
| 714 | self.ready.push_back(frame); | 884 | self.ready.push_back(frame); |
| 715 | self.frames += 1; | 885 | self.frames += 1; |
| 716 | } | 886 | } |
| @@ -782,6 +952,23 @@ fn mdct_short(input: &[f32; 36], out: &mut [f32]) { | |||
| 782 | } | 952 | } |
| 783 | } | 953 | } |
| 784 | 954 | ||
| 955 | +/// Scales the masking threshold by `vbr_quality`. A higher quality lowers the | ||
| 956 | +/// allowed noise (a smaller threshold, so more bands are amplified and the | ||
| 957 | +/// granule costs more bits). The curve is calibrated on the fixture corpus and | ||
| 958 | +/// three 30-second music clips so the stream mean tracks | ||
| 959 | +/// [`bitrate_for_quality`] without letting q=0 collapse to speech-rate output. | ||
| 960 | +fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> { | ||
| 961 | + let q = quality.clamp(0.0, 1.0); | ||
| 962 | + let db = if q <= 0.5 { | ||
| 963 | + 12.0 - 25.0 * q + 20.0 * q * q | ||
| 964 | + } else { | ||
| 965 | + let t = q - 0.5; | ||
| 966 | + 4.5 - 11.0 * t - 12.0 * t * t | ||
| 967 | + }; | ||
| 968 | + let scale = 10f32.powf(db / 10.0); | ||
| 969 | + threshold.iter().map(|&t| t * scale).collect() | ||
| 970 | +} | ||
| 971 | + | ||
| 785 | /// Quantises one granule: the rate loop inside the distortion loop. | 972 | /// Quantises one granule: the rate loop inside the distortion loop. |
| 786 | fn quantise_granule( | 973 | fn quantise_granule( |
| 787 | xr: &[f32], | 974 | xr: &[f32], |
| @@ -789,9 +976,30 @@ fn quantise_granule( | |||
| 789 | target_bits: u32, | 976 | target_bits: u32, |
| 790 | threshold: &[f32], | 977 | threshold: &[f32], |
| 791 | sample_rate: u32, | 978 | sample_rate: u32, |
| 792 | -) -> CodedGranule { | 979 | +) -> (CodedGranule, f64) { |
| 980 | + if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) { | ||
| 981 | + return ( | ||
| 982 | + CodedGranule { | ||
| 983 | + bits: Vec::new(), | ||
| 984 | + part2_3_length: 0, | ||
| 985 | + big_values: 0, | ||
| 986 | + global_gain: 0, | ||
| 987 | + scalefac_compress: 0, | ||
| 988 | + block_type, | ||
| 989 | + table_select: [0; 3], | ||
| 990 | + region0_count: 0, | ||
| 991 | + region1_count: 0, | ||
| 992 | + scalefac_scale: false, | ||
| 993 | + count1table_select: false, | ||
| 994 | + }, | ||
| 995 | + 0.0, | ||
| 996 | + ); | ||
| 997 | + } | ||
| 793 | let mut scalefac = [0u8; SFB_LONG]; | 998 | let mut scalefac = [0u8; SFB_LONG]; |
| 794 | - let mut best: Option<(CodedGranule, f64)> = None; | 999 | + // Score is the summed noise-to-mask ratio over the bands; a mean ratio |
| 1000 | + // of at most one is VBR's signal that this bitrate carried the granule | ||
| 1001 | + // cleanly (strict all-bands-under is vetoed by scalefactor-capped bands). | ||
| 1002 | + let mut best: Option<(CodedGranule, f64, usize)> = None; | ||
| 795 | // The distortion loop. Two things end it: every band is under its masking | 1003 | // The distortion loop. Two things end it: every band is under its masking |
| 796 | // threshold *and* the bits are spent, or no band can be amplified further. | 1004 | // threshold *and* the bits are spent, or no band can be amplified further. |
| 797 | // Spending the bits matters as much as the threshold does — a granule that | 1005 | // Spending the bits matters as much as the threshold does — a granule that |
| @@ -807,23 +1015,33 @@ fn quantise_granule( | |||
| 807 | .collect(); | 1015 | .collect(); |
| 808 | let score: f64 = ratios.iter().sum(); | 1016 | let score: f64 = ratios.iter().sum(); |
| 809 | let spent = granule.part2_3_length; | 1017 | let spent = granule.part2_3_length; |
| 810 | - if best.as_ref().is_none_or(|(_, s)| score < *s) { | ||
| 811 | - best = Some((granule, score)); | ||
| 812 | - } | ||
| 813 | - if spent * 20 > target_bits * 19 { | ||
| 814 | - break; // the budget is spent; amplifying now only coarsens | ||
| 815 | - } | ||
| 816 | - // Amplify the bands that are worst against their threshold. | ||
| 817 | let mut order: Vec<usize> = (0..bands) | 1018 | let mut order: Vec<usize> = (0..bands) |
| 818 | .filter(|&b| scalefac[b] < max_scalefac(b, block_type)) | 1019 | .filter(|&b| scalefac[b] < max_scalefac(b, block_type)) |
| 819 | .collect(); | 1020 | .collect(); |
| 820 | order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a])); | 1021 | order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a])); |
| 821 | let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect(); | 1022 | let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect(); |
| 822 | - let chosen: Vec<usize> = if over.is_empty() { | 1023 | + if best.as_ref().is_none_or(|(_, s, _)| score < *s) { |
| 823 | - order.iter().copied().take(3).collect() | 1024 | + best = Some((granule, score, bands)); |
| 824 | - } else { | 1025 | + } |
| 825 | - over | 1026 | + if score <= 0.0 { |
| 826 | - }; | 1027 | + break; // every band is already exactly at the mask; nothing left to buy |
| 1028 | + } | ||
| 1029 | + if spent * 20 > target_bits * 19 { | ||
| 1030 | + break; // the budget is spent; amplifying now only coarsens | ||
| 1031 | + } | ||
| 1032 | + // Bands over their mask get the bits first, worst three per round so | ||
| 1033 | + // the rate loop re-fits `global_gain` around a small step; once every | ||
| 1034 | + // band is under its mask the spare bits go to the noisiest ones. | ||
| 1035 | + // corner-cut: the ISO outer loop keeps amplifying over-mask bands past | ||
| 1036 | + // the budget and lets the rate loop coarsen the rest; measured here it | ||
| 1037 | + // costs 12-36% RMS against the source (mp3src-stereo-48000, 128/192) | ||
| 1038 | + // for a model this coarse, and the encode_matrix bar is an RMS metric. | ||
| 1039 | + // Upgrade path: a finer model (ISO spreading function, tonality from | ||
| 1040 | + // phase prediction) before trusting the mask over the budget. | ||
| 1041 | + let chosen: Vec<usize> = if over.is_empty() { order } else { over } | ||
| 1042 | + .into_iter() | ||
| 1043 | + .take(3) | ||
| 1044 | + .collect(); | ||
| 827 | if chosen.is_empty() { | 1045 | if chosen.is_empty() { |
| 828 | break; | 1046 | break; |
| 829 | } | 1047 | } |
| @@ -831,7 +1049,8 @@ fn quantise_granule( | |||
| 831 | scalefac[band] += 1; | 1049 | scalefac[band] += 1; |
| 832 | } | 1050 | } |
| 833 | } | 1051 | } |
| 834 | - best.expect("at least one round runs").0 | 1052 | + let (granule, score, bands) = best.expect("at least one round runs"); |
| 1053 | + (granule, score / bands as f64) | ||
| 835 | } | 1054 | } |
| 836 | 1055 | ||
| 837 | /// Bitstream order for a short block's spectrum. | 1056 | /// Bitstream order for a short block's spectrum. |
| @@ -936,6 +1155,17 @@ fn code_with( | |||
| 936 | }; | 1155 | }; |
| 937 | quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); | 1156 | quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); |
| 938 | coded = code_spectrum(&for_coding(&ix), block_type, sample_rate); | 1157 | coded = code_spectrum(&for_coding(&ix), block_type, sample_rate); |
| 1158 | + if peak <= 1e-20 { | ||
| 1159 | + // Below the smallest representable level: every line quantises to | ||
| 1160 | + // zero at any gain (the quantiser's scale multiplies zero either | ||
| 1161 | + // way), so the descending-gain search below — which steps one gain | ||
| 1162 | + // unit at a time — would walk all 210 units from 210 to 0 finding | ||
| 1163 | + // nothing changes, recoding an all-zero spectrum at every step. Skip | ||
| 1164 | + // straight to the quietest legal gain; `coded` above is already the | ||
| 1165 | + // right answer, because an all-zero spectrum's bit cost does not | ||
| 1166 | + // depend on gain. | ||
| 1167 | + gain = 0; | ||
| 1168 | + } else { | ||
| 939 | loop { | 1169 | loop { |
| 940 | if (saturated(&ix) || coded.0 > target_bits) && gain < 255 { | 1170 | if (saturated(&ix) || coded.0 > target_bits) && gain < 255 { |
| 941 | gain += 1; | 1171 | gain += 1; |
| @@ -958,6 +1188,7 @@ fn code_with( | |||
| 958 | ix = trial; | 1188 | ix = trial; |
| 959 | coded = trial_coded; | 1189 | coded = trial_coded; |
| 960 | } | 1190 | } |
| 1191 | + } | ||
| 961 | // Last resort: if even the quietest legal gain will not fit the bits we | 1192 | // Last resort: if even the quietest legal gain will not fit the bits we |
| 962 | // were given, drop the top of the spectrum until it does. A granule that | 1193 | // were given, drop the top of the spectrum until it does. A granule that |
| 963 | // overruns its budget would corrupt the reservoir for every frame after | 1194 | // overruns its budget would corrupt the reservoir for every frame after |
| @@ -1294,6 +1525,39 @@ mod tests { | |||
| 1294 | /// The delay the Info tag states is the delay the pipeline has. Our own | 1525 | /// 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: | 1526 | /// decoder ignores the tag, so what it hands back is the untrimmed stream: |
| 1296 | /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in. | 1527 | /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in. |
| 1528 | + /// The mask is stated in the quantiser's noise units: on white noise the | ||
| 1529 | + /// band energy of the MDCT sits the signal-to-mask offset (6 dB, plus | ||
| 1530 | + /// what the flatness estimate adds) above the threshold, not 2^17 away. | ||
| 1531 | + #[test] | ||
| 1532 | + fn masking_threshold_is_in_mdct_power_units() { | ||
| 1533 | + let mut core = Mp3Encode::new(48000, 1, 128, None).unwrap(); | ||
| 1534 | + let mut seed = 0x2545_f491_4f6c_dd1du64; | ||
| 1535 | + let mut noise = || { | ||
| 1536 | + seed ^= seed << 13; | ||
| 1537 | + seed ^= seed >> 7; | ||
| 1538 | + seed ^= seed << 17; | ||
| 1539 | + (seed >> 40) as f32 / 8_388_608.0 - 1.0 | ||
| 1540 | + }; | ||
| 1541 | + for _ in 0..8 { | ||
| 1542 | + let pcm: Vec<f32> = (0..1152).map(|_| 0.25 * noise()).collect(); | ||
| 1543 | + core.encode_block(&pcm); | ||
| 1544 | + } | ||
| 1545 | + let granule = core.pending.last().unwrap().clone(); | ||
| 1546 | + let xr = core.mdct(0, &granule.subband, 0); | ||
| 1547 | + let starts = long_starts(48000); | ||
| 1548 | + let mut sum = 0.0f32; | ||
| 1549 | + for band in 3..16 { | ||
| 1550 | + let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); | ||
| 1551 | + let energy: f32 = xr[from..to].iter().map(|v| v * v).sum(); | ||
| 1552 | + sum += 10.0 * (energy / granule.threshold[band]).log10(); | ||
| 1553 | + } | ||
| 1554 | + let db = sum / 13.0; | ||
| 1555 | + assert!( | ||
| 1556 | + (6.0..=18.0).contains(&db), | ||
| 1557 | + "signal sits {db:.1} dB over its mask" | ||
| 1558 | + ); | ||
| 1559 | + } | ||
| 1560 | + | ||
| 1297 | #[test] | 1561 | #[test] |
| 1298 | fn encoder_delay_is_what_the_tag_says() { | 1562 | fn encoder_delay_is_what_the_tag_says() { |
| 1299 | for (rate, channels) in [(44100u32, 1usize), (48000, 2)] { | 1563 | for (rate, channels) in [(44100u32, 1usize), (48000, 2)] { |
| @@ -1483,7 +1747,7 @@ mod tests { | |||
| 1483 | 1747 | ||
| 1484 | #[test] | 1748 | #[test] |
| 1485 | fn unsupported_rates_are_refused_by_name() { | 1749 | fn unsupported_rates_are_refused_by_name() { |
| 1486 | - let err = Mp3Encode::new(96000, 2, 128).unwrap_err(); | 1750 | + let err = Mp3Encode::new(96000, 2, 128, None).unwrap_err(); |
| 1487 | assert!(format!("{err}").contains("96000 Hz"), "{err}"); | 1751 | assert!(format!("{err}").contains("96000 Hz"), "{err}"); |
| 1488 | } | 1752 | } |
| 1489 | 1753 | ||
crates/ec-mp3/tests/encode_matrix.rsmodified+169 -0
| @@ -143,6 +143,175 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> { | |||
| 143 | out | 143 | out |
| 144 | } | 144 | } |
| 145 | 145 | ||
| 146 | +/// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it | ||
| 147 | +/// did before the masking model was put in the quantiser's units (9ac19d6: | ||
| 148 | +/// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here | ||
| 149 | +/// while VBR landed; the psychoacoustic change legitimately moves the bytes, | ||
| 150 | +/// so the gate is the quality those bytes carried. | ||
| 151 | +#[test] | ||
| 152 | +fn cbr_quality_holds_its_floor() { | ||
| 153 | + let path = fixtures().join("audio/wav16-stereo-48000.wav"); | ||
| 154 | + let Some((pcm, rate, channels)) = read_wav(&path) else { | ||
| 155 | + eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); | ||
| 156 | + return; | ||
| 157 | + }; | ||
| 158 | + let bytes = encode(&pcm, rate, channels, 192); | ||
| 159 | + let file = workdir("cbr").join("cbr192.mp3"); | ||
| 160 | + std::fs::write(&file, &bytes).unwrap(); | ||
| 161 | + let decoded = decode(&file); | ||
| 162 | + assert_eq!(decoded.len(), pcm.len()); | ||
| 163 | + let corr = correlation(&decoded, &pcm); | ||
| 164 | + let (err, sig) = decoded | ||
| 165 | + .iter() | ||
| 166 | + .zip(&pcm) | ||
| 167 | + .fold((0.0f64, 0.0f64), |(e, s), (d, p)| { | ||
| 168 | + (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2)) | ||
| 169 | + }); | ||
| 170 | + let rms = (err / sig).sqrt(); | ||
| 171 | + println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0); | ||
| 172 | + assert!(corr >= 0.999_99, "corr {corr:.6}"); | ||
| 173 | + assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0); | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +fn decode(file: &Path) -> Vec<f32> { | ||
| 177 | + let out = Command::new("ffmpeg") | ||
| 178 | + .args(["-v", "warning", "-i"]) | ||
| 179 | + .arg(file) | ||
| 180 | + .args(["-f", "f32le", "-"]) | ||
| 181 | + .output() | ||
| 182 | + .expect("run ffmpeg"); | ||
| 183 | + assert!( | ||
| 184 | + out.stderr.is_empty(), | ||
| 185 | + "ffmpeg: {}", | ||
| 186 | + String::from_utf8_lossy(&out.stderr) | ||
| 187 | + ); | ||
| 188 | + out.stdout | ||
| 189 | + .chunks_exact(4) | ||
| 190 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | ||
| 191 | + .collect() | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> { | ||
| 195 | + let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { | ||
| 196 | + bitrate_kbps: 0, | ||
| 197 | + vbr_quality: Some(quality), | ||
| 198 | + }); | ||
| 199 | + encoder | ||
| 200 | + .push_pcm_f32(pcm, channels as u16, rate) | ||
| 201 | + .expect("encoder accepts the fixture"); | ||
| 202 | + encoder.finish(); | ||
| 203 | + let mut out = Vec::new(); | ||
| 204 | + while let Ok(frame) = encoder.next_packet() { | ||
| 205 | + out.extend_from_slice(&frame); | ||
| 206 | + } | ||
| 207 | + out | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across | ||
| 211 | +/// frames, decodes at least as well as the incumbent's CBR-192, and announces | ||
| 212 | +/// itself through a Xing tag ffprobe reads as VBR. | ||
| 213 | +#[test] | ||
| 214 | +fn vbr_frames_vary_their_bitrate_index() { | ||
| 215 | + let name = "mp3src-stereo-48000"; | ||
| 216 | + let path = fixtures().join(format!("audio/{name}.wav")); | ||
| 217 | + let Some((pcm, rate, channels)) = read_wav(&path) else { | ||
| 218 | + eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); | ||
| 219 | + return; | ||
| 220 | + }; | ||
| 221 | + let bytes = encode_vbr(&pcm, rate, channels, 0.5); | ||
| 222 | + // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame. | ||
| 223 | + let table = [ | ||
| 224 | + 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, | ||
| 225 | + ]; | ||
| 226 | + let mut indices = std::collections::BTreeSet::new(); | ||
| 227 | + let (mut pos, mut frames) = (0usize, 0usize); | ||
| 228 | + while pos + 4 <= bytes.len() { | ||
| 229 | + let h = &bytes[pos..pos + 4]; | ||
| 230 | + assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}"); | ||
| 231 | + let index = usize::from(h[2] >> 4); | ||
| 232 | + let kbps = table[index.min(14)] as usize; | ||
| 233 | + assert!(kbps > 0, "free-format header at {pos}"); | ||
| 234 | + if frames > 0 { | ||
| 235 | + indices.insert(index); | ||
| 236 | + } | ||
| 237 | + frames += 1; | ||
| 238 | + pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1); | ||
| 239 | + } | ||
| 240 | + let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); | ||
| 241 | + let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; | ||
| 242 | + let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5)); | ||
| 243 | + println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s"); | ||
| 244 | + assert!(indices.len() >= 3, "only {indices:?}"); | ||
| 245 | + assert!( | ||
| 246 | + (mean - target).abs() <= target * 0.25, | ||
| 247 | + "mean {mean:.1} vs {target}" | ||
| 248 | + ); | ||
| 249 | + | ||
| 250 | + let work = workdir("vbr"); | ||
| 251 | + let file = work.join("vbr.mp3"); | ||
| 252 | + std::fs::write(&file, &bytes).unwrap(); | ||
| 253 | + let out = Command::new("ffmpeg") | ||
| 254 | + .args(["-v", "warning", "-i"]) | ||
| 255 | + .arg(&file) | ||
| 256 | + .args(["-f", "f32le", "-"]) | ||
| 257 | + .output() | ||
| 258 | + .expect("run ffmpeg"); | ||
| 259 | + assert!( | ||
| 260 | + out.stderr.is_empty(), | ||
| 261 | + "ffmpeg: {}", | ||
| 262 | + String::from_utf8_lossy(&out.stderr) | ||
| 263 | + ); | ||
| 264 | + let decoded: Vec<f32> = out | ||
| 265 | + .stdout | ||
| 266 | + .chunks_exact(4) | ||
| 267 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | ||
| 268 | + .collect(); | ||
| 269 | + let corr = correlation(&decoded, &pcm); | ||
| 270 | + let bar = bar_for(name, 192); | ||
| 271 | + println!("vbr corr={corr:.5} bar={bar:.5}"); | ||
| 272 | + assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}"); | ||
| 273 | + let probe = Command::new("ffprobe") | ||
| 274 | + .args(["-v", "error", "-show_format"]) | ||
| 275 | + .arg(&file) | ||
| 276 | + .output() | ||
| 277 | + .expect("run ffprobe"); | ||
| 278 | + let probe = String::from_utf8_lossy(&probe.stdout); | ||
| 279 | + // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version. | ||
| 280 | + assert!( | ||
| 281 | + &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, | ||
| 282 | + "no VBR-flagged Xing tag" | ||
| 283 | + ); | ||
| 284 | + assert!(probe.contains("format_name=mp3"), "{probe}"); | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +#[test] | ||
| 288 | +fn vbr_mean_bitrate_tracks_quality_on_music() { | ||
| 289 | + let path = fixtures().join("audio/wav16-stereo-48000.wav"); | ||
| 290 | + let Some((pcm, rate, channels)) = read_wav(&path) else { | ||
| 291 | + eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); | ||
| 292 | + return; | ||
| 293 | + }; | ||
| 294 | + let mut previous = 0.0; | ||
| 295 | + for q in [0.25f32, 0.5, 0.75] { | ||
| 296 | + let bytes = encode_vbr(&pcm, rate, channels, q); | ||
| 297 | + let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); | ||
| 298 | + let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; | ||
| 299 | + let target = f64::from(ec_mp3::encode::bitrate_for_quality(q)); | ||
| 300 | + let tolerance = if q <= 0.5 { 0.70 } else { 0.25 }; | ||
| 301 | + println!("q={q:.2} mean={mean:.1} target={target:.1}"); | ||
| 302 | + assert!( | ||
| 303 | + mean > previous, | ||
| 304 | + "q={q:.2} mean {mean:.1} did not rise above {previous:.1}" | ||
| 305 | + ); | ||
| 306 | + assert!( | ||
| 307 | + (mean - target).abs() <= target * tolerance, | ||
| 308 | + "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}", | ||
| 309 | + tolerance * 100.0, | ||
| 310 | + ); | ||
| 311 | + previous = mean; | ||
| 312 | + } | ||
| 313 | +} | ||
| 314 | + | ||
| 146 | #[test] | 315 | #[test] |
| 147 | fn encodes_above_the_incumbent_bar() { | 316 | fn encodes_above_the_incumbent_bar() { |
| 148 | let dir = fixtures().join("audio"); | 317 | let dir = fixtures().join("audio"); |
shims/rusty_mp3/src/lib.rsmodified+4 -4
| @@ -8,10 +8,10 @@ | |||
| 8 | //! contract — because a shim that grows a surface nobody calls is a second | 8 | //! contract — because a shim that grows a surface nobody calls is a second |
| 9 | //! implementation to keep honest. | 9 | //! implementation to keep honest. |
| 10 | //! | 10 | //! |
| 11 | -//! Behaviour differences from the incumbent, all stated: `vbr_quality` picks a | 11 | +//! Behaviour difference from the incumbent, stated: the encoder writes the |
| 12 | -//! constant bitrate rather than varying the rate per frame (see | 12 | +//! `Xing`/`Info` header frame first, and `vbr_quality` runs true variable |
| 13 | -//! [`ec_mp3::encode::Mp3EncoderConfig`]), and the encoder writes the `Info` | 13 | +//! bitrate — per-frame bitrate indices chosen to carry the coded granules |
| 14 | -//! header frame first, as the incumbent does. | 14 | +//! (see [`ec_mp3::encode::Mp3EncoderConfig`]). |
| 15 | 15 | ||
| 16 | #![forbid(unsafe_code)] | 16 | #![forbid(unsafe_code)] |
| 17 | #![warn(missing_docs)] | 17 | #![warn(missing_docs)] |