embedded-audio-core 0.2.1

no_std duty-modulated PWM audio: effect banks, tiered DSP, and mixing for Cortex-M
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Optional Digital Signal Processing (DSP) integrations powered by `embedded-dsp`.
//!
//! This module provides real-time audio manipulation and analysis primitives for embedded systems:
//! - **Biquad Filters**: Highpass, Lowpass, Bandpass, Notch biquad filters for audio filtering and tone shaping.
//! - **Spectrum Analysis**: Windowed Real FFT (RFFT) spectrum analysis for pitch detection and spectral magnitude visualization.
//! - **Audio Metering**: RMS amplitude, peak detection, signal power, and variance metering.
//! - **LMS Adaptive Filtering**: Real-time noise cancellation and system identification.

#[allow(unused_imports)]
use embedded_dsp::FloatMath;
use embedded_dsp::{
    BiquadCascadeInstanceF32, LmsInstanceF32, apply_window_f32, biquad_cascade_df1_f32,
    blackman_f32, flattop_f32, hamming_f32, hanning_f32, lms_f32, mean_f32, power_f32, rfft_f32,
    rms_f32, var_f32,
};

/// Biquad audio filter for real-time sample-by-sample or block filtering.
#[derive(Clone)]
pub struct BiquadAudioFilter {
    coeffs: [f32; 5], // [b0, b1, b2, a1, a2]
    state: [f32; 4],  // [x[n-1], x[n-2], y[n-1], y[n-2]]
}

impl BiquadAudioFilter {
    /// Create a custom biquad filter given 5 normalized coefficients `[b0, b1, b2, a1, a2]`.
    pub fn new(b0: f32, b1: f32, b2: f32, a1: f32, a2: f32) -> Self {
        Self {
            coeffs: [b0, b1, b2, a1, a2],
            state: [0.0; 4],
        }
    }

    /// Design a 2nd-order Lowpass Biquad filter.
    pub fn lowpass(cutoff_hz: f32, sample_rate_hz: f32, q: f32) -> Self {
        let omega = 2.0 * core::f32::consts::PI * cutoff_hz / sample_rate_hz;
        let alpha = omega.sin() / (2.0 * q);
        let cos_w = omega.cos();

        let b0 = (1.0 - cos_w) / 2.0;
        let b1 = 1.0 - cos_w;
        let b2 = (1.0 - cos_w) / 2.0;
        let a0 = 1.0 + alpha;
        let a1 = -2.0 * cos_w;
        let a2 = 1.0 - alpha;

        Self::new(b0 / a0, b1 / a0, b2 / a0, -a1 / a0, -a2 / a0)
    }

    /// Design a 2nd-order Highpass Biquad filter.
    pub fn highpass(cutoff_hz: f32, sample_rate_hz: f32, q: f32) -> Self {
        let omega = 2.0 * core::f32::consts::PI * cutoff_hz / sample_rate_hz;
        let alpha = omega.sin() / (2.0 * q);
        let cos_w = omega.cos();

        let b0 = (1.0 + cos_w) / 2.0;
        let b1 = -(1.0 + cos_w);
        let b2 = (1.0 + cos_w) / 2.0;
        let a0 = 1.0 + alpha;
        let a1 = -2.0 * cos_w;
        let a2 = 1.0 - alpha;

        Self::new(b0 / a0, b1 / a0, b2 / a0, -a1 / a0, -a2 / a0)
    }

    /// Design a 2nd-order Bandpass Biquad filter (constant peak gain).
    pub fn bandpass(cutoff_hz: f32, sample_rate_hz: f32, q: f32) -> Self {
        let omega = 2.0 * core::f32::consts::PI * cutoff_hz / sample_rate_hz;
        let alpha = omega.sin() / (2.0 * q);
        let cos_w = omega.cos();

        let b0 = alpha;
        let b1 = 0.0;
        let b2 = -alpha;
        let a0 = 1.0 + alpha;
        let a1 = -2.0 * cos_w;
        let a2 = 1.0 - alpha;

        Self::new(b0 / a0, b1 / a0, b2 / a0, -a1 / a0, -a2 / a0)
    }

