Commits
Commits on
9b5376d7bbf7ddbfcd274cfcaf2a7dabf7ed77f7Filtered to crates/ec-mp3/src/encode.rsClear filter2026-09-06
test(mp3): census the distortion loop's exit reason, and record what LAME's shape measuresAhmet Kaan Gümüş · 3458620
test(mp3): census the distortion loop's exit reason, and record what LAME's shape measures The outer loop's exit reason was only knowable by patching the encoder, so every round that asked "does the distortion loop run" had to re-instrument it. `EC_MP3_LOOP_TRACE=1` now prints one `mp3loop <reason> <round>` line per granule, countable with `sort | uniq -c`. Measured on two library sources at 128 and 192 kbit/s, 36758 granules: 36494 exit at round 0 on the budget break, 264 after one to five rounds, 3 at the cap. The loop is a rate loop, as recorded. Restructuring it into LAME's shape -- drop the budget break, let the distortion test drive, since the inner loop already fits the budget at every round -- was built and measured on the same two sources before being reverted. It does make the loop live (10440 of 36758 granules reach the 20-round cap), and it loses on both of the gate's metrics: 0.99917 -> 0.99787 correlation at 128 kbit/s, from ahead of libmp3lame to behind it, and the worst 20 ms window from -15.3 to -12.4 dB, at about five times the encode time. The finding is in the comment so the next round does not pay for it again.
2026-08-23
mp3: gate VBR against the reference ladder, and split its frames tooAhmet Kaan Gümüş · 806ee38
mp3: gate VBR against the reference ladder, and split its frames too VBR had no reference gate, which is why the demand-weighted frame split landed in the CBR arm only. The gate encodes every rung of libmp3lame's VBR ladder on each source and compares against the rung that actually spent what we spent -- nominal rates are no guide, since V6 is nominally 115 kbit/s and lands near 60 on speech. Measured that way the shipped VBR lost almost everywhere: 11 of 14 rows behind on correlation and up to 8 dB behind on the worst 20 ms window at the same rate. The demand split takes that to 10 rows ahead, and recalibrating the quality bar takes it to 13. The recalibration is the second half of the split: reaching the same masking bar for fewer bits has to be spent, not pocketed, because the quality knob promises a mean rate. The bar now tightens by 1.6 - 12q decibels, fitted so quality 0.3 lands at 162 kbit/s against its promised 163 and quality 0.6 at 232 against 230. Floors are set from the measurement: correlation -0.0005, worst-window excess 3.5 dB, and 8% of the matched rung's rate, with top-rung rows exempt from the rate check because the reference cannot spend more there.
mp3: split the frame budget by each channel's bit demandAhmet Kaan Gümüş · e90e593
mp3: split the frame budget by each channel's bit demand CBR handed every granule-channel the same share of the frame, so the quiet channel of a mid/side pair held bits it had no way to spend while the loud one was starved. The quantiser codes |xr|^(3/4), so the sum of that over a granule's lines is the shape of its demand; the frame is now split by it, blended seven parts demand to three parts even. The blend is where the two gate metrics disagree. Correlation keeps improving to a pure demand split, but the worst 20 ms window turns around before it: at full demand the loud granules take so much of the frame that a quiet one cannot code its own transient, and one row falls 1.8 dB behind the reference. Seven tenths takes nearly all the correlation and leaves every row's worst window ahead. All fourteen sweep rows now beat libmp3lame on both metrics. The correlation floor becomes zero -- falling behind the reference at all is the regression -- and the worst-window excess tightens from 5.0 dB to 1.0. The split is CBR only. VBR chooses its bitrate from the noise-to-mask ratio a candidate reaches, and that mapping is calibrated to the even split: quality 0.5 settles at 154.6 kbit/s rather than 208 with the demand split in. Both want to move together, against a VBR reference gate that does not exist yet.
mp3: code correlated stereo as mid/sideAhmet Kaan Gümüş · 21447bf
mp3: code correlated stereo as mid/side The encoder declared joint stereo in every frame header and then wrote mode_extension zero, which is plain left/right. The decoder had implemented mid/side all along, so the two spoken-word sources in the library sweep were coded twice over -- once per channel -- at half the bits each, and sat 12.6 dB behind the reference in the worst 20 ms window. A frame now takes mid/side when the difference of its channels is quieter than their sum, which is every correlated mix and no opposed one. Both channels of a frame take the same window, because adding a long block's lines to a short block's describes two different time slices. A mid/side pair is held to whichever channel masked less, since an error in the side channel lands in both ears. All fourteen sweep rows improve or hold. Five now beat the reference where three did; the worst window on the speech rows closes to a tie at 192 kbit/s. Both gate floors tighten onto the new worst rows: correlation to -0.0012, and worst-window excess from 13.5 dB to 5.0 dB.
perf(mp3): stop amplifying at 85% of the frame budget, not 95%Ahmet Kaan Gümüş · 5912f29
perf(mp3): stop amplifying at 85% of the frame budget, not 95% The worst-window metric from the last commit left a question: on the speech sources the worst 20 ms barely improves when the bitrate rises by half, so something other than the bit supply was capping it. The distortion loop has three stop conditions and none of them had been swept. Two are not live. Raising the round cap from 20 to 60 gives bit-identical output, so the loop never reaches it, and amplifying one band per round instead of three is a wash. The third is the budget break, and it is the whole story. Stopping at 85% instead of 95% improves every one of the fourteen library rows in correlation and none of them regresses in the worst window; reelm and hein at 192 kbit/s gain 2.8 and 1.4 dB. The mean gap to the reference at 128 kbit/s halves, from -0.00058 to -0.00033. The other direction shows why. Letting the loop amplify to 100% of the budget costs reelm 0.0048 correlation: past the budget an amplified band buys nothing and the rate loop coarsens every other band to pay for it. Below 70% the condition stops binding at all, since the first round already spends more. Both gate floors tighten onto the new worst rows.
fix(mp3): wake the block switcher, and measure what it is forAhmet Kaan Gümüş · 4ca0311
fix(mp3): wake the block switcher, and measure what it is for The switcher decided a granule was a transient when the next granule's total energy grew eightfold. A granule is 13 ms, and music meets that about once a minute: counting block types in our own coded streams found one short granule in 9196, against libmp3lame's 88 over the same audio. It has been dead code since it was written. Sweeping the constant over 2 through 32 moved whole-file correlation by 0.00004, which is the second half of the finding: the crate's quality gate cannot see pre-echo at all. A few milliseconds of noise smeared backwards before an attack disappears into a minute of correlation, and a gate like that would have accepted the switcher being deleted. So the sweep now also reports the worst 20 ms error-to-signal ratio, for ours and for the reference, skipping windows under -60 dBFS. Against that metric the constant is not flat: at the shipped 8.0 one window of a real file carries more error energy than signal (+1.1 dB), the curve is flat from 1.6 to 4, and the cliff sits between 4 and 8. The shipped value was just past the edge of it. 4.0 lands, at the cheap end of the flat part. The new gate's floor is set from the measurement and the measurement is unflattering: we lead the reference in the worst window on all four music sources and trail it on all three speech ones, worst by 14 dB. On those, the worst window barely improves when the bitrate rises by half, so the limit is the masking model rather than the bits. That is the next round.
2026-08-21
fix(mp3): speed up VBR silenceAhmet Kaan Gümüş · f0cad7a
fix(mp3): speed up VBR silence Add a zero-granule fast path, make VBR candidate search local to the previous frame, and recalibrate the quality threshold curve on music clips.
2026-08-20
fix(mp3): state the masking threshold in MDCT power units so NMR means somethingAhmet Kaan Gümüş · 60c1bbb
fix(mp3): state the masking threshold in MDCT power units so NMR means something psy_threshold summed an unnormalised 1024-point FFT while code_with measures noise as summed squared MDCT lines; the two differ by exactly 2^17 (512 P per bin from the sine-windowed FFT, P/288 per line from the unity-gain filterbank and the 1/9-scaled 36-point MDCT, 512/576 bins per line), so every band read as "under its mask" and the model was inert. Derivation is in the doc comment; a unit test checks white noise lands the signal-to-mask offset over the mask. The -48 dB corner-cut in quality_threshold goes; the q mapping is 24 dB across the range, centred 4 dB over the mask (documented calibration: q 0.5 lands 210-225 kbit/s on mp3src-stereo-48000 and two real tracks, above the CBR-192 bar). The outer loop now takes the worst over-mask bands first; it still stops at the budget, because letting it run past (ISO style) costs 12-36% RMS under a model this coarse and the bars are an RMS metric (corner-cut noted inline). cbr_output_is_unchanged pinned bytes of the inert-model CBR; CBR bytes legitimately move now, so it is replaced by cbr_quality_holds_its_floor, gating corr >= 0.99999 and RMS <= 0.025% (the pinned stream measured 0.999999 / 0.020%).
feat(mp3): true VBR — per-frame bitrate index chosen by mean noise-to-mask ratioAhmet Kaan Gümüş · 252530f
feat(mp3): true VBR — per-frame bitrate index chosen by mean noise-to-mask ratio vbr_quality now varies the bitrate index per frame: the frame's granules are coded against each candidate's share with the CBR distortion loop, and the cheapest candidate whose mean noise-to-mask ratio is <= 1 wins (bisection over the table). quantise_granule reports that ratio. The VBR threshold scale absorbs the FFT-vs-MDCT unit gap (-48 dB at quality 0.5); CBR output is byte-identical (hash pinned in cbr_output_is_unchanged).
2026-08-14
fix(mp3): gapless Info tag, and the region split a switched granule must useAhmet Kaan Gümüş · 09040eb
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.
feat(mp3): Layer III decoder and encoder, tables measured not copiedAhmet Kaan Gümüş · 1325107
feat(mp3): Layer III decoder and encoder, tables measured not copied ec-mp3 decodes MPEG-1, MPEG-2 LSF and MPEG-2.5 Layer III and encodes CBR MPEG-1 Layer III, and shims/rusty_mp3 carries the incumbent's name, version and call shape over it. Layer III's Huffman code tables and its 512-tap polyphase window are normative data no formula produces. Instead of copying them out of an existing implementation, scripts/mp3-tables measures them against a reference decoder: it writes legal frames whose main-data bits it chooses, decodes them with ffmpeg, and reads the answer back through a model of the decode chain. Every code tree is walked to its leaves and checked for a Kraft sum of exactly 1, complete coverage of its value grid and no duplicates; the window is least-squares fitted to a 1.6e-6 residual, the f32 noise floor of the decoder measured. The same rig produced the MPEG-1 long scalefactor band widths, which came out equal to the published layouts, and it corrected two things a description would not have: the MPEG-2.5 11.025 and 12 kHz short-block layouts are the 16 kHz ones, and the short-block region boundary is three scalefactor bands rather than the fixed 36 lines that only holds where those bands are four wide. Decoder: header and CRC, side info, scalefactors (MPEG-1 with scfsi and the LSF partition scheme), all Huffman tables, requantisation, mid/side and intensity stereo, short-block reorder, alias reduction, IMDCT with the four block windows, and a DCT-based polyphase bank from ec-dsp. ID3v2 and the Xing/LAME/VBRI header frame are skipped, junk is resynced over, and free-format is refused by name rather than guessed at. Encoder: polyphase analysis (the synthesis bank's adjoint, reconstructing to its -85 dB design limit), MDCT with block switching, an FFT-based masking model whose gaps are stated in the module docs, inner rate and outer distortion loops, Huffman table and region selection, and a bit reservoir that emits frames one behind so a granule can start inside the previous frame's payload. Measured, all against ffmpeg: - decode: 47 fixtures (nine sample rates, mono/stereo/joint/simple, CBR and VBR) at correlation 1.000000, 333-3232x realtime - encode: at or above rusty_mp3 0.6.1 on the same corpus and metric at 128/192/320 kbit/s, mono and stereo, every stream decoding without an ffmpeg warning