bbx_dsp 0.4.3

Block-based audio DSP graph system with oscillators, effects, modulators, and realtime-safe processing
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
//! Audio file output block with non-blocking I/O.

use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread::{self, JoinHandle},
};

use bbx_core::{Consumer, Producer, SpscRingBuffer};

use crate::{block::Block, context::DspContext, parameter::ModulationOutput, sample::Sample, writer::Writer};

/// Default ring buffer capacity in samples (~1 second at 44.1kHz stereo).
const DEFAULT_RING_BUFFER_CAPACITY: usize = 44100 * 2;

/// Writes audio from the DSP graph to a file.
///
/// This block uses a separate I/O thread to perform disk writes,
/// avoiding blocking the audio thread. Samples are passed through
/// a lock-free ring buffer.
pub struct FileOutputBlock<S: Sample> {
    /// Ring buffer producer (audio thread side).
    producer: Option<Producer<S>>,

    /// Writer thread handle.
    writer_thread: Option<JoinHandle<()>>,

    /// Signal for writer thread to stop.
    stop_signal: Arc<AtomicBool>,

    /// Flag indicating a write error occurred.
    error_flag: Arc<AtomicBool>,

    /// Recording state.
    is_recording: bool,

    /// Number of audio channels.
    num_channels: usize,
}

impl<S: Sample + Send + 'static> FileOutputBlock<S> {
    /// Create a `FileOutputBlock` with the `Writer` implementation for a particular type of audio file.
    ///
    /// The writer is moved to a background I/O thread. Samples are passed through
    /// a lock-free ring buffer to avoid blocking the audio thread.
    pub fn new(writer: Box<dyn Writer<S>>) -> Self {
        let num_channels = writer.num_channels();
        let sample_rate = writer.sample_rate() as usize;

        // Ring buffer capacity: ~1 second of audio
        let buffer_capacity = sample_rate.max(DEFAULT_RING_BUFFER_CAPACITY) * num_channels;
        let (producer, consumer) = SpscRingBuffer::new::<S>(buffer_capacity);

        let stop_signal = Arc::new(AtomicBool::new(false));
        let error_flag = Arc::new(AtomicBool::new(false));

        let stop_signal_clone = stop_signal.clone();
        let error_flag_clone = error_flag.clone();

        let writer_thread = thread::spawn(move || {
            Self::writer_thread_fn(consumer, writer, stop_signal_clone, error_flag_clone, num_channels);
        });

        Self {
            producer: Some(producer),
            writer_thread: Some(writer_thread),
            stop_signal,
            error_flag,
            is_recording: true,
            num_channels,
        }
    }

    /// Writer thread function that consumes samples and writes to disk.
    fn writer_thread_fn(
        mut consumer: Consumer<S>,
        mut writer: Box<dyn Writer<S>>,
        stop_signal: Arc<AtomicBool>,
        error_flag: Arc<AtomicBool>,
        num_channels: usize,
    ) {
        let mut channel_buffers: Vec<Vec<S>> = vec![Vec::new(); num_channels];
        let mut current_channel = 0;

        // Flush threshold (samples per channel before writing to disk)
        const FLUSH_THRESHOLD: usize = 4096;

        loop {
            while let Some(sample) = consumer.try_pop() {
                channel_buffers[current_channel].push(sample);
                current_channel = (current_channel + 1) % num_channels;

                if channel_buffers[0].len() >= FLUSH_THRESHOLD {
                    for (ch, buffer) in channel_buffers.iter_mut().enumerate() {
                        if writer.write_channel(ch, buffer).is_err() {
                            error_flag.store(true, Ordering::Relaxed);
                        }
                        buffer.clear();
                    }
                }
            }

            if stop_signal.load(Ordering::Acquire) {
                for (ch, buffer) in channel_buffers.iter().enumerate() {
                    if !buffer.is_empty() && writer.write_channel(ch, buffer).is_err() {
                        error_flag.store(true, Ordering::Relaxed);
                    }
                }

                if writer.finalize().is_err() {
                    error_flag.store(true, Ordering::Relaxed);
                }

                break;
            }

            // Sleep briefly to avoid busy-waiting
            thread::sleep(std::time::Duration::from_millis(1));
        }
    }

    /// Tell the writer to begin storing audio sample data.
    #[inline]
    pub fn start_recording(&mut self) {
        self.is_recording = true;
    }

    /// Tell the writer to stop storing audio sample data.
    ///
    /// This signals the I/O thread to flush remaining samples and finalize the file.
    /// The method blocks until the I/O thread completes.
    pub fn stop_recording(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.is_recording = false;

        self.stop_signal.store(true, Ordering::Release);

        if let Some(handle) = self.writer_thread.take() {
            handle.join().map_err(|_| "Writer thread panicked")?;
        }

        if self.error_flag.load(Ordering::Relaxed) {
            return Err("Error occurred while writing to file".into());
        }

        Ok(())
    }

    /// Check whether the writer is actively storing audio sample data.
    #[inline]
    pub fn is_recording(&self) -> bool {
        self.is_recording
    }

    /// Check whether any write errors have occurred.
    ///
    /// This can be queried periodically to detect I/O failures
    /// without blocking the audio thread.
    #[inline]
    pub fn error_occurred(&self) -> bool {
        self.error_flag.load(Ordering::Relaxed)
    }
}

