forge
Explore
Log in

Don't you dare go Hollow

The encoder stops shuffling its own buffers

Browse files at this commit

dcaf6bb94c99f7891dc187ec0eb1986edc94331dAhmet Kaan GümüşParent: 59a18cf
  • perf
    • the encoder stops shuffling its own buffers
Show full message
perf(mp3): the encoder stops shuffling its own buffers

Three allocation/memmove habits from the profile's tail: the packet
layer drained one frame at a time, memmoving the whole remaining push
per frame (quadratic on a single large push); encode_block built a fresh
deinterleave Vec per channel per frame; emit_frame cloned every held
granule (subbands and thresholds) to satisfy a borrow that a drain
before the loop removes. Byte-identical on all eight fixtures, suite
green. encode: stereo CBR 96.0x -> 109.8x realtime (ratio 0.693), VBR
52.4x -> 55.7x.
crates/ec-mp3/src/encode.rsmodified+41 -25
@@ -137,6 +137,8 @@ pub struct Mp3Encode {
137137 fft: RealFft<f32>,
138138 fft_window: Window<f32>,
139139 psy_history: Vec<Vec<f32>>,
140+ /// Deinterleave scratch for `encode_block`, grown once and reused.
141+ pcm_scratch: Vec<f32>,
140142 /// The main-data byte stream and how much of it frames have carried.
141143 stream: Vec<u8>,
142144 used: usize,
@@ -219,6 +221,7 @@ impl Mp3Encode {
219221 assigned: 0,
220222 written: 0,
221223 queued: std::collections::VecDeque::new(),
224+ pcm_scratch: Vec::new(),
222225 ready: std::collections::VecDeque::new(),
223226 frames: 0,
224227 frame_bytes: 0,
@@ -350,26 +353,34 @@ impl Mp3Encoder {
350353 }
351354
352355 fn drain(&mut self, flush: bool) {
353- let Some(core) = self.core.as_mut() else {
356+ let Self {
357+ core, pcm, frames, ..
358+ } = self;
359+ let Some(core) = core.as_mut() else {
354360 return;
355361 };
356362 let channels = core.channels;
357363 let need = core.frame_samples() * channels;
358- while self.pcm.len() >= need {
359- let block: Vec<f32> = self.pcm.drain(..need).collect();
360- core.encode_block(&block);
361- }
364+ // Encode behind a read cursor and shift the leftovers once: draining
365+ // per frame memmoved the whole remaining push for every frame, which
366+ // on a single large push is quadratic in the file length.
367+ let mut pos = 0usize;
368+ while pcm.len() - pos >= need {
369+ core.encode_block(&pcm[pos..pos + need]);
370+ pos += need;
371+ }
372+ pcm.drain(..pos);
362373 if flush {
363- if !self.pcm.is_empty() {
364- let mut block = std::mem::take(&mut self.pcm);
365- block.resize(need, 0.0);
366- core.encode_block(&block);
374+ if !pcm.is_empty() {
375+ pcm.resize(need, 0.0);
376+ core.encode_block(pcm);
377+ pcm.clear();
367378 }
368379 core.flush_pending();
369380 core.flush_frames();
370381 }
371382 while let Some(frame) = core.ready.pop_front() {
372- self.frames.push_back(frame);
383+ frames.push_back(frame);
373384 }
374385 }
375386
@@ -514,10 +525,15 @@ impl Mp3Encode {
514525 let granules = self.granules();
515526 // Polyphase analysis, one channel at a time.
516527 for ch in 0..channels {
517- let mut mono: Vec<f32> = Vec::with_capacity(pcm.len() / channels);
528+ // One deinterleave buffer per encoder, grown once: this frame's
529+ // mono channel used to be a fresh allocation per channel per
530+ // frame.
531+ self.pcm_scratch.clear();
532+ self.pcm_scratch.reserve(pcm.len() / channels);
518533 for frame in pcm.chunks(channels) {
519- mono.push(frame[ch]);
534+ self.pcm_scratch.push(frame[ch]);
520535 }
536+ let mono = &self.pcm_scratch;
521537 for chunk in mono.chunks(32) {
522538 if chunk.len() < 32 {
523539 break;
@@ -526,7 +542,13 @@ impl Mp3Encode {
526542 self.slots[ch].push(slot);
527543 }
528544 }
529- self.psy_push(ch, &mono);
545+ // The masking model's history update, inlined from `psy_push` so
546+ // it can touch `psy_history` while `mono` borrows `pcm_scratch`.
547+ let n = mono.len().min(1024);
548+ let history = &mut self.psy_history[ch];
549+ history.copy_within(n.., 0);
550+ let keep = 1024 - n;
551+ history[keep..].copy_from_slice(&mono[mono.len() - n..]);
530552 }
531553 // A granule is 18 slots; hold one back so block switching can look
532554 // ahead at the next granule's energy.
@@ -557,15 +579,6 @@ impl Mp3Encode {
557579 }
558580 }
559581
560- /// One FFT per granule of input, kept for the masking model.
561- fn psy_push(&mut self, ch: usize, mono: &[f32]) {
562- let n = 1024.min(mono.len());
563- let history = &mut self.psy_history[ch];
564- history.copy_within(n.., 0);
565- let keep = 1024 - n;
566- history[keep..].copy_from_slice(&mono[mono.len() - n..]);
567- }
568-
569582 /// Allowed noise per long scalefactor band, from the masking model, in
570583 /// the units `code_with` measures quantisation noise in (summed squared
571584 /// MDCT lines), so noise / threshold is a noise-to-mask ratio.
@@ -702,18 +715,21 @@ impl Mp3Encode {
702715 // every bitrate candidate VBR tries below; compute them once.
703716 let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
704717 let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
718+ // Take the held-back granules once: the per-granule clone that used
719+ // to feed `mdct` copied every subband and threshold just to keep the
720+ // borrow checker happy about `history`.
721+ let held: Vec<PendingGranule> = self.pending.drain(..granules * channels).collect();
705722 for gr in 0..granules {
706723 for ch in 0..channels {
707724 let index = gr * channels + ch;
708- let granule = self.pending[index].clone();
725+ let granule = &held[index];
709726 xrs.push(self.mdct(ch, &granule.subband, types[index]));
710727 thresholds.push(match vbr {
711728 Some(quality) => quality_threshold(&granule.threshold, quality),
712- None => granule.threshold,
729+ None => granule.threshold.clone(),
713730 });
714731 }
715732 }
716- self.pending.drain(..granules * channels);
717733
718734 // Mid/side stereo. The two channels of real music are mostly the same
719735 // signal, and coding their sum and difference puts nearly all of the