Skip to main content

qualia_audio/
production.rs

1//! Swarm P — bounded production engine (zero-alloc process block + FX primitives).
2//!
3//! Offline bounce uses the same `process_block` path as RT so deterministic FX
4//! match sample-for-sample when automation is fixed.
5
6/// Fixed-capacity track strip.
7pub const MAX_TRACKS: usize = 16;
8pub const MAX_BLOCK: usize = 512;
9pub const MAX_DELAY_SAMPLES: usize = 48_000; // 1s @ 48k
10
11#[derive(Debug, Clone, Copy)]
12pub struct TrackState {
13    pub gain: f32,
14    pub pan: f32,
15    pub mute: bool,
16    pub solo: bool,
17    /// Simple one-pole lowpass coefficient 0..1 (0 = bypass).
18    pub lowpass: f32,
19    /// Peaking EQ gain dB (0 = bypass). Applied after lowpass.
20    pub eq_gain_db: f32,
21    pub eq_freq_hz: f32,
22    /// Compressor threshold linear (0..1); ratio ≥ 1.
23    pub comp_threshold: f32,
24    pub comp_ratio: f32,
25    /// Delay time in samples (0 = off); wet mix 0..1.
26    pub delay_samples: u32,
27    pub delay_mix: f32,
28}
29
30impl Default for TrackState {
31    fn default() -> Self {
32        Self {
33            gain: 1.0,
34            pan: 0.0,
35            mute: false,
36            solo: false,
37            lowpass: 0.0,
38            eq_gain_db: 0.0,
39            eq_freq_hz: 1000.0,
40            comp_threshold: 1.0,
41            comp_ratio: 1.0,
42            delay_samples: 0,
43            delay_mix: 0.0,
44        }
45    }
46}
47
48/// One-pole peaking-ish shelf via gain around centre freq (reference quality).
49#[inline]
50pub fn apply_eq_sample(
51    s: f32,
52    eq_gain_db: f32,
53    _freq_hz: f32,
54    sample_rate: u32,
55    z: &mut f32,
56) -> f32 {
57    if eq_gain_db.abs() < 0.01 || sample_rate == 0 {
58        return s;
59    }
60    let g = 10f32.powf(eq_gain_db / 40.0); // amplitude-ish
61                                           // Mild high-shelf: blend highpassed residual
62    let hp = s - *z;
63    *z += 0.05 * (s - *z);
64    s + hp * (g - 1.0) * 0.25
65}
66
67/// Soft-knee compressor sample (stateful envelope in `env`).
68#[inline]
69pub fn apply_comp_sample(s: f32, threshold: f32, ratio: f32, env: &mut f32) -> f32 {
70    if threshold >= 0.999 || ratio <= 1.001 {
71        return s;
72    }
73    let a = s.abs();
74    *env = *env * 0.9 + a * 0.1;
75    if *env <= threshold {
76        return s;
77    }
78    let over = *env / threshold.max(1e-6);
79    let gain = over.powf(1.0 / ratio.max(1.0)) / over.max(1e-6);
80    s * gain.clamp(0.05, 1.0)
81}
82
83/// Circular delay line (caller-owned buffer).
84#[derive(Debug, Clone)]
85pub struct DelayLine {
86    buf: Vec<f32>,
87    w: usize,
88}
89
90impl DelayLine {
91    /// Creates a new instance.
92    pub fn new(max_samples: usize) -> Self {
93        Self {
94            buf: vec![0.0; max_samples.max(1)],
95            w: 0,
96        }
97    }
98
99    /// Processes.
100    pub fn process(&mut self, s: f32, delay_samples: usize, mix: f32) -> f32 {
101        let n = self.buf.len();
102        if delay_samples == 0 || mix <= 0.0 || n == 0 {
103            return s;
104        }
105        let d = delay_samples.min(n - 1);
106        let r = (self.w + n - d) % n;
107        let delayed = self.buf[r];
108        self.buf[self.w] = s + delayed * 0.2; // light feedback
109        self.w = (self.w + 1) % n;
110        s * (1.0 - mix) + delayed * mix
111    }
112}
113
114/// Compiled execution plan for one audio block (no graph walk in callback).
115#[derive(Debug, Clone)]
116pub struct ProcessPlan {
117    pub tracks: [TrackState; MAX_TRACKS],
118    pub n_tracks: usize,
119    pub sample_rate: u32,
120    pub block_frames: usize,
121}
122
123impl ProcessPlan {
124    /// Creates a new instance.
125    pub fn new(sample_rate: u32, block_frames: usize) -> Self {
126        Self {
127            tracks: [TrackState::default(); MAX_TRACKS],
128            n_tracks: 0,
129            sample_rate,
130            block_frames: block_frames.min(MAX_BLOCK).max(1),
131        }
132    }
133
134    /// Adds track.
135    pub fn add_track(&mut self, t: TrackState) -> Option<usize> {
136        if self.n_tracks >= MAX_TRACKS {
137            return None;
138        }
139        let i = self.n_tracks;
140        self.tracks[i] = t;
141        self.n_tracks += 1;
142        Some(i)
143    }
144
145    /// Mix `n_tracks` mono input blocks into stereo out (interleaved L,R).
146    /// `inputs[t]` length ≥ block_frames. **No allocation.**
147    pub fn process_block(
148        &self,
149        inputs: &[&[f32]],
150        out_interleaved: &mut [f32],
151    ) -> Result<(), &'static str> {
152        let bf = self.block_frames;
153        if out_interleaved.len() < bf * 2 {
154            return Err("out too small");
155        }
156        out_interleaved[..bf * 2].fill(0.0);
157        let any_solo = self.tracks[..self.n_tracks].iter().any(|t| t.solo);
158        let n = self.n_tracks.min(inputs.len());
159        for t in 0..n {
160            let tr = self.tracks[t];
161            if tr.mute {
162                continue;
163            }
164            if any_solo && !tr.solo {
165                continue;
166            }
167            let buf = inputs[t];
168            if buf.len() < bf {
169                continue;
170            }
171            let g = tr.gain;
172            let pan = tr.pan.clamp(-1.0, 1.0);
173            let gl = g * (0.5 * (1.0 - pan));
174            let gr = g * (0.5 * (1.0 + pan));
175            let lp = tr.lowpass.clamp(0.0, 0.99);
176            let mut z_lp = 0.0f32;
177            let mut z_eq = 0.0f32;
178            let mut env = 0.0f32;
179            // Delay: short stack buffer for block-local wet (no heap in hot path)
180            let mut delay_ring = [0.0f32; 512];
181            let mut delay_w = 0usize;
182            let dlen = tr.delay_samples as usize;
183            let dmix = tr.delay_mix.clamp(0.0, 1.0);
184            for i in 0..bf {
185                let mut s = buf[i];
186                if lp > 0.0 {
187                    z_lp += lp * (s - z_lp);
188                    s = z_lp;
189                }
190                s = apply_eq_sample(s, tr.eq_gain_db, tr.eq_freq_hz, self.sample_rate, &mut z_eq);
191                s = apply_comp_sample(s, tr.comp_threshold, tr.comp_ratio, &mut env);
192                if dlen > 0 && dmix > 0.0 {
193                    let cap = delay_ring.len();
194                    let d = dlen.min(cap - 1);
195                    let r = (delay_w + cap - d) % cap;
196                    let delayed = delay_ring[r];
197                    delay_ring[delay_w] = s;
198                    delay_w = (delay_w + 1) % cap;
199                    s = s * (1.0 - dmix) + delayed * dmix;
200                }
201                out_interleaved[i * 2] += s * gl;
202                out_interleaved[i * 2 + 1] += s * gr;
203            }
204        }
205        Ok(())
206    }
207
208    /// Apply track FX chain to mono offline (same ops as process_block path).
209    pub fn process_mono_fx(
210        track: &TrackState,
211        sample_rate: u32,
212        mono: &[f32],
213        out: &mut [f32],
214    ) -> usize {
215        let n = mono.len().min(out.len());
216        let mut z_lp = 0.0f32;
217        let mut z_eq = 0.0f32;
218        let mut env = 0.0f32;
219        let mut delay =
220            DelayLine::new((track.delay_samples as usize).max(1).min(MAX_DELAY_SAMPLES));
221        let lp = track.lowpass.clamp(0.0, 0.99);
222        for i in 0..n {
223            let mut s = mono[i];
224            if lp > 0.0 {
225                z_lp += lp * (s - z_lp);
226                s = z_lp;
227            }
228            s = apply_eq_sample(
229                s,
230                track.eq_gain_db,
231                track.eq_freq_hz,
232                sample_rate,
233                &mut z_eq,
234            );
235            s = apply_comp_sample(s, track.comp_threshold, track.comp_ratio, &mut env);
236            s = delay.process(s, track.delay_samples as usize, track.delay_mix);
237            out[i] = s * track.gain;
238        }
239        n
240    }
241
242    /// Offline bounce: process all input blocks into contiguous interleaved stereo.
243    /// `inputs[t]` is full track audio; written frames = min lengths.
244    pub fn bounce_interleaved(
245        &self,
246        inputs: &[&[f32]],
247        out: &mut [f32],
248    ) -> Result<usize, &'static str> {
249        let bf = self.block_frames;
250        let n_frames = inputs.iter().map(|b| b.len()).min().unwrap_or(0);
251        let mut written = 0usize;
252        let mut pos = 0usize;
253        let mut scratch_in: [&[f32]; MAX_TRACKS] = [&[]; MAX_TRACKS];
254        while pos + bf <= n_frames {
255            for t in 0..self.n_tracks.min(inputs.len()) {
256                scratch_in[t] = &inputs[t][pos..pos + bf];
257            }
258            let refs: Vec<&[f32]> = (0..self.n_tracks.min(inputs.len()))
259                .map(|t| scratch_in[t])
260                .collect();
261            let out_slice = &mut out[written * 2..(written + bf) * 2];
262            if out_slice.len() < bf * 2 {
263                break;
264            }
265            self.process_block(&refs, out_slice)?;
266            written += bf;
267            pos += bf;
268        }
269        Ok(written)
270    }
271}
272
273/// Largest delay supported by the stateful block mixer, in frames.
274pub const MAX_MIX_DELAY: usize = MAX_BLOCK - 1;
275
276#[derive(Debug, Clone)]
277struct MixTrackMemory {
278    lowpass: f32,
279    eq: f32,
280    envelope: f32,
281    delay: [f32; MAX_BLOCK],
282    delay_write: usize,
283}
284
285impl Default for MixTrackMemory {
286    fn default() -> Self {
287        Self { lowpass: 0.0, eq: 0.0, envelope: 0.0, delay: [0.0; MAX_BLOCK], delay_write: 0 }
288    }
289}
290
291/// Persistent allocation-free mixing of aligned mono tracks into stereo.
292/// Call `reset` after a discontinuous seek, track-slot reassignment or sample-rate
293/// change. Source scheduling, resampling, limiting and device playback remain
294/// host duties. Effect memory follows the input while bypassed: lowpass tracks
295/// the last source sample, while EQ and compressor retain their normal smoothers.
296/// Delay stores processed input even when bypassed; changes to its length read
297/// from that history, with no crossfade. This delay has no feedback or tail policy.
298#[derive(Debug, Clone, Default)]
299pub struct StatefulMixer {
300    memory: [MixTrackMemory; MAX_TRACKS],
301    sample_rate: Option<u32>,
302}
303
304impl StatefulMixer {
305    pub fn new() -> Self { Self::default() }
306
307    /// Discard effect history, for example after a seek.
308    pub fn reset(&mut self) { *self = Self::default(); }
309
310    /// Mix aligned blocks, with silence supplied for inactive tracks. Block
311    /// length may vary up to the plan's block size. Muted tracks continue to
312    /// advance their effect memory. Validation precedes all state/output writes.
313    /// Samples and gain are bounded to ±16, EQ to ±60 dB, compressor threshold
314    /// to 0..=1, ratio to 1..=100, and pan, lowpass and delay mix to their usual
315    /// normalized ranges. EQ frequency is accepted when finite and nonnegative:
316    /// the current EQ helper is a shelf and does not use that frequency. These
317    /// conservative limits keep the signal chain finite; no limiting occurs.
318    pub fn process_block(
319        &mut self,
320        plan: &ProcessPlan,
321        inputs: &[&[f32]],
322        frames: usize,
323        out: &mut [f32],
324    ) -> Result<(), &'static str> {
325        if plan.n_tracks > MAX_TRACKS || plan.sample_rate == 0 ||
326            plan.block_frames == 0 || plan.block_frames > MAX_BLOCK || frames > plan.block_frames {
327            return Err("invalid mixer plan or block size");
328        }
329        if inputs.len() != plan.n_tracks || inputs.iter().any(|input| input.len() < frames) {
330            return Err("each track requires an aligned input block");
331        }
332        if out.len() < frames * 2 { return Err("out too small"); }
333        if self.sample_rate.is_some_and(|rate| rate != plan.sample_rate) {
334            return Err("reset mixer before changing sample rate");
335        }
336        for (track, input) in plan.tracks[..plan.n_tracks].iter().zip(inputs) {
337            if !(-16.0..=16.0).contains(&track.gain) || !(-1.0..=1.0).contains(&track.pan) ||
338                !(0.0..=1.0).contains(&track.lowpass) || !(-60.0..=60.0).contains(&track.eq_gain_db) ||
339                !track.eq_freq_hz.is_finite() || track.eq_freq_hz < 0.0 ||
340                !(0.0..=1.0).contains(&track.comp_threshold) ||
341                !(1.0..=100.0).contains(&track.comp_ratio) || !(0.0..=1.0).contains(&track.delay_mix) ||
342                track.delay_samples as usize > MAX_MIX_DELAY ||
343                input[..frames].iter().any(|sample| !(-16.0..=16.0).contains(sample)) {
344                return Err("invalid track parameters or samples");
345            }
346        }
347        if frames > 0 { self.sample_rate = Some(plan.sample_rate); }
348        out[..frames * 2].fill(0.0);
349        let any_solo = plan.tracks[..plan.n_tracks].iter().any(|track| track.solo);
350        for (index, (track, input)) in plan.tracks[..plan.n_tracks].iter().zip(inputs).enumerate() {
351            let state = &mut self.memory[index];
352            let pan = track.pan.clamp(-1.0, 1.0);
353            let gl = track.gain * (0.5 * (1.0 - pan));
354            let gr = track.gain * (0.5 * (1.0 + pan));
355            let lp = track.lowpass.clamp(0.0, 0.99);
356            let delay = track.delay_samples as usize;
357            let wet = track.delay_mix.clamp(0.0, 1.0);
358            let audible = !track.mute && (!any_solo || track.solo);
359            for (i, &sample) in input[..frames].iter().enumerate() {
360                let mut s = sample;
361                if lp > 0.0 {
362                    state.lowpass += lp * (s - state.lowpass);
363                    s = state.lowpass;
364                } else {
365                    state.lowpass = s;
366                }
367                if track.eq_gain_db.abs() < 0.01 {
368                    state.eq += 0.05 * (s - state.eq);
369                } else {
370                    s = apply_eq_sample(s, track.eq_gain_db, track.eq_freq_hz, plan.sample_rate, &mut state.eq);
371                }
372                if track.comp_threshold >= 0.999 || track.comp_ratio <= 1.001 {
373                    state.envelope = state.envelope * 0.9 + s.abs() * 0.1;
374                } else {
375                    s = apply_comp_sample(s, track.comp_threshold, track.comp_ratio, &mut state.envelope);
376                }
377                // Advance the ring even while bypassed so enabling delay can
378                // use recent processed history.
379                let read = (state.delay_write + MAX_BLOCK - delay) % MAX_BLOCK;
380                let delayed = state.delay[read];
381                state.delay[state.delay_write] = s;
382                state.delay_write = (state.delay_write + 1) % MAX_BLOCK;
383                if delay > 0 && wet > 0.0 { s = s * (1.0 - wet) + delayed * wet; }
384                if audible {
385                    out[2 * i] += s * gl;
386                    out[2 * i + 1] += s * gr;
387                }
388            }
389        }
390        Ok(())
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn stateful_mixer_is_independent_of_block_partition() {
400        let mut plan = ProcessPlan::new(48000, 8);
401        plan.add_track(TrackState { pan: -1.0, lowpass: 0.4, delay_samples: 3, delay_mix: 0.5, ..Default::default() });
402        plan.add_track(TrackState { pan: 1.0, gain: 0.5, ..Default::default() });
403        let a = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
404        let b = [0.5; 8];
405        let mut whole = [0.0; 16];
406        StatefulMixer::new().process_block(&plan, &[&a, &b], 8, &mut whole).unwrap();
407        let mut split = [0.0; 16];
408        let mut mixer = StatefulMixer::new();
409        mixer.process_block(&plan, &[&a[..3], &b[..3]], 3, &mut split[..6]).unwrap();
410        mixer.process_block(&plan, &[&a[3..], &b[3..]], 5, &mut split[6..]).unwrap();
411        assert_eq!(whole, split);
412        assert!(whole[6] > 0.0); // delayed impulse survived the boundary
413        assert_eq!(whole[1], 0.25); // independent right-panned track
414    }
415
416    #[test]
417    fn stateful_mixer_rejects_bad_input_without_mutating_state_or_output() {
418        let mut plan = ProcessPlan::new(48000, 4);
419        plan.add_track(TrackState { pan: -1.0, delay_samples: 1, delay_mix: 1.0, ..Default::default() });
420        let mut mixer = StatefulMixer::new();
421        let mut first = [0.0; 2];
422        mixer.process_block(&plan, &[&[1.0]], 1, &mut first).unwrap();
423        let mut output = [7.0; 2];
424        assert!(mixer.process_block(&plan, &[&[f32::NAN]], 1, &mut output).is_err());
425        assert_eq!(output, [7.0; 2]);
426        mixer.process_block(&plan, &[&[0.0]], 1, &mut output).unwrap();
427        assert_eq!(output, [1.0, 0.0]);
428        mixer.reset();
429        mixer.process_block(&plan, &[&[0.0]], 1, &mut output).unwrap();
430        assert_eq!(output, [0.0, 0.0]);
431    }
432
433    #[test]
434    fn muted_tracks_continue_to_advance() {
435        let mut plan = ProcessPlan::new(48000, 4);
436        plan.add_track(TrackState { pan: -1.0, mute: true, delay_samples: 1, delay_mix: 1.0, ..Default::default() });
437        let mut mixer = StatefulMixer::new();
438        let mut output = [0.0; 2];
439        mixer.process_block(&plan, &[&[1.0]], 1, &mut output).unwrap();
440        assert_eq!(output, [0.0, 0.0]);
441        plan.tracks[0].mute = false;
442        mixer.process_block(&plan, &[&[0.0]], 1, &mut output).unwrap();
443        assert_eq!(output, [1.0, 0.0]);
444    }
445
446    #[test]
447    fn stateful_mixer_rejects_extremes_and_rate_changes_transactionally() {
448        let mut plan = ProcessPlan::new(48000, 4);
449        plan.add_track(TrackState::default());
450        let mut mixer = StatefulMixer::new();
451        let mut output = [7.0; 2];
452        plan.tracks[0].eq_gain_db = 4000.0;
453        assert!(mixer.process_block(&plan, &[&[1.0]], 1, &mut output).is_err());
454        assert_eq!(output, [7.0; 2]);
455        plan.tracks[0].eq_gain_db = 0.0;
456        assert!(mixer.process_block(&plan, &[&[17.0]], 1, &mut output).is_err());
457        mixer.process_block(&plan, &[&[1.0]], 1, &mut output).unwrap();
458        plan.sample_rate = 44100;
459        output = [7.0; 2];
460        assert!(mixer.process_block(&plan, &[&[1.0]], 1, &mut output).is_err());
461        assert_eq!(output, [7.0; 2]);
462        mixer.reset();
463        mixer.process_block(&plan, &[&[1.0]], 1, &mut output).unwrap();
464    }
465
466    #[test]
467    fn bypassed_effects_follow_input_before_reactivation() {
468        let mut plan = ProcessPlan::new(48000, 4);
469        plan.add_track(TrackState { pan: -1.0, ..Default::default() });
470        let mut mixer = StatefulMixer::new();
471        let mut output = [0.0; 2];
472        mixer.process_block(&plan, &[&[1.0]], 1, &mut output).unwrap();
473        assert_eq!(mixer.memory[0].lowpass, 1.0);
474        assert_eq!(mixer.memory[0].eq, 0.05);
475        assert_eq!(mixer.memory[0].envelope, 0.1);
476        plan.tracks[0].lowpass = 0.5;
477        mixer.process_block(&plan, &[&[1.0]], 1, &mut output).unwrap();
478        assert_eq!(output, [1.0, 0.0]);
479    }
480
481    #[test]
482    fn mix_two_tracks() {
483        let mut p = ProcessPlan::new(48000, 64);
484        p.add_track(TrackState {
485            gain: 1.0,
486            pan: -1.0,
487            ..Default::default()
488        });
489        p.add_track(TrackState {
490            gain: 1.0,
491            pan: 1.0,
492            ..Default::default()
493        });
494        let a = [0.5f32; 64];
495        let b = [0.5f32; 64];
496        let mut out = [0.0f32; 128];
497        p.process_block(&[&a, &b], &mut out).unwrap();
498        assert!(out[0] > 0.0); // L
499        assert!(out[1] > 0.0); // R
500    }
501
502    #[test]
503    fn bounce_writes_frames() {
504        let mut p = ProcessPlan::new(48000, 32);
505        p.add_track(TrackState::default());
506        let a = [0.25f32; 128];
507        let mut out = [0.0f32; 256];
508        let n = p.bounce_interleaved(&[&a], &mut out).unwrap();
509        assert_eq!(n, 128);
510        assert!(out[0] != 0.0);
511    }
512
513    #[test]
514    fn eq_and_comp_change_signal() {
515        let mut tr = TrackState::default();
516        tr.eq_gain_db = 6.0;
517        tr.comp_threshold = 0.2;
518        tr.comp_ratio = 4.0;
519        let mono: Vec<f32> = (0..256)
520            .map(|i| (2.0 * core::f32::consts::PI * 440.0 * i as f32 / 48000.0).sin())
521            .collect();
522        let mut out = vec![0.0f32; 256];
523        let n = ProcessPlan::process_mono_fx(&tr, 48000, &mono, &mut out);
524        assert_eq!(n, 256);
525        let energy: f32 = out.iter().map(|x| x * x).sum();
526        assert!(energy > 0.0);
527    }
528
529    #[test]
530    fn delay_mix_preserves_length() {
531        let mut tr = TrackState::default();
532        tr.delay_samples = 64;
533        tr.delay_mix = 0.3;
534        let mono = [0.5f32; 128];
535        let mut out = [0.0f32; 128];
536        assert_eq!(
537            ProcessPlan::process_mono_fx(&tr, 48000, &mono, &mut out),
538            128
539        );
540    }
541}