ringkernel-audio-fft 1.1.0

GPU-accelerated audio FFT processing with direct/ambience separation using RingKernel actors
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Audio input handling for files and device streams.
//!
//! This module provides a unified interface for reading audio from:
//! - WAV files (via hound)
//! - Real-time audio devices (via cpal)

use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;

#[cfg(feature = "device-input")]
use crossbeam::channel::bounded;
use crossbeam::channel::{Receiver, Sender};
#[cfg(feature = "device-input")]
use tracing::{debug, error, info, warn};
#[cfg(not(feature = "device-input"))]
use tracing::{debug, info};

use crate::error::{AudioFftError, Result};
use crate::messages::AudioFrame;

/// Audio source trait for unified input handling.
pub trait AudioSource: Send + Sync {
    /// Get the sample rate in Hz.
    fn sample_rate(&self) -> u32;

    /// Get the number of channels.
    fn channels(&self) -> u8;

    /// Get the total number of samples (None for streams).
    fn total_samples(&self) -> Option<u64>;

    /// Read the next frame of audio.
    fn read_frame(&mut self, frame_size: usize) -> Result<Option<AudioFrame>>;

    /// Check if the source is exhausted.
    fn is_exhausted(&self) -> bool;

    /// Reset to the beginning (if supported).
    fn reset(&mut self) -> Result<()>;
}

/// Audio input from a WAV file.
pub struct FileSource {
    path: String,
    sample_rate: u32,
    channels: u8,
    samples: Vec<f32>,
    position: usize,
    frame_counter: u64,
}

impl FileSource {
    /// Open a WAV file for reading.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        info!("Opening audio file: {}", path_str);

        let reader = hound::WavReader::open(path.as_ref())
            .map_err(|e| AudioFftError::file_read(format!("{}: {}", path_str, e)))?;

        let spec = reader.spec();
        let sample_rate = spec.sample_rate;
        let channels = spec.channels as u8;

        debug!(
            "File spec: {} Hz, {} channels, {} bits, {:?}",
            sample_rate, channels, spec.bits_per_sample, spec.sample_format
        );

        // Read all samples and convert to f32
        let samples: Vec<f32> = match spec.sample_format {
            hound::SampleFormat::Float => reader
                .into_samples::<f32>()
                .filter_map(|s| s.ok())
                .collect(),
            hound::SampleFormat::Int => {
                let scale = 1.0 / (1 << (spec.bits_per_sample - 1)) as f32;
                reader
                    .into_samples::<i32>()
                    .filter_map(|s| s.ok())
                    .map(|s| s as f32 * scale)
                    .collect()
            }
        };

        info!(
            "Loaded {} samples ({:.2} seconds)",
            samples.len(),
            samples.len() as f64 / channels as f64 / sample_rate as f64
        );

        Ok(Self {
            path: path_str,
            sample_rate,
            channels,
            samples,
            position: 0,
            frame_counter: 0,
        })
    }

    /// Get the file path.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Get the duration in seconds.
    pub fn duration_secs(&self) -> f64 {
        self.samples.len() as f64 / self.channels as f64 / self.sample_rate as f64
    }
}

impl AudioSource for FileSource {
    fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    fn channels(&self) -> u8 {
        self.channels
    }

    fn total_samples(&self) -> Option<u64> {
        Some(self.samples.len() as u64 / self.channels as u64)
    }

    fn read_frame(&mut self, frame_size: usize) -> Result<Option<AudioFrame>> {
        if self.position >= self.samples.len() {
            return Ok(None);
        }

        let samples_to_read =
            (frame_size * self.channels as usize).min(self.samples.len() - self.position);

        let frame_samples = self.samples[self.position..self.position + samples_to_read].to_vec();
        let timestamp = self.position as u64 / self.channels as u64;

        self.position += samples_to_read;
        self.frame_counter += 1;

        Ok(Some(AudioFrame::new(
            self.frame_counter,
            self.sample_rate,
            self.channels,
            frame_samples,
            timestamp,
        )))
    }

    fn is_exhausted(&self) -> bool {
        self.position >= self.samples.len()
    }

    fn reset(&mut self) -> Result<()> {
        self.position = 0;
        self.frame_counter = 0;
        Ok(())
    }
}