    /// Design a 2nd-order Notch (Band-Stop) Biquad filter.
    pub fn notch(cutoff_hz: f32, sample_rate_hz: f32, q: f32) -> Self {
        let omega = 2.0 * core::f32::consts::PI * cutoff_hz / sample_rate_hz;
        let alpha = omega.sin() / (2.0 * q);
        let cos_w = omega.cos();

        let b0 = 1.0;
        let b1 = -2.0 * cos_w;
        let b2 = 1.0;
        let a0 = 1.0 + alpha;
        let a1 = -2.0 * cos_w;
        let a2 = 1.0 - alpha;

        Self::new(b0 / a0, b1 / a0, b2 / a0, -a1 / a0, -a2 / a0)
    }

    /// Reset internal delay line state to 0.
    pub fn reset(&mut self) {
        self.state.fill(0.0);
    }

    /// Process a single floating-point sample in range `[-1.0, 1.0]`.
    pub fn process_sample(&mut self, input: f32) -> f32 {
        let mut inst = BiquadCascadeInstanceF32 {
            num_stages: 1,
            coeffs: &self.coeffs,
            state: &mut self.state,
        };
        let src = [input];
        let mut dst = [0.0];
        biquad_cascade_df1_f32(&mut inst, &src, &mut dst);
        dst[0]
    }

    /// Process a PCM8 sample (`i8`).
    pub fn process_pcm8(&mut self, input: i8) -> i8 {
        let in_f32 = input as f32 / 128.0;
        let out_f32 = self.process_sample(in_f32);
        (out_f32 * 127.0).clamp(-128.0, 127.0) as i8
    }

    /// Process a block of floating-point audio samples in place.
    pub fn process_buffer(&mut self, samples: &mut [f32]) {
        let mut inst = BiquadCascadeInstanceF32 {
            num_stages: 1,
            coeffs: &self.coeffs,
            state: &mut self.state,
        };
        for sample in samples.iter_mut() {
            let src = [*sample];
            let mut dst = [0.0];
            biquad_cascade_df1_f32(&mut inst, &src, &mut dst);
            *sample = dst[0];
        }
    }
}

/// Window function types for spectral analysis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowType {
    Rectangular,
    Hanning,
    Hamming,
    Blackman,
    FlatTop,
}

/// FFT-based audio spectrum analyzer for real-time embedded feature extraction.
pub struct AudioSpectrumAnalyzer;

impl AudioSpectrumAnalyzer {
    /// Compute the magnitude spectrum of real audio samples `src`.
    ///
    /// `src` length must match `n`. `dst_mag` receives `n / 2` magnitude bins.
    pub fn analyze_spectrum(src: &[f32], window_type: WindowType, dst_mag: &mut [f32]) {
        let n = src.len();
        if n < 2 || (n & (n - 1)) != 0 || dst_mag.len() < n / 2 {
            return;
        }

        let mut win_buf = [0.0f32; 1024];
        let mut sample_buf = [0.0f32; 1024];

        if n > 1024 {
            return;
        }

        sample_buf[..n].copy_from_slice(&src[..n]);

        match window_type {
            WindowType::Rectangular => {}
            WindowType::Hanning => {
                hanning_f32(&mut win_buf[..n]);
                apply_window_f32(&mut sample_buf[..n], &win_buf[..n]);
            }
            WindowType::Hamming => {
                hamming_f32(&mut win_buf[..n]);
                apply_window_f32(&mut sample_buf[..n], &win_buf[..n]);
            }
            WindowType::Blackman => {
                blackman_f32(&mut win_buf[..n]);
                apply_window_f32(&mut sample_buf[..n], &win_buf[..n]);
            }
            WindowType::FlatTop => {
                flattop_f32(&mut win_buf[..n]);
                apply_window_f32(&mut sample_buf[..n], &win_buf[..n]);
            }
        }

        let mut fft_out = [0.0f32; 2048];
        rfft_f32(&sample_buf[..n], &mut fft_out[..2 * n], n, 0);

        for k in 0..(n / 2) {
            let re = fft_out[2 * k];
            let im = fft_out[2 * k + 1];
            dst_mag[k] = (re * re + im * im).sqrt();
        }
    }

