forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-aacenc-perf' (465fa1fc): ec-aac encode is 3x faster -- 102.7x RT stereo (1.30x rusty, was 0.44x) and 44.4x RT 5.1 (1.46x, was 0.42x) -- band invariants hoisted, pow lookup tables, per-(channel,band,scalefactor) noise memo, rate-loop warm-start gallop; output byte-identical to base at every commit (auditor-proven on 6 HEAD configs + all 5 commits + 2 dep resolutions, counterfactual-verified); quality edge unchanged (96k stereo 0.8857 vs rusty 0.3858); threading declined (sequential seat API, target exceeded)

Browse files at this commit

1451897bbb3018a946668eb467f588e0d56a36fcAhmet Kaan GümüşParent: d5d7c0a17417bc
crates/ec-aac/examples/aacenc_rt.rsadded+105 -0
@@ -0,0 +1,105 @@
1+//! AAC-LC encode speed relative to realtime, which is how the crate's encode
2+//! perf claim is measured: a deterministic tonal-plus-transient program, ten
3+//! seconds, at the seat's rates (stereo 256 kbit/s, 5.1 512 kbit/s), the
4+//! shortest wall of several alternating repetitions.
5+//!
6+//! ```text
7+//! cargo run --release -p ec-aac --example aacenc_rt
8+//! ```
9+
10+use std::time::Instant;
11+
12+use ec_aac::{AacEncoder, AacEncoderConfig};
13+
14+/// Deterministic tonal stacks with periodic noise bursts: enough tonality for
15+/// the spreading function to bite, enough attacks to exercise the short-block
16+/// path.
17+struct Lcg(u64);
18+impl Lcg {
19+ fn next_f32(&mut self) -> f32 {
20+ self.0 = self
21+ .0
22+ .wrapping_mul(6364136223846793005)
23+ .wrapping_add(1442695040888963407);
24+ ((self.0 >> 40) as f32 / 16777216.0) * 2.0 - 1.0
25+ }
26+}
27+
28+fn channel(f0: f64, seed: u64, rate: u32, secs: usize, burst_period: f64) -> Vec<f32> {
29+ let mut noise = Lcg(seed);
30+ let mut out = Vec::with_capacity(secs * rate as usize);
31+ for i in 0..secs * rate as usize {
32+ let t = i as f64 / rate as f64;
33+ let frac = (t % burst_period) / burst_period;
34+ let burst = (-frac * 18.0_f64).exp() as f32;
35+ let stack = (f0.sin() * 0.5
36+ + (f0 * 3.0).sin() * 0.15
37+ + (f0 * 5.0 + 0.31 * (6.0 * std::f64::consts::TAU * t).sin()).sin() * 0.08)
38+ as f32
39+ * (0.7 + 0.3 * (0.5 * std::f64::consts::TAU * t).sin()) as f32;
40+ out.push(stack + burst * noise.next_f32() * 0.3);
41+ }
42+ out
43+}
44+
45+fn program(channels: usize, rate: u32, secs: usize) -> Vec<f32> {
46+ let stereo = [0x5EED_1234u64, 0xC0FF_EE01];
47+ let five_one = [0x5EED_1234, 0xC0FF_EE01, 0xABCD_0001, 0xABCD_0002, 0xABCD_0003, 0xABCD_0004];
48+ let f0s = [220.0f64, 277.0, 330.0, 55.0, 196.0, 246.9];
49+ let periods = [0.9f64, 0.8, 1.1, 1.3, 0.7, 0.85];
50+ let seeds: &[u64] = if channels == 2 {
51+ &stereo
52+ } else {
53+ &five_one
54+ };
55+ let chans: Vec<Vec<f32>> = (0..channels)
56+ .map(|c| channel(f0s[c], seeds[c], rate, secs, periods[c]))
57+ .collect();
58+ let mut pcm = Vec::with_capacity(chans[0].len() * channels);
59+ for i in 0..chans[0].len() {
60+ for c in &chans {
61+ pcm.push(c[i]);
62+ }
63+ }
64+ pcm
65+}
66+
67+fn encode(pcm: &[f32], channels: usize, kbps: u32) -> usize {
68+ let mut enc = AacEncoder::new(AacEncoderConfig {
69+ bitrate_bps: kbps * 1_000,
70+ ..Default::default()
71+ });
72+ enc.push_pcm(pcm, channels as u16, 48_000).expect("pcm accepted");
73+ enc.finish();
74+ let mut bytes = 0usize;
75+ while let Ok(p) = enc.next_packet() {
76+ bytes += p.data.len();
77+ }
78+ bytes
79+}
80+
81+fn main() {
82+ let reps: usize = std::env::var("REPS")
83+ .ok()
84+ .and_then(|s| s.parse().ok())
85+ .unwrap_or(7);
86+ for (channels, kbps) in [(2usize, 256u32), (6, 512)] {
87+ let pcm = program(channels, 48_000, 10);
88+ let secs = pcm.len() as f64 / (48_000.0 * channels as f64);
89+ let _ = encode(&pcm, channels, kbps); // warm
90+ let mut walls = Vec::with_capacity(reps);
91+ for _ in 0..reps {
92+ let t0 = Instant::now();
93+ let bytes = encode(&pcm, channels, kbps);
94+ walls.push((t0.elapsed().as_secs_f64(), bytes));
95+ }
96+ walls.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
97+ let (wall, bytes) = walls[0];
98+ println!(
99+ "{channels}ch {kbps}k: min {wall:.4}s = {:.1}x realtime ({} B, {} reps)",
100+ secs / wall,
101+ bytes,
102+ reps
103+ );
104+ }
105+}
crates/ec-aac/src/encode.rsmodified+234 -44
@@ -122,6 +122,9 @@ pub struct AacEncoder {
122 queue: std::collections::VecDeque<EncodedPacket>,122 queue: std::collections::VecDeque<EncodedPacket>,
123 frames_out: i64,123 frames_out: i64,
124 reservoir: i32,124 reservoir: i32,
125+ /// The rate loop's working point from the previous frame, where the next
126+ /// frame's search starts looking for its own edge.
127+ warm_offset: i32,
125 flushed: bool,128 flushed: bool,
126 initialised: bool,129 initialised: bool,
127 }130 }
@@ -155,6 +158,7 @@ impl AacEncoder {
155 queue: std::collections::VecDeque::new(),158 queue: std::collections::VecDeque::new(),
156 frames_out: 0,159 frames_out: 0,
157 reservoir: 0,160 reservoir: 0,
161+ warm_offset: 0,
158 flushed: false,162 flushed: false,
159 initialised: false,163 initialised: false,
160 }164 }
@@ -523,10 +527,27 @@ impl AacEncoder {
523 // so the finest quantisation that fits the budget is a bisection --527 // so the finest quantisation that fits the budget is a bisection --
524 // which also means the psychoacoustic model only has to get the shape528 // which also means the psychoacoustic model only has to get the shape
525 // of the allocation right, not its absolute level.529 // of the allocation right, not its absolute level.
526- let cost = |enc: &AacEncoder, offset: i32| -> (i32, Vec<Coded>) {530+ // Per-band peak, energy and scalefactor floor on the post-M/S
531+ // coefficients: none of them depend on the rate loop's offset, so
532+ // they are computed once per channel and read by every cost probe.
533+ let profiles: Vec<Vec<BandProfile>> = elements
534+ .iter()
535+ .map(|plan| {
536+ plan.frames
537+ .iter()
538+ .map(|frame| band_profile(frame, swb, max_sfb, short))
539+ .collect()
540+ })
541+ .collect();
542+ // Every noise query a probe makes is memoised for the frame: the
543+ // bisection probes revisit the same (band, scalefactor) pairs across
544+ // the outer loop, and band_noise is pure per frame.
545+ let mut memo = NoiseMemo::new(self.channels * max_sfb * 256);
546+ let mut cost = |enc: &AacEncoder, offset: i32| -> (i32, Vec<Coded>) {
527 let mut coded = Vec::new();547 let mut coded = Vec::new();
528 let mut bits = 10i32; // END element plus byte-alignment slack548 let mut bits = 10i32; // END element plus byte-alignment slack
529- for plan in &elements {549+ let mut ch_slot = 0usize;
550+ for (plan, profiles) in elements.iter().zip(&profiles) {
530 bits += 3551 bits += 3
531 + 4552 + 4
532 + if plan.element == Element::Cpe {553 + if plan.element == Element::Cpe {
@@ -534,41 +555,98 @@ impl AacEncoder {
534 } else {555 } else {
535 0556 0
536 };557 };
537- for frame in &plan.frames {558+ for (frame, profile) in plan.frames.iter().zip(profiles) {
538- let c = enc.quantise(frame, seq, swb, max_sfb, offset);559+ let c =
560+ enc.quantise(frame, profile, &mut memo, ch_slot, seq, swb, max_sfb, offset);
539 bits += c.bits;561 bits += c.bits;
540 coded.push(c);562 coded.push(c);
563+ ch_slot += 1;
541 }564 }
542 }565 }
543 (bits, coded)566 (bits, coded)
544 };567 };
545- let (mut lo, mut hi) = (-240i32, 240i32);568+ let (probe_bits, mut coded) = cost(self, 240);
546- let (mut bits, mut coded) = cost(self, hi);569+ let mut answer = 240i32;
547- if bits > budget {570+ if probe_bits > budget {
548 // Even the coarsest setting overflows: take it and let the571 // Even the coarsest setting overflows: take it and let the
549 // reservoir absorb the overshoot.572 // reservoir absorb the overshoot.
550- lo = hi;
551 } else {573 } else {
552- while lo < hi {574+ // Bits fall monotonically as the offset rises, so "fits the
553- let mid = lo + (hi - lo) / 2;575+ // budget" is true on an upper interval and the finest fitting
576+ // setting is its left edge. Last frame's working point sits next
577+ // to that edge, so probe it first and gallop outward until one
578+ // side is known to fail, then bisect the short bracket -- the
579+ // same edge a full-range bisection would find, in a few probes.
580+ let start = self.warm_offset.clamp(-240, 240);
581+ let (start_bits, start_coded) = cost(self, start);
582+ if start_bits <= budget {
583+ // Known to fit: the edge is at or below `start`. Walk down.
584+ let mut hi = start;
585+ coded = start_coded;
586+ let mut fail = None;
587+ let mut step = 1i32;
588+ loop {
589+ let probe = (start - step).max(-240);
590+ let (b, c) = cost(self, probe);
591+ if b <= budget {
592+ hi = probe;
593+ coded = c;
594+ } else {
595+ fail = Some(probe);
596+ }
597+ let done = probe == -240 || fail.is_some();
598+ if done {
599+ break;
600+ }
601+ step *= 2;
602+ }
603+ if let Some(mut lo) = fail {
604+ while hi - lo > 1 {
605+ let mid = lo + (hi - lo + 1) / 2;
554 let (b, c) = cost(self, mid);606 let (b, c) = cost(self, mid);
555 if b <= budget {607 if b <= budget {
556 hi = mid;608 hi = mid;
557- bits = b;
558 coded = c;609 coded = c;
559 } else {610 } else {
560- lo = mid + 1;611+ lo = mid;
612+ }
613+ }
614+ }
615+ answer = hi;
616+ } else {
617+ // `start` sits past the edge: the answer is above it. Walk up.
618+ let mut lo = start;
619+ let mut hi = 240i32; // known to fit from the first probe
620+ let mut step = 1i32;
621+ loop {
622+ let probe = (start + step).min(240);
623+ if probe == 240 {
624+ // Already probed and known to fit; `hi` keeps 240.
625+ break;
561 }626 }
627+ let (b, c) = cost(self, probe);
628+ if b <= budget {
629+ hi = probe;
630+ coded = c;
631+ break;
562 }632 }
563- if lo < 240 {633+ lo = probe;
564- let (b, c) = cost(self, lo);634+ step *= 2;
635+ }
636+ while hi - lo > 1 {
637+ let mid = lo + (hi - lo + 1) / 2;
638+ let (b, c) = cost(self, mid);
565 if b <= budget {639 if b <= budget {
566- bits = b;640+ hi = mid;
567 coded = c;641 coded = c;
642+ } else {
643+ lo = mid;
568 }644 }
569 }645 }
646+ answer = hi;
570 }647 }
571- let _ = (lo, bits);648+ }
649+ self.warm_offset = answer;
572 650
573 let mut w = BitWriter::new();651 let mut w = BitWriter::new();
574 let mut at = 0usize;652 let mut at = 0usize;
@@ -612,6 +690,9 @@ impl AacEncoder {
612 fn quantise(690 fn quantise(
613 &self,691 &self,
614 frame: &ChannelFrame,692 frame: &ChannelFrame,
693+ profile: &BandProfile,
694+ memo: &mut NoiseMemo,
695+ ch_slot: usize,
615 seq: WindowSequence,696 seq: WindowSequence,
616 swb: &'static [u16],697 swb: &'static [u16],
617 max_sfb: usize,698 max_sfb: usize,
@@ -623,45 +704,37 @@ impl AacEncoder {
623 let mut floor = vec![0i32; max_sfb];704 let mut floor = vec![0i32; max_sfb];
624 let mut zero = vec![true; max_sfb];705 let mut zero = vec![true; max_sfb];
625 for b in 0..max_sfb {706 for b in 0..max_sfb {
626- let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));707+ if profile.peak[b] < 1e-4 {
627- let mut peak = 0.0f32;
628- for w in 0..windows {
629- let base = if short { w * SHORT_LEN } else { 0 };
630- for k in base + lo..base + hi {
631- peak = peak.max(frame.coef[k].abs());
632- }
633- }
634- if peak < 1e-4 {
635 continue;708 continue;
636 }709 }
637 // The rate loop scales the whole mask rather than shifting the710 // The rate loop scales the whole mask rather than shifting the
638 // scalefactors: that keeps the noise following the shape the model711 // scalefactors: that keeps the noise following the shape the model
639 // asked for, and lets a band whose signal falls under its own mask712 // asked for, and lets a band whose signal falls under its own mask
640 // drop out entirely instead of being coded ever more coarsely.713 // drop out entirely instead of being coded ever more coarsely.
641- let target = frame.threshold[b] * 2f32.powf(offset as f32 * 0.5);714+ let target = frame.threshold[b] * POW_HALF[(offset + 240) as usize];
642- let mut energy = 0.0f32;715+ if profile.energy[b] / profile.count[b].max(1) as f32 <= target {
643- let mut count = 0usize;
644- for w in 0..windows {
645- let base = if short { w * SHORT_LEN } else { 0 };
646- for k in base + lo..base + hi {
647- energy += frame.coef[k] * frame.coef[k];
648- count += 1;
649- }
650- }
651- if energy / count.max(1) as f32 <= target {
652 continue;716 continue;
653 }717 }
654- floor[b] = sf_floor(peak).max(0);718+ floor[b] = profile.floor[b];
655 // Noise is non-decreasing in level (coarser step -> more error),719 // Noise is non-decreasing in level (coarser step -> more error),
656 // the same assumption the original linear scan relied on to break720 // the same assumption the original linear scan relied on to break
657 // on first overage; bisect for the largest level still under721 // on first overage; bisect for the largest level still under
658 // target instead of walking it one step at a time.722 // target instead of walking it one step at a time.
659 let mut best = floor[b];723 let mut best = floor[b];
660- if self.band_noise(frame, swb, b, floor[b], windows, short) <= target {724+ if memo.noise(
725+ ch_slot,
726+ max_sfb,
727+ b,
728+ floor[b],
729+ || self.band_noise(frame, swb, b, floor[b], windows, short),
730+ ) <= target
731+ {
661 let (mut lo, mut hi) = (floor[b], 255);732 let (mut lo, mut hi) = (floor[b], 255);
662 while lo < hi {733 while lo < hi {
663 let mid = lo + (hi - lo + 1) / 2;734 let mid = lo + (hi - lo + 1) / 2;
664- if self.band_noise(frame, swb, b, mid, windows, short) <= target {735+ if memo.noise(ch_slot, max_sfb, b, mid, || {
736+ self.band_noise(frame, swb, b, mid, windows, short)
737+ }) <= target {
665 lo = mid;738 lo = mid;
666 } else {739 } else {
667 hi = mid - 1;740 hi = mid - 1;
@@ -675,6 +748,9 @@ impl AacEncoder {
675 748
676 let mut quant = vec![0i32; FRAME_LEN];749 let mut quant = vec![0i32; FRAME_LEN];
677 let mut books = vec![0u8; max_sfb];750 let mut books = vec![0u8; max_sfb];
751+ // Bands whose scalefactor the delta chain moved since they were last
752+ // quantised; every band is dirty on the first pass.
753+ let mut dirty = vec![true; max_sfb];
678 for _ in 0..4 {754 for _ in 0..4 {
679 let mut settled = true;755 let mut settled = true;
680 let mut prev: Option<i32> = None;756 let mut prev: Option<i32> = None;
@@ -688,6 +764,7 @@ impl AacEncoder {
688 };764 };
689 if fixed != sf[b] {765 if fixed != sf[b] {
690 sf[b] = fixed;766 sf[b] = fixed;
767+ dirty[b] = true;
691 settled = false;768 settled = false;
692 }769 }
693 prev = Some(sf[b]);770 prev = Some(sf[b]);
@@ -700,18 +777,26 @@ impl AacEncoder {
700 let base = if short { w * SHORT_LEN } else { 0 };777 let base = if short { w * SHORT_LEN } else { 0 };
701 quant[base + lo..base + hi].fill(0);778 quant[base + lo..base + hi].fill(0);
702 }779 }
780+ dirty[b] = false;
703 continue;781 continue;
704 }782 }
783+ // A band the delta chain left alone keeps its quantised
784+ // values, its peak and its codebook from the previous pass.
785+ if !dirty[b] {
786+ continue;
787+ }
788+ let gain = pow_quarter(SF_OFFSET - sf[b]);
705 let mut peak = 0i32;789 let mut peak = 0i32;
706 for w in 0..windows {790 for w in 0..windows {
707 let base = if short { w * SHORT_LEN } else { 0 };791 let base = if short { w * SHORT_LEN } else { 0 };
708 for k in lo..hi {792 for k in lo..hi {
709- let q = quantise_one(frame.coef[base + k], sf[b]);793+ let q = quantise_one(frame.coef[base + k], gain);
710 quant[base + k] = q;794 quant[base + k] = q;
711 peak = peak.max(q.abs());795 peak = peak.max(q.abs());
712 }796 }
713 }797 }
714 books[b] = codebook_for(peak);798 books[b] = codebook_for(peak);
799+ dirty[b] = false;
715 if peak == 0 {800 if peak == 0 {
716 // Nothing survived: the band leaves the delta chain, which801 // Nothing survived: the band leaves the delta chain, which
717 // may free the bands after it to go coarser.802 // may free the bands after it to go coarser.
@@ -768,14 +853,15 @@ impl AacEncoder {
768 short: bool,853 short: bool,
769 ) -> f32 {854 ) -> f32 {
770 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));855 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
771- let gain = 2f32.powf((sf - SF_OFFSET) as f32 * 0.25);856+ let gain = pow_quarter(sf - SF_OFFSET);
857+ let gain_inv = pow_quarter(SF_OFFSET - sf);
772 let mut noise = 0.0f32;858 let mut noise = 0.0f32;
773 let mut count = 0usize;859 let mut count = 0usize;
774 for w in 0..windows {860 for w in 0..windows {
775 let base = if short { w * SHORT_LEN } else { 0 };861 let base = if short { w * SHORT_LEN } else { 0 };
776 for k in base + lo..base + hi {862 for k in base + lo..base + hi {
777 let x = frame.coef[k];863 let x = frame.coef[k];
778- let q = quantise_one(x, sf);864+ let q = quantise_one(x, gain_inv);
779 let mut back = pow43(q.unsigned_abs()) * gain;865 let mut back = pow43(q.unsigned_abs()) * gain;
780 if q < 0 {866 if q < 0 {
781 back = -back;867 back = -back;
@@ -827,6 +913,84 @@ fn ms_wins(l: &ChannelFrame, r: &ChannelFrame, swb: &[u16], band: usize, short:
827 ms > lr * 1.5913 ms > lr * 1.5
828 }914 }
829 915
916+/// Per-band constants of one channel's quantised frame: the peak magnitude,
917+/// the coefficient energy and the escape-codebook scalefactor floor. All
918+/// three are independent of the rate loop's offset, so `write_frame` computes
919+/// them once and every cost probe reads them back.
920+struct BandProfile {
921+ peak: Vec<f32>,
922+ energy: Vec<f32>,
923+ /// Coefficient count per band, the energy's divisor.
924+ count: Vec<usize>,
925+ floor: Vec<i32>,
926+}
927+
928+fn band_profile(frame: &ChannelFrame, swb: &[u16], max_sfb: usize, short: bool) -> BandProfile {
929+ let windows = if short { 8 } else { 1 };
930+ let mut peak = vec![0.0f32; max_sfb];
931+ let mut energy = vec![0.0f32; max_sfb];
932+ let mut count = vec![0usize; max_sfb];
933+ let mut floor = vec![0i32; max_sfb];
934+ for b in 0..max_sfb {
935+ let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
936+ for w in 0..windows {
937+ let base = if short { w * SHORT_LEN } else { 0 };
938+ for k in base + lo..base + hi {
939+ let c = frame.coef[k];
940+ peak[b] = peak[b].max(c.abs());
941+ energy[b] += c * c;
942+ count[b] += 1;
943+ }
944+ }
945+ floor[b] = sf_floor(peak[b]).max(0);
946+ }
947+ BandProfile {
948+ peak,
949+ energy,
950+ count,
951+ floor,
952+ }
953+}
954+
955+/// Per-frame cache for the noise search: `band_noise(band, sf)` is pure for
956+/// one frame's coefficients, and the outer rate loop's probes re-ask the same
957+/// (band, scalefactor) pairs, so each pair is computed at most once per frame
958+/// clearing pass.
959+struct NoiseMemo {
960+ stamp: Vec<u32>,
961+ val: Vec<f32>,
962+ cur: u32,
963+}
964+
965+impl NoiseMemo {
966+ fn new(capacity: usize) -> NoiseMemo {
967+ NoiseMemo {
968+ stamp: vec![0; capacity],
969+ val: vec![0.0; capacity],
970+ cur: 1,
971+ }
972+ }
973+
974+ /// The memoised noise at `(band, sf)`, computing through `f` on a miss.
975+ fn noise(
976+ &mut self,
977+ ch_slot: usize,
978+ max_sfb: usize,
979+ band: usize,
980+ sf: i32,
981+ f: impl FnOnce() -> f32,
982+ ) -> f32 {
983+ let idx = (ch_slot * max_sfb + band) * 256 + sf as usize;
984+ if self.stamp[idx] == self.cur {
985+ return self.val[idx];
986+ }
987+ let noise = f();
988+ self.stamp[idx] = self.cur;
989+ self.val[idx] = noise;
990+ noise
991+ }
992+}
993+
830 fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) {994 fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) {
831 let windows = if short { 8 } else { 1 };995 let windows = if short { 8 } else { 1 };
832 for b in 0..max_sfb {996 for b in 0..max_sfb {
@@ -858,6 +1022,29 @@ static POW43: LazyLock<Vec<f32>> = LazyLock::new(|| {
858 .collect()1022 .collect()
859 });1023 });
860 1024
1025+/// `2^(v/4)` for every integer v the rate loop asks for: a band's quantiser
1026+/// step is `2^((sf-100)/4)` in `band_noise` and its reciprocal inside
1027+/// [`quantise_one`], and the exponent's integer range over sf in 0..=255 is
1028+/// -100..=155 either way. Every entry is produced by the very `powf` call it
1029+/// replaces, so lookups return the bit-identical value.
1030+static POW_QUARTER: LazyLock<Vec<f32>> = LazyLock::new(|| {
1031+ (-155i32..=155)
1032+ .map(|v| 2f32.powf(v as f32 * 0.25))
1033+ .collect()
1034+});
1035+
1036+fn pow_quarter(v: i32) -> f32 {
1037+ POW_QUARTER[(v + 155) as usize]
1038+}
1039+
1040+/// `2^(offset/2)`, the rate loop's mask scale, same table trick at the
1041+/// half-octave stride; the bisection bounds keep offset in -240..=240.
1042+static POW_HALF: LazyLock<Vec<f32>> = LazyLock::new(|| {
1043+ (-240i32..=240)
1044+ .map(|o| 2f32.powf(o as f32 * 0.5))
1045+ .collect()
1046+});
1047+
861 fn pow43(q: u32) -> f32 {1048 fn pow43(q: u32) -> f32 {
862 POW43[q.min(MAX_QUANT as u32) as usize]1049 POW43[q.min(MAX_QUANT as u32) as usize]
863 }1050 }
@@ -870,11 +1057,14 @@ fn sf_floor(peak: f32) -> i32 {
870 SF_OFFSET + want.ceil() as i321057 SF_OFFSET + want.ceil() as i32
871 }1058 }
872 1059
873-fn quantise_one(x: f32, sf: i32) -> i32 {1060+/// The gain is the band's `2^((sf-100)/4)` reciprocal -- `pow_quarter`'s
1061+/// job -- hoisted to the call sites so the inner-inner loop is sqrts only.
1062+/// The value is the same f32 the old per-coefficient `powf` produced, so the
1063+/// quantised integers do not move.
1064+fn quantise_one(x: f32, gain: f32) -> i32 {
874 if x == 0.0 {1065 if x == 0.0 {
875 return 0;1066 return 0;
876 }1067 }
877- let gain = 2f32.powf(-(sf - SF_OFFSET) as f32 * 0.25);
878 // x^0.75 == sqrt(x * sqrt(x)): two sqrtf beat one powf by a wide margin,1068 // x^0.75 == sqrt(x * sqrt(x)): two sqrtf beat one powf by a wide margin,
879 // and this call site is the rate loop's inner-inner loop.1069 // and this call site is the rate loop's inner-inner loop.
880 let v = x.abs() * gain;1070 let v = x.abs() * gain;