From d08a7f73d2f73eb276e80cedf2080ccfc33f76b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 28 Aug 2026 01:13:54 +0300 Subject: [PATCH] perf(aac): kill the rate loop's powf hot path Profiling encode_frame (perf record --call-graph dwarf on a 10s real-PCM loop) showed 82% of wall time in libm's powf_fma, all reached through write_frame's cost closure -> quantise -> band_noise/quantise_one: band_noise's per-band scalefactor search called band_noise (two powf calls per coefficient) up to ~255 times per band, linearly walking every candidate level. - quantise_one's x^0.75 -> sqrt(x)*sqrt(sqrt(x)): two sqrtf beat one powf. - band_noise's q^(4/3) -> a precomputed lookup table over q's bounded (MAX_QUANT) integer range, since q is always an integer there. - the scalefactor search itself -> bisection, since the algorithm already assumed monotonic noise-vs-level to break on first overage; that's exactly what a binary search needs, and it drops ~255 candidate levels to ~8 per band. ec-bench's aac encode row: 3.54x -> 37.83x realtime (10.9x on a standalone 10s-PCM loop, matching the profiling harness). All ec-aac tests green. Also fixes crates/ec-aac/tests/oracle.rs's esds_asc helper, which scanned raw bytes for a literal 0x05 instead of walking the MPEG-4 descriptor tree by tag+length: a legitimate byte in the DecoderConfigDescriptor's avgBitrate field (which shifted with the quantiser's new floating-point path) could and did false-positive as the DecSpecificInfoTag. --- crates/ec-aac/src/encode.rs | 42 +++++++++++++++++++++++------ crates/ec-aac/tests/oracle.rs | 50 ++++++++++++++++++++++++++--------- 2 files changed, 72 insertions(+), 20 deletions(-) diff --git a/crates/ec-aac/src/encode.rs b/crates/ec-aac/src/encode.rs index ede1dcef..9a2dfbce 100644 --- a/crates/ec-aac/src/encode.rs +++ b/crates/ec-aac/src/encode.rs @@ -20,6 +20,8 @@ //! rather than iterators. #![allow(clippy::needless_range_loop)] +use std::sync::LazyLock; + use ec_core::{BitWriter, Error, Result}; use ec_dsp::{Complex, Mdct, RealFft, Window}; @@ -650,14 +652,22 @@ impl AacEncoder { continue; } floor[b] = sf_floor(peak).max(0); + // Noise is non-decreasing in level (coarser step -> more error), + // the same assumption the original linear scan relied on to break + // on first overage; bisect for the largest level still under + // target instead of walking it one step at a time. let mut best = floor[b]; - let mut level = best; - while level < 255 { - if self.band_noise(frame, swb, b, level, windows, short) > target { - break; + if self.band_noise(frame, swb, b, floor[b], windows, short) <= target { + let (mut lo, mut hi) = (floor[b], 255); + while lo < hi { + let mid = lo + (hi - lo + 1) / 2; + if self.band_noise(frame, swb, b, mid, windows, short) <= target { + lo = mid; + } else { + hi = mid - 1; + } } - best = level; - level += 1; + best = lo; } sf[b] = best.clamp(floor[b], 255); zero[b] = false; @@ -766,7 +776,7 @@ impl AacEncoder { for k in base + lo..base + hi { let x = frame.coef[k]; let q = quantise_one(x, sf); - let mut back = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain; + let mut back = pow43(q.unsigned_abs()) * gain; if q < 0 { back = -back; } @@ -839,6 +849,19 @@ fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, } } +/// `q^(4/3)` for the (small, bounded-by-`MAX_QUANT`) integer magnitudes the +/// rate loop's noise search re-tests at every candidate scalefactor: a table +/// lookup replaces what was otherwise the encoder's hottest `powf` call site. +static POW43: LazyLock> = LazyLock::new(|| { + (0..=MAX_QUANT as u32) + .map(|q| (q as f32).powf(4.0 / 3.0)) + .collect() +}); + +fn pow43(q: u32) -> f32 { + POW43[q.min(MAX_QUANT as u32) as usize] +} + /// The finest scalefactor at which a peak of this size still fits the escape /// codebook: below it the quantiser saturates, which costs bits *and* adds /// distortion. @@ -852,7 +875,10 @@ fn quantise_one(x: f32, sf: i32) -> i32 { return 0; } let gain = 2f32.powf(-(sf - SF_OFFSET) as f32 * 0.25); - let q = ((x.abs() * gain).powf(0.75) + ROUND_BIAS) as i32; + // x^0.75 == sqrt(x * sqrt(x)): two sqrtf beat one powf by a wide margin, + // and this call site is the rate loop's inner-inner loop. + let v = x.abs() * gain; + let q = (v.sqrt() * v.sqrt().sqrt() + ROUND_BIAS) as i32; let q = q.min(MAX_QUANT); if x < 0.0 { -q } else { q } } diff --git a/crates/ec-aac/tests/oracle.rs b/crates/ec-aac/tests/oracle.rs index 43674409..7ddde830 100644 --- a/crates/ec-aac/tests/oracle.rs +++ b/crates/ec-aac/tests/oracle.rs @@ -627,23 +627,49 @@ fn asc_matches_the_one_ffmpeg_writes() { /// The DecoderSpecificInfo payload of the first `esds` box: tag 0x05 inside the /// DecoderConfigDescriptor, with the usual 7-bit length encoding. fn esds_asc(mp4: &[u8]) -> Option> { + // Walks the MPEG-4 descriptor tree (tag, BER length, payload) rather than + // scanning raw bytes for 0x05: a scalar field elsewhere in the tree + // (e.g. avgBitrate) can legitimately contain that byte value, which a + // blind byte scan would mistake for the DecSpecificInfoTag. let at = mp4.windows(4).position(|w| w == b"esds")?; - let mut i = at + 4; + let mut i = at + 4 + 4; // "esds" tag, then the box's version+flags while i < mp4.len() { - if mp4[i] == 0x05 { - let mut j = i + 1; - let mut len = 0usize; - loop { - let b = *mp4.get(j)?; - len = (len << 7) | usize::from(b & 0x7F); - j += 1; - if b & 0x80 == 0 { - break; + let tag = mp4[i]; + i += 1; + let mut len = 0usize; + loop { + let b = *mp4.get(i)?; + i += 1; + len = (len << 7) | usize::from(b & 0x7F); + if b & 0x80 == 0 { + break; + } + } + match tag { + 0x05 => return mp4.get(i..i + len).map(<[u8]>::to_vec), + // ES_DescrTag: ES_ID(2) + flags(1), then optional fields the + // flags select, before its nested descriptors. + 0x03 => { + let flags = *mp4.get(i + 2)?; + i += 3; + if flags & 0x80 != 0 { + i += 2; // dependsOn ES_ID + } + if flags & 0x40 != 0 { + let url_len = usize::from(*mp4.get(i)?); + i += 1 + url_len; + } + if flags & 0x20 != 0 { + i += 2; // OCR ES_ID } } - return mp4.get(j..j + len).map(<[u8]>::to_vec); + // DecoderConfigDescrTag: objectType(1) + streamType/flags(1) + + // bufferSizeDB(3) + maxBitrate(4) + avgBitrate(4), then its + // nested DecSpecificInfo. + 0x04 => i += 13, + // An opaque leaf descriptor: its whole payload is `len` bytes. + _ => i += len, } - i += 1; } None }