    /// Estimate dominant (peak) frequency in Hz and its magnitude.
    /// Returns `(frequency_hz, peak_magnitude)`.
    pub fn find_peak_frequency(
        src: &[f32],
        sample_rate_hz: f32,
        window_type: WindowType,
    ) -> (f32, f32) {
        let n = src.len();
        if n < 4 || (n & (n - 1)) != 0 {
            return (0.0, 0.0);
        }

        let num_bins = n / 2;
        let mut mag_buf = [0.0f32; 512];
        if num_bins > mag_buf.len() {
            return (0.0, 0.0);
        }

        Self::analyze_spectrum(src, window_type, &mut mag_buf[..num_bins]);

        let mut max_mag = 0.0f32;
        let mut max_bin = 0;

        for (k, &mag) in mag_buf[..num_bins].iter().enumerate().skip(1) {
            if mag > max_mag {
                max_mag = mag;
                max_bin = k;
            }
        }

        let bin_width = sample_rate_hz / (n as f32);
        let freq = (max_bin as f32) * bin_width;

        (freq, max_mag)
    }
}

/// Statistics metrics for an audio frame.
#[derive(Debug, Clone, Copy)]
pub struct AudioStats {
    pub rms: f32,
    pub peak: f32,
    pub mean: f32,
    pub power: f32,
    pub variance: f32,
}

/// Audio signal statistics and metering.
pub struct AudioMeter;

impl AudioMeter {
    /// Calculate RMS, peak, mean, power, and variance for a slice of float audio samples.
    pub fn measure(samples: &[f32]) -> AudioStats {
        if samples.is_empty() {
            return AudioStats {
                rms: 0.0,
                peak: 0.0,
                mean: 0.0,
                power: 0.0,
                variance: 0.0,
            };
        }

        let mut mean = 0.0f32;
        let mut rms = 0.0f32;
        let mut power = 0.0f32;
        let mut variance = 0.0f32;

        let _ = mean_f32(samples, &mut mean);
        let _ = rms_f32(samples, &mut rms);
        let _ = power_f32(samples, &mut power);
        let _ = var_f32(samples, &mut variance);

        let mut peak = 0.0f32;
        for &s in samples {
            let abs_s = s.abs();
            if abs_s > peak {
                peak = abs_s;
            }
        }

        AudioStats {
            rms,
            peak,
            mean,
            power,
            variance,
        }
    }
}

/// Adaptive LMS filter for noise reduction and system identification.
pub struct AudioLmsFilter<'a> {
    inst: LmsInstanceF32<'a>,
}

impl<'a> AudioLmsFilter<'a> {
    /// Initialize an LMS filter with specified number of taps, coefficient storage, state buffer, and step size `mu`.
    pub fn new(num_taps: u16, coeffs: &'a mut [f32], state: &'a mut [f32], mu: f32) -> Self {
        let inst = LmsInstanceF32::init(num_taps, coeffs, state, mu);
        Self { inst }
    }

    /// Process input signal and reference signal blocks.
    /// Writes output signal into `out` and error signal into `err`.
    pub fn process(&mut self, src: &[f32], ref_signal: &[f32], out: &mut [f32], err: &mut [f32]) {
        lms_f32(&mut self.inst, src, ref_signal, out, err);
    }
}

/// Single-frequency Goertzel algorithm detector for tone and DTMF decoding.
pub struct GoertzelDetector {
    coeff: f32,
    s_prev: f32,
    s_prev2: f32,
}