impl<S: Sample + Send + 'static> Block<S> for FileOutputBlock<S> {
    fn process(&mut self, inputs: &[&[S]], _outputs: &mut [&mut [S]], _modulation_values: &[S], _context: &DspContext) {
        if !self.is_recording || inputs.is_empty() {
            return;
        }

        let producer = match &mut self.producer {
            Some(p) => p,
            None => return,
        };

        let buffer_len = inputs[0].len();

        for sample_idx in 0..buffer_len {
            for ch in 0..self.num_channels {
                let sample = inputs.get(ch).map_or(S::ZERO, |input| input[sample_idx]);
                let _ = producer.try_push(sample);
            }
        }
    }

    #[inline]
    fn input_count(&self) -> usize {
        self.num_channels
    }

    #[inline]
    fn output_count(&self) -> usize {
        0
    }

    #[inline]
    fn modulation_outputs(&self) -> &[ModulationOutput] {
        &[]
    }
}

impl<S: Sample + Send + 'static> Drop for FileOutputBlock<S> {
    fn drop(&mut self) {
        self.stop_signal.store(true, Ordering::Release);

        // Ignore errors in drop
        if let Some(handle) = self.writer_thread.take() {
            let _ = handle.join();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;
    use crate::channel::ChannelLayout;

    struct MockWriter<S: Sample> {
        sample_rate: f64,
        num_channels: usize,
        channels: Arc<Mutex<Vec<Vec<S>>>>,
        finalized: Arc<AtomicBool>,
    }

    impl<S: Sample> MockWriter<S> {
        fn new(sample_rate: f64, num_channels: usize) -> Self {
            let channels: Vec<Vec<S>> = (0..num_channels).map(|_| Vec::new()).collect();
            Self {
                sample_rate,
                num_channels,
                channels: Arc::new(Mutex::new(channels)),
                finalized: Arc::new(AtomicBool::new(false)),
            }
        }

        fn get_channels(&self) -> Arc<Mutex<Vec<Vec<S>>>> {
            self.channels.clone()
        }

        fn get_finalized(&self) -> Arc<AtomicBool> {
            self.finalized.clone()
        }
    }

    impl<S: Sample> Writer<S> for MockWriter<S> {
        fn sample_rate(&self) -> f64 {
            self.sample_rate
        }

        fn num_channels(&self) -> usize {
            self.num_channels
        }

        fn can_write(&self) -> bool {
            true
        }

        fn write_channel(&mut self, channel_index: usize, samples: &[S]) -> Result<(), Box<dyn std::error::Error>> {
            let mut channels = self.channels.lock().unwrap();
            if channel_index < channels.len() {
                channels[channel_index].extend_from_slice(samples);
            }
            Ok(())
        }

        fn finalize(&mut self) -> Result<(), Box<dyn std::error::Error>> {
            self.finalized.store(true, Ordering::Relaxed);
            Ok(())
        }
    }

    fn test_context(buffer_size: usize) -> DspContext {
        DspContext {
            sample_rate: 44100.0,
            buffer_size,
            num_channels: 2,
            current_sample: 0,
            channel_layout: ChannelLayout::Stereo,
        }
    }

    #[test]
    fn test_file_output_block_counts() {
        let writer = MockWriter::<f32>::new(44100.0, 2);
        let block = FileOutputBlock::new(Box::new(writer));
        assert_eq!(block.input_count(), 2);
        assert_eq!(block.output_count(), 0);
    }

    #[test]
    fn test_file_output_block_recording_state() {
        let writer = MockWriter::<f32>::new(44100.0, 2);
        let mut block = FileOutputBlock::new(Box::new(writer));

        assert!(block.is_recording());

        block.start_recording();
        assert!(block.is_recording());
    }

    #[test]
    fn test_file_output_block_writes_and_finalizes() {
        let writer = MockWriter::<f32>::new(44100.0, 1);
        let channels = writer.get_channels();
        let finalized = writer.get_finalized();

        let mut block = FileOutputBlock::new(Box::new(writer));

        let context = test_context(10);
        let input: Vec<f32> = vec![0.5; 10];
        let inputs: [&[f32]; 1] = [&input];
        let mut outputs: [&mut [f32]; 0] = [];

        block.process(&inputs, &mut outputs, &[], &context);

        block.stop_recording().unwrap();

        assert!(finalized.load(Ordering::Relaxed));
        let written = channels.lock().unwrap();
        assert!(!written[0].is_empty());
    }

    #[test]
    fn test_file_output_block_no_error_initially() {
        let writer = MockWriter::<f32>::new(44100.0, 2);
        let block = FileOutputBlock::new(Box::new(writer));
        assert!(!block.error_occurred());
    }

    #[test]
    fn test_file_output_block_empty_inputs() {
        let writer = MockWriter::<f32>::new(44100.0, 1);
        let mut block = FileOutputBlock::new(Box::new(writer));

        let context = test_context(10);
        let inputs: [&[f32]; 0] = [];
        let mut outputs: [&mut [f32]; 0] = [];

        block.process(&inputs, &mut outputs, &[], &context);

        block.stop_recording().unwrap();
        assert!(!block.error_occurred());
    }

    #[test]
    fn test_file_output_block_mono_input_to_stereo_file() {
        let writer = MockWriter::<f32>::new(44100.0, 2);
        let channels = writer.get_channels();

        let mut block = FileOutputBlock::new(Box::new(writer));

        let context = test_context(4);
        let mono_input: Vec<f32> = vec![0.1, 0.2, 0.3, 0.4];
        let inputs: [&[f32]; 1] = [&mono_input];
        let mut outputs: [&mut [f32]; 0] = [];

        block.process(&inputs, &mut outputs, &[], &context);
        block.stop_recording().unwrap();

        let written = channels.lock().unwrap();
        assert_eq!(written[0], vec![0.1, 0.2, 0.3, 0.4]);
        assert_eq!(written[1], vec![0.0, 0.0, 0.0, 0.0]);
    }

    #[test]
    fn test_file_output_block_interleaving_order() {
        let writer = MockWriter::<f32>::new(44100.0, 2);
        let channels = writer.get_channels();

        let mut block = FileOutputBlock::new(Box::new(writer));

        let context = test_context(3);
        let left: Vec<f32> = vec![1.0, 2.0, 3.0];
        let right: Vec<f32> = vec![0.1, 0.2, 0.3];
        let inputs: [&[f32]; 2] = [&left, &right];
        let mut outputs: [&mut [f32]; 0] = [];

        block.process(&inputs, &mut outputs, &[], &context);
        block.stop_recording().unwrap();

        let written = channels.lock().unwrap();
        assert_eq!(written[0], vec![1.0, 2.0, 3.0]);
        assert_eq!(written[1], vec![0.1, 0.2, 0.3]);
    }

    #[test]
    fn test_file_output_block_excess_inputs_ignored() {
        let writer = MockWriter::<f32>::new(44100.0, 2);
        let channels = writer.get_channels();

        let mut block = FileOutputBlock::new(Box::new(writer));

        let context = test_context(2);
        let ch0: Vec<f32> = vec![1.0, 2.0];
        let ch1: Vec<f32> = vec![0.1, 0.2];
        let ch2: Vec<f32> = vec![9.9, 9.9];
        let inputs: [&[f32]; 3] = [&ch0, &ch1, &ch2];
        let mut outputs: [&mut [f32]; 0] = [];

        block.process(&inputs, &mut outputs, &[], &context);
        block.stop_recording().unwrap();

        let written = channels.lock().unwrap();
        assert_eq!(written[0], vec![1.0, 2.0]);
        assert_eq!(written[1], vec![0.1, 0.2]);
        assert_eq!(written.len(), 2);
    }
}