forge
Explore
Log in

Don't you dare go Hollow

Gapless Info tag, and the region split a switched granule must use

Browse files at this commit

09040ebdf398d4a7472f5320df69571f87402c6cAhmet Kaan GümüşParent: 6e48da7
  • fix
    • gapless Info tag, and the region split a switched granule must use
Show full message
fix(mp3): gapless Info tag, and the region split a switched granule must use

The encoder now writes a real Xing/Info header — frame and byte counts plus
the encoder delay and padding — so a decoder that honours it hands back
exactly the samples that went in. ffmpeg does: a two-second timeline clip
encodes and decodes back to 88200 samples per channel at lag zero, where
before it came back 1728 samples late with no way to know it, and 72 samples
short because the granules held for block-switching lookahead were dropped at
the end instead of flushed.

Chasing that alignment surfaced two real defects, both invisible until the
comparison was made at lag zero over the whole stream:

- A granule that switches windows does not transmit its region boundaries;
  the decoder derives them (three short bands for a short block, eight long
  bands for a start or stop one). The encoder was choosing its own split and
  writing the tables for it, so every switched granule parsed as different
  tables. Bit accounting still landed exactly on part2_3_length, every
  fixture still decoded, and only the switched granules came back as noise --
  47x the intended energy in the worst one measured.
- Short-block spectra are coded band by band and window by window, which is
  not the order the transform produces them in. The decoder's reorder had no
  inverse in the encoder.

Both now have tests that fail without the fix: one drives an attack that
forces the switch and checks the granules around it through our own decoder,
one runs the whole window sequence through the transform pair directly.

Also: scalefactors for short blocks (they had none, so their noise was flat
across the spectrum); a ceiling on scalefactor amplification, since the
second partition's length is at most three bits and a band above the split
cannot carry more than 7 -- the quantiser used what it wanted and the decoder
rebuilt the band with zero; the window-type sequence now carries across frame
boundaries, where it used to restart and leave a start window facing a normal
one; and a frame of priming silence, so the transform's startup lands before
the audio rather than on top of it.

Measured on W2's timeline content, ours at lag zero against the incumbent
rusty_mp3 0.6.1 at its own lag, RMS error against the source:

  128k  1.173e-4 vs 1.143e-4    256k  3.986e-5 vs 3.985e-5
  192k  6.027e-5 vs 6.110e-5    320k  2.535e-5 vs 2.567e-5