/// Real-time audio device stream.
pub struct DeviceStream {
    sample_rate: u32,
    channels: u8,
    receiver: Receiver<Vec<f32>>,
    buffer: Vec<f32>,
    frame_counter: Arc<AtomicU64>,
    running: Arc<AtomicBool>,
    // Keep the stream alive (only with device-input feature)
    #[cfg(feature = "device-input")]
    _stream: Option<cpal::Stream>,
}

/// Device stream configuration.
#[derive(Debug, Clone)]
pub struct DeviceConfig {
    /// Preferred sample rate (None = use device default).
    pub sample_rate: Option<u32>,
    /// Preferred channels (None = use device default).
    pub channels: Option<u8>,
    /// Buffer size in samples.
    pub buffer_size: usize,
    /// Device name (None = default device).
    pub device_name: Option<String>,
}

impl Default for DeviceConfig {
    fn default() -> Self {
        Self {
            sample_rate: None,
            channels: None,
            buffer_size: 4096,
            device_name: None,
        }
    }
}

impl DeviceStream {
    /// Create a new device stream with the default input device.
    #[cfg(feature = "device-input")]
    pub fn new(config: DeviceConfig) -> Result<Self> {
        use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};

        let host = cpal::default_host();

        let device = if let Some(name) = &config.device_name {
            host.input_devices()
                .map_err(|e| AudioFftError::device(format!("Failed to enumerate devices: {}", e)))?
                .find(|d| d.name().map(|n| n.contains(name)).unwrap_or(false))
                .ok_or_else(|| AudioFftError::device(format!("Device '{}' not found", name)))?
        } else {
            host.default_input_device()
                .ok_or_else(|| AudioFftError::device("No default input device"))?
        };

        let device_name = device.name().unwrap_or_else(|_| "unknown".to_string());
        info!("Using input device: {}", device_name);

        let supported_config = device
            .default_input_config()
            .map_err(|e| AudioFftError::device(format!("Failed to get device config: {}", e)))?;

        let sample_rate = config
            .sample_rate
            .unwrap_or(supported_config.sample_rate().0);
        let channels = config.channels.unwrap_or(supported_config.channels() as u8);

        debug!("Stream config: {} Hz, {} channels", sample_rate, channels);

        let (sender, receiver) = bounded(64);
        let running = Arc::new(AtomicBool::new(true));
        let frame_counter = Arc::new(AtomicU64::new(0));

        let running_clone = running.clone();
        let sender_clone = sender.clone();

        let stream_config = cpal::StreamConfig {
            channels: channels as u16,
            sample_rate: cpal::SampleRate(sample_rate),
            buffer_size: cpal::BufferSize::Fixed(config.buffer_size as u32),
        };

        let stream = device
            .build_input_stream(
                &stream_config,
                move |data: &[f32], _: &cpal::InputCallbackInfo| {
                    if running_clone.load(Ordering::Relaxed) {
                        if sender_clone.try_send(data.to_vec()).is_err() {
                            warn!("Audio buffer overflow - dropping samples");
                        }
                    }
                },
                move |err| {
                    error!("Audio stream error: {}", err);
                },
                None,
            )
            .map_err(|e| AudioFftError::device(format!("Failed to build stream: {}", e)))?;

        stream
            .play()
            .map_err(|e| AudioFftError::device(format!("Failed to start stream: {}", e)))?;

        info!("Audio device stream started");

