diff --git a/src/common/fft.rs b/src/common/fft.rs index b7db636..0e37bf0 100644 --- a/src/common/fft.rs +++ b/src/common/fft.rs @@ -1,44 +1,40 @@ -use rustfft::{FftPlanner, num_complex::Complex}; +use std::sync::Arc; + +use rustfft::{Fft, FftPlanner, num_complex::Complex}; pub struct SpectrumAnalyzer { - planner: FftPlanner, + fft: Arc>, complex_buf: Vec>, scratch: Vec>, } impl SpectrumAnalyzer { pub fn new(max_size: usize) -> Self { + let mut planner = FftPlanner::new(); + let fft = planner.plan_fft_forward(max_size); + let scratch = vec![Complex { re: 0.0, im: 0.0 }; fft.get_inplace_scratch_len()]; Self { - planner: FftPlanner::new(), + fft, complex_buf: vec![Complex { re: 0.0, im: 0.0 }; max_size], - scratch: vec![Complex { re: 0.0, im: 0.0 }; max_size], + scratch, } } pub fn process(&mut self, input: &[f32], output: &mut [f32]) { - let n = input.len(); - if n == 0 { + if input.is_empty() { output.fill(0.0); return; } - let fft = self.planner.plan_fft_forward(n); - - for (i, &s) in input.iter().enumerate() { - self.complex_buf[i].re = s; - self.complex_buf[i].im = 0.0; - } - for complex in self.complex_buf.iter_mut().take(n).skip(input.len()) { - complex.re = 0.0; - complex.im = 0.0; - } - - let scratch_len = fft.get_inplace_scratch_len(); - if self.scratch.len() < scratch_len { - self.scratch - .resize(scratch_len, Complex { re: 0.0, im: 0.0 }); + for (complex, &sample) in self.complex_buf.iter_mut().zip(input) { + *complex = Complex { + re: sample, + im: 0.0, + }; } - fft.process_with_scratch(&mut self.complex_buf[..n], &mut self.scratch[..scratch_len]); + self.complex_buf[input.len()..].fill(Complex { re: 0.0, im: 0.0 }); + self.fft + .process_with_scratch(&mut self.complex_buf, &mut self.scratch); let out_len = output.len().min(self.complex_buf.len()); for (c, o) in self.complex_buf[..out_len] diff --git a/src/common/lufs.rs b/src/common/lufs.rs index 496affe..90eac9b 100644 --- a/src/common/lufs.rs +++ b/src/common/lufs.rs @@ -13,6 +13,7 @@ const INTEGRATED_HOP_MS: f64 = 100.0; const LOUDNESS_OFFSET: f64 = -0.691; const ABSOLUTE_GATE_LUFS: f64 = -70.0; const RELATIVE_GATE_LU: f64 = -10.0; +const MAX_INTEGRATED_BLOCKS: usize = 24 * 60 * 60 * 1000 / INTEGRATED_HOP_MS as usize; #[derive(Clone, Copy)] struct Biquad { @@ -193,8 +194,11 @@ pub struct LufsMeter { hop_len: usize, hop_remaining: usize, /// Channel-averaged 400 ms energies, one per 100 ms hop, for the - /// integrated measurement's absolute and relative gating. + /// integrated measurement's absolute and relative gating. The most recent + /// 24 hours are retained in fixed storage. blocks: Vec, + blocks_len: usize, + block_pos: usize, } impl LufsMeter { @@ -207,7 +211,9 @@ impl LufsMeter { ], hop_len, hop_remaining: hop_len, - blocks: Vec::new(), + blocks: vec![0.0; MAX_INTEGRATED_BLOCKS], + blocks_len: 0, + block_pos: 0, } } @@ -216,7 +222,8 @@ impl LufsMeter { channel.reset(); } self.hop_remaining = self.hop_len; - self.blocks.clear(); + self.blocks_len = 0; + self.block_pos = 0; } /// Feed one block of interleaved-by-slice stereo samples. @@ -234,7 +241,16 @@ impl LufsMeter { .map(|c| c.momentary.mean_square()) .sum::() / self.channels.len() as f64; - self.blocks.push(energy); + let write_pos = if self.blocks_len < self.blocks.len() { + let position = self.blocks_len; + self.blocks_len += 1; + position + } else { + let position = self.block_pos; + self.block_pos = (self.block_pos + 1) % self.blocks.len(); + position + }; + self.blocks[write_pos] = energy; } } } @@ -257,26 +273,34 @@ impl LufsMeter { } pub fn integrated_lufs(&self) -> f64 { - if self.blocks.is_empty() { + let blocks = &self.blocks[..self.blocks_len]; + if blocks.is_empty() { return f64::NEG_INFINITY; } let absolute_gate = 10.0_f64.powf((ABSOLUTE_GATE_LUFS - LOUDNESS_OFFSET) / 10.0); - let gated: Vec = self - .blocks + let (gated_sum, gated_count) = blocks .iter() .copied() .filter(|&e| e >= absolute_gate) - .collect(); - if gated.is_empty() { + .fold((0.0, 0_usize), |(sum, count), energy| { + (sum + energy, count + 1) + }); + if gated_count == 0 { return f64::NEG_INFINITY; } - let gated_mean = gated.iter().sum::() / gated.len() as f64; + let gated_mean = gated_sum / gated_count as f64; let relative_gate = gated_mean * 10.0_f64.powf(RELATIVE_GATE_LU / 10.0); - let final_blocks: Vec = gated.into_iter().filter(|&e| e >= relative_gate).collect(); - if final_blocks.is_empty() { + let (final_sum, final_count) = blocks + .iter() + .copied() + .filter(|&e| e >= absolute_gate && e >= relative_gate) + .fold((0.0, 0_usize), |(sum, count), energy| { + (sum + energy, count + 1) + }); + if final_count == 0 { return f64::NEG_INFINITY; } - let final_mean = final_blocks.iter().sum::() / final_blocks.len() as f64; + let final_mean = final_sum / final_count as f64; LOUDNESS_OFFSET + 10.0 * final_mean.log10() } } diff --git a/src/common/true_peak.rs b/src/common/true_peak.rs index 45f5bb2..2026617 100644 --- a/src/common/true_peak.rs +++ b/src/common/true_peak.rs @@ -56,7 +56,7 @@ fn phase_taps(factor: usize, phase: usize) -> [f32; TRUE_PEAK_TAPS] { /// Polyphase interpolator producing `factor` sub-samples per input sample. pub struct TruePeakDetector { factor: usize, - taps: Vec<[f32; TRUE_PEAK_TAPS]>, + taps: [[f32; TRUE_PEAK_TAPS]; 8], state: [f32; TRUE_PEAK_TAPS], position: usize, } @@ -73,13 +73,30 @@ impl TruePeakDetector { } else { 1 }; - let taps = (0..factor).map(|phase| phase_taps(factor, phase)).collect(); - Self { + let mut detector = Self { factor, - taps, + taps: [[0.0; TRUE_PEAK_TAPS]; 8], state: [0.0; TRUE_PEAK_TAPS], position: 0, + }; + detector.set_factor(factor); + detector + } + + pub fn set_factor(&mut self, factor: usize) { + self.factor = if factor >= 8 { + 8 + } else if factor >= 4 { + 4 + } else if factor >= 2 { + 2 + } else { + 1 + }; + for (phase, taps) in self.taps.iter_mut().enumerate().take(self.factor) { + *taps = phase_taps(self.factor, phase); } + self.reset(); } pub fn factor(&self) -> usize { @@ -109,7 +126,7 @@ impl TruePeakDetector { self.state[self.position] = x; let mask = TRUE_PEAK_TAPS - 1; let mut peak = 0.0_f32; - for phase_taps in &self.taps { + for phase_taps in self.taps.iter().take(self.factor) { let mut acc = 0.0_f32; for (k, &tap) in phase_taps.iter().enumerate() { let index = (self.position + TRUE_PEAK_TAPS - k) & mask; diff --git a/src/delay/dsp.rs b/src/delay/dsp.rs index eee382f..528091b 100644 --- a/src/delay/dsp.rs +++ b/src/delay/dsp.rs @@ -37,10 +37,10 @@ impl Default for Delay { current_delay: 0.0, chase: 0.0, sample_rate: 48_000.0, - temp_dry_l: vec![0.0; 1024], - temp_dry_r: vec![0.0; 1024], - temp_wet_l: vec![0.0; 1024], - temp_wet_r: vec![0.0; 1024], + temp_dry_l: vec![0.0; 16_384], + temp_dry_r: vec![0.0; 16_384], + temp_wet_l: vec![0.0; 16_384], + temp_wet_r: vec![0.0; 16_384], } } } @@ -50,6 +50,13 @@ impl Delay { self.sample_rate = sample_rate; } + pub fn prepare(&mut self, max_frames: usize) { + self.temp_dry_l = vec![0.0; max_frames]; + self.temp_dry_r = vec![0.0; max_frames]; + self.temp_wet_l = vec![0.0; max_frames]; + self.temp_wet_r = vec![0.0; max_frames]; + } + pub fn reset(&mut self) { self.buf_l.fill(0.0); self.buf_r.fill(0.0); @@ -113,14 +120,6 @@ impl Delay { let max_len = self.buf_l.len(); let frames = left.len().min(right.len()); - if self.temp_dry_l.len() < frames { - let new_len = frames.next_power_of_two(); - self.temp_dry_l.resize(new_len, 0.0); - self.temp_dry_r.resize(new_len, 0.0); - self.temp_wet_l.resize(new_len, 0.0); - self.temp_wet_r.resize(new_len, 0.0); - } - for i in 0..frames { let wp = self.write_pos; let delayed_l = Self::read_interp(&self.buf_l, wp, self.current_delay); diff --git a/src/delay/plugin.rs b/src/delay/plugin.rs index f6220f2..78f44fd 100644 --- a/src/delay/plugin.rs +++ b/src/delay/plugin.rs @@ -162,6 +162,7 @@ impl AudioProcessor { fn new(sample_rate: f64, max_frames: u32, bus_data: Option) -> Self { let mut dsp = Delay::default(); dsp.set_sample_rate(sample_rate); + dsp.prepare(max_frames as usize); Self { dsp, temp_left: vec![0.0; max_frames as usize], diff --git a/src/drums/engine/limiter.rs b/src/drums/engine/limiter.rs index 12aa4cf..2a2e78b 100644 --- a/src/drums/engine/limiter.rs +++ b/src/drums/engine/limiter.rs @@ -5,6 +5,7 @@ pub struct Limiter { release_coeff: f32, gain_reduction: f32, enabled: bool, + gains: Vec, } impl Default for Limiter { @@ -22,9 +23,14 @@ impl Limiter { release_coeff: 1.0 - (-1000.0 / (release_ms * sr)).exp(), gain_reduction: 1.0, enabled: true, + gains: Vec::new(), } } + pub fn prepare(&mut self, max_frames: usize) { + self.gains = vec![1.0; max_frames]; + } + pub fn set_enabled(&mut self, enabled: bool) { self.enabled = enabled; } @@ -44,20 +50,12 @@ impl Limiter { self.release_coeff = 1.0 - (-1000.0 / (release_ms * sr)).exp(); } - pub fn process(&mut self, buffers: &mut [Vec], frames: usize) { - if !self.enabled || buffers.is_empty() { - return; - } - let mut slices: Vec<&mut [f32]> = buffers.iter_mut().map(|b| b.as_mut_slice()).collect(); - self.process_slices(&mut slices, frames); - } - pub fn process_slices(&mut self, slices: &mut [&mut [f32]], frames: usize) { if !self.enabled || slices.is_empty() { return; } - let mut gains = vec![1.0f32; frames]; + let gains = &mut self.gains[..frames]; #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] unsafe { diff --git a/src/drums/engine/mod.rs b/src/drums/engine/mod.rs index c7446cd..fec0d6f 100644 --- a/src/drums/engine/mod.rs +++ b/src/drums/engine/mod.rs @@ -115,6 +115,7 @@ unsafe impl Send for ChannelPlayback {} #[derive(Debug)] pub struct AudioState { pub voices: Vec, + pub voice_pool: Vec, pub velocity_filter: VelocityFilter, pub powermap_filter: PowermapFilter, pub stamina_filter: StaminaFilter, @@ -127,19 +128,29 @@ impl Default for AudioState { fn default() -> Self { Self { voices: Vec::with_capacity(MAX_VOICES), + voice_pool: (0..MAX_VOICES) + .map(|_| Voice { + instrument_index: 0, + sample_index: 0, + velocity: 0.0, + active: false, + playback_position: 0, + playbacks: Vec::with_capacity(MAX_CHANNELS), + }) + .collect(), velocity_filter: VelocityFilter::new(0.08), powermap_filter: PowermapFilter::new(false), stamina_filter: StaminaFilter::new(0.5, 0.25), latency_filter: LatencyFilter::new(5.0, 20.0), humanizer_rng: LockFreeRandom::default(), - last_sample_index: Vec::new(), + last_sample_index: vec![None; 128], } } } impl AudioState { pub fn reset(&mut self, seed: u64) { - self.voices.clear(); + self.voice_pool.append(&mut self.voices); self.last_sample_index.fill(None); if seed > 0 { self.velocity_filter.set_seed(seed); @@ -262,26 +273,38 @@ fn select_sample_with_diversity( let target_power = min_power + velocity * (max_power - min_power); let tolerance = (max_power - min_power) * 0.25; - let mut candidates: Vec = Vec::with_capacity(4); + let mut candidate_storage = [0_usize; 4]; + let mut candidate_count = 0; for (i, sample) in instr.samples.iter().enumerate() { - if (sample.power - target_power).abs() < tolerance && candidates.len() < 4 { - candidates.push(i); + if (sample.power - target_power).abs() < tolerance && candidate_count < 4 { + candidate_storage[candidate_count] = i; + candidate_count += 1; } } - if candidates.is_empty() { - let mut sorted: Vec<(usize, f32)> = instr - .samples - .iter() - .enumerate() - .map(|(i, s)| (i, (s.power - target_power).abs())) - .collect(); - sorted.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); - for (i, _) in sorted.into_iter().take(4) { - candidates.push(i); + if candidate_count == 0 { + let mut nearest = [(0_usize, f32::INFINITY); 4]; + for (index, sample) in instr.samples.iter().enumerate() { + let distance = (sample.power - target_power).abs(); + if let Some(slot) = nearest + .iter_mut() + .rev() + .find(|(_, best_distance)| distance < *best_distance) + { + *slot = (index, distance); + nearest.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); + } + } + for (candidate, (index, _)) in candidate_storage + .iter_mut() + .zip(nearest.into_iter().take(instr.samples.len().min(4))) + { + *candidate = index; + candidate_count += 1; } } + let candidates = &candidate_storage[..candidate_count]; if candidates.is_empty() { return Some(0); } @@ -294,7 +317,7 @@ fn select_sample_with_diversity( if round_robin_mix < 0.01 { let mut best_idx = candidates[0]; let mut best_dist = f32::INFINITY; - for &idx in &candidates { + for &idx in candidates { let dist = (instr.samples[idx].power - target_power).abs(); if dist < best_dist { best_dist = dist; @@ -308,9 +331,9 @@ fn select_sample_with_diversity( Some(candidates[next]) } else { let mut total_weight = 0.0f32; - let mut weights: Vec<(usize, f32)> = Vec::with_capacity(candidates.len()); + let mut weights = [(0_usize, 0.0_f32); 4]; - for &idx in &candidates { + for (weight_slot, &idx) in weights.iter_mut().zip(candidates) { let dist = (instr.samples[idx].power - target_power).abs(); let mut weight = 1.0 / (1.0 + dist * 5.0); @@ -329,13 +352,13 @@ fn select_sample_with_diversity( weight *= 1.0 + round_robin_mix * 1.5; } - weights.push((idx, weight)); + *weight_slot = (idx, weight); total_weight += weight; } let random_value = rng.next_f32() * total_weight; let mut cumulative = 0.0f32; - for (idx, weight) in weights { + for (idx, weight) in weights.into_iter().take(candidate_count) { cumulative += weight; if random_value <= cumulative { return Some(idx); @@ -833,7 +856,33 @@ impl DrumGizmoEngine { let sample = &instr.samples[sample_idx]; state.last_sample_index[event.instrument_index] = Some(sample_idx); - let mut playbacks = Vec::with_capacity(sample.audiofiles.len()); + if state.voices.len() >= MAX_VOICES { + let mut best_idx = None; + let mut best_score = i64::MIN; + for (i, voice) in state.voices.iter().enumerate() { + if !voice.active { + continue; + } + let mut score = voice.playback_position as i64; + if score < 2000 { + score -= 1_000_000; + } + if voice.playbacks.iter().any(|pb| pb.delay_remaining > 0) { + score -= 10_000_000; + } + if score > best_score { + best_score = score; + best_idx = Some(i); + } + } + let index = best_idx.unwrap_or(0); + let voice = state.voices.remove(index); + state.voice_pool.push(voice); + } + let Some(mut new_voice) = state.voice_pool.pop() else { + return; + }; + new_voice.playbacks.clear(); for af in &sample.audiofiles { if let Some(&file_idx) = audio_index.get(&af.abs_path) @@ -860,7 +909,7 @@ impl DrumGizmoEngine { }; let buffer = &audio_file.channels[loaded_channel]; - playbacks.push(ChannelPlayback { + new_voice.playbacks.push(ChannelPlayback { audio_ref: AudioRef { file_index: file_idx, filechannel: af.filechannel, @@ -880,107 +929,82 @@ impl DrumGizmoEngine { } } - if !playbacks.is_empty() { - let num_both = playbacks + if !new_voice.playbacks.is_empty() { + let num_both = new_voice + .playbacks .iter() .filter(|pb| matches!(pb.side, ChannelSide::Both)) .count(); if num_both > 1 { let channel_gain = 1.0 / (num_both as f32).sqrt(); - for pb in &mut playbacks { + for pb in &mut new_voice.playbacks { pb.gain *= channel_gain; } } } - if !playbacks.is_empty() { - if !instr.group.is_empty() { - for voice in &mut state.voices { - if !voice.active { - continue; - } - if voice.instrument_index == event.instrument_index { - continue; - } - if let Some(other_instr) = - kit.instruments.get(voice.instrument_index) - && other_instr.group == instr.group - { - let ramp_samples = (0.068 * sr) as usize; - for pb in &mut voice.playbacks { - if pb.rampdown_samples.is_none() { - pb.rampdown_total = ramp_samples.max(1); - pb.rampdown_samples = Some(pb.rampdown_total); - } - } - } - } - } + if new_voice.playbacks.is_empty() { + state.voice_pool.push(new_voice); + return; + } - let same_instr_count = state - .voices - .iter() - .filter(|v| v.active && v.instrument_index == event.instrument_index) - .count(); - if same_instr_count >= voice_limit_max { - let to_ramp = same_instr_count - voice_limit_max + 1; - let ramp_samples = (voice_limit_rampdown * sr) as usize; - let mut ramped = 0; - for voice in &mut state.voices { - if !voice.active { - continue; - } - if voice.instrument_index != event.instrument_index { - continue; - } - if ramped >= to_ramp { - break; - } + if !instr.group.is_empty() { + for voice in &mut state.voices { + if !voice.active { + continue; + } + if voice.instrument_index == event.instrument_index { + continue; + } + if let Some(other_instr) = kit.instruments.get(voice.instrument_index) + && other_instr.group == instr.group + { + let ramp_samples = (0.068 * sr) as usize; for pb in &mut voice.playbacks { if pb.rampdown_samples.is_none() { pb.rampdown_total = ramp_samples.max(1); pb.rampdown_samples = Some(pb.rampdown_total); } } - ramped += 1; } } + } - if state.voices.len() >= MAX_VOICES { - let mut best_idx = None; - let mut best_score = i64::MIN; - for (i, voice) in state.voices.iter().enumerate() { - if !voice.active { - continue; - } - let mut score = voice.playback_position as i64; - if score < 2000 { - score -= 1_000_000; - } - if voice.playbacks.iter().any(|pb| pb.delay_remaining > 0) { - score -= 10_000_000; - } - if score > best_score { - best_score = score; - best_idx = Some(i); - } + let same_instr_count = state + .voices + .iter() + .filter(|v| v.active && v.instrument_index == event.instrument_index) + .count(); + if same_instr_count >= voice_limit_max { + let to_ramp = same_instr_count - voice_limit_max + 1; + let ramp_samples = (voice_limit_rampdown * sr) as usize; + let mut ramped = 0; + for voice in &mut state.voices { + if !voice.active { + continue; + } + if voice.instrument_index != event.instrument_index { + continue; } - if let Some(idx) = best_idx { - state.voices.remove(idx); - } else { - state.voices.remove(0); + if ramped >= to_ramp { + break; } + for pb in &mut voice.playbacks { + if pb.rampdown_samples.is_none() { + pb.rampdown_total = ramp_samples.max(1); + pb.rampdown_samples = Some(pb.rampdown_total); + } + } + ramped += 1; } - - state.voices.push(Voice { - instrument_index: event.instrument_index, - sample_index: sample_idx, - velocity, - active: true, - playback_position: 0, - playbacks, - }); } + + new_voice.instrument_index = event.instrument_index; + new_voice.sample_index = sample_idx; + new_voice.velocity = velocity; + new_voice.active = true; + new_voice.playback_position = 0; + state.voices.push(new_voice); } } EventType::Choke => { @@ -1141,7 +1165,15 @@ impl DrumGizmoEngine { } } - state.voices.retain(|v| v.active); + let mut index = 0; + while index < state.voices.len() { + if state.voices[index].active { + index += 1; + } else { + let voice = state.voices.remove(index); + state.voice_pool.push(voice); + } + } } pub fn render(&self, frames: usize, outputs: &mut [Vec]) { @@ -1239,7 +1271,15 @@ impl DrumGizmoEngine { } } - state.voices.retain(|v| v.active); + let mut index = 0; + while index < state.voices.len() { + if state.voices[index].active { + index += 1; + } else { + let voice = state.voices.remove(index); + state.voice_pool.push(voice); + } + } } } diff --git a/src/drums/plugin.rs b/src/drums/plugin.rs index 77689aa..9cd884f 100644 --- a/src/drums/plugin.rs +++ b/src/drums/plugin.rs @@ -87,6 +87,7 @@ impl AudioProcessor { engine.set_sample_rate(sample_rate as f32); let mut limiter = Limiter::default(); limiter.set_sample_rate(sample_rate as f32); + limiter.prepare(max_frames as usize); Self { shared, engine, @@ -104,27 +105,24 @@ impl AudioProcessor { let kit_ready = self.engine.kit_ready.load(Ordering::Acquire); - let mut out_outputs: Vec> = Vec::with_capacity(MAX_CHANNELS); + let mut out_outputs: [Option<&mut [f32]>; MAX_CHANNELS] = std::array::from_fn(|_| None); let output_count = process.audio_outputs_count() as usize; + let output_channels = output_count.min(MAX_CHANNELS / 2) * 2; for out in 0..output_count.min(MAX_CHANNELS / 2) { let mut port = process.audio_outputs(out as u32); if port.channel_count() >= 1 { unsafe { let buf_l = std::slice::from_raw_parts_mut(port.data32(0).as_mut_ptr(), frames); buf_l.fill(0.0); - out_outputs.push(Some(buf_l)); + out_outputs[out * 2] = Some(buf_l); } - } else { - out_outputs.push(None); } if port.channel_count() >= 2 { unsafe { let buf_r = std::slice::from_raw_parts_mut(port.data32(1).as_mut_ptr(), frames); buf_r.fill(0.0); - out_outputs.push(Some(buf_r)); + out_outputs[out * 2 + 1] = Some(buf_r); } - } else { - out_outputs.push(None); } } @@ -210,7 +208,8 @@ impl AudioProcessor { self.last_params_version = params_version; } if !bypass && kit_ready { - self.engine.render_outputs(frames, &mut out_outputs); + self.engine + .render_outputs(frames, &mut out_outputs[..output_channels]); } let gain = 10.0_f32.powf(self.shared.params.get(ParamId::MasterGain) as f32 * 0.05); @@ -246,15 +245,18 @@ impl AudioProcessor { } } - let mut flat_slices: Vec<&mut [f32]> = Vec::with_capacity(MAX_CHANNELS); + let mut flat_slices: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| &mut [][..]); + let mut flat_count = 0; for buf in out_outputs.iter_mut().flatten() { - flat_slices.push(buf); + flat_slices[flat_count] = buf; + flat_count += 1; } let limiter_threshold = self.shared.params.get(ParamId::LimiterThreshold) as f32; self.limiter.set_enabled(limiter_threshold < 0.0); self.limiter.set_threshold_db(limiter_threshold); - self.limiter.process_slices(&mut flat_slices, frames); + self.limiter + .process_slices(&mut flat_slices[..flat_count], frames); if let Some(ref bus) = self.bus_data && bus::needs(bus::NEED_FFT) diff --git a/src/eq/dsp.rs b/src/eq/dsp.rs index 1a4ea76..0654c93 100644 --- a/src/eq/dsp.rs +++ b/src/eq/dsp.rs @@ -80,10 +80,24 @@ pub fn build_chain( q: f32, gain_db: f32, ) -> Vec { + let mut chain = Vec::with_capacity(2 * slope_stages(effective_slope(shape, slope))); + build_chain_into(&mut chain, shape, slope, sample_rate, freq, q, gain_db); + chain +} + +pub fn build_chain_into( + chain: &mut Vec, + shape: u8, + slope: u8, + sample_rate: f32, + freq: f32, + q: f32, + gain_db: f32, +) { + chain.clear(); let slope = effective_slope(shape, slope); let n = slope_stages(slope); let stage_gain = gain_db / n as f32; - let mut chain = Vec::with_capacity(2 * n); for stage in 0..n { let stage_q = cut_stage_q(shape, slope, stage, q); let mut b = Biquad::default(); @@ -125,7 +139,6 @@ pub fn build_chain( } } } - chain } fn chain_len(shape: u8, slope: u8) -> usize { diff --git a/src/eq/linear_phase.rs b/src/eq/linear_phase.rs index 54d935c..f70d45e 100644 --- a/src/eq/linear_phase.rs +++ b/src/eq/linear_phase.rs @@ -35,6 +35,9 @@ pub struct LinearPhaseEq { ola: [Vec; 2], frame: Vec, product: Vec, + fft_scratch: Vec, + ifft_scratch: Vec, + chain: Vec, designs: Vec, redesign_pending: bool, redesign_countdown: usize, @@ -53,6 +56,8 @@ impl LinearPhaseEq { let mut planner = FftPlanner::::new(); let fft = planner.plan_fft_forward(LP_FFT); let ifft = planner.plan_fft_inverse(LP_FFT); + let fft_scratch = vec![Complex32::ZERO; fft.get_inplace_scratch_len()]; + let ifft_scratch = vec![Complex32::ZERO; ifft.get_inplace_scratch_len()]; Self { fft, ifft, @@ -61,7 +66,10 @@ impl LinearPhaseEq { ola: [vec![0.0; LP_FFT], vec![0.0; LP_FFT]], frame: vec![Complex32::ZERO; LP_FFT], product: vec![Complex32::ZERO; LP_FFT], - designs: Vec::new(), + fft_scratch, + ifft_scratch, + chain: Vec::with_capacity(2 * dsp::slope_stages(dsp::SLOPE_BRICKWALL)), + designs: Vec::with_capacity(dsp::MAX_BANDS), redesign_pending: true, redesign_countdown: 0, consumed: 0, @@ -92,17 +100,19 @@ impl LinearPhaseEq { self.redesign_countdown = (sample_rate as usize / LP_BLOCK / 10).max(1); } else { self.redesign_pending = true; - self.designs = designs.to_vec(); + self.designs.clear(); + self.designs.extend_from_slice(designs); } } fn redesign(&mut self, designs: &[BandDesign], sample_rate: f32) { - self.designs = designs.to_vec(); + self.designs.clear(); + self.designs.extend_from_slice(designs); self.redesign_pending = false; + let mut chain = std::mem::take(&mut self.chain); let bin_hz = sample_rate / LP_FFT as f32; - let mut spec = vec![Complex32::ZERO; LP_FFT]; - for (k, h) in spec.iter_mut().enumerate().take(LP_FFT / 2 + 1) { + for (k, h) in self.product.iter_mut().enumerate().take(LP_FFT / 2 + 1) { let freq = k as f32 * bin_hz; let mut re = 1.0_f32; let mut im = 0.0_f32; @@ -110,7 +120,8 @@ impl LinearPhaseEq { if !design.on || freq < 1.0 { continue; } - let chain = dsp::build_chain( + dsp::build_chain_into( + &mut chain, design.shape, design.slope, sample_rate, @@ -128,26 +139,29 @@ impl LinearPhaseEq { *h = Complex32::new(re, im); } for k in LP_FFT / 2 + 1..LP_FFT { - spec[k] = spec[LP_FFT - k].conj(); + self.product[k] = self.product[LP_FFT - k].conj(); } - self.frame.copy_from_slice(&spec); - self.ifft.process(&mut self.frame); + self.frame.copy_from_slice(&self.product); + self.ifft + .process_with_scratch(&mut self.frame, &mut self.ifft_scratch); // Extract the centered LP_IR_LEN tap window and Hann-window it. - let mut ir = vec![0.0_f32; LP_FFT]; - for (i, tap) in ir.iter_mut().enumerate().take(LP_IR_LEN) { - let src = (i + LP_FFT - LP_IR_LEN / 2) % LP_FFT; - let w = - 0.5 - 0.5 * (2.0 * std::f32::consts::PI * i as f32 / (LP_IR_LEN - 1) as f32).cos(); - *tap = self.frame[src].re * w / LP_FFT as f32; - } - self.frame.iter_mut().for_each(|c| *c = Complex32::ZERO); - for (i, c) in self.frame.iter_mut().enumerate().take(LP_IR_LEN) { - *c = Complex32::new(ir[i], 0.0); + for (i, tap) in self.product.iter_mut().enumerate() { + *tap = if i < LP_IR_LEN { + let src = (i + LP_FFT - LP_IR_LEN / 2) % LP_FFT; + let w = 0.5 + - 0.5 * (2.0 * std::f32::consts::PI * i as f32 / (LP_IR_LEN - 1) as f32).cos(); + Complex32::new(self.frame[src].re * w / LP_FFT as f32, 0.0) + } else { + Complex32::ZERO + }; } - self.fft.process(&mut self.frame); + self.frame.copy_from_slice(&self.product); + self.fft + .process_with_scratch(&mut self.frame, &mut self.fft_scratch); self.ir_spec.copy_from_slice(&self.frame); + self.chain = chain; } fn process_block(&mut self, channels: usize) { @@ -160,11 +174,13 @@ impl LinearPhaseEq { Complex32::ZERO }; } - self.fft.process(&mut self.frame); + self.fft + .process_with_scratch(&mut self.frame, &mut self.fft_scratch); for (i, p) in self.product.iter_mut().enumerate() { *p = self.frame[i] * self.ir_spec[i]; } - self.ifft.process(&mut self.product); + self.ifft + .process_with_scratch(&mut self.product, &mut self.ifft_scratch); let scale = 1.0 / LP_FFT as f32; for (i, p) in self .product diff --git a/src/eq/spectral.rs b/src/eq/spectral.rs index da517e0..98bb1b7 100644 --- a/src/eq/spectral.rs +++ b/src/eq/spectral.rs @@ -47,6 +47,8 @@ struct SpectralBand { region: Vec, env_db: Vec, gain_db: Vec, + threshold_chain: Vec, + target_chain: Vec, attack_coef: f32, release_coef: f32, gain_smooth: f32, @@ -62,6 +64,8 @@ impl SpectralBand { region: vec![false; NUM_BINS], env_db: vec![-120.0; NUM_BINS], gain_db: vec![0.0; NUM_BINS], + threshold_chain: Vec::with_capacity(2 * dsp::slope_stages(dsp::SLOPE_BRICKWALL)), + target_chain: Vec::with_capacity(2 * dsp::slope_stages(dsp::SLOPE_BRICKWALL)), attack_coef: 0.0, release_coef: 0.0, gain_smooth: 0.0, @@ -83,7 +87,8 @@ impl SpectralBand { self.gain_smooth = (-hop_dt / 0.010).exp(); let sense = dsp::detector_biquad(config.shape, sample_rate, config.freq, config.q); - let threshold_chain = dsp::build_chain( + dsp::build_chain_into( + &mut self.threshold_chain, config.shape, config.slope, sample_rate, @@ -96,7 +101,8 @@ impl SpectralBand { } else { 0.0 }; - let target_chain = dsp::build_chain( + dsp::build_chain_into( + &mut self.target_chain, config.shape, config.slope, sample_rate, @@ -104,6 +110,8 @@ impl SpectralBand { config.q, target_gain, ); + let threshold_chain = &self.threshold_chain; + let target_chain = &self.target_chain; let bin_hz = sample_rate / SPECTRAL_FFT_SIZE as f32; for bin in 0..NUM_BINS { let freq = bin as f32 * bin_hz; @@ -195,6 +203,8 @@ pub struct SpectralDynamics { window: Vec, frame: Vec, sc_frame: Vec, + fft_scratch: Vec, + ifft_scratch: Vec, specs: [Vec; 2], sc_spec: Vec, bands: Vec, @@ -214,6 +224,8 @@ impl SpectralDynamics { let mut planner = FftPlanner::::new(); let fft = planner.plan_fft_forward(SPECTRAL_FFT_SIZE); let ifft = planner.plan_fft_inverse(SPECTRAL_FFT_SIZE); + let fft_scratch = vec![Complex32::ZERO; fft.get_inplace_scratch_len()]; + let ifft_scratch = vec![Complex32::ZERO; ifft.get_inplace_scratch_len()]; let window = (0..SPECTRAL_FFT_SIZE) .map(|i| { 0.5 - 0.5 @@ -230,6 +242,8 @@ impl SpectralDynamics { window, frame: vec![Complex32::ZERO; SPECTRAL_FFT_SIZE], sc_frame: vec![Complex32::ZERO; SPECTRAL_FFT_SIZE], + fft_scratch, + ifft_scratch, specs: [ vec![Complex32::ZERO; SPECTRAL_FFT_SIZE], vec![Complex32::ZERO; SPECTRAL_FFT_SIZE], @@ -377,7 +391,7 @@ impl SpectralDynamics { let idx = (start + i) % SPECTRAL_FFT_SIZE; *f = Complex32::new(src[idx] * w, 0.0); } - self.fft.process(frame); + self.fft.process_with_scratch(frame, &mut self.fft_scratch); if sidechain { self.sc_spec.copy_from_slice(frame); } else { @@ -464,7 +478,8 @@ impl SpectralDynamics { let start = self.consumed - SPECTRAL_FFT_SIZE; for ch in 0..channels { self.frame.copy_from_slice(&self.specs[ch]); - self.ifft.process(&mut self.frame); + self.ifft + .process_with_scratch(&mut self.frame, &mut self.ifft_scratch); for i in 0..SPECTRAL_FFT_SIZE { let slot = (start + i) % SPECTRAL_FFT_SIZE; self.ola[ch][slot] += self.frame[i].re * self.window[i] / SPECTRAL_FFT_SIZE as f32; diff --git a/src/kick/dsp/mod.rs b/src/kick/dsp/mod.rs index 3e16dfd..d8295e2 100644 --- a/src/kick/dsp/mod.rs +++ b/src/kick/dsp/mod.rs @@ -30,6 +30,7 @@ pub const OSCILLATORS_PER_LAYER: usize = 2; pub const LAYERS_PER_INSTRUMENT: usize = 3; pub const INSTRUMENTS_PER_KIT: usize = 16; const MAX_SAMPLES: usize = 192_000 * 4; +const RENDER_BLOCK: usize = 1024; #[derive(Clone)] pub struct Layer { @@ -80,45 +81,47 @@ impl Layer { return; } - let mut osc_bufs: [Vec; OSCILLATORS_PER_LAYER] = - [vec![0.0; num_samples], vec![0.0; num_samples]]; - - for i in 0..OSCILLATORS_PER_LAYER { - self.oscillators[i].set_midi_note(midi_note); - let fm_src = self.fm_routing[i] as usize; - let fm_input = if fm_src != i && fm_src < OSCILLATORS_PER_LAYER { - let fm_buf = unsafe { &*std::ptr::addr_of!(osc_bufs[fm_src]) }; - Some(fm_buf.as_slice()) - } else { - None - }; - let buf = unsafe { &mut *std::ptr::addr_of_mut!(osc_bufs[i]) }; - self.oscillators[i].render(buf, num_samples, fm_input); - } + let mut osc_bufs = [[0.0_f32; RENDER_BLOCK]; OSCILLATORS_PER_LAYER]; + let mut noise_buf = [0.0_f32; RENDER_BLOCK]; + let mut dist_vol_buf = [0.0_f32; RENDER_BLOCK]; + for out in out[..num_samples].chunks_mut(RENDER_BLOCK) { + let chunk_len = out.len(); + for i in 0..OSCILLATORS_PER_LAYER { + self.oscillators[i].set_midi_note(midi_note); + let fm_src = self.fm_routing[i] as usize; + let fm_input = if fm_src != i && fm_src < OSCILLATORS_PER_LAYER { + let fm_buf = unsafe { &*std::ptr::addr_of!(osc_bufs[fm_src]) }; + Some(&fm_buf[..chunk_len]) + } else { + None + }; + let buf = unsafe { &mut *std::ptr::addr_of_mut!(osc_bufs[i]) }; + self.oscillators[i].render(&mut buf[..chunk_len], chunk_len, fm_input); + } - out[..num_samples].fill(0.0); - for buf in &osc_bufs { - simd::add_inplace(out, buf); - } + out.fill(0.0); + for buf in &osc_bufs { + simd::add_inplace(out, &buf[..chunk_len]); + } - let mut noise_buf = vec![0.0f32; num_samples]; - self.noise.render(&mut noise_buf, num_samples); - simd::add_inplace(out, &noise_buf); + self.noise.render(&mut noise_buf, chunk_len); + simd::add_inplace(out, &noise_buf[..chunk_len]); - self.filter.filter_type = self.filter_type; - self.filter - .prepare_block(self.filter_cutoff_hz, self.filter_q, num_samples); - self.filter.process_block(out); + self.filter.filter_type = self.filter_type; + self.filter + .prepare_block(self.filter_cutoff_hz, self.filter_q, chunk_len); + self.filter.process_block(out); - let mut dist_vol_buf = vec![0.0f32; num_samples]; - self.distortion - .volume_env - .fill_buffer(&mut dist_vol_buf, 1.0 / num_samples.max(1) as f32); - self.distortion - .process_block_modulated(out, None, Some(&dist_vol_buf)); + let dist_vol = &mut dist_vol_buf[..chunk_len]; + self.distortion + .volume_env + .fill_buffer(dist_vol, 1.0 / chunk_len.max(1) as f32); + self.distortion + .process_block_modulated(out, None, Some(dist_vol)); - if (self.amplitude - 1.0).abs() > 1.0e-6 { - crate::kick::simd_kick::mul_gain_inplace(out, self.amplitude); + if (self.amplitude - 1.0).abs() > 1.0e-6 { + crate::kick::simd_kick::mul_gain_inplace(out, self.amplitude); + } } } } @@ -204,42 +207,47 @@ impl Instrument { } pub fn render(&mut self, out: &mut [f32], num_samples: usize, midi_note: u8) { - let mut mix = vec![0.0f32; num_samples]; + let mut mix = [0.0_f32; RENDER_BLOCK]; + let mut layer_buf = [0.0_f32; RENDER_BLOCK]; + let mut dist_vol_buf = [0.0_f32; RENDER_BLOCK]; + let mut env_buf = [0.0_f32; RENDER_BLOCK]; + for out in out[..num_samples].chunks_mut(RENDER_BLOCK) { + let chunk_len = out.len(); + let mix = &mut mix[..chunk_len]; + mix.fill(0.0); + for layer in &mut self.layers { + layer.render(&mut layer_buf, chunk_len, midi_note); + simd::add_inplace(mix, &layer_buf[..chunk_len]); + } - for layer in &mut self.layers { - let mut layer_buf = vec![0.0f32; num_samples]; - layer.render(&mut layer_buf, num_samples, midi_note); - simd::add_inplace(&mut mix, &layer_buf); - } + self.master_filter.filter_type = self.master_filter_type; + self.master_filter.prepare_block( + self.master_filter_cutoff_hz, + self.master_filter_q, + chunk_len, + ); + self.master_filter.process_block(mix); + + let dist_vol = &mut dist_vol_buf[..chunk_len]; + self.master_distortion + .volume_env + .fill_buffer(dist_vol, 1.0 / chunk_len.max(1) as f32); + self.master_distortion + .process_block_modulated(mix, None, Some(dist_vol)); + + let dt = 1.0 / chunk_len.max(1) as f32; + let env = &mut env_buf[..chunk_len]; + self.global_amp_env.fill_buffer(env, dt); + simd::mul_per_sample_inplace(mix, env); + + let gain_lin = db_to_linear(self.output_gain_db); + if (gain_lin - 1.0).abs() > 1.0e-6 { + crate::kick::simd_kick::mul_gain_inplace(mix, gain_lin); + } - self.master_filter.filter_type = self.master_filter_type; - self.master_filter.prepare_block( - self.master_filter_cutoff_hz, - self.master_filter_q, - num_samples, - ); - self.master_filter.process_block(&mut mix); - - let mut dist_vol_buf = vec![0.0f32; num_samples]; - self.master_distortion - .volume_env - .fill_buffer(&mut dist_vol_buf, 1.0 / num_samples.max(1) as f32); - self.master_distortion - .process_block_modulated(&mut mix, None, Some(&dist_vol_buf)); - - let dt = 1.0 / num_samples.max(1) as f32; - let mut env_buf = vec![0.0f32; num_samples]; - self.global_amp_env.fill_buffer(&mut env_buf, dt); - simd::mul_per_sample_inplace(&mut mix, &env_buf); - - let gain_lin = db_to_linear(self.output_gain_db); - if (gain_lin - 1.0).abs() > 1.0e-6 { - crate::kick::simd_kick::mul_gain_inplace(&mut mix, gain_lin); + self.master_limiter.process_block(mix); + out.copy_from_slice(mix); } - - self.master_limiter.process_block(&mut mix); - - out[..num_samples].copy_from_slice(&mix); } } diff --git a/src/kick/dsp/noise.rs b/src/kick/dsp/noise.rs index dc20649..ed33f46 100644 --- a/src/kick/dsp/noise.rs +++ b/src/kick/dsp/noise.rs @@ -168,30 +168,35 @@ impl NoiseGenerator { } pub fn render(&mut self, out: &mut [f32], num_samples: usize) { - let dt = 1.0 / num_samples.max(1) as f32; - let mut env_buf = vec![0.0f32; num_samples]; - let mut density_buf = vec![0.0f32; num_samples]; - self.amp_env.fill_buffer_linear(&mut env_buf, dt); - self.density_env.fill_buffer_linear(&mut density_buf, dt); - - let thresh = (1.0 - self.density) * u32::MAX as f32; - for i in 0..num_samples { - let sample = if self.rng.next_u32() as f32 >= thresh { - let white = self.rng.next_f32(); - match self.noise_type { - NoiseType::White => white, - NoiseType::Pink => self.pink.next(white), - NoiseType::Brownian => self.brown.next(white), - } - } else { - 0.0 - }; - out[i] = sample * self.amplitude * env_buf[i] * density_buf[i]; + let mut env_buf = [0.0_f32; super::RENDER_BLOCK]; + let mut density_buf = [0.0_f32; super::RENDER_BLOCK]; + for out in out[..num_samples].chunks_mut(super::RENDER_BLOCK) { + let chunk_len = out.len(); + let dt = 1.0 / chunk_len.max(1) as f32; + let env = &mut env_buf[..chunk_len]; + let density = &mut density_buf[..chunk_len]; + self.amp_env.fill_buffer_linear(env, dt); + self.density_env.fill_buffer_linear(density, dt); + + let thresh = (1.0 - self.density) * u32::MAX as f32; + for i in 0..chunk_len { + let sample = if self.rng.next_u32() as f32 >= thresh { + let white = self.rng.next_f32(); + match self.noise_type { + NoiseType::White => white, + NoiseType::Pink => self.pink.next(white), + NoiseType::Brownian => self.brown.next(white), + } + } else { + 0.0 + }; + out[i] = sample * self.amplitude * env[i] * density[i]; + } + + self.filter.filter_type = self.filter_type; + self.filter + .prepare_block(self.filter_cutoff_hz, self.filter_q, chunk_len); + self.filter.process_block(out); } - - self.filter.filter_type = self.filter_type; - self.filter - .prepare_block(self.filter_cutoff_hz, self.filter_q, num_samples); - self.filter.process_block(out); } } diff --git a/src/kick/plugin.rs b/src/kick/plugin.rs index 4813cb9..d4c4fb6 100644 --- a/src/kick/plugin.rs +++ b/src/kick/plugin.rs @@ -1433,8 +1433,7 @@ impl AudioProcessor { display.0.resize(num, 0.0); display.1.resize(num, 0.0); self.synth.copy_active_buffer(&mut display.0); - let mono = display.0.clone(); - display.1.copy_from_slice(&mono); + self.synth.copy_active_buffer(&mut display.1); } if let Some(ref bus) = self.bus_data diff --git a/src/limiter/dsp.rs b/src/limiter/dsp.rs index 4dcf7c0..28abdad 100644 --- a/src/limiter/dsp.rs +++ b/src/limiter/dsp.rs @@ -72,15 +72,14 @@ impl ChannelState { if self.detector.factor() == factor { return; } - let mut detector = TruePeakDetector::new(factor); + self.detector.set_factor(factor); if !self.delay.is_empty() { let write_pos = position % self.delay.len(); for offset in (1..=TRUE_PEAK_TAPS).rev() { let index = (write_pos + self.delay.len() - offset) % self.delay.len(); - detector.detect(self.delay[index]); + self.detector.detect(self.delay[index]); } } - self.detector = detector; } fn shape_weight(&self, len: usize, index: usize) -> f64 { diff --git a/src/random/plugin.rs b/src/random/plugin.rs index b3de9eb..ff5de69 100644 --- a/src/random/plugin.rs +++ b/src/random/plugin.rs @@ -127,11 +127,11 @@ struct AudioProcessor { silent_output: Vec, } impl AudioProcessor { - fn new(sample_rate: f64, _max_frames: u32) -> Self { + fn new(sample_rate: f64, max_frames: u32) -> Self { Self { dsp: Random::new(sample_rate), - midi_events: Vec::new(), - silent_output: Vec::new(), + midi_events: Vec::with_capacity(2 * max_frames as usize + 2), + silent_output: vec![0.0; max_frames as usize], } } fn reset(&mut self) { @@ -158,9 +158,8 @@ impl AudioProcessor { shared.params.get(ParamId::LowestNote) as u8, shared.params.get(ParamId::HighestNote) as u8, ); - self.silent_output.resize(frames, 0.0); self.dsp.render( - &mut self.silent_output, + &mut self.silent_output[..frames], RenderSettings { playing, tempo, diff --git a/src/sampler/dsp/engine.rs b/src/sampler/dsp/engine.rs index 94561e0..5fe3293 100644 --- a/src/sampler/dsp/engine.rs +++ b/src/sampler/dsp/engine.rs @@ -71,6 +71,7 @@ pub struct SamplerEngine { note_volume: [f32; 128], zone_trigger_counts: HashMap, + zone_cache: HashMap>, sustain_pedal: bool, @@ -119,6 +120,7 @@ impl SamplerEngine { note_timbre: [0.0; 128], note_volume: [1.0; 128], zone_trigger_counts: HashMap::new(), + zone_cache: HashMap::new(), sustain_pedal: false, sustained_notes: Vec::new(), mod_wheel: 0.0, @@ -148,6 +150,15 @@ impl SamplerEngine { } } } + self.zone_cache.clear(); + for part in &self.patch.parts { + for group in &part.groups { + for zone in &group.zones { + let key = zone as *const Zone as usize; + self.zone_cache.insert(key, Arc::new(zone.clone())); + } + } + } } pub fn patch(&self) -> &Patch { @@ -497,6 +508,12 @@ impl SamplerEngine { self.patch.parts[part_index].previous_note = Some(note); return; }; + let zone_key = zone as *const Zone as usize; + let cached_zone = self + .zone_cache + .get(&zone_key) + .cloned() + .expect("selected zone is cached"); ( gi, group.play_mode, @@ -507,8 +524,8 @@ impl SamplerEngine { part.transpose, part.gain_db, part.pan, - zone as *const Zone as usize, - Arc::new(zone.clone()), + zone_key, + cached_zone, ) }; self.patch.parts[part_index].previous_note = Some(note); @@ -538,12 +555,7 @@ impl SamplerEngine { .map(|v| v.increment()); if zone.variant_mode == crate::sampler::dsp::zone::VariantMode::Unison { - let samples: Vec<_> = if zone.variants.is_empty() { - vec![zone.sample.clone()] - } else { - zone.variants.clone() - }; - for sample in samples { + let mut trigger = |sample: Arc| { let args = TriggerArgs { zone: zone.clone(), note: play_note, @@ -565,6 +577,13 @@ impl SamplerEngine { prev_increment, }, ); + }; + if zone.variants.is_empty() { + trigger(zone.sample.clone()); + } else { + for sample in &zone.variants { + trigger(sample.clone()); + } } return; } @@ -708,7 +727,12 @@ impl SamplerEngine { pitch_bend_raw, &self.held_note_flags, ) { - let zone = Arc::new(zone.clone()); + let zone_key = zone as *const Zone as usize; + let zone = self + .zone_cache + .get(&zone_key) + .cloned() + .expect("selected zone is cached"); let portamento = group.portamento; if let Some(voice) = self.voices.iter_mut().find(|v| v.is_active()) { voice.retarget(zone, next_note, portamento); @@ -887,78 +911,67 @@ impl SamplerEngine { } } - let stolen_index = { - let group_poly = self - .patch - .parts - .get(args.part_index) - .and_then(|p| p.groups.get(args.group_index)) - .map(|g| g.poly_limit) - .unwrap_or(0); - if group_poly > 0 { - let group_voices: Vec = self - .voices - .iter() - .enumerate() - .filter(|(_, v)| { - v.is_active() - && v.group_index() == args.group_index - && v.part_index() == args.part_index - }) - .map(|(i, _)| i) - .collect(); - if group_voices.len() >= group_poly { - group_voices.first().copied() - } else { - None + let group_poly = self + .patch + .parts + .get(args.part_index) + .and_then(|p| p.groups.get(args.group_index)) + .map(|g| g.poly_limit) + .unwrap_or(0); + let mut group_voice_count = 0; + let mut first_group_voice = None; + if group_poly > 0 { + for (index, voice) in self.voices.iter().enumerate() { + if voice.is_active() + && voice.group_index() == args.group_index + && voice.part_index() == args.part_index + { + first_group_voice.get_or_insert(index); + group_voice_count += 1; } - } else { - None } - }; + } + let stolen_index = (group_voice_count >= group_poly && group_poly > 0) + .then_some(first_group_voice) + .flatten(); - let stolen_index = stolen_index.or_else(|| { - let part_poly = self - .patch - .parts - .get(args.part_index) - .map(|p| p.poly_limit) - .unwrap_or(0); - if part_poly > 0 { - let part_voices: Vec = self - .voices - .iter() - .enumerate() - .filter(|(_, v)| v.is_active() && v.part_index() == args.part_index) - .map(|(i, _)| i) - .collect(); - if part_voices.len() >= part_poly { - part_voices.first().copied() - } else { - None + let part_poly = self + .patch + .parts + .get(args.part_index) + .map(|p| p.poly_limit) + .unwrap_or(0); + let mut part_voice_count = 0; + let mut first_part_voice = None; + if stolen_index.is_none() && part_poly > 0 { + for (index, voice) in self.voices.iter().enumerate() { + if voice.is_active() && voice.part_index() == args.part_index { + first_part_voice.get_or_insert(index); + part_voice_count += 1; } - } else { - None } + } + let stolen_index = stolen_index.or_else(|| { + (part_voice_count >= part_poly && part_poly > 0) + .then_some(first_part_voice) + .flatten() }); let stolen_index = stolen_index.or_else(|| { - if self.global_poly_limit > 0 { - let active: Vec = self - .voices - .iter() - .enumerate() - .filter(|(_, v)| v.is_active()) - .map(|(i, _)| i) - .collect(); - if active.len() >= self.global_poly_limit { - active.first().copied() - } else { - None + if self.global_poly_limit == 0 { + return None; + } + let mut active_count = 0; + let mut first_active = None; + for (index, voice) in self.voices.iter().enumerate() { + if voice.is_active() { + first_active.get_or_insert(index); + active_count += 1; } - } else { - None } + (active_count >= self.global_poly_limit) + .then_some(first_active) + .flatten() }); let index = stolen_index diff --git a/src/stereo/dsp.rs b/src/stereo/dsp.rs index 8dda32b..8196ef9 100644 --- a/src/stereo/dsp.rs +++ b/src/stereo/dsp.rs @@ -45,10 +45,10 @@ impl Default for Mild { fpd_l: rand::random(), fpd_r: rand::random(), sample_rate: 48_000.0, - temp_dry_l: vec![0.0; 1024], - temp_dry_r: vec![0.0; 1024], - temp_wet_l: vec![0.0; 1024], - temp_wet_r: vec![0.0; 1024], + temp_dry_l: vec![0.0; 16_384], + temp_dry_r: vec![0.0; 16_384], + temp_wet_l: vec![0.0; 16_384], + temp_wet_r: vec![0.0; 16_384], } } } @@ -69,6 +69,13 @@ impl Mild { self.sample_rate = sr; } + fn prepare(&mut self, max_frames: usize) { + self.temp_dry_l = vec![0.0; max_frames]; + self.temp_dry_r = vec![0.0; max_frames]; + self.temp_wet_l = vec![0.0; max_frames]; + self.temp_wet_r = vec![0.0; max_frames]; + } + pub fn process_stereo( &mut self, left: &mut [f32], @@ -96,14 +103,6 @@ impl Mild { let near_level = 1.0 - far_level; let frames = left.len().min(right.len()); - if self.temp_dry_l.len() < frames { - let new_len = frames.next_power_of_two(); - self.temp_dry_l.resize(new_len, 0.0); - self.temp_dry_r.resize(new_len, 0.0); - self.temp_wet_l.resize(new_len, 0.0); - self.temp_wet_r.resize(new_len, 0.0); - } - for i in 0..frames { let mut input_l = left[i] as f64; let mut input_r = right[i] as f64; @@ -465,8 +464,8 @@ impl Default for Stereo { smooth_output: ParamSmoother::new(0.0), smooth_boost: ParamSmoother::new(1.0), mild: Mild::default(), - section_out_l: vec![0.0; 1024], - section_out_r: vec![0.0; 1024], + section_out_l: vec![0.0; 16_384], + section_out_r: vec![0.0; 16_384], }; s.update_band_maxima_from_sample_rate(); s.rebuild_band_luts(); @@ -476,6 +475,12 @@ impl Default for Stereo { } impl Stereo { + pub fn prepare(&mut self, max_frames: usize) { + self.section_out_l = vec![0.0; max_frames]; + self.section_out_r = vec![0.0; max_frames]; + self.mild.prepare(max_frames); + } + fn update_smoothing_coeff(&mut self) { let tau_seconds = 0.005_f64; let sr = self.sample_rate.max(1.0); @@ -628,12 +633,6 @@ impl Stereo { } let any_solo = params.solo_low || params.solo_mid || params.solo_high; let frames = left.len().min(right.len()); - if self.section_out_l.len() < frames { - let new_len = frames.next_power_of_two(); - self.section_out_l.resize(new_len, 0.0); - self.section_out_r.resize(new_len, 0.0); - } - for i in 0..frames { let low_gain = Self::step_smoother(&mut self.smooth_low_gain, self.smooth_coeff); let mid_gain = Self::step_smoother(&mut self.smooth_mid_gain, self.smooth_coeff); diff --git a/src/stereo/plugin.rs b/src/stereo/plugin.rs index 1ef99a0..7113307 100644 --- a/src/stereo/plugin.rs +++ b/src/stereo/plugin.rs @@ -230,6 +230,7 @@ impl AudioProcessor { fn new(sample_rate: f64, max_frames: u32, bus_data: Option) -> Self { let mut dsp = Stereo::default(); dsp.set_sample_rate(sample_rate); + dsp.prepare(max_frames as usize); Self { dsp, temp_left: vec![0.0; max_frames as usize], diff --git a/src/synth/dsp/engine.rs b/src/synth/dsp/engine.rs index dd3d78d..7d891df 100644 --- a/src/synth/dsp/engine.rs +++ b/src/synth/dsp/engine.rs @@ -24,10 +24,13 @@ pub fn soft_clip_master(x: f32) -> f32 { x.signum() * (MASTER_CLIP_KNEE + (1.0 - MASTER_CLIP_KNEE) * over.tanh()) } +const MAX_VOICE_POOL: usize = 64; + #[derive(Debug, Clone)] pub struct SynthEngine { sample_rate: f32, voices: Vec, + spare_voices: Vec, max_voices: usize, steal_mode: StealMode, pub params: VoiceParams, @@ -53,18 +56,26 @@ pub struct SynthEngine { impl SynthEngine { pub fn new(sample_rate: f32, max_voices: usize) -> Self { - let mut voices = Vec::with_capacity(max_voices); - for _ in 0..max_voices { - voices.push(Voice::new(sample_rate)); + let max_voices = max_voices.clamp(1, MAX_VOICE_POOL); + let mut voices = Vec::with_capacity(MAX_VOICE_POOL); + let mut spare_voices = Vec::with_capacity(MAX_VOICE_POOL); + for index in 0..MAX_VOICE_POOL { + let voice = Voice::new(sample_rate); + if index < max_voices { + voices.push(voice); + } else { + spare_voices.push(voice); + } } let mut engine = Self { sample_rate, voices, + spare_voices, max_voices, steal_mode: StealMode::Oldest, params: VoiceParams::default(), - held_notes: Vec::new(), - sustained_notes: Vec::new(), + held_notes: Vec::with_capacity(128), + sustained_notes: Vec::with_capacity(128), last_note: 0, mts_esp: None, scene_lfo1: Lfo::new(sample_rate), @@ -73,17 +84,10 @@ impl SynthEngine { scene_lfo4: Lfo::new(sample_rate), scene_lfo5: Lfo::new(sample_rate), scene_lfo6: Lfo::new(sample_rate), - scene_lfo_bufs: [ - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - ], + scene_lfo_bufs: std::array::from_fn(|_| vec![0.0; 16_384]), pitch_bend: 0.0, - temp_l: Vec::new(), - temp_r: Vec::new(), + temp_l: vec![0.0; 16_384], + temp_r: vec![0.0; 16_384], visual_lfo_mod_values: [[0.0; ModTarget::COUNT as usize]; 6], custom_wavetables: [None, None, None], }; @@ -96,9 +100,15 @@ impl SynthEngine { engine } + pub fn prepare(&mut self, max_frames: usize) { + self.temp_l = vec![0.0; max_frames]; + self.temp_r = vec![0.0; max_frames]; + self.scene_lfo_bufs = std::array::from_fn(|_| vec![0.0; max_frames]); + } + pub fn set_sample_rate(&mut self, sample_rate: f32) { self.sample_rate = sample_rate; - for voice in &mut self.voices { + for voice in self.voices.iter_mut().chain(self.spare_voices.iter_mut()) { voice.set_sample_rate(sample_rate); } self.scene_lfo1 = Lfo::new(sample_rate); @@ -116,11 +126,13 @@ impl SynthEngine { } pub fn set_max_voices(&mut self, max_voices: usize) { - self.max_voices = max_voices.max(1); + self.max_voices = max_voices.clamp(1, MAX_VOICE_POOL); if self.voices.len() < self.max_voices { let pitch_bend = self.pitch_bend; for _ in self.voices.len()..self.max_voices { - let mut voice = Voice::new(self.sample_rate); + let Some(mut voice) = self.spare_voices.pop() else { + break; + }; voice.pitch_bend = pitch_bend; self.voices.push(voice); } @@ -741,19 +753,34 @@ impl SynthEngine { audio_in_r: Option<&[f32]>, ) { let frames = out_l.len().min(out_r.len()); - if frames == 0 { + let chunk_size = self.temp_l.len(); + if chunk_size == 0 { return; } + for start in (0..frames).step_by(chunk_size) { + let end = (start + chunk_size).min(frames); + self.process_block_chunk( + &mut out_l[start..end], + &mut out_r[start..end], + audio_in_l.map(|input| &input[start..end]), + audio_in_r.map(|input| &input[start..end]), + ); + } + } + + fn process_block_chunk( + &mut self, + out_l: &mut [f32], + out_r: &mut [f32], + audio_in_l: Option<&[f32]>, + audio_in_r: Option<&[f32]>, + ) { + let frames = out_l.len().min(out_r.len()); out_l.fill(0.0); out_r.fill(0.0); self.visual_lfo_mod_values = [[0.0; ModTarget::COUNT as usize]; 6]; - if self.temp_l.len() < frames { - self.temp_l.resize(frames, 0.0); - self.temp_r.resize(frames, 0.0); - } - let scene_lfo_bufs = &mut self.scene_lfo_bufs; let scene_lfos = [ &mut self.scene_lfo1, @@ -766,9 +793,6 @@ impl SynthEngine { // Advance the scene LFOs exactly once per output sample, even when no // voices are active, so they keep time regardless of voice count. for (buf, lfo) in scene_lfo_bufs.iter_mut().zip(scene_lfos) { - if buf.len() < frames { - buf.resize(frames, 0.0); - } for sample in buf[..frames].iter_mut() { *sample = lfo.next(); } @@ -851,14 +875,15 @@ impl SynthEngine { // release once they are fully faded. This also drops inactive pool // voices when `set_max_voices` shrank the pool. let mut overflow = self.voices.len().saturating_sub(self.max_voices); - self.voices.retain(|v| { - if v.is_active() || overflow == 0 { - true - } else { + let mut index = self.voices.len(); + while overflow > 0 && index > 0 { + index -= 1; + if !self.voices[index].is_active() { + let voice = self.voices.remove(index); + self.spare_voices.push(voice); overflow -= 1; - false } - }); + } } pub fn visual_lfo_mod_values(&self) -> &[[f32; ModTarget::COUNT as usize]; 6] { @@ -887,7 +912,9 @@ impl SynthEngine { }; self.voices[idx].begin_uber_release(); - let mut voice = Voice::new(self.sample_rate); + let Some(mut voice) = self.spare_voices.pop() else { + return; + }; voice.pitch_bend = self.pitch_bend; if let Some(template) = self.voices.first() { let tempo_bpm = template.tempo_bpm; diff --git a/src/synth/plugin.rs b/src/synth/plugin.rs index a5010f3..be3ac19 100644 --- a/src/synth/plugin.rs +++ b/src/synth/plugin.rs @@ -2591,6 +2591,7 @@ struct AudioProcessor { engine: SynthEngine, temp_l: Vec, temp_r: Vec, + timed_events: Vec<(u32, TimedEvent)>, bus_data: Option, fft_scratch: Vec, fft_mag: Vec, @@ -2607,6 +2608,7 @@ impl AudioProcessor { fn new(sample_rate: f64, max_frames: u32, bus_data: Option) -> Self { let frames = max_frames as usize; let mut engine = SynthEngine::new(sample_rate as f32, 8); + engine.prepare(frames); let mts_esp = MtsEspClient::try_new(); engine.set_mts_esp(mts_esp); let (scl_files, scl_cache) = Self::scan_scl_files(); @@ -2614,6 +2616,7 @@ impl AudioProcessor { engine, temp_l: vec![0.0; frames], temp_r: vec![0.0; frames], + timed_events: Vec::with_capacity(1024), bus_data, fft_scratch: vec![0.0; frames], fft_mag: vec![0.0; 1024], @@ -2881,7 +2884,8 @@ impl AudioProcessor { // Collect note/CC events with their sample offsets so they can be // applied at the exact sample position instead of at block start. - let mut timed_events: Vec<(u32, TimedEvent)> = Vec::new(); + let mut timed_events = std::mem::take(&mut self.timed_events); + timed_events.clear(); let events = process.in_events(); for i in 0..events.size() { let header = unsafe { events.get_unchecked(i) }; @@ -2936,11 +2940,6 @@ impl AudioProcessor { // sort anyway (stable, so same-offset events keep their order). timed_events.sort_by_key(|(time, _)| *time); - if self.temp_l.len() < frames { - self.temp_l.resize(frames, 0.0); - self.temp_r.resize(frames, 0.0); - } - self.temp_l[..frames].fill(0.0); self.temp_r[..frames].fill(0.0); @@ -2988,6 +2987,7 @@ impl AudioProcessor { audio_in_r.map(|s| &s[seg_start..frames]), ); } + self.timed_events = timed_events; shared.set_visual_lfo_mod_values(self.engine.visual_lfo_mod_values()); if let Some(ref notifier) = *shared.poll_notifier.lock() { notifier.notify(); diff --git a/src/tuner/dsp.rs b/src/tuner/dsp.rs index 78ece61..ccb3f5e 100644 --- a/src/tuner/dsp.rs +++ b/src/tuner/dsp.rs @@ -39,6 +39,9 @@ impl Tuner { let window_size = 4096; let hop_size = window_size / 2; let padding = window_size / 2; + let mut detector = YINDetector::new(window_size, padding); + let work = vec![1.0; window_size]; + detector.get_pitch(&work, sample_rate as usize, 5.0, 0.7); Self { sample_rate, window_size, @@ -46,9 +49,9 @@ impl Tuner { power_threshold: 5.0, clarity_threshold: 0.7, reference_hz: 440.0, - detector: YINDetector::new(window_size, padding), + detector, buffer: Vec::with_capacity(window_size), - work: vec![0.0; window_size], + work, samples_since_report: 0, } }