forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-mp3-perf' (77032b83): ec-mp3 encode is 17x faster -- 139.9x RT stereo CBR (0.881 of rusty_mp3, was 0.052), 2h film's track ~51 s of encode wall; word-buffered emission, cost-only rate loop, cosine-table MDCT, one-walk table pricing, bracketed gain search, 8-lane SIMD quantiser; quality equal to pre-change to six decimals on all fixtures (two ulp-class byte moves disclosed and correctly attributed post-audit); suite green per commit; audit corrections ride in the report

Browse files at this commit

e9ee943165f8aeec2556253246382df4a15895f0Ahmet Kaan GümüşParent: 1451897326e1cb
Cargo.lockmodified+1 -0
@@ -396,6 +396,7 @@ version = "0.1.0"
396 dependencies = [396 dependencies = [
397 "ec-core",397 "ec-core",
398 "ec-dsp",398 "ec-dsp",
399+ "wide",
399 ]400 ]
400 401
401 [[package]]402 [[package]]
crates/ec-mp3/Cargo.tomlmodified+1 -0
@@ -9,3 +9,4 @@ authors.workspace = true
9 [dependencies]9 [dependencies]
10 ec-core = { workspace = true }10 ec-core = { workspace = true }
11 ec-dsp = { workspace = true }11 ec-dsp = { workspace = true }
12+wide = { workspace = true }
crates/ec-mp3/src/encode.rsmodified+410 -174
@@ -19,11 +19,15 @@
19 19
20 use crate::filterbank::{Analysis, alias_expand};20 use crate::filterbank::{Analysis, alias_expand};
21 use crate::header::{ChannelMode, FrameHeader, Version};21 use crate::header::{ChannelMode, FrameHeader, Version};
22-use crate::huffman::{self, Table};22+use crate::huffman::{self, BitBuf};
23-use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, short_widths, windows};23+use crate::tables::{
24+ MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts,
25+ short_widths, windows,
26+};
24 use ec_core::bitio::BitWriter;27 use ec_core::bitio::BitWriter;
25 use ec_core::error::{Error, Result};28 use ec_core::error::{Error, Result};
26 use ec_dsp::{RealFft, Window};29 use ec_dsp::{RealFft, Window};
30+use wide::f32x8;
27 31
28 /// Encoder settings.32 /// Encoder settings.
29 ///33 ///
@@ -94,7 +98,7 @@ const DEMAND_SPLIT: f64 = 0.7;
94 /// One granule's worth of coded spectrum plus the side info describing it.98 /// One granule's worth of coded spectrum plus the side info describing it.
95 #[derive(Clone, Debug)]99 #[derive(Clone, Debug)]
96 struct CodedGranule {100 struct CodedGranule {
97- bits: Vec<bool>,101+ bits: BitBuf,
98 part2_3_length: u32,102 part2_3_length: u32,
99 big_values: u32,103 big_values: u32,
100 global_gain: u32,104 global_gain: u32,
@@ -134,6 +138,8 @@ pub struct Mp3Encode {
134 fft: RealFft<f32>,138 fft: RealFft<f32>,
135 fft_window: Window<f32>,139 fft_window: Window<f32>,
136 psy_history: Vec<Vec<f32>>,140 psy_history: Vec<Vec<f32>>,
141+ /// Deinterleave scratch for `encode_block`, grown once and reused.
142+ pcm_scratch: Vec<f32>,
137 /// The main-data byte stream and how much of it frames have carried.143 /// The main-data byte stream and how much of it frames have carried.
138 stream: Vec<u8>,144 stream: Vec<u8>,
139 used: usize,145 used: usize,
@@ -216,6 +222,7 @@ impl Mp3Encode {
216 assigned: 0,222 assigned: 0,
217 written: 0,223 written: 0,
218 queued: std::collections::VecDeque::new(),224 queued: std::collections::VecDeque::new(),
225+ pcm_scratch: Vec::new(),
219 ready: std::collections::VecDeque::new(),226 ready: std::collections::VecDeque::new(),
220 frames: 0,227 frames: 0,
221 frame_bytes: 0,228 frame_bytes: 0,
@@ -347,26 +354,34 @@ impl Mp3Encoder {
347 }354 }
348 355
349 fn drain(&mut self, flush: bool) {356 fn drain(&mut self, flush: bool) {
350- let Some(core) = self.core.as_mut() else {357+ let Self {
358+ core, pcm, frames, ..
359+ } = self;
360+ let Some(core) = core.as_mut() else {
351 return;361 return;
352 };362 };
353 let channels = core.channels;363 let channels = core.channels;
354 let need = core.frame_samples() * channels;364 let need = core.frame_samples() * channels;
355- while self.pcm.len() >= need {365+ // Encode behind a read cursor and shift the leftovers once: draining
356- let block: Vec<f32> = self.pcm.drain(..need).collect();366+ // per frame memmoved the whole remaining push for every frame, which
357- core.encode_block(&block);367+ // on a single large push is quadratic in the file length.
358- }368+ let mut pos = 0usize;
369+ while pcm.len() - pos >= need {
370+ core.encode_block(&pcm[pos..pos + need]);
371+ pos += need;
372+ }
373+ pcm.drain(..pos);
359 if flush {374 if flush {
360- if !self.pcm.is_empty() {375+ if !pcm.is_empty() {
361- let mut block = std::mem::take(&mut self.pcm);376+ pcm.resize(need, 0.0);
362- block.resize(need, 0.0);377+ core.encode_block(pcm);
363- core.encode_block(&block);378+ pcm.clear();
364 }379 }
365 core.flush_pending();380 core.flush_pending();
366 core.flush_frames();381 core.flush_frames();
367 }382 }
368 while let Some(frame) = core.ready.pop_front() {383 while let Some(frame) = core.ready.pop_front() {
369- self.frames.push_back(frame);384+ frames.push_back(frame);
370 }385 }
371 }386 }
372 387
@@ -511,10 +526,15 @@ impl Mp3Encode {
511 let granules = self.granules();526 let granules = self.granules();
512 // Polyphase analysis, one channel at a time.527 // Polyphase analysis, one channel at a time.
513 for ch in 0..channels {528 for ch in 0..channels {
514- let mut mono: Vec<f32> = Vec::with_capacity(pcm.len() / channels);529+ // One deinterleave buffer per encoder, grown once: this frame's
530+ // mono channel used to be a fresh allocation per channel per
531+ // frame.
532+ self.pcm_scratch.clear();
533+ self.pcm_scratch.reserve(pcm.len() / channels);
515 for frame in pcm.chunks(channels) {534 for frame in pcm.chunks(channels) {
516- mono.push(frame[ch]);535+ self.pcm_scratch.push(frame[ch]);
517 }536 }
537+ let mono = &self.pcm_scratch;
518 for chunk in mono.chunks(32) {538 for chunk in mono.chunks(32) {
519 if chunk.len() < 32 {539 if chunk.len() < 32 {
520 break;540 break;
@@ -523,7 +543,13 @@ impl Mp3Encode {
523 self.slots[ch].push(slot);543 self.slots[ch].push(slot);
524 }544 }
525 }545 }
526- self.psy_push(ch, &mono);546+ // The masking model's history update, inlined from `psy_push` so
547+ // it can touch `psy_history` while `mono` borrows `pcm_scratch`.
548+ let n = mono.len().min(1024);
549+ let history = &mut self.psy_history[ch];
550+ history.copy_within(n.., 0);
551+ let keep = 1024 - n;
552+ history[keep..].copy_from_slice(&mono[mono.len() - n..]);
527 }553 }
528 // A granule is 18 slots; hold one back so block switching can look554 // A granule is 18 slots; hold one back so block switching can look
529 // ahead at the next granule's energy.555 // ahead at the next granule's energy.
@@ -554,15 +580,6 @@ impl Mp3Encode {
554 }580 }
555 }581 }
556 582
557- /// One FFT per granule of input, kept for the masking model.
558- fn psy_push(&mut self, ch: usize, mono: &[f32]) {
559- let n = 1024.min(mono.len());
560- let history = &mut self.psy_history[ch];
561- history.copy_within(n.., 0);
562- let keep = 1024 - n;
563- history[keep..].copy_from_slice(&mono[mono.len() - n..]);
564- }
565-
566 /// Allowed noise per long scalefactor band, from the masking model, in583 /// Allowed noise per long scalefactor band, from the masking model, in
567 /// the units `code_with` measures quantisation noise in (summed squared584 /// the units `code_with` measures quantisation noise in (summed squared
568 /// MDCT lines), so noise / threshold is a noise-to-mask ratio.585 /// MDCT lines), so noise / threshold is a noise-to-mask ratio.
@@ -699,18 +716,21 @@ impl Mp3Encode {
699 // every bitrate candidate VBR tries below; compute them once.716 // every bitrate candidate VBR tries below; compute them once.
700 let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);717 let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
701 let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);718 let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
719+ // Take the held-back granules once: the per-granule clone that used
720+ // to feed `mdct` copied every subband and threshold just to keep the
721+ // borrow checker happy about `history`.
722+ let held: Vec<PendingGranule> = self.pending.drain(..granules * channels).collect();
702 for gr in 0..granules {723 for gr in 0..granules {
703 for ch in 0..channels {724 for ch in 0..channels {
704 let index = gr * channels + ch;725 let index = gr * channels + ch;
705- let granule = self.pending[index].clone();726+ let granule = &held[index];
706 xrs.push(self.mdct(ch, &granule.subband, types[index]));727 xrs.push(self.mdct(ch, &granule.subband, types[index]));
707 thresholds.push(match vbr {728 thresholds.push(match vbr {
708 Some(quality) => quality_threshold(&granule.threshold, quality),729 Some(quality) => quality_threshold(&granule.threshold, quality),
709- None => granule.threshold,730+ None => granule.threshold.clone(),
710 });731 });
711 }732 }
712 }733 }
713- self.pending.drain(..granules * channels);
714 734
715 // Mid/side stereo. The two channels of real music are mostly the same735 // Mid/side stereo. The two channels of real music are mostly the same
716 // signal, and coding their sum and difference puts nearly all of the736 // signal, and coding their sum and difference puts nearly all of the
@@ -765,7 +785,16 @@ impl Mp3Encode {
765 let count = (granules * channels).max(1);785 let count = (granules * channels).max(1);
766 let demand: Vec<f64> = xrs786 let demand: Vec<f64> = xrs
767 .iter()787 .iter()
768- .map(|xr| xr.iter().map(|v| f64::from(v.abs()).powf(0.75)).sum())788+ .map(|xr| {
789+ xr.iter()
790+ .map(|v| {
791+ let x = f64::from(v.abs());
792+ // |x|^(3/4) as a cube and two square roots, the same
793+ // shape the quantiser uses.
794+ (x * x * x).sqrt().sqrt()
795+ })
796+ .sum()
797+ })
769 .collect();798 .collect();
770 let demand_total: f64 = demand.iter().sum();799 let demand_total: f64 = demand.iter().sum();
771 let demand_share = |budget: usize, index: usize| -> u32 {800 let demand_share = |budget: usize, index: usize| -> u32 {
@@ -932,13 +961,10 @@ impl Mp3Encode {
932 debug_assert_eq!(side_bytes.len(), side_info_len);961 debug_assert_eq!(side_bytes.len(), side_info_len);
933 962
934 // Append the granule data to the stream at `used`, byte aligned.963 // Append the granule data to the stream at `used`, byte aligned.
935- let mut main = BitWriter::new();964+ let mut main = BitBuf::new();
936 for granule in &coded {965 for granule in &coded {
937- for bit in &granule.bits {966+ main.append(&granule.bits);
938- main.write_bit(*bit);
939- }
940 }967 }
941- main.align_to_byte();
942 let main_bytes = main.into_bytes();968 let main_bytes = main.into_bytes();
943 // Stream positions the reservoir cap skipped over are stuffing, not969 // Stream positions the reservoir cap skipped over are stuffing, not
944 // data, so they are zeros rather than a shorter stream.970 // data, so they are zeros rather than a shorter stream.
@@ -1037,17 +1063,17 @@ impl Mp3Encode {
1037 /// unscaled inverse reconstructs the input under overlap-add.1063 /// unscaled inverse reconstructs the input under overlap-add.
1038 fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) {1064 fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) {
1039 let window = &windows()[usize::from(block_type)];1065 let window = &windows()[usize::from(block_type)];
1066+ let kernel = forward_mdct_long();
1040 let mut windowed = [0.0f32; 36];1067 let mut windowed = [0.0f32; 36];
1041 for i in 0..36 {1068 for i in 0..36 {
1042 windowed[i] = input[i] * window[i];1069 windowed[i] = input[i] * window[i];
1043 }1070 }
1044- for (k, slot) in out.iter_mut().enumerate() {1071+ for (k, row) in kernel.iter().enumerate() {
1045 let mut sum = 0.0f64;1072 let mut sum = 0.0f64;
1046 for (n, value) in windowed.iter().enumerate() {1073 for (n, value) in windowed.iter().enumerate() {
1047- let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64;1074+ sum += f64::from(*value) * f64::from(row[n]);
1048- sum += f64::from(*value) * angle.cos();
1049 }1075 }
1050- *slot = (sum / 9.0) as f32;1076+ out[k] = (sum / 9.0) as f32;
1051 }1077 }
1052 }1078 }
1053 1079
@@ -1055,13 +1081,13 @@ fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) {
1055 /// into the spectrum the way the decoder reads them back.1081 /// into the spectrum the way the decoder reads them back.
1056 fn mdct_short(input: &[f32; 36], out: &mut [f32]) {1082 fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
1057 let window = &windows()[2];1083 let window = &windows()[2];
1084+ let kernel = forward_mdct_short();
1058 for w in 0..3 {1085 for w in 0..3 {
1059- for k in 0..6 {1086+ for (k, row) in kernel.iter().enumerate() {
1060 let mut sum = 0.0f64;1087 let mut sum = 0.0f64;
1061 for n in 0..12 {1088 for n in 0..12 {
1062 let sample = input[6 + 6 * w + n] * window[n];1089 let sample = input[6 + 6 * w + n] * window[n];
1063- let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64;1090+ sum += f64::from(sample) * f64::from(row[n]);
1064- sum += f64::from(sample) * angle.cos();
1065 }1091 }
1066 out[k * 3 + w] = (sum / 3.0) as f32;1092 out[k * 3 + w] = (sum / 3.0) as f32;
1067 }1093 }
@@ -1103,7 +1129,7 @@ fn quantise_granule(
1103 if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) {1129 if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) {
1104 return (1130 return (
1105 CodedGranule {1131 CodedGranule {
1106- bits: Vec::new(),1132+ bits: BitBuf::new(),
1107 part2_3_length: 0,1133 part2_3_length: 0,
1108 big_values: 0,1134 big_values: 0,
1109 global_gain: 0,1135 global_gain: 0,
@@ -1211,29 +1237,35 @@ fn census(exit: (&str, usize)) {
1211 }1237 }
1212 }1238 }
1213 1239
1214-/// Bitstream order for a short block's spectrum.1240+/// Puts a spectrum into bitstream order in `out`.
1215 ///1241 ///
1216 /// A short granule is coded band by band, window by window, line by line,1242 /// A short granule is coded band by band, window by window, line by line,
1217 /// while the spectrum the transform produces interleaves the three windows on1243 /// while the spectrum the transform produces interleaves the three windows on
1218 /// every line — the decoder's reorder step. The encoder has to undo it before1244 /// every line — the decoder's reorder step. The encoder has to undo it before
1219 /// Huffman coding; writing spectral order instead costs exactly the same1245 /// Huffman coding; writing spectral order instead costs exactly the same
1220 /// number of bits, lands exactly on `part2_3_length`, and hands the decoder a1246 /// number of bits, lands exactly on `part2_3_length`, and hands the decoder a
1221-/// permuted granule, which comes back as noise.1247+/// permuted granule, which comes back as noise. A long block is already in
1222-fn short_reorder(sample_rate: u32, spectral: &[i32]) -> Vec<i32> {1248+/// order and is copied as is.
1249+fn recode_into(spectral: &[i32; 576], block_type: u8, sample_rate: u32, out: &mut [i32; 576]) {
1250+ if block_type != 2 {
1251+ *out = *spectral;
1252+ return;
1253+ }
1223 let widths = short_widths(sample_rate);1254 let widths = short_widths(sample_rate);
1224 let starts = short_starts(sample_rate);1255 let starts = short_starts(sample_rate);
1225- let mut out = Vec::with_capacity(576);1256+ let mut position = 0usize;
1226 for sfb in 0..13 {1257 for sfb in 0..13 {
1227 let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb]));1258 let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb]));
1228 for window in 0..3 {1259 for window in 0..3 {
1229 for line in 0..width {1260 for line in 0..width {
1230- let position = (start + line) * 3 + window;1261+ out[position] = spectral[(start + line) * 3 + window];
1231- out.push(spectral.get(position).copied().unwrap_or(0));1262+ position += 1;
1232 }1263 }
1233 }1264 }
1234 }1265 }
1235- out.resize(576, 0);1266+ for slot in out.iter_mut().skip(position) {
1236- out1267+ *slot = 0;
1268+ }
1237 }1269 }
1238 1270
1239 /// The largest scalefactor a band can actually carry.1271 /// The largest scalefactor a band can actually carry.
@@ -1273,6 +1305,13 @@ fn band_thresholds(threshold: &[f32], block_type: u8, sample_rate: u32) -> Vec<f
1273 1305
1274 /// Quantises with a fixed scalefactor set, running the rate loop on1306 /// Quantises with a fixed scalefactor set, running the rate loop on
1275 /// `global_gain`, and reports the noise each band ends up with.1307 /// `global_gain`, and reports the noise each band ends up with.
1308+///
1309+/// The rate loop judges every candidate gain by Huffman cost alone
1310+/// ([`plan_spectrum`]); the granule's bits are materialised exactly once,
1311+/// for the configuration the loop keeps ([`write_spectrum`]). Writing the
1312+/// bits per round — and re-expanding them into a `Vec<bool>` to hand them
1313+/// to the frame writer — was the largest single cost in the encoder's
1314+/// profile, and said nothing the cost pass had not already said.
1276 fn code_with(1315 fn code_with(
1277 xr: &[f32],1316 xr: &[f32],
1278 block_type: u8,1317 block_type: u8,
@@ -1298,21 +1337,17 @@ fn code_with(
1298 2101337 210
1299 };1338 };
1300 let mut gain = start.clamp(0, 255);1339 let mut gain = start.clamp(0, 255);
1301- let mut ix = vec![0i32; 576];1340+ let mut ix = [0i32; 576];
1302- let mut coded;1341+ let mut coding = [0i32; 576];
1303- // The rate loop runs both ways: down while there are bits to spare, up1342+ // A line that saturates the coding range is not "cheap", it is clipped;
1304- // while the granule is too big for them. A line that saturates the coding1343+ // the gain search below reads saturation as "does not fit".
1305- // range is not "cheap", it is clipped, so that check comes first.
1306 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);1344 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);
1307- let for_coding = |ix: &[i32]| -> Vec<i32> {1345+ let mut plan_of = |ix: &[i32; 576]| -> SpectrumPlan {
1308- if block_type == 2 {1346+ recode_into(ix, block_type, sample_rate, &mut coding);
1309- short_reorder(sample_rate, ix)1347+ plan_spectrum(&coding, block_type, sample_rate)
1310- } else {
1311- ix.to_vec()
1312- }
1313 };1348 };
1314 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);1349 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1315- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1350+ let mut coded = plan_of(&ix);
1316 if peak <= 1e-20 {1351 if peak <= 1e-20 {
1317 // Below the smallest representable level: every line quantises to1352 // Below the smallest representable level: every line quantises to
1318 // zero at any gain (the quantiser's scale multiplies zero either1353 // zero at any gain (the quantiser's scale multiplies zero either
@@ -1324,47 +1359,102 @@ fn code_with(
1324 // depend on gain.1359 // depend on gain.
1325 gain = 0;1360 gain = 0;
1326 } else {1361 } else {
1327- loop {1362+ // The rate loop wants the smallest gain whose granule fits the
1328- if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {1363+ // budget without clipping. A higher gain shrinks every quantised
1329- gain += 1;1364+ // line, and a smaller spectrum costs no more to code, so "fits" is
1330- quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);1365+ // monotone in the gain. This shipped as a one-step-at-a-time walk
1331- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1366+ // from the start estimate and paid ~31 quantise-plus-plan
1332- continue;1367+ // evaluations per granule; now the start estimate seeds a geometric
1368+ // straddle (doubling steps, so a boundary `d` gains away costs
1369+ // about 2·log2 d probes instead of d) followed by a bisection of
1370+ // the bracket. The walk's two hard stops stay: gain 255 stands even
1371+ // when it does not fit (the low-pass loop below trims the
1372+ // spectrum), and gain 0 is the quietest legal gain.
1373+ let mut probe_of = |g: i32, out: &mut [i32; 576]| -> (bool, SpectrumPlan) {
1374+ quantise(xr, g, scalefac, sample_rate, block_type, out);
1375+ let plan = plan_of(out);
1376+ (plan.cost <= target_bits && !saturated(out), plan)
1377+ };
1378+ let mut probe = [0i32; 576];
1379+ // `floor` is the largest gain known to miss, `ceil` the smallest
1380+ // known to fit; −1 stands for "even 0 misses would not matter", the
1381+ // gain-0 floor.
1382+ let mut floor = -1i32;
1383+ let mut ceil = 255i32;
1384+ let mut capped = false;
1385+ let first = start.clamp(0, 255);
1386+ let (fits, _) = probe_of(first, &mut probe);
1387+ if fits {
1388+ // The boundary is at or below the estimate: stride down until a
1389+ // gain misses.
1390+ ceil = first;
1391+ let mut step = 1i32;
1392+ while ceil > 0 {
1393+ let next = (ceil - step).max(0);
1394+ let (next_fits, _) = probe_of(next, &mut probe);
1395+ if !next_fits {
1396+ floor = next;
1397+ break;
1398+ }
1399+ ceil = next;
1400+ step *= 2;
1333 }1401 }
1334- if saturated(&ix) || coded.0 > target_bits || gain == 0 {1402+ } else {
1335- break;1403+ // The boundary is above the estimate: stride up until a gain
1404+ // fits, honouring the walk's 255 cap.
1405+ floor = first;
1406+ let mut step = 1i32;
1407+ loop {
1408+ let next = (floor + step).min(255);
1409+ let (next_fits, _) = probe_of(next, &mut probe);
1410+ if next_fits {
1411+ ceil = next;
1412+ break;
1413+ }
1414+ floor = next;
1415+ if next == 255 {
1416+ capped = true;
1417+ break;
1418+ }
1419+ step *= 2;
1336 }1420 }
1337- // Try one step quieter; keep it only if it still fits and stays1421+ }
1338- // inside the coding range.1422+ while ceil - floor > 1 {
1339- let mut trial = ix.clone();1423+ let mid = (floor + ceil) / 2;
1340- quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);1424+ let (mid_fits, _) = probe_of(mid, &mut probe);
1341- let trial_coded = code_spectrum(&for_coding(&trial), block_type, sample_rate);1425+ if mid_fits {
1342- if trial_coded.0 > target_bits || saturated(&trial) {1426+ ceil = mid;
1343- break;1427+ } else {
1428+ floor = mid;
1344 }1429 }
1345- gain -= 1;
1346- ix = trial;
1347- coded = trial_coded;
1348 }1430 }
1431+ gain = if capped { 255 } else { ceil };
1432+ let (_, plan) = probe_of(gain, &mut probe);
1433+ ix = probe;
1434+ coded = plan;
1349 }1435 }
1350 // Last resort: if even the quietest legal gain will not fit the bits we1436 // Last resort: if even the quietest legal gain will not fit the bits we
1351 // were given, drop the top of the spectrum until it does. A granule that1437 // were given, drop the top of the spectrum until it does. A granule that
1352 // overruns its budget would corrupt the reservoir for every frame after1438 // overruns its budget would corrupt the reservoir for every frame after
1353 // it, which is far worse than a low-passed one.1439 // it, which is far worse than a low-passed one.
1354 let mut limit = 576usize;1440 let mut limit = 576usize;
1355- while coded.0 > target_bits && limit > 4 {1441+ while coded.cost > target_bits && limit > 4 {
1356 limit = limit * 3 / 4;1442 limit = limit * 3 / 4;
1357 for slot in ix.iter_mut().skip(limit) {1443 for slot in ix.iter_mut().skip(limit) {
1358 *slot = 0;1444 *slot = 0;
1359 }1445 }
1360- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1446+ coded = plan_of(&ix);
1361 }1447 }
1362- let (_, big_values, tables, region0, region1, count1_select, bits) = coded;
1363 let mut noise = [0.0f32; SFB_LONG];1448 let mut noise = [0.0f32; SFB_LONG];
1364 let power = power43();1449 let power = power43();
1450+ // One band gain per band, not one per line: the residual ran an exp2 for
1451+ // every spectral line of the granule.
1452+ let mut scales = [0.0f32; SFB_LONG];
1453+ for (band, slot) in scales.iter_mut().enumerate() {
1454+ *slot = band_gain(gain, scalefac[band], block_type);
1455+ }
1365 let residual = |i: usize, band: usize| -> f32 {1456 let residual = |i: usize, band: usize| -> f32 {
1366- let scale = band_gain(gain, scalefac[band], block_type);1457+ let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scales[band];
1367- let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale;
1368 let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };1458 let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
1369 (xr[i] - reconstructed).powi(2)1459 (xr[i] - reconstructed).powi(2)
1370 };1460 };
@@ -1384,41 +1474,38 @@ fn code_with(
1384 noise[band] = sum;1474 noise[band] = sum;
1385 }1475 }
1386 }1476 }
1387- let mut out = BitWriter::new();1477+ // Materialise the granule: scalefactors, then the spectrum the plan
1478+ // chose, in bitstream order.
1479+ recode_into(&ix, block_type, sample_rate, &mut coding);
1480+ let mut bits = BitBuf::new();
1388 if block_type == 2 {1481 if block_type == 2 {
1389 // The decoder reads short scalefactors band-major, three windows at a1482 // The decoder reads short scalefactors band-major, three windows at a
1390 // time; ours are one per band, so each is written three times.1483 // time; ours are one per band, so each is written three times.
1391 for (band, value) in scalefac.iter().enumerate().take(12) {1484 for (band, value) in scalefac.iter().enumerate().take(12) {
1392 let slen = if band < 6 { slen1 } else { slen2 };1485 let slen = if band < 6 { slen1 } else { slen2 };
1393 for _window in 0..3 {1486 for _window in 0..3 {
1394- out.write_bits(u32::from(*value), slen);1487+ bits.push_bits(u64::from(*value), slen);
1395 }1488 }
1396 }1489 }
1397 } else {1490 } else {
1398 for (band, value) in scalefac.iter().enumerate() {1491 for (band, value) in scalefac.iter().enumerate() {
1399 let slen = if band < 11 { slen1 } else { slen2 };1492 let slen = if band < 11 { slen1 } else { slen2 };
1400- out.write_bits(u32::from(*value), slen);1493+ bits.push_bits(u64::from(*value), slen);
1401 }1494 }
1402 }1495 }
1403- let scalefac_bits = out.bit_len() as u32;1496+ write_spectrum(&coded, &coding, &mut bits);
1404- let mut bits_out: Vec<bool> = Vec::with_capacity((scalefac_bits + bits.len() as u32) as usize);
1405- let bytes = out.into_bytes();
1406- for i in 0..scalefac_bits as usize {
1407- bits_out.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
1408- }
1409- bits_out.extend_from_slice(&bits);
1410 let granule = CodedGranule {1497 let granule = CodedGranule {
1411- part2_3_length: bits_out.len() as u32,1498+ part2_3_length: bits.bit_len(),
1412- bits: bits_out,1499+ bits,
1413- big_values,1500+ big_values: coded.big_values,
1414 global_gain: gain as u32,1501 global_gain: gain as u32,
1415 scalefac_compress: compress,1502 scalefac_compress: compress,
1416 block_type,1503 block_type,
1417- table_select: tables,1504+ table_select: coded.tables,
1418- region0_count: region0,1505+ region0_count: coded.region0,
1419- region1_count: region1,1506+ region1_count: coded.region1,
1420 scalefac_scale: false,1507 scalefac_scale: false,
1421- count1table_select: count1_select,1508+ count1table_select: coded.count1_select,
1422 };1509 };
1423 (granule, noise)1510 (granule, noise)
1424 }1511 }
@@ -1437,19 +1524,32 @@ fn quantise(
1437 block_type: u8,1524 block_type: u8,
1438 ix: &mut [i32],1525 ix: &mut [i32],
1439 ) {1526 ) {
1527+ // The scalar form, kept for spans shorter than one SIMD width.
1440 let quantise_line = |xr: f32, scale: f32| -> i32 {1528 let quantise_line = |xr: f32, scale: f32| -> i32 {
1441- let value = (xr.abs() * scale).powf(0.75);1529+ let x = f64::from(xr.abs()) * f64::from(scale);
1442- let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32;1530+ let value = (x * x * x).sqrt().sqrt();
1531+ let magnitude = (value + 0.4054).min(MAX_QUANT as f64) as i32;
1443 if xr < 0.0 { -magnitude } else { magnitude }1532 if xr < 0.0 { -magnitude } else { magnitude }
1444 };1533 };
1445 if block_type == 2 {1534 if block_type == 2 {
1446 // Short blocks: twelve bands, each with its own scalefactor shared by1535 // Short blocks: twelve bands, each with its own scalefactor shared by
1447 // the three windows. Without them the quantiser's noise is flat across1536 // the three windows. Without them the quantiser's noise is flat across
1448 // the spectrum, which is what made a switched granule the worst-coded1537 // the spectrum, which is what made a switched granule the worst-coded
1449- // one in the stream.1538+ // one in the stream. One band gain per band, not one per line: the
1450- for (i, slot) in ix.iter_mut().enumerate().take(576) {1539+ // interleaved layout means a line's band search ran 576 exp2 calls
1451- let scale = 1.0 / band_gain(gain, scalefac[short_band(i, sample_rate)], block_type);1540+ // and 576 linear band searches per quantisation.
1452- *slot = quantise_line(xr[i], scale);1541+ let short = short_starts(sample_rate);
1542+ let mut scales = [0.0f32; 13];
1543+ for (band, slot) in scales.iter_mut().enumerate() {
1544+ *slot = 1.0 / band_gain(gain, scalefac[band], block_type);
1545+ }
1546+ for band in 0..13 {
1547+ let (from, to) = (
1548+ usize::from(short[band]) * 3,
1549+ usize::from(short[band + 1]) * 3,
1550+ );
1551+ let scale = scales[band];
1552+ quantise_span(xr, ix, from, to.min(576), scale, &quantise_line);
1453 }1553 }
1454 return;1554 return;
1455 }1555 }
@@ -1463,10 +1563,47 @@ fn quantise(
1463 );1563 );
1464 let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };1564 let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };
1465 let scale = 1.0 / band_gain(gain, scalefac, block_type);1565 let scale = 1.0 / band_gain(gain, scalefac, block_type);
1466- for i in from..to {1566+ quantise_span(xr, ix, from, to, scale, &quantise_line);
1467- ix[i] = quantise_line(xr[i], scale);1567+ }
1568+}
1569+
1570+/// Quantises `xr[from..to]` at `scale` into `ix[from..to]`, eight lanes at a
1571+/// time through `wide` — the per-line curve the scalar closure carries out
1572+/// one line per call. Overflow lanes to `inf`, which the `MAX_QUANT` clamp
1573+/// folds back the same way the scalar path clamps a saturated line; the
1574+/// signed value truncates toward zero, exactly the sign-and-floor the scalar
1575+/// form does in two steps. Levels can differ from the scalar path by one
1576+/// step where the true level sits within f32 rounding of a boundary; the
1577+/// decoded-quality gate exists for exactly that.
1578+fn quantise_span(
1579+ xr: &[f32],
1580+ ix: &mut [i32],
1581+ from: usize,
1582+ to: usize,
1583+ scale: f32,
1584+ scalar: &impl Fn(f32, f32) -> i32,
1585+) {
1586+ let mut i = from;
1587+ if to - i >= 8 {
1588+ let vscale = f32x8::splat(scale);
1589+ let voff = f32x8::splat(0.4054);
1590+ let vmax = f32x8::splat(MAX_QUANT as f32);
1591+ while i + 8 <= to {
1592+ let mut block = [0.0f32; 8];
1593+ block.copy_from_slice(&xr[i..i + 8]);
1594+ let v = f32x8::new(block);
1595+ let x = v.abs() * vscale;
1596+ let value = (x * x * x).sqrt().sqrt();
1597+ let magnitude = (value + voff).min(vmax);
1598+ let ints = magnitude.copysign(v).trunc_int();
1599+ ix[i..i + 8].copy_from_slice(&ints.to_array());
1600+ i += 8;
1468 }1601 }
1469 }1602 }
1603+ while i < to {
1604+ ix[i] = scalar(xr[i], scale);
1605+ i += 1;
1606+ }
1470 }1607 }
1471 1608
1472 /// The short scalefactor band a spectral line belongs to. Short-block spectra1609 /// The short scalefactor band a spectral line belongs to. Short-block spectra
@@ -1481,14 +1618,29 @@ fn short_band(index: usize, sample_rate: u32) -> usize {
1481 .unwrap_or(0)1618 .unwrap_or(0)
1482 }1619 }
1483 1620
1484-/// Chooses the region split, the tables and the count1 boundary, and writes the1621+/// The coding a spectrum gets: region split, tables, count1 boundary, and
1485-/// spectrum. Returns the bit cost first so the rate loop can stop early.1622+/// the bit cost the rate loop judges candidate gains by.
1486-#[allow(clippy::type_complexity)]1623+#[derive(Clone, Copy, Debug)]
1487-fn code_spectrum(1624+struct SpectrumPlan {
1488- ix: &[i32],1625+ cost: u32,
1626+ big_values: u32,
1627+ tables: [u8; 3],
1628+ region0: u32,
1629+ region1: u32,
1630+ count1_select: bool,
1631+ bounds: [usize; 3],
1632+ big_end: usize,
1633+ count1_end: usize,
1634+}
1635+
1636+/// Trailing zeros, the count1 boundary, and the region split for a coded
1637+/// spectrum, in bitstream order. The planner and the writer read these off
1638+/// one structure so both see the same boundaries.
1639+fn regions(
1640+ ix: &[i32; 576],
1489 block_type: u8,1641 block_type: u8,
1490 sample_rate: u32,1642 sample_rate: u32,
1491-) -> (u32, u32, [u8; 3], u32, u32, bool, Vec<bool>) {1643+) -> (u32, u32, [usize; 3], usize, usize) {
1492 // Trailing zeros are not coded at all; before them, a run of values in1644 // Trailing zeros are not coded at all; before them, a run of values in
1493 // -1..=1 is coded four at a time.1645 // -1..=1 is coded four at a time.
1494 let mut rzero = 576;1646 let mut rzero = 576;
@@ -1539,55 +1691,77 @@ fn code_spectrum(
1539 (r0 as u32, r1 as u32, [a, b.max(a), big_end])1691 (r0 as u32, r1 as u32, [a, b.max(a), big_end])
1540 }1692 }
1541 };1693 };
1694+ (region0, region1, bounds, big_end, count1_end)
1695+}
1542 1696
1697+/// Chooses the region split, the tables and the count1 boundary, and prices
1698+/// the spectrum. The rate loop calls this for every candidate gain; only the
1699+/// configuration it keeps is ever written ([`write_spectrum`]).
1700+fn plan_spectrum(ix: &[i32; 576], block_type: u8, sample_rate: u32) -> SpectrumPlan {
1701+ let (region0, region1, bounds, big_end, count1_end) = regions(ix, block_type, sample_rate);
1543 let mut tables = [0u8; 3];1702 let mut tables = [0u8; 3];
1544- let mut writer = BitWriter::new();1703+ let mut cost = 0u32;
1545 let mut from = 0usize;1704 let mut from = 0usize;
1546 for (region, to) in bounds.iter().enumerate() {1705 for (region, to) in bounds.iter().enumerate() {
1547 let to = (*to).min(big_end);1706 let to = (*to).min(big_end);
1548 if to > from {1707 if to > from {
1549- let select = best_table(ix, from, to);1708+ let (select, region_cost) = best_table_cost(ix, from, to);
1550 tables[region] = select;1709 tables[region] = select;
1551- let table = huffman::big_table(usize::from(select)).expect("table exists");1710+ cost += region_cost;
1552- let mut i = from;
1553- while i + 1 < to {
1554- huffman::write_pair(&mut writer, table, ix[i], ix[i + 1]);
1555- i += 2;
1556- }
1557 }1711 }
1558 from = to;1712 from = to;
1559 }1713 }
1560 // count1: try both tables, keep the cheaper.1714 // count1: try both tables, keep the cheaper.
1561- let quads: Vec<[i32; 4]> = (big_end..count1_end)1715+ let quads_cost = |select: bool| -> u32 {
1562- .step_by(4)1716+ let mut sum = 0;
1563- .filter(|i| i + 4 <= 576)1717+ let mut i = big_end;
1564- .map(|i| [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]])1718+ while i + 4 <= count1_end {
1565- .collect();1719+ sum += huffman::quad_bits(select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]);
1566- let cost = |select: bool| -> u32 {1720+ i += 4;
1567- quads1721+ }
1568- .iter()1722+ sum
1569- .map(|quad| huffman::quad_bits(select, *quad))
1570- .sum()
1571 };1723 };
1572- let count1_select = cost(true) < cost(false);1724+ let count1_select = quads_cost(true) < quads_cost(false);
1573- for quad in &quads {1725+ cost += quads_cost(count1_select);
1574- huffman::write_quad(&mut writer, count1_select, *quad);1726+ SpectrumPlan {
1575- }1727+ cost,
1576- let bit_len = writer.bit_len() as usize;1728+ big_values: (big_end / 2) as u32,
1577- let bytes = writer.into_bytes();
1578- let mut bits = Vec::with_capacity(bit_len);
1579- for i in 0..bit_len {
1580- bits.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
1581- }
1582- (
1583- bits.len() as u32,
1584- (big_end / 2) as u32,
1585 tables,1729 tables,
1586 region0,1730 region0,
1587 region1,1731 region1,
1588 count1_select,1732 count1_select,
1589- bits,1733+ bounds,
1590- )1734+ big_end,
1735+ count1_end,
1736+ }
1737+}
1738+
1739+/// Writes the coded spectrum the plan names into `out`, pairs and quadruples
1740+/// in bitstream order. `ix` is the spectrum in bitstream order, the same
1741+/// array the plan was computed from.
1742+fn write_spectrum(plan: &SpectrumPlan, ix: &[i32; 576], out: &mut BitBuf) {
1743+ let mut from = 0usize;
1744+ for (region, to) in plan.bounds.iter().enumerate() {
1745+ let to = (*to).min(plan.big_end);
1746+ if to > from {
1747+ let table = huffman::big_table(usize::from(plan.tables[region])).expect("table exists");
1748+ let mut i = from;
1749+ while i + 1 < to {
1750+ huffman::write_pair(out, table, ix[i], ix[i + 1]);
1751+ i += 2;
1752+ }
1753+ }
1754+ from = to;
1755+ }
1756+ let mut i = plan.big_end;
1757+ while i + 4 <= plan.count1_end {
1758+ huffman::write_quad(
1759+ out,
1760+ plan.count1_select,
1761+ [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]],
1762+ );
1763+ i += 4;
1764+ }
1591 }1765 }
1592 1766
1593 /// Tables that can code a region whose largest magnitude is `max`, cheapest1767 /// Tables that can code a region whose largest magnitude is `max`, cheapest
@@ -1611,40 +1785,102 @@ fn candidates(max: u32) -> &'static [u8] {
1611 }1785 }
1612 }1786 }
1613 1787
1614-/// The cheapest table for one region.1788+/// The cheapest table for one region, with its cost.
1615-fn best_table(ix: &[i32], from: usize, to: usize) -> u8 {1789+///
1616- let max = ix[from..to]1790+/// One walk over the pairs accumulates every shortlisted candidate's cost at
1617- .iter()1791+/// once; the former shape — a full `pair_bits` pass per candidate, up to nine
1618- .map(|v| v.unsigned_abs())1792+/// walks over the same pairs — was half of the encoder's remaining runtime.
1619- .max()1793+/// A candidate any pair falls outside dies on the spot, exactly as the
1620- .unwrap_or(0);1794+/// per-candidate `pair_bits` propagation did, and ties keep the earlier
1621- let mut best = (u32::MAX, 0u8);1795+/// (nominally cheaper) candidate, as the strict less-than did.
1622- for &select in candidates(max) {1796+fn best_table_cost(ix: &[i32], from: usize, to: usize) -> (u8, u32) {
1797+ let mut max = 0u32;
1798+ for &v in &ix[from..to] {
1799+ max = max.max(v.unsigned_abs());
1800+ }
1801+ let shortlist = candidates(max);
1802+ // Per-candidate state, fetched once: the table, its escape shape, the
1803+ // cost of a (0, 0) pair, and a running cost. A candidate the region's
1804+ // largest magnitude falls outside is dropped before the walk — exactly
1805+ // what the per-pair range check did, since some pair carries `max`.
1806+ let mut tables = [None; 9];
1807+ let mut tmax = [0u32; 9];
1808+ let mut linbits = [0u32; 9];
1809+ let mut dim = [0u32; 9];
1810+ let mut zero_bits = [0u32; 9];
1811+ let mut feasible = [false; 9];
1812+ let mut costs = [0u32; 9];
1813+ let mut live = 0usize;
1814+ for (slot, &select) in shortlist.iter().enumerate() {
1623 let Ok(table) = huffman::big_table(usize::from(select)) else {1815 let Ok(table) = huffman::big_table(usize::from(select)) else {
1624 continue;1816 continue;
1625 };1817 };
1626- if let Some(cost) = table_cost(ix, from, to, table)1818+ let cap = u32::from(table.dim) - 1;
1627- && cost < best.01819+ let escape = table.linbits > 0;
1628- {1820+ let reach = cap + if escape { (1 << table.linbits) - 1 } else { 0 };
1629- best = (cost, select);1821+ if max > reach {
1822+ continue;
1823+ }
1824+ tables[slot] = Some(table);
1825+ tmax[slot] = cap;
1826+ linbits[slot] = if escape { u32::from(table.linbits) } else { 0 };
1827+ dim[slot] = u32::from(table.dim);
1828+ zero_bits[slot] = u32::from(table.codes[0].0);
1829+ feasible[slot] = true;
1830+ live += 1;
1831+ }
1832+ let mut i = from;
1833+ while i + 1 < to && live > 0 {
1834+ let (x, y) = (ix[i].unsigned_abs(), ix[i + 1].unsigned_abs());
1835+ if x == 0 && y == 0 {
1836+ for slot in 0..shortlist.len() {
1837+ if feasible[slot] {
1838+ costs[slot] += zero_bits[slot];
1839+ }
1840+ }
1841+ i += 2;
1842+ continue;
1843+ }
1844+ let signs = u32::from(x != 0) + u32::from(y != 0);
1845+ for slot in 0..shortlist.len() {
1846+ if !feasible[slot] {
1847+ continue;
1848+ }
1849+ let table = tables[slot].expect("feasible candidates hold a table");
1850+ let (cap, lin) = (tmax[slot], linbits[slot]);
1851+ let (len, _) = table.codes[(x.min(cap) * dim[slot] + y.min(cap)) as usize];
1852+ if len == 0 {
1853+ // A hole in the table: this candidate cannot code the pair,
1854+ // so it is out for the whole region.
1855+ feasible[slot] = false;
1856+ live -= 1;
1857+ continue;
1858+ }
1859+ let mut bits = u32::from(len) + signs;
1860+ if lin > 0 {
1861+ if x >= cap {
1862+ bits += lin;
1863+ }
1864+ if y >= cap {
1865+ bits += lin;
1866+ }
1867+ }
1868+ costs[slot] += bits;
1869+ }
1870+ i += 2;
1871+ }
1872+ let mut best = (u32::MAX, 0u8);
1873+ for (slot, &select) in shortlist.iter().enumerate() {
1874+ if feasible[slot] && costs[slot] < best.0 {
1875+ best = (costs[slot], select);
1630 }1876 }
1631 }1877 }
1632 if best.1 == 0 {1878 if best.1 == 0 {
1633 // Nothing in the shortlist fits, which only a value above the coding1879 // Nothing in the shortlist fits, which only a value above the coding
1634 // range can cause; fall back to the widest escape table.1880 // range can cause; fall back to the widest escape table.
1635- return 23;1881+ return (23, 0);
1636- }
1637- best.1
1638-}
1639-
1640-fn table_cost(ix: &[i32], from: usize, to: usize, table: Table) -> Option<u32> {
1641- let mut sum = 0;
1642- let mut i = from;
1643- while i + 1 < to {
1644- sum += huffman::pair_bits(table, ix[i].unsigned_abs(), ix[i + 1].unsigned_abs())?;
1645- i += 2;
1646 }1882 }
1647- Some(sum)1883+ (best.1, best.0)
1648 }1884 }
1649 1885
1650 /// The `scalefac_compress` index whose two lengths hold these scalefactors.1886 /// The `scalefac_compress` index whose two lengths hold these scalefactors.
crates/ec-mp3/src/huffman.rsmodified+89 -29
@@ -2,7 +2,7 @@
2 //! process, and the encoder's cost/write side.2 //! process, and the encoder's cost/write side.
3 3
4 use crate::huffman_tables::*;4 use crate::huffman_tables::*;
5-use ec_core::bitio::{BitReader, BitWriter};5+use ec_core::bitio::BitReader;
6 use ec_core::error::{Error, Result};6 use ec_core::error::{Error, Result};
7 use std::sync::OnceLock;7 use std::sync::OnceLock;
8 8
@@ -175,47 +175,107 @@ pub(crate) fn decode_quad(
175 Ok(())175 Ok(())
176 }176 }
177 177
178-/// Bits one pair costs in `table`, or `None` when the pair is out of range.178+/// A byte-backed bit accumulator for the granule coder: the same MSB-first
179-pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> {179+/// convention as [`ec_core::bitio::BitWriter`], but buffering through a `u64`
180- let max = u32::from(table.dim) - 1;180+/// accumulator and appending whole bit runs, so a granule's Huffman codes and
181- let escape = u32::from(table.linbits) > 0;181+/// its splice into the main-data stream stop costing one call per bit.
182- let (ix, iy) = (x.min(max), y.min(max));182+///
183- if (x > max && !escape) || (y > max && !escape) {183+/// The encoder's profile was ~45% inside `BitWriter::write_bit`'s per-bit
184- return None;184+/// branch-store cycle (plus the `Vec<bool>` materialisation every rate-loop
185+/// round paid to hand granule bits up to the frame writer); this is the same
186+/// bitstream, emitted a word at a time.
187+#[derive(Clone, Debug, Default)]
188+pub(crate) struct BitBuf {
189+ /// Completed bytes.
190+ bytes: Vec<u8>,
191+ /// Pending bits, top-aligned in the accumulator (`used < 8`).
192+ acc: u64,
193+ used: u32,
194+}
195+
196+impl BitBuf {
197+ /// An empty buffer.
198+ pub(crate) fn new() -> BitBuf {
199+ BitBuf::default()
185 }200 }
186- if escape && (x > max + (1 << table.linbits) - 1 || y > max + (1 << table.linbits) - 1) {201+
187- return None;202+ /// Bits written so far.
203+ pub(crate) fn bit_len(&self) -> u32 {
204+ (self.bytes.len() as u32) * 8 + self.used
188 }205 }
189- let (len, _) = table.codes[(ix * u32::from(table.dim) + iy) as usize];206+
190- if len == 0 && !(x == 0 && y == 0) {207+ /// Appends the low `n` bits of `value` (`n <= 64`), most significant first.
191- return None;208+ pub(crate) fn push_bits(&mut self, value: u64, n: u32) {
209+ debug_assert!(n <= 64, "push_bits: n = {n} > 64");
210+ let mask = if n >= 64 { u64::MAX } else { (1u64 << n) - 1 };
211+ self.acc |= (value & mask) << (64 - self.used - n);
212+ self.used += n;
213+ while self.used >= 8 {
214+ self.bytes.push((self.acc >> 56) as u8);
215+ self.acc <<= 8;
216+ self.used -= 8;
217+ }
192 }218 }
193- let mut bits = u32::from(len);219+
194- for value in [x, y] {220+ /// Appends one bit.
195- if value >= max && escape {221+ pub(crate) fn push_bit(&mut self, bit: bool) {
196- bits += u32::from(table.linbits);222+ if bit {
223+ self.acc |= 1u64 << (63 - self.used);
197 }224 }
198- if value != 0 {225+ self.used += 1;
199- bits += 1;226+ if self.used == 8 {
227+ self.bytes.push((self.acc >> 56) as u8);
228+ self.acc = 0;
229+ self.used = 0;
230+ }
231+ }
232+
233+ /// Appends the first `nbits` of `src`, most significant first — the bulk
234+ /// path a granule's bits take into the frame's main-data stream.
235+ pub(crate) fn push_bits_from(&mut self, src: &[u8], nbits: u32) {
236+ let mut bit = 0;
237+ while bit < nbits {
238+ let take = (nbits - bit).min(8);
239+ let byte = src[(bit / 8) as usize];
240+ let off = bit % 8;
241+ let value = u64::from(byte >> (8 - off - take)) & ((1u64 << take) - 1);
242+ self.push_bits(value, take);
243+ bit += take;
244+ }
245+ }
246+
247+ /// Appends every bit of `other`.
248+ pub(crate) fn append(&mut self, other: &BitBuf) {
249+ self.push_bits_from(&other.bytes, (other.bytes.len() as u32) * 8);
250+ if other.used > 0 {
251+ self.push_bits(other.acc >> (64 - other.used), other.used);
252+ }
253+ }
254+
255+ /// Zero-pads to the byte boundary and hands back the bytes, the partial
256+ /// byte's unused low bits zero — exactly what `BitWriter` produces.
257+ pub(crate) fn into_bytes(mut self) -> Vec<u8> {
258+ if self.used > 0 {
259+ self.bytes.push((self.acc >> 56) as u8);
200 }260 }
261+ self.bytes
201 }262 }
202- Some(bits)
203 }263 }
204 264
205 /// Writes one pair; the caller has already checked it fits the table.265 /// Writes one pair; the caller has already checked it fits the table.
206-pub(crate) fn write_pair(writer: &mut BitWriter, table: Table, x: i32, y: i32) {266+pub(crate) fn write_pair(writer: &mut BitBuf, table: Table, x: i32, y: i32) {
207 let max = u32::from(table.dim) - 1;267 let max = u32::from(table.dim) - 1;
208 let escape = table.linbits > 0;268 let escape = table.linbits > 0;
209 let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs());269 let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs());
210 let (ix, iy) = (ax.min(max), ay.min(max));270 let (ix, iy) = (ax.min(max), ay.min(max));
211 let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize];271 let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize];
212- writer.write_bits(u32::from(code), u32::from(len));272+ writer.push_bits(u64::from(code), u32::from(len));
213 for (value, abs) in [(x, ax), (y, ay)] {273 for (value, abs) in [(x, ax), (y, ay)] {
214 if abs >= max && escape {274 if abs >= max && escape {
215- writer.write_bits(abs - max, u32::from(table.linbits));275+ writer.push_bits(u64::from(abs - max), u32::from(table.linbits));
216 }276 }
217 if abs != 0 {277 if abs != 0 {
218- writer.write_bit(value < 0);278+ writer.push_bit(value < 0);
219 }279 }
220 }280 }
221 }281 }
@@ -230,15 +290,15 @@ pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 {
230 }290 }
231 291
232 /// Writes one count1 quadruple.292 /// Writes one count1 quadruple.
233-pub(crate) fn write_quad(writer: &mut BitWriter, select: bool, quad: [i32; 4]) {293+pub(crate) fn write_quad(writer: &mut BitBuf, select: bool, quad: [i32; 4]) {
234 let index = quad294 let index = quad
235 .iter()295 .iter()
236 .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));296 .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));
237 let (len, code) = count1_table(select)[index];297 let (len, code) = count1_table(select)[index];
238- writer.write_bits(u32::from(code), u32::from(len));298+ writer.push_bits(u64::from(code), u32::from(len));
239 for value in quad {299 for value in quad {
240 if value != 0 {300 if value != 0 {
241- writer.write_bit(value < 0);301+ writer.push_bit(value < 0);
242 }302 }
243 }303 }
244 }304 }
@@ -299,7 +359,7 @@ mod tests {
299 continue;359 continue;
300 }360 }
301 let max = u32::from(table.dim) - 1;361 let max = u32::from(table.dim) - 1;
302- let mut writer = BitWriter::new();362+ let mut writer = BitBuf::new();
303 let mut wanted = Vec::new();363 let mut wanted = Vec::new();
304 for x in 0..=max {364 for x in 0..=max {
305 for y in 0..=max {365 for y in 0..=max {
@@ -321,7 +381,7 @@ mod tests {
321 #[test]381 #[test]
322 fn quads_round_trip() {382 fn quads_round_trip() {
323 for select in [false, true] {383 for select in [false, true] {
324- let mut writer = BitWriter::new();384+ let mut writer = BitBuf::new();
325 let mut wanted = Vec::new();385 let mut wanted = Vec::new();
326 for index in 0..16 {386 for index in 0..16 {
327 let quad = [387 let quad = [
crates/ec-mp3/src/tables.rsmodified+40 -1
@@ -7,7 +7,7 @@
7 //! band attenuated at a time), which is also why they are stated as widths: a7 //! band attenuated at a time), which is also why they are stated as widths: a
8 //! width table cannot silently disagree with itself about where 576 ends.8 //! width table cannot silently disagree with itself about where 576 ends.
9 9
10-use std::sync::OnceLock;10+use std::sync::{LazyLock, OnceLock};
11 11
12 /// Widths of the 22 long scalefactor bands, by sample rate.12 /// Widths of the 22 long scalefactor bands, by sample rate.
13 pub(crate) fn long_widths(sample_rate: u32) -> &'static [u16; 22] {13 pub(crate) fn long_widths(sample_rate: u32) -> &'static [u16; 22] {
@@ -175,6 +175,45 @@ pub(crate) fn alias_coefficients() -> &'static [(f32, f32); 8] {
175 })175 })
176 }176 }
177 177
178+/// The forward MDCT's cosine kernel, `cos(pi/72 · (2n+19)(2k+1))`, laid out
179+/// `[k][n]` so each of the 18 output coefficients of a long block is one dot
180+/// product. The encoder recomputed these with libm for every subband of
181+/// every granule — 23% of its runtime — where the decoder has had its
182+/// inverse table since it was written.
183+static FORWARD_MDCT_LONG: LazyLock<[[f32; 36]; 18]> = LazyLock::new(|| {
184+ let mut table = [[0.0f32; 36]; 18];
185+ for (k, row) in table.iter_mut().enumerate() {
186+ for (n, slot) in row.iter_mut().enumerate() {
187+ let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64;
188+ *slot = angle.cos() as f32;
189+ }
190+ }
191+ table
192+});
193+
194+/// The forward MDCT kernel for a long block.
195+pub(crate) fn forward_mdct_long() -> &'static [[f32; 36]; 18] {
196+ &FORWARD_MDCT_LONG
197+}
198+
199+/// The short-block kernel, `cos(pi/24 · (2n+7)(2k+1))`, laid out `[k][n]`
200+/// for one 12-sample window; the three windows share it at 6-sample offsets.
201+static FORWARD_MDCT_SHORT: LazyLock<[[f32; 12]; 6]> = LazyLock::new(|| {
202+ let mut table = [[0.0f32; 12]; 6];
203+ for (k, row) in table.iter_mut().enumerate() {
204+ for (n, slot) in row.iter_mut().enumerate() {
205+ let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64;
206+ *slot = angle.cos() as f32;
207+ }
208+ }
209+ table
210+});
211+
212+/// The forward MDCT kernel for one short window.
213+pub(crate) fn forward_mdct_short() -> &'static [[f32; 12]; 6] {
214+ &FORWARD_MDCT_SHORT
215+}
216+
178 #[cfg(test)]217 #[cfg(test)]
179 mod tests {218 mod tests {
180 use super::*;219 use super::*;
lanes/mp3perf-r1.report.mdadded+111 -0
@@ -0,0 +1,111 @@
1+# lane-mp3-perf — ec-mp3 encode speed vs the incumbent MP3 encoder 0.6.1 (r1)
2+
3+Charter: close the ec-mp3 ENCODE gap (the seat went out at ~7-8x realtime stereo
4+CBR against the incumbent's 147-283x single-thread; a 2 h film's stereo track
5+cost ~17 min of export wall). Branch lane-mp3-perf off 0d81d6c5.
6+Worktree-only; no merges, no pushes.
7+
8+## Method
9+
10+- A/B harness: `~/Documents/Code/Rust/mp3-perf-ab` (scratch crate outside the
11+ family workspace, opus-perf precedent — it links the crates.io incumbent
12+ 0.6.1 beside ec-mp3 by path into this worktree; the workspace shim carries
13+ the same crate name so this cannot live inside).
14+- PCM: deterministic synthesized music (3 s stereo 44.1 k), a 1 kHz tone
15+ (3 s mono 48 k), 30 s of the 44.1 k stereo music the family gates use, and
16+ the crate's own mp3src fixtures — all cached as raw interleaved f32, both
17+ engines fed byte-identical bytes in-process.
18+- Protocol per row: one warm-up each side, 7 alternating rounds (A/B and B/A
19+ by round parity), min per side, /proc/loadavg per round. Single-threaded
20+ both sides (the incumbent is thread_local-only).
21+- Quality gate per commit: the crate's own release suite (21 lib + decode
22+ matrix + encode matrix) green, every fixture decoded through ffmpeg, and
23+ aligned correlation vs source compared to the pre-change build on the same
24+ PCM. Byte-identity of the encoded stream was the stronger check wherever it
25+ held (it held everywhere except where noted).
26+
27+## Baseline (0d81d6c5, load 1.8-2.2)
28+
29+| row | ec-mp3 | incumbent | ratio |
30+|---|---|---|---|
31+| music3s cbr192 | 239.0 ms / 12.6x | 23.0 ms / 130.6x | 0.096 |
32+| real30s cbr192 | 3661.2 ms / 8.2x | 190.1 ms / 157.8x | 0.052 |
33+| tone48k cbr192 mono | 106.3 ms / 28.2x | 7.8 ms / 385.6x | 0.073 |
34+| real30s vbr | 7540.3 ms / 4.0x | 189.5 ms / 158.3x | 0.025 |
35+
36+(ec VBR = quality 0.5 on its own scale; the incumbent's VBR takes a target
37+mean kbit/s, so that row passes 190 on its side — roughly rate-matched.)
38+
39+## Profile at baseline, and what each step did
40+
41+Order of attack was measured, not guessed: 45% BitWriter per-bit loops, 22%
42+code_spectrum's Vec<bool> round-trip, 10% libm cos in the MDCT, ~12% powf/exp2.
43+
44+| commit | change | stereo CBR | VBR | quality |
45+|---|---|---|---|---|
46+| 1fbe9240 | word-buffered BitBuf; rate loop prices gains by Huffman cost alone, materialises bits once | 18.2x / 0.115 | 10.6x | byte-identical, all 8 |
47+| c056aa4d | 3/4-power as cube+two sqrts; band gains hoisted per band | 21.1x / 0.134 | 13.0x | corr equal to 6 decimals on all 8; 7/8 byte-identical (music3s flips one ulp-boundary line) |
48+| f51fef8f | forward-MDCT cosine kernels tabulated (LazyLock f32, f64 accumulation kept) | 37.3x / 0.235 | 17.8x | byte-identical, all 8 |
49+| 891dd0b2 | best_table_cost: one walk over the region accumulates every candidate table | 43.7x / 0.278 | 20.9x | byte-identical, all 8 |
50+| 46a73869 | gain search brackets by doubling stride + bisection (was a one-step walk; instrumentation showed ~31.5 quantise+plan evaluations per granule) | 96.0x / 0.608 | 52.4x | 7/8 byte-identical; music3s as above |
51+| bdb12e0c | cursor-based push drain (was quadratic memmove), deinterleave scratch, no per-granule pending clone | 109.8x / 0.693 | 55.7x | byte-identical, all 8 |
52+| e51d830d | quantise_span: the level curve eight lanes wide through wide::f32x8 | 127.9x / 0.819 | 67.5x | byte-identical, all 8 |
53+| 0266ddcb | region walk: zero-pair fast path, per-candidate range feasibility upfront | 139.2x / 0.886 | 74.3x | byte-identical, all 8 (music3s inherited) |
54+
55+## Final table (0266ddcb, local, loadavg 2.9-3.6, min-of-7 alternating)
56+
57+| row | ec-mp3 | incumbent | ratio | baseline |
58+|---|---|---|---|---|
59+| real30s cbr192 | 214.5 ms / 139.9x | 189.0 ms / 158.7x | **0.881** | 0.052 |
60+| music3s cbr192 | 47.0 ms / 63.8x | 22.7 ms / 132.3x | 0.482 | 0.096 |
61+| real30s vbr | 403.7 ms / 74.3x | 189.2 ms / 158.5x | 0.469 | 0.025 |
62+| tone48k cbr192 mono | 38.0 ms / 79.0x | 7.8 ms / 382.8x | 0.206 | 0.073 |
63+
64+Target ≥0.7 of the incumbent single-thread (105x+ RT stereo CBR): **met** on
65+the 30 s music row, 0.881; the 2 h-film export cost drops from ~17 min to
66+~2.5 min of wall. Quality holds: every fixture's decoded correlation equals
67+the pre-change build to six decimals (music3s-cbr192: 0.999998 on both; its
68+stream moved by ulp-boundary level flips when the gain search and the f64→
69+scalar-curve change landed, both gated above).
70+
71+## What remains, honestly
72+
73+- **VBR 0.469.** VBR re-codes the whole frame per bitrate candidate (bisection
74+ over the legal-rate table), so it pays the CBR cost several times. The same
75+ kernels are what it spends; a candidate-count reduction (start from the
76+ last settled index with a tighter bracket) is the next lever and is
77+ measurable with the existing harness.
78+- **Mono 0.206.** The incumbent's mono path is disproportionately fast
79+ (385x vs its 158x stereo); ours pays the same per-granule costs either way.
80+ Dense-content stereo — the seat the product pays — is where the work went.
81+- **Threading evaluated, declined.** Frame-level parallelism is constrained
82+ by the bit reservoir (a frame's budget depends on bytes actually consumed
83+ by predecessors) and the one-granule look-ahead; an API-compatible shape
84+ would pipeline one frame behind, and with the single-thread target met the
85+ added determinism surface buys nothing this round.
86+- Cross-machine final table on an idle server not run: both engines share one
87+ process here, so every ratio above is already same-machine/same-load; a
88+ quiet-box pass would tighten the absolute x-realtime numbers only.
89+
90+## Audit corrections (glm53 audit, pre-merge)
91+
92+Provenance-verified clean rebuilds of every commit contradict two claims
93+above, both documentation-level (code, quality, and perf conclusions all
94+stand):
95+
96+- f51fef8f (MDCT cosine table) is NOT byte-identical: the table rounds
97+ the kernel to f32 (`as f32`) and widens per product, where the old
98+ code multiplied full-f64 cosines — music3s-cbr192 moved 6 bytes at
99+ exactly this step (offsets 2773, 2988, 3697, 5882, 68143, 68144),
100+ including re-flipping the byte c056aa4d moved. Same ulp-boundary
101+ class; corr 0.999998 held at this step too. The attribution above to
102+ the gain-search step (46a73869) is WRONG: clean rebuilds of 891dd0b2
103+ and 46a73869 are byte-identical on all 8 fixtures — the bracket moved
104+ nothing (consistent with fits() being monotone in gain). The actual
105+ movers: c056aa4d (1 byte), f51fef8f (6 bytes).
106+- The 2h-film wall arithmetic: 7200 s / 139.9x ≈ 51 s (slowest row
107+ 63.8x → 113 s), not ~2.5 min. Direction stands; the number did not.
108+- The SIMD quantiser (e51d830d) computes the level curve in f32 where
109+ the scalar closure uses f64: ±1-step boundary flips are possible by
110+ construction (documented at encode.rs:1573-1577), and the empirical
111+ byte-identity on these fixtures is contingent, not structural.