Correlation is 1.000000 at 256k and above. The encode fixture matrix is
unchanged in shape and every entry still beats its bar, now measured at lag
zero rather than at the best shift.
crates/ec-mp3/src/encode.rsmodified+504 -85
@@ -20,7 +20,7 @@
2020 use crate::filterbank::{Analysis, alias_expand};
2121 use crate::header::{ChannelMode, FrameHeader, Version};
2222 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};
2424 use ec_core::bitio::BitWriter;
2525 use ec_core::error::{Error, Result};
2626 use ec_dsp::{RealFft, Window};
@@ -101,6 +101,9 @@ pub struct Mp3Encode {
101101 history: Vec<[[f32; 32]; 18]>,
102102 /// Window type chosen for the granule we are holding back.
103103 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>,
104107 fft: RealFft<f32>,
105108 fft_window: Window<f32>,
106109 psy_history: Vec<Vec<f32>>,
@@ -161,6 +164,7 @@ impl Mp3Encode {
161164 slots: vec![Vec::new(); channels],
162165 history: vec![[[0.0; 32]; 18]; channels],
163166 pending: Vec::new(),
167+ previous_block: vec![0; channels],
164168 fft: RealFft::new(1024),
165169 fft_window: Window::sine(1024),
166170 psy_history: vec![vec![0.0; 1024]; channels],
@@ -242,6 +246,7 @@ impl Mp3Encoder {
242246 None => self.config.bitrate_kbps.max(8),
243247 };
244248 self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?);
249+ self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0);
245250 }
246251 self.pcm.extend_from_slice(interleaved);
247252 self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64;
@@ -268,10 +273,11 @@ impl Mp3Encoder {
268273 pub fn finish(&mut self) {
269274 if let Some(core) = &self.core {
270275 let channels = core.channels;
271- // The filterbank runs fifteen slots behind, and the MDCT one
272- // granule behind that; feed silence so the last real samples come
273- // out the other end.
274- let tail = vec![0.0f32; channels * (576 * 2 + 480)];
276+ // The filterbank runs fifteen slots behind, the MDCT one granule
277+ // behind that, and block switching holds one more granule back to
278+ // look ahead; feed silence so every real sample comes out the other
279+ // end rather than being dropped with the pipeline.
280+ let tail = vec![0.0f32; channels * (576 * 3 + 480)];
275281 self.pcm.extend_from_slice(&tail);
276282 }
277283 self.drain(true);
@@ -294,6 +300,7 @@ impl Mp3Encoder {
294300 block.resize(need, 0.0);
295301 core.encode_block(&block);
296302 }
303+ core.flush_pending();
297304 core.flush_frames();
298305 }
299306 while let Some(frame) = core.ready.pop_front() {
@@ -307,7 +314,7 @@ impl Mp3Encoder {
307314 if !self.header_written && (self.finished || !self.frames.is_empty()) {
308315 self.header_written = true;
309316 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));
311318 }
312319 }
313320 match self.frames.pop_front() {
@@ -318,20 +325,102 @@ impl Mp3Encoder {
318325 }
319326 }
320327
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+
321367 /// The Xing/Info header frame every player expects first: a silent frame whose
322368 /// main data is the tag, so a decoder that does not know the tag still decodes
323369 /// 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> {
325378 let header = core.header();
326379 let frame_len = header.frame_len().unwrap_or(417);
327380 let mut out = vec![0u8; frame_len];
328381 out[..4].copy_from_slice(&header.to_bytes());
329382 let at = 4 + header.side_info_len();
330- let tag: &[u8] = b"Info";
331- out[at..at + 4].copy_from_slice(tag);
332- out[at + 4..at + 8].copy_from_slice(&1u32.to_be_bytes()); // frames field present
333- let frames = samples.div_ceil(header.samples_per_frame() as u64) as u32;
334- out[at + 8..at + 12].copy_from_slice(&frames.to_be_bytes());
383+ let spf = header.samples_per_frame() as u64;
384+ let (frames, padding) = if complete {
385+ let frames = core.frames;
386+ let coded = u64::from(frames) * spf;
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]);
335424 out
336425 }
337426
@@ -451,28 +540,36 @@ impl Mp3Encode {
451540 let frame_len = header.frame_len().unwrap_or(0);
452541 let capacity = frame_len - 4 - header.side_info_len();
453542
454- // Window types: a granule whose successor is much louder starts the
455- // switch, the loud one is short, and the one after stops it.
543+ // 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
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.
456549 let mut types = vec![0u8; granules * channels];
457550 for gr in 0..granules {
458551 for ch in 0..channels {
459552 let index = gr * channels + ch;
460- let next = index + channels;
461553 let here = self.pending[index].energy;
462- let there = self.pending.get(next).map_or(here, |g| g.energy);
463- if there > here * 8.0 + 1e-6 {
464- types[index] = 1; // start
465- }
466- }
467- }
468- for gr in 0..granules {
469- for ch in 0..channels {
470- let index = gr * channels + ch;
471- if index >= channels && types[index - channels] == 1 {
472- types[index] = 2; // short
473- } else if index >= 2 * channels && types[index - 2 * channels] == 2 {
474- types[index] = 3; // stop
475- }
554+ let next = self
555+ .pending
556+ .get(index + channels)
557+ .map_or(here, |g| g.energy);
558+ // Digital silence is not a transient to protect: switching on
559+ // the way out of it (the priming, or a cut in a timeline) costs
560+ // the resolution a long block would have spent on the attack
561+ // itself, and there is no pre-echo to hide when nothing
562+ // precedes it.
563+ let attack = here > 1e-9 && next > here * 8.0 + 1e-6;
564+ let block = match self.previous_block[ch] {
565+ 1 => 2,
566+ 2 if attack => 2,
567+ 2 => 3,
568+ _ if attack => 1,
569+ _ => 0,
570+ };
571+ types[index] = block;
572+ self.previous_block[ch] = block;
476573 }
477574 }
478575
@@ -591,6 +688,14 @@ impl Mp3Encode {
591688 }
592689 }
593690
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+
594699 /// Writes out whatever frames are still queued, padding the stream so the
595700 /// last frame is complete.
596701 fn flush_frames(&mut self) {
@@ -692,9 +797,12 @@ fn quantise_granule(
692797 // Spending the bits matters as much as the threshold does — a granule that
693798 // stops early leaves the extra bitrate on the floor, which is what makes an
694799 // 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);
695803 for _round in 0..20 {
696804 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)
698806 .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30))
699807 .collect();
700808 let score: f64 = ratios.iter().sum();
@@ -702,14 +810,13 @@ fn quantise_granule(
702810 if best.as_ref().is_none_or(|(_, s)| score < *s) {
703811 best = Some((granule, score));
704812 }
705- if block_type == 2 {
706- break; // short blocks carry no long scalefactors here
707- }
708813 if spent * 20 > target_bits * 19 {
709814 break; // the budget is spent; amplifying now only coarsens
710815 }
711816 // 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();
713820 order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
714821 let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect();
715822 let chosen: Vec<usize> = if over.is_empty() {
@@ -727,6 +834,66 @@ fn quantise_granule(
727834 best.expect("at least one round runs").0
728835 }
729836
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+
730897 /// Quantises with a fixed scalefactor set, running the rate loop on
731898 /// `global_gain`, and reports the noise each band ends up with.
732899 fn code_with(
@@ -736,10 +903,11 @@ fn code_with(
736903 scalefac: &[u8; SFB_LONG],
737904 sample_rate: u32,
738905 ) -> (CodedGranule, [f32; SFB_LONG]) {
739- let (slen1, slen2, compress) = scalefac_compress(scalefac);
740- // The scalefactors come out of the same budget as the spectrum does.
906+ let (slen1, slen2, compress) = scalefac_compress(scalefac, block_type);
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.
741909 let scalefac_bits = if block_type == 2 {
742- 0
910+ (slen1 + slen2) * 18
743911 } else {
744912 slen1 * 11 + slen2 * 10
745913 };
@@ -759,13 +927,20 @@ fn code_with(
759927 // while the granule is too big for them. A line that saturates the coding
760928 // range is not "cheap", it is clipped, so that check comes first.
761929 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+ };
762937 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);
764939 loop {
765940 if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {
766941 gain += 1;
767942 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);
769944 continue;
770945 }
771946 if saturated(&ix) || coded.0 > target_bits || gain == 0 {
@@ -775,7 +950,7 @@ fn code_with(
775950 // inside the coding range.
776951 let mut trial = ix.clone();
777952 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);
779954 if trial_coded.0 > target_bits || saturated(&trial) {
780955 break;
781956 }
@@ -793,27 +968,46 @@ fn code_with(
793968 for slot in ix.iter_mut().skip(limit) {
794969 *slot = 0;
795970 }
796- coded = code_spectrum(&ix, block_type, sample_rate);
971+ coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);
797972 }
798973 let (_, big_values, tables, region0, region1, count1_select, bits) = coded;
799974 let mut noise = [0.0f32; SFB_LONG];
800- let starts = long_starts(sample_rate);
801975 let power = power43();
802- for band in 0..SFB_LONG {
803- let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
976+ let residual = |i: usize, band: usize| -> f32 {
804977 let scale = band_gain(gain, scalefac[band], block_type);
805- let mut sum = 0.0f32;
806- for i in from..to.min(576) {
807- let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale;
808- let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
809- sum += (xr[i] - reconstructed).powi(2);
978+ let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale;
979+ let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
980+ (xr[i] - reconstructed).powi(2)
981+ };
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;
810996 }
811- noise[band] = sum;
812997 }
813998 let mut out = BitWriter::new();
814- for (band, value) in scalefac.iter().enumerate() {
815- let slen = if band < 11 { slen1 } else { slen2 };
816- if block_type != 2 {
999+ if block_type == 2 {
1000+ // The decoder reads short scalefactors band-major, three windows at a
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 };
8171011 out.write_bits(u32::from(*value), slen);
8181012 }
8191013 }
@@ -840,13 +1034,9 @@ fn code_with(
8401034 (granule, noise)
8411035 }
8421036
843-fn band_gain(gain: i32, scalefac: u8, block_type: u8) -> f32 {
1037+fn band_gain(gain: i32, scalefac: u8, _block_type: u8) -> f32 {
8441038 let base = (gain as f32 - 210.0) * 0.25;
845- if block_type == 2 {
846- base.exp2()
847- } else {
848- (base - 0.5 * f32::from(scalefac)).exp2()
849- }
1039+ (base - 0.5 * f32::from(scalefac)).exp2()
8501040 }
8511041
8521042 /// The spectrum as integers, per the decoder's requantisation read backwards.
@@ -858,6 +1048,22 @@ fn quantise(
8581048 block_type: u8,
8591049 ix: &mut [i32],
8601050 ) {
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+ }
8611067 let starts = long_starts(sample_rate);
8621068 // 22 bands, not 21: the topmost band carries no transmitted scalefactor,
8631069 // but it does carry audio — zeroing it low-passes the encoder at 16 kHz.
@@ -869,13 +1075,23 @@ fn quantise(
8691075 let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };
8701076 let scale = 1.0 / band_gain(gain, scalefac, block_type);
8711077 for i in from..to {
872- let value = (xr[i].abs() * scale).powf(0.75);
873- let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32;
874- ix[i] = if xr[i] < 0.0 { -magnitude } else { magnitude };
1078+ ix[i] = quantise_line(xr[i], scale);
8751079 }
8761080 }
8771081 }
8781082
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+
8791095 /// Chooses the region split, the tables and the count1 boundary, and writes the
8801096 /// spectrum. Returns the bit cost first so the rate loop can stop early.
8811097 #[allow(clippy::type_complexity)]
@@ -902,24 +1118,37 @@ fn code_spectrum(
9021118 let big_end = count1_start;
9031119
9041120 let starts = long_starts(sample_rate);
905- let short = block_type == 2;
906- // Region boundaries land on band edges. Splitting the big-value region in
907- // three roughly equal parts is what makes the three tables specialise;
908- // searching every legal split costs far more than it saves.
909- let (region0, region1, bounds) = if short {
910- let first = usize::from(short_starts(sample_rate)[3]) * 3;
911- (8u32, 12u32, [first.min(big_end), big_end, big_end])
912- } else {
913- let band_at = |target: usize| -> usize {
914- (0..21)
915- .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target))
916- .unwrap_or(7)
917- };
918- let r0 = band_at(big_end / 3).min(15);
919- let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7);
920- let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end);
921- let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end);
922- (r0 as u32, r1 as u32, [a, b.max(a), big_end])
1121+ // Region boundaries land on band edges. A granule that switches windows
1122+ // does not transmit `region0_count`/`region1_count` at all — the decoder
1123+ // derives them (three short bands for a short block, eight long bands
1124+ // otherwise, with region 2 empty) — so the encoder has to use exactly
1125+ // those, not a split of its own. Choosing differently costs no bits and
1126+ // parses as different tables, which is a granule of noise wherever the
1127+ // window switches. Only a normal block gets to pick.
1128+ let (region0, region1, bounds) = match block_type {
1129+ 2 => {
1130+ let first = usize::from(short_starts(sample_rate)[3]) * 3;
1131+ (8u32, 12u32, [first.min(big_end), big_end, big_end])
1132+ }
1133+ 1 | 3 => {
1134+ let first = usize::from(starts[8]);
1135+ (7u32, 13u32, [first.min(big_end), big_end, big_end])
1136+ }
1137+ _ => {
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+ }
9231152 };
9241153
9251154 let mut tables = [0u8; 3];
@@ -1030,17 +1259,26 @@ fn table_cost(ix: &[i32], from: usize, to: usize, table: Table) -> Option<u32> {
10301259 }
10311260
10321261 /// 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) {
10341263 let bits_for = |slice: &[u8]| -> u32 {
10351264 let max = slice.iter().copied().max().unwrap_or(0);
10361265 (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4)
10371266 };
1038- let need1 = bits_for(&scalefac[..11]);
1039- let need2 = bits_for(&scalefac[11..]);
1040- let mut best = (u32::MAX, 0u32, 0u32, 0u32);
1267+ // Long blocks split their bands 11/10, short blocks 6/6 per window.
1268+ let (first, second, cost1, cost2) = if block_type == 2 {
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);
10411279 for (index, (slen1, slen2)) in SLEN.iter().enumerate() {
10421280 if *slen1 >= need1 && *slen2 >= need2 {
1043- let cost = slen1 * 11 + slen2 * 10;
1281+ let cost = slen1 * cost1 + slen2 * cost2;
10441282 if cost < best.0 {
10451283 best = (cost, *slen1, *slen2, index as u32);
10461284 }
@@ -1053,6 +1291,187 @@ fn scalefac_compress(scalefac: &[u8; SFB_LONG]) -> (u32, u32, u32) {
10531291 mod tests {
10541292 use super::*;
10551293
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+
10561475 #[test]
10571476 fn bitrates_snap_to_legal_values() {
10581477 assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128);
crates/ec-mp3/src/lib.rsmodified+4 -1
@@ -8,7 +8,10 @@
88 //! reservoir across frames.
99 //! - [`Mp3Decoder`], the [`ec_core::Decoder`] contract, for a container that
1010 //! 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.
1215 //!
1316 //! **Where the constants came from.** Layer III's Huffman code tables and its
1417 //! 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() {
199199 .chunks_exact(4)
200200 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
201201 .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+ }
203225 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
204226 let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
205227 let name = source.file_name().unwrap().to_string_lossy();