        Ok(Self {
            sample_rate,
            channels,
            receiver,
            buffer: Vec::with_capacity(config.buffer_size * 2),
            frame_counter,
            running,
            _stream: Some(stream),
        })
    }

    /// Create a dummy device stream (for testing without audio device).
    #[cfg(not(feature = "device-input"))]
    pub fn new(_config: DeviceConfig) -> Result<Self> {
        Err(AudioFftError::device(
            "Device input not enabled. Compile with --features device-input",
        ))
    }

    /// Create a mock stream for testing.
    #[cfg(feature = "device-input")]
    pub fn mock(
        sample_rate: u32,
        channels: u8,
        _sender: Sender<Vec<f32>>,
        receiver: Receiver<Vec<f32>>,
    ) -> Self {
        Self {
            sample_rate,
            channels,
            receiver,
            buffer: Vec::new(),
            frame_counter: Arc::new(AtomicU64::new(0)),
            running: Arc::new(AtomicBool::new(true)),
            _stream: None,
        }
    }

    /// Create a mock stream for testing.
    #[cfg(not(feature = "device-input"))]
    pub fn mock(
        sample_rate: u32,
        channels: u8,
        _sender: Sender<Vec<f32>>,
        receiver: Receiver<Vec<f32>>,
    ) -> Self {
        Self {
            sample_rate,
            channels,
            receiver,
            buffer: Vec::new(),
            frame_counter: Arc::new(AtomicU64::new(0)),
            running: Arc::new(AtomicBool::new(true)),
        }
    }

    /// Stop the stream.
    pub fn stop(&self) {
        self.running.store(false, Ordering::Relaxed);
    }

    /// Check if the stream is running.
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::Relaxed)
    }
}

impl AudioSource for DeviceStream {
    fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    fn channels(&self) -> u8 {
        self.channels
    }

    fn total_samples(&self) -> Option<u64> {
        None // Stream has no defined length
    }

    fn read_frame(&mut self, frame_size: usize) -> Result<Option<AudioFrame>> {
        let required_samples = frame_size * self.channels as usize;

        // Fill buffer from receiver
        while self.buffer.len() < required_samples {
            match self.receiver.try_recv() {
                Ok(samples) => self.buffer.extend(samples),
                Err(crossbeam::channel::TryRecvError::Empty) => {
                    // Not enough data yet
                    if !self.is_running() && self.buffer.is_empty() {
                        return Ok(None);
                    }
                    // Return what we have (might be less than frame_size)
                    if !self.buffer.is_empty() {
                        break;
                    }
                    // Wait for more data
                    match self
                        .receiver
                        .recv_timeout(std::time::Duration::from_millis(100))
                    {
                        Ok(samples) => self.buffer.extend(samples),
                        Err(_) => {
                            if !self.is_running() {
                                return Ok(None);
                            }
                            continue;
                        }
                    }
                }
                Err(crossbeam::channel::TryRecvError::Disconnected) => {
                    if self.buffer.is_empty() {
                        return Ok(None);
                    }
                    break;
                }
            }
        }

        if self.buffer.is_empty() {
            return Ok(None);
        }

        let samples_to_take = required_samples.min(self.buffer.len());
        let frame_samples: Vec<f32> = self.buffer.drain(..samples_to_take).collect();

        let frame_id = self.frame_counter.fetch_add(1, Ordering::Relaxed);
        let timestamp = frame_id * frame_size as u64;

        Ok(Some(AudioFrame::new(
            frame_id,
            self.sample_rate,
            self.channels,
            frame_samples,
            timestamp,
        )))
    }

    fn is_exhausted(&self) -> bool {
        !self.is_running() && self.buffer.is_empty()
    }

    fn reset(&mut self) -> Result<()> {
        self.buffer.clear();
        self.frame_counter.store(0, Ordering::Relaxed);
        Ok(())
    }
}

impl Drop for DeviceStream {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Unified audio input that can be either file or device.
pub enum AudioInput {
    /// File-based input.
    File(FileSource),
    /// Device stream input.
    Device(DeviceStream),
}

impl AudioInput {
    /// Create input from a file.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        Ok(Self::File(FileSource::open(path)?))
    }

    /// Create input from the default audio device.
    pub fn from_device(config: DeviceConfig) -> Result<Self> {
        Ok(Self::Device(DeviceStream::new(config)?))
    }

    /// Create input from raw samples (for testing).
    pub fn from_samples(samples: Vec<f32>, sample_rate: u32, channels: u8) -> Self {
        Self::File(FileSource {
            path: "<memory>".to_string(),
            sample_rate,
            channels,
            samples,
            position: 0,
            frame_counter: 0,
        })
    }
}

impl AudioSource for AudioInput {
    fn sample_rate(&self) -> u32 {
        match self {
            Self::File(f) => f.sample_rate(),
            Self::Device(d) => d.sample_rate(),
        }
    }

    fn channels(&self) -> u8 {
        match self {
            Self::File(f) => f.channels(),
            Self::Device(d) => d.channels(),
        }
    }