impl GoertzelDetector {
    /// Initialise a Goertzel detector for a target frequency and sample rate.
    pub fn new(target_freq: f32, sample_rate: f32) -> Self {
        let omega = 2.0 * core::f32::consts::PI * target_freq / sample_rate;
        let coeff = 2.0 * omega.cos();
        Self {
            coeff,
            s_prev: 0.0,
            s_prev2: 0.0,
        }
    }

    /// Reset state for a new window of samples.
    pub fn reset(&mut self) {
        self.s_prev = 0.0;
        self.s_prev2 = 0.0;
    }

    /// Process a single audio sample.
    pub fn update(&mut self, sample: f32) {
        let s = sample + self.coeff * self.s_prev - self.s_prev2;
        self.s_prev2 = self.s_prev;
        self.s_prev = s;
    }

    /// Compute the current magnitude at the target frequency.
    pub fn magnitude(&self) -> f32 {
        (self.s_prev * self.s_prev + self.s_prev2 * self.s_prev2
            - self.coeff * self.s_prev * self.s_prev2)
            .sqrt()
    }
}

/// Peak/RMS envelope follower with configurable attack and release smoothing.
pub struct EnvelopeFollower {
    attack_coeff: f32,
    release_coeff: f32,
    envelope: f32,
}

impl EnvelopeFollower {
    /// Create envelope follower given attack and release time constants in seconds and sample rate.
    pub fn new(attack_time_sec: f32, release_time_sec: f32, sample_rate: f32) -> Self {
        let attack_coeff = (-1.0 / (attack_time_sec * sample_rate)).exp();
        let release_coeff = (-1.0 / (release_time_sec * sample_rate)).exp();
        Self {
            attack_coeff,
            release_coeff,
            envelope: 0.0,
        }
    }

    /// Update envelope follower with incoming sample value.
    pub fn update(&mut self, sample: f32) -> f32 {
        let input_mag = sample.abs();
        if input_mag > self.envelope {
            self.envelope =
                self.attack_coeff * self.envelope + (1.0 - self.attack_coeff) * input_mag;
        } else {
            self.envelope =
                self.release_coeff * self.envelope + (1.0 - self.release_coeff) * input_mag;
        }
        self.envelope
    }

    /// Reset internal envelope state.
    pub fn reset(&mut self) {
        self.envelope = 0.0;
    }
}

/// Fixed-point Q15 Biquad filter operating without hardware floating-point operations.
#[derive(Debug, Clone)]
pub struct BiquadAudioFilterQ15 {
    // Coefficients scaled in Q14 (1.14 fixed point format)
    b0: i16,
    b1: i16,
    b2: i16,
    a1: i16,
    a2: i16,
    x1: i16,
    x2: i16,
    y1: i16,
    y2: i16,
}

impl BiquadAudioFilterQ15 {
    pub const fn new(b0: i16, b1: i16, b2: i16, a1: i16, a2: i16) -> Self {
        Self {
            b0,
            b1,
            b2,
            a1,
            a2,
            x1: 0,
            x2: 0,
            y1: 0,
            y2: 0,
        }
    }

    pub fn reset(&mut self) {
        self.x1 = 0;
        self.x2 = 0;
        self.y1 = 0;
        self.y2 = 0;
    }

    /// Process a single 16-bit signed PCM sample (`i16`).
    pub fn process_sample_i16(&mut self, x: i16) -> i16 {
        let acc = (self.b0 as i32 * x as i32)
            + (self.b1 as i32 * self.x1 as i32)
            + (self.b2 as i32 * self.x2 as i32)
            - (self.a1 as i32 * self.y1 as i32)
            - (self.a2 as i32 * self.y2 as i32);

        let y = (acc >> 14).clamp(-32768, 32767) as i16;

        self.x2 = self.x1;
        self.x1 = x;
        self.y2 = self.y1;
        self.y1 = y;

        y
    }

    /// Process a single 8-bit signed PCM sample (`i8`).
    pub fn process_sample_i8(&mut self, x: i8) -> i8 {
        let x16 = (x as i16) << 8;
        let y16 = self.process_sample_i16(x16);
        (y16 >> 8) as i8
    }
}