True VBR — per-frame bitrate index chosen by mean noise-to-mask ratio
Browse files at this commit252530f0a7f54f4f49678159f7ed695c0c922e08Parent: b966d5e- feat
- true VBR — per-frame bitrate index chosen by mean noise-to-mask ratio
3 changed files +298 -61
- crates/ec-mp3/src/encode.rs +191 -57
- crates/ec-mp3/tests/encode_matrix.rs +103 -0
- shims/rusty_mp3/src/lib.rs +4 -4
crates/ec-mp3/src/encode.rsmodified+191 -57
| @@ -35,11 +35,11 @@ pub struct Mp3EncoderConfig { | ||
| 35 | 35 | pub bitrate_kbps: u32, |
| 36 | 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 | |
| 39 | - /// varying the rate per frame — the streams are legal and decode | |
| 40 | - /// everywhere, they just do not spend fewer bits on easy frames. Upgrade | |
| 41 | - /// path is a per-frame bitrate index chosen after the rate loop, which the | |
| 42 | - /// frame writer here already supports (it writes the header last). | |
| 38 | + /// Runs true variable bitrate: each frame's granules are quantised to the | |
| 39 | + /// masking threshold scaled by this quality (no fixed bit budget), and the | |
| 40 | + /// frame then picks the smallest legal bitrate that carries them; the | |
| 41 | + /// quality's mean lands near [`bitrate_for_quality`]. Easy frames cost | |
| 42 | + /// fewer bits, hard ones more. | |
| 43 | 43 | pub vbr_quality: Option<f32>, |
| 44 | 44 | } |
| 45 | 45 | |
| @@ -68,6 +68,9 @@ pub fn bitrate_for_quality(quality: f32) -> u32 { | ||
| 68 | 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; | |
| 71 | 74 | const SFB_LONG: usize = 21; |
| 72 | 75 | |
| 73 | 76 | /// One granule's worth of coded spectrum plus the side info describing it. |
| @@ -92,6 +95,9 @@ pub struct Mp3Encode { | ||
| 92 | 95 | sample_rate: u32, |
| 93 | 96 | channels: usize, |
| 94 | 97 | bitrate_kbps: u32, |
| 98 | + /// When set, frames are coded to a quality target and their bitrate is | |
| 99 | + /// chosen per frame; `bitrate_kbps` is then the floor, not the rate. | |
| 100 | + vbr_quality: Option<f32>, | |
| 95 | 101 | version: Version, |
| 96 | 102 | mode: ChannelMode, |
| 97 | 103 | analysis: Vec<Analysis>, |
| @@ -117,9 +123,14 @@ pub struct Mp3Encode { | ||
| 117 | 123 | /// Frames whose header and side info are decided but whose payload is |
| 118 | 124 | /// still being filled: the bit reservoir means a frame's payload carries |
| 119 | 125 | /// the *next* frame's granule data, so emission runs one frame behind. |
| 120 | - queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>)>, | |
| 126 | + /// The third field is the frame's main-data capacity in bytes, which a | |
| 127 | + /// VBR frame chooses for itself. | |
| 128 | + queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>, usize)>, | |
| 121 | 129 | ready: std::collections::VecDeque<Vec<u8>>, |
| 122 | 130 | frames: u32, |
| 131 | + /// Bytes of emitted audio frames (everything after the info header), for | |
| 132 | + /// the Xing header's byte count and average bitrate. | |
| 133 | + frame_bytes: u64, | |
| 123 | 134 | } |
| 124 | 135 | |
| 125 | 136 | #[derive(Clone, Debug)] |
| @@ -132,7 +143,12 @@ struct PendingGranule { | ||
| 132 | 143 | impl Mp3Encode { |
| 133 | 144 | /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer |
| 134 | 145 | /// III frame and are refused by name. |
| 135 | - pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result<Mp3Encode> { | |
| 146 | + pub fn new( | |
| 147 | + sample_rate: u32, | |
| 148 | + channels: usize, | |
| 149 | + bitrate_kbps: u32, | |
| 150 | + vbr_quality: Option<f32>, | |
| 151 | + ) -> Result<Mp3Encode> { | |
| 136 | 152 | let version = match sample_rate { |
| 137 | 153 | 32000 | 44100 | 48000 => Version::Mpeg1, |
| 138 | 154 | 16000 | 22050 | 24000 => Version::Mpeg2, |
| @@ -154,6 +170,7 @@ impl Mp3Encode { | ||
| 154 | 170 | sample_rate, |
| 155 | 171 | channels, |
| 156 | 172 | bitrate_kbps: snap_bitrate(version, bitrate_kbps), |
| 173 | + vbr_quality, | |
| 157 | 174 | version, |
| 158 | 175 | mode: if channels == 2 { |
| 159 | 176 | ChannelMode::JointStereo |
| @@ -175,16 +192,17 @@ impl Mp3Encode { | ||
| 175 | 192 | queued: std::collections::VecDeque::new(), |
| 176 | 193 | ready: std::collections::VecDeque::new(), |
| 177 | 194 | frames: 0, |
| 195 | + frame_bytes: 0, | |
| 178 | 196 | }) |
| 179 | 197 | } |
| 180 | 198 | |
| 181 | - /// The header every frame of this stream carries. | |
| 182 | - fn header(&self) -> FrameHeader { | |
| 199 | + /// The header every frame of this stream carries, at `bitrate_kbps`. | |
| 200 | + fn header(&self, bitrate_kbps: u32) -> FrameHeader { | |
| 183 | 201 | FrameHeader { |
| 184 | 202 | version: self.version, |
| 185 | 203 | layer: 3, |
| 186 | 204 | crc: false, |
| 187 | - bitrate_kbps: self.bitrate_kbps, | |
| 205 | + bitrate_kbps, | |
| 188 | 206 | sample_rate: self.sample_rate, |
| 189 | 207 | padding: false, |
| 190 | 208 | private: false, |
| @@ -198,7 +216,7 @@ impl Mp3Encode { | ||
| 198 | 216 | |
| 199 | 217 | /// Granules per frame for this stream. |
| 200 | 218 | pub fn granules(&self) -> usize { |
| 201 | - self.header().granules() | |
| 219 | + self.header(self.bitrate_kbps).granules() | |
| 202 | 220 | } |
| 203 | 221 | |
| 204 | 222 | /// Samples per channel one frame codes. |
| @@ -245,7 +263,12 @@ impl Mp3Encoder { | ||
| 245 | 263 | Some(q) => bitrate_for_quality(q), |
| 246 | 264 | None => self.config.bitrate_kbps.max(8), |
| 247 | 265 | }; |
| 248 | - self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?); | |
| 266 | + self.core = Some(Mp3Encode::new( | |
| 267 | + sample_rate, | |
| 268 | + usize::from(channels), | |
| 269 | + bitrate, | |
| 270 | + self.config.vbr_quality, | |
| 271 | + )?); | |
| 249 | 272 | self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0); |
| 250 | 273 | } |
| 251 | 274 | self.pcm.extend_from_slice(interleaved); |
| @@ -375,7 +398,8 @@ const LAME_VERSION: &[u8; 9] = b"LAME3.100"; | ||
| 375 | 398 | /// that interleaves pushes and pulls gets the delay (a constant) right and the |
| 376 | 399 | /// counts as of the first pull. |
| 377 | 400 | fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { |
| 378 | - let header = core.header(); | |
| 401 | + let vbr = core.vbr_quality.is_some(); | |
| 402 | + let header = core.header(core.bitrate_kbps); | |
| 379 | 403 | let frame_len = header.frame_len().unwrap_or(417); |
| 380 | 404 | let mut out = vec![0u8; frame_len]; |
| 381 | 405 | out[..4].copy_from_slice(&header.to_bytes()); |
| @@ -389,25 +413,42 @@ fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { | ||
| 389 | 413 | } else { |
| 390 | 414 | (0, 0) |
| 391 | 415 | }; |
| 416 | + // The header's byte count is the whole stream, info frame included. | |
| 417 | + // `frame_bytes` sums emitted audio-frame lengths; in CBR that is | |
| 418 | + // `frames * frame_len`, reducing to the old `(frames + 1) * frame_len`. | |
| 392 | 419 | let bytes = if complete { |
| 393 | - (u64::from(frames) + 1) * frame_len as u64 | |
| 420 | + core.frame_bytes + frame_len as u64 | |
| 394 | 421 | } else { |
| 395 | 422 | 0 |
| 396 | 423 | }; |
| 424 | + // The LAME "bitrate" byte: a VBR stream reports its mean rate, a CBR one | |
| 425 | + // its constant rate. | |
| 426 | + let bitrate_byte = if vbr && complete && samples > 0 { | |
| 427 | + let seconds = samples as f64 / f64::from(core.sample_rate); | |
| 428 | + let kbps = bytes as f64 * 8.0 / seconds / 1000.0; | |
| 429 | + (kbps.round() as u32).min(255) as u8 | |
| 430 | + } else { | |
| 431 | + core.bitrate_kbps.min(255) as u8 | |
| 432 | + }; | |
| 397 | 433 | |
| 398 | 434 | let mut tag: Vec<u8> = Vec::with_capacity(64); |
| 399 | - tag.extend_from_slice(b"Info"); // constant bitrate; "Xing" is the VBR name | |
| 435 | + if vbr { | |
| 436 | + tag.extend_from_slice(b"Xing"); | |
| 437 | + } else { | |
| 438 | + tag.extend_from_slice(b"Info"); | |
| 439 | + } | |
| 400 | 440 | tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present |
| 401 | 441 | tag.extend_from_slice(&frames.to_be_bytes()); |
| 402 | 442 | tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes()); |
| 403 | 443 | tag.extend_from_slice(LAME_VERSION); |
| 404 | - tag.push(0); // tag revision and VBR method | |
| 444 | + // Tag revision (0), VBR flag (0x10) and VBR method (3) when variable. | |
| 445 | + tag.push(if vbr { 0x70 } else { 0 }); | |
| 405 | 446 | tag.push(0); // lowpass in 100 Hz units, unstated |
| 406 | 447 | tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak |
| 407 | 448 | tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain |
| 408 | 449 | tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain |
| 409 | 450 | tag.push(0); // encoding flags and ATH type |
| 410 | - tag.push(core.bitrate_kbps.min(255) as u8); | |
| 451 | + tag.push(bitrate_byte); | |
| 411 | 452 | let delay_padding = (ENCODER_DELAY << 12) | padding; |
| 412 | 453 | tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each |
| 413 | 454 | tag.push(0); // misc |
| @@ -536,9 +577,7 @@ impl Mp3Encode { | ||
| 536 | 577 | fn emit_frame(&mut self) { |
| 537 | 578 | let channels = self.channels; |
| 538 | 579 | let granules = self.granules(); |
| 539 | - let header = self.header(); | |
| 540 | - let frame_len = header.frame_len().unwrap_or(0); | |
| 541 | - let capacity = frame_len - 4 - header.side_info_len(); | |
| 580 | + let vbr = self.vbr_quality; | |
| 542 | 581 | |
| 543 | 582 | // Window types. A granule whose successor is much louder starts the |
| 544 | 583 | // switch, the loud one is short, and the one after stops it — and the |
| @@ -574,28 +613,103 @@ impl Mp3Encode { | ||
| 574 | 613 | } |
| 575 | 614 | |
| 576 | 615 | let begin = self.assigned - self.used; |
| 577 | - let budget_bits = (self.assigned + capacity - self.used) * 8; | |
| 578 | - let mut coded: Vec<CodedGranule> = Vec::with_capacity(granules * channels); | |
| 579 | - let share = budget_bits / (granules * channels).max(1); | |
| 616 | + | |
| 617 | + // The MDCT and the quality-scaled masking threshold are shared by | |
| 618 | + // every bitrate candidate VBR tries below; compute them once. | |
| 619 | + let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels); | |
| 620 | + let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels); | |
| 580 | 621 | for gr in 0..granules { |
| 581 | 622 | for ch in 0..channels { |
| 582 | 623 | let index = gr * channels + ch; |
| 583 | 624 | let granule = self.pending[index].clone(); |
| 584 | - let xr = self.mdct(ch, &granule.subband, types[index]); | |
| 585 | - let spent: usize = coded.iter().map(|c| c.part2_3_length as usize).sum(); | |
| 586 | - let left = budget_bits.saturating_sub(spent); | |
| 587 | - let target = share.min(left).min(4095); | |
| 588 | - coded.push(quantise_granule( | |
| 589 | - &xr, | |
| 590 | - types[index], | |
| 591 | - target as u32, | |
| 592 | - &granule.threshold, | |
| 593 | - self.sample_rate, | |
| 594 | - )); | |
| 625 | + xrs.push(self.mdct(ch, &granule.subband, types[index])); | |
| 626 | + thresholds.push(match vbr { | |
| 627 | + Some(quality) => quality_threshold(&granule.threshold, quality), | |
| 628 | + None => granule.threshold, | |
| 629 | + }); | |
| 595 | 630 | } |
| 596 | 631 | } |
| 597 | 632 | self.pending.drain(..granules * channels); |
| 598 | 633 | |
| 634 | + // Quantise the granules. CBR codes to a fixed frame budget. VBR tries | |
| 635 | + // legal bitrates, coding the whole frame's granules against each one's | |
| 636 | + // share with the same distortion loop CBR uses, and keeps the | |
| 637 | + // cheapest one whose mean noise-to-mask ratio sits under one. | |
| 638 | + let (coded, kbps): (Vec<CodedGranule>, u32) = match vbr { | |
| 639 | + Some(_) => { | |
| 640 | + let table: &[u32] = if self.version == Version::Mpeg1 { | |
| 641 | + &BITRATES_V1 | |
| 642 | + } else { | |
| 643 | + &BITRATES_V2 | |
| 644 | + }; | |
| 645 | + // Codes the frame at one candidate and reports its mean | |
| 646 | + // noise-to-mask ratio; the ratio falls as the bitrate rises, | |
| 647 | + // so the cheapest candidate at or under 1.0 is found by | |
| 648 | + // bisection over the table (four codings, not fourteen). | |
| 649 | + let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) { | |
| 650 | + let header = self.header(candidate); | |
| 651 | + let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); | |
| 652 | + let share = ((capacity * 8) / (granules * channels).max(1)) | |
| 653 | + .min(PART2_3_MAX as usize) as u32; | |
| 654 | + let mut frame_coded = Vec::with_capacity(granules * channels); | |
| 655 | + let mut ratio = 0.0; | |
| 656 | + for index in 0..granules * channels { | |
| 657 | + let (granule, r) = quantise_granule( | |
| 658 | + &xrs[index], | |
| 659 | + types[index], | |
| 660 | + share, | |
| 661 | + &thresholds[index], | |
| 662 | + self.sample_rate, | |
| 663 | + ); | |
| 664 | + ratio += r / (granules * channels) as f64; | |
| 665 | + frame_coded.push(granule); | |
| 666 | + } | |
| 667 | + (frame_coded, ratio) | |
| 668 | + }; | |
| 669 | + let (mut lo, mut hi) = (0usize, table.len() - 1); | |
| 670 | + let mut best = code_at(table[hi]); | |
| 671 | + let mut best_kbps = table[hi]; | |
| 672 | + while lo < hi { | |
| 673 | + let mid = (lo + hi) / 2; | |
| 674 | + let (coded, ratio) = code_at(table[mid]); | |
| 675 | + if ratio <= 1.0 { | |
| 676 | + best = (coded, ratio); | |
| 677 | + best_kbps = table[mid]; | |
| 678 | + hi = mid; | |
| 679 | + } else { | |
| 680 | + lo = mid + 1; | |
| 681 | + } | |
| 682 | + } | |
| 683 | + (best.0, best_kbps) | |
| 684 | + } | |
| 685 | + None => { | |
| 686 | + let header = self.header(self.bitrate_kbps); | |
| 687 | + let frame_len = header.frame_len().unwrap_or(0); | |
| 688 | + let capacity = frame_len - 4 - header.side_info_len(); | |
| 689 | + let budget_bits = (self.assigned + capacity - self.used) * 8; | |
| 690 | + let share = budget_bits / (granules * channels).max(1); | |
| 691 | + let mut frame_coded = Vec::with_capacity(granules * channels); | |
| 692 | + for index in 0..granules * channels { | |
| 693 | + let spent: usize = frame_coded.iter().map(|c: &CodedGranule| c.part2_3_length as usize).sum(); | |
| 694 | + let left = budget_bits.saturating_sub(spent); | |
| 695 | + let target = share.min(left).min(4095); | |
| 696 | + let (granule, _) = quantise_granule( | |
| 697 | + &xrs[index], | |
| 698 | + types[index], | |
| 699 | + target as u32, | |
| 700 | + &thresholds[index], | |
| 701 | + self.sample_rate, | |
| 702 | + ); | |
| 703 | + frame_coded.push(granule); | |
| 704 | + } | |
| 705 | + (frame_coded, self.bitrate_kbps) | |
| 706 | + } | |
| 707 | + }; | |
| 708 | + | |
| 709 | + let header = self.header(kbps); | |
| 710 | + let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); | |
| 711 | + let side_info_len = header.side_info_len(); | |
| 712 | + | |
| 599 | 713 | // Assemble the frame: header, side info, and this frame's window on |
| 600 | 714 | // the main-data stream. |
| 601 | 715 | let mut side = BitWriter::new(); |
| @@ -645,7 +759,7 @@ impl Mp3Encode { | ||
| 645 | 759 | } |
| 646 | 760 | side.align_to_byte(); |
| 647 | 761 | let side_bytes = side.into_bytes(); |
| 648 | - debug_assert_eq!(side_bytes.len(), header.side_info_len()); | |
| 762 | + debug_assert_eq!(side_bytes.len(), side_info_len); | |
| 649 | 763 | |
| 650 | 764 | // Append the granule data to the stream at `used`, byte aligned. |
| 651 | 765 | let mut main = BitWriter::new(); |
| @@ -666,18 +780,22 @@ impl Mp3Encode { | ||
| 666 | 780 | self.used += main_bytes.len(); |
| 667 | 781 | |
| 668 | 782 | self.queued |
| 669 | - .push_back((header.to_bytes().to_vec(), side_bytes)); | |
| 783 | + .push_back((header.to_bytes().to_vec(), side_bytes, capacity)); | |
| 670 | 784 | self.assigned += capacity; |
| 671 | 785 | // A queued frame can only go out once real granule data covers its |
| 672 | 786 | // whole payload; padding it early is what would strand the next |
| 673 | 787 | // frame's `main_data_begin` in bytes that were already written. |
| 674 | - while !self.queued.is_empty() && self.stream.len() >= self.written + capacity { | |
| 675 | - let (head, side) = self.queued.pop_front().expect("queue is not empty"); | |
| 676 | - let mut frame = Vec::with_capacity(frame_len); | |
| 788 | + while let Some(&(_, _, front)) = self.queued.front() { | |
| 789 | + if self.stream.len() < self.written + front { | |
| 790 | + break; | |
| 791 | + } | |
| 792 | + let (head, side, cap) = self.queued.pop_front().expect("queue is not empty"); | |
| 793 | + let mut frame = Vec::with_capacity(4 + side_info_len + cap); | |
| 677 | 794 | frame.extend_from_slice(&head); |
| 678 | 795 | frame.extend_from_slice(&side); |
| 679 | - frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); | |
| 680 | - self.written += capacity; | |
| 796 | + frame.extend_from_slice(&self.stream[self.written..self.written + cap]); | |
| 797 | + self.written += cap; | |
| 798 | + self.frame_bytes += (4 + side_info_len + cap) as u64; | |
| 681 | 799 | self.ready.push_back(frame); |
| 682 | 800 | self.frames += 1; |
| 683 | 801 | } |
| @@ -699,18 +817,16 @@ impl Mp3Encode { | ||
| 699 | 817 | /// Writes out whatever frames are still queued, padding the stream so the |
| 700 | 818 | /// last frame is complete. |
| 701 | 819 | fn flush_frames(&mut self) { |
| 702 | - let header = self.header(); | |
| 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() { | |
| 820 | + while let Some((head, side, capacity)) = self.queued.pop_front() { | |
| 706 | 821 | if self.stream.len() < self.written + capacity { |
| 707 | 822 | self.stream.resize(self.written + capacity, 0); |
| 708 | 823 | } |
| 709 | - let mut frame = Vec::with_capacity(frame_len); | |
| 824 | + let mut frame = Vec::with_capacity(4 + side.len() + capacity); | |
| 710 | 825 | frame.extend_from_slice(&head); |
| 711 | 826 | frame.extend_from_slice(&side); |
| 712 | 827 | frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); |
| 713 | 828 | self.written += capacity; |
| 829 | + self.frame_bytes += (4 + side.len() + capacity) as u64; | |
| 714 | 830 | self.ready.push_back(frame); |
| 715 | 831 | self.frames += 1; |
| 716 | 832 | } |
| @@ -782,6 +898,21 @@ fn mdct_short(input: &[f32; 36], out: &mut [f32]) { | ||
| 782 | 898 | } |
| 783 | 899 | } |
| 784 | 900 | |
| 901 | +/// Scales the masking threshold by `vbr_quality`. A higher quality lowers the | |
| 902 | +/// allowed noise (a smaller threshold, so more bands are amplified and the | |
| 903 | +/// granule costs more bits); a lower quality raises it. 0.5 is neutral. | |
| 904 | +fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> { | |
| 905 | + let q = quality.clamp(0.0, 1.0); | |
| 906 | + // The psychoacoustic threshold is in the unnormalised FFT's power units, | |
| 907 | + // the quantisation noise in MDCT units, so the 0.5 point carries the unit | |
| 908 | + // gap plus the masking margin. corner-cut: -48 dB is the calibration that | |
| 909 | + // lands wav16-* VBR at its 192 kbit/s mean; a normalised threshold would | |
| 910 | + // make it a plain margin. | |
| 911 | + let db = (0.5 - q) * 24.0 - 48.0; | |
| 912 | + let scale = 10f32.powf(db / 10.0); | |
| 913 | + threshold.iter().map(|&t| t * scale).collect() | |
| 914 | +} | |
| 915 | + | |
| 785 | 916 | /// Quantises one granule: the rate loop inside the distortion loop. |
| 786 | 917 | fn quantise_granule( |
| 787 | 918 | xr: &[f32], |
| @@ -789,9 +920,12 @@ fn quantise_granule( | ||
| 789 | 920 | target_bits: u32, |
| 790 | 921 | threshold: &[f32], |
| 791 | 922 | sample_rate: u32, |
| 792 | -) -> CodedGranule { | |
| 923 | +) -> (CodedGranule, f64) { | |
| 793 | 924 | let mut scalefac = [0u8; SFB_LONG]; |
| 794 | - let mut best: Option<(CodedGranule, f64)> = None; | |
| 925 | + // Score is the summed noise-to-mask ratio over the bands; a mean ratio | |
| 926 | + // of at most one is VBR's signal that this bitrate carried the granule | |
| 927 | + // cleanly (strict all-bands-under is vetoed by scalefactor-capped bands). | |
| 928 | + let mut best: Option<(CodedGranule, f64, usize)> = None; | |
| 795 | 929 | // The distortion loop. Two things end it: every band is under its masking |
| 796 | 930 | // threshold *and* the bits are spent, or no band can be amplified further. |
| 797 | 931 | // Spending the bits matters as much as the threshold does — a granule that |
| @@ -807,18 +941,17 @@ fn quantise_granule( | ||
| 807 | 941 | .collect(); |
| 808 | 942 | let score: f64 = ratios.iter().sum(); |
| 809 | 943 | 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 | 944 | let mut order: Vec<usize> = (0..bands) |
| 818 | 945 | .filter(|&b| scalefac[b] < max_scalefac(b, block_type)) |
| 819 | 946 | .collect(); |
| 820 | 947 | order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a])); |
| 821 | 948 | let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect(); |
| 949 | + if best.as_ref().is_none_or(|(_, s, _)| score < *s) { | |
| 950 | + best = Some((granule, score, bands)); | |
| 951 | + } | |
| 952 | + if spent * 20 > target_bits * 19 { | |
| 953 | + break; // the budget is spent; amplifying now only coarsens | |
| 954 | + } | |
| 822 | 955 | let chosen: Vec<usize> = if over.is_empty() { |
| 823 | 956 | order.iter().copied().take(3).collect() |
| 824 | 957 | } else { |
| @@ -831,7 +964,8 @@ fn quantise_granule( | ||
| 831 | 964 | scalefac[band] += 1; |
| 832 | 965 | } |
| 833 | 966 | } |
| 834 | - best.expect("at least one round runs").0 | |
| 967 | + let (granule, score, bands) = best.expect("at least one round runs"); | |
| 968 | + (granule, score / bands as f64) | |
| 835 | 969 | } |
| 836 | 970 | |
| 837 | 971 | /// Bitstream order for a short block's spectrum. |
| @@ -1483,7 +1617,7 @@ mod tests { | ||
| 1483 | 1617 | |
| 1484 | 1618 | #[test] |
| 1485 | 1619 | fn unsupported_rates_are_refused_by_name() { |
| 1486 | - let err = Mp3Encode::new(96000, 2, 128).unwrap_err(); | |
| 1620 | + let err = Mp3Encode::new(96000, 2, 128, None).unwrap_err(); | |
| 1487 | 1621 | assert!(format!("{err}").contains("96000 Hz"), "{err}"); |
| 1488 | 1622 | } |
| 1489 | 1623 |
crates/ec-mp3/tests/encode_matrix.rsmodified+103 -0
| @@ -143,6 +143,109 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> { | ||
| 143 | 143 | out |
| 144 | 144 | } |
| 145 | 145 | |
| 146 | +fn fnv1a(bytes: &[u8]) -> u64 { | |
| 147 | + let mut h: u64 = 0xcbf2_9ce4_8422_2325; | |
| 148 | + for &b in bytes { | |
| 149 | + h ^= u64::from(b); | |
| 150 | + h = h.wrapping_mul(0x0000_0100_0000_01b3); | |
| 151 | + } | |
| 152 | + h | |
| 153 | +} | |
| 154 | + | |
| 155 | +/// VBR must not move CBR: the byte stream for CBR-192 of the stereo 48 kHz | |
| 156 | +/// tone fixture, hashed on the encoder before VBR landed (9ac19d6). | |
| 157 | +#[test] | |
| 158 | +fn cbr_output_is_unchanged() { | |
| 159 | + let path = fixtures().join("audio/wav16-stereo-48000.wav"); | |
| 160 | + let Some((pcm, rate, channels)) = read_wav(&path) else { | |
| 161 | + eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); | |
| 162 | + return; | |
| 163 | + }; | |
| 164 | + let bytes = encode(&pcm, rate, channels, 192); | |
| 165 | + assert_eq!((bytes.len(), fnv1a(&bytes)), (73728, 0xab48da1954f88c48)); | |
| 166 | +} | |
| 167 | + | |
| 168 | +fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> { | |
| 169 | + let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { | |
| 170 | + bitrate_kbps: 0, | |
| 171 | + vbr_quality: Some(quality), | |
| 172 | + }); | |
| 173 | + encoder | |
| 174 | + .push_pcm_f32(pcm, channels as u16, rate) | |
| 175 | + .expect("encoder accepts the fixture"); | |
| 176 | + encoder.finish(); | |
| 177 | + let mut out = Vec::new(); | |
| 178 | + while let Ok(frame) = encoder.next_packet() { | |
| 179 | + out.extend_from_slice(&frame); | |
| 180 | + } | |
| 181 | + out | |
| 182 | +} | |
| 183 | + | |
| 184 | +/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across | |
| 185 | +/// frames, decodes at least as well as the incumbent's CBR-192, and announces | |
| 186 | +/// itself through a Xing tag ffprobe reads as VBR. | |
| 187 | +#[test] | |
| 188 | +fn vbr_frames_vary_their_bitrate_index() { | |
| 189 | + let name = "mp3src-stereo-48000"; | |
| 190 | + let path = fixtures().join(format!("audio/{name}.wav")); | |
| 191 | + let Some((pcm, rate, channels)) = read_wav(&path) else { | |
| 192 | + eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); | |
| 193 | + return; | |
| 194 | + }; | |
| 195 | + let bytes = encode_vbr(&pcm, rate, channels, 0.5); | |
| 196 | + // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame. | |
| 197 | + let table = [0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]; | |
| 198 | + let mut indices = std::collections::BTreeSet::new(); | |
| 199 | + let (mut pos, mut frames) = (0usize, 0usize); | |
| 200 | + while pos + 4 <= bytes.len() { | |
| 201 | + let h = &bytes[pos..pos + 4]; | |
| 202 | + assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}"); | |
| 203 | + let index = usize::from(h[2] >> 4); | |
| 204 | + let kbps = table[index.min(14)] as usize; | |
| 205 | + assert!(kbps > 0, "free-format header at {pos}"); | |
| 206 | + if frames > 0 { | |
| 207 | + indices.insert(index); | |
| 208 | + } | |
| 209 | + frames += 1; | |
| 210 | + pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1); | |
| 211 | + } | |
| 212 | + let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); | |
| 213 | + let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; | |
| 214 | + let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5)); | |
| 215 | + println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s"); | |
| 216 | + assert!(indices.len() >= 3, "only {indices:?}"); | |
| 217 | + assert!((mean - target).abs() <= target * 0.25, "mean {mean:.1} vs {target}"); | |
| 218 | + | |
| 219 | + let work = workdir("vbr"); | |
| 220 | + let file = work.join("vbr.mp3"); | |
| 221 | + std::fs::write(&file, &bytes).unwrap(); | |
| 222 | + let out = Command::new("ffmpeg") | |
| 223 | + .args(["-v", "warning", "-i"]) | |
| 224 | + .arg(&file) | |
| 225 | + .args(["-f", "f32le", "-"]) | |
| 226 | + .output() | |
| 227 | + .expect("run ffmpeg"); | |
| 228 | + assert!(out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); | |
| 229 | + let decoded: Vec<f32> = out | |
| 230 | + .stdout | |
| 231 | + .chunks_exact(4) | |
| 232 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | |
| 233 | + .collect(); | |
| 234 | + let corr = correlation(&decoded, &pcm); | |
| 235 | + let bar = bar_for(name, 192); | |
| 236 | + println!("vbr corr={corr:.5} bar={bar:.5}"); | |
| 237 | + assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}"); | |
| 238 | + let probe = Command::new("ffprobe") | |
| 239 | + .args(["-v", "error", "-show_format"]) | |
| 240 | + .arg(&file) | |
| 241 | + .output() | |
| 242 | + .expect("run ffprobe"); | |
| 243 | + let probe = String::from_utf8_lossy(&probe.stdout); | |
| 244 | + // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version. | |
| 245 | + assert!(&bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, "no VBR-flagged Xing tag"); | |
| 246 | + assert!(probe.contains("format_name=mp3"), "{probe}"); | |
| 247 | +} | |
| 248 | + | |
| 146 | 249 | #[test] |
| 147 | 250 | fn encodes_above_the_incumbent_bar() { |
| 148 | 251 | let dir = fixtures().join("audio"); |
shims/rusty_mp3/src/lib.rsmodified+4 -4
| @@ -8,10 +8,10 @@ | ||
| 8 | 8 | //! contract — because a shim that grows a surface nobody calls is a second |
| 9 | 9 | //! implementation to keep honest. |
| 10 | 10 | //! |
| 11 | -//! Behaviour differences from the incumbent, all stated: `vbr_quality` picks a | |
| 12 | -//! constant bitrate rather than varying the rate per frame (see | |
| 13 | -//! [`ec_mp3::encode::Mp3EncoderConfig`]), and the encoder writes the `Info` | |
| 14 | -//! header frame first, as the incumbent does. | |
| 11 | +//! Behaviour difference from the incumbent, stated: the encoder writes the | |
| 12 | +//! `Xing`/`Info` header frame first, and `vbr_quality` runs true variable | |
| 13 | +//! bitrate — per-frame bitrate indices chosen to carry the coded granules | |
| 14 | +//! (see [`ec_mp3::encode::Mp3EncoderConfig`]). | |
| 15 | 15 | |
| 16 | 16 | #![forbid(unsafe_code)] |
| 17 | 17 | #![warn(missing_docs)] |