    fn total_samples(&self) -> Option<u64> {
        match self {
            Self::File(f) => f.total_samples(),
            Self::Device(d) => d.total_samples(),
        }
    }

    fn read_frame(&mut self, frame_size: usize) -> Result<Option<AudioFrame>> {
        match self {
            Self::File(f) => f.read_frame(frame_size),
            Self::Device(d) => d.read_frame(frame_size),
        }
    }

    fn is_exhausted(&self) -> bool {
        match self {
            Self::File(f) => f.is_exhausted(),
            Self::Device(d) => d.is_exhausted(),
        }
    }

    fn reset(&mut self) -> Result<()> {
        match self {
            Self::File(f) => f.reset(),
            Self::Device(d) => d.reset(),
        }
    }
}

/// Audio output writer for WAV files.
#[derive(Debug, Clone)]
pub struct AudioOutput {
    /// Sample rate in Hz.
    pub sample_rate: u32,
    /// Number of channels.
    pub channels: u8,
    /// Audio samples.
    pub samples: Vec<f32>,
}

impl AudioOutput {
    /// Create a new empty audio output.
    pub fn new(sample_rate: u32, channels: u8) -> Self {
        Self {
            sample_rate,
            channels,
            samples: Vec::new(),
        }
    }

    /// Create from existing samples.
    pub fn from_samples(samples: Vec<f32>, sample_rate: u32, channels: u8) -> Self {
        Self {
            sample_rate,
            channels,
            samples,
        }
    }

    /// Append samples.
    pub fn append(&mut self, samples: &[f32]) {
        self.samples.extend_from_slice(samples);
    }

    /// Get duration in seconds.
    pub fn duration_secs(&self) -> f64 {
        self.samples.len() as f64 / self.channels as f64 / self.sample_rate as f64
    }

    /// Write to a WAV file.
    pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let spec = hound::WavSpec {
            channels: self.channels as u16,
            sample_rate: self.sample_rate,
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
        };

        let mut writer = hound::WavWriter::create(path.as_ref(), spec)
            .map_err(|e| AudioFftError::file_write(e.to_string()))?;

        for sample in &self.samples {
            writer
                .write_sample(*sample)
                .map_err(|e| AudioFftError::file_write(e.to_string()))?;
        }

        writer
            .finalize()
            .map_err(|e| AudioFftError::file_write(e.to_string()))?;

        info!(
            "Wrote {} samples to {}",
            self.samples.len(),
            path.as_ref().display()
        );

        Ok(())
    }

    /// Normalize the audio to peak at 1.0.
    pub fn normalize(&mut self) {
        let max = self.samples.iter().map(|s| s.abs()).fold(0.0f32, f32::max);

        if max > 1e-6 {
            let scale = 1.0 / max;
            for sample in &mut self.samples {
                *sample *= scale;
            }
        }
    }

    /// Apply gain.
    pub fn apply_gain(&mut self, gain: f32) {
        for sample in &mut self.samples {
            *sample *= gain;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_audio_input_from_samples() {
        let samples = vec![0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7];
        let mut input = AudioInput::from_samples(samples, 44100, 2);

        assert_eq!(input.sample_rate(), 44100);
        assert_eq!(input.channels(), 2);
        assert_eq!(input.total_samples(), Some(4)); // 8 samples / 2 channels

        let frame = input.read_frame(2).unwrap().unwrap();
        assert_eq!(frame.samples.len(), 4); // 2 samples * 2 channels
        assert!(!input.is_exhausted());

        let frame2 = input.read_frame(2).unwrap().unwrap();
        assert_eq!(frame2.samples.len(), 4);
        assert!(input.is_exhausted());
    }

    #[test]
    fn test_audio_output() {
        let mut output = AudioOutput::new(44100, 1);
        output.append(&[0.5, -0.5, 0.25, -0.25]);

        assert_eq!(output.samples.len(), 4);
        assert!((output.duration_secs() - 4.0 / 44100.0).abs() < 1e-6);

        output.normalize();
        assert!((output.samples[0] - 1.0).abs() < 1e-6);
        assert!((output.samples[1] - (-1.0)).abs() < 1e-6);
